text
stringlengths
65
6.05M
lang
stringclasses
8 values
type
stringclasses
2 values
id
stringlengths
64
64
'use strict'; const Web3 = require('web3'); const squba = require('squba'); const contract_ids = require('../lib/contract_ids.js'); const abi_bin = require('../lib/abi_bin.js'); const networks = require('../lib/networks.js'); const mainNetMsg = () => 'Attention: Your metamask is connected to mainnet. ' + 'Don\'t use this prototype on mainnet - it can result in loss of money!'; const metamaskMsg = () => 'Attention: Your metamask is not connected to testnet.' + ' Only use this prototype on testnet - otherwise it can result in loss of money!'; angular .module('app') .service('ethereum', ethereum); function ethereum() { const server_contracts = {}; const state = { }; initialize(); return { getPolicies, tokenSale, state }; function web3Connect() { return new Promise(function(resolve, reject) { // MetaMask injects the web3 object for us if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); resolve(web3); return; } // If there's not web3 object then we initialize one const message = 'No web3? You should consider trying MetaMask!'; console.warn(message); reject({ message }); }); } function getNetwork() { return new Promise((resolve, reject) => { web3.version.getNetwork((err, res) => { if (res !== 3 && res !== '3') { reject({message: 'Connected to the wrong network!'}); return; } resolve({network: res}); }); }); } function getBalance() { return new Promise((resolve, reject) => { web3.eth.getBalance(web3.eth.accounts[0], (err, res) => { resolve({ web3_Connected: true, balance: web3.fromWei(res).toFixed(2), account: web3.eth.accounts[0] }); }); }); } function initialize() { web3Connect() .then(getNetwork, err => {state.message = err.message;}) .then(({network}) => { state.network = network; return true; }, err => {state.message = err.message;}) .then(getBalance) .then(({web3_Connected, balance, account}) => { state.web3_Connected = web3_Connected; state.balance = balance; state.account = account; return true; }) .then(() => { console.log('Server started'); web3.eth.getBlockNumber((err, res) => { console.log(`BlockNumber: ${res}`); }); // get the address resolver contract, just a SYNC call const RSC_AddressResolver = web3.eth .contract(abi_bin.abi.RSC_AddressResolver) .at(networks.ropsten.AddressResolver_addr); getAllContracts(contract_ids.contracts); // interate over contracts and add them to server_contracts (async) function getAllContracts(contracts) { for (let contract in contracts) { getContract(contract); } }; // get the contract address (async) function getContract(contract) { RSC_AddressResolver.getAddress(web3.sha3(contract), (err, address) => { if (err) { console.error(err); return; } // get the contract at that adress and add it to the server_contracts list (async) web3.eth.contract(abi_bin.abi[contract]).at(address, (err, res) => { server_contracts[contract] = res; }); }); } }); // .then } function getPolicies() { console.log('Method Call: getPolicies'); if (typeof squba(server_contracts, 'RSC_Insurance') === 'undefined') { console.log('Did not load the policies yet.'); return new Promise((resolve) => resolve([])); } return getPolicyCount(server_contracts.RSC_Insurance) .then(policyCount => { var policies = []; for (let index = 0; index < policyCount; index++) { const policyPromise = getPolicyByIndex(server_contracts.RSC_Insurance, index); policies.push(policyPromise); } return Promise.all(policies); }); } function tokenSale(amount) { var tx = { value: web3.toWei(amount, 'ether') }; return new Promise((resolve, reject) => { web3.version.getNetwork((err, res) => { if (res == 1) { const error = {message: mainNetMsg()}; reject({ success: false, message: error.message.slice(0, error.message.indexOf('\n')), hash: '' }); return; } if (res !== 3 && res !== '3') { const error = {message: metamaskMsg()}; reject({ success: false, message: error.message.slice(0, error.message.indexOf('\n')), hash: '' }); return; } try { server_contracts.RSC_SimpleSale.tokenSale(tx, (err, result) => { if (err) { reject({ success: false, message: err.message.slice(0, err.message.indexOf('\n')), hash: '' }); return; } resolve({ success: true, message: result, hash: result }); }); } catch (e) { reject({ success: false, message: e.message.slice(0, e.message.indexOf('\n')), hash: '' }); } }); }); } function getPolicyByIndex(RSC_Insurance, index) { return new Promise(function(resolve, reject) { RSC_Insurance.policies(index, (err, row) => { if (err) { reject(err); return; } row.push(row[0].slice(0,7)); row[1] = web3.fromWei(row[1], 'ether').toFixed(4); row[3] = web3.toDecimal(row[3]) / 10000; row[5] = new Date(web3.toDecimal(row[5]) * 1000).toUTCString(); row[7] = web3.fromWei(row[7], 'ether').toFixed(4); row[8] = web3.fromWei(row[8], 'ether').toFixed(4); resolve(row); }); }); } function getPolicyCount(RSC_Insurance) { return new Promise(function(resolve, reject) { RSC_Insurance.getPolicyCount((err, res) => { if (err) { reject(err); return; } resolve(res.toNumber()); // it is a BigNumber so needs to be transformed }); }); } }
JavaScript
CL
81dab355d8064e333ebea49d20d2ddda1e4b13ef52d86c5b914eebf3ebb2b8f4
const express = require('express'); const router = express.Router(); const ProductController = require('../controller/products.controller'); const {tokenVerify} = require('../utils/jwtUtils'); // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmaXJzdG5hbWUiOiJ6ZWJyYW5kcyIsInBhc3N3b3JkIjoiemVicmFuZHMiLCJlbWFpbCI6InplYnJhbmRzQHplYnJhbmRzLmNvbSIsInVzZXJuYW1lIjoiemVicmFuZHMiLCJsYXN0bmFtZSI6InplYnJhbmRzIiwicHJvZmlsZSI6MSwiaWF0IjoxNjE3NzgwMjE0LCJleHAiOjE2MTc3ODM4MTR9.so4ZtY0ul8CDayolHmqxJaVJ8-twsJUlPhPuJO97FZw /** * @swagger * /products: * get: * security: * - bearerAuth: [] * description: Lista todos los productos. * tags: * - Products * responses: * 200: * description: Exitosamente * schema: * type: object * properties: * message: * type: string * data: * type: array * items: * type: object * properties: * sku: * type: integer * name: * type: string * price: * type: integer * brand: * type: string * 403: * description: No autorizado * schema: * type: string * 500: * description: Error Interno del Servidor * schema: * type: string */ router.get('/', tokenVerify, ProductController.getAllProduct); /** * @swagger * /products: * post: * description: Crear un nuevo producto * tags: * - Products * security: * - bearerAuth: [] * consumes: * - application/json * parameters: * - in: body * name: product * description: * schema: * type: object * required: * - userName * properties: * sku: * type: integer * name: * type: string * price: * type: integer * brand: * type: string * responses: * 200: * description: Exitosamente * schema: * type: object * properties: * message: * type: string * data: * type: object * properties: * sku: * type: integer * name: * type: string * price: * type: integer * brand: * type: string * 403: * description: No autorizado * schema: * type: string * 500: * description: Error Interno del Servidor * schema: * type: string * * */ router.post('/', tokenVerify, ProductController.createProduct); /** * @swagger * /products/{sku}: * put: * description: Actualiza un producto por su SKU * tags: * - Products * security: * - bearerAuth: [] * consumes: * - application/json * parameters: * - in: path * name: sku * description: Sku del producto a editar * type: number * required: true * - in: body * name: body * description: Información a editar * required: true * schema: * type: object * required: * - userName * properties: * name: * type: string * price: * type: integer * brand: * type: string * responses: * 200: * description: Success * 403: * description: No autorizado * schema: * type: string * 500: * description: Error Interno del Servidor * schema: * type: string * * */ router.put('/:sku', tokenVerify, ProductController.updateProduct); /** * @swagger * /products/{sku}: * get: * description: Obtiene un producto por el SKU * tags: * - Products * security: * - bearerAuth: [] * parameters: * - name: sku * in: path * type: integer * required: true * responses: * 200: * description: Success * schema: * type: object * properties: * message: * type: string * data: * type: object * properties: * sku: * type: integer * name: * type: string * price: * type: integer * brand: * type: string * 403: * description: No autorizado * schema: * type: string * 500: * description: Error Interno del Servidor * schema: * type: string * */ router.get('/:sku', tokenVerify, ProductController.getProductBySku); /** * @swagger * /products/{sku}: * delete: * description: Elimina un producto. * tags: * - Products * security: * - bearerAuth: [] * parameters: * - name: sku * in: path * description: * type: number * required: true * responses: * 200: * description: Exitosamente * schema: * type: string * 403: * description: No autorizado * schema: * type: string * 500: * description: Error Interno del Servidor * schema: * type: string */ router.delete('/:sku', tokenVerify, ProductController.deleteProduct); module.exports = router;
JavaScript
CL
b4508fa376264b7d06a2658e1520f3ca9e8c8c7e66da2033ed7c35a4b2df65c6
'use strict' const express = require('express'); const middleware = require('./lib/middleware'); const routes = require('./lib/routes'); const logger = require('./lib/logger'); // TODO: Set $NODE_ENV=production in ELB // TODO: Add TLS // TODO: Add password to admin page const app = express() middleware.setupMiddleware(app); routes.setupRoutes(app); const port = process.env.PORT || 3000 app.listen(port, function() { logger.log(`Started listening on port: ${port}`); });
JavaScript
CL
96963f48bfc19c2c49f3a5ddb9e7bb03f1ed7400290a5b974ccb9827a88c6f66
/*! * A QUnit assertion to compare DOM node trees. * * Adapted from VisualEditor plugin for QUnit. Additionally supports comparing properties to * attributes (for dynamically generated nodes) and order-insensitive comparison of classes on * DOM nodes. * * @copyright 2011-2020 VisualEditor Team and others; see http://ve.mit-license.org */ ( function ( QUnit ) { /** * Build a summary of an HTML element. * * Summaries include node name, text, attributes and recursive summaries of children. * Used for serializing or comparing HTML elements. * * @private * @param {HTMLElement} element Element to summarize * @return {Object|null} Summary of element. */ function getDomElementSummary( element ) { var i, name, attribute, property, childSummary, matches, summary = { type: element.nodeName.toLowerCase(), // $( '<div><textarea>Foo</textarea></div>' )[0].textContent === 'Foo', which breaks // comparisons :( childNodes are summarized anyway, this would just be a nicety // text: element.textContent, attributes: {}, children: [] }, autogeneratedAttributes = [ 'id', 'for', 'aria-owns', 'aria-controls', 'aria-activedescendant', 'aria-labelledby' ], // This is used to gather certain properties and pretend they are attributes. // Take note of casing differences. propertyAttributes = { value: 'value', readOnly: 'readonly', required: 'required', checked: 'checked', selected: 'selected', disabled: 'disabled', tabIndex: 'tabindex', dir: 'dir' }; // Gather attributes if ( element.attributes ) { for ( i = 0; i < element.attributes.length; i++ ) { name = element.attributes[ i ].name; summary.attributes[ name ] = element.attributes[ i ].value; } } // Sort classes if ( summary.attributes.class ) { summary.attributes.class = summary.attributes.class.split( ' ' ).sort().join( ' ' ); } for ( property in propertyAttributes ) { attribute = propertyAttributes[ property ]; if ( element[ property ] !== undefined ) { summary.attributes[ attribute ] = element[ property ]; } } // Ignore the nested DropdownWidget when comparing PHP and JS DropdownInputWidget if ( summary.attributes.class && summary.attributes.class.match( /oo-ui-dropdownWidget/ ) ) { return null; } // Summarize children if ( element.childNodes ) { for ( i = 0; i < element.childNodes.length; i++ ) { childSummary = getDomElementSummary( element.childNodes[ i ] ); if ( childSummary ) { summary.children.push( childSummary ); } } } // Special handling for textareas, where we only want to account for the content as the // 'value' property, never as childNodes or textContent. if ( summary.type === 'textarea' ) { // summary.text = ''; summary.children = []; } // Filter out acceptable differences between OOUI's PHP widgets and JS widgets. // Automatically generated IDs (Tag::generateElementId(), OO.ui.generateElementId()). for ( i = 0; i < autogeneratedAttributes.length; i++ ) { attribute = autogeneratedAttributes[ i ]; if ( summary.attributes[ attribute ] !== undefined && summary.attributes[ attribute ].match( /^(ooui-php-|ooui-)/ ) ) { summary.attributes[ attribute ] = '(autogenerated)'; } } if ( summary.attributes.id === '(autogenerated)' ) { // The 'id' might be missing on the JS side, while PHP always generates them for // infusion. For other attributes using autogenerated ids, the value might differ, // but the attribute should be either present in both PHP and JS, or missing in both // PHP and JS. delete summary.attributes.id; } // Infusion data if ( summary.attributes[ 'data-ooui' ] !== undefined ) { delete summary.attributes[ 'data-ooui' ]; } // Classes for custom styling of PHP widgets if ( summary.attributes.class !== undefined ) { // Ignore the extra classes on PHP widgets summary.attributes.class = summary.attributes.class.replace( /oo-ui-textInputWidget-php /g, '' ); summary.attributes.class = summary.attributes.class.replace( /oo-ui-dropdownInputWidget-php /g, '' ); } // Extra stuff on PHP DropdownInputWidget's $input if ( summary.type === 'select' ) { summary.attributes.class = 'oo-ui-inputWidget-input'; delete summary.attributes.tabindex; delete summary.attributes.title; delete summary.attributes[ 'aria-disabled' ]; } // PHP ToggleSwitchWidget has an extra 'a' tag that needs to be removed if ( summary.attributes.class && summary.attributes.class.match( /oo-ui-toggleSwitchWidget/ ) && summary.children[ 1 ] !== undefined && summary.children[ 1 ].type === 'a' ) { summary.children[ 1 ] = summary.children[ 1 ].children[ 0 ]; } // Extra stuff on JS Field(set)Layout's $help if ( summary.attributes.class && ( matches = summary.attributes.class.match( /oo-ui-field(set)?Layout-help/ ) ) ) { summary.attributes.class = matches[ 0 ]; summary.children = []; } // Only used by JS FieldLayout delete summary.attributes[ 'aria-describedby' ]; delete summary.attributes[ 'aria-haspopup' ]; delete summary.attributes[ 'aria-owns' ]; delete summary.attributes.role; return summary; } /** * @method * @static * @param {HTMLElement} actual * @param {HTMLElement} expected * @param {string} message */ QUnit.assert.equalDomElement = function ( actual, expected, message ) { var actualSummary = getDomElementSummary( actual ), expectedSummary = getDomElementSummary( expected ); this.pushResult( { result: QUnit.equiv( actualSummary, expectedSummary ), actual: { html: actual, summary: actualSummary }, expected: { html: expected, summary: expectedSummary }, message: message } ); }; }( QUnit ) );
JavaScript
CL
be587c9c6aba3881b7398d16b2a36b30e9328daa0d433d02746c2169e00036bc
// Geometric convention: x to the right, y upward, z out of the screen (counter-clockwise / right-handed basis) // All distance measurements and related (velocity, acceleration, area...) are expressed in custom "abstract" units, from now on simply called "units" // +--------------------------------------+ // | PHYSICAL / GEOMETRICAL CONSTANTS | adjust at your own pleasing (and risk) // +--------------------------------------+ /** * @type {number} number of frames per second, used in physics calculations */ const FRAMERATE = 60; /** * @type {number} number of collision checks & updates per frame, used in physics calculations */ const SUBSTEPS = 6; /** * @type {number} width of the pinball board in units */ const BOARD_WIDTH = 4.95; /** * @type {number} height of the pinball board in units */ const BOARD_HEIGHT = 10.9; /** * @type {number} gravitational acceleration downwards in units per second squared */ const GRAVITATIONAL_ACCELERATION = 4; /** * @type {number} radius of the ball in units */ const BALL_RADIUS = .16; /** * @type {number} coefficient of dynamic friction in units per second squared */ const FRICTION = .02; /** * @type {number} coefficient of fluid friction in 1 / units (acceleration per velocity squared) */ const DRAG = .012; /** * @type {number} ratio between the ball's velocity's component normal to the wall after vs. before the impact with said wall */ const WALL_RESTITUTION = -.5; /** * @type {number} ratio between the ball's velocity after vs. before the impact with a bumper */ const BUMPER_RESTITUTION = -1.4; /** * @type {number} radius of the bumpers in units */ const BUMPER_RADIUS = .33; /** * @type {number} angle of the left flipper, in resting position, w.r.t the horizontal (x axis) measured counterclockwise in radians */ const FLIPPER_RESTING_ANGLE = -.5236; /** * @type {number} angle of the left flipper, after a full swipe, w.r.t the horizontal (x axis) measured counterclockwise in radians */ const FLIPPER_ACTIVE_ANGLE = .5236; /** * @type {number} sweep time of the left flipper in seconds */ const FLIPPER_SWEEP_TIME = .12; /** * @type {number} length of the flippers in units */ const FLIPPER_LENGTH = .9; /** * @type {number} ratio between the ball's velocity after vs. before the impact with a non-moving flipper */ const FLIPPER_RESTITUTION = -.4; /** * @type {number} portion of the kinetic energy transferred from flipper to ball ~ `1` is perfectly elastic, `0` is as if the flipper were stationary * The flipper is idealized as an infinite mass object */ const FLIPPER_ENERGY_TRANSFER_EFFICIENCY = .4; /** * @type {number} x coordinate of the start position of the ball */ const BALL_START_X = 4.6; /** * @type {number} y coordinate of the start position of the ball */ const BALL_START_Y = 2; /** * @type {number} y component of the launch velocity of the ball */ const BALL_LAUNCH_SPEED = 14; // INFFERRED: /** * angular velocity of the left flipper while moving up */ const FLIPPER_PULSE = (FLIPPER_ACTIVE_ANGLE - FLIPPER_RESTING_ANGLE) / FLIPPER_SWEEP_TIME; /** * velocity at which the ball covers a distance equal to its radius in one frame */ const CRITICAL_VELOCITY = BALL_RADIUS * FRAMERATE; /** * velocity above which collisions are not guaranteed to be detected (ball may clip through walls) */ const SAFE_VELOCITY = .5 * CRITICAL_VELOCITY * SUBSTEPS; // +----------------------+ // | GLOBAL VARIABLES | // +----------------------+ /** * @type {number} the accumulated score of the game */ var score = 0; /** * @type {number} the remaining lives of the player */ var lives = 3; // +--------------------------------------------+ // | MODEL CLASSES AND STATE REPRESENTATION | // +--------------------------------------------+ /** * A 2D vector embedded in the flipper board plane. Used to represent positions, velocities, accelerations, distances and so on. * This class is immutable, i.e.: every operation applied to a vector results in a new vector being created and the original one being left unchanged. */ class Vector { /** * Creates a new vector given its components. * @param {number} x horizontal component (positive to the right) * @param {number} y vertical component (positive upward) */ constructor(x, y) { this.x = x; this.y = y; } /** * Returns the absolute value (or magnitude) of the vector. */ get abs() { return Math.hypot(this.x, this.y); } /** * Returns the phase (i.e. angle w.r.t. positive x-axis) of the vector. */ get phase() { return Math.atan2(this.y, this.x); } /** * the null vector `(0, 0)` */ static NULL = new Vector(0, 0); /** * Creates a unit vector whose phase is given. * @param {number} angle the phase of the vector */ static unit(angle) { return new Vector(Math.cos(angle), Math.sin(angle)); } /** * Returns the result of component-wise (euclidean) addition with another vector. * @param {Vector} vector the other vector */ add(vector) { return new Vector(this.x + vector.x, this.y + vector.y); } /** * Returns the scaling of the vector by a given factor. * @param {number} factor the scaling factor */ scale(factor) { return new Vector(factor * this.x, factor * this.y); } /** * Returns the result of component-wise (euclidean) subtraction with another vector. * @param {Vector} vector the other vector */ sub(vector) { return this.add(vector.scale(-1)); } /** * Returns the normalization of the vector. */ unit() { return new Vector(Math.cos(this.phase), Math.sin(this.phase)); } /** * Returns the dot product with another vector. * @param {Vector} vector the other vector. */ dot(vector) { return this.x * vector.x + this.y * vector.y; } /** * Returns the counterclockwise normal of the vector. */ normal() { return new Vector(-this.y, this.x); } } /** * Walls are lines through which the ball shall not pass. */ class Wall { /** * Creates a new wall given a start and an end point (which are totally interchangeable). * @param {Vector} start the start point * @param {Vector} end the end point */ constructor(start, end) { this.start = start; this.end = end; this.length = end.sub(start).abs; this.direction = end.sub(start).unit(); Wall.list.push(this); } /** * @type {Wall[]} list of all instances */ static list = []; } /** * Bumpers are stationary round objects that bounce the ball away from them, along the direction they were hit from. */ class Bumper { /** * Creates a new bumper given its position. * @param {Vector} position the bumper's position on the flipper board */ constructor(position) { this.position = position; Bumper.list.push(this); } /** * @type {Bumper[]} list of all instances */ static list = []; } class Flipper { constructor(position, isLeft) { this.position = position; this.isLeft = isLeft; Flipper.list.push(this); } /** * @type {Flipper[]} list of all instances */ static list = []; /** * @type {boolean} seeking the 'up' position */ active = false; /** * @type {boolean} currently in motion to achieve its desired position */ isMoving = false; /** * @type {number} current relative angular position: `0` totally down, `1` totally up */ angleRatio = 0; /** * Returns the flipper's current angle w.r.t. the positive x-axis. */ get angle() { let leftAngle = FLIPPER_RESTING_ANGLE + (FLIPPER_ACTIVE_ANGLE - FLIPPER_RESTING_ANGLE) * this.angleRatio; return this.isLeft ? leftAngle : Math.PI - leftAngle; } /** * Returns the flipper's unit vector from hinge to extremity. */ get direction() { return Vector.unit(this.angle); } /** * Returns the position of the flipper's extremity. */ get extremity() { return this.direction.scale(FLIPPER_LENGTH).add(this.position); } /** * Returns the flipper's current angular velocity in radians per second (positive = counterclockwise). */ get pulse() { if (!this.isMoving) return 0; if (this.isLeft ^ this.active) return -FLIPPER_PULSE; return FLIPPER_PULSE; } /** * Updates the flipper's position and motion over a small time differential. * @param {number} dt the time differential */ update(dt) { let pulseDirection = this.active ? 1 : -1; let rawAngleRatio = this.angleRatio + pulseDirection * dt / FLIPPER_SWEEP_TIME; if (rawAngleRatio >= 0 && rawAngleRatio <= 1) { this.angleRatio = rawAngleRatio; this.isMoving = true; } else this.isMoving = false; } } class Ball { /** * @type {Vector} the position of the ball in units */ position = new Vector(BALL_START_X, BALL_START_Y); /** * @type {Vector} the velocity of the ball in units per second */ velocity = new Vector(0, 0); /** * @type {boolean} whether the ball has been launched */ launched = false; /** * Updates the ball's position and velocity regardless of collisions over a small time differential. * @param {Vector} gravity the direction of gravity * @param {number} dt the time differential */ update(gravity, dt) { const CENTER_SEEKING_FORCE = .4; this.velocity = this.velocity.add(gravity.scale(dt)).sub(this.velocity.unit().scale(FRICTION * dt)).sub(this.velocity.scale(this.velocity.abs * DRAG * dt)); if(this.position.x < 1.52 && this.launched) this.velocity = this.velocity.add(new Vector(CENTER_SEEKING_FORCE, 0).scale(dt)); else if(this.position.x > 3.5 && this.launched) this.velocity = this.velocity.sub(new Vector(CENTER_SEEKING_FORCE, 0).scale(dt)); if(this.velocity.abs > SAFE_VELOCITY) this.velocity = this.velocity.unit().scale(SAFE_VELOCITY); this.position = this.position.add(this.velocity.scale(dt)); if(this.position.y < -2 * BALL_RADIUS) { if(lives > 1) { this.position = new Vector(BALL_START_X, BALL_START_Y); this.launched = false; lives--; updateBallCounter(lives, false); playSound(soundReload); } else if(lives == 1) updateBallCounter(0, true); this.velocity = Vector.NULL; } } /** * Checks and manages collisions with a wall. * @param {Wall} wall the wall */ checkCollisionWithWall(wall) { let relativeToStart = this.position.sub(wall.start); let wallAbscissa = relativeToStart.dot(wall.direction); wallAbscissa = Math.max(0, Math.min(wallAbscissa, wall.length)); // clamp wallAbscissa in [0, length] let impactPoint = wall.direction.scale(wallAbscissa).add(wall.start); let hit = this.handleCollision(impactPoint, Vector.NULL, WALL_RESTITUTION, 0); if(hit) { if(this.velocity.abs < 1 || this.position.y < 1.4 && Math.abs(this.velocity.y) < 1) return; let i = Math.floor(3 * Math.random()); let sound = [soundWall1, soundWall2, soundWall3][i]; playSound(sound); } } /** * Checks and manages collisions with a bumper. * @param {Bumper} bumper the bumper */ checkCollisionWithBumper(bumper) { let bumperCenterToBall = this.position.sub(bumper.position); let bumperCenterToImpactPoint = bumperCenterToBall.unit().scale(BUMPER_RADIUS); let impactPoint = bumperCenterToImpactPoint.add(bumper.position); let hit = this.handleCollision(impactPoint, Vector.NULL, BUMPER_RESTITUTION, 0); if(hit) { score += Date.now() % 61; let i = Math.floor(3 * Math.random()); let sound = [soundBumper1, soundBumper2, soundBumper3][i]; playSound(sound); } } /** * Checks and manages collisions with a flipper. * @param {Flipper} flipper the flipper */ checkCollisionWithFlipper(flipper) { let relativeToHinge = this.position.sub(flipper.position); let flipperAbscissa = relativeToHinge.dot(flipper.direction); flipperAbscissa = Math.max(0, Math.min(flipperAbscissa, FLIPPER_LENGTH)); // clamp flipperAbscissa in [0, length] let impactPoint = flipper.direction.scale(flipperAbscissa).add(flipper.position); let impactPointVelocity = flipper.direction.normal().scale(flipperAbscissa * flipper.pulse); // apply rivals theorem: new basis rotating with flipper let hit = this.handleCollision(impactPoint, impactPointVelocity, FLIPPER_RESTITUTION, FLIPPER_ENERGY_TRANSFER_EFFICIENCY); if(hit) { if(this.velocity.abs < 1 || this.position.y < 1.4 && Math.abs(this.velocity.y) < 1) return; let i = Math.floor(3 * Math.random()); let sound = [soundWall1, soundWall2, soundWall3][i]; playSound(sound); } } /** * Updates the ball's position and velocity considering a collision with a flat surface in a neighbourhood of a given impact point * @param {Vector} impactPoint the position of the point of impact * @param {Vector} impactPointVelocity the velocity of the point of impact on the moving surface (null vector if stationary) * @param {number} restitution the ratio between the ball's velocity's normal-to-the-surface component before vs. after the impact * @param {number} energyTransferEfficiency the portion of the kinetic energy transferred from the surface to the ball, if the surface is moving */ handleCollision(impactPoint, impactPointVelocity, restitution, energyTransferEfficiency) { let relativePosition = this.position.sub(impactPoint); let distance = relativePosition.abs; if (distance >= BALL_RADIUS) return false; // "bounce" the ball out of the surface along a line connecting the impact point to the center of the ball (i.e. normal to the surface) let normal = relativePosition.unit(); let penetration = BALL_RADIUS - distance; distance = BALL_RADIUS + penetration; relativePosition = normal.scale(distance); this.position = impactPoint.add(relativePosition); // adjust velocity ~ restitution and energy transfer efficiency only apply to the normal component of the relative velocity let relativeVelocity = this.velocity.sub(impactPointVelocity); let tangent = normal.normal(); // sounds dodgy but it's true let velocityTangent = relativeVelocity.dot(tangent); let velocityNormal = relativeVelocity.dot(normal); velocityNormal *= restitution; velocityNormal += 2 * impactPointVelocity.abs * energyTransferEfficiency; relativeVelocity = normal.scale(velocityNormal).add(tangent.scale(velocityTangent)); this.velocity = impactPointVelocity.add(relativeVelocity); return true; } /** * Launches the ball. */ launch(force) { if(this.launched) return; this.velocity = new Vector(0, force * BALL_LAUNCH_SPEED); this.launched = true; playSound(soundLaunch); } }
JavaScript
CL
965ad077925e1e19495020fbf02d30388ac73d5f05d163a2d95eb576634f454f
// REACT DEPENDENCIES import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { render } from 'react-dom'; // COMPONENT LAYERS import Template from "./template/trb-map.template.jsx"; import Api from "./api/trb-map.api.jsx"; import Styles from "./services/trb-map.styles.service.jsx"; import Texts from "./services/trb-map.text.service.jsx"; // COMPONENT STATIC DATA import stylesDefault from "./styles/trb-map.styles.default.js"; import stylesOptions from "./styles/trb-map.styles-options.default.js"; import computeStyles from "./styles/trb-map.compute-styles.js"; import texts from "./text/trb-map.text.js"; //COMPONENT CHILDREN import SimpleMap from "./components/simple-map/simple-map.jsx" import SideList from "./components/side-list-mui/side-list-mui.jsx" import ClientsDataService from "./../../../api/clients/client/clients.data.service.jsx"; //PARENT SERVICE import AppStylesOptionsService from "./../../services/app.styles-options.service.jsx" // BUILD CHLIDREN @SimpleMap() class $SimpleMap{} //@AppStylesOptionsService() @SideList() class $SideList{} let appChilds = { SimpleMap : $SimpleMap, SideList : $SideList } export default function TrbMap(SimpleMap){ return (wrappedComponent)=>{ @ClientsDataService() @Styles(computeStyles, stylesDefault, stylesOptions) @Api() @Texts(texts) @Template(appChilds) class TrbMap_Component {} return TrbMap_Component } }
JavaScript
CL
add975f6cadae0079d5b6d6eac4d51833af286fc60f0455f60fca06df607906d
//========================= // Plane: Gobosh // Lesson: 1 //========================= //========================= // Section Headers //========================= exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('lessonContents').del() .then(function () { // Inserts seed entries return knex('lessonContents').insert([ //========================= // Plane: Gobosh // Lesson: 1 //========================= //========================= // Section Headers //========================= { lesson_id: knex('lessons').where('lessonOn', 'gobosh').select('id').first(), order: 1.0, type: 'sectionHeader', content: 'Gobosh Descriptive Data and Definitions and Abbreviations' }, //========================= // Data list // // ( = Sub header // > = data type // - = list item // : = data value // ; = end of line/list item // < = paragraph //========================= { lesson_id: knex('lessons').where('lessonOn', 'gobosh').select('id').first(), order: 1.1, type: 'dataList', content: `(Important Gobosh Characteristics; > Dimensions; - Span : 27.4 ft; - Lenght : 20.5 ft; - Height : 7.34 ft; > Landing gear; - Wheel track : 7.42 ft; > Engine; < Four cylinder, horizontally opposed BOMBARDIER ROTAX, model 912ULS engine. The cylinders are air-cooled, the cylinder heads, by liquid cooled. Dual ignition. 98.5 HP take-off power, 92.5 HP continuous power.` },{ lesson_id: knex('lessons').where('lessonOn', 'gobosh').select('id').first(), order: 1.2, type: 'dataList', content: `(Important or helpful Abbreviations and definitions; > Air Speeds; - TAS : “TRUE AIRSPEED” means the airspeed of an air vessel, relative to the undisturbed airflow. It is CAS corrected by the change of air density depending on altitude and temperature.; - VNE : Maximum never exceed airspeed. This is a limit speed, which cannot be exceeded in any conditions.; - VNO : Maximum structural cruising speed. This is a limit speed which cannot be exceeded except in non-turbulent conditions, and then, only with care.; - VA : Maneuvering speed. Above this speed, rapid or full displacement of the control surfaces may in certain circumstances result in exceeding the maximum permissible loads of the structure.; - VFE : Maximum airspeed with wing flaps extended. This is the maximum permitted airspeed of the airplane with wing flaps extended.; - VS1 : Stalling speed, or minimum airspeed of steady flight, at which the airplane is steer able in any other configuration than the landing configu- ration.; - VS0 : Stalling speed, or minimum airspeed of steady flight, at which the airplane is steer able in the landing configuration.; - VX : Airspeed for the maximum angle of climb. This is the airspeed, at which the maximum increase of altitude over the shortest distance may be achieved.; - VY : Airspeed for the maximum rate of climb. This is the airspeed at which the maximum increase of altitude in the shortest time may be achieved.;` } ]); }); };
JavaScript
CL
f82d03b8db5d6e32c43d02498110d439b050aa5fee11681abb3a1e9260833c2d
/* @license This software is distributed under The MIT License (MIT). Copyright (c) 2013 Present Creative */ import event.Emitter as Emitter; var DEFAULT_TIMER = 1000; exports = Class(Emitter, function(supr) { this.init = function(opts) { supr(this, 'init', [opts]); //set up array to hold scheduled events this._timerEvents = {}; //Get Current Time, set to master clock var date = new Date(); this._masterClock = date.getTime(); GC.app.engine.on('Tick', bind(this,function (dt) { //increment master clock by the delta time since last frame this._masterClock += dt; this._fireEvents(dt); })); } //Get whatever the current master clock is this._currentClockTime = function() { return new Number(this._masterClock); } this._scheduleEvent = function(eventFunc,timer,repeat,limit) { //do not schedule if function is not defined if(typeof(eventFunc) != "function") { return; } timer = timer === undefined ? DEFAULT_TIMER : timer; //when the event should be fired repeat = repeat === undefined ? false : repeat; //defaults to a single event limit = limit === undefined ? 0 : limit; //defaults to a single event var currentTime = this._currentClockTime(); var _event = { startTime: currentTime, scheduledFiringTime: currentTime + timer, repeat: repeat, timer: timer, loops: 0, limit: limit, eventFunction: eventFunc, fired: false, }; var _uid = this._makeEventUID(); //unique identifier this._timerEvents[_uid] = _event; return _uid; } //create a unique identifier this._makeEventUID = function() { var str = this._currentClockTime(); var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; i < 5; i++ ) { str += possible.charAt(Math.floor(Math.random() * possible.length)); } //verify the uid is not in use if(this._timerEvents[str] === undefined) { return str; } else { return this._makeEventUID(); } } //removes event from the firing schedule this._removeEvent = function(uid) { if(this._timerEvents[uid] === undefined) { return false; } else { delete this._timerEvents[uid]; return true; } } //fire all scheduled events this._fireEvents = function() { var now = this._currentClockTime(); var eventsToDelete = []; //loop through scheduled events and fire the ones necessary for(var i in this._timerEvents) { var evt = this._timerEvents[i]; if(evt.scheduledFiringTime <= now) { evt.eventFunction(); //if repeating event, set next timer, else remove the event if(evt.repeat) { evt.scheduledFiringTime = now + evt.timer; evt.loops += 1; //check for limit if(evt.limit > 0 && evt.loops >= evt.limit) { eventsToDelete.push(i); } } else { eventsToDelete.push(i); } } } for(var k in eventsToDelete) { this._removeEvent(eventsToDelete[k]); } }; //API ACCESSIBLE FUNCTIONS this.scheduleSingleEvent = function(eventFunc,timer) { return this._scheduleEvent(eventFunc,timer,false); //returns uid of event }; this.scheduleRepeatingEvent = function(eventFunc,timer,limit) { limit = limit == undefined ? 0 : limit; //defaults to neverending loop return this._scheduleEvent(eventFunc,timer,true,limit); //returns uid of event }; this.cancelEvent = function(uid) { return this._removeEvent(uid); //if event is removed, returns true } this.getEvent = function(uid) { return this._timerEvents[uid]; }; });
JavaScript
CL
9faf65e7559a984f014c98ffc504e0eddcb936c44114e7676ff0a393bce7f532
import React, { PureComponent } from "react" import { graphql } from "gatsby" import ChurchManagement from '../components/home/church'; import Management from '../components/home/management'; import Features from '../components/home/features'; import Devices from '../components/home/devices'; import Testimonials from '../components/home/testimonials'; import Ministry from '../components/home/ministry'; import Pricing from '../components/home/Pricing'; import LatestBlog from '../components/blogs/latestblog'; import Layout from "../components/layout" import 'bootstrap/dist/css/bootstrap.min.css'; import './index.scss'; /** * * @param {*} props data from index.md via graphQL * @see https://codeburst.io/build-a-blog-using-gatsby-js-react-8561bfe8fc91 */ class IndexPage extends PureComponent { constructor(props) { super(props); this.handleMenuClick = this.handleMenuClick.bind(this); } handleMenuClick() { this.setState({ isMenuOpen: !this.state.isMenuOpen, }); } render() { const homepage = this.props.data.allMarkdownRemark; const { title } = homepage.edges[0].node.frontmatter; if(typeof window !== `undefined`) document.title = `UCare | ${title}`; return ( <Layout> <ChurchManagement /> <Management /> <Features /> <Devices fluid={ this.props.data.deviceImage.childImageSharp.fluid } googlefluid={ this.props.data.googleImage.childImageSharp.fluid } /> <Testimonials /> <Ministry /> <Pricing fluid={ this.props.data.pricingImage.childImageSharp.fluid } /> <LatestBlog /> </Layout> ) } } export default IndexPage export const listQuery = graphql` query ListQuery { allMarkdownRemark( filter: { frontmatter: { url: { eq: "/home/"}}}) { edges { node { fields { slug } html excerpt(pruneLength: 250) frontmatter { date(formatString: "MMMM Do YYYY") title url } } } } deviceImage: file(relativePath: { eq: "page/home/iDevices2.png"}) { childImageSharp { fluid { base64 tracedSVG aspectRatio src srcSet srcWebp srcSetWebp sizes originalImg originalName } } } appleImage: file(relativePath: { eq: "page/home/badge_appstore-lrg.svg"}) { childImageSharp { fluid { base64 tracedSVG aspectRatio src srcSet srcWebp srcSetWebp sizes originalImg originalName } } } googleImage: file(relativePath: { eq: "page/home/en_badge_web_generic-300x89.png"}) { childImageSharp { fluid { base64 tracedSVG aspectRatio src srcSet srcWebp srcSetWebp sizes originalImg originalName } } } pricingImage: file(relativePath: { eq: "page/home/pricing.jpg" }) { childImageSharp { fluid { base64 tracedSVG aspectRatio src srcSet srcWebp srcSetWebp sizes originalImg originalName } } } } `
JavaScript
CL
9a602f86458e29bae5a14b6d2a0743f6d3afee9195cdb0030a79302c8f4e7eb7
const quotes = [ { "quote" : "Роль человечества — достигать ниспосланных целей c чистым сердцем, находящимся в гармонии с мирозданием и любящим всё.", "source" : "Морихэй Уэсиба" }, { "quote" : "Сохраняйте свой разум светлым и чистым, как огромное небо, великий океан и самая высокая вершина, пустым от всех мыслей. Всегда сохраняйте ваше тело полным света и тепла. Заполните себя силой мудрости и просветления.", "source" : "Морихэй Уэсиба" }, { "quote" : "Прогресс приходит к тем, кто тренируется изо дня в день. Полагающиеся на секретные техники ни к чему не придут.", "source" : "Морихэй Уэсиба" }, { "quote" : "Все законы неба и земли живут в тебе. Жизнь сама по себе есть истина, и это не изменится никогда. Всё сущее на небе и на земле дышит. Дыхание — это нить, связывающая всё мироздание воедино.", "source" : "Морихэй Уэсиба" }, { "quote" : "Не взирай на этот мир со страхом и отвращением. Смело смотри в лицо тому, что предлагают тебе боги.", "source" : "Морихэй Уэсиба" }, { "quote" : "Как только ты начинаешь искать «хорошее» и «плохое» в своих близких, в твоём сердце открывается дыра, через которую входит зломыслие. Если ты испытываешь других, соревнуешься с ними, критикуешь их — это приводит к твоему ослаблению и поражению.", "source" : "Морихэй Уэсиба" }, { "quote" : "Цель тренировок — подтягивать ослабленное, тренировать тело и шлифовать дух.", "source" : "Морихэй Уэсиба" }, { "quote" : "В Искусстве Мира нет состязаний. Истинный Воин непобедим, поскольку он ни с кем не сражается. Нанести поражение означает поражение нашего собственного противоречивого ума.", "source" : "Морихэй Уэсиба" }, { "quote" : "Тебе не нужны дома, деньги, власть или положение, чтобы практиковать Искусство Мира. Небо — там, где ты сейчас стоишь, и это как раз то место, где можно тренироваться.", "source" : "Морихэй Уэсиба" }, { "quote" : "У каждого есть дух, который нужно совершенствовать; тело, которое должно быть тренировано; и путь, который должен быть пройден...", "source" : "Морихэй Уэсиба" }, { "quote" : "Жизнь — это мгновение за мгновением, и мера вашей жизни — то, как ваш дух расцветает в каждое из этих мгновений.", "source" : "Морихэй Уэсиба" }, { "quote" : "Правильная поза и осанка отражают должное состояние духа.", "source" : "Морихэй Уэсиба" }, { "quote" : "Техники требуют четырёх качеств, в которых отражается природа нашего мира. В зависимости от обстоятельств, ты должен быть: твёрдым, как алмаз, гибким, как ива, плавным, как течение воды, или пустым, как небо.", "source" : "Морихэй Уэсиба" } ] function randomQuote() { let random = quotes[Math.floor(Math.random() * quotes.length)]; quotation.innerText = "“"+random.quote+"”"; source.innerText = random.source; } randomQuote(); document.querySelector("qfooter").addEventListener('click', randomQuote) $(".nav a").on("click", function(){ $(".nav").find(".active").removeClass("active"); $(this).parent().addClass("active"); });
JavaScript
CL
cc6bf4e0f5f68de18e6a7c623ad71f9344e9ee903364b9b382765050f9602412
import {flip, pickRandom} from 'app/tools/rand' import {logM} from 'app/tools/debug' import {compose, reduce, filter, set, lensPath, append, dissocPath} from 'ramda' const Location = (row, col, i) => ({row, col, i}) const shouldMove = () => flip(0.75) const isTruey = x => !!x const canMoveUp = (rowIdx) => rowIdx > 0 const canMoveDown = (board, rowIdx) => rowIdx < (board.length - 1) const canMoveLeft = (colIdx) => colIdx > 0 const canMoveRight = (board, colIdx) => board.length && colIdx < (board[0].length - 1) const moveUnit = (from, to, board) => { return compose( logM(`after: (${from.row}, ${from.col}, ${from.i}) -> (${to.row}, ${to.col})`), dissocPath( [from.row, from.col, from.i] ), set( lensPath([to.row, to.col]), append(board[from.row][from.col][from.i], board[to.row][to.col]) ), logM(`before: (${from.row}, ${from.col}, ${from.i}) -> (${to.row}, ${to.col})`) )(board) } // TODO -- there's a bug here. Each iteration gives us a new board, but we're using old indexes (i.e. the unitIdx may no longer exist in the new board) const move = (board) => reduce( (board, rowIdx) => reduce( (board, colIdx) => reduce( (board, unitIdx) => { // shouldn't move if(!shouldMove()) return board const possibleMovements = filter(isTruey, [ canMoveUp(rowIdx) ? 'up' : false, canMoveDown(board, rowIdx) ? 'down' : false, canMoveLeft(colIdx) ? 'left' : false, canMoveRight(board, colIdx) ? 'right' : false, ]) // can't move if(!possibleMovements.length) return board const movement = pickRandom(possibleMovements) switch(movement) { case 'up': return moveUnit( Location(rowIdx, colIdx, unitIdx), Location(rowIdx - 1, colIdx, null), board ) case 'down': return moveUnit( Location(rowIdx, colIdx, unitIdx), Location(rowIdx + 1, colIdx, null), board ) case 'left': return moveUnit( Location(rowIdx, colIdx, unitIdx), Location(rowIdx, colIdx - 1, null), board ) case 'right': return moveUnit( Location(rowIdx, colIdx, unitIdx), Location(rowIdx, colIdx + 1, null), board ) } }, board, board[rowIdx][colIdx].keys() ), board, board[rowIdx].keys() ), board, board.keys() ) const react = (board) => { return board } export const step = compose( react, move )
JavaScript
CL
a71370bbd50d6d81a95d2994256773dc6b64dcc5d6654e4e268b8d70d18f62c2
// In development use .env.local for environment variables if (process.env.NODE_ENV !== "production") { require("dotenv").config({ path: ".env.local" }); } const config = Object.freeze({ MONGO_URL: process.env.MONGODB_URI || "mongodb://localhost:27017/silma", ENV: process.env.NODE_ENV || "development", PORT: process.env.PORT || 3000, CROSS_ORIGIN: process.env.CROSS_ORIGIN || "*", SECRET_JWT: process.env.SECRET_JWT || "secret", EMAIL_HOST: process.env.EMAIL_HOST, EMAIL_PORT: process.env.EMAIL_PORT, EMAIL_USER: process.env.EMAIL_USER, EMAIL_PASSWORD: process.env.EMAIL_PASSWORD, AWS_BUCKET: process.env.AWS_BUCKET || 'silmaprod', AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY }); export default config;
JavaScript
CL
73d9ffa228347788c3df46e8074748b9ac2b8ce6969bcb59a6015f0040fdb282
'use strict'; /*jshint expr: true*/ const envRestorer = require( 'env-restorer' ); const expect = require( 'chai' ).expect; const MODULE_PATH = 'lib/plugins/protect/index'; const ProtectPlugin = require( '../../../../' + MODULE_PATH ); describe( MODULE_PATH, function() { describe( 'ProtectPlugin', function() { describe( 'constructor', function() { beforeEach( function() { delete process.env.VANDIUM_PROTECT; }); afterEach( function() { envRestorer.restore(); }); it( 'process.env.VANDIUM_PROTECT not set', function() { let protect = new ProtectPlugin(); expect( protect.name ).to.equal( 'protect' ); expect( protect.engines ).to.exist; expect( protect.engines.sql ).to.exist; expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); }); [ [ 'yes', { sql: { enabled: true, mode: 'fail', lambdaProxy: false } } ], [ 'on', { sql: { enabled: true, mode: 'fail', lambdaProxy: false } } ], [ 'true', { sql: { enabled: true, mode: 'fail', lambdaProxy: false } } ], [ 'no', { sql: { enabled: false } } ], [ 'off', { sql: { enabled: false } } ], [ 'false', { sql: { enabled: false } } ], [ 'report', { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ], [ 'unknown-value', { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ] ].forEach( function( testCase ) { it( 'process.env.VANDIUM_PROTECT = ' + testCase[0], function() { process.env.VANDIUM_PROTECT = testCase[0]; let protect = new ProtectPlugin(); expect( protect.name ).to.equal( 'protect' ); expect( protect.engines ).to.exist; expect( protect.engines.sql ).to.exist; expect( protect.state ).to.eql( testCase[1] ); }); it( 'process.env.VANDIUM_PROTECT = ' + testCase[0].toUpperCase(), function() { process.env.VANDIUM_PROTECT = testCase[0].toUpperCase(); let protect = new ProtectPlugin(); expect( protect.name ).to.equal( 'protect' ); expect( protect.engines ).to.exist; expect( protect.engines.sql ).to.exist; expect( protect.state ).to.eql( testCase[1] ); }); }); }); describe( '.disable', function() { it( 'disable sql', function() { let protect = new ProtectPlugin(); expect( protect.sql.state.enabled ).to.be.true; protect.disable( 'sql' ); expect( protect.sql.state ).to.eql( { enabled: false } ); expect( protect.state ).to.eql( { sql: { enabled: false } } ); }); it( 'disable unknown engine', function() { let protect = new ProtectPlugin(); expect( protect.sql.state.enabled ).to.be.true; protect.disable( 'special' ); expect( protect.sql.state.enabled ).to.be.true; }); it( 'disable all', function() { let protect = new ProtectPlugin(); expect( protect.sql.state.enabled ).to.be.true; protect.disable(); expect( protect.sql.state ).to.eql( { enabled: false } ); expect( protect.state ).to.eql( { sql: { enabled: false } } ); }); }); describe( '.configure', function() { it( 'empty configuration, newly created instance', function() { let protect = new ProtectPlugin(); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); protect.configure( {} ); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); }); it( 'empty configuration, disabled instance', function() { let protect = new ProtectPlugin(); protect.disable(); expect( protect.state ).to.eql( { sql: { enabled: false} } ); protect.configure( {} ); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); }); it( 'missing configuration, newly created instance', function() { let protect = new ProtectPlugin(); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); protect.configure(); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); }); it( 'missing configuration, disabled instance', function() { let protect = new ProtectPlugin(); protect.disable(); expect( protect.state ).to.eql( { sql: { enabled: false} } ); protect.configure(); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); }); it( 'configuration = { mode: "fail" }', function() { let protect = new ProtectPlugin(); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); protect.configure( { mode: 'fail' } ); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'fail', lambdaProxy: false } } ); }); it( 'configuration = { mode: "disabled" }', function() { let protect = new ProtectPlugin(); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); protect.configure( { mode: 'disabled' } ); expect( protect.state ).to.eql( { sql: { enabled: false } } ); }); it( 'configuration = { mode: "report" }', function() { let protect = new ProtectPlugin(); protect.disable(); expect( protect.state ).to.eql( { sql: { enabled: false } } ); protect.configure( { mode: 'report' } ); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); }); it( 'configuration = { mode: "unknown-value" }', function() { let protect = new ProtectPlugin(); protect.disable(); expect( protect.state ).to.eql( { sql: { enabled: false } } ); protect.configure( { mode: 'unknown-value' } ); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); }); it( 'configuration = { sql: { mode: "fail" } }', function() { let protect = new ProtectPlugin(); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); protect.configure( { sql: { mode: "fail" } } ); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'fail', lambdaProxy: false } } ); }); it( 'configuration = { sql: { mode: "fail", lambdaProxy: true } }', function() { let protect = new ProtectPlugin(); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); protect.configure( { sql: { mode: "fail", lambdaProxy: true } } ); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'fail', lambdaProxy: true } } ); }); it( 'configuration = { lambdaProxy: true, sql: { mode: "fail" } }', function() { let protect = new ProtectPlugin(); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'report', lambdaProxy: false } } ); protect.configure( { lambdaProxy: true, sql: { mode: "fail" } } ); expect( protect.state ).to.eql( { sql: { enabled: true, mode: 'fail', lambdaProxy: true } } ); }); }); describe( '.getConfiguration', function() { it( 'normal operation', function() { let protect = new ProtectPlugin(); protect.configure( { mode: 'report' } ); expect( protect.getConfiguration() ).to.eql( { mode: 'report' } ); protect.configure( { mode: 'disabled' } ); expect( protect.getConfiguration() ).to.eql( { mode: 'disabled' } ); protect.configure( { mode: 'fail' } ); expect( protect.getConfiguration() ).to.eql( { mode: 'fail' } ); }); }); describe( '.execute', function() { it( 'no attack', function( done ) { let event = { myField: "nothin' exciting" }; let protect = new ProtectPlugin(); protect.sql.fail(); protect.execute( { event }, function( err ) { done( err ); }); }); it( 'potential attack', function( done ) { let event = { myField: "1';drop table user;" }; let protect = new ProtectPlugin(); protect.sql.fail(); protect.execute( { event }, function( err ) { expect( err.message ).to.equal( 'validation error: myField is invalid' ); done(); }); }); }); }); });
JavaScript
CL
761a3551ebf91e5069ee7ddf61380a35686a197d6b3ccfcaea02b10cc4cfc78a
import React from 'react'; import ReactDOM from 'react-dom'; import './style/index.css'; import registerServiceWorker from './registerServiceWorker'; // REACT ROUTER import {BrowserRouter, Switch, Route} from 'react-router-dom'; // COMPONENTS import BaseLayout from './components/BaseLayout'; import App from './components/App'; import StrategyGames from './components/StrategyGames'; import CardGames from './components/CardGames'; import KidsGames from './components/KidsGames'; import About from './components/About'; import Contact from './components/Contact'; ReactDOM.render( <BrowserRouter> <Switch> <BaseLayout> <Route exact path="/" component={App} /> <Route path="/strategy" component={StrategyGames} /> <Route path="/card" component={CardGames} /> <Route path="/kids" component={KidsGames} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> </BaseLayout> </Switch> </BrowserRouter> , document.getElementById('root')); registerServiceWorker();
JavaScript
CL
6e04100d8f3641d3f909903620851c2253695a6698826c6f8b5b68935fe89333
/******/ (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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _p = __webpack_require__(1); var P5 = _interopRequireWildcard(_p); var _sketch = __webpack_require__(6); var _sketch2 = _interopRequireDefault(_sketch); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var p5 = new P5.default(_sketch2.default); // TODO: Try to use p5.min or maybe point to the local file // import * as P5 from '../../vendor/js/p5.min'; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;var require;var require;var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj;}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};/*! p5.js v0.7.2 September 02, 2018 */(function(f){if(( false?"undefined":_typeof(exports))==="object"&&typeof module!=="undefined"){module.exports=f();}else if(true){!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (f), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));}else{var g;if(typeof window!=="undefined"){g=window;}else if(typeof global!=="undefined"){g=global;}else if(typeof self!=="undefined"){g=self;}else{g=this;}g.p5=f();}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return require(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f;}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e);},l,l.exports,e,t,n,r);}return n[o].exports;}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++){s(r[o]);}return s;}({1:[function(_dereq_,module,exports){module.exports={"project":{"name":"p5","description":"[![Build Status](https://travis-ci.org/processing/p5.js.svg?branch=master)](https://travis-ci.org/processing/p5.js) [![npm version](https://badge.fury.io/js/p5.svg)](https://www.npmjs.com/package/p5)","version":"0.7.2","url":"https://github.com/processing/p5.js#readme"},"files":{"src/color/color_conversion.js":{"name":"src/color/color_conversion.js","modules":{"Color Conversion":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/color/creating_reading.js":{"name":"src/color/creating_reading.js","modules":{"Creating & Reading":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/color/p5.Color.js":{"name":"src/color/p5.Color.js","modules":{},"classes":{"p5.Color":1},"fors":{"p5":1},"namespaces":{}},"src/color/setting.js":{"name":"src/color/setting.js","modules":{"Setting":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/core/shape/2d_primitives.js":{"name":"src/core/shape/2d_primitives.js","modules":{"2D Primitives":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/core/shape/attributes.js":{"name":"src/core/shape/attributes.js","modules":{"Attributes":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/core/shape/curves.js":{"name":"src/core/shape/curves.js","modules":{"Curves":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/core/shape/vertex.js":{"name":"src/core/shape/vertex.js","modules":{"Vertex":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/core/constants.js":{"name":"src/core/constants.js","modules":{"Constants":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/core/environment.js":{"name":"src/core/environment.js","modules":{"Environment":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/core/error_helpers.js":{"name":"src/core/error_helpers.js","modules":{},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/core/helpers.js":{"name":"src/core/helpers.js","modules":{},"classes":{},"fors":{},"namespaces":{}},"src/core/init.js":{"name":"src/core/init.js","modules":{},"classes":{},"fors":{},"namespaces":{}},"src/core/legacy.js":{"name":"src/core/legacy.js","modules":{},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/core/main.js":{"name":"src/core/main.js","modules":{"Structure":1},"classes":{"p5":1},"fors":{"p5":1},"namespaces":{}},"src/core/p5.Element.js":{"name":"src/core/p5.Element.js","modules":{"DOM":1},"classes":{"p5.Element":1},"fors":{"p5.Element":1},"namespaces":{}},"src/core/p5.Graphics.js":{"name":"src/core/p5.Graphics.js","modules":{"Rendering":1},"classes":{"p5.Graphics":1},"fors":{"p5":1},"namespaces":{}},"src/core/p5.Renderer.js":{"name":"src/core/p5.Renderer.js","modules":{},"classes":{"p5.Renderer":1},"fors":{"p5":1},"namespaces":{}},"src/core/p5.Renderer2D.js":{"name":"src/core/p5.Renderer2D.js","modules":{},"classes":{},"fors":{},"namespaces":{}},"src/core/rendering.js":{"name":"src/core/rendering.js","modules":{},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/core/shim.js":{"name":"src/core/shim.js","modules":{},"classes":{},"fors":{},"namespaces":{}},"src/core/structure.js":{"name":"src/core/structure.js","modules":{},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/core/transform.js":{"name":"src/core/transform.js","modules":{"Transform":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/data/p5.TypedDict.js":{"name":"src/data/p5.TypedDict.js","modules":{"Dictionary":1},"classes":{"p5.TypedDict":1,"p5.StringDict":1,"p5.NumberDict":1},"fors":{"p5.TypedDict":1,"p5":1},"namespaces":{}},"src/events/acceleration.js":{"name":"src/events/acceleration.js","modules":{"Acceleration":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/events/keyboard.js":{"name":"src/events/keyboard.js","modules":{"Keyboard":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/events/mouse.js":{"name":"src/events/mouse.js","modules":{"Mouse":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/events/touch.js":{"name":"src/events/touch.js","modules":{"Touch":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/image/filters.js":{"name":"src/image/filters.js","modules":{},"classes":{},"fors":{},"namespaces":{}},"src/image/image.js":{"name":"src/image/image.js","modules":{"Image":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/image/loading_displaying.js":{"name":"src/image/loading_displaying.js","modules":{"Loading & Displaying":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/image/p5.Image.js":{"name":"src/image/p5.Image.js","modules":{},"classes":{"p5.Image":1},"fors":{},"namespaces":{}},"src/image/pixels.js":{"name":"src/image/pixels.js","modules":{"Pixels":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/io/files.js":{"name":"src/io/files.js","modules":{"Input":1,"Output":1},"classes":{"p5.PrintWriter":1},"fors":{"p5":1},"namespaces":{}},"src/io/p5.Table.js":{"name":"src/io/p5.Table.js","modules":{"Table":1},"classes":{"p5.Table":1},"fors":{},"namespaces":{}},"src/io/p5.TableRow.js":{"name":"src/io/p5.TableRow.js","modules":{},"classes":{"p5.TableRow":1},"fors":{},"namespaces":{}},"src/io/p5.XML.js":{"name":"src/io/p5.XML.js","modules":{"XML":1},"classes":{"p5.XML":1},"fors":{},"namespaces":{}},"src/math/calculation.js":{"name":"src/math/calculation.js","modules":{"Calculation":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/math/math.js":{"name":"src/math/math.js","modules":{"Math":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/math/noise.js":{"name":"src/math/noise.js","modules":{"Noise":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/math/p5.Vector.js":{"name":"src/math/p5.Vector.js","modules":{},"classes":{"p5.Vector":1},"fors":{},"namespaces":{}},"src/math/random.js":{"name":"src/math/random.js","modules":{"Random":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/math/trigonometry.js":{"name":"src/math/trigonometry.js","modules":{"Trigonometry":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/typography/attributes.js":{"name":"src/typography/attributes.js","modules":{},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/typography/loading_displaying.js":{"name":"src/typography/loading_displaying.js","modules":{},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/typography/p5.Font.js":{"name":"src/typography/p5.Font.js","modules":{"Font":1},"classes":{"p5.Font":1},"fors":{},"namespaces":{}},"src/utilities/array_functions.js":{"name":"src/utilities/array_functions.js","modules":{"Array Functions":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/utilities/conversion.js":{"name":"src/utilities/conversion.js","modules":{"Conversion":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/utilities/string_functions.js":{"name":"src/utilities/string_functions.js","modules":{"String Functions":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/utilities/time_date.js":{"name":"src/utilities/time_date.js","modules":{"Time & Date":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/webgl/3d_primitives.js":{"name":"src/webgl/3d_primitives.js","modules":{"3D Primitives":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/webgl/interaction.js":{"name":"src/webgl/interaction.js","modules":{"Interaction":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/webgl/light.js":{"name":"src/webgl/light.js","modules":{"Lights":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/webgl/loading.js":{"name":"src/webgl/loading.js","modules":{"3D Models":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/webgl/material.js":{"name":"src/webgl/material.js","modules":{"Material":1},"classes":{},"fors":{"p5":1},"namespaces":{}},"src/webgl/p5.Camera.js":{"name":"src/webgl/p5.Camera.js","modules":{"Camera":1},"classes":{"p5.Camera":1},"fors":{"p5":1,"p5.Camera":1},"namespaces":{}},"src/webgl/p5.Geometry.js":{"name":"src/webgl/p5.Geometry.js","modules":{},"classes":{"p5.Geometry":1},"fors":{},"namespaces":{}},"src/webgl/p5.Matrix.js":{"name":"src/webgl/p5.Matrix.js","modules":{},"classes":{"p5.Matrix":1},"fors":{},"namespaces":{}},"src/webgl/p5.RendererGL.Immediate.js":{"name":"src/webgl/p5.RendererGL.Immediate.js","modules":{},"classes":{},"fors":{},"namespaces":{}},"src/webgl/p5.RendererGL.Retained.js":{"name":"src/webgl/p5.RendererGL.Retained.js","modules":{},"classes":{},"fors":{},"namespaces":{}},"src/webgl/p5.RendererGL.js":{"name":"src/webgl/p5.RendererGL.js","modules":{},"classes":{"p5.RendererGL":1},"fors":{"p5":1},"namespaces":{}},"src/webgl/p5.Shader.js":{"name":"src/webgl/p5.Shader.js","modules":{"Shaders":1},"classes":{"p5.Shader":1},"fors":{"p5":1},"namespaces":{}},"src/webgl/p5.Texture.js":{"name":"src/webgl/p5.Texture.js","modules":{},"classes":{"p5.Texture":1},"fors":{"p5":1},"namespaces":{}},"src/webgl/text.js":{"name":"src/webgl/text.js","modules":{},"classes":{"ImageInfos":1,"FontInfo":1,"Cubic":1},"fors":{},"namespaces":{}},"lib/addons/p5.dom.js":{"name":"lib/addons/p5.dom.js","modules":{"p5.dom":1},"classes":{"p5.MediaElement":1,"p5.File":1},"fors":{"p5":1,"p5.Element":1},"namespaces":{}},"lib/addons/p5.sound.js":{"name":"lib/addons/p5.sound.js","modules":{"p5.sound":1},"classes":{"p5.SoundFile":1,"p5.Amplitude":1,"p5.FFT":1,"p5.Signal":1,"p5.Oscillator":1,"p5.SinOsc":1,"p5.TriOsc":1,"p5.SawOsc":1,"p5.SqrOsc":1,"p5.Envelope":1,"p5.Pulse":1,"p5.Noise":1,"p5.AudioIn":1,"p5.Effect":1,"p5.Filter":1,"p5.LowPass":1,"p5.HighPass":1,"p5.BandPass":1,"p5.EQ":1,"p5.Panner3D":1,"p5.Delay":1,"p5.Reverb":1,"p5.Convolver":1,"p5.Phrase":1,"p5.Part":1,"p5.Score":1,"p5.SoundLoop":1,"p5.Compressor":1,"p5.SoundRecorder":1,"p5.PeakDetect":1,"p5.Gain":1,"p5.AudioVoice":1,"p5.MonoSynth":1,"p5.PolySynth":1,"p5.Distortion":1},"fors":{"p5.sound":1,"p5":1},"namespaces":{}},"lib/addons/p5.sound.min.js":{"name":"lib/addons/p5.sound.min.js","modules":{},"classes":{},"fors":{},"namespaces":{}}},"modules":{"Color":{"name":"Color","submodules":{"Color Conversion":1,"Creating & Reading":1,"Setting":1},"elements":{},"classes":{"p5.Color":1},"fors":{"p5":1},"namespaces":{},"file":"src/color/p5.Color.js","line":16},"Color Conversion":{"name":"Color Conversion","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Color","namespace":"","file":"src/color/color_conversion.js","line":1,"requires":["core"]},"Creating & Reading":{"name":"Creating & Reading","submodules":{},"elements":{},"classes":{"p5.Color":1},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Color","namespace":"","file":"src/color/p5.Color.js","line":16,"requires":["core","constants"],"description":"<p>Each color stores the color mode and level maxes that applied at the\ntime of its construction. These are used to interpret the input arguments\n(at construction and later for that instance of color) and to format the\noutput e.g. when <a href=\"#/p5/saturation\">saturation()</a> is requested.</p>\n<p>Internally we store an array representing the ideal RGBA values in floating\npoint form, normalized from 0 to 1. From this we calculate the closest\nscreen color (RGBA levels from 0 to 255) and expose this to the renderer.</p>\n<p>We also cache normalized, floating point components of the color in various\nrepresentations as they are calculated. This is done to prevent repeating a\nconversion that has already been performed.</p>\n"},"Setting":{"name":"Setting","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Color","namespace":"","file":"src/color/setting.js","line":1,"requires":["core","constants"]},"Shape":{"name":"Shape","submodules":{"2D Primitives":1,"Curves":1,"Vertex":1,"3D Primitives":1,"3D Models":1},"elements":{},"classes":{},"fors":{"p5":1},"namespaces":{}},"2D Primitives":{"name":"2D Primitives","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Shape","namespace":"","file":"src/core/shape/2d_primitives.js","line":1,"requires":["core","constants"]},"Attributes":{"name":"Attributes","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Typography","namespace":"","file":"src/core/shape/attributes.js","line":1,"requires":["core","constants"]},"Curves":{"name":"Curves","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Shape","namespace":"","file":"src/core/shape/curves.js","line":1,"requires":["core"]},"Vertex":{"name":"Vertex","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Shape","namespace":"","file":"src/core/shape/vertex.js","line":1,"requires":["core","constants"]},"Constants":{"name":"Constants","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"namespaces":{},"module":"Constants","file":"src/core/constants.js","line":1},"Environment":{"name":"Environment","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"namespaces":{},"module":"Environment","file":"src/core/environment.js","line":1,"requires":["core","constants"]},"Structure":{"name":"Structure","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"namespaces":{},"module":"IO","file":"src/core/main.js","line":1,"requires":["constants"]},"DOM":{"name":"DOM","submodules":{},"elements":{},"classes":{"p5.Element":1},"fors":{"p5.Element":1},"namespaces":{},"module":"DOM","file":"src/core/p5.Element.js","line":11,"description":"<p>Base class for all elements added to a sketch, including canvas,\ngraphics buffers, and other HTML elements. Methods in blue are\nincluded in the core functionality, methods in brown are added\nwith the <a href=\"http://p5js.org/reference/#/libraries/p5.dom\">p5.dom\nlibrary</a>.\nIt is not called directly, but <a href=\"#/p5.Element\">p5.Element</a>\nobjects are created by calling <a href=\"#/p5/createCanvas\">createCanvas</a>, <a href=\"#/p5/createGraphics\">createGraphics</a>,\nor in the p5.dom library, <a href=\"#/p5/createDiv\">createDiv</a>, <a href=\"#/p5/createImg\">createImg</a>, <a href=\"#/p5/createInput\">createInput</a>, etc.</p>\n"},"Rendering":{"name":"Rendering","submodules":{"undefined":1},"elements":{},"classes":{"p5.RendererGL":1,"p5.Graphics":1,"p5.Renderer":1},"fors":{"p5":1},"namespaces":{},"module":"Rendering","file":"src/webgl/p5.RendererGL.js","line":427,"description":"<p>Thin wrapper around a renderer, to be used for creating a\ngraphics buffer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. The fields and methods for this class are\nextensive, but mirror the normal drawing API for p5.</p>\n"},"Transform":{"name":"Transform","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"namespaces":{},"module":"Transform","file":"src/core/transform.js","line":1,"requires":["core","constants"]},"Data":{"name":"Data","submodules":{"Dictionary":1,"Array Functions":1,"Conversion":1,"String Functions":1},"elements":{},"classes":{"p5.TypedDict":1,"p5.StringDict":1,"p5.NumberDict":1},"fors":{"p5.TypedDict":1,"p5":1},"namespaces":{},"file":"src/data/p5.TypedDict.js","line":410},"Dictionary":{"name":"Dictionary","submodules":{},"elements":{},"classes":{"p5.TypedDict":1,"p5.StringDict":1,"p5.NumberDict":1},"fors":{"p5.TypedDict":1,"p5":1},"is_submodule":1,"namespaces":{},"module":"Data","namespace":"","file":"src/data/p5.TypedDict.js","line":410,"requires":["core\n\nThis module defines the p5 methods for the p5 Dictionary classes.\nThe classes StringDict and NumberDict are for storing and working\nwith key-value pairs."],"description":"<p>Base class for all p5.Dictionary types. Specifically\n typed Dictionary classes inherit from this class.</p>\n"},"Events":{"name":"Events","submodules":{"Acceleration":1,"Keyboard":1,"Mouse":1,"Touch":1},"elements":{},"classes":{},"fors":{"p5":1},"namespaces":{}},"Acceleration":{"name":"Acceleration","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Events","namespace":"","file":"src/events/acceleration.js","line":1,"requires":["core"]},"Keyboard":{"name":"Keyboard","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Events","namespace":"","file":"src/events/keyboard.js","line":1,"requires":["core"]},"Mouse":{"name":"Mouse","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Events","namespace":"","file":"src/events/mouse.js","line":1,"requires":["core","constants"]},"Touch":{"name":"Touch","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Events","namespace":"","file":"src/events/touch.js","line":1,"requires":["core"]},"Image":{"name":"Image","submodules":{"Pixels":1},"elements":{},"classes":{"p5.Image":1},"fors":{"p5":1},"namespaces":{},"module":"Image","file":"src/image/p5.Image.js","line":23,"requires":["core"],"description":"<p>Creates a new <a href=\"#/p5.Image\">p5.Image</a>. A <a href=\"#/p5.Image\">p5.Image</a> is a canvas backed representation of an\nimage.\n<br><br>\np5 can display .gif, .jpg and .png images. Images may be displayed\nin 2D and 3D space. Before an image is used, it must be loaded with the\n<a href=\"#/p5/loadImage\">loadImage()</a> function. The <a href=\"#/p5.Image\">p5.Image</a> class contains fields for the width and\nheight of the image, as well as an array called <a href=\"#/p5.Image/pixels\">pixels[]</a> that contains the\nvalues for every pixel in the image.\n<br><br>\nThe methods described below allow easy access to the image&#39;s pixels and\nalpha channel and simplify the process of compositing.\n<br><br>\nBefore using the <a href=\"#/p5.Image/pixels\">pixels[]</a> array, be sure to use the <a href=\"#/p5.Image/loadPixels\">loadPixels()</a> method on\nthe image to make sure that the pixel data is properly loaded.</p>\n"},"Loading & Displaying":{"name":"Loading & Displaying","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Typography","namespace":"","file":"src/image/loading_displaying.js","line":1,"requires":["core"]},"Pixels":{"name":"Pixels","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Image","namespace":"","file":"src/image/pixels.js","line":1,"requires":["core"]},"IO":{"name":"IO","submodules":{"Structure":1,"Input":1,"Output":1,"Table":1,"XML":1,"Time & Date":1},"elements":{},"classes":{"p5":1,"p5.PrintWriter":1,"p5.Table":1,"p5.TableRow":1,"p5.XML":1},"fors":{"p5":1},"namespaces":{},"file":"src/io/p5.XML.js","line":11},"Input":{"name":"Input","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"IO","namespace":"","file":"src/io/files.js","line":1,"requires":["core"]},"Output":{"name":"Output","submodules":{},"elements":{},"classes":{"p5":1,"p5.PrintWriter":1},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"IO","namespace":"","file":"src/io/files.js","line":1242,"description":"<p>This is the p5 instance constructor.</p>\n<p>A p5 instance holds all the properties and methods related to\na p5 sketch. It expects an incoming sketch closure and it can also\ntake an optional node parameter for attaching the generated p5 canvas\nto a node. The sketch closure takes the newly created p5 instance as\nits sole argument and may optionally set <a href=\"#/p5/preload\">preload()</a>, <a href=\"#/p5/setup\">setup()</a>, and/or\n<a href=\"#/p5/draw\">draw()</a> properties on it for running a sketch.</p>\n<p>A p5 sketch can run in &quot;global&quot; or &quot;instance&quot; mode:\n&quot;global&quot; - all properties and methods are attached to the window\n&quot;instance&quot; - all properties and methods are bound to this p5 object</p>\n"},"Table":{"name":"Table","submodules":{},"elements":{},"classes":{"p5.Table":1,"p5.TableRow":1},"fors":{},"is_submodule":1,"namespaces":{},"module":"IO","namespace":"","file":"src/io/p5.TableRow.js","line":11,"requires":["core"],"description":"<p><a href=\"#/p5.Table\">Table</a> objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file.</p>\n"},"XML":{"name":"XML","submodules":{},"elements":{},"classes":{"p5.XML":1},"fors":{},"is_submodule":1,"namespaces":{},"module":"IO","namespace":"","file":"src/io/p5.XML.js","line":11,"requires":["core"],"description":"<p>XML is a representation of an XML object, able to parse XML code. Use\n<a href=\"#/p5/loadXML\">loadXML()</a> to load external XML files and create XML objects.</p>\n"},"Math":{"name":"Math","submodules":{"Calculation":1,"Noise":1,"Random":1,"Trigonometry":1},"elements":{},"classes":{"p5.Vector":1},"fors":{"p5":1},"namespaces":{},"module":"Math","file":"src/math/p5.Vector.js","line":12,"requires":["core"],"description":"<p>A class to describe a two or three dimensional vector, specifically\na Euclidean (also known as geometric) vector. A vector is an entity\nthat has both magnitude and direction. The datatype, however, stores\nthe components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude\nand direction can be accessed via the methods <a href=\"#/p5/mag\">mag()</a> and <a href=\"#/p5/heading\">heading()</a>.\n<br><br>\nIn many of the p5.js examples, you will see <a href=\"#/p5.Vector\">p5.Vector</a> used to describe a\nposition, velocity, or acceleration. For example, if you consider a rectangle\nmoving across the screen, at any given instant it has a position (a vector\nthat points from the origin to its location), a velocity (the rate at which\nthe object&#39;s position changes per time unit, expressed as a vector), and\nacceleration (the rate at which the object&#39;s velocity changes per time\nunit, expressed as a vector).\n<br><br>\nSince vectors represent groupings of values, we cannot simply use\ntraditional addition/multiplication/etc. Instead, we&#39;ll need to do some\n&quot;vector&quot; math, which is made easy by the methods inside the <a href=\"#/p5.Vector\">p5.Vector</a> class.</p>\n"},"Calculation":{"name":"Calculation","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Math","namespace":"","file":"src/math/calculation.js","line":1,"requires":["core"]},"Noise":{"name":"Noise","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Math","namespace":"","file":"src/math/noise.js","line":14,"requires":["core"]},"Random":{"name":"Random","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Math","namespace":"","file":"src/math/random.js","line":1,"requires":["core"]},"Trigonometry":{"name":"Trigonometry","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Math","namespace":"","file":"src/math/trigonometry.js","line":1,"requires":["core","constants"]},"Typography":{"name":"Typography","submodules":{"Attributes":1,"Loading & Displaying":1,"Font":1},"elements":{},"classes":{"p5.Font":1},"fors":{"p5":1},"namespaces":{},"file":"src/typography/p5.Font.js","line":21},"Font":{"name":"Font","submodules":{},"elements":{},"classes":{"p5.Font":1},"fors":{},"is_submodule":1,"namespaces":{},"module":"Typography","namespace":"","file":"src/typography/p5.Font.js","line":21,"description":"<p>This module defines the <a href=\"#/p5.Font\">p5.Font</a> class and functions for\ndrawing text to the display canvas.</p>\n","requires":["core","constants"]},"Array Functions":{"name":"Array Functions","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Data","namespace":"","file":"src/utilities/array_functions.js","line":1,"requires":["core"]},"Conversion":{"name":"Conversion","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Data","namespace":"","file":"src/utilities/conversion.js","line":1,"requires":["core"]},"String Functions":{"name":"String Functions","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Data","namespace":"","file":"src/utilities/string_functions.js","line":1,"requires":["core"]},"Time & Date":{"name":"Time & Date","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"IO","namespace":"","file":"src/utilities/time_date.js","line":1,"requires":["core"]},"3D Primitives":{"name":"3D Primitives","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Shape","namespace":"","file":"src/webgl/3d_primitives.js","line":1,"requires":["core","p5.Geometry"]},"Lights, Camera":{"name":"Lights, Camera","submodules":{"Interaction":1,"Lights":1,"Material":1,"Camera":1,"Shaders":1},"elements":{},"classes":{"p5.Camera":1,"p5.Geometry":1,"p5.Matrix":1,"p5.Shader":1,"p5.Texture":1,"ImageInfos":1,"FontInfo":1,"Cubic":1},"fors":{"p5":1,"p5.Camera":1},"namespaces":{},"file":"src/webgl/text.js","line":259},"Interaction":{"name":"Interaction","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Lights, Camera","namespace":"","file":"src/webgl/interaction.js","line":1,"requires":["core"]},"Lights":{"name":"Lights","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Lights, Camera","namespace":"","file":"src/webgl/light.js","line":1,"requires":["core"]},"3D Models":{"name":"3D Models","submodules":{},"elements":{},"classes":{},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Shape","namespace":"","file":"src/webgl/loading.js","line":1,"requires":["core","p5.Geometry"]},"Material":{"name":"Material","submodules":{},"elements":{},"classes":{"p5.Texture":1},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Lights, Camera","namespace":"","file":"src/webgl/p5.Texture.js","line":14,"requires":["core"],"description":"<p>This module defines the p5.Texture class</p>\n"},"Camera":{"name":"Camera","submodules":{},"elements":{},"classes":{"p5.Camera":1},"fors":{"p5":1,"p5.Camera":1},"is_submodule":1,"namespaces":{},"module":"Lights, Camera","namespace":"","file":"src/webgl/p5.Camera.js","line":209,"requires":["core"],"description":"<p>This class describes a camera for use in p5&#39;s\n<a href=\"https://github.com/processing/p5.js/wiki/Getting-started-with-WebGL-in-p5\">\nWebGL mode</a>. It contains camera position, orientation, and projection\ninformation necessary for rendering a 3D scene.</p>\n<p>New p5.Camera objects can be made through the\n<a href=\"#/p5/createCamera\">createCamera()</a> function and controlled through\nthe methods described below. A camera created in this way will use a default\nposition in the scene and a default perspective projection until these\nproperties are changed through the various methods available. It is possible\nto create multiple cameras, in which case the current camera\ncan be set through the <a href=\"#/p5/setCamera\">setCamera()</a> method.</p>\n<p>Note:\nThe methods below operate in two coordinate systems: the &#39;world&#39; coordinate\nsystem describe positions in terms of their relationship to the origin along\nthe X, Y and Z axes whereas the camera&#39;s &#39;local&#39; coordinate system\ndescribes positions from the camera&#39;s point of view: left-right, up-down,\nand forward-backward. The <a href=\"#/p5.Camera/move\">move()</a> method,\nfor instance, moves the camera along its own axes, whereas the\n<a href=\"#/p5.Camera/setPosition\">setPosition()</a>\nmethod sets the camera&#39;s position in world-space.</p>\n"},"Shaders":{"name":"Shaders","submodules":{},"elements":{},"classes":{"p5.Shader":1},"fors":{"p5":1},"is_submodule":1,"namespaces":{},"module":"Lights, Camera","namespace":"","file":"src/webgl/p5.Shader.js","line":13,"description":"<p>This module defines the p5.Shader class</p>\n","requires":["core"]},"p5.dom":{"name":"p5.dom","submodules":{},"elements":{},"classes":{"p5.MediaElement":1,"p5.File":1},"fors":{"p5":1,"p5.Element":1},"namespaces":{},"module":"p5.dom","file":"lib/addons/p5.dom.js","line":3083,"description":"<p><p>The web is much more than just canvas and p5.dom makes it easy to interact\nwith other HTML5 objects, including text, hyperlink, image, input, video,\naudio, and webcam.</p></p>\n<p><p>There is a set of creation methods, DOM manipulation methods, and\nan extended <a href=\"#/p5.Element\">p5.Element</a> that supports a range of HTML elements. See the\n<a href='https://github.com/processing/p5.js/wiki/Beyond-the-canvas'>\nbeyond the canvas tutorial</a> for a full overview of how this addon works.</p>\n<p><p>Methods and properties shown in black are part of the p5.js core, items in\nblue are part of the p5.dom library. You will need to include an extra file\nin order to access the blue functions. See the\n<a href='http://p5js.org/libraries/#using-a-library'>using a library</a>\nsection for information on how to include this library. p5.dom comes with\n<a href='http://p5js.org/download'>p5 complete</a> or you can download the single file\n<a href='https://raw.githubusercontent.com/lmccart/p5.js/master/lib/addons/p5.dom.js'>\nhere</a>.</p></p>\n<p><p>See <a href='https://github.com/processing/p5.js/wiki/Beyond-the-canvas'>tutorial: beyond the canvas</a>\nfor more info on how to use this libary.</a></p>\n","tag":"main","itemtype":"main"},"p5.sound":{"name":"p5.sound","submodules":{},"elements":{},"classes":{"p5.sound":1,"p5.SoundFile":1,"p5.Amplitude":1,"p5.FFT":1,"p5.Signal":1,"p5.Oscillator":1,"p5.SinOsc":1,"p5.TriOsc":1,"p5.SawOsc":1,"p5.SqrOsc":1,"p5.Envelope":1,"p5.Pulse":1,"p5.Noise":1,"p5.AudioIn":1,"p5.Effect":1,"p5.Filter":1,"p5.LowPass":1,"p5.HighPass":1,"p5.BandPass":1,"p5.EQ":1,"p5.Panner3D":1,"p5.Delay":1,"p5.Reverb":1,"p5.Convolver":1,"p5.Phrase":1,"p5.Part":1,"p5.Score":1,"p5.SoundLoop":1,"p5.Compressor":1,"p5.SoundRecorder":1,"p5.PeakDetect":1,"p5.Gain":1,"p5.AudioVoice":1,"p5.MonoSynth":1,"p5.PolySynth":1,"p5.Distortion":1},"fors":{"p5.sound":1,"p5":1},"namespaces":{},"module":"p5.sound","file":"lib/addons/p5.sound.js","line":12501,"description":"<p>p5.sound extends p5 with <a href=\"http://caniuse.com/audio-api\"\ntarget=\"_blank\">Web Audio</a> functionality including audio input,\nplayback, analysis and synthesis.\n<br/><br/>\n<a href=\"#/p5.SoundFile\"><b>p5.SoundFile</b></a>: Load and play sound files.<br/>\n<a href=\"#/p5.Amplitude\"><b>p5.Amplitude</b></a>: Get the current volume of a sound.<br/>\n<a href=\"#/p5.AudioIn\"><b>p5.AudioIn</b></a>: Get sound from an input source, typically\n a computer microphone.<br/>\n<a href=\"#/p5.FFT\"><b>p5.FFT</b></a>: Analyze the frequency of sound. Returns\n results from the frequency spectrum or time domain (waveform).<br/>\n<a href=\"#/p5.Oscillator\"><b>p5.Oscillator</b></a>: Generate Sine,\n Triangle, Square and Sawtooth waveforms. Base class of\n <a href=\"#/p5.Noise\">p5.Noise</a> and <a href=\"#/p5.Pulse\">p5.Pulse</a>.\n <br/>\n<a href=\"#/p5.Env\"><b>p5.Env</b></a>: An Envelope is a series\n of fades over time. Often used to control an object&#39;s\n output gain level as an &quot;ADSR Envelope&quot; (Attack, Decay,\n Sustain, Release). Can also modulate other parameters.<br/>\n<a href=\"#/p5.Delay\"><b>p5.Delay</b></a>: A delay effect with\n parameters for feedback, delayTime, and lowpass filter.<br/>\n<a href=\"#/p5.Filter\"><b>p5.Filter</b></a>: Filter the frequency range of a\n sound.\n<br/>\n<a href=\"#/p5.Reverb\"><b>p5.Reverb</b></a>: Add reverb to a sound by specifying\n duration and decay. <br/>\n<b><a href=\"#/p5.Convolver\">p5.Convolver</a>:</b> Extends\n<a href=\"#/p5.Reverb\">p5.Reverb</a> to simulate the sound of real\n physical spaces through convolution.<br/>\n<b><a href=\"#/p5.SoundRecorder\">p5.SoundRecorder</a></b>: Record sound for playback\n / save the .wav file.\n<b><a href=\"#/p5.Phrase\">p5.Phrase</a></b>, <b><a href=\"#/p5.Part\">p5.Part</a></b> and\n<b><a href=\"#/p5.Score\">p5.Score</a></b>: Compose musical sequences.\n<br/><br/>\np5.sound is on <a href=\"https://github.com/therewasaguy/p5.sound/\">GitHub</a>.\nDownload the latest version\n<a href=\"https://github.com/therewasaguy/p5.sound/blob/master/lib/p5.sound.js\">here</a>.</p>\n","tag":"main","itemtype":"main"}},"classes":{"p5":{"name":"p5","shortname":"p5","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"IO","submodule":"Output","namespace":"","file":"src/core/main.js","line":15,"description":"<p>This is the p5 instance constructor.</p>\n<p>A p5 instance holds all the properties and methods related to\na p5 sketch. It expects an incoming sketch closure and it can also\ntake an optional node parameter for attaching the generated p5 canvas\nto a node. The sketch closure takes the newly created p5 instance as\nits sole argument and may optionally set <a href=\"#/p5/preload\">preload()</a>, <a href=\"#/p5/setup\">setup()</a>, and/or\n<a href=\"#/p5/draw\">draw()</a> properties on it for running a sketch.</p>\n<p>A p5 sketch can run in &quot;global&quot; or &quot;instance&quot; mode:\n&quot;global&quot; - all properties and methods are attached to the window\n&quot;instance&quot; - all properties and methods are bound to this p5 object</p>\n","is_constructor":1,"params":[{"name":"sketch","description":"<p>a closure that can set optional <a href=\"#/p5/preload\">preload()</a>,\n <a href=\"#/p5/setup\">setup()</a>, and/or <a href=\"#/p5/draw\">draw()</a> properties on the\n given p5 instance</p>\n","type":"Function"},{"name":"node","description":"<p>element to attach canvas to, if a\n boolean is passed in use it as sync</p>\n","type":"HTMLElement|Boolean","optional":true},{"name":"sync","description":"<p>start synchronously (optional)</p>\n","type":"Boolean","optional":true}],"return":{"description":"a p5 instance","type":"P5"}},"p5.Color":{"name":"p5.Color","shortname":"p5.Color","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Color","submodule":"Creating & Reading","namespace":"","file":"src/color/p5.Color.js","line":16,"description":"<p>Each color stores the color mode and level maxes that applied at the\ntime of its construction. These are used to interpret the input arguments\n(at construction and later for that instance of color) and to format the\noutput e.g. when <a href=\"#/p5/saturation\">saturation()</a> is requested.</p>\n<p>Internally we store an array representing the ideal RGBA values in floating\npoint form, normalized from 0 to 1. From this we calculate the closest\nscreen color (RGBA levels from 0 to 255) and expose this to the renderer.</p>\n<p>We also cache normalized, floating point components of the color in various\nrepresentations as they are calculated. This is done to prevent repeating a\nconversion that has already been performed.</p>\n"},"p5.Element":{"name":"p5.Element","shortname":"p5.Element","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"DOM","submodule":"DOM","namespace":"","file":"src/core/p5.Element.js","line":11,"description":"<p>Base class for all elements added to a sketch, including canvas,\ngraphics buffers, and other HTML elements. Methods in blue are\nincluded in the core functionality, methods in brown are added\nwith the <a href=\"http://p5js.org/reference/#/libraries/p5.dom\">p5.dom\nlibrary</a>.\nIt is not called directly, but <a href=\"#/p5.Element\">p5.Element</a>\nobjects are created by calling <a href=\"#/p5/createCanvas\">createCanvas</a>, <a href=\"#/p5/createGraphics\">createGraphics</a>,\nor in the p5.dom library, <a href=\"#/p5/createDiv\">createDiv</a>, <a href=\"#/p5/createImg\">createImg</a>, <a href=\"#/p5/createInput\">createInput</a>, etc.</p>\n","params":[{"name":"elt","description":"<p>DOM node that is wrapped</p>\n","type":"String"},{"name":"pInst","description":"<p>pointer to p5 instance</p>\n","type":"P5","optional":true}]},"p5.Graphics":{"name":"p5.Graphics","shortname":"p5.Graphics","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Rendering","submodule":"Rendering","namespace":"","file":"src/core/p5.Graphics.js","line":12,"description":"<p>Thin wrapper around a renderer, to be used for creating a\ngraphics buffer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels. The fields and methods for this class are\nextensive, but mirror the normal drawing API for p5.</p>\n","extends":"p5.Element","params":[{"name":"w","description":"<p>width</p>\n","type":"Number"},{"name":"h","description":"<p>height</p>\n","type":"Number"},{"name":"renderer","description":"<p>the renderer to use, either P2D or WEBGL</p>\n","type":"Constant"},{"name":"pInst","description":"<p>pointer to p5 instance</p>\n","type":"P5","optional":true}]},"p5.Renderer":{"name":"p5.Renderer","shortname":"p5.Renderer","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Rendering","submodule":"Rendering","namespace":"","file":"src/core/p5.Renderer.js","line":12,"description":"<p>Main graphics and rendering context, as well as the base API\nimplementation for p5.js &quot;core&quot;. To be used as the superclass for\nRenderer2D and Renderer3D classes, respecitvely.</p>\n","is_constructor":1,"extends":"p5.Element","params":[{"name":"elt","description":"<p>DOM node that is wrapped</p>\n","type":"String"},{"name":"pInst","description":"<p>pointer to p5 instance</p>\n","type":"P5","optional":true},{"name":"isMainCanvas","description":"<p>whether we&#39;re using it as main canvas</p>\n","type":"Boolean","optional":true}]},"p5.TypedDict":{"name":"p5.TypedDict","shortname":"p5.TypedDict","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Data","submodule":"Dictionary","namespace":"","file":"src/data/p5.TypedDict.js","line":84,"description":"<p>Base class for all p5.Dictionary types. Specifically\n typed Dictionary classes inherit from this class.</p>\n"},"p5.StringDict":{"name":"p5.StringDict","shortname":"p5.StringDict","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Data","submodule":"Dictionary","namespace":"","file":"src/data/p5.TypedDict.js","line":391,"description":"<p>A simple Dictionary class for Strings.</p>\n","extends":"p5.TypedDict"},"p5.NumberDict":{"name":"p5.NumberDict","shortname":"p5.NumberDict","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Data","submodule":"Dictionary","namespace":"","file":"src/data/p5.TypedDict.js","line":410,"description":"<p>A simple Dictionary class for Numbers.</p>\n","extends":"p5.TypedDict"},"p5.Image":{"name":"p5.Image","shortname":"p5.Image","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Image","submodule":"Image","namespace":"","file":"src/image/p5.Image.js","line":23,"description":"<p>Creates a new <a href=\"#/p5.Image\">p5.Image</a>. A <a href=\"#/p5.Image\">p5.Image</a> is a canvas backed representation of an\nimage.\n<br><br>\np5 can display .gif, .jpg and .png images. Images may be displayed\nin 2D and 3D space. Before an image is used, it must be loaded with the\n<a href=\"#/p5/loadImage\">loadImage()</a> function. The <a href=\"#/p5.Image\">p5.Image</a> class contains fields for the width and\nheight of the image, as well as an array called <a href=\"#/p5.Image/pixels\">pixels[]</a> that contains the\nvalues for every pixel in the image.\n<br><br>\nThe methods described below allow easy access to the image&#39;s pixels and\nalpha channel and simplify the process of compositing.\n<br><br>\nBefore using the <a href=\"#/p5.Image/pixels\">pixels[]</a> array, be sure to use the <a href=\"#/p5.Image/loadPixels\">loadPixels()</a> method on\nthe image to make sure that the pixel data is properly loaded.</p>\n","example":["\n<div><code>\nfunction setup() {\n var img = createImage(100, 100); // same as new p5.Image(100, 100);\n img.loadPixels();\n createCanvas(100, 100);\n background(0);\n\n // helper for writing color to array\n function writeColor(image, x, y, red, green, blue, alpha) {\n var index = (x + y * width) * 4;\n image.pixels[index] = red;\n image.pixels[index + 1] = green;\n image.pixels[index + 2] = blue;\n image.pixels[index + 3] = alpha;\n }\n\n var x, y;\n // fill with random colors\n for (y = 0; y < img.height; y++) {\n for (x = 0; x < img.width; x++) {\n var red = random(255);\n var green = random(255);\n var blue = random(255);\n var alpha = 255;\n writeColor(img, x, y, red, green, blue, alpha);\n }\n }\n\n // draw a red line\n y = 0;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 255, 0, 0, 255);\n }\n\n // draw a green line\n y = img.height - 1;\n for (x = 0; x < img.width; x++) {\n writeColor(img, x, y, 0, 255, 0, 255);\n }\n\n img.updatePixels();\n image(img, 0, 0);\n}\n</code></div>"],"params":[{"name":"width","description":"","type":"Number"},{"name":"height","description":"","type":"Number"}]},"p5.PrintWriter":{"name":"p5.PrintWriter","shortname":"p5.PrintWriter","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"IO","submodule":"Output","namespace":"","file":"src/io/files.js","line":1242,"params":[{"name":"filename","description":"","type":"String"},{"name":"extension","description":"","type":"String","optional":true}]},"p5.Table":{"name":"p5.Table","shortname":"p5.Table","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"IO","submodule":"Table","namespace":"","file":"src/io/p5.Table.js","line":35,"description":"<p><a href=\"#/p5.Table\">Table</a> objects store data with multiple rows and columns, much\nlike in a traditional spreadsheet. Tables can be generated from\nscratch, dynamically, or using data from an existing file.</p>\n","is_constructor":1,"params":[{"name":"rows","description":"<p>An array of p5.TableRow objects</p>\n","type":"p5.TableRow[]","optional":true}]},"p5.TableRow":{"name":"p5.TableRow","shortname":"p5.TableRow","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"IO","submodule":"Table","namespace":"","file":"src/io/p5.TableRow.js","line":11,"description":"<p>A TableRow object represents a single row of data values,\nstored in columns, from a table.</p>\n<p>A Table Row contains both an ordered array, and an unordered\nJSON object.</p>\n","is_constructor":1,"params":[{"name":"str","description":"<p>optional: populate the row with a\n string of values, separated by the\n separator</p>\n","type":"String","optional":true},{"name":"separator","description":"<p>comma separated values (csv) by default</p>\n","type":"String","optional":true}]},"p5.XML":{"name":"p5.XML","shortname":"p5.XML","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"IO","submodule":"XML","namespace":"","file":"src/io/p5.XML.js","line":11,"description":"<p>XML is a representation of an XML object, able to parse XML code. Use\n<a href=\"#/p5/loadXML\">loadXML()</a> to load external XML files and create XML objects.</p>\n","is_constructor":1,"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var children = xml.getChildren('animal');\n\n for (var i = 0; i < children.length; i++) {\n var id = children[i].getNum('id');\n var coloring = children[i].getString('species');\n var name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n</code></div>"],"alt":"no image displayed"},"p5.Vector":{"name":"p5.Vector","shortname":"p5.Vector","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Math","submodule":"Math","namespace":"","file":"src/math/p5.Vector.js","line":12,"description":"<p>A class to describe a two or three dimensional vector, specifically\na Euclidean (also known as geometric) vector. A vector is an entity\nthat has both magnitude and direction. The datatype, however, stores\nthe components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude\nand direction can be accessed via the methods <a href=\"#/p5/mag\">mag()</a> and <a href=\"#/p5/heading\">heading()</a>.\n<br><br>\nIn many of the p5.js examples, you will see <a href=\"#/p5.Vector\">p5.Vector</a> used to describe a\nposition, velocity, or acceleration. For example, if you consider a rectangle\nmoving across the screen, at any given instant it has a position (a vector\nthat points from the origin to its location), a velocity (the rate at which\nthe object&#39;s position changes per time unit, expressed as a vector), and\nacceleration (the rate at which the object&#39;s velocity changes per time\nunit, expressed as a vector).\n<br><br>\nSince vectors represent groupings of values, we cannot simply use\ntraditional addition/multiplication/etc. Instead, we&#39;ll need to do some\n&quot;vector&quot; math, which is made easy by the methods inside the <a href=\"#/p5.Vector\">p5.Vector</a> class.</p>\n","params":[{"name":"x","description":"<p>x component of the vector</p>\n","type":"Number","optional":true},{"name":"y","description":"<p>y component of the vector</p>\n","type":"Number","optional":true},{"name":"z","description":"<p>z component of the vector</p>\n","type":"Number","optional":true}],"example":["\n<div>\n<code>\nvar v1 = createVector(40, 50);\nvar v2 = createVector(40, 50);\n\nellipse(v1.x, v1.y, 50, 50);\nellipse(v2.x, v2.y, 50, 50);\nv1.add(v2);\nellipse(v1.x, v1.y, 50, 50);\n</code>\n</div>"],"alt":"2 white ellipses. One center-left the other bottom right and off canvas"},"p5.Font":{"name":"p5.Font","shortname":"p5.Font","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Typography","submodule":"Font","namespace":"","file":"src/typography/p5.Font.js","line":21,"description":"<p>Base class for font handling</p>\n","params":[{"name":"pInst","description":"<p>pointer to p5 instance</p>\n","type":"P5","optional":true}]},"p5.Camera":{"name":"p5.Camera","shortname":"p5.Camera","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Lights, Camera","submodule":"Camera","namespace":"","file":"src/webgl/p5.Camera.js","line":209,"description":"<p>This class describes a camera for use in p5&#39;s\n<a href=\"https://github.com/processing/p5.js/wiki/Getting-started-with-WebGL-in-p5\">\nWebGL mode</a>. It contains camera position, orientation, and projection\ninformation necessary for rendering a 3D scene.</p>\n<p>New p5.Camera objects can be made through the\n<a href=\"#/p5/createCamera\">createCamera()</a> function and controlled through\nthe methods described below. A camera created in this way will use a default\nposition in the scene and a default perspective projection until these\nproperties are changed through the various methods available. It is possible\nto create multiple cameras, in which case the current camera\ncan be set through the <a href=\"#/p5/setCamera\">setCamera()</a> method.</p>\n<p>Note:\nThe methods below operate in two coordinate systems: the &#39;world&#39; coordinate\nsystem describe positions in terms of their relationship to the origin along\nthe X, Y and Z axes whereas the camera&#39;s &#39;local&#39; coordinate system\ndescribes positions from the camera&#39;s point of view: left-right, up-down,\nand forward-backward. The <a href=\"#/p5.Camera/move\">move()</a> method,\nfor instance, moves the camera along its own axes, whereas the\n<a href=\"#/p5.Camera/setPosition\">setPosition()</a>\nmethod sets the camera&#39;s position in world-space.</p>\n","params":[{"name":"rendererGL","description":"<p>instance of WebGL renderer</p>\n","type":"RendererGL"}],"example":["\n<div>\n<code>\nvar cam;\nvar delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n</code>\n</div>"],"alt":"camera view pans left and right across a series of rotating 3D boxes."},"p5.Geometry":{"name":"p5.Geometry","shortname":"p5.Geometry","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Lights, Camera","namespace":"","file":"src/webgl/p5.Geometry.js","line":6,"description":"<p>p5 Geometry class</p>\n","is_constructor":1,"params":[{"name":"detailX","description":"<p>number of vertices on horizontal surface</p>\n","type":"Integer","optional":true},{"name":"detailY","description":"<p>number of vertices on horizontal surface</p>\n","type":"Integer","optional":true},{"name":"callback","description":"<p>function to call upon object instantiation.</p>\n","type":"Function","optional":true}]},"p5.Shader":{"name":"p5.Shader","shortname":"p5.Shader","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"Lights, Camera","submodule":"Shaders","namespace":"","file":"src/webgl/p5.Shader.js","line":13,"description":"<p>Shader class for WEBGL Mode</p>\n","params":[{"name":"renderer","description":"<p>an instance of p5.RendererGL that\nwill provide the GL context for this new p5.Shader</p>\n","type":"p5.RendererGL"},{"name":"vertSrc","description":"<p>source code for the vertex shader (as a string)</p>\n","type":"String"},{"name":"fragSrc","description":"<p>source code for the fragment shader (as a string)</p>\n","type":"String"}]},"p5.MediaElement":{"name":"p5.MediaElement","shortname":"p5.MediaElement","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.dom","submodule":"p5.dom","namespace":"","file":"lib/addons/p5.dom.js","line":1975,"description":"<p>Extends <a href=\"#/p5.Element\">p5.Element</a> to handle audio and video. In addition to the methods\nof <a href=\"#/p5.Element\">p5.Element</a>, it also contains methods for controlling media. It is not\ncalled directly, but <a href=\"#/p5.MediaElement\">p5.MediaElement</a>s are created by calling <a href=\"#/p5/createVideo\">createVideo</a>,\n<a href=\"#/p5/createAudio\">createAudio</a>, and <a href=\"#/p5/createCapture\">createCapture</a>.</p>\n","is_constructor":1,"params":[{"name":"elt","description":"<p>DOM node that is wrapped</p>\n","type":"String"}]},"p5.File":{"name":"p5.File","shortname":"p5.File","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.dom","submodule":"p5.dom","namespace":"","file":"lib/addons/p5.dom.js","line":3083,"description":"<p>Base class for a file\nUsing this for createFileInput</p>\n","is_constructor":1,"params":[{"name":"file","description":"<p>File that is wrapped</p>\n","type":"File"}]},"p5.sound":{"name":"p5.sound","shortname":"p5.sound","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":""},"p5.SoundFile":{"name":"p5.SoundFile","shortname":"p5.SoundFile","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":808,"description":"<p>SoundFile object with a path to a file.</p>\n\n<p>The p5.SoundFile may not be available immediately because\nit loads the file information asynchronously.</p>\n\n<p>To do something with the sound as soon as it loads\npass the name of a function as the second parameter.</p>\n\n<p>Only one file path is required. However, audio file formats\n(i.e. mp3, ogg, wav and m4a/aac) are not supported by all\nweb browsers. If you want to ensure compatability, instead of a single\nfile path, you may include an Array of filepaths, and the browser will\nchoose a format that works.</p>","is_constructor":1,"params":[{"name":"path","description":"<p>path to a sound file (String). Optionally,\n you may include multiple file formats in\n an array. Alternately, accepts an object\n from the HTML5 File API, or a p5.File.</p>\n","type":"String|Array"},{"name":"successCallback","description":"<p>Name of a function to call once file loads</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>Name of a function to call if file fails to\n load. This function will receive an error or\n XMLHttpRequest object with information\n about what went wrong.</p>\n","type":"Function","optional":true},{"name":"whileLoadingCallback","description":"<p>Name of a function to call while file\n is loading. That function will\n receive progress of the request to\n load the sound file\n (between 0 and 1) as its first\n parameter. This progress\n does not account for the additional\n time needed to decode the audio data.</p>\n","type":"Function","optional":true}],"example":["\n<div><code>\n\nfunction preload() {\n soundFormats('mp3', 'ogg');\n mySound = loadSound('assets/doorbell.mp3');\n}\n\nfunction setup() {\n mySound.setVolume(0.1);\n mySound.play();\n}\n\n </code></div>"]},"p5.Amplitude":{"name":"p5.Amplitude","shortname":"p5.Amplitude","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":2234,"description":"<p>Amplitude measures volume between 0.0 and 1.0.\nListens to all p5sound by default, or use setInput()\nto listen to a specific sound source. Accepts an optional\nsmoothing value, which defaults to 0.</p>\n","is_constructor":1,"params":[{"name":"smoothing","description":"<p>between 0.0 and .999 to smooth\n amplitude readings (defaults to 0)</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar sound, amplitude, cnv;\n\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\nfunction setup() {\n cnv = createCanvas(100,100);\n amplitude = new p5.Amplitude();\n\n // start / stop the sound when canvas is clicked\n cnv.mouseClicked(function() {\n if (sound.isPlaying() ){\n sound.stop();\n } else {\n sound.play();\n }\n });\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\n\n</code></div>"]},"p5.FFT":{"name":"p5.FFT","shortname":"p5.FFT","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":2513,"description":"<p>FFT (Fast Fourier Transform) is an analysis algorithm that\nisolates individual\n<a href=\"https://en.wikipedia.org/wiki/Audio_frequency\">\naudio frequencies</a> within a waveform.</p>\n\n<p>Once instantiated, a p5.FFT object can return an array based on\ntwo types of analyses: <br> • <code>FFT.waveform()</code> computes\namplitude values along the time domain. The array indices correspond\nto samples across a brief moment in time. Each value represents\namplitude of the waveform at that sample of time.<br>\n• <code>FFT.analyze() </code> computes amplitude values along the\nfrequency domain. The array indices correspond to frequencies (i.e.\npitches), from the lowest to the highest that humans can hear. Each\nvalue represents amplitude at that slice of the frequency spectrum.\nUse with <code>getEnergy()</code> to measure amplitude at specific\nfrequencies, or within a range of frequencies. </p>\n\n<p>FFT analyzes a very short snapshot of sound called a sample\nbuffer. It returns an array of amplitude measurements, referred\nto as <code>bins</code>. The array is 1024 bins long by default.\nYou can change the bin array length, but it must be a power of 2\nbetween 16 and 1024 in order for the FFT algorithm to function\ncorrectly. The actual size of the FFT buffer is twice the\nnumber of bins, so given a standard sample rate, the buffer is\n2048/44100 seconds long.</p>","is_constructor":1,"params":[{"name":"smoothing","description":"<p>Smooth results of Freq Spectrum.\n 0.0 &lt; smoothing &lt; 1.0.\n Defaults to 0.8.</p>\n","type":"Number","optional":true},{"name":"bins","description":"<p>Length of resulting array.\n Must be a power of two between\n 16 and 1024. Defaults to 1024.</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nfunction preload(){\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup(){\n var cnv = createCanvas(100,100);\n cnv.mouseClicked(togglePlay);\n fft = new p5.FFT();\n sound.amp(0.2);\n}\n\nfunction draw(){\n background(0);\n\n var spectrum = fft.analyze();\n noStroke();\n fill(0,255,0); // spectrum is green\n for (var i = 0; i< spectrum.length; i++){\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h )\n }\n\n var waveform = fft.waveform();\n noFill();\n beginShape();\n stroke(255,0,0); // waveform is red\n strokeWeight(1);\n for (var i = 0; i< waveform.length; i++){\n var x = map(i, 0, waveform.length, 0, width);\n var y = map( waveform[i], -1, 1, 0, height);\n vertex(x,y);\n }\n endShape();\n\n text('click to play/pause', 4, 10);\n}\n\n// fade sound if mouse is over canvas\nfunction togglePlay() {\n if (sound.isPlaying()) {\n sound.pause();\n } else {\n sound.loop();\n }\n}\n</code></div>"]},"p5.Signal":{"name":"p5.Signal","shortname":"p5.Signal","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":4916,"description":"<p>p5.Signal is a constant audio-rate signal used by p5.Oscillator\nand p5.Envelope for modulation math.</p>\n\n<p>This is necessary because Web Audio is processed on a seprate clock.\nFor example, the p5 draw loop runs about 60 times per second. But\nthe audio clock must process samples 44100 times per second. If we\nwant to add a value to each of those samples, we can&#39;t do it in the\ndraw loop, but we can do it by adding a constant-rate audio signal.&lt;/p.\n\n<p>This class mostly functions behind the scenes in p5.sound, and returns\na Tone.Signal from the Tone.js library by Yotam Mann.\nIf you want to work directly with audio signals for modular\nsynthesis, check out\n<a href='http://bit.ly/1oIoEng' target=_'blank'>tone.js.</a></p>","is_constructor":1,"return":{"description":"A Signal object from the Tone.js library","type":"Tone.Signal"},"example":["\n<div><code>\nfunction setup() {\n carrier = new p5.Oscillator('sine');\n carrier.amp(1); // set amplitude\n carrier.freq(220); // set frequency\n carrier.start(); // start oscillating\n\n modulator = new p5.Oscillator('sawtooth');\n modulator.disconnect();\n modulator.amp(1);\n modulator.freq(4);\n modulator.start();\n\n // Modulator's default amplitude range is -1 to 1.\n // Multiply it by -200, so the range is -200 to 200\n // then add 220 so the range is 20 to 420\n carrier.freq( modulator.mult(-200).add(220) );\n}\n</code></div>"]},"p5.Oscillator":{"name":"p5.Oscillator","shortname":"p5.Oscillator","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":5062,"description":"<p>Creates a signal that oscillates between -1.0 and 1.0.\nBy default, the oscillation takes the form of a sinusoidal\nshape (&#39;sine&#39;). Additional types include &#39;triangle&#39;,\n&#39;sawtooth&#39; and &#39;square&#39;. The frequency defaults to\n440 oscillations per second (440Hz, equal to the pitch of an\n&#39;A&#39; note).</p>\n\n<p>Set the type of oscillation with setType(), or by instantiating a\nspecific oscillator: <a href=\"/reference/#/p5.SinOsc\">p5.SinOsc</a>, <a\nhref=\"/reference/#/p5.TriOsc\">p5.TriOsc</a>, <a\nhref=\"/reference/#/p5.SqrOsc\">p5.SqrOsc</a>, or <a\nhref=\"/reference/#/p5.SawOsc\">p5.SawOsc</a>.\n</p>","is_constructor":1,"params":[{"name":"freq","description":"<p>frequency defaults to 440Hz</p>\n","type":"Number","optional":true},{"name":"type","description":"<p>type of oscillator. Options:\n &#39;sine&#39; (default), &#39;triangle&#39;,\n &#39;sawtooth&#39;, &#39;square&#39;</p>\n","type":"String","optional":true}],"example":["\n<div><code>\nvar osc;\nvar playing = false;\n\nfunction setup() {\n backgroundColor = color(255,0,255);\n textAlign(CENTER);\n\n osc = new p5.Oscillator();\n osc.setType('sine');\n osc.freq(240);\n osc.amp(0);\n osc.start();\n}\n\nfunction draw() {\n background(backgroundColor)\n text('click to play', width/2, height/2);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {\n if (!playing) {\n // ramp amplitude to 0.5 over 0.05 seconds\n osc.amp(0.5, 0.05);\n playing = true;\n backgroundColor = color(0,255,255);\n } else {\n // ramp amplitude to 0 over 0.5 seconds\n osc.amp(0, 0.5);\n playing = false;\n backgroundColor = color(255,0,255);\n }\n }\n}\n</code> </div>"]},"p5.SinOsc":{"name":"p5.SinOsc","shortname":"p5.SinOsc","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":5503,"description":"<p>Constructor: <code>new p5.SinOsc()</code>.\nThis creates a Sine Wave Oscillator and is\nequivalent to <code> new p5.Oscillator(&#39;sine&#39;)\n</code> or creating a p5.Oscillator and then calling\nits method <code>setType(&#39;sine&#39;)</code>.\nSee p5.Oscillator for methods.</p>\n","is_constructor":1,"extends":"p5.Oscillator","params":[{"name":"freq","description":"<p>Set the frequency</p>\n","type":"Number","optional":true}]},"p5.TriOsc":{"name":"p5.TriOsc","shortname":"p5.TriOsc","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":5520,"description":"<p>Constructor: <code>new p5.TriOsc()</code>.\nThis creates a Triangle Wave Oscillator and is\nequivalent to <code>new p5.Oscillator(&#39;triangle&#39;)\n</code> or creating a p5.Oscillator and then calling\nits method <code>setType(&#39;triangle&#39;)</code>.\nSee p5.Oscillator for methods.</p>\n","is_constructor":1,"extends":"p5.Oscillator","params":[{"name":"freq","description":"<p>Set the frequency</p>\n","type":"Number","optional":true}]},"p5.SawOsc":{"name":"p5.SawOsc","shortname":"p5.SawOsc","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":5537,"description":"<p>Constructor: <code>new p5.SawOsc()</code>.\nThis creates a SawTooth Wave Oscillator and is\nequivalent to <code> new p5.Oscillator(&#39;sawtooth&#39;)\n</code> or creating a p5.Oscillator and then calling\nits method <code>setType(&#39;sawtooth&#39;)</code>.\nSee p5.Oscillator for methods.</p>\n","is_constructor":1,"extends":"p5.Oscillator","params":[{"name":"freq","description":"<p>Set the frequency</p>\n","type":"Number","optional":true}]},"p5.SqrOsc":{"name":"p5.SqrOsc","shortname":"p5.SqrOsc","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":5554,"description":"<p>Constructor: <code>new p5.SqrOsc()</code>.\nThis creates a Square Wave Oscillator and is\nequivalent to <code> new p5.Oscillator(&#39;square&#39;)\n</code> or creating a p5.Oscillator and then calling\nits method <code>setType(&#39;square&#39;)</code>.\nSee p5.Oscillator for methods.</p>\n","is_constructor":1,"extends":"p5.Oscillator","params":[{"name":"freq","description":"<p>Set the frequency</p>\n","type":"Number","optional":true}]},"p5.Envelope":{"name":"p5.Envelope","shortname":"p5.Envelope","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":6011,"description":"<p>Envelopes are pre-defined amplitude distribution over time.\nTypically, envelopes are used to control the output volume\nof an object, a series of fades referred to as Attack, Decay,\nSustain and Release (\n<a href=\"https://upload.wikimedia.org/wikipedia/commons/e/ea/ADSR_parameter.svg\">ADSR</a>\n). Envelopes can also control other Web Audio Parameters—for example, a p5.Envelope can\ncontrol an Oscillator&#39;s frequency like this: <code>osc.freq(env)</code>.</p>\n<p>Use <code><a href=\"#/p5.Envelope/setRange\">setRange</a></code> to change the attack/release level.\nUse <code><a href=\"#/p5.Envelope/setADSR\">setADSR</a></code> to change attackTime, decayTime, sustainPercent and releaseTime.</p>\n<p>Use the <code><a href=\"#/p5.Envelope/play\">play</a></code> method to play the entire envelope,\nthe <code><a href=\"#/p5.Envelope/ramp\">ramp</a></code> method for a pingable trigger,\nor <code><a href=\"#/p5.Envelope/triggerAttack\">triggerAttack</a></code>/\n<code><a href=\"#/p5.Envelope/triggerRelease\">triggerRelease</a></code> to trigger noteOn/noteOff.</p>","is_constructor":1,"example":["\n<div><code>\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n</code></div>"]},"p5.Pulse":{"name":"p5.Pulse","shortname":"p5.Pulse","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":6809,"description":"<p>Creates a Pulse object, an oscillator that implements\nPulse Width Modulation.\nThe pulse is created with two oscillators.\nAccepts a parameter for frequency, and to set the\nwidth between the pulses. See <a href=\"\nhttp://p5js.org/reference/#/p5.Oscillator\">\n<code>p5.Oscillator</code> for a full list of methods.</p>\n","extends":"p5.Oscillator","is_constructor":1,"params":[{"name":"freq","description":"<p>Frequency in oscillations per second (Hz)</p>\n","type":"Number","optional":true},{"name":"w","description":"<p>Width between the pulses (0 to 1.0,\n defaults to 0)</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar pulse;\nfunction setup() {\n background(0);\n\n // Create and start the pulse wave oscillator\n pulse = new p5.Pulse();\n pulse.amp(0.5);\n pulse.freq(220);\n pulse.start();\n}\n\nfunction draw() {\n var w = map(mouseX, 0, width, 0, 1);\n w = constrain(w, 0, 1);\n pulse.width(w)\n}\n</code></div>"]},"p5.Noise":{"name":"p5.Noise","shortname":"p5.Noise","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":6988,"description":"<p>Noise is a type of oscillator that generates a buffer with random values.</p>\n","extends":"p5.Oscillator","is_constructor":1,"params":[{"name":"type","description":"<p>Type of noise can be &#39;white&#39; (default),\n &#39;brown&#39; or &#39;pink&#39;.</p>\n","type":"String"}]},"p5.AudioIn":{"name":"p5.AudioIn","shortname":"p5.AudioIn","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":7136,"description":"<p>Get audio from an input, i.e. your computer&#39;s microphone.</p>\n\n<p>Turn the mic on/off with the start() and stop() methods. When the mic\nis on, its volume can be measured with getLevel or by connecting an\nFFT object.</p>\n\n<p>If you want to hear the AudioIn, use the .connect() method.\nAudioIn does not connect to p5.sound output by default to prevent\nfeedback.</p>\n\n<p><em>Note: This uses the <a href=\"http://caniuse.com/stream\">getUserMedia/\nStream</a> API, which is not supported by certain browsers. Access in Chrome browser\nis limited to localhost and https, but access over http may be limited.</em></p>","is_constructor":1,"params":[{"name":"errorCallback","description":"<p>A function to call if there is an error\n accessing the AudioIn. For example,\n Safari and iOS devices do not\n currently allow microphone access.</p>\n","type":"Function","optional":true}],"example":["\n<div><code>\nvar mic;\nfunction setup(){\n mic = new p5.AudioIn()\n mic.start();\n}\nfunction draw(){\n background(0);\n micLevel = mic.getLevel();\n ellipse(width/2, constrain(height-micLevel*height*5, 0, height), 10, 10);\n}\n</code></div>"]},"p5.Effect":{"name":"p5.Effect","shortname":"p5.Effect","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":8033,"description":"<p>Effect is a base class for audio effects in p5. <br>\nThis module handles the nodes and methods that are \ncommon and useful for current and future effects.</p>\n<p>This class is extended by <a href=\"/reference/#/p5.Distortion\">p5.Distortion</a>, \n<a href=\"/reference/#/p5.Compressor\">p5.Compressor</a>,\n<a href=\"/reference/#/p5.Delay\">p5.Delay</a>, \n<a href=\"/reference/#/p5.Filter\">p5.Filter</a>, \n<a href=\"/reference/#/p5.Reverb\">p5.Reverb</a>.</p>\n","is_constructor":1,"params":[{"name":"ac","description":"<p>Reference to the audio context of the p5 object</p>\n","type":"Object","optional":true},{"name":"input","description":"<p>Gain Node effect wrapper</p>\n","type":"AudioNode","optional":true},{"name":"output","description":"<p>Gain Node effect wrapper</p>\n","type":"AudioNode","optional":true},{"name":"_drywet","description":"<p>Tone.JS CrossFade node (defaults to value: 1)</p>\n","type":"Object","optional":true},{"name":"wet","description":"<p>Effects that extend this class should connect\n to the wet signal to this gain node, so that dry and wet \n signals are mixed properly.</p>\n","type":"AudioNode","optional":true}]},"p5.Filter":{"name":"p5.Filter","shortname":"p5.Filter","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":8175,"description":"<p><p>A p5.Filter uses a Web Audio Biquad Filter to filter\nthe frequency response of an input source. Subclasses\ninclude:</p></p>\n<ul>\n<li><a href=\"/reference/#/p5.LowPass\"><code>p5.LowPass</code></a>:\nAllows frequencies below the cutoff frequency to pass through,\nand attenuates frequencies above the cutoff.<br/></li>\n<li><a href=\"/reference/#/p5.HighPass\"><code>p5.HighPass</code></a>:\nThe opposite of a lowpass filter. <br/></li>\n<li><a href=\"/reference/#/p5.BandPass\"><code>p5.BandPass</code></a>:\nAllows a range of frequencies to pass through and attenuates\nthe frequencies below and above this frequency range.<br/></li>\n</ul>\n<p>The <code>.res()</code> method controls either width of the\nbandpass, or resonance of the low/highpass cutoff frequency.</p>\n<p>This class extends <a href = \"/reference/#/p5.Effect\">p5.Effect</a>.<br>Methods <a href = \"/reference/#/p5.Effect/amp\">amp()</a>, <a href = \"/reference/#/p5.Effect/chain\">chain()</a>, \n<a href = \"/reference/#/p5.Effect/drywet\">drywet()</a>, <a href = \"/reference/#/p5.Effect/connect\">connect()</a>, and \n<a href = \"/reference/#/p5.Effect/disconnect\">disconnect()</a> are available.</p>\n","extends":"p5.Effect","is_constructor":1,"params":[{"name":"type","description":"<p>&#39;lowpass&#39; (default), &#39;highpass&#39;, &#39;bandpass&#39;</p>\n","type":"String","optional":true}],"example":["\n<div><code>\nvar fft, noise, filter;\n\nfunction setup() {\n fill(255, 40, 255);\n\n filter = new p5.BandPass();\n\n noise = new p5.Noise();\n // disconnect unfiltered noise,\n // and connect to filter\n noise.disconnect();\n noise.connect(filter);\n noise.start();\n\n fft = new p5.FFT();\n}\n\nfunction draw() {\n background(30);\n\n // set the BandPass frequency based on mouseX\n var freq = map(mouseX, 0, width, 20, 10000);\n filter.freq(freq);\n // give the filter a narrow band (lower res = wider bandpass)\n filter.res(50);\n\n // draw filtered spectrum\n var spectrum = fft.analyze();\n noStroke();\n for (var i = 0; i < spectrum.length; i++) {\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width/spectrum.length, h);\n }\n\n isMouseOverCanvas();\n}\n\nfunction isMouseOverCanvas() {\n var mX = mouseX, mY = mouseY;\n if (mX > 0 && mX < width && mY < height && mY > 0) {\n noise.amp(0.5, 0.2);\n } else {\n noise.amp(0, 0.2);\n }\n}\n</code></div>"]},"p5.LowPass":{"name":"p5.LowPass","shortname":"p5.LowPass","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":8407,"description":"<p>Constructor: <code>new p5.LowPass()</code> Filter.\nThis is the same as creating a p5.Filter and then calling\nits method <code>setType(&#39;lowpass&#39;)</code>.\nSee p5.Filter for methods.</p>\n","is_constructor":1,"extends":"p5.Filter"},"p5.HighPass":{"name":"p5.HighPass","shortname":"p5.HighPass","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":8421,"description":"<p>Constructor: <code>new p5.HighPass()</code> Filter.\nThis is the same as creating a p5.Filter and then calling\nits method <code>setType(&#39;highpass&#39;)</code>.\nSee p5.Filter for methods.</p>\n","is_constructor":1,"extends":"p5.Filter"},"p5.BandPass":{"name":"p5.BandPass","shortname":"p5.BandPass","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":8435,"description":"<p>Constructor: <code>new p5.BandPass()</code> Filter.\nThis is the same as creating a p5.Filter and then calling\nits method <code>setType(&#39;bandpass&#39;)</code>.\nSee p5.Filter for methods.</p>\n","is_constructor":1,"extends":"p5.Filter"},"p5.EQ":{"name":"p5.EQ","shortname":"p5.EQ","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":8506,"description":"<p>p5.EQ is an audio effect that performs the function of a multiband\naudio equalizer. Equalization is used to adjust the balance of\nfrequency compoenents of an audio signal. This process is commonly used\nin sound production and recording to change the waveform before it reaches\na sound output device. EQ can also be used as an audio effect to create\ninteresting distortions by filtering out parts of the spectrum. p5.EQ is\nbuilt using a chain of Web Audio Biquad Filter Nodes and can be\ninstantiated with 3 or 8 bands. Bands can be added or removed from\nthe EQ by directly modifying p5.EQ.bands (the array that stores filters).</p>\n<p>This class extends <a href = \"/reference/#/p5.Effect\">p5.Effect</a>.\nMethods <a href = \"/reference/#/p5.Effect/amp\">amp()</a>, <a href = \"/reference/#/p5.Effect/chain\">chain()</a>,\n<a href = \"/reference/#/p5.Effect/drywet\">drywet()</a>, <a href = \"/reference/#/p5.Effect/connect\">connect()</a>, and\n<a href = \"/reference/#/p5.Effect/disconnect\">disconnect()</a> are available.</p>\n","is_constructor":1,"extends":"p5.Effect","params":[{"name":"_eqsize","description":"<p>Constructor will accept 3 or 8, defaults to 3</p>\n","type":"Number","optional":true}],"return":{"description":"p5.EQ object","type":"Object"},"example":["\n<div><code>\nvar eq;\nvar band_names;\nvar band_index;\n\nvar soundFile, play;\n\nfunction preload() {\n soundFormats('mp3', 'ogg');\n soundFile = loadSound('assets/beat');\n}\n\nfunction setup() {\n eq = new p5.EQ(3);\n soundFile.disconnect();\n eq.process(soundFile);\n\n band_names = ['lows','mids','highs'];\n band_index = 0;\n play = false;\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(30);\n noStroke();\n fill(255);\n text('click to kill',50,25);\n\n fill(255, 40, 255);\n textSize(26);\n text(band_names[band_index],50,55);\n\n fill(255);\n textSize(9);\n text('space = play/pause',50,80);\n}\n\n//If mouse is over canvas, cycle to the next band and kill the frequency\nfunction mouseClicked() {\n for (var i = 0; i < eq.bands.length; i++) {\n eq.bands[i].gain(0);\n }\n eq.bands[band_index].gain(-40);\n if (mouseX > 0 && mouseX < width && mouseY < height && mouseY > 0) {\n band_index === 2 ? band_index = 0 : band_index++;\n }\n}\n\n//use space bar to trigger play / pause\nfunction keyPressed() {\n if (key===' ') {\n play = !play\n play ? soundFile.loop() : soundFile.pause();\n }\n}\n</code></div>"]},"p5.Panner3D":{"name":"p5.Panner3D","shortname":"p5.Panner3D","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":8698,"description":"<p>Panner3D is based on the <a title=\"Web Audio Panner docs\" href=\n\"https://developer.mozilla.org/en-US/docs/Web/API/PannerNode\">\nWeb Audio Spatial Panner Node</a>.\nThis panner is a spatial processing node that allows audio to be positioned\nand oriented in 3D space.</p>\n<p>The position is relative to an <a title=\"Web Audio Listener docs\" href=\n\"https://developer.mozilla.org/en-US/docs/Web/API/AudioListener\">\nAudio Context Listener</a>, which can be accessed\nby <code>p5.soundOut.audiocontext.listener</code></p>\n","is_constructor":1},"p5.Delay":{"name":"p5.Delay","shortname":"p5.Delay","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":9149,"description":"<p>Delay is an echo effect. It processes an existing sound source,\nand outputs a delayed version of that sound. The p5.Delay can\nproduce different effects depending on the delayTime, feedback,\nfilter, and type. In the example below, a feedback of 0.5 (the\ndefaul value) will produce a looping delay that decreases in\nvolume by 50% each repeat. A filter will cut out the high\nfrequencies so that the delay does not sound as piercing as the\noriginal source.</p>\n<p>This class extends <a href = \"/reference/#/p5.Effect\">p5.Effect</a>.<br>Methods <a href = \"/reference/#/p5.Effect/amp\">amp()</a>, <a href = \"/reference/#/p5.Effect/chain\">chain()</a>, \n<a href = \"/reference/#/p5.Effect/drywet\">drywet()</a>, <a href = \"/reference/#/p5.Effect/connect\">connect()</a>, and \n<a href = \"/reference/#/p5.Effect/disconnect\">disconnect()</a> are available.</p>\n","extends":"p5.Effect","is_constructor":1,"example":["\n<div><code>\nvar noise, env, delay;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n noise = new p5.Noise('brown');\n noise.amp(0);\n noise.start();\n\n delay = new p5.Delay();\n\n // delay.process() accepts 4 parameters:\n // source, delayTime, feedback, filter frequency\n // play with these numbers!!\n delay.process(noise, .12, .7, 2300);\n\n // play the noise with an envelope,\n // a series of fades ( time / value pairs )\n env = new p5.Envelope(.01, 0.2, .2, .1);\n}\n\n// mouseClick triggers envelope\nfunction mouseClicked() {\n // is mouse over canvas?\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n env.play(noise);\n }\n}\n</code></div>"]},"p5.Reverb":{"name":"p5.Reverb","shortname":"p5.Reverb","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":9426,"description":"<p>Reverb adds depth to a sound through a large number of decaying\nechoes. It creates the perception that sound is occurring in a\nphysical space. The p5.Reverb has paramters for Time (how long does the\nreverb last) and decayRate (how much the sound decays with each echo)\nthat can be set with the .set() or .process() methods. The p5.Convolver\nextends p5.Reverb allowing you to recreate the sound of actual physical\nspaces through convolution.</p>\n<p>This class extends <a href = \"/reference/#/p5.Effect\">p5.Effect</a>.\nMethods <a href = \"/reference/#/p5.Effect/amp\">amp()</a>, <a href = \"/reference/#/p5.Effect/chain\">chain()</a>,\n<a href = \"/reference/#/p5.Effect/drywet\">drywet()</a>, <a href = \"/reference/#/p5.Effect/connect\">connect()</a>, and\n<a href = \"/reference/#/p5.Effect/disconnect\">disconnect()</a> are available.</p>\n","extends":"p5.Effect","is_constructor":1,"example":["\n<div><code>\nvar soundFile, reverb;\nfunction preload() {\n soundFile = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n reverb = new p5.Reverb();\n soundFile.disconnect(); // so we'll only hear reverb...\n\n // connect soundFile to reverb, process w/\n // 3 second reverbTime, decayRate of 2%\n reverb.process(soundFile, 3, 2);\n soundFile.play();\n}\n</code></div>"]},"p5.Convolver":{"name":"p5.Convolver","shortname":"p5.Convolver","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":9586,"description":"<p>p5.Convolver extends p5.Reverb. It can emulate the sound of real\nphysical spaces through a process called <a href=\"\nhttps://en.wikipedia.org/wiki/Convolution_reverb#Real_space_simulation\">\nconvolution</a>.</p>\n\n<p>Convolution multiplies any audio input by an &quot;impulse response&quot;\nto simulate the dispersion of sound over time. The impulse response is\ngenerated from an audio file that you provide. One way to\ngenerate an impulse response is to pop a balloon in a reverberant space\nand record the echo. Convolution can also be used to experiment with\nsound.</p>\n\n<p>Use the method <code>createConvolution(path)</code> to instantiate a\np5.Convolver with a path to your impulse response audio file.</p>","extends":"p5.Effect","is_constructor":1,"params":[{"name":"path","description":"<p>path to a sound file</p>\n","type":"String"},{"name":"callback","description":"<p>function to call when loading succeeds</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>function to call if loading fails.\n This function will receive an error or\n XMLHttpRequest object with information\n about what went wrong.</p>\n","type":"Function","optional":true}],"example":["\n<div><code>\nvar cVerb, sound;\nfunction preload() {\n // We have both MP3 and OGG versions of all sound assets\n soundFormats('ogg', 'mp3');\n\n // Try replacing 'bx-spring' with other soundfiles like\n // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'\n cVerb = createConvolver('assets/bx-spring.mp3');\n\n // Try replacing 'Damscray_DancingTiger' with\n // 'beat', 'doorbell', lucky_dragons_-_power_melody'\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\n</code></div>"]},"p5.Phrase":{"name":"p5.Phrase","shortname":"p5.Phrase","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":10148,"description":"<p>A phrase is a pattern of musical events over time, i.e.\na series of notes and rests.</p>\n\n<p>Phrases must be added to a p5.Part for playback, and\neach part can play multiple phrases at the same time.\nFor example, one Phrase might be a kick drum, another\ncould be a snare, and another could be the bassline.</p>\n\n<p>The first parameter is a name so that the phrase can be\nmodified or deleted later. The callback is a a function that\nthis phrase will call at every step—for example it might be\ncalled <code>playNote(value){}</code>. The array determines\nwhich value is passed into the callback at each step of the\nphrase. It can be numbers, an object with multiple numbers,\nor a zero (0) indicates a rest so the callback won&#39;t be called).</p>","is_constructor":1,"params":[{"name":"name","description":"<p>Name so that you can access the Phrase.</p>\n","type":"String"},{"name":"callback","description":"<p>The name of a function that this phrase\n will call. Typically it will play a sound,\n and accept two parameters: a time at which\n to play the sound (in seconds from now),\n and a value from the sequence array. The\n time should be passed into the play() or\n start() method to ensure precision.</p>\n","type":"Function"},{"name":"sequence","description":"<p>Array of values to pass into the callback\n at each step of the phrase.</p>\n","type":"Array"}],"example":["\n<div><code>\nvar mySound, myPhrase, myPart;\nvar pattern = [1,0,0,2,0,2,0,0];\nvar msg = 'click to play';\n\nfunction preload() {\n mySound = loadSound('assets/beatbox.mp3');\n}\n\nfunction setup() {\n noStroke();\n fill(255);\n textAlign(CENTER);\n masterVolume(0.1);\n\n myPhrase = new p5.Phrase('bbox', makeSound, pattern);\n myPart = new p5.Part();\n myPart.addPhrase(myPhrase);\n myPart.setBPM(60);\n}\n\nfunction draw() {\n background(0);\n text(msg, width/2, height/2);\n}\n\nfunction makeSound(time, playbackRate) {\n mySound.rate(playbackRate);\n mySound.play(time);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n myPart.start();\n msg = 'playing pattern';\n }\n}\n\n</code></div>"]},"p5.Part":{"name":"p5.Part","shortname":"p5.Part","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":10233,"description":"<p>A p5.Part plays back one or more p5.Phrases. Instantiate a part\nwith steps and tatums. By default, each step represents 1/16th note.</p>\n\n<p>See p5.Phrase for more about musical timing.</p>","is_constructor":1,"params":[{"name":"steps","description":"<p>Steps in the part</p>\n","type":"Number","optional":true},{"name":"tatums","description":"<p>Divisions of a beat (default is 1/16, a quarter note)</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar box, drum, myPart;\nvar boxPat = [1,0,0,2,0,2,0,0];\nvar drumPat = [0,1,1,0,2,0,1,0];\nvar msg = 'click to play';\n\nfunction preload() {\n box = loadSound('assets/beatbox.mp3');\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n noStroke();\n fill(255);\n textAlign(CENTER);\n masterVolume(0.1);\n\n var boxPhrase = new p5.Phrase('box', playBox, boxPat);\n var drumPhrase = new p5.Phrase('drum', playDrum, drumPat);\n myPart = new p5.Part();\n myPart.addPhrase(boxPhrase);\n myPart.addPhrase(drumPhrase);\n myPart.setBPM(60);\n masterVolume(0.1);\n}\n\nfunction draw() {\n background(0);\n text(msg, width/2, height/2);\n}\n\nfunction playBox(time, playbackRate) {\n box.rate(playbackRate);\n box.play(time);\n}\n\nfunction playDrum(time, playbackRate) {\n drum.rate(playbackRate);\n drum.play(time);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n myPart.start();\n msg = 'playing part';\n }\n}\n</code></div>"]},"p5.Score":{"name":"p5.Score","shortname":"p5.Score","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":10487,"description":"<p>A Score consists of a series of Parts. The parts will\nbe played back in order. For example, you could have an\nA part, a B part, and a C part, and play them back in this order\n<code>new p5.Score(a, a, b, a, c)</code></p>\n","is_constructor":1,"params":[{"name":"parts","description":"<p>One or multiple parts, to be played in sequence.</p>\n","type":"p5.Part","optional":true,"multiple":true}]},"p5.SoundLoop":{"name":"p5.SoundLoop","shortname":"p5.SoundLoop","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":10618,"description":"<p>SoundLoop</p>\n","is_constructor":1,"params":[{"name":"callback","description":"<p>this function will be called on each iteration of theloop</p>\n","type":"Function"},{"name":"interval","description":"<p>amount of time or beats for each iteration of the loop\n defaults to 1</p>\n","type":"Number|String","optional":true}],"example":["\n<div><code>\nvar click;\nvar looper1;\n\nfunction preload() {\n click = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n //the looper's callback is passed the timeFromNow\n //this value should be used as a reference point from \n //which to schedule sounds \n looper1 = new p5.SoundLoop(function(timeFromNow){\n click.play(timeFromNow);\n background(255 * (looper1.iterations % 2));\n }, 2);\n\n //stop after 10 iteratios;\n looper1.maxIterations = 10;\n //start the loop\n looper1.start();\n}\n</code></div>"]},"p5.Compressor":{"name":"p5.Compressor","shortname":"p5.Compressor","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":10878,"description":"<p>Compressor is an audio effect class that performs dynamics compression\non an audio input source. This is a very commonly used technique in music\nand sound production. Compression creates an overall louder, richer, \nand fuller sound by lowering the volume of louds and raising that of softs.\nCompression can be used to avoid clipping (sound distortion due to \npeaks in volume) and is especially useful when many sounds are played \nat once. Compression can be used on indivudal sound sources in addition\nto the master output. </p>\n<p>This class extends <a href = \"/reference/#/p5.Effect\">p5.Effect</a>.<br>Methods <a href = \"/reference/#/p5.Effect/amp\">amp()</a>, <a href = \"/reference/#/p5.Effect/chain\">chain()</a>, \n<a href = \"/reference/#/p5.Effect/drywet\">drywet()</a>, <a href = \"/reference/#/p5.Effect/connect\">connect()</a>, and \n<a href = \"/reference/#/p5.Effect/disconnect\">disconnect()</a> are available.</p>\n","is_constructor":1,"extends":"p5.Effect"},"p5.SoundRecorder":{"name":"p5.SoundRecorder","shortname":"p5.SoundRecorder","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":11089,"description":"<p>Record sounds for playback and/or to save as a .wav file.\nThe p5.SoundRecorder records all sound output from your sketch,\nor can be assigned a specific source with setInput().</p>\n<p>The record() method accepts a p5.SoundFile as a parameter.\nWhen playback is stopped (either after the given amount of time,\nor with the stop() method), the p5.SoundRecorder will send its\nrecording to that p5.SoundFile for playback.</p>","is_constructor":1,"example":["\n<div><code>\nvar mic, recorder, soundFile;\nvar state = 0;\n\nfunction setup() {\n background(200);\n // create an audio in\n mic = new p5.AudioIn();\n\n // prompts user to enable their browser mic\n mic.start();\n\n // create a sound recorder\n recorder = new p5.SoundRecorder();\n\n // connect the mic to the recorder\n recorder.setInput(mic);\n\n // this sound file will be used to\n // playback & save the recording\n soundFile = new p5.SoundFile();\n\n text('keyPress to record', 20, 20);\n}\n\nfunction keyPressed() {\n // make sure user enabled the mic\n if (state === 0 && mic.enabled) {\n\n // record to our p5.SoundFile\n recorder.record(soundFile);\n\n background(255,0,0);\n text('Recording!', 20, 20);\n state++;\n }\n else if (state === 1) {\n background(0,255,0);\n\n // stop recorder and\n // send result to soundFile\n recorder.stop();\n\n text('Stopped', 20, 20);\n state++;\n }\n\n else if (state === 2) {\n soundFile.play(); // play the result!\n save(soundFile, 'mySound.wav');\n state++;\n }\n}\n</div></code>"]},"p5.PeakDetect":{"name":"p5.PeakDetect","shortname":"p5.PeakDetect","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":11378,"description":"<p>PeakDetect works in conjunction with p5.FFT to\nlook for onsets in some or all of the frequency spectrum.\n</p>\n<p>\nTo use p5.PeakDetect, call <code>update</code> in the draw loop\nand pass in a p5.FFT object.\n</p>\n<p>\nYou can listen for a specific part of the frequency spectrum by\nsetting the range between <code>freq1</code> and <code>freq2</code>.\n</p>\n\n<p><code>threshold</code> is the threshold for detecting a peak,\nscaled between 0 and 1. It is logarithmic, so 0.1 is half as loud\nas 1.0.</p>\n\n<p>\nThe update method is meant to be run in the draw loop, and\n<b>frames</b> determines how many loops must pass before\nanother peak can be detected.\nFor example, if the frameRate() = 60, you could detect the beat of a\n120 beat-per-minute song with this equation:\n<code> framesPerPeak = 60 / (estimatedBPM / 60 );</code>\n</p>\n\n<p>\nBased on example contribtued by @b2renger, and a simple beat detection\nexplanation by <a href=\"a\nhref=&quot;http://www.airtightinteractive.com/2013/10/making-audio-reactive-visuals/&quot;\ntarget=&quot;_blank&quot;\">a\nhref=&quot;http://www.airtightinteractive.com/2013/10/making-audio-reactive-visuals/&quot;\ntarget=&quot;_blank&quot;</a>Felix Turner</a>.\n</p>","is_constructor":1,"params":[{"name":"freq1","description":"<p>lowFrequency - defaults to 20Hz</p>\n","type":"Number","optional":true},{"name":"freq2","description":"<p>highFrequency - defaults to 20000 Hz</p>\n","type":"Number","optional":true},{"name":"threshold","description":"<p>Threshold for detecting a beat between 0 and 1\n scaled logarithmically where 0.1 is 1/2 the loudness\n of 1.0. Defaults to 0.35.</p>\n","type":"Number","optional":true},{"name":"framesPerPeak","description":"<p>Defaults to 20.</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\n\nvar cnv, soundFile, fft, peakDetect;\nvar ellipseWidth = 10;\n\nfunction preload() {\n soundFile = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n\n // p5.PeakDetect requires a p5.FFT\n fft = new p5.FFT();\n peakDetect = new p5.PeakDetect();\n}\n\nfunction draw() {\n background(0);\n text('click to play/pause', width/2, height/2);\n\n // peakDetect accepts an fft post-analysis\n fft.analyze();\n peakDetect.update(fft);\n\n if ( peakDetect.isDetected ) {\n ellipseWidth = 50;\n } else {\n ellipseWidth *= 0.95;\n }\n\n ellipse(width/2, height/2, ellipseWidth, ellipseWidth);\n}\n\n// toggle play/stop when canvas is clicked\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n if (soundFile.isPlaying() ) {\n soundFile.stop();\n } else {\n soundFile.play();\n }\n }\n}\n</code></div>"]},"p5.Gain":{"name":"p5.Gain","shortname":"p5.Gain","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":11602,"description":"<p>A gain node is usefull to set the relative volume of sound.\nIt&#39;s typically used to build mixers.</p>\n","is_constructor":1,"example":["\n<div><code>\n\n // load two soundfile and crossfade beetween them\n var sound1,sound2;\n var gain1, gain2, gain3;\n\n function preload(){\n soundFormats('ogg', 'mp3');\n sound1 = loadSound('assets/Damscray_-_Dancing_Tiger_01');\n sound2 = loadSound('assets/beat.mp3');\n }\n\n function setup() {\n createCanvas(400,200);\n\n // create a 'master' gain to which we will connect both soundfiles\n gain3 = new p5.Gain();\n gain3.connect();\n\n // setup first sound for playing\n sound1.rate(1);\n sound1.loop();\n sound1.disconnect(); // diconnect from p5 output\n\n gain1 = new p5.Gain(); // setup a gain node\n gain1.setInput(sound1); // connect the first sound to its input\n gain1.connect(gain3); // connect its output to the 'master'\n\n sound2.rate(1);\n sound2.disconnect();\n sound2.loop();\n\n gain2 = new p5.Gain();\n gain2.setInput(sound2);\n gain2.connect(gain3);\n\n }\n\n function draw(){\n background(180);\n\n // calculate the horizontal distance beetween the mouse and the right of the screen\n var d = dist(mouseX,0,width,0);\n\n // map the horizontal position of the mouse to values useable for volume control of sound1\n var vol1 = map(mouseX,0,width,0,1);\n var vol2 = 1-vol1; // when sound1 is loud, sound2 is quiet and vice versa\n\n gain1.amp(vol1,0.5,0);\n gain2.amp(vol2,0.5,0);\n\n // map the vertical position of the mouse to values useable for 'master volume control'\n var vol3 = map(mouseY,0,height,0,1);\n gain3.amp(vol3,0.5,0);\n }\n</code></div>\n"]},"p5.AudioVoice":{"name":"p5.AudioVoice","shortname":"p5.AudioVoice","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":11743,"description":"<p>Base class for monophonic synthesizers. Any extensions of this class\nshould follow the API and implement the methods below in order to \nremain compatible with p5.PolySynth();</p>\n","is_constructor":1},"p5.MonoSynth":{"name":"p5.MonoSynth","shortname":"p5.MonoSynth","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":11796,"description":"<p>A MonoSynth is used as a single voice for sound synthesis.\nThis is a class to be used in conjunction with the PolySynth\nclass. Custom synthetisers should be built inheriting from\nthis class.</p>\n","is_constructor":1,"example":["\n<div><code>\nvar monoSynth;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n\n monoSynth = new p5.MonoSynth();\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n}\n\nfunction playSynth() {\n // time from now (in seconds)\n var time = 0;\n // note duration (in seconds)\n var dur = 0.25;\n // velocity (volume, from 0 to 1)\n var v = 0.2;\n\n monoSynth.play(\"G3\", v, time, dur);\n monoSynth.play(\"C4\", v, time += dur, dur);\n\n background(random(255), random(255), 255);\n text('click to play', width/2, height/2);\n}\n</code></div>"]},"p5.PolySynth":{"name":"p5.PolySynth","shortname":"p5.PolySynth","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":12096,"description":"<p>An AudioVoice is used as a single voice for sound synthesis.\nThe PolySynth class holds an array of AudioVoice, and deals\nwith voices allocations, with setting notes to be played, and\nparameters to be set.</p>\n","is_constructor":1,"params":[{"name":"synthVoice","description":"<p>A monophonic synth voice inheriting\n the AudioVoice class. Defaults to p5.MonoSynth</p>\n","type":"Number","optional":true},{"name":"maxVoices","description":"<p>Number of voices, defaults to 8;</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar polySynth;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n\n polySynth = new p5.PolySynth();\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n}\n\nfunction playSynth() {\n // note duration (in seconds)\n var dur = 1.5;\n\n // time from now (in seconds)\n var time = 0;\n\n // velocity (volume, from 0 to 1)\n var vel = 0.1;\n\n // notes can overlap with each other\n polySynth.play(\"G2\", vel, 0, dur);\n polySynth.play(\"C3\", vel, time += 1/3, dur);\n polySynth.play(\"G3\", vel, time += 1/3, dur);\n\n background(random(255), random(255), 255);\n text('click to play', width/2, height/2);\n}\n</code></div>"]},"p5.Distortion":{"name":"p5.Distortion","shortname":"p5.Distortion","classitems":[],"plugins":[],"extensions":[],"plugin_for":[],"extension_for":[],"module":"p5.sound","submodule":"p5.sound","namespace":"","file":"lib/addons/p5.sound.js","line":12501,"description":"<p>A Distortion effect created with a Waveshaper Node,\nwith an approach adapted from\n<a href=\"http://stackoverflow.com/questions/22312841/waveshaper-node-in-webaudio-how-to-emulate-distortion\">Kevin Ennis</a></p>\n<p>This class extends <a href = \"/reference/#/p5.Effect\">p5.Effect</a>.<br>Methods <a href = \"/reference/#/p5.Effect/amp\">amp()</a>, <a href = \"/reference/#/p5.Effect/chain\">chain()</a>, \n<a href = \"/reference/#/p5.Effect/drywet\">drywet()</a>, <a href = \"/reference/#/p5.Effect/connect\">connect()</a>, and \n<a href = \"/reference/#/p5.Effect/disconnect\">disconnect()</a> are available.</p>\n","extends":"p5.Effect","is_constructor":1,"params":[{"name":"amount","description":"<p>Unbounded distortion amount.\n Normal values range from 0-1.</p>\n","type":"Number","optional":true,"optdefault":"0.25"},{"name":"oversample","description":"<p>&#39;none&#39;, &#39;2x&#39;, or &#39;4x&#39;.</p>\n","type":"String","optional":true,"optdefault":"'none'"}]}},"elements":{},"classitems":[{"file":"src/color/color_conversion.js","line":10,"description":"<p>Conversions adapted from <a href=\"http://www.easyrgb.com/en/math.php\">http://www.easyrgb.com/en/math.php</a>.</p>\n<p>In these functions, hue is always in the range [0, 1], just like all other\ncomponents are in the range [0, 1]. &#39;Brightness&#39; and &#39;value&#39; are used\ninterchangeably.</p>\n","class":"p5","module":"Color","submodule":"Color Conversion"},{"file":"src/color/color_conversion.js","line":21,"description":"<p>Convert an HSBA array to HSLA.</p>\n","class":"p5","module":"Color","submodule":"Color Conversion"},{"file":"src/color/color_conversion.js","line":47,"description":"<p>Convert an HSBA array to RGBA.</p>\n","class":"p5","module":"Color","submodule":"Color Conversion"},{"file":"src/color/color_conversion.js","line":102,"description":"<p>Convert an HSLA array to HSBA.</p>\n","class":"p5","module":"Color","submodule":"Color Conversion"},{"file":"src/color/color_conversion.js","line":125,"description":"<p>Convert an HSLA array to RGBA.</p>\n<p>We need to change basis from HSLA to something that can be more easily be\nprojected onto RGBA. We will choose hue and brightness as our first two\ncomponents, and pick a convenient third one (&#39;zest&#39;) so that we don&#39;t need\nto calculate formal HSBA saturation.</p>\n","class":"p5","module":"Color","submodule":"Color Conversion"},{"file":"src/color/color_conversion.js","line":189,"description":"<p>Convert an RGBA array to HSBA.</p>\n","class":"p5","module":"Color","submodule":"Color Conversion"},{"file":"src/color/color_conversion.js","line":228,"description":"<p>Convert an RGBA array to HSLA.</p>\n","class":"p5","module":"Color","submodule":"Color Conversion"},{"file":"src/color/creating_reading.js","line":16,"description":"<p>Extracts the alpha value from a color or pixel array.</p>\n","itemtype":"method","name":"alpha","params":[{"name":"color","description":"<p><a href=\"#/p5.Color\">p5.Color</a> object, color components,\n or CSS color</p>\n","type":"p5.Color|Number[]|String"}],"return":{"description":"the alpha value","type":"Number"},"example":["\n<div>\n<code>\nnoStroke();\nvar c = color(0, 126, 255, 102);\nfill(c);\nrect(15, 15, 35, 70);\nvar value = alpha(c); // Sets 'value' to 102\nfill(value);\nrect(50, 15, 35, 70);\n</code>\n</div>"],"alt":"Left half of canvas light blue and right half light charcoal grey.\nLeft half of canvas light purple and right half a royal blue.\nLeft half of canvas salmon pink and the right half white.\nYellow rect in middle right of canvas, with 55 pixel width and height.\nYellow ellipse in top left canvas, black ellipse in bottom right,both 80x80.\nBright fuschia rect in middle of canvas, 60 pixel width and height.\nTwo bright green rects on opposite sides of the canvas, both 45x80.\nFour blue rects in each corner of the canvas, each are 35x35.\nBright sea green rect on left and darker rect on right of canvas, both 45x80.\nDark green rect on left and light green rect on right of canvas, both 45x80.\nDark blue rect on left and light teal rect on right of canvas, both 45x80.\nblue rect on left and green on right, both with black outlines & 35x60.\nsalmon pink rect on left and black on right, both 35x60.\n4 rects, tan, brown, brownish purple and purple, with white outlines & 20x60.\nlight pastel green rect on left and dark grey rect on right, both 35x60.\nyellow rect on left and red rect on right, both with black outlines & 35x60.\ngrey canvas\ndeep pink rect on left and grey rect on right, both 35x60.","class":"p5","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/creating_reading.js","line":61,"description":"<p>Extracts the blue value from a color or pixel array.</p>\n","itemtype":"method","name":"blue","params":[{"name":"color","description":"<p><a href=\"#/p5.Color\">p5.Color</a> object, color components,\n or CSS color</p>\n","type":"p5.Color|Number[]|String"}],"return":{"description":"the blue value","type":"Number"},"example":["\n<div>\n<code>\nvar c = color(175, 100, 220); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nvar blueValue = blue(c); // Get blue in 'c'\nprint(blueValue); // Prints \"220.0\"\nfill(0, 0, blueValue); // Use 'blueValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n</code>\n</div>"],"alt":"Left half of canvas light purple and right half a royal blue.","class":"p5","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/creating_reading.js","line":91,"description":"<p>Extracts the HSB brightness value from a color or pixel array.</p>\n","itemtype":"method","name":"brightness","params":[{"name":"color","description":"<p><a href=\"#/p5.Color\">p5.Color</a> object, color components,\n or CSS color</p>\n","type":"p5.Color|Number[]|String"}],"return":{"description":"the brightness value","type":"Number"},"example":["\n<div>\n<code>\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = brightness(c); // Sets 'value' to 255\nfill(value);\nrect(50, 20, 35, 60);\n</code>\n</div>"],"alt":"Left half of canvas salmon pink and the right half white.","class":"p5","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/creating_reading.js","line":121,"description":"<p>Creates colors for storing in variables of the color datatype. The\nparameters are interpreted as RGB or HSB values depending on the\ncurrent <a href=\"#/p5/colorMode\">colorMode()</a>. The default mode is RGB values from 0 to 255\nand, therefore, the function call color(255, 204, 0) will return a\nbright yellow color.\n<br><br>\nNote that if only one value is provided to <a href=\"#/p5/color\">color()</a>, it will be interpreted\nas a grayscale value. Add a second value, and it will be used for alpha\ntransparency. When three values are specified, they are interpreted as\neither RGB or HSB values. Adding a fourth value applies alpha\ntransparency.\n<br><br>\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.</p>\n","itemtype":"method","name":"color","return":{"description":"resulting color","type":"p5.Color"},"example":["\n<div>\n<code>\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nrect(30, 20, 55, 55); // Draw rectangle\n</code>\n</div>\n\n<div>\n<code>\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nellipse(25, 25, 80, 80); // Draw left circle\n\n// Using only one value with color()\n// generates a grayscale value.\nc = color(65); // Update 'c' with grayscale value\nfill(c); // Use updated 'c' as fill color\nellipse(75, 75, 80, 80); // Draw right circle\n</code>\n</div>\n\n<div>\n<code>\n// Named SVG & CSS colors may be used,\nvar c = color('magenta');\nfill(c); // Use 'c' as fill color\nnoStroke(); // Don't draw a stroke around shapes\nrect(20, 20, 60, 60); // Draw rectangle\n</code>\n</div>\n\n<div>\n<code>\n// as can hex color codes:\nnoStroke(); // Don't draw a stroke around shapes\nvar c = color('#0f0');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('#00ff00');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n</code>\n</div>\n\n<div>\n<code>\n// RGB and RGBA color strings are also supported:\n// these all set to the same color (solid blue)\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('rgb(0,0,255)');\nfill(c); // Use 'c' as fill color\nrect(10, 10, 35, 35); // Draw rectangle\n\nc = color('rgb(0%, 0%, 100%)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 35, 35); // Draw rectangle\n\nc = color('rgba(0, 0, 255, 1)');\nfill(c); // Use updated 'c' as fill color\nrect(10, 55, 35, 35); // Draw rectangle\n\nc = color('rgba(0%, 0%, 100%, 1)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 55, 35, 35); // Draw rectangle\n</code>\n</div>\n\n<div>\n<code>\n// HSL color is also supported and can be specified\n// by value\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('hsl(160, 100%, 50%)');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('hsla(160, 100%, 50%, 0.5)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n</code>\n</div>\n\n<div>\n<code>\n// HSB color is also supported and can be specified\n// by value\nvar c;\nnoStroke(); // Don't draw a stroke around shapes\nc = color('hsb(160, 100%, 50%)');\nfill(c); // Use 'c' as fill color\nrect(0, 10, 45, 80); // Draw rectangle\n\nc = color('hsba(160, 100%, 50%, 0.5)');\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw rectangle\n</code>\n</div>\n\n<div>\n<code>\nvar c; // Declare color 'c'\nnoStroke(); // Don't draw a stroke around shapes\n\n// If no colorMode is specified, then the\n// default of RGB with scale of 0-255 is used.\nc = color(50, 55, 100); // Create a color for 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(0, 10, 45, 80); // Draw left rect\n\ncolorMode(HSB, 100); // Use HSB with scale of 0-100\nc = color(50, 55, 100); // Update 'c' with new color\nfill(c); // Use updated 'c' as fill color\nrect(55, 10, 45, 80); // Draw right rect\n</code>\n</div>"],"alt":"Yellow rect in middle right of canvas, with 55 pixel width and height.\nYellow ellipse in top left of canvas, black ellipse in bottom right,both 80x80.\nBright fuschia rect in middle of canvas, 60 pixel width and height.\nTwo bright green rects on opposite sides of the canvas, both 45x80.\nFour blue rects in each corner of the canvas, each are 35x35.\nBright sea green rect on left and darker rect on right of canvas, both 45x80.\nDark green rect on left and lighter green rect on right of canvas, both 45x80.\nDark blue rect on left and light teal rect on right of canvas, both 45x80.","class":"p5","module":"Color","submodule":"Creating & Reading","overloads":[{"line":121,"params":[{"name":"gray","description":"<p>number specifying value between white\n and black.</p>\n","type":"Number"},{"name":"alpha","description":"<p>alpha value relative to current color range\n (default is 0-255)</p>\n","type":"Number","optional":true}],"return":{"description":"resulting color","type":"p5.Color"}},{"line":280,"params":[{"name":"v1","description":"<p>red or hue value relative to\n the current color range</p>\n","type":"Number"},{"name":"v2","description":"<p>green or saturation value\n relative to the current color range</p>\n","type":"Number"},{"name":"v3","description":"<p>blue or brightness value\n relative to the current color range</p>\n","type":"Number"},{"name":"alpha","description":"","type":"Number","optional":true}],"return":{"description":"","type":"p5.Color"}},{"line":292,"params":[{"name":"value","description":"<p>a color string</p>\n","type":"String"}],"return":{"description":"","type":"p5.Color"}},{"line":297,"params":[{"name":"values","description":"<p>an array containing the red,green,blue &amp;\n and alpha components of the color</p>\n","type":"Number[]"}],"return":{"description":"","type":"p5.Color"}},{"line":303,"params":[{"name":"color","description":"","type":"p5.Color"}],"return":{"description":"","type":"p5.Color"}}]},{"file":"src/color/creating_reading.js","line":319,"description":"<p>Extracts the green value from a color or pixel array.</p>\n","itemtype":"method","name":"green","params":[{"name":"color","description":"<p><a href=\"#/p5.Color\">p5.Color</a> object, color components,\n or CSS color</p>\n","type":"p5.Color|Number[]|String"}],"return":{"description":"the green value","type":"Number"},"example":["\n<div>\n<code>\nvar c = color(20, 75, 200); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nvar greenValue = green(c); // Get green in 'c'\nprint(greenValue); // Print \"75.0\"\nfill(0, greenValue, 0); // Use 'greenValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n</code>\n</div>"],"alt":"blue rect on left and green on right, both with black outlines & 35x60.","class":"p5","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/creating_reading.js","line":350,"description":"<p>Extracts the hue value from a color or pixel array.</p>\n<p>Hue exists in both HSB and HSL. This function will return the\nHSB-normalized hue when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL-normalized hue otherwise. (The values will only be different if the\nmaximum hue setting for each system is different.)</p>\n","itemtype":"method","name":"hue","params":[{"name":"color","description":"<p><a href=\"#/p5.Color\">p5.Color</a> object, color components,\n or CSS color</p>\n","type":"p5.Color|Number[]|String"}],"return":{"description":"the hue","type":"Number"},"example":["\n<div>\n<code>\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = hue(c); // Sets 'value' to \"0\"\nfill(value);\nrect(50, 20, 35, 60);\n</code>\n</div>"],"alt":"salmon pink rect on left and black on right, both 35x60.","class":"p5","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/creating_reading.js","line":387,"description":"<p>Blends two colors to find a third color somewhere between them. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first color, 0.1 is very near the first color, 0.5 is halfway\nin between, etc. An amount below 0 will be treated as 0. Likewise, amounts\nabove 1 will be capped at 1. This is different from the behavior of <a href=\"#/p5/lerp\">lerp()</a>,\nbut necessary because otherwise numbers outside the range will produce\nstrange and unexpected colors.\n<br><br>\nThe way that colours are interpolated depends on the current color mode.</p>\n","itemtype":"method","name":"lerpColor","params":[{"name":"c1","description":"<p>interpolate from this color</p>\n","type":"p5.Color"},{"name":"c2","description":"<p>interpolate to this color</p>\n","type":"p5.Color"},{"name":"amt","description":"<p>number between 0 and 1</p>\n","type":"Number"}],"return":{"description":"interpolated color","type":"p5.Color"},"example":["\n<div>\n<code>\ncolorMode(RGB);\nstroke(255);\nbackground(51);\nvar from = color(218, 165, 32);\nvar to = color(72, 61, 139);\ncolorMode(RGB); // Try changing to HSB.\nvar interA = lerpColor(from, to, 0.33);\nvar interB = lerpColor(from, to, 0.66);\nfill(from);\nrect(10, 20, 20, 60);\nfill(interA);\nrect(30, 20, 20, 60);\nfill(interB);\nrect(50, 20, 20, 60);\nfill(to);\nrect(70, 20, 20, 60);\n</code>\n</div>"],"alt":"4 rects one tan, brown, brownish purple, purple, with white outlines & 20x60","class":"p5","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/creating_reading.js","line":484,"description":"<p>Extracts the HSL lightness value from a color or pixel array.</p>\n","itemtype":"method","name":"lightness","params":[{"name":"color","description":"<p><a href=\"#/p5.Color\">p5.Color</a> object, color components,\n or CSS color</p>\n","type":"p5.Color|Number[]|String"}],"return":{"description":"the lightness","type":"Number"},"example":["\n<div>\n<code>\nnoStroke();\ncolorMode(HSL);\nvar c = color(156, 100, 50, 1);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = lightness(c); // Sets 'value' to 50\nfill(value);\nrect(50, 20, 35, 60);\n</code>\n</div>"],"alt":"light pastel green rect on left and dark grey rect on right, both 35x60.","class":"p5","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/creating_reading.js","line":514,"description":"<p>Extracts the red value from a color or pixel array.</p>\n","itemtype":"method","name":"red","params":[{"name":"color","description":"<p><a href=\"#/p5.Color\">p5.Color</a> object, color components,\n or CSS color</p>\n","type":"p5.Color|Number[]|String"}],"return":{"description":"the red value","type":"Number"},"example":["\n<div>\n<code>\nvar c = color(255, 204, 0); // Define color 'c'\nfill(c); // Use color variable 'c' as fill color\nrect(15, 20, 35, 60); // Draw left rectangle\n\nvar redValue = red(c); // Get red in 'c'\nprint(redValue); // Print \"255.0\"\nfill(redValue, 0, 0); // Use 'redValue' in new fill\nrect(50, 20, 35, 60); // Draw right rectangle\n</code>\n</div>\n\n<div>\n<code>\ncolorMode(RGB, 255);\nvar c = color(127, 255, 0);\ncolorMode(RGB, 1);\nvar myColor = red(c);\nprint(myColor);\n</code>\n</div>"],"alt":"yellow rect on left and red rect on right, both with black outlines and 35x60.\ngrey canvas","class":"p5","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/creating_reading.js","line":554,"description":"<p>Extracts the saturation value from a color or pixel array.</p>\n<p>Saturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object (or when supplied\nwith a pixel array while the color mode is HSB), but will default to the\nHSL saturation otherwise.</p>\n","itemtype":"method","name":"saturation","params":[{"name":"color","description":"<p><a href=\"#/p5.Color\">p5.Color</a> object, color components,\n or CSS color</p>\n","type":"p5.Color|Number[]|String"}],"return":{"description":"the saturation value","type":"Number"},"example":["\n<div>\n<code>\nnoStroke();\ncolorMode(HSB, 255);\nvar c = color(0, 126, 255);\nfill(c);\nrect(15, 20, 35, 60);\nvar value = saturation(c); // Sets 'value' to 126\nfill(value);\nrect(50, 20, 35, 60);\n</code>\n</div>"],"alt":"deep pink rect on left and grey rect on right, both 35x60.","class":"p5","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/p5.Color.js","line":52,"description":"<p>This function returns the color formatted as a string. This can be useful\nfor debugging, or for using p5.js with other libraries.</p>\n","itemtype":"method","name":"toString","params":[{"name":"format","description":"<p>How the color string will be formatted.\nLeaving this empty formats the string as rgba(r, g, b, a).\n&#39;#rgb&#39; &#39;#rgba&#39; &#39;#rrggbb&#39; and &#39;#rrggbbaa&#39; format as hexadecimal color codes.\n&#39;rgb&#39; &#39;hsb&#39; and &#39;hsl&#39; return the color formatted in the specified color mode.\n&#39;rgba&#39; &#39;hsba&#39; and &#39;hsla&#39; are the same as above but with alpha channels.\n&#39;rgb%&#39; &#39;hsb%&#39; &#39;hsl%&#39; &#39;rgba%&#39; &#39;hsba%&#39; and &#39;hsla%&#39; format as percentages.</p>\n","type":"String","optional":true}],"return":{"description":"the formatted string","type":"String"},"example":["\n<div>\n<code>\nvar myColor;\nfunction setup() {\n createCanvas(200, 200);\n stroke(255);\n myColor = color(100, 100, 250);\n fill(myColor);\n}\n\nfunction draw() {\n rotate(HALF_PI);\n text(myColor.toString(), 0, -5);\n text(myColor.toString('#rrggbb'), 0, -30);\n text(myColor.toString('rgba%'), 0, -55);\n}\n</code>\n</div>"],"alt":"canvas with text representation of color","class":"p5.Color","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/p5.Color.js","line":248,"itemtype":"method","name":"setRed","params":[{"name":"red","description":"<p>the new red value</p>\n","type":"Number"}],"example":["\n<div>\n<code>\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setRed(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n</code>\n</div>"],"alt":"canvas with gradually changing background color","class":"p5.Color","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/p5.Color.js","line":275,"itemtype":"method","name":"setGreen","params":[{"name":"green","description":"<p>the new green value</p>\n","type":"Number"}],"example":["\n<div>\n<code>\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setGreen(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n</code>\n</div>"],"alt":"canvas with gradually changing background color","class":"p5.Color","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/p5.Color.js","line":302,"itemtype":"method","name":"setBlue","params":[{"name":"blue","description":"<p>the new blue value</p>\n","type":"Number"}],"example":["\n<div>\n<code>\nvar backgroundColor;\n\nfunction setup() {\n backgroundColor = color(100, 50, 150);\n}\n\nfunction draw() {\n backgroundColor.setBlue(128 + 128 * sin(millis() / 1000));\n background(backgroundColor);\n}\n</code>\n</div>"],"alt":"canvas with gradually changing background color","class":"p5.Color","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/p5.Color.js","line":329,"itemtype":"method","name":"setAlpha","params":[{"name":"alpha","description":"<p>the new alpha value</p>\n","type":"Number"}],"example":["\n<div>\n<code>\nvar squareColor;\n\nfunction setup() {\n ellipseMode(CORNERS);\n strokeWeight(4);\n squareColor = color(100, 50, 150);\n}\n\nfunction draw() {\n background(255);\n\n noFill();\n stroke(0);\n ellipse(10, 10, width - 10, height - 10);\n\n squareColor.setAlpha(128 + 128 * sin(millis() / 1000));\n fill(squareColor);\n noStroke();\n rect(13, 13, width - 26, height - 26);\n}\n</code>\n</div>"],"alt":"circle behind a square with gradually changing opacity","class":"p5.Color","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/p5.Color.js","line":410,"description":"<p>Hue is the same in HSB and HSL, but the maximum value may be different.\nThis function will return the HSB-normalized saturation when supplied with\nan HSB color object, but will default to the HSL-normalized saturation\notherwise.</p>\n","class":"p5.Color","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/p5.Color.js","line":441,"description":"<p>Saturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object, but will default\nto the HSL saturation otherwise.</p>\n","class":"p5.Color","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/p5.Color.js","line":460,"description":"<p>CSS named colors.</p>\n","class":"p5.Color","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/p5.Color.js","line":613,"description":"<p>These regular expressions are used to build up the patterns for matching\nviable CSS color strings: fragmenting the regexes in this way increases the\nlegibility and comprehensibility of the code.</p>\n<p>Note that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency.</p>\n","class":"p5.Color","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/p5.Color.js","line":626,"description":"<p>Full color string patterns. The capture groups are necessary.</p>\n","class":"p5.Color","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/p5.Color.js","line":989,"description":"<p>For HSB and HSL, interpret the gray level as a brightness/lightness\nvalue (they are equivalent when chroma is zero). For RGB, normalize the\ngray level according to the blue maximum.</p>\n","class":"p5.Color","module":"Color","submodule":"Creating & Reading"},{"file":"src/color/setting.js","line":15,"description":"<p>The <a href=\"#/p5/background\">background()</a> function sets the color used for the background of the\np5.js canvas. The default background is light gray. This function is\ntypically used within <a href=\"#/p5/draw\">draw()</a> to clear the display window at the beginning\nof each frame, but it can be used inside <a href=\"#/p5/setup\">setup()</a> to set the background on\nthe first frame of animation or if the background need only be set once.\n<br><br>\nThe color is either specified in terms of the RGB, HSB, or HSL color\ndepending on the current <a href=\"#/p5/colorMode\">colorMode</a>. (The default color space is RGB, with\neach value in the range from 0 to 255). The alpha range by default is also 0 to 255.\n<br><br>\nIf a single string argument is provided, RGB, RGBA and Hex CSS color strings\nand all named color strings are supported. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.\n<br><br>\nA <a href=\"#/p5.Color\">p5.Color</a> object can also be provided to set the background color.\n<br><br>\nA <a href=\"#/p5.Image\">p5.Image</a> can also be provided to set the background image.</p>\n","itemtype":"method","name":"background","chainable":1,"example":["\n<div>\n<code>\n// Grayscale integer value\nbackground(51);\n</code>\n</div>\n\n<div>\n<code>\n// R, G & B integer values\nbackground(255, 204, 0);\n</code>\n</div>\n\n<div>\n<code>\n// H, S & B integer values\ncolorMode(HSB);\nbackground(255, 204, 100);\n</code>\n</div>\n\n<div>\n<code>\n// Named SVG/CSS color string\nbackground('red');\n</code>\n</div>\n\n<div>\n<code>\n// three-digit hexadecimal RGB notation\nbackground('#fae');\n</code>\n</div>\n\n<div>\n<code>\n// six-digit hexadecimal RGB notation\nbackground('#222222');\n</code>\n</div>\n\n<div>\n<code>\n// integer RGB notation\nbackground('rgb(0,255,0)');\n</code>\n</div>\n\n<div>\n<code>\n// integer RGBA notation\nbackground('rgba(0,255,0, 0.25)');\n</code>\n</div>\n\n<div>\n<code>\n// percentage RGB notation\nbackground('rgb(100%,0%,10%)');\n</code>\n</div>\n\n<div>\n<code>\n// percentage RGBA notation\nbackground('rgba(100%,0%,100%,0.5)');\n</code>\n</div>\n\n<div>\n<code>\n// p5 Color object\nbackground(color(0, 0, 255));\n</code>\n</div>"],"alt":"canvas with darkest charcoal grey background.\ncanvas with yellow background.\ncanvas with royal blue background.\ncanvas with red background.\ncanvas with pink background.\ncanvas with black background.\ncanvas with bright green background.\ncanvas with soft green background.\ncanvas with red background.\ncanvas with light purple background.\ncanvas with blue background.","class":"p5","module":"Color","submodule":"Setting","overloads":[{"line":15,"params":[{"name":"color","description":"<p>any value created by the <a href=\"#/p5/color\">color()</a> function</p>\n","type":"p5.Color"}],"chainable":1},{"line":131,"params":[{"name":"colorstring","description":"<p>color string, possible formats include: integer\n rgb() or rgba(), percentage rgb() or rgba(),\n 3-digit hex, 6-digit hex</p>\n","type":"String"},{"name":"a","description":"<p>opacity of the background relative to current\n color range (default is 0-255)</p>\n","type":"Number","optional":true}],"chainable":1},{"line":141,"params":[{"name":"gray","description":"<p>specifies a value between white and black</p>\n","type":"Number"},{"name":"a","description":"","type":"Number","optional":true}],"chainable":1},{"line":148,"params":[{"name":"v1","description":"<p>red or hue value (depending on the current color\n mode)</p>\n","type":"Number"},{"name":"v2","description":"<p>green or saturation value (depending on the current\n color mode)</p>\n","type":"Number"},{"name":"v3","description":"<p>blue or brightness value (depending on the current\n color mode)</p>\n","type":"Number"},{"name":"a","description":"","type":"Number","optional":true}],"chainable":1},{"line":160,"params":[{"name":"values","description":"<p>an array containing the red,green,blue &amp;\n and alpha components of the color</p>\n","type":"Number[]"}],"chainable":1},{"line":167,"params":[{"name":"image","description":"<p>image created with <a href=\"#/p5/loadImage\">loadImage()</a> or <a href=\"#/p5/createImage\">createImage()</a>,\n to set as background\n (must be same size as the sketch window)</p>\n","type":"p5.Image"},{"name":"a","description":"","type":"Number","optional":true}],"chainable":1}]},{"file":"src/color/setting.js","line":185,"description":"<p>Clears the pixels within a buffer. This function only works on p5.Canvas\nobjects created with the <a href=\"#/p5/createCanvas\">createCanvas()</a> function; it won&#39;t work with the\nmain display window. Unlike the main graphics context, pixels in\nadditional graphics areas created with <a href=\"#/p5/createGraphics\">createGraphics()</a> can be entirely\nor partially transparent. This function clears everything to make all of\nthe pixels 100% transparent.</p>\n","itemtype":"method","name":"clear","chainable":1,"example":["\n<div>\n<code>\n// Clear the screen on mouse press.\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n ellipse(mouseX, mouseY, 20, 20);\n}\n\nfunction mousePressed() {\n clear();\n}\n</code>\n</div>"],"alt":"20x20 white ellipses are continually drawn at mouse x and y coordinates.","class":"p5","module":"Color","submodule":"Setting"},{"file":"src/color/setting.js","line":223,"description":"<p><a href=\"#/p5/colorMode\">colorMode()</a> changes the way p5.js interprets color data. By default, the\nparameters for <a href=\"#/p5/fill\">fill()</a>, <a href=\"#/p5/stroke\">stroke()</a>, <a href=\"#/p5/background\">background()</a>, and <a href=\"#/p5/color\">color()</a> are defined by\nvalues between 0 and 255 using the RGB color model. This is equivalent to\nsetting colorMode(RGB, 255). Setting colorMode(HSB) lets you use the HSB\nsystem instead. By default, this is colorMode(HSB, 360, 100, 100, 1). You\ncan also use HSL.\n<br><br>\nNote: existing color objects remember the mode that they were created in,\nso you can change modes as you like without affecting their appearance.</p>\n","itemtype":"method","name":"colorMode","chainable":1,"example":["\n<div>\n<code>\nnoStroke();\ncolorMode(RGB, 100);\nfor (var i = 0; i < 100; i++) {\n for (var j = 0; j < 100; j++) {\n stroke(i, j, 0);\n point(i, j);\n }\n}\n</code>\n</div>\n\n<div>\n<code>\nnoStroke();\ncolorMode(HSB, 100);\nfor (var i = 0; i < 100; i++) {\n for (var j = 0; j < 100; j++) {\n stroke(i, j, 100);\n point(i, j);\n }\n}\n</code>\n</div>\n\n<div>\n<code>\ncolorMode(RGB, 255);\nvar c = color(127, 255, 0);\n\ncolorMode(RGB, 1);\nvar myColor = c._getRed();\ntext(myColor, 10, 10, 80, 80);\n</code>\n</div>\n\n<div>\n<code>\nnoFill();\ncolorMode(RGB, 255, 255, 255, 1);\nbackground(255);\n\nstrokeWeight(4);\nstroke(255, 0, 10, 0.3);\nellipse(40, 40, 50, 50);\nellipse(50, 50, 40, 40);\n</code>\n</div>"],"alt":"Green to red gradient from bottom L to top R. shading originates from top left.\nRainbow gradient from left to right. Brightness increasing to white at top.\nunknown image.\n50x50 ellipse at middle L & 40x40 ellipse at center. Transluscent pink outlines.","class":"p5","module":"Color","submodule":"Setting","overloads":[{"line":223,"params":[{"name":"mode","description":"<p>either RGB, HSB or HSL, corresponding to\n Red/Green/Blue and Hue/Saturation/Brightness\n (or Lightness)</p>\n","type":"Constant"},{"name":"max","description":"<p>range for all values</p>\n","type":"Number","optional":true}],"chainable":1},{"line":300,"params":[{"name":"mode","description":"","type":"Constant"},{"name":"max1","description":"<p>range for the red or hue depending on the\n current color mode</p>\n","type":"Number"},{"name":"max2","description":"<p>range for the green or saturation depending\n on the current color mode</p>\n","type":"Number"},{"name":"max3","description":"<p>range for the blue or brightness/lighntess\n depending on the current color mode</p>\n","type":"Number"},{"name":"maxA","description":"<p>range for the alpha</p>\n","type":"Number","optional":true}],"chainable":1}]},{"file":"src/color/setting.js","line":344,"description":"<p>Sets the color used to fill shapes. For example, if you run\nfill(204, 102, 0), all subsequent shapes will be filled with orange. This\ncolor is either specified in terms of the RGB or HSB color depending on\nthe current <a href=\"#/p5/colorMode\">colorMode()</a>. (The default color space is RGB, with each value\nin the range from 0 to 255). The alpha range by default is also 0 to 255.\n<br><br>\nIf a single string argument is provided, RGB, RGBA and Hex CSS color strings\nand all named color strings are supported. In this case, an alpha number\nvalue as a second argument is not supported, the RGBA form should be used.\n<br><br>\nA p5 <a href=\"#/p5.Color\">Color</a> object can also be provided to set the fill color.</p>\n","itemtype":"method","name":"fill","chainable":1,"example":["\n<div>\n<code>\n// Grayscale integer value\nfill(51);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// R, G & B integer values\nfill(255, 204, 0);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// H, S & B integer values\ncolorMode(HSB);\nfill(255, 204, 100);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// Named SVG/CSS color string\nfill('red');\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// three-digit hexadecimal RGB notation\nfill('#fae');\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// six-digit hexadecimal RGB notation\nfill('#222222');\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// integer RGB notation\nfill('rgb(0,255,0)');\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// integer RGBA notation\nfill('rgba(0,255,0, 0.25)');\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// percentage RGB notation\nfill('rgb(100%,0%,10%)');\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// percentage RGBA notation\nfill('rgba(100%,0%,100%,0.5)');\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// p5 Color object\nfill(color(0, 0, 255));\nrect(20, 20, 60, 60);\n</code>\n</div>"],"alt":"60x60 dark charcoal grey rect with black outline in center of canvas.\n60x60 yellow rect with black outline in center of canvas.\n60x60 royal blue rect with black outline in center of canvas.\n60x60 red rect with black outline in center of canvas.\n60x60 pink rect with black outline in center of canvas.\n60x60 black rect with black outline in center of canvas.\n60x60 light green rect with black outline in center of canvas.\n60x60 soft green rect with black outline in center of canvas.\n60x60 red rect with black outline in center of canvas.\n60x60 dark fushcia rect with black outline in center of canvas.\n60x60 blue rect with black outline in center of canvas.","class":"p5","module":"Color","submodule":"Setting","overloads":[{"line":344,"params":[{"name":"v1","description":"<p>red or hue value relative to\n the current color range</p>\n","type":"Number"},{"name":"v2","description":"<p>green or saturation value\n relative to the current color range</p>\n","type":"Number"},{"name":"v3","description":"<p>blue or brightness value\n relative to the current color range</p>\n","type":"Number"},{"name":"alpha","description":"","type":"Number","optional":true}],"chainable":1},{"line":469,"params":[{"name":"value","description":"<p>a color string</p>\n","type":"String"}],"chainable":1},{"line":475,"params":[{"name":"gray","description":"<p>a gray value</p>\n","type":"Number"},{"name":"alpha","description":"","type":"Number","optional":true}],"chainable":1},{"line":482,"params":[{"name":"values","description":"<p>an array containing the red,green,blue &amp;\n and alpha components of the color</p>\n","type":"Number[]"}],"chainable":1},{"line":489,"params":[{"name":"color","description":"<p>the fill color</p>\n","type":"p5.Color"}],"chainable":1}]},{"file":"src/color/setting.js","line":501,"description":"<p>Disables filling geometry. If both <a href=\"#/p5/noStroke\">noStroke()</a> and <a href=\"#/p5/noFill\">noFill()</a> are called,\nnothing will be drawn to the screen.</p>\n","itemtype":"method","name":"noFill","chainable":1,"example":["\n<div>\n<code>\nrect(15, 10, 55, 55);\nnoFill();\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div modernizr='webgl'>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n noFill();\n stroke(100, 100, 240);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(45, 45, 45);\n}\n</code>\n</div>"],"alt":"white rect top middle and noFill rect center. Both 60x60 with black outlines.\nblack canvas with purple cube wireframe spinning","class":"p5","module":"Color","submodule":"Setting"},{"file":"src/color/setting.js","line":542,"description":"<p>Disables drawing the stroke (outline). If both <a href=\"#/p5/noStroke\">noStroke()</a> and <a href=\"#/p5/noFill\">noFill()</a>\nare called, nothing will be drawn to the screen.</p>\n","itemtype":"method","name":"noStroke","chainable":1,"example":["\n<div>\n<code>\nnoStroke();\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div modernizr='webgl'>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n noStroke();\n fill(240, 150, 150);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(45, 45, 45);\n}\n</code>\n</div>"],"alt":"60x60 white rect at center. no outline.\nblack canvas with pink cube spinning","class":"p5","module":"Color","submodule":"Setting"},{"file":"src/color/setting.js","line":582,"description":"<p>Sets the color used to draw lines and borders around shapes. This color\nis either specified in terms of the RGB or HSB color depending on the\ncurrent <a href=\"#/p5/colorMode\">colorMode()</a> (the default color space is RGB, with each value in\nthe range from 0 to 255). The alpha range by default is also 0 to 255.\n<br><br>\nIf a single string argument is provided, RGB, RGBA and Hex CSS color\nstrings and all named color strings are supported. In this case, an alpha\nnumber value as a second argument is not supported, the RGBA form should be\nused.\n<br><br>\nA p5 <a href=\"#/p5.Color\">Color</a> object can also be provided to set the stroke color.</p>\n","itemtype":"method","name":"stroke","chainable":1,"example":["\n<div>\n<code>\n// Grayscale integer value\nstrokeWeight(4);\nstroke(51);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// R, G & B integer values\nstroke(255, 204, 0);\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// H, S & B integer values\ncolorMode(HSB);\nstrokeWeight(4);\nstroke(255, 204, 100);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// Named SVG/CSS color string\nstroke('red');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// three-digit hexadecimal RGB notation\nstroke('#fae');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// six-digit hexadecimal RGB notation\nstroke('#222222');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// integer RGB notation\nstroke('rgb(0,255,0)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// integer RGBA notation\nstroke('rgba(0,255,0,0.25)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// percentage RGB notation\nstroke('rgb(100%,0%,10%)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// percentage RGBA notation\nstroke('rgba(100%,0%,100%,0.5)');\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n</code>\n</div>\n\n<div>\n<code>\n// p5 Color object\nstroke(color(0, 0, 255));\nstrokeWeight(4);\nrect(20, 20, 60, 60);\n</code>\n</div>"],"alt":"60x60 white rect at center. Dark charcoal grey outline.\n60x60 white rect at center. Yellow outline.\n60x60 white rect at center. Royal blue outline.\n60x60 white rect at center. Red outline.\n60x60 white rect at center. Pink outline.\n60x60 white rect at center. Black outline.\n60x60 white rect at center. Bright green outline.\n60x60 white rect at center. Soft green outline.\n60x60 white rect at center. Red outline.\n60x60 white rect at center. Dark fushcia outline.\n60x60 white rect at center. Blue outline.","class":"p5","module":"Color","submodule":"Setting","overloads":[{"line":582,"params":[{"name":"v1","description":"<p>red or hue value relative to\n the current color range</p>\n","type":"Number"},{"name":"v2","description":"<p>green or saturation value\n relative to the current color range</p>\n","type":"Number"},{"name":"v3","description":"<p>blue or brightness value\n relative to the current color range</p>\n","type":"Number"},{"name":"alpha","description":"","type":"Number","optional":true}],"chainable":1},{"line":721,"params":[{"name":"value","description":"<p>a color string</p>\n","type":"String"}],"chainable":1},{"line":727,"params":[{"name":"gray","description":"<p>a gray value</p>\n","type":"Number"},{"name":"alpha","description":"","type":"Number","optional":true}],"chainable":1},{"line":734,"params":[{"name":"values","description":"<p>an array containing the red,green,blue &amp;\n and alpha components of the color</p>\n","type":"Number[]"}],"chainable":1},{"line":741,"params":[{"name":"color","description":"<p>the stroke color</p>\n","type":"p5.Color"}],"chainable":1}]},{"file":"src/core/shape/2d_primitives.js","line":16,"description":"<p>Draw an arc to the screen. If called with only x, y, w, h, start, and\nstop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc\nwill be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The\norigin may be changed with the <a href=\"#/p5/ellipseMode\">ellipseMode()</a> function.<br><br>\nNote that drawing a full circle (ex: 0 to TWO_PI) will appear blank\nbecause 0 and TWO_PI are the same position on the unit circle. The\nbest way to handle this is by using the <a href=\"#/p5/ellipse\">ellipse()</a> function instead\nto create a closed ellipse, and to use the <a href=\"#/p5/arc\">arc()</a> function\nonly to draw parts of an ellipse.</p>\n","itemtype":"method","name":"arc","params":[{"name":"x","description":"<p>x-coordinate of the arc&#39;s ellipse</p>\n","type":"Number"},{"name":"y","description":"<p>y-coordinate of the arc&#39;s ellipse</p>\n","type":"Number"},{"name":"w","description":"<p>width of the arc&#39;s ellipse by default</p>\n","type":"Number"},{"name":"h","description":"<p>height of the arc&#39;s ellipse by default</p>\n","type":"Number"},{"name":"start","description":"<p>angle to start the arc, specified in radians</p>\n","type":"Number"},{"name":"stop","description":"<p>angle to stop the arc, specified in radians</p>\n","type":"Number"},{"name":"mode","description":"<p>optional parameter to determine the way of drawing\n the arc. either CHORD, PIE or OPEN</p>\n","type":"Constant","optional":true},{"name":"detail","description":"<p>optional parameter for WebGL mode only. This is to\n specify the number of vertices that makes up the\n perimeter of the arc. Default value is 25.</p>\n","type":"Number","optional":true}],"chainable":1,"example":["\n<div>\n<code>\narc(50, 55, 50, 50, 0, HALF_PI);\nnoFill();\narc(50, 55, 60, 60, HALF_PI, PI);\narc(50, 55, 70, 70, PI, PI + QUARTER_PI);\narc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI);\n</code>\n</div>\n\n<div>\n<code>\narc(50, 50, 80, 80, 0, PI + QUARTER_PI);\n</code>\n</div>\n\n<div>\n<code>\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN);\n</code>\n</div>\n\n<div>\n<code>\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD);\n</code>\n</div>\n\n<div>\n<code>\narc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE);\n</code>\n</div>"],"alt":"shattered outline of an ellipse with a quarter of a white circle bottom-right.\nwhite ellipse with top right quarter missing.\nwhite ellipse with black outline with top right missing.\nwhite ellipse with top right missing with black outline around shape.\nwhite ellipse with top right quarter missing with black outline around the shape.","class":"p5","module":"Shape","submodule":"2D Primitives"},{"file":"src/core/shape/2d_primitives.js","line":149,"description":"<p>Draws an ellipse (oval) to the screen. An ellipse with equal width and\nheight is a circle. By default, the first two parameters set the location,\nand the third and fourth parameters set the shape&#39;s width and height. If\nno height is specified, the value of width is used for both the width and\nheight. If a negative height or width is specified, the absolute value is taken.\nThe origin may be changed with the <a href=\"#/p5/ellipseMode\">ellipseMode()</a> function.</p>\n","itemtype":"method","name":"ellipse","chainable":1,"example":["\n<div>\n<code>\nellipse(56, 46, 55, 55);\n</code>\n</div>"],"alt":"white ellipse with black outline in middle-right of canvas that is 55x55.","class":"p5","module":"Shape","submodule":"2D Primitives","overloads":[{"line":149,"params":[{"name":"x","description":"<p>x-coordinate of the ellipse.</p>\n","type":"Number"},{"name":"y","description":"<p>y-coordinate of the ellipse.</p>\n","type":"Number"},{"name":"w","description":"<p>width of the ellipse.</p>\n","type":"Number"},{"name":"h","description":"<p>height of the ellipse.</p>\n","type":"Number","optional":true}],"chainable":1},{"line":174,"params":[{"name":"x","description":"","type":"Number"},{"name":"y","description":"","type":"Number"},{"name":"w","description":"","type":"Number"},{"name":"h","description":"","type":"Number"},{"name":"detail","description":"<p>number of radial sectors to draw</p>\n","type":"Integer"}]}]},{"file":"src/core/shape/2d_primitives.js","line":208,"description":"<p>Draws a line (a direct path between two points) to the screen. The version\nof <a href=\"#/p5/line\">line()</a> with four parameters draws the line in 2D. To color a line, use\nthe <a href=\"#/p5/stroke\">stroke()</a> function. A line cannot be filled, therefore the <a href=\"#/p5/fill\">fill()</a>\nfunction will not affect the color of a line. 2D lines are drawn with a\nwidth of one pixel by default, but this can be changed with the\n<a href=\"#/p5/strokeWeight\">strokeWeight()</a> function.</p>\n","itemtype":"method","name":"line","chainable":1,"example":["\n<div>\n<code>\nline(30, 20, 85, 75);\n</code>\n</div>\n\n<div>\n<code>\nline(30, 20, 85, 20);\nstroke(126);\nline(85, 20, 85, 75);\nstroke(255);\nline(85, 75, 30, 75);\n</code>\n</div>"],"alt":"line 78 pixels long running from mid-top to bottom-right of canvas.\n3 lines of various stroke sizes. Form top, bottom and right sides of a square.","class":"p5","module":"Shape","submodule":"2D Primitives","overloads":[{"line":208,"params":[{"name":"x1","description":"<p>the x-coordinate of the first point</p>\n","type":"Number"},{"name":"y1","description":"<p>the y-coordinate of the first point</p>\n","type":"Number"},{"name":"x2","description":"<p>the x-coordinate of the second point</p>\n","type":"Number"},{"name":"y2","description":"<p>the y-coordinate of the second point</p>\n","type":"Number"}],"chainable":1},{"line":244,"params":[{"name":"x1","description":"","type":"Number"},{"name":"y1","description":"","type":"Number"},{"name":"z1","description":"<p>the z-coordinate of the first point</p>\n","type":"Number"},{"name":"x2","description":"","type":"Number"},{"name":"y2","description":"","type":"Number"},{"name":"z2","description":"<p>the z-coordinate of the second point</p>\n","type":"Number"}],"chainable":1}]},{"file":"src/core/shape/2d_primitives.js","line":264,"description":"<p>Draws a point, a coordinate in space at the dimension of one pixel.\nThe first parameter is the horizontal value for the point, the second\nvalue is the vertical value for the point. The color of the point is\ndetermined by the current stroke.</p>\n","itemtype":"method","name":"point","params":[{"name":"x","description":"<p>the x-coordinate</p>\n","type":"Number"},{"name":"y","description":"<p>the y-coordinate</p>\n","type":"Number"},{"name":"z","description":"<p>the z-coordinate (for WEBGL mode)</p>\n","type":"Number","optional":true}],"chainable":1,"example":["\n<div>\n<code>\npoint(30, 20);\npoint(85, 20);\npoint(85, 75);\npoint(30, 75);\n</code>\n</div>"],"alt":"4 points centered in the middle-right of the canvas.","class":"p5","module":"Shape","submodule":"2D Primitives"},{"file":"src/core/shape/2d_primitives.js","line":299,"description":"<p>Draw a quad. A quad is a quadrilateral, a four sided polygon. It is\nsimilar to a rectangle, but the angles between its edges are not\nconstrained to ninety degrees. The first pair of parameters (x1,y1)\nsets the first vertex and the subsequent pairs should proceed\nclockwise or counter-clockwise around the defined shape.</p>\n","itemtype":"method","name":"quad","chainable":1,"example":["\n<div>\n<code>\nquad(38, 31, 86, 20, 69, 63, 30, 76);\n</code>\n</div>"],"alt":"irregular white quadrilateral shape with black outline mid-right of canvas.","class":"p5","module":"Shape","submodule":"2D Primitives","overloads":[{"line":299,"params":[{"name":"x1","description":"<p>the x-coordinate of the first point</p>\n","type":"Number"},{"name":"y1","description":"<p>the y-coordinate of the first point</p>\n","type":"Number"},{"name":"x2","description":"<p>the x-coordinate of the second point</p>\n","type":"Number"},{"name":"y2","description":"<p>the y-coordinate of the second point</p>\n","type":"Number"},{"name":"x3","description":"<p>the x-coordinate of the third point</p>\n","type":"Number"},{"name":"y3","description":"<p>the y-coordinate of the third point</p>\n","type":"Number"},{"name":"x4","description":"<p>the x-coordinate of the fourth point</p>\n","type":"Number"},{"name":"y4","description":"<p>the y-coordinate of the fourth point</p>\n","type":"Number"}],"chainable":1},{"line":327,"params":[{"name":"x1","description":"","type":"Number"},{"name":"y1","description":"","type":"Number"},{"name":"z1","description":"<p>the z-coordinate of the first point</p>\n","type":"Number"},{"name":"x2","description":"","type":"Number"},{"name":"y2","description":"","type":"Number"},{"name":"z2","description":"<p>the z-coordinate of the second point</p>\n","type":"Number"},{"name":"x3","description":"","type":"Number"},{"name":"y3","description":"","type":"Number"},{"name":"z3","description":"<p>the z-coordinate of the third point</p>\n","type":"Number"},{"name":"x4","description":"","type":"Number"},{"name":"y4","description":"","type":"Number"},{"name":"z4","description":"<p>the z-coordinate of the fourth point</p>\n","type":"Number"}],"chainable":1}]},{"file":"src/core/shape/2d_primitives.js","line":353,"description":"<p>Draws a rectangle to the screen. A rectangle is a four-sided shape with\nevery angle at ninety degrees. By default, the first two parameters set\nthe location of the upper-left corner, the third sets the width, and the\nfourth sets the height. The way these parameters are interpreted, however,\nmay be changed with the <a href=\"#/p5/rectMode\">rectMode()</a> function.\n<br><br>\nThe fifth, sixth, seventh and eighth parameters, if specified,\ndetermine corner radius for the top-left, top-right, lower-right and\nlower-left corners, respectively. An omitted corner radius parameter is set\nto the value of the previously specified radius value in the parameter list.</p>\n","itemtype":"method","name":"rect","chainable":1,"example":["\n<div>\n<code>\n// Draw a rectangle at location (30, 20) with a width and height of 55.\nrect(30, 20, 55, 55);\n</code>\n</div>\n\n<div>\n<code>\n// Draw a rectangle with rounded corners, each having a radius of 20.\nrect(30, 20, 55, 55, 20);\n</code>\n</div>\n\n<div>\n<code>\n// Draw a rectangle with rounded corners having the following radii:\n// top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5.\nrect(30, 20, 55, 55, 20, 15, 10, 5);\n</code>\n</div>"],"alt":"55x55 white rect with black outline in mid-right of canvas.\n55x55 white rect with black outline and rounded edges in mid-right of canvas.\n55x55 white rect with black outline and rounded edges of different radii.","class":"p5","module":"Shape","submodule":"2D Primitives","overloads":[{"line":353,"params":[{"name":"x","description":"<p>x-coordinate of the rectangle.</p>\n","type":"Number"},{"name":"y","description":"<p>y-coordinate of the rectangle.</p>\n","type":"Number"},{"name":"w","description":"<p>width of the rectangle.</p>\n","type":"Number"},{"name":"h","description":"<p>height of the rectangle.</p>\n","type":"Number"},{"name":"tl","description":"<p>optional radius of top-left corner.</p>\n","type":"Number","optional":true},{"name":"tr","description":"<p>optional radius of top-right corner.</p>\n","type":"Number","optional":true},{"name":"br","description":"<p>optional radius of bottom-right corner.</p>\n","type":"Number","optional":true},{"name":"bl","description":"<p>optional radius of bottom-left corner.</p>\n","type":"Number","optional":true}],"chainable":1},{"line":403,"params":[{"name":"x","description":"","type":"Number"},{"name":"y","description":"","type":"Number"},{"name":"w","description":"","type":"Number"},{"name":"h","description":"","type":"Number"},{"name":"detailX","description":"<p>number of segments in the x-direction</p>\n","type":"Integer","optional":true},{"name":"detailY","description":"<p>number of segments in the y-direction</p>\n","type":"Integer","optional":true}],"chainable":1}]},{"file":"src/core/shape/2d_primitives.js","line":436,"description":"<p>A triangle is a plane created by connecting three points. The first two\narguments specify the first point, the middle two arguments specify the\nsecond point, and the last two arguments specify the third point.</p>\n","itemtype":"method","name":"triangle","params":[{"name":"x1","description":"<p>x-coordinate of the first point</p>\n","type":"Number"},{"name":"y1","description":"<p>y-coordinate of the first point</p>\n","type":"Number"},{"name":"x2","description":"<p>x-coordinate of the second point</p>\n","type":"Number"},{"name":"y2","description":"<p>y-coordinate of the second point</p>\n","type":"Number"},{"name":"x3","description":"<p>x-coordinate of the third point</p>\n","type":"Number"},{"name":"y3","description":"<p>y-coordinate of the third point</p>\n","type":"Number"}],"chainable":1,"example":["\n<div>\n<code>\ntriangle(30, 75, 58, 20, 86, 75);\n</code>\n</div>"],"alt":"white triangle with black outline in mid-right of canvas.","class":"p5","module":"Shape","submodule":"2D Primitives"},{"file":"src/core/shape/attributes.js","line":14,"description":"<p>Modifies the location from which ellipses are drawn by changing the way\nin which parameters given to <a href=\"#/p5/ellipse\">ellipse()</a> are interpreted.\n<br><br>\nThe default mode is ellipseMode(CENTER), which interprets the first two\nparameters of <a href=\"#/p5/ellipse\">ellipse()</a> as the shape&#39;s center point, while the third and\nfourth parameters are its width and height.\n<br><br>\nellipseMode(RADIUS) also uses the first two parameters of <a href=\"#/p5/ellipse\">ellipse()</a> as\nthe shape&#39;s center point, but uses the third and fourth parameters to\nspecify half of the shapes&#39;s width and height.\n<br><br>\nellipseMode(CORNER) interprets the first two parameters of <a href=\"#/p5/ellipse\">ellipse()</a> as\nthe upper-left corner of the shape, while the third and fourth parameters\nare its width and height.\n<br><br>\nellipseMode(CORNERS) interprets the first two parameters of <a href=\"#/p5/ellipse\">ellipse()</a> as\nthe location of one corner of the ellipse&#39;s bounding box, and the third\nand fourth parameters as the location of the opposite corner.\n<br><br>\nThe parameter must be written in ALL CAPS because Javascript is a\ncase-sensitive language.</p>\n","itemtype":"method","name":"ellipseMode","params":[{"name":"mode","description":"<p>either CENTER, RADIUS, CORNER, or CORNERS</p>\n","type":"Constant"}],"chainable":1,"example":["\n<div>\n<code>\nellipseMode(RADIUS); // Set ellipseMode to RADIUS\nfill(255); // Set fill to white\nellipse(50, 50, 30, 30); // Draw white ellipse using RADIUS mode\n\nellipseMode(CENTER); // Set ellipseMode to CENTER\nfill(100); // Set fill to gray\nellipse(50, 50, 30, 30); // Draw gray ellipse using CENTER mode\n</code>\n</div>\n\n<div>\n<code>\nellipseMode(CORNER); // Set ellipseMode is CORNER\nfill(255); // Set fill to white\nellipse(25, 25, 50, 50); // Draw white ellipse using CORNER mode\n\nellipseMode(CORNERS); // Set ellipseMode to CORNERS\nfill(100); // Set fill to gray\nellipse(25, 25, 50, 50); // Draw gray ellipse using CORNERS mode\n</code>\n</div>"],"alt":"60x60 white ellipse and 30x30 grey ellipse with black outlines at center.\n60x60 white ellipse @center and 30x30 grey ellipse top-right, black outlines.","class":"p5","module":"Shape","submodule":"Attributes"},{"file":"src/core/shape/attributes.js","line":83,"description":"<p>Draws all geometry with jagged (aliased) edges. Note that <a href=\"#/p5/smooth\">smooth()</a> is\nactive by default in 2D mode, so it is necessary to call <a href=\"#/p5/noSmooth\">noSmooth()</a> to disable\nsmoothing of geometry, images, and fonts. In 3D mode, <a href=\"#/p5/noSmooth\">noSmooth()</a> is enabled\nby default, so it is necessary to call <a href=\"#/p5/smooth\">smooth()</a> if you would like\nsmooth (antialiased) edges on your geometry.</p>\n","itemtype":"method","name":"noSmooth","chainable":1,"example":["\n<div>\n<code>\nbackground(0);\nnoStroke();\nsmooth();\nellipse(30, 48, 36, 36);\nnoSmooth();\nellipse(70, 48, 36, 36);\n</code>\n</div>"],"alt":"2 pixelated 36x36 white ellipses to left & right of center, black background","class":"p5","module":"Shape","submodule":"Attributes"},{"file":"src/core/shape/attributes.js","line":113,"description":"<p>Modifies the location from which rectangles are drawn by changing the way\nin which parameters given to <a href=\"#/p5/rect\">rect()</a> are interpreted.\n<br><br>\nThe default mode is rectMode(CORNER), which interprets the first two\nparameters of <a href=\"#/p5/rect\">rect()</a> as the upper-left corner of the shape, while the\nthird and fourth parameters are its width and height.\n<br><br>\nrectMode(CORNERS) interprets the first two parameters of <a href=\"#/p5/rect\">rect()</a> as the\nlocation of one corner, and the third and fourth parameters as the\nlocation of the opposite corner.\n<br><br>\nrectMode(CENTER) interprets the first two parameters of <a href=\"#/p5/rect\">rect()</a> as the\nshape&#39;s center point, while the third and fourth parameters are its\nwidth and height.\n<br><br>\nrectMode(RADIUS) also uses the first two parameters of <a href=\"#/p5/rect\">rect()</a> as the\nshape&#39;s center point, but uses the third and fourth parameters to specify\nhalf of the shapes&#39;s width and height.\n<br><br>\nThe parameter must be written in ALL CAPS because Javascript is a\ncase-sensitive language.</p>\n","itemtype":"method","name":"rectMode","params":[{"name":"mode","description":"<p>either CORNER, CORNERS, CENTER, or RADIUS</p>\n","type":"Constant"}],"chainable":1,"example":["\n<div>\n<code>\nrectMode(CORNER); // Default rectMode is CORNER\nfill(255); // Set fill to white\nrect(25, 25, 50, 50); // Draw white rect using CORNER mode\n\nrectMode(CORNERS); // Set rectMode to CORNERS\nfill(100); // Set fill to gray\nrect(25, 25, 50, 50); // Draw gray rect using CORNERS mode\n</code>\n</div>\n\n<div>\n<code>\nrectMode(RADIUS); // Set rectMode to RADIUS\nfill(255); // Set fill to white\nrect(50, 50, 30, 30); // Draw white rect using RADIUS mode\n\nrectMode(CENTER); // Set rectMode to CENTER\nfill(100); // Set fill to gray\nrect(50, 50, 30, 30); // Draw gray rect using CENTER mode\n</code>\n</div>"],"alt":"50x50 white rect at center and 25x25 grey rect in the top left of the other.\n50x50 white rect at center and 25x25 grey rect in the center of the other.","class":"p5","module":"Shape","submodule":"Attributes"},{"file":"src/core/shape/attributes.js","line":182,"description":"<p>Draws all geometry with smooth (anti-aliased) edges. <a href=\"#/p5/smooth\">smooth()</a> will also\nimprove image quality of resized images. Note that <a href=\"#/p5/smooth\">smooth()</a> is active by\ndefault in 2D mode; <a href=\"#/p5/noSmooth\">noSmooth()</a> can be used to disable smoothing of geometry,\nimages, and fonts. In 3D mode, <a href=\"#/p5/noSmooth\">noSmooth()</a> is enabled\nby default, so it is necessary to call <a href=\"#/p5/smooth\">smooth()</a> if you would like\nsmooth (antialiased) edges on your geometry.</p>\n","itemtype":"method","name":"smooth","chainable":1,"example":["\n<div>\n<code>\nbackground(0);\nnoStroke();\nsmooth();\nellipse(30, 48, 36, 36);\nnoSmooth();\nellipse(70, 48, 36, 36);\n</code>\n</div>"],"alt":"2 pixelated 36x36 white ellipses one left one right of center. On black.","class":"p5","module":"Shape","submodule":"Attributes"},{"file":"src/core/shape/attributes.js","line":213,"description":"<p>Sets the style for rendering line endings. These ends are either squared,\nextended, or rounded, each of which specified with the corresponding\nparameters: SQUARE, PROJECT, and ROUND. The default cap is ROUND.</p>\n","itemtype":"method","name":"strokeCap","params":[{"name":"cap","description":"<p>either SQUARE, PROJECT, or ROUND</p>\n","type":"Constant"}],"chainable":1,"example":["\n<div>\n<code>\nstrokeWeight(12.0);\nstrokeCap(ROUND);\nline(20, 30, 80, 30);\nstrokeCap(SQUARE);\nline(20, 50, 80, 50);\nstrokeCap(PROJECT);\nline(20, 70, 80, 70);\n</code>\n</div>"],"alt":"3 lines. Top line: rounded ends, mid: squared, bottom:longer squared ends.","class":"p5","module":"Shape","submodule":"Attributes"},{"file":"src/core/shape/attributes.js","line":250,"description":"<p>Sets the style of the joints which connect line segments. These joints\nare either mitered, beveled, or rounded and specified with the\ncorresponding parameters MITER, BEVEL, and ROUND. The default joint is\nMITER.</p>\n","itemtype":"method","name":"strokeJoin","params":[{"name":"join","description":"<p>either MITER, BEVEL, ROUND</p>\n","type":"Constant"}],"chainable":1,"example":["\n<div>\n<code>\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(MITER);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(BEVEL);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nnoFill();\nstrokeWeight(10.0);\nstrokeJoin(ROUND);\nbeginShape();\nvertex(35, 20);\nvertex(65, 50);\nvertex(35, 80);\nendShape();\n</code>\n</div>"],"alt":"Right-facing arrowhead shape with pointed tip in center of canvas.\nRight-facing arrowhead shape with flat tip in center of canvas.\nRight-facing arrowhead shape with rounded tip in center of canvas.","class":"p5","module":"Shape","submodule":"Attributes"},{"file":"src/core/shape/attributes.js","line":317,"description":"<p>Sets the width of the stroke used for lines, points, and the border\naround shapes. All widths are set in units of pixels.</p>\n","itemtype":"method","name":"strokeWeight","params":[{"name":"weight","description":"<p>the weight (in pixels) of the stroke</p>\n","type":"Number"}],"chainable":1,"example":["\n<div>\n<code>\nstrokeWeight(1); // Default\nline(20, 20, 80, 20);\nstrokeWeight(4); // Thicker\nline(20, 40, 80, 40);\nstrokeWeight(10); // Beastly\nline(20, 70, 80, 70);\n</code>\n</div>"],"alt":"3 horizontal black lines. Top line: thin, mid: medium, bottom:thick.","class":"p5","module":"Shape","submodule":"Attributes"},{"file":"src/core/shape/curves.js","line":13,"description":"<p>Draws a cubic Bezier curve on the screen. These curves are defined by a\nseries of anchor and control points. The first two parameters specify\nthe first anchor point and the last two parameters specify the other\nanchor point, which become the first and last points on the curve. The\nmiddle parameters specify the two control points which define the shape\nof the curve. Approximately speaking, control points &quot;pull&quot; the curve\ntowards them.<br /><br />Bezier curves were developed by French\nautomotive engineer Pierre Bezier, and are commonly used in computer\ngraphics to define gently sloping curves. See also <a href=\"#/p5/curve\">curve()</a>.</p>\n","itemtype":"method","name":"bezier","chainable":1,"example":["\n<div>\n<code>\nnoFill();\nstroke(255, 102, 0);\nline(85, 20, 10, 10);\nline(90, 90, 15, 80);\nstroke(0, 0, 0);\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\n</code>\n</div>\n\n<div>\n<code>\nbackground(0, 0, 0);\nnoFill();\nstroke(255);\nbezier(250, 250, 0, 100, 100, 0, 100, 0, 0, 0, 100, 0);\n</code>\n</div>"],"alt":"stretched black s-shape in center with orange lines extending from end points.\nstretched black s-shape with 10 5x5 white ellipses along the shape.\nstretched black s-shape with 7 5x5 ellipses and orange lines along the shape.\nstretched black s-shape with 17 small orange lines extending from under shape.\nhorseshoe shape with orange ends facing left and black curved center.\nhorseshoe shape with orange ends facing left and black curved center.\nLine shaped like right-facing arrow,points move with mouse-x and warp shape.\nhorizontal line that hooks downward on the right and 13 5x5 ellipses along it.\nright curving line mid-right of canvas with 7 short lines radiating from it.","class":"p5","module":"Shape","submodule":"Curves","overloads":[{"line":13,"params":[{"name":"x1","description":"<p>x-coordinate for the first anchor point</p>\n","type":"Number"},{"name":"y1","description":"<p>y-coordinate for the first anchor point</p>\n","type":"Number"},{"name":"x2","description":"<p>x-coordinate for the first control point</p>\n","type":"Number"},{"name":"y2","description":"<p>y-coordinate for the first control point</p>\n","type":"Number"},{"name":"x3","description":"<p>x-coordinate for the second control point</p>\n","type":"Number"},{"name":"y3","description":"<p>y-coordinate for the second control point</p>\n","type":"Number"},{"name":"x4","description":"<p>x-coordinate for the second anchor point</p>\n","type":"Number"},{"name":"y4","description":"<p>y-coordinate for the second anchor point</p>\n","type":"Number"}],"chainable":1},{"line":66,"params":[{"name":"x1","description":"","type":"Number"},{"name":"y1","description":"","type":"Number"},{"name":"z1","description":"<p>z-coordinate for the first anchor point</p>\n","type":"Number"},{"name":"x2","description":"","type":"Number"},{"name":"y2","description":"","type":"Number"},{"name":"z2","description":"<p>z-coordinate for the first control point</p>\n","type":"Number"},{"name":"x3","description":"","type":"Number"},{"name":"y3","description":"","type":"Number"},{"name":"z3","description":"<p>z-coordinate for the second control point</p>\n","type":"Number"},{"name":"x4","description":"","type":"Number"},{"name":"y4","description":"","type":"Number"},{"name":"z4","description":"<p>z-coordinate for the second anchor point</p>\n","type":"Number"}],"chainable":1}]},{"file":"src/core/shape/curves.js","line":96,"description":"<p>Sets the resolution at which Beziers display.</p>\n<p>The default value is 20.</p>\n<p>This function is only useful when using the WEBGL renderer\nas the default canvas renderer does not use this information.</p>\n","itemtype":"method","name":"bezierDetail","params":[{"name":"detail","description":"<p>resolution of the curves</p>\n","type":"Number"}],"chainable":1,"example":["\n<div modernizr='webgl'>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noFill();\n\n bezierDetail(5);\n}\n\nfunction draw() {\n background(200);\n\n // prettier-ignore\n bezier(-40, -40, 0,\n 90, -40, 0,\n -90, 40, 0,\n 40, 40, 0);\n}\n</code>\n</div>"],"alt":"stretched black s-shape with a low level of bezier detail","class":"p5","module":"Shape","submodule":"Curves"},{"file":"src/core/shape/curves.js","line":139,"description":"<p>Evaluates the Bezier at position t for points a, b, c, d.\nThe parameters a and d are the first and last points\non the curve, and b and c are the control points.\nThe final parameter t varies between 0 and 1.\nThis can be done once with the x coordinates and a second time\nwith the y coordinates to get the location of a bezier curve at t.</p>\n","itemtype":"method","name":"bezierPoint","params":[{"name":"a","description":"<p>coordinate of first point on the curve</p>\n","type":"Number"},{"name":"b","description":"<p>coordinate of first control point</p>\n","type":"Number"},{"name":"c","description":"<p>coordinate of second control point</p>\n","type":"Number"},{"name":"d","description":"<p>coordinate of second point on the curve</p>\n","type":"Number"},{"name":"t","description":"<p>value between 0 and 1</p>\n","type":"Number"}],"return":{"description":"the value of the Bezier at position t","type":"Number"},"example":["\n<div>\n<code>\nnoFill();\nvar x1 = 85,\n x2 = 10,\n x3 = 90,\n x4 = 15;\nvar y1 = 20,\n y2 = 10,\n y3 = 90,\n y4 = 80;\nbezier(x1, y1, x2, y2, x3, y3, x4, y4);\nfill(255);\nvar steps = 10;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = bezierPoint(x1, x2, x3, x4, t);\n var y = bezierPoint(y1, y2, y3, y4, t);\n ellipse(x, y, 5, 5);\n}\n</code>\n</div>"],"alt":"stretched black s-shape with 17 small orange lines extending from under shape.","class":"p5","module":"Shape","submodule":"Curves"},{"file":"src/core/shape/curves.js","line":194,"description":"<p>Evaluates the tangent to the Bezier at position t for points a, b, c, d.\nThe parameters a and d are the first and last points\non the curve, and b and c are the control points.\nThe final parameter t varies between 0 and 1.</p>\n","itemtype":"method","name":"bezierTangent","params":[{"name":"a","description":"<p>coordinate of first point on the curve</p>\n","type":"Number"},{"name":"b","description":"<p>coordinate of first control point</p>\n","type":"Number"},{"name":"c","description":"<p>coordinate of second control point</p>\n","type":"Number"},{"name":"d","description":"<p>coordinate of second point on the curve</p>\n","type":"Number"},{"name":"t","description":"<p>value between 0 and 1</p>\n","type":"Number"}],"return":{"description":"the tangent at position t","type":"Number"},"example":["\n<div>\n<code>\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nvar steps = 6;\nfill(255);\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n // Get the location of the point\n var x = bezierPoint(85, 10, 90, 15, t);\n var y = bezierPoint(20, 10, 90, 80, t);\n // Get the tangent points\n var tx = bezierTangent(85, 10, 90, 15, t);\n var ty = bezierTangent(20, 10, 90, 80, t);\n // Calculate an angle from the tangent points\n var a = atan2(ty, tx);\n a += PI;\n stroke(255, 102, 0);\n line(x, y, cos(a) * 30 + x, sin(a) * 30 + y);\n // The following line of code makes a line\n // inverse of the above line\n //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y);\n stroke(0);\n ellipse(x, y, 5, 5);\n}\n</code>\n</div>\n\n<div>\n<code>\nnoFill();\nbezier(85, 20, 10, 10, 90, 90, 15, 80);\nstroke(255, 102, 0);\nvar steps = 16;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = bezierPoint(85, 10, 90, 15, t);\n var y = bezierPoint(20, 10, 90, 80, t);\n var tx = bezierTangent(85, 10, 90, 15, t);\n var ty = bezierTangent(20, 10, 90, 80, t);\n var a = atan2(ty, tx);\n a -= HALF_PI;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n</code>\n</div>"],"alt":"s-shaped line with 17 short orange lines extending from underside of shape","class":"p5","module":"Shape","submodule":"Curves"},{"file":"src/core/shape/curves.js","line":273,"description":"<p>Draws a curved line on the screen between two points, given as the\nmiddle four parameters. The first two parameters are a control point, as\nif the curve came from this point even though it&#39;s not drawn. The last\ntwo parameters similarly describe the other control point. <br /><br />\nLonger curves can be created by putting a series of <a href=\"#/p5/curve\">curve()</a> functions\ntogether or using <a href=\"#/p5/curveVertex\">curveVertex()</a>. An additional function called\n<a href=\"#/p5/curveTightness\">curveTightness()</a> provides control for the visual quality of the curve.\nThe <a href=\"#/p5/curve\">curve()</a> function is an implementation of Catmull-Rom splines.</p>\n","itemtype":"method","name":"curve","chainable":1,"example":["\n<div>\n<code>\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\nstroke(0);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nstroke(255, 102, 0);\ncurve(73, 24, 73, 61, 15, 65, 15, 65);\n</code>\n</div>\n<div>\n<code>\n// Define the curve points as JavaScript objects\nvar p1 = { x: 5, y: 26 },\n p2 = { x: 73, y: 24 };\nvar p3 = { x: 73, y: 61 },\n p4 = { x: 15, y: 65 };\nnoFill();\nstroke(255, 102, 0);\ncurve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);\nstroke(0);\ncurve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y);\nstroke(255, 102, 0);\ncurve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y);\n</code>\n</div>\n<div>\n<code>\nnoFill();\nstroke(255, 102, 0);\ncurve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0);\nstroke(0);\ncurve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0);\nstroke(255, 102, 0);\ncurve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0);\n</code>\n</div>"],"alt":"horseshoe shape with orange ends facing left and black curved center.\nhorseshoe shape with orange ends facing left and black curved center.\ncurving black and orange lines.","class":"p5","module":"Shape","submodule":"Curves","overloads":[{"line":273,"params":[{"name":"x1","description":"<p>x-coordinate for the beginning control point</p>\n","type":"Number"},{"name":"y1","description":"<p>y-coordinate for the beginning control point</p>\n","type":"Number"},{"name":"x2","description":"<p>x-coordinate for the first point</p>\n","type":"Number"},{"name":"y2","description":"<p>y-coordinate for the first point</p>\n","type":"Number"},{"name":"x3","description":"<p>x-coordinate for the second point</p>\n","type":"Number"},{"name":"y3","description":"<p>y-coordinate for the second point</p>\n","type":"Number"},{"name":"x4","description":"<p>x-coordinate for the ending control point</p>\n","type":"Number"},{"name":"y4","description":"<p>y-coordinate for the ending control point</p>\n","type":"Number"}],"chainable":1},{"line":338,"params":[{"name":"x1","description":"","type":"Number"},{"name":"y1","description":"","type":"Number"},{"name":"z1","description":"<p>z-coordinate for the beginning control point</p>\n","type":"Number"},{"name":"x2","description":"","type":"Number"},{"name":"y2","description":"","type":"Number"},{"name":"z2","description":"<p>z-coordinate for the first point</p>\n","type":"Number"},{"name":"x3","description":"","type":"Number"},{"name":"y3","description":"","type":"Number"},{"name":"z3","description":"<p>z-coordinate for the second point</p>\n","type":"Number"},{"name":"x4","description":"","type":"Number"},{"name":"y4","description":"","type":"Number"},{"name":"z4","description":"<p>z-coordinate for the ending control point</p>\n","type":"Number"}],"chainable":1}]},{"file":"src/core/shape/curves.js","line":364,"description":"<p>Sets the resolution at which curves display.</p>\n<p>The default value is 20 while the minimum value is 3.</p>\n<p>This function is only useful when using the WEBGL renderer\nas the default canvas renderer does not use this\ninformation.</p>\n","itemtype":"method","name":"curveDetail","params":[{"name":"resolution","description":"<p>of the curves</p>\n","type":"Number"}],"chainable":1,"example":["\n<div modernizr='webgl'>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n curveDetail(5);\n}\nfunction draw() {\n background(200);\n\n curve(250, 600, 0, -30, 40, 0, 30, 30, 0, -250, 600, 0);\n}\n</code>\n</div>"],"alt":"white arch shape with a low level of curve detail.","class":"p5","module":"Shape","submodule":"Curves"},{"file":"src/core/shape/curves.js","line":406,"description":"<p>Modifies the quality of forms created with <a href=\"#/p5/curve\">curve()</a> and <a href=\"#/p5/curveVertex\">curveVertex()</a>.\nThe parameter tightness determines how the curve fits to the vertex\npoints. The value 0.0 is the default value for tightness (this value\ndefines the curves to be Catmull-Rom splines) and the value 1.0 connects\nall the points with straight lines. Values within the range -5.0 and 5.0\nwill deform the curves but will leave them recognizable and as values\nincrease in magnitude, they will continue to deform.</p>\n","itemtype":"method","name":"curveTightness","params":[{"name":"amount","description":"<p>of deformation from the original vertices</p>\n","type":"Number"}],"chainable":1,"example":["\n<div>\n<code>\n// Move the mouse left and right to see the curve change\n\nfunction setup() {\n createCanvas(100, 100);\n noFill();\n}\n\nfunction draw() {\n background(204);\n var t = map(mouseX, 0, width, -5, 5);\n curveTightness(t);\n beginShape();\n curveVertex(10, 26);\n curveVertex(10, 26);\n curveVertex(83, 24);\n curveVertex(83, 61);\n curveVertex(25, 65);\n curveVertex(25, 65);\n endShape();\n}\n</code>\n</div>"],"alt":"Line shaped like right-facing arrow,points move with mouse-x and warp shape.","class":"p5","module":"Shape","submodule":"Curves"},{"file":"src/core/shape/curves.js","line":453,"description":"<p>Evaluates the curve at position t for points a, b, c, d.\nThe parameter t varies between 0 and 1, a and d are control points\nof the curve, and b and c are the start and end points of the curve.\nThis can be done once with the x coordinates and a second time\nwith the y coordinates to get the location of a curve at t.</p>\n","itemtype":"method","name":"curvePoint","params":[{"name":"a","description":"<p>coordinate of first control point of the curve</p>\n","type":"Number"},{"name":"b","description":"<p>coordinate of first point</p>\n","type":"Number"},{"name":"c","description":"<p>coordinate of second point</p>\n","type":"Number"},{"name":"d","description":"<p>coordinate of second control point</p>\n","type":"Number"},{"name":"t","description":"<p>value between 0 and 1</p>\n","type":"Number"}],"return":{"description":"bezier value at position t","type":"Number"},"example":["\n<div>\n<code>\nnoFill();\ncurve(5, 26, 5, 26, 73, 24, 73, 61);\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nfill(255);\nellipseMode(CENTER);\nvar steps = 6;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = curvePoint(5, 5, 73, 73, t);\n var y = curvePoint(26, 26, 24, 61, t);\n ellipse(x, y, 5, 5);\n x = curvePoint(5, 73, 73, 15, t);\n y = curvePoint(26, 24, 61, 65, t);\n ellipse(x, y, 5, 5);\n}\n</code>\n</div>\n\nline hooking down to right-bottom with 13 5x5 white ellipse points"],"class":"p5","module":"Shape","submodule":"Curves"},{"file":"src/core/shape/curves.js","line":502,"description":"<p>Evaluates the tangent to the curve at position t for points a, b, c, d.\nThe parameter t varies between 0 and 1, a and d are points on the curve,\nand b and c are the control points.</p>\n","itemtype":"method","name":"curveTangent","params":[{"name":"a","description":"<p>coordinate of first point on the curve</p>\n","type":"Number"},{"name":"b","description":"<p>coordinate of first control point</p>\n","type":"Number"},{"name":"c","description":"<p>coordinate of second control point</p>\n","type":"Number"},{"name":"d","description":"<p>coordinate of second point on the curve</p>\n","type":"Number"},{"name":"t","description":"<p>value between 0 and 1</p>\n","type":"Number"}],"return":{"description":"the tangent at position t","type":"Number"},"example":["\n<div>\n<code>\nnoFill();\ncurve(5, 26, 73, 24, 73, 61, 15, 65);\nvar steps = 6;\nfor (var i = 0; i <= steps; i++) {\n var t = i / steps;\n var x = curvePoint(5, 73, 73, 15, t);\n var y = curvePoint(26, 24, 61, 65, t);\n //ellipse(x, y, 5, 5);\n var tx = curveTangent(5, 73, 73, 15, t);\n var ty = curveTangent(26, 24, 61, 65, t);\n var a = atan2(ty, tx);\n a -= PI / 2.0;\n line(x, y, cos(a) * 8 + x, sin(a) * 8 + y);\n}\n</code>\n</div>"],"alt":"right curving line mid-right of canvas with 7 short lines radiating from it.","class":"p5","module":"Shape","submodule":"Curves"},{"file":"src/core/shape/vertex.js","line":22,"description":"<p>Use the <a href=\"#/p5/beginContour\">beginContour()</a> and <a href=\"#/p5/endContour\">endContour()</a> functions to create negative\nshapes within shapes such as the center of the letter &#39;O&#39;. <a href=\"#/p5/beginContour\">beginContour()</a>\nbegins recording vertices for the shape and <a href=\"#/p5/endContour\">endContour()</a> stops recording.\nThe vertices that define a negative shape must &quot;wind&quot; in the opposite\ndirection from the exterior shape. First draw vertices for the exterior\nclockwise order, then for internal shapes, draw vertices\nshape in counter-clockwise.\n<br><br>\nThese functions can only be used within a <a href=\"#/p5/beginShape\">beginShape()</a>/<a href=\"#/p5/endShape\">endShape()</a> pair and\ntransformations such as <a href=\"#/p5/translate\">translate()</a>, <a href=\"#/p5/rotate\">rotate()</a>, and <a href=\"#/p5/scale\">scale()</a> do not work\nwithin a <a href=\"#/p5/beginContour\">beginContour()</a>/<a href=\"#/p5/endContour\">endContour()</a> pair. It is also not possible to use\nother shapes, such as <a href=\"#/p5/ellipse\">ellipse()</a> or <a href=\"#/p5/rect\">rect()</a> within.</p>\n","itemtype":"method","name":"beginContour","chainable":1,"example":["\n<div>\n<code>\ntranslate(50, 50);\nstroke(255, 0, 0);\nbeginShape();\n// Exterior part of shape, clockwise winding\nvertex(-40, -40);\nvertex(40, -40);\nvertex(40, 40);\nvertex(-40, 40);\n// Interior part of shape, counter-clockwise winding\nbeginContour();\nvertex(-20, -20);\nvertex(-20, 20);\nvertex(20, 20);\nvertex(20, -20);\nendContour();\nendShape(CLOSE);\n</code>\n</div>"],"alt":"white rect and smaller grey rect with red outlines in center of canvas.","class":"p5","module":"Shape","submodule":"Vertex"},{"file":"src/core/shape/vertex.js","line":70,"description":"<p>Using the <a href=\"#/p5/beginShape\">beginShape()</a> and <a href=\"#/p5/endShape\">endShape()</a> functions allow creating more\ncomplex forms. <a href=\"#/p5/beginShape\">beginShape()</a> begins recording vertices for a shape and\n<a href=\"#/p5/endShape\">endShape()</a> stops recording. The value of the kind parameter tells it which\ntypes of shapes to create from the provided vertices. With no mode\nspecified, the shape can be any irregular polygon.\n<br><br>\nThe parameters available for <a href=\"#/p5/beginShape\">beginShape()</a> are POINTS, LINES, TRIANGLES,\nTRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. After calling the\n<a href=\"#/p5/beginShape\">beginShape()</a> function, a series of <a href=\"#/p5/vertex\">vertex()</a> commands must follow. To stop\ndrawing the shape, call <a href=\"#/p5/endShape\">endShape()</a>. Each shape will be outlined with the\ncurrent stroke color and filled with the fill color.\n<br><br>\nTransformations such as <a href=\"#/p5/translate\">translate()</a>, <a href=\"#/p5/rotate\">rotate()</a>, and <a href=\"#/p5/scale\">scale()</a> do not work\nwithin <a href=\"#/p5/beginShape\">beginShape()</a>. It is also not possible to use other shapes, such as\n<a href=\"#/p5/ellipse\">ellipse()</a> or <a href=\"#/p5/rect\">rect()</a> within <a href=\"#/p5/beginShape\">beginShape()</a>.</p>\n","itemtype":"method","name":"beginShape","params":[{"name":"kind","description":"<p>either POINTS, LINES, TRIANGLES, TRIANGLE_FAN\n TRIANGLE_STRIP, QUADS, or QUAD_STRIP</p>\n","type":"Constant","optional":true}],"chainable":1,"example":["\n<div>\n<code>\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n</code>\n</div>\n\n<div>\n<code>\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nbeginShape(LINES);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nnoFill();\nbeginShape();\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape(CLOSE);\n</code>\n</div>\n\n<div>\n<code>\nbeginShape(TRIANGLES);\nvertex(30, 75);\nvertex(40, 20);\nvertex(50, 75);\nvertex(60, 20);\nvertex(70, 75);\nvertex(80, 20);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nbeginShape(TRIANGLE_STRIP);\nvertex(30, 75);\nvertex(40, 20);\nvertex(50, 75);\nvertex(60, 20);\nvertex(70, 75);\nvertex(80, 20);\nvertex(90, 75);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nbeginShape(TRIANGLE_FAN);\nvertex(57.5, 50);\nvertex(57.5, 15);\nvertex(92, 50);\nvertex(57.5, 85);\nvertex(22, 50);\nvertex(57.5, 15);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nbeginShape(QUADS);\nvertex(30, 20);\nvertex(30, 75);\nvertex(50, 75);\nvertex(50, 20);\nvertex(65, 20);\nvertex(65, 75);\nvertex(85, 75);\nvertex(85, 20);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nbeginShape(QUAD_STRIP);\nvertex(30, 20);\nvertex(30, 75);\nvertex(50, 20);\nvertex(50, 75);\nvertex(65, 20);\nvertex(65, 75);\nvertex(85, 20);\nvertex(85, 75);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nbeginShape();\nvertex(20, 20);\nvertex(40, 20);\nvertex(40, 40);\nvertex(60, 40);\nvertex(60, 60);\nvertex(20, 60);\nendShape(CLOSE);\n</code>\n</div>"],"alt":"white square-shape with black outline in middle-right of canvas.\n4 black points in a square shape in middle-right of canvas.\n2 horizontal black lines. In the top-right and bottom-right of canvas.\n3 line shape with horizontal on top, vertical in middle and horizontal bottom.\nsquare line shape in middle-right of canvas.\n2 white triangle shapes mid-right canvas. left one pointing up and right down.\n5 horizontal interlocking and alternating white triangles in mid-right canvas.\n4 interlocking white triangles in 45 degree rotated square-shape.\n2 white rectangle shapes in mid-right canvas. Both 20x55.\n3 side-by-side white rectangles center rect is smaller in mid-right canvas.\nThick white l-shape with black outline mid-top-left of canvas.","class":"p5","module":"Shape","submodule":"Vertex"},{"file":"src/core/shape/vertex.js","line":270,"description":"<p>Specifies vertex coordinates for Bezier curves. Each call to\nbezierVertex() defines the position of two control points and\none anchor point of a Bezier curve, adding a new segment to a\nline or shape. For WebGL mode bezierVertex() can be used in 2D\nas well as 3D mode. 2D mode expects 6 parameters, while 3D mode\nexpects 9 parameters (including z coordinates).\n<br><br>\nThe first time bezierVertex() is used within a <a href=\"#/p5/beginShape\">beginShape()</a>\ncall, it must be prefaced with a call to <a href=\"#/p5/vertex\">vertex()</a> to set the first anchor\npoint. This function must be used between <a href=\"#/p5/beginShape\">beginShape()</a> and <a href=\"#/p5/endShape\">endShape()</a>\nand only when there is no MODE or POINTS parameter specified to\n<a href=\"#/p5/beginShape\">beginShape()</a>.</p>\n","itemtype":"method","name":"bezierVertex","chainable":1,"example":["\n<div>\n<code>\nnoFill();\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nbeginShape();\nvertex(30, 20);\nbezierVertex(80, 0, 80, 75, 30, 75);\nbezierVertex(50, 80, 60, 25, 30, 20);\nendShape();\n</code>\n</div>"],"alt":"crescent-shaped line in middle of canvas. Points facing left.\nwhite crescent shape in middle of canvas. Points facing left.","class":"p5","module":"Shape","submodule":"Vertex","overloads":[{"line":270,"params":[{"name":"x2","description":"<p>x-coordinate for the first control point</p>\n","type":"Number"},{"name":"y2","description":"<p>y-coordinate for the first control point</p>\n","type":"Number"},{"name":"x3","description":"<p>x-coordinate for the second control point</p>\n","type":"Number"},{"name":"y3","description":"<p>y-coordinate for the second control point</p>\n","type":"Number"},{"name":"x4","description":"<p>x-coordinate for the anchor point</p>\n","type":"Number"},{"name":"y4","description":"<p>y-coordinate for the anchor point</p>\n","type":"Number"}],"chainable":1},{"line":317,"params":[{"name":"x2","description":"","type":"Number"},{"name":"y2","description":"","type":"Number"},{"name":"z2","description":"<p>z-coordinate for the first control point (for WebGL mode)</p>\n","type":"Number","optional":true},{"name":"x3","description":"","type":"Number"},{"name":"y3","description":"","type":"Number"},{"name":"z3","description":"<p>z-coordinate for the second control point (for WebGL mode)</p>\n","type":"Number","optional":true},{"name":"x4","description":"","type":"Number"},{"name":"y4","description":"","type":"Number"},{"name":"z4","description":"<p>z-coordinate for the anchor point (for WebGL mode)</p>\n","type":"Number","optional":true}],"chainable":1}]},{"file":"src/core/shape/vertex.js","line":390,"description":"<p>Specifies vertex coordinates for curves. This function may only\nbe used between <a href=\"#/p5/beginShape\">beginShape()</a> and <a href=\"#/p5/endShape\">endShape()</a> and only when there\nis no MODE parameter specified to <a href=\"#/p5/beginShape\">beginShape()</a>.\nFor WebGL mode curveVertex() can be used in 2D as well as 3D mode.\n2D mode expects 2 parameters, while 3D mode expects 3 parameters.\n<br><br>\nThe first and last points in a series of curveVertex() lines will be used to\nguide the beginning and end of a the curve. A minimum of four\npoints is required to draw a tiny curve between the second and\nthird points. Adding a fifth point with curveVertex() will draw\nthe curve between the second, third, and fourth points. The\ncurveVertex() function is an implementation of Catmull-Rom\nsplines.</p>\n","itemtype":"method","name":"curveVertex","chainable":1,"example":["\n<div>\n<code>\nstrokeWeight(5);\npoint(84, 91);\npoint(68, 19);\npoint(21, 17);\npoint(32, 91);\nstrokeWeight(1);\n\nnoFill();\nbeginShape();\ncurveVertex(84, 91);\ncurveVertex(84, 91);\ncurveVertex(68, 19);\ncurveVertex(21, 17);\ncurveVertex(32, 91);\ncurveVertex(32, 91);\nendShape();\n</code>\n</div>"],"alt":"Upside-down u-shape line, mid canvas. left point extends beyond canvas view.","class":"p5","module":"Shape","submodule":"Vertex","overloads":[{"line":390,"params":[{"name":"x","description":"<p>x-coordinate of the vertex</p>\n","type":"Number"},{"name":"y","description":"<p>y-coordinate of the vertex</p>\n","type":"Number"}],"chainable":1},{"line":435,"params":[{"name":"x","description":"","type":"Number"},{"name":"y","description":"","type":"Number"},{"name":"z","description":"<p>z-coordinate of the vertex (for WebGL mode)</p>\n","type":"Number","optional":true}],"chainable":1}]},{"file":"src/core/shape/vertex.js","line":500,"description":"<p>Use the <a href=\"#/p5/beginContour\">beginContour()</a> and <a href=\"#/p5/endContour\">endContour()</a> functions to create negative\nshapes within shapes such as the center of the letter &#39;O&#39;. <a href=\"#/p5/beginContour\">beginContour()</a>\nbegins recording vertices for the shape and <a href=\"#/p5/endContour\">endContour()</a> stops recording.\nThe vertices that define a negative shape must &quot;wind&quot; in the opposite\ndirection from the exterior shape. First draw vertices for the exterior\nclockwise order, then for internal shapes, draw vertices\nshape in counter-clockwise.\n<br><br>\nThese functions can only be used within a <a href=\"#/p5/beginShape\">beginShape()</a>/<a href=\"#/p5/endShape\">endShape()</a> pair and\ntransformations such as <a href=\"#/p5/translate\">translate()</a>, <a href=\"#/p5/rotate\">rotate()</a>, and <a href=\"#/p5/scale\">scale()</a> do not work\nwithin a <a href=\"#/p5/beginContour\">beginContour()</a>/<a href=\"#/p5/endContour\">endContour()</a> pair. It is also not possible to use\nother shapes, such as <a href=\"#/p5/ellipse\">ellipse()</a> or <a href=\"#/p5/rect\">rect()</a> within.</p>\n","itemtype":"method","name":"endContour","chainable":1,"example":["\n<div>\n<code>\ntranslate(50, 50);\nstroke(255, 0, 0);\nbeginShape();\n// Exterior part of shape, clockwise winding\nvertex(-40, -40);\nvertex(40, -40);\nvertex(40, 40);\nvertex(-40, 40);\n// Interior part of shape, counter-clockwise winding\nbeginContour();\nvertex(-20, -20);\nvertex(-20, 20);\nvertex(20, 20);\nvertex(20, -20);\nendContour();\nendShape(CLOSE);\n</code>\n</div>"],"alt":"white rect and smaller grey rect with red outlines in center of canvas.","class":"p5","module":"Shape","submodule":"Vertex"},{"file":"src/core/shape/vertex.js","line":560,"description":"<p>The <a href=\"#/p5/endShape\">endShape()</a> function is the companion to <a href=\"#/p5/beginShape\">beginShape()</a> and may only be\ncalled after <a href=\"#/p5/beginShape\">beginShape()</a>. When <a href=\"#/p5/endshape\">endshape()</a> is called, all of image data\ndefined since the previous call to <a href=\"#/p5/beginShape\">beginShape()</a> is written into the image\nbuffer. The constant CLOSE as the value for the MODE parameter to close\nthe shape (to connect the beginning and the end).</p>\n","itemtype":"method","name":"endShape","params":[{"name":"mode","description":"<p>use CLOSE to close the shape</p>\n","type":"Constant","optional":true}],"chainable":1,"example":["\n<div>\n<code>\nnoFill();\n\nbeginShape();\nvertex(20, 20);\nvertex(45, 20);\nvertex(45, 80);\nendShape(CLOSE);\n\nbeginShape();\nvertex(50, 20);\nvertex(75, 20);\nvertex(75, 80);\nendShape();\n</code>\n</div>"],"alt":"Triangle line shape with smallest interior angle on bottom and upside-down L.","class":"p5","module":"Shape","submodule":"Vertex"},{"file":"src/core/shape/vertex.js","line":646,"description":"<p>Specifies vertex coordinates for quadratic Bezier curves. Each call to\nquadraticVertex() defines the position of one control points and one\nanchor point of a Bezier curve, adding a new segment to a line or shape.\nThe first time quadraticVertex() is used within a <a href=\"#/p5/beginShape\">beginShape()</a> call, it\nmust be prefaced with a call to <a href=\"#/p5/vertex\">vertex()</a> to set the first anchor point.\nFor WebGL mode quadraticVertex() can be used in 2D as well as 3D mode.\n2D mode expects 4 parameters, while 3D mode expects 6 parameters\n(including z coordinates).\n<br><br>\nThis function must be used between <a href=\"#/p5/beginShape\">beginShape()</a> and <a href=\"#/p5/endShape\">endShape()</a>\nand only when there is no MODE or POINTS parameter specified to\n<a href=\"#/p5/beginShape\">beginShape()</a>.</p>\n","itemtype":"method","name":"quadraticVertex","chainable":1,"example":["\n<div>\n<code>\nstrokeWeight(5);\npoint(20, 20);\npoint(80, 20);\npoint(50, 50);\n\nnoFill();\nstrokeWeight(1);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nendShape();\n</code>\n</div>\n\n<div>\n<code>\nstrokeWeight(5);\npoint(20, 20);\npoint(80, 20);\npoint(50, 50);\n\npoint(20, 80);\npoint(80, 80);\npoint(80, 60);\n\nnoFill();\nstrokeWeight(1);\nbeginShape();\nvertex(20, 20);\nquadraticVertex(80, 20, 50, 50);\nquadraticVertex(20, 80, 80, 80);\nvertex(80, 60);\nendShape();\n</code>\n</div>"],"alt":"arched-shaped black line with 4 pixel thick stroke weight.\nbackwards s-shaped black line with 4 pixel thick stroke weight.","class":"p5","module":"Shape","submodule":"Vertex","overloads":[{"line":646,"params":[{"name":"cx","description":"<p>x-coordinate for the control point</p>\n","type":"Number"},{"name":"cy","description":"<p>y-coordinate for the control point</p>\n","type":"Number"},{"name":"x3","description":"<p>x-coordinate for the anchor point</p>\n","type":"Number"},{"name":"y3","description":"<p>y-coordinate for the anchor point</p>\n","type":"Number"}],"chainable":1},{"line":709,"params":[{"name":"cx","description":"","type":"Number"},{"name":"cy","description":"","type":"Number"},{"name":"cz","description":"<p>z-coordinate for the control point (for WebGL mode)</p>\n","type":"Number","optional":true},{"name":"x3","description":"","type":"Number"},{"name":"y3","description":"","type":"Number"},{"name":"z3","description":"<p>z-coordinate for the anchor point (for WebGL mode)</p>\n","type":"Number","optional":true}],"chainable":1}]},{"file":"src/core/shape/vertex.js","line":800,"description":"<p>All shapes are constructed by connecting a series of vertices. <a href=\"#/p5/vertex\">vertex()</a>\nis used to specify the vertex coordinates for points, lines, triangles,\nquads, and polygons. It is used exclusively within the <a href=\"#/p5/beginShape\">beginShape()</a> and\n<a href=\"#/p5/endShape\">endShape()</a> functions.</p>\n","itemtype":"method","name":"vertex","chainable":1,"example":["\n<div>\n<code>\nstrokeWeight(3);\nbeginShape(POINTS);\nvertex(30, 20);\nvertex(85, 20);\nvertex(85, 75);\nvertex(30, 75);\nendShape();\n</code>\n</div>"],"alt":"8 points making 4 lines","class":"p5","module":"Shape","submodule":"Vertex","overloads":[{"line":800,"params":[{"name":"x","description":"<p>x-coordinate of the vertex</p>\n","type":"Number"},{"name":"y","description":"<p>y-coordinate of the vertex</p>\n","type":"Number"}],"chainable":1},{"line":887,"params":[{"name":"x","description":"","type":"Number"},{"name":"y","description":"","type":"Number"},{"name":"z","description":"<p>z-coordinate of the vertex</p>\n","type":"Number"},{"name":"u","description":"<p>the vertex&#39;s texture u-coordinate</p>\n","type":"Number","optional":true},{"name":"v","description":"<p>the vertex&#39;s texture v-coordinate</p>\n","type":"Number","optional":true}],"chainable":1}]},{"file":"src/core/constants.js","line":13,"itemtype":"property","name":"P2D","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":18,"itemtype":"property","name":"WEBGL","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":25,"itemtype":"property","name":"ARROW","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":30,"itemtype":"property","name":"CROSS","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":35,"itemtype":"property","name":"HAND","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":40,"itemtype":"property","name":"MOVE","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":45,"itemtype":"property","name":"TEXT","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":50,"itemtype":"property","name":"WAIT","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":58,"description":"<p>HALF_PI is a mathematical constant with the value\n1.57079632679489661923. It is half the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions <a href=\"#/p5/sin\">sin()</a> and <a href=\"#/p5/cos\">cos()</a>.</p>\n","itemtype":"property","name":"HALF_PI","type":"Number","final":1,"example":["\n<div><code>\narc(50, 50, 80, 80, 0, HALF_PI);\n</code></div>"],"alt":"80x80 white quarter-circle with curve toward bottom right of canvas.","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":77,"description":"<p>PI is a mathematical constant with the value\n3.14159265358979323846. It is the ratio of the circumference\nof a circle to its diameter. It is useful in combination with\nthe trigonometric functions <a href=\"#/p5/sin\">sin()</a> and <a href=\"#/p5/cos\">cos()</a>.</p>\n","itemtype":"property","name":"PI","type":"Number","final":1,"example":["\n<div><code>\narc(50, 50, 80, 80, 0, PI);\n</code></div>"],"alt":"white half-circle with curve toward bottom of canvas.","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":96,"description":"<p>QUARTER_PI is a mathematical constant with the value 0.7853982.\nIt is one quarter the ratio of the circumference of a circle to\nits diameter. It is useful in combination with the trigonometric\nfunctions <a href=\"#/p5/sin\">sin()</a> and <a href=\"#/p5/cos\">cos()</a>.</p>\n","itemtype":"property","name":"QUARTER_PI","type":"Number","final":1,"example":["\n<div><code>\narc(50, 50, 80, 80, 0, QUARTER_PI);\n</code></div>"],"alt":"white eighth-circle rotated about 40 degrees with curve bottom right canvas.","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":115,"description":"<p>TAU is an alias for TWO_PI, a mathematical constant with the\nvalue 6.28318530717958647693. It is twice the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions <a href=\"#/p5/sin\">sin()</a> and <a href=\"#/p5/cos\">cos()</a>.</p>\n","itemtype":"property","name":"TAU","type":"Number","final":1,"example":["\n<div><code>\narc(50, 50, 80, 80, 0, TAU);\n</code></div>"],"alt":"80x80 white ellipse shape in center of canvas.","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":134,"description":"<p>TWO_PI is a mathematical constant with the value\n6.28318530717958647693. It is twice the ratio of the\ncircumference of a circle to its diameter. It is useful in\ncombination with the trigonometric functions <a href=\"#/p5/sin\">sin()</a> and <a href=\"#/p5/cos\">cos()</a>.</p>\n","itemtype":"property","name":"TWO_PI","type":"Number","final":1,"example":["\n<div><code>\narc(50, 50, 80, 80, 0, TWO_PI);\n</code></div>"],"alt":"80x80 white ellipse shape in center of canvas.","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":153,"description":"<p>Constant to be used with <a href=\"#/p5/angleMode\">angleMode()</a> function, to set the mode which\np5.js interprates and calculates angles (either DEGREES or RADIANS).</p>\n","itemtype":"property","name":"DEGREES","type":"String","final":1,"example":["\n<div class='norender'><code>\nfunction setup() {\n angleMode(DEGREES);\n}\n</code></div>"],"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":167,"description":"<p>Constant to be used with <a href=\"#/p5/angleMode\">angleMode()</a> function, to set the mode which\np5.js interprates and calculates angles (either RADIANS or DEGREES).</p>\n","itemtype":"property","name":"RADIANS","type":"String","final":1,"example":["\n<div class='norender'><code>\nfunction setup() {\n angleMode(RADIANS);\n}\n</code></div>"],"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":185,"itemtype":"property","name":"CORNER","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":190,"itemtype":"property","name":"CORNERS","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":195,"itemtype":"property","name":"RADIUS","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":200,"itemtype":"property","name":"RIGHT","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":205,"itemtype":"property","name":"LEFT","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":210,"itemtype":"property","name":"CENTER","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":215,"itemtype":"property","name":"TOP","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":220,"itemtype":"property","name":"BOTTOM","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":225,"itemtype":"property","name":"BASELINE","type":"String","final":1,"default":"alphabetic","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":231,"itemtype":"property","name":"POINTS","type":"Number","final":1,"default":"0x0000","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":237,"itemtype":"property","name":"LINES","type":"Number","final":1,"default":"0x0001","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":243,"itemtype":"property","name":"LINE_STRIP","type":"Number","final":1,"default":"0x0003","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":249,"itemtype":"property","name":"LINE_LOOP","type":"Number","final":1,"default":"0x0002","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":255,"itemtype":"property","name":"TRIANGLES","type":"Number","final":1,"default":"0x0004","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":261,"itemtype":"property","name":"TRIANGLE_FAN","type":"Number","final":1,"default":"0x0006","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":267,"itemtype":"property","name":"TRIANGLE_STRIP","type":"Number","final":1,"default":"0x0005","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":273,"itemtype":"property","name":"QUADS","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":278,"itemtype":"property","name":"QUAD_STRIP","type":"String","final":1,"default":"quad_strip","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":284,"itemtype":"property","name":"CLOSE","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":289,"itemtype":"property","name":"OPEN","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":294,"itemtype":"property","name":"CHORD","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":299,"itemtype":"property","name":"PIE","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":304,"itemtype":"property","name":"PROJECT","type":"String","final":1,"default":"square","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":310,"itemtype":"property","name":"SQUARE","type":"String","final":1,"default":"butt","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":316,"itemtype":"property","name":"ROUND","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":321,"itemtype":"property","name":"BEVEL","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":326,"itemtype":"property","name":"MITER","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":333,"itemtype":"property","name":"RGB","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":338,"itemtype":"property","name":"HSB","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":343,"itemtype":"property","name":"HSL","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":350,"itemtype":"property","name":"AUTO","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":373,"itemtype":"property","name":"BLEND","type":"String","final":1,"default":"source-over","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":379,"itemtype":"property","name":"ADD","type":"String","final":1,"default":"lighter","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":387,"itemtype":"property","name":"DARKEST","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":392,"itemtype":"property","name":"LIGHTEST","type":"String","final":1,"default":"lighten","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":398,"itemtype":"property","name":"DIFFERENCE","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":403,"itemtype":"property","name":"EXCLUSION","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":408,"itemtype":"property","name":"MULTIPLY","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":413,"itemtype":"property","name":"SCREEN","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":418,"itemtype":"property","name":"REPLACE","type":"String","final":1,"default":"copy","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":424,"itemtype":"property","name":"OVERLAY","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":429,"itemtype":"property","name":"HARD_LIGHT","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":434,"itemtype":"property","name":"SOFT_LIGHT","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":439,"itemtype":"property","name":"DODGE","type":"String","final":1,"default":"color-dodge","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":445,"itemtype":"property","name":"BURN","type":"String","final":1,"default":"color-burn","class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":453,"itemtype":"property","name":"THRESHOLD","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":458,"itemtype":"property","name":"GRAY","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":463,"itemtype":"property","name":"OPAQUE","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":468,"itemtype":"property","name":"INVERT","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":473,"itemtype":"property","name":"POSTERIZE","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":478,"itemtype":"property","name":"DILATE","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":483,"itemtype":"property","name":"ERODE","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":488,"itemtype":"property","name":"BLUR","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":495,"itemtype":"property","name":"NORMAL","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":500,"itemtype":"property","name":"ITALIC","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":505,"itemtype":"property","name":"BOLD","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":536,"itemtype":"property","name":"LANDSCAPE","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":541,"itemtype":"property","name":"PORTRAIT","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":551,"itemtype":"property","name":"GRID","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/constants.js","line":557,"itemtype":"property","name":"AXES","type":"String","final":1,"class":"p5","module":"Constants","submodule":"Constants"},{"file":"src/core/environment.js","line":22,"description":"<p>The <a href=\"#/p5/print\">print()</a> function writes to the console area of your browser.\nThis function is often helpful for looking at the data a program is\nproducing. This function creates a new line of text for each call to\nthe function. Individual elements can be\nseparated with quotes (&quot;&quot;) and joined with the addition operator (+).</p>\n","itemtype":"method","name":"print","params":[{"name":"contents","description":"<p>any combination of Number, String, Object, Boolean,\n Array to print</p>\n","type":"Any"}],"example":["\n<div><code class='norender'>\nvar x = 10;\nprint('The value of x is ' + x);\n// prints \"The value of x is 10\"\n</code></div>"],"alt":"default grey canvas","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":49,"description":"<p>The system variable <a href=\"#/p5/frameCount\">frameCount</a> contains the number of frames that have\nbeen displayed since the program started. Inside <a href=\"#/p5/setup\">setup()</a> the value is 0,\nafter the first iteration of draw it is 1, etc.</p>\n","itemtype":"property","name":"frameCount","type":"Integer","readonly":"","example":["\n <div><code>\nfunction setup() {\n frameRate(30);\n textSize(30);\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(200);\n text(frameCount, width / 2, height / 2);\n}\n</code></div>"],"alt":"numbers rapidly counting upward with frame count set to 30.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":76,"description":"<p>Confirms if the window a p5.js program is in is &quot;focused,&quot; meaning that\nthe sketch will accept mouse or keyboard input. This variable is\n&quot;true&quot; if the window is focused and &quot;false&quot; if not.</p>\n","itemtype":"property","name":"focused","type":"Boolean","readonly":"","example":["\n<div><code>\n// To demonstrate, put two windows side by side.\n// Click on the window that the p5 sketch isn't in!\nfunction draw() {\n background(200);\n noStroke();\n fill(0, 200, 0);\n ellipse(25, 25, 50, 50);\n\n if (!focused) {\n // or \"if (focused === false)\"\n stroke(200, 0, 0);\n line(0, 0, 100, 100);\n line(100, 0, 0, 100);\n }\n}\n</code></div>"],"alt":"green 50x50 ellipse at top left. Red X covers canvas when page focus changes","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":108,"description":"<p>Sets the cursor to a predefined symbol or an image, or makes it visible\nif already hidden. If you are trying to set an image as the cursor, the\nrecommended size is 16x16 or 32x32 pixels. The values for parameters x and y\nmust be less than the dimensions of the image.</p>\n","itemtype":"method","name":"cursor","params":[{"name":"type","description":"<p>either ARROW, CROSS, HAND, MOVE, TEXT, or\n WAIT, or path for image</p>\n","type":"String|Constant"},{"name":"x","description":"<p>the horizontal active spot of the cursor</p>\n","type":"Number","optional":true},{"name":"y","description":"<p>the vertical active spot of the cursor</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\n// Move the mouse left and right across the image\n// to see the cursor change from a cross to a hand\nfunction draw() {\n line(width / 2, 0, width / 2, height);\n if (mouseX < 50) {\n cursor(CROSS);\n } else {\n cursor(HAND);\n }\n}\n</code></div>"],"alt":"horizontal line divides canvas. cursor on left is a cross, right is hand.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":167,"description":"<p>Specifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within <a href=\"#/p5/setup\">setup()</a> is\nrecommended. The default frame rate is based on the frame rate of the display\n(here also called &quot;refresh rate&quot;), which is set to 60 frames per second on most\ncomputers. A frame rate of 24 frames per second (usual for movies) or above\nwill be enough for smooth animations\nThis is the same as setFrameRate(val).\n<br><br>\nCalling <a href=\"#/p5/frameRate\">frameRate()</a> with no arguments returns the current framerate. The\ndraw function must run at least once before it will return a value. This\nis the same as <a href=\"#/p5/getFrameRate\">getFrameRate()</a>.\n<br><br>\nCalling <a href=\"#/p5/frameRate\">frameRate()</a> with arguments that are not of the type numbers\nor are non positive also returns current framerate.</p>\n","itemtype":"method","name":"frameRate","chainable":1,"example":["\n\n<div><code>\nvar rectX = 0;\nvar fr = 30; //starting FPS\nvar clr;\n\nfunction setup() {\n background(200);\n frameRate(fr); // Attempt to refresh at starting FPS\n clr = color(255, 0, 0);\n}\n\nfunction draw() {\n background(200);\n rectX = rectX += 1; // Move Rectangle\n\n if (rectX >= width) {\n // If you go off screen.\n if (fr === 30) {\n clr = color(0, 0, 255);\n fr = 10;\n frameRate(fr); // make frameRate 10 FPS\n } else {\n clr = color(255, 0, 0);\n fr = 30;\n frameRate(fr); // make frameRate 30 FPS\n }\n rectX = 0;\n }\n fill(clr);\n rect(rectX, 40, 20, 20);\n}\n</code></div>"],"alt":"blue rect moves left to right, followed by red rect moving faster. Loops.","class":"p5","module":"Environment","submodule":"Environment","overloads":[{"line":167,"params":[{"name":"fps","description":"<p>number of frames to be displayed every second</p>\n","type":"Number"}],"chainable":1},{"line":228,"params":[],"return":{"description":"current frameRate","type":"Number"}}]},{"file":"src/core/environment.js","line":268,"description":"<p>Hides the cursor from view.</p>\n","itemtype":"method","name":"noCursor","example":["\n<div><code>\nfunction setup() {\n noCursor();\n}\n\nfunction draw() {\n background(200);\n ellipse(mouseX, mouseY, 10, 10);\n}\n</code></div>"],"alt":"cursor becomes 10x 10 white ellipse the moves with mouse x and y.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":293,"description":"<p>System variable that stores the width of the screen display according to The\ndefault <a href=\"#/p5/pixelDensity\">pixelDensity</a>. This is used to run a\nfull-screen program on any display size. To return actual screen size,\nmultiply this by pixelDensity.</p>\n","itemtype":"property","name":"displayWidth","type":"Number","readonly":"","example":["\n<div class=\"norender\"><code>\ncreateCanvas(displayWidth, displayHeight);\n</code></div>"],"alt":"cursor becomes 10x 10 white ellipse the moves with mouse x and y.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":312,"description":"<p>System variable that stores the height of the screen display according to The\ndefault <a href=\"#/p5/pixelDensity\">pixelDensity</a>. This is used to run a\nfull-screen program on any display size. To return actual screen size,\nmultiply this by pixelDensity.</p>\n","itemtype":"property","name":"displayHeight","type":"Number","readonly":"","example":["\n<div class=\"norender\"><code>\ncreateCanvas(displayWidth, displayHeight);\n</code></div>"],"alt":"no display.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":331,"description":"<p>System variable that stores the width of the inner window, it maps to\nwindow.innerWidth.</p>\n","itemtype":"property","name":"windowWidth","type":"Number","readonly":"","example":["\n<div class=\"norender\"><code>\ncreateCanvas(windowWidth, windowHeight);\n</code></div>"],"alt":"no display.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":347,"description":"<p>System variable that stores the height of the inner window, it maps to\nwindow.innerHeight.</p>\n","itemtype":"property","name":"windowHeight","type":"Number","readonly":"","example":["\n<div class=\"norender\"><code>\ncreateCanvas(windowWidth, windowHeight);\n</code></div>"],"alt":"no display.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":363,"description":"<p>The <a href=\"#/p5/windowResized\">windowResized()</a> function is called once every time the browser window\nis resized. This is a good place to resize the canvas or do any other\nadjustments to accommodate the new window size.</p>\n","itemtype":"method","name":"windowResized","example":["\n<div class=\"norender\"><code>\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n}\n\nfunction draw() {\n background(0, 100, 200);\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n</code></div>"],"alt":"no display.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":417,"description":"<p>System variable that stores the width of the drawing canvas. This value\nis set by the first parameter of the <a href=\"#/p5/createCanvas\">createCanvas()</a> function.\nFor example, the function call createCanvas(320, 240) sets the width\nvariable to the value 320. The value of width defaults to 100 if\n<a href=\"#/p5/createCanvas\">createCanvas()</a> is not used in a program.</p>\n","itemtype":"property","name":"width","type":"Number","readonly":"","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":429,"description":"<p>System variable that stores the height of the drawing canvas. This value\nis set by the second parameter of the <a href=\"#/p5/createCanvas\">createCanvas()</a> function. For\nexample, the function call createCanvas(320, 240) sets the height\nvariable to the value 240. The value of height defaults to 100 if\n<a href=\"#/p5/createCanvas\">createCanvas()</a> is not used in a program.</p>\n","itemtype":"property","name":"height","type":"Number","readonly":"","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":441,"description":"<p>If argument is given, sets the sketch to fullscreen or not based on the\nvalue of the argument. If no argument is given, returns the current\nfullscreen state. Note that due to browser restrictions this can only\nbe called on user input, for example, on mouse press like the example\nbelow.</p>\n","itemtype":"method","name":"fullscreen","params":[{"name":"val","description":"<p>whether the sketch should be in fullscreen mode\nor not</p>\n","type":"Boolean","optional":true}],"return":{"description":"current fullscreen state","type":"Boolean"},"example":["\n<div>\n<code>\n// Clicking in the box toggles fullscreen on and off.\nfunction setup() {\n background(200);\n}\nfunction mousePressed() {\n if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) {\n var fs = fullscreen();\n fullscreen(!fs);\n }\n}\n</code>\n</div>"],"alt":"no display.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":492,"description":"<p>Sets the pixel scaling for high pixel density displays. By default\npixel density is set to match display density, call pixelDensity(1)\nto turn this off. Calling <a href=\"#/p5/pixelDensity\">pixelDensity()</a> with no arguments returns\nthe current pixel density of the sketch.</p>\n","itemtype":"method","name":"pixelDensity","chainable":1,"example":["\n<div>\n<code>\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n</code>\n</div>\n<div>\n<code>\nfunction setup() {\n pixelDensity(3.0);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n</code>\n</div>"],"alt":"fuzzy 50x50 white ellipse with black outline in center of canvas.\nsharp 50x50 white ellipse with black outline in center of canvas.","class":"p5","module":"Environment","submodule":"Environment","overloads":[{"line":492,"params":[{"name":"val","description":"<p>whether or how much the sketch should scale</p>\n","type":"Number"}],"chainable":1},{"line":527,"params":[],"return":{"description":"current pixel density of the sketch","type":"Number"}}]},{"file":"src/core/environment.js","line":547,"description":"<p>Returns the pixel density of the current display the sketch is running on.</p>\n","itemtype":"method","name":"displayDensity","return":{"description":"current pixel density of the display","type":"Number"},"example":["\n<div>\n<code>\nfunction setup() {\n var density = displayDensity();\n pixelDensity(density);\n createCanvas(100, 100);\n background(200);\n ellipse(width / 2, height / 2, 50, 50);\n}\n</code>\n</div>"],"alt":"50x50 white ellipse with black outline in center of canvas.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":604,"description":"<p>Gets the current URL.</p>\n","itemtype":"method","name":"getURL","return":{"description":"url","type":"String"},"example":["\n<div>\n<code>\nvar url;\nvar x = 100;\n\nfunction setup() {\n fill(0);\n noStroke();\n url = getURL();\n}\n\nfunction draw() {\n background(200);\n text(url, x, height / 2);\n x--;\n}\n</code>\n</div>"],"alt":"current url (http://p5js.org/reference/#/p5/getURL) moves right to left.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":635,"description":"<p>Gets the current URL path as an array.</p>\n","itemtype":"method","name":"getURLPath","return":{"description":"path components","type":"String[]"},"example":["\n<div class='norender'><code>\nfunction setup() {\n var urlPath = getURLPath();\n for (var i = 0; i < urlPath.length; i++) {\n text(urlPath[i], 10, i * 20 + 20);\n }\n}\n</code></div>"],"alt":"no display","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/environment.js","line":658,"description":"<p>Gets the current URL params as an Object.</p>\n","itemtype":"method","name":"getURLParams","return":{"description":"URL params","type":"Object"},"example":["\n<div class='norender notest'>\n<code>\n// Example: http://p5js.org?year=2014&month=May&day=15\n\nfunction setup() {\n var params = getURLParams();\n text(params.day, 10, 20);\n text(params.month, 10, 40);\n text(params.year, 10, 60);\n}\n</code>\n</div>"],"alt":"no display.","class":"p5","module":"Environment","submodule":"Environment"},{"file":"src/core/error_helpers.js","line":1,"requires":["core"],"class":"p5","module":"Environment"},{"file":"src/core/error_helpers.js","line":563,"description":"<p>Validates parameters\nparam {String} func the name of the function\nparam {Array} args user input arguments</p>\n<p>example:\n var a;\n ellipse(10,10,a,5);\nconsole ouput:\n &quot;It looks like ellipse received an empty variable in spot #2.&quot;</p>\n<p>example:\n ellipse(10,&quot;foo&quot;,5,5);\nconsole output:\n &quot;ellipse was expecting a number for parameter #1,\n received &quot;foo&quot; instead.&quot;</p>\n","class":"p5","module":"Environment"},{"file":"src/core/error_helpers.js","line":624,"description":"<p>Prints out all the colors in the color pallete with white text.\nFor color blindness testing.</p>\n","class":"p5","module":"Environment"},{"file":"src/core/helpers.js","line":1,"requires":["constants"],"class":"p5","module":"Environment"},{"file":"src/core/legacy.js","line":1,"requires":["core\nThese are functions that are part of the Processing API but are not part of\nthe p5.js API. In some cases they have a new name","in others","they are\nremoved completely. Not all unsupported Processing functions are listed here\nbut we try to include ones that a user coming from Processing might likely\ncall."],"class":"p5","module":"Environment"},{"file":"src/core/main.js","line":49,"description":"<p>Called directly before <a href=\"#/p5/setup\">setup()</a>, the <a href=\"#/p5/preload\">preload()</a> function is used to handle\nasynchronous loading of external files in a blocking way. If a preload\nfunction is defined, <a href=\"#/p5/setup\">setup()</a> will wait until any load calls within have\nfinished. Nothing besides load calls (<a href=\"#/p5/loadImage\">loadImage</a>, <a href=\"#/p5/loadJSON\">loadJSON</a>, <a href=\"#/p5/loadFont\">loadFont</a>,\n<a href=\"#/p5/loadStrings\">loadStrings</a>, etc.) should be inside the preload function. If asynchronous\nloading is preferred, the load methods can instead be called in <a href=\"#/p5/setup\">setup()</a>\nor anywhere else with the use of a callback parameter.\n<br><br>\nBy default the text &quot;loading...&quot; will be displayed. To make your own\nloading page, include an HTML element with id &quot;p5_loading&quot; in your\npage. More information <a href=\"http://bit.ly/2kQ6Nio\">here</a>.</p>\n","itemtype":"method","name":"preload","example":["\n<div><code>\nvar img;\nvar c;\nfunction preload() {\n // preload() runs once\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n // setup() waits until preload() is done\n img.loadPixels();\n // get color of middle pixel\n c = img.get(img.width / 2, img.height / 2);\n}\n\nfunction draw() {\n background(c);\n image(img, 25, 25, 50, 50);\n}\n</code></div>"],"alt":"nothing displayed","class":"p5","module":"Structure","submodule":"Structure"},{"file":"src/core/main.js","line":90,"description":"<p>The <a href=\"#/p5/setup\">setup()</a> function is called once when the program starts. It&#39;s used to\ndefine initial environment properties such as screen size and background\ncolor and to load media such as images and fonts as the program starts.\nThere can only be one <a href=\"#/p5/setup\">setup()</a> function for each program and it shouldn&#39;t\nbe called again after its initial execution.\n<br><br>\nNote: Variables declared within <a href=\"#/p5/setup\">setup()</a> are not accessible within other\nfunctions, including <a href=\"#/p5/draw\">draw()</a>.</p>\n","itemtype":"method","name":"setup","example":["\n<div><code>\nvar a = 0;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(102);\n}\n\nfunction draw() {\n rect(a++ % width, 10, 2, 80);\n}\n</code></div>"],"alt":"nothing displayed","class":"p5","module":"Structure","submodule":"Structure"},{"file":"src/core/main.js","line":121,"description":"<p>Called directly after <a href=\"#/p5/setup\">setup()</a>, the <a href=\"#/p5/draw\">draw()</a> function continuously executes\nthe lines of code contained inside its block until the program is stopped\nor <a href=\"#/p5/noLoop\">noLoop()</a> is called. Note if <a href=\"#/p5/noLoop\">noLoop()</a> is called in <a href=\"#/p5/setup\">setup()</a>, <a href=\"#/p5/draw\">draw()</a> will\nstill be executed once before stopping. <a href=\"#/p5/draw\">draw()</a> is called automatically and\nshould never be called explicitly.\n<br><br>\nIt should always be controlled with <a href=\"#/p5/noLoop\">noLoop()</a>, <a href=\"#/p5/redraw\">redraw()</a> and <a href=\"#/p5/loop\">loop()</a>. After\n<a href=\"#/p5/noLoop\">noLoop()</a> stops the code in <a href=\"#/p5/draw\">draw()</a> from executing, <a href=\"#/p5/redraw\">redraw()</a> causes the\ncode inside <a href=\"#/p5/draw\">draw()</a> to execute once, and <a href=\"#/p5/loop\">loop()</a> will cause the code\ninside <a href=\"#/p5/draw\">draw()</a> to resume executing continuously.\n<br><br>\nThe number of times <a href=\"#/p5/draw\">draw()</a> executes in each second may be controlled with\nthe <a href=\"#/p5/frameRate\">frameRate()</a> function.\n<br><br>\nThere can only be one <a href=\"#/p5/draw\">draw()</a> function for each sketch, and <a href=\"#/p5/draw\">draw()</a> must\nexist if you want the code to run continuously, or to process events such\nas <a href=\"#/p5/mousePressed\">mousePressed()</a>. Sometimes, you might have an empty call to <a href=\"#/p5/draw\">draw()</a> in\nyour program, as shown in the above example.\n<br><br>\nIt is important to note that the drawing coordinate system will be reset\nat the beginning of each <a href=\"#/p5/draw\">draw()</a> call. If any transformations are performed\nwithin <a href=\"#/p5/draw\">draw()</a> (ex: scale, rotate, translate), their effects will be\nundone at the beginning of <a href=\"#/p5/draw\">draw()</a>, so transformations will not accumulate\nover time. On the other hand, styling applied (ex: fill, stroke, etc) will\nremain in effect.</p>\n","itemtype":"method","name":"draw","example":["\n<div><code>\nvar yPos = 0;\nfunction setup() {\n // setup() runs once\n frameRate(30);\n}\nfunction draw() {\n // draw() loops forever, until stopped\n background(204);\n yPos = yPos - 1;\n if (yPos < 0) {\n yPos = height;\n }\n line(0, yPos, width, yPos);\n}\n</code></div>"],"alt":"nothing displayed","class":"p5","module":"Structure","submodule":"Structure"},{"file":"src/core/main.js","line":408,"description":"<p>Removes the entire p5 sketch. This will remove the canvas and any\nelements created by p5.js. It will also stop the draw loop and unbind\nany properties or methods from the window global scope. It will\nleave a variable p5 in case you wanted to create a new p5 sketch.\nIf you like, you can set p5 = null to erase it. While all functions and\nvariables and objects created by the p5 library will be removed, any\nother global variables created by your code will remain.</p>\n","itemtype":"method","name":"remove","example":["\n<div class='norender'><code>\nfunction draw() {\n ellipse(50, 50, 10, 10);\n}\n\nfunction mousePressed() {\n remove(); // remove whole sketch on mouse press\n}\n</code></div>"],"alt":"nothing displayed","class":"p5","module":"Structure","submodule":"Structure"},{"file":"src/core/p5.Element.js","line":26,"description":"<p>Underlying HTML element. All normal HTML methods can be called on this.</p>\n","example":["\n<div>\n<code>\ncreateCanvas(300, 500);\nbackground(0, 0, 0, 0);\nvar input = createInput();\ninput.position(20, 225);\nvar inputElem = new p5.Element(input.elt);\ninputElem.style('width:450px;');\ninputElem.value('some string');\n</code>\n</div>"],"itemtype":"property","name":"elt","readonly":"","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":51,"description":"<p>Attaches the element to the parent specified. A way of setting\n the container for the element. Accepts either a string ID, DOM\n node, or <a href=\"#/p5.Element\">p5.Element</a>. If no arguments given, parent node is returned.\n For more ways to position the canvas, see the\n <a href='https://github.com/processing/p5.js/wiki/Positioning-your-canvas'>\n positioning the canvas</a> wiki page.</p>\n","itemtype":"method","name":"parent","chainable":1,"example":["\n <div class=\"norender notest\"><code>\n // in the html file:\n // &lt;div id=\"myContainer\">&lt;/div>\n// in the js file:\n var cnv = createCanvas(100, 100);\n cnv.parent('myContainer');\n </code></div>\n <div class='norender'><code>\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div1.parent(div0); // use p5.Element\n </code></div>\n <div class='norender'><code>\n var div0 = createDiv('this is the parent');\n div0.id('apples');\n var div1 = createDiv('this is the child');\n div1.parent('apples'); // use id\n </code></div>\n <div class='norender notest'><code>\n var elt = document.getElementById('myParentDiv');\n var div1 = createDiv('this is the child');\n div1.parent(elt); // use element from page\n </code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM","overloads":[{"line":51,"params":[{"name":"parent","description":"<p>the ID, DOM node, or <a href=\"#/p5.Element\">p5.Element</a>\n of desired parent element</p>\n","type":"String|p5.Element|Object"}],"chainable":1},{"line":94,"params":[],"return":{"description":"","type":"p5.Element"}}]},{"file":"src/core/p5.Element.js","line":116,"description":"<p>Sets the ID of the element. If no ID argument is passed in, it instead\n returns the current ID of the element.</p>\n","itemtype":"method","name":"id","chainable":1,"example":["\n <div class='norender'><code>\n function setup() {\n var cnv = createCanvas(100, 100);\n // Assigns a CSS selector ID to\n // the canvas element.\n cnv.id('mycanvas');\n }\n </code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM","overloads":[{"line":116,"params":[{"name":"id","description":"<p>ID of the element</p>\n","type":"String"}],"chainable":1},{"line":138,"params":[],"return":{"description":"the id of the element","type":"String"}}]},{"file":"src/core/p5.Element.js","line":153,"description":"<p>Adds given class to the element. If no class argument is passed in, it\n instead returns a string containing the current class(es) of the element.</p>\n","itemtype":"method","name":"class","chainable":1,"example":["\n <div class='norender'><code>\n function setup() {\n var cnv = createCanvas(100, 100);\n // Assigns a CSS selector class 'small'\n // to the canvas element.\n cnv.class('small');\n }\n </code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM","overloads":[{"line":153,"params":[{"name":"class","description":"<p>class to add</p>\n","type":"String"}],"chainable":1},{"line":175,"params":[],"return":{"description":"the class of the element","type":"String"}}]},{"file":"src/core/p5.Element.js","line":188,"description":"<p>The .<a href=\"#/p5.Element/mousePressed\">mousePressed()</a> function is called once after every time a\nmouse button is pressed over the element.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners.</p>\n","itemtype":"method","name":"mousePressed","params":[{"name":"fxn","description":"<p>function to be fired when mouse is\n pressed over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div class='norender'><code>\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mousePressed(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any click anywhere\nfunction mousePressed() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n</code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":249,"description":"<p>The .<a href=\"#/p5.Element/doubleClicked\">doubleClicked()</a> function is called once after every time a\nmouse button is pressed twice over the element. This can be used to\nattach element and action specific event listeners.</p>\n","itemtype":"method","name":"doubleClicked","params":[{"name":"fxn","description":"<p>function to be fired when mouse is\n double clicked over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"return":{"description":"","type":"p5.Element"},"example":["\n<div class='norender'><code>\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.doubleClicked(changeGray); // attach listener for\n // canvas double click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any double click anywhere\nfunction doubleClicked() {\n d = d + 10;\n}\n\n// this function fires only when cnv is double clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n</code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":298,"description":"<p>The .<a href=\"#/p5.Element/mouseWheel\">mouseWheel()</a> function is called once after every time a\nmouse wheel is scrolled over the element. This can be used to\nattach element specific event listeners.\n<br><br>\nThe function accepts a callback function as argument which will be executed\nwhen the <code>wheel</code> event is triggered on the element, the callback function is\npassed one argument <code>event</code>. The <code>event.deltaY</code> property returns negative\nvalues if the mouse wheel is rotated up or away from the user and positive\nin the other direction. The <code>event.deltaX</code> does the same as <code>event.deltaY</code>\nexcept it reads the horizontal wheel scroll of the mouse wheel.\n<br><br>\nOn OS X with &quot;natural&quot; scrolling enabled, the <code>event.deltaY</code> values are\nreversed.</p>\n","itemtype":"method","name":"mouseWheel","params":[{"name":"fxn","description":"<p>function to be fired when mouse is\n scrolled over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div class='norender'><code>\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseWheel(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with mousewheel movement\n// anywhere on screen\nfunction mouseWheel() {\n g = g + 10;\n}\n\n// this function fires with mousewheel movement\n// over canvas only\nfunction changeSize(event) {\n if (event.deltaY > 0) {\n d = d + 10;\n } else {\n d = d - 10;\n }\n}\n</code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":364,"description":"<p>The .<a href=\"#/p5.Element/mouseReleased\">mouseReleased()</a> function is called once after every time a\nmouse button is released over the element.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners.</p>\n","itemtype":"method","name":"mouseReleased","params":[{"name":"fxn","description":"<p>function to be fired when mouse is\n released over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div class='norender'><code>\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseReleased(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// released\nfunction mouseReleased() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// released while on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n</code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":418,"description":"<p>The .<a href=\"#/p5.Element/mouseClicked\">mouseClicked()</a> function is called once after a mouse button is\npressed and released over the element.\nSome mobile browsers may also trigger this event on a touch screen,\nif the user performs a quick tap.\nThis can be used to attach element specific event listeners.</p>\n","itemtype":"method","name":"mouseClicked","params":[{"name":"fxn","description":"<p>function to be fired when mouse is\n clicked over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div class=\"norender\">\n<code>\nvar cnv;\nvar d;\nvar g;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseClicked(changeGray); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires after the mouse has been\n// clicked anywhere\nfunction mouseClicked() {\n d = d + 10;\n}\n\n// this function fires after the mouse has been\n// clicked on canvas\nfunction changeGray() {\n g = random(0, 255);\n}\n</code>\n</div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":474,"description":"<p>The .<a href=\"#/p5.Element/mouseMoved\">mouseMoved()</a> function is called once every time a\nmouse moves over the element. This can be used to attach an\nelement specific event listener.</p>\n","itemtype":"method","name":"mouseMoved","params":[{"name":"fxn","description":"<p>function to be fired when a mouse moves\n over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div class='norender'><code>\nvar cnv;\nvar d = 30;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseMoved(changeSize); // attach listener for\n // activity on canvas only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n fill(200);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires when mouse moves anywhere on\n// page\nfunction mouseMoved() {\n g = g + 5;\n if (g > 255) {\n g = 0;\n }\n}\n\n// this function fires when mouse moves over canvas\nfunction changeSize() {\n d = d + 2;\n if (d > 100) {\n d = 0;\n }\n}\n</code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":532,"description":"<p>The .<a href=\"#/p5.Element/mouseOver\">mouseOver()</a> function is called once after every time a\nmouse moves onto the element. This can be used to attach an\nelement specific event listener.</p>\n","itemtype":"method","name":"mouseOver","params":[{"name":"fxn","description":"<p>function to be fired when a mouse moves\n onto the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div class='norender'><code>\nvar cnv;\nvar d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOver(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n</code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":575,"description":"<p>The .<a href=\"#/p5.Element/changed\">changed()</a> function is called when the value of an\nelement changes.\nThis can be used to attach an element specific event listener.</p>\n","itemtype":"method","name":"changed","params":[{"name":"fxn","description":"<p>function to be fired when the value of\n an element changes.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div><code>\nvar sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n var item = sel.value();\n background(200);\n text(\"it's a \" + item + '!', 50, 50);\n}\n</code></div>\n<div><code>\nvar checkbox;\nvar cnv;\n\nfunction setup() {\n checkbox = createCheckbox(' fill');\n checkbox.changed(changeFill);\n cnv = createCanvas(100, 100);\n cnv.position(0, 30);\n noFill();\n}\n\nfunction draw() {\n background(200);\n ellipse(50, 50, 50, 50);\n}\n\nfunction changeFill() {\n if (checkbox.checked()) {\n fill(0);\n } else {\n noFill();\n }\n}\n</code></div>"],"alt":"dropdown: pear, kiwi, grape. When selected text \"its a\" + selection shown.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":642,"description":"<p>The .<a href=\"#/p5.Element/input\">input()</a> function is called when any user input is\ndetected with an element. The input event is often used\nto detect keystrokes in a input element, or changes on a\nslider element. This can be used to attach an element specific\nevent listener.</p>\n","itemtype":"method","name":"input","params":[{"name":"fxn","description":"<p>function to be fired when any user input is\n detected within the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div class='norender'><code>\n// Open your console to see the output\nfunction setup() {\n var inp = createInput('');\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent() {\n console.log('you are typing: ', this.value());\n}\n</code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":677,"description":"<p>The .<a href=\"#/p5.Element/mouseOut\">mouseOut()</a> function is called once after every time a\nmouse moves off the element. This can be used to attach an\nelement specific event listener.</p>\n","itemtype":"method","name":"mouseOut","params":[{"name":"fxn","description":"<p>function to be fired when a mouse\n moves off of an element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div class='norender'><code>\nvar cnv;\nvar d;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.mouseOut(changeGray);\n d = 10;\n}\n\nfunction draw() {\n ellipse(width / 2, height / 2, d, d);\n}\n\nfunction changeGray() {\n d = d + 10;\n if (d > 100) {\n d = 0;\n }\n}\n</code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":719,"description":"<p>The .<a href=\"#/p5.Element/touchStarted\">touchStarted()</a> function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners.</p>\n","itemtype":"method","name":"touchStarted","params":[{"name":"fxn","description":"<p>function to be fired when a touch\n starts over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div class='norender'><code>\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchStarted(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchStarted() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n</code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":767,"description":"<p>The .<a href=\"#/p5.Element/touchMoved\">touchMoved()</a> function is called once after every time a touch move is\nregistered. This can be used to attach element specific event listeners.</p>\n","itemtype":"method","name":"touchMoved","params":[{"name":"fxn","description":"<p>function to be fired when a touch moves over\n the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div class='norender'><code>\nvar cnv;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchMoved(changeGray); // attach listener for\n // canvas click only\n g = 100;\n}\n\nfunction draw() {\n background(g);\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n</code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":807,"description":"<p>The .<a href=\"#/p5.Element/touchEnded\">touchEnded()</a> function is called once after every time a touch is\nregistered. This can be used to attach element specific event listeners.</p>\n","itemtype":"method","name":"touchEnded","params":[{"name":"fxn","description":"<p>function to be fired when a touch ends\n over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div class='norender'><code>\nvar cnv;\nvar d;\nvar g;\nfunction setup() {\n cnv = createCanvas(100, 100);\n cnv.touchEnded(changeGray); // attach listener for\n // canvas click only\n d = 10;\n g = 100;\n}\n\nfunction draw() {\n background(g);\n ellipse(width / 2, height / 2, d, d);\n}\n\n// this function fires with any touch anywhere\nfunction touchEnded() {\n d = d + 10;\n}\n\n// this function fires only when cnv is clicked\nfunction changeGray() {\n g = random(0, 255);\n}\n</code></div>"],"alt":"no display.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":856,"description":"<p>The .<a href=\"#/p5.Element/dragOver\">dragOver()</a> function is called once after every time a\nfile is dragged over the element. This can be used to attach an\nelement specific event listener.</p>\n","itemtype":"method","name":"dragOver","params":[{"name":"fxn","description":"<p>function to be fired when a file is\n dragged over the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div><code>\n// To test this sketch, simply drag a\n// file over the canvas\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragOver(dragOverCallback);\n}\n\n// This function will be called whenever\n// a file is dragged over the canvas\nfunction dragOverCallback() {\n background(240);\n text('Dragged over', width / 2, height / 2);\n}\n</code></div>"],"alt":"nothing displayed","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":894,"description":"<p>The .dragLeave() function is called once after every time a\ndragged file leaves the element area. This can be used to attach an\nelement specific event listener.</p>\n","itemtype":"method","name":"dragLeave","params":[{"name":"fxn","description":"<p>function to be fired when a file is\n dragged off the element.\n if <code>false</code> is passed instead, the previously\n firing function will no longer fire.</p>\n","type":"Function|Boolean"}],"chainable":1,"example":["\n<div><code>\n// To test this sketch, simply drag a file\n// over and then out of the canvas area\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('Drag file', width / 2, height / 2);\n c.dragLeave(dragLeaveCallback);\n}\n\n// This function will be called whenever\n// a file is dragged out of the canvas\nfunction dragLeaveCallback() {\n background(240);\n text('Dragged off', width / 2, height / 2);\n}\n</code></div>"],"alt":"nothing displayed","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":932,"description":"<p>The .<a href=\"#/p5.Element/drop\">drop()</a> function is called for each file dropped on the element.\nIt requires a callback that is passed a p5.File object. You can\noptionally pass two callbacks, the first one (required) is triggered\nfor each file dropped when the file is loaded. The second (optional)\nis triggered just once when a file (or files) are dropped.</p>\n","itemtype":"method","name":"drop","params":[{"name":"callback","description":"<p>callback triggered when files are dropped.</p>\n","type":"Function"},{"name":"fxn","description":"<p>callback to receive loaded file.</p>\n","type":"Function","optional":true}],"chainable":1,"example":["\n<div><code>\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop file', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction gotFile(file) {\n background(200);\n text('received file:', width / 2, height / 2);\n text(file.name, width / 2, height / 2 + 50);\n}\n</code></div>\n\n<div><code>\nvar img;\n\nfunction setup() {\n var c = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('drop image', width / 2, height / 2);\n c.drop(gotFile);\n}\n\nfunction draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction gotFile(file) {\n img = createImg(file.data).hide();\n}\n</code></div>"],"alt":"Canvas turns into whatever image is dragged/dropped onto it.","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Element.js","line":1088,"description":"<p>Helper fxn for sharing pixel methods</p>\n","class":"p5.Element","module":"DOM","submodule":"DOM"},{"file":"src/core/p5.Graphics.js","line":65,"description":"<p>Removes a Graphics object from the page and frees any resources\nassociated with it.</p>\n","itemtype":"method","name":"remove","example":["\n<div class='norender'><code>\nvar bg;\nfunction setup() {\n bg = createCanvas(100, 100);\n bg.background(0);\n image(bg, 0, 0);\n bg.remove();\n}\n</code></div>\n\n<div><code>\nvar bg;\nfunction setup() {\n pixelDensity(1);\n createCanvas(100, 100);\n stroke(255);\n fill(0);\n\n // create and draw the background image\n bg = createGraphics(100, 100);\n bg.background(200);\n bg.ellipse(50, 50, 80, 80);\n}\nfunction draw() {\n var t = millis() / 1000;\n // draw the background\n if (bg) {\n image(bg, frameCount % 100, 0);\n image(bg, frameCount % 100 - 100, 0);\n }\n // draw the foreground\n var p = p5.Vector.fromAngle(t, 35).add(50, 50);\n ellipse(p.x, p.y, 30);\n}\nfunction mouseClicked() {\n // remove the background\n if (bg) {\n bg.remove();\n bg = null;\n }\n}\n</code></div>"],"alt":"no image\na multi-colored circle moving back and forth over a scrolling background.","class":"p5.Graphics","module":"Rendering","submodule":"Rendering"},{"file":"src/core/p5.Renderer.js","line":96,"description":"<p>Resize our canvas element.</p>\n","class":"p5.Renderer","module":"Rendering","submodule":"Rendering"},{"file":"src/core/p5.Renderer.js","line":300,"description":"<p>Helper fxn to check font type (system or otf)</p>\n","class":"p5.Renderer","module":"Rendering","submodule":"Rendering"},{"file":"src/core/p5.Renderer.js","line":353,"description":"<p>Helper fxn to measure ascent and descent.\nAdapted from <a href=\"http://stackoverflow.com/a/25355178\">http://stackoverflow.com/a/25355178</a></p>\n","class":"p5.Renderer","module":"Rendering","submodule":"Rendering"},{"file":"src/core/p5.Renderer2D.js","line":9,"description":"<p>p5.Renderer2D\nThe 2D graphics canvas renderer class.\nextends p5.Renderer</p>\n","class":"p5","module":"Rendering"},{"file":"src/core/p5.Renderer2D.js","line":414,"description":"<p>Generate a cubic Bezier representing an arc on the unit circle of total\nangle <code>size</code> radians, beginning <code>start</code> radians above the x-axis. Up to\nfour of these curves are combined to make a full arc.</p>\n<p>See www.joecridge.me/bezier.pdf for an explanation of the method.</p>\n","class":"p5","module":"Rendering"},{"file":"src/core/rendering.js","line":17,"description":"<p>Creates a canvas element in the document, and sets the dimensions of it\nin pixels. This method should be called only once at the start of setup.\nCalling <a href=\"#/p5/createCanvas\">createCanvas</a> more than once in a sketch will result in very\nunpredictable behavior. If you want more than one drawing canvas\nyou could use <a href=\"#/p5/createGraphics\">createGraphics</a> (hidden by default but it can be shown).\n<br><br>\nThe system variables width and height are set by the parameters passed\nto this function. If <a href=\"#/p5/createCanvas\">createCanvas()</a> is not used, the window will be\ngiven a default size of 100x100 pixels.\n<br><br>\nFor more ways to position the canvas, see the\n<a href='https://github.com/processing/p5.js/wiki/Positioning-your-canvas'>\npositioning the canvas</a> wiki page.</p>\n","itemtype":"method","name":"createCanvas","params":[{"name":"w","description":"<p>width of the canvas</p>\n","type":"Number"},{"name":"h","description":"<p>height of the canvas</p>\n","type":"Number"},{"name":"renderer","description":"<p>either P2D or WEBGL</p>\n","type":"Constant","optional":true}],"return":{"description":"","type":"p5.Renderer"},"example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 50);\n background(153);\n line(0, 0, width, height);\n}\n</code>\n</div>"],"alt":"Black line extending from top-left of canvas to bottom right.","class":"p5","module":"Rendering","submodule":"Rendering"},{"file":"src/core/rendering.js","line":119,"description":"<p>Resizes the canvas to given width and height. The canvas will be cleared\nand draw will be called immediately, allowing the sketch to re-render itself\nin the resized canvas.</p>\n","itemtype":"method","name":"resizeCanvas","params":[{"name":"w","description":"<p>width of the canvas</p>\n","type":"Number"},{"name":"h","description":"<p>height of the canvas</p>\n","type":"Number"},{"name":"noRedraw","description":"<p>don&#39;t redraw the canvas immediately</p>\n","type":"Boolean","optional":true}],"example":["\n<div class=\"norender\"><code>\nfunction setup() {\n createCanvas(windowWidth, windowHeight);\n}\n\nfunction draw() {\n background(0, 100, 200);\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth, windowHeight);\n}\n</code></div>"],"alt":"No image displayed.","class":"p5","module":"Rendering","submodule":"Rendering"},{"file":"src/core/rendering.js","line":174,"description":"<p>Removes the default canvas for a p5 sketch that doesn&#39;t\nrequire a canvas</p>\n","itemtype":"method","name":"noCanvas","example":["\n<div>\n<code>\nfunction setup() {\n noCanvas();\n}\n</code>\n</div>"],"alt":"no image displayed","class":"p5","module":"Rendering","submodule":"Rendering"},{"file":"src/core/rendering.js","line":197,"description":"<p>Creates and returns a new p5.Renderer object. Use this class if you need\nto draw into an off-screen graphics buffer. The two parameters define the\nwidth and height in pixels.</p>\n","itemtype":"method","name":"createGraphics","params":[{"name":"w","description":"<p>width of the offscreen graphics buffer</p>\n","type":"Number"},{"name":"h","description":"<p>height of the offscreen graphics buffer</p>\n","type":"Number"},{"name":"renderer","description":"<p>either P2D or WEBGL\nundefined defaults to p2d</p>\n","type":"Constant","optional":true}],"return":{"description":"offscreen graphics buffer","type":"p5.Graphics"},"example":["\n<div>\n<code>\nvar pg;\nfunction setup() {\n createCanvas(100, 100);\n pg = createGraphics(100, 100);\n}\nfunction draw() {\n background(200);\n pg.background(100);\n pg.noStroke();\n pg.ellipse(pg.width / 2, pg.height / 2, 50, 50);\n image(pg, 50, 50);\n image(pg, 0, 0, 50, 50);\n}\n</code>\n</div>"],"alt":"4 grey squares alternating light and dark grey. White quarter circle mid-left.","class":"p5","module":"Rendering","submodule":"Rendering"},{"file":"src/core/rendering.js","line":236,"description":"<p>Blends the pixels in the display window according to the defined mode.\nThere is a choice of the following modes to blend the source pixels (A)\nwith the ones of pixels already in the display window (B):</p>\n<ul>\n<li><code>BLEND</code> - linear interpolation of colours: C =\nA*factor + B. This is the default blending mode.</li>\n<li><code>ADD</code> - sum of A and B</li>\n<li><code>DARKEST</code> - only the darkest colour succeeds: C =\nmin(A*factor, B).</li>\n<li><code>LIGHTEST</code> - only the lightest colour succeeds: C =\nmax(A*factor, B).</li>\n<li><code>DIFFERENCE</code> - subtract colors from underlying image.</li>\n<li><code>EXCLUSION</code> - similar to <code>DIFFERENCE</code>, but less\nextreme.</li>\n<li><code>MULTIPLY</code> - multiply the colors, result will always be\ndarker.</li>\n<li><code>SCREEN</code> - opposite multiply, uses inverse values of the\ncolors.</li>\n<li><code>REPLACE</code> - the pixels entirely replace the others and\ndon&#39;t utilize alpha (transparency) values.</li>\n<li><code>OVERLAY</code> - mix of <code>MULTIPLY</code> and <code>SCREEN\n</code>. Multiplies dark values, and screens light values.</li>\n<li><code>HARD_LIGHT</code> - <code>SCREEN</code> when greater than 50%\ngray, <code>MULTIPLY</code> when lower.</li>\n<li><code>SOFT_LIGHT</code> - mix of <code>DARKEST</code> and\n<code>LIGHTEST</code>. Works like <code>OVERLAY</code>, but not as harsh.\n</li>\n<li><code>DODGE</code> - lightens light tones and increases contrast,\nignores darks.</li>\n<li><code>BURN</code> - darker areas are applied, increasing contrast,\nignores lights.</li>\n</ul>","itemtype":"method","name":"blendMode","params":[{"name":"mode","description":"<p>blend mode to set for canvas.\n either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY,\n EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL</p>\n","type":"Constant"}],"example":["\n<div>\n<code>\nblendMode(LIGHTEST);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n</code>\n</div>\n<div>\n<code>\nblendMode(MULTIPLY);\nstrokeWeight(30);\nstroke(80, 150, 255);\nline(25, 25, 75, 75);\nstroke(255, 50, 50);\nline(75, 25, 25, 75);\n</code>\n</div>"],"alt":"translucent image thick red & blue diagonal rounded lines intersecting center\nThick red & blue diagonal rounded lines intersecting center. dark at overlap","class":"p5","module":"Rendering","submodule":"Rendering"},{"file":"src/core/shim.js","line":23,"description":"<p>shim for Uint8ClampedArray.slice\n(allows arrayCopy to work with pixels[])\nwith thanks to <a href=\"http://halfpapstudios.com/blog/tag/html5-canvas/\">http://halfpapstudios.com/blog/tag/html5-canvas/</a>\nEnumerable set to false to protect for...in from\nUint8ClampedArray.prototype pollution.</p>\n","class":"p5","module":"Rendering"},{"file":"src/core/shim.js","line":45,"description":"<p>this is implementation of Object.assign() which is unavailable in\nIE11 and (non-Chrome) Android browsers.\nThe assign() method is used to copy the values of all enumerable\nown properties from one or more source objects to a target object.\nIt will return the target object.\nModified from <a href=\"https://github.com/ljharb/object.assign\">https://github.com/ljharb/object.assign</a></p>\n","class":"p5","module":"Rendering"},{"file":"src/core/structure.js","line":12,"description":"<p>Stops p5.js from continuously executing the code within <a href=\"#/p5/draw\">draw()</a>.\nIf <a href=\"#/p5/loop\">loop()</a> is called, the code in <a href=\"#/p5/draw\">draw()</a> begins to run continuously again.\nIf using <a href=\"#/p5/noLoop\">noLoop()</a> in <a href=\"#/p5/setup\">setup()</a>, it should be the last line inside the block.\n<br><br>\nWhen <a href=\"#/p5/noLoop\">noLoop()</a> is used, it&#39;s not possible to manipulate or access the\nscreen inside event handling functions such as <a href=\"#/p5/mousePressed\">mousePressed()</a> or\n<a href=\"#/p5/keyPressed\">keyPressed()</a>. Instead, use those functions to call <a href=\"#/p5/redraw\">redraw()</a> or <a href=\"#/p5/loop\">loop()</a>,\nwhich will run <a href=\"#/p5/draw\">draw()</a>, which can update the screen properly. This means\nthat when <a href=\"#/p5/noLoop\">noLoop()</a> has been called, no drawing can happen, and functions\nlike <a href=\"#/p5/saveFrame\">saveFrame()</a> or <a href=\"#/p5/loadPixels\">loadPixels()</a> may not be used.\n<br><br>\nNote that if the sketch is resized, <a href=\"#/p5/redraw\">redraw()</a> will be called to update\nthe sketch, even after <a href=\"#/p5/noLoop\">noLoop()</a> has been specified. Otherwise, the sketch\nwould enter an odd state until <a href=\"#/p5/loop\">loop()</a> was called.</p>\n","itemtype":"method","name":"noLoop","example":["\n<div><code>\nfunction setup() {\n createCanvas(100, 100);\n background(200);\n noLoop();\n}\n\nfunction draw() {\n line(10, 10, 90, 90);\n}\n</code></div>\n\n<div><code>\nvar x = 0;\nfunction setup() {\n createCanvas(100, 100);\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n noLoop();\n}\n\nfunction mouseReleased() {\n loop();\n}\n</code></div>"],"alt":"113 pixel long line extending from top-left to bottom right of canvas.\nhorizontal line moves slowly from left. Loops but stops on mouse press.","class":"p5","module":"Structure","submodule":"Structure"},{"file":"src/core/structure.js","line":74,"description":"<p>By default, p5.js loops through draw() continuously, executing the code\nwithin it. However, the <a href=\"#/p5/draw\">draw()</a> loop may be stopped by calling <a href=\"#/p5/noLoop\">noLoop()</a>.\nIn that case, the <a href=\"#/p5/draw\">draw()</a> loop can be resumed with loop().</p>\n","itemtype":"method","name":"loop","example":["\n<div><code>\nvar x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n}\n\nfunction draw() {\n background(204);\n x = x + 0.1;\n if (x > width) {\n x = 0;\n }\n line(x, 0, x, height);\n}\n\nfunction mousePressed() {\n loop();\n}\n\nfunction mouseReleased() {\n noLoop();\n}\n</code></div>"],"alt":"horizontal line moves slowly from left. Loops but stops on mouse press.","class":"p5","module":"Structure","submodule":"Structure"},{"file":"src/core/structure.js","line":116,"description":"<p>The <a href=\"#/p5/push\">push()</a> function saves the current drawing style settings and\ntransformations, while <a href=\"#/p5/pop\">pop()</a> restores these settings. Note that these\nfunctions are always used together. They allow you to change the style\nand transformation settings and later return to what you had. When a new\nstate is started with <a href=\"#/p5/push\">push()</a>, it builds on the current style and transform\ninformation. The <a href=\"#/p5/push\">push()</a> and <a href=\"#/p5/pop\">pop()</a> functions can be embedded to provide\nmore control. (See the second example for a demonstration.)\n<br><br>\n<a href=\"#/p5/push\">push()</a> stores information related to the current transformation state\nand style settings controlled by the following functions: <a href=\"#/p5/fill\">fill()</a>,\n<a href=\"#/p5/stroke\">stroke()</a>, <a href=\"#/p5/tint\">tint()</a>, <a href=\"#/p5/strokeWeight\">strokeWeight()</a>, <a href=\"#/p5/strokeCap\">strokeCap()</a>, <a href=\"#/p5/strokeJoin\">strokeJoin()</a>,\n<a href=\"#/p5/imageMode\">imageMode()</a>, <a href=\"#/p5/rectMode\">rectMode()</a>, <a href=\"#/p5/ellipseMode\">ellipseMode()</a>, <a href=\"#/p5/colorMode\">colorMode()</a>, <a href=\"#/p5/textAlign\">textAlign()</a>,\n<a href=\"#/p5/textFont\">textFont()</a>, <a href=\"#/p5/textMode\">textMode()</a>, <a href=\"#/p5/textSize\">textSize()</a>, <a href=\"#/p5/textLeading\">textLeading()</a>.</p>\n","itemtype":"method","name":"push","example":["\n<div>\n<code>\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\ntranslate(50, 0);\nellipse(0, 50, 33, 33); // Middle circle\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n</code>\n</div>\n<div>\n<code>\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(33, 50, 33, 33); // Left-middle circle\n\npush(); // Start another new drawing state\nstroke(0, 102, 153);\nellipse(66, 50, 33, 33); // Right-middle circle\npop(); // Restore previous state\n\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n</code>\n</div>"],"alt":"Gold ellipse + thick black outline @center 2 white ellipses on left and right.\n2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.","class":"p5","module":"Structure","submodule":"Structure"},{"file":"src/core/structure.js","line":181,"description":"<p>The <a href=\"#/p5/push\">push()</a> function saves the current drawing style settings and\ntransformations, while <a href=\"#/p5/pop\">pop()</a> restores these settings. Note that these\nfunctions are always used together. They allow you to change the style\nand transformation settings and later return to what you had. When a new\nstate is started with <a href=\"#/p5/push\">push()</a>, it builds on the current style and transform\ninformation. The <a href=\"#/p5/push\">push()</a> and <a href=\"#/p5/pop\">pop()</a> functions can be embedded to provide\nmore control. (See the second example for a demonstration.)\n<br><br>\n<a href=\"#/p5/push\">push()</a> stores information related to the current transformation state\nand style settings controlled by the following functions: <a href=\"#/p5/fill\">fill()</a>,\n<a href=\"#/p5/stroke\">stroke()</a>, <a href=\"#/p5/tint\">tint()</a>, <a href=\"#/p5/strokeWeight\">strokeWeight()</a>, <a href=\"#/p5/strokeCap\">strokeCap()</a>, <a href=\"#/p5/strokeJoin\">strokeJoin()</a>,\n<a href=\"#/p5/imageMode\">imageMode()</a>, <a href=\"#/p5/rectMode\">rectMode()</a>, <a href=\"#/p5/ellipseMode\">ellipseMode()</a>, <a href=\"#/p5/colorMode\">colorMode()</a>, <a href=\"#/p5/textAlign\">textAlign()</a>,\n<a href=\"#/p5/textFont\">textFont()</a>, <a href=\"#/p5/textMode\">textMode()</a>, <a href=\"#/p5/textSize\">textSize()</a>, <a href=\"#/p5/textLeading\">textLeading()</a>.</p>\n","itemtype":"method","name":"pop","example":["\n<div>\n<code>\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\ntranslate(50, 0);\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(0, 50, 33, 33); // Middle circle\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n</code>\n</div>\n<div>\n<code>\nellipse(0, 50, 33, 33); // Left circle\n\npush(); // Start a new drawing state\nstrokeWeight(10);\nfill(204, 153, 0);\nellipse(33, 50, 33, 33); // Left-middle circle\n\npush(); // Start another new drawing state\nstroke(0, 102, 153);\nellipse(66, 50, 33, 33); // Right-middle circle\npop(); // Restore previous state\n\npop(); // Restore original state\n\nellipse(100, 50, 33, 33); // Right circle\n</code>\n</div>"],"alt":"Gold ellipse + thick black outline @center 2 white ellipses on left and right.\n2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right.","class":"p5","module":"Structure","submodule":"Structure"},{"file":"src/core/structure.js","line":247,"description":"<p>Executes the code within <a href=\"#/p5/draw\">draw()</a> one time. This functions allows the\n program to update the display window only when necessary, for example\n when an event registered by <a href=\"#/p5/mousePressed\">mousePressed()</a> or <a href=\"#/p5/keyPressed\">keyPressed()</a> occurs.\n <br><br>\n In structuring a program, it only makes sense to call <a href=\"#/p5/redraw\">redraw()</a> within\n events such as <a href=\"#/p5/mousePressed\">mousePressed()</a>. This is because <a href=\"#/p5/redraw\">redraw()</a> does not run\n <a href=\"#/p5/draw\">draw()</a> immediately (it only sets a flag that indicates an update is\n needed).\n <br><br>\n The <a href=\"#/p5/redraw\">redraw()</a> function does not work properly when called inside <a href=\"#/p5/draw\">draw()</a>.\n To enable/disable animations, use <a href=\"#/p5/loop\">loop()</a> and <a href=\"#/p5/noLoop\">noLoop()</a>.\n <br><br>\n In addition you can set the number of redraws per method call. Just\n add an integer as single parameter for the number of redraws.</p>\n","itemtype":"method","name":"redraw","params":[{"name":"n","description":"<p>Redraw for n-times. The default value is 1.</p>\n","type":"Integer","optional":true}],"example":["\n <div><code>\n var x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n x += 1;\n redraw();\n }\n </code></div>\n<div class='norender'><code>\n var x = 0;\nfunction setup() {\n createCanvas(100, 100);\n noLoop();\n }\nfunction draw() {\n background(204);\n x += 1;\n line(x, 0, x, height);\n }\nfunction mousePressed() {\n redraw(5);\n }\n </code></div>"],"alt":"black line on far left of canvas\n black line on far left of canvas","class":"p5","module":"Structure","submodule":"Structure"},{"file":"src/core/transform.js","line":13,"description":"<p>Multiplies the current matrix by the one specified through the parameters.\nThis is a powerful operation that can perform the equivalent of translate,\nscale, shear and rotate all at once. You can learn more about transformation\nmatrices on <a href=\"https://en.wikipedia.org/wiki/Transformation_matrix\">\nWikipedia</a>.</p>\n<p>The naming of the arguments here follows the naming of the <a href=\n\"https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-transform\">\nWHATWG specification</a> and corresponds to a\ntransformation matrix of the\nform:</p>\n<blockquote>\n<p><img style=\"max-width: 150px\" src=\"assets/transformation-matrix.png\"\nalt=\"The transformation matrix used when applyMatrix is called\"/></p>\n</blockquote>\n","itemtype":"method","name":"applyMatrix","params":[{"name":"a","description":"<p>numbers which define the 2x3 matrix to be multiplied</p>\n","type":"Number"},{"name":"b","description":"<p>numbers which define the 2x3 matrix to be multiplied</p>\n","type":"Number"},{"name":"c","description":"<p>numbers which define the 2x3 matrix to be multiplied</p>\n","type":"Number"},{"name":"d","description":"<p>numbers which define the 2x3 matrix to be multiplied</p>\n","type":"Number"},{"name":"e","description":"<p>numbers which define the 2x3 matrix to be multiplied</p>\n","type":"Number"},{"name":"f","description":"<p>numbers which define the 2x3 matrix to be multiplied</p>\n","type":"Number"}],"chainable":1,"example":["\n<div>\n<code>\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n // Equivalent to translate(x, y);\n applyMatrix(1, 0, 0, 1, 40 + step, 50);\n rect(0, 0, 50, 50);\n}\n</code>\n</div>\n<div>\n<code>\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n background(200);\n translate(50, 50);\n // Equivalent to scale(x, y);\n applyMatrix(1 / step, 0, 0, 1 / step, 0, 0);\n rect(0, 0, 50, 50);\n}\n</code>\n</div>\n<div>\n<code>\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, 0, TWO_PI);\n var cos_a = cos(angle);\n var sin_a = sin(angle);\n background(200);\n translate(50, 50);\n // Equivalent to rotate(angle);\n applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0);\n rect(0, 0, 50, 50);\n}\n</code>\n</div>\n<div>\n<code>\nfunction setup() {\n frameRate(10);\n rectMode(CENTER);\n}\n\nfunction draw() {\n var step = frameCount % 20;\n var angle = map(step, 0, 20, -PI / 4, PI / 4);\n background(200);\n translate(50, 50);\n // equivalent to shearX(angle);\n var shear_factor = 1 / tan(PI / 2 - angle);\n applyMatrix(1, 0, shear_factor, 1, 0, 0);\n rect(0, 0, 50, 50);\n}\n</code>\n</div>"],"alt":"A rectangle translating to the right\nA rectangle shrinking to the center\nA rectangle rotating clockwise about the center\nA rectangle shearing","class":"p5","module":"Transform","submodule":"Transform"},{"file":"src/core/transform.js","line":135,"description":"<p>Replaces the current matrix with the identity matrix.</p>\n","itemtype":"method","name":"resetMatrix","chainable":1,"example":["\n<div>\n<code>\ntranslate(50, 50);\napplyMatrix(0.5, 0.5, -0.5, 0.5, 0, 0);\nrect(0, 0, 20, 20);\n// Note that the translate is also reset.\nresetMatrix();\nrect(0, 0, 20, 20);\n</code>\n</div>"],"alt":"A rotated retangle in the center with another at the top left corner","class":"p5","module":"Transform","submodule":"Transform"},{"file":"src/core/transform.js","line":161,"description":"<p>Rotates a shape the amount specified by the angle parameter. This\nfunction accounts for <a href=\"#/p5/angleMode\">angleMode</a>, so angles can be entered in either\nRADIANS or DEGREES.\n<br><br>\nObjects are always rotated around their relative position to the\norigin and positive numbers rotate objects in a clockwise direction.\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nrotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI).\nAll tranformations are reset when <a href=\"#/p5/draw\">draw()</a> begins again.\n<br><br>\nTechnically, <a href=\"#/p5/rotate\">rotate()</a> multiplies the current transformation matrix\nby a rotation matrix. This function can be further controlled by\nthe <a href=\"#/p5/push\">push()</a> and <a href=\"#/p5/pop\">pop()</a>.</p>\n","itemtype":"method","name":"rotate","params":[{"name":"angle","description":"<p>the angle of rotation, specified in radians\n or degrees, depending on current angleMode</p>\n","type":"Number"},{"name":"axis","description":"<p>(in 3d) the axis to rotate around</p>\n","type":"p5.Vector|Number[]","optional":true}],"chainable":1,"example":["\n<div>\n<code>\ntranslate(width / 2, height / 2);\nrotate(PI / 3.0);\nrect(-26, -26, 52, 52);\n</code>\n</div>"],"alt":"white 52x52 rect with black outline at center rotated counter 45 degrees","class":"p5","module":"Transform","submodule":"Transform"},{"file":"src/core/transform.js","line":201,"description":"<p>Rotates around X axis.</p>\n","itemtype":"method","name":"rotateX","params":[{"name":"angle","description":"<p>the angle of rotation, specified in radians\n or degrees, depending on current angleMode</p>\n","type":"Number"}],"chainable":1,"example":["\n<div modernizr='webgl'>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateX(millis() / 1000);\n box();\n}\n</code>\n</div>"],"alt":"3d box rotating around the x axis.","class":"p5","module":"Transform","submodule":"Transform"},{"file":"src/core/transform.js","line":231,"description":"<p>Rotates around Y axis.</p>\n","itemtype":"method","name":"rotateY","params":[{"name":"angle","description":"<p>the angle of rotation, specified in radians\n or degrees, depending on current angleMode</p>\n","type":"Number"}],"chainable":1,"example":["\n<div modernizr='webgl'>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateY(millis() / 1000);\n box();\n}\n</code>\n</div>"],"alt":"3d box rotating around the y axis.","class":"p5","module":"Transform","submodule":"Transform"},{"file":"src/core/transform.js","line":261,"description":"<p>Rotates around Z axis. Webgl mode only.</p>\n","itemtype":"method","name":"rotateZ","params":[{"name":"angle","description":"<p>the angle of rotation, specified in radians\n or degrees, depending on current angleMode</p>\n","type":"Number"}],"chainable":1,"example":["\n<div modernizr='webgl'>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(255);\n rotateZ(millis() / 1000);\n box();\n}\n</code>\n</div>"],"alt":"3d box rotating around the z axis.","class":"p5","module":"Transform","submodule":"Transform"},{"file":"src/core/transform.js","line":291,"description":"<p>Increases or decreases the size of a shape by expanding and contracting\nvertices. Objects always scale from their relative origin to the\ncoordinate system. Scale values are specified as decimal percentages.\nFor example, the function call scale(2.0) increases the dimension of a\nshape by 200%.\n<br><br>\nTransformations apply to everything that happens after and subsequent\ncalls to the function multiply the effect. For example, calling scale(2.0)\nand then scale(1.5) is the same as scale(3.0). If <a href=\"#/p5/scale\">scale()</a> is called\nwithin <a href=\"#/p5/draw\">draw()</a>, the transformation is reset when the loop begins again.\n<br><br>\nUsing this function with the z parameter is only available in WEBGL mode.\nThis function can be further controlled with <a href=\"#/p5/push\">push()</a> and <a href=\"#/p5/pop\">pop()</a>.</p>\n","itemtype":"method","name":"scale","chainable":1,"example":["\n<div>\n<code>\nrect(30, 20, 50, 50);\nscale(0.5);\nrect(30, 20, 50, 50);\n</code>\n</div>\n\n<div>\n<code>\nrect(30, 20, 50, 50);\nscale(0.5, 1.3);\nrect(30, 20, 50, 50);\n</code>\n</div>"],"alt":"white 52x52 rect with black outline at center rotated counter 45 degrees\n2 white rects with black outline- 1 50x50 at center. other 25x65 bottom left","class":"p5","module":"Transform","submodule":"Transform","overloads":[{"line":291,"params":[{"name":"s","description":"<p>percent to scale the object, or percentage to\n scale the object in the x-axis if multiple arguments\n are given</p>\n","type":"Number|p5.Vector|Number[]"},{"name":"y","description":"<p>percent to scale the object in the y-axis</p>\n","type":"Number","optional":true},{"name":"z","description":"<p>percent to scale the object in the z-axis (webgl only)</p>\n","type":"Number","optional":true}],"chainable":1},{"line":336,"params":[{"name":"scales","description":"<p>per-axis percents to scale the object</p>\n","type":"p5.Vector|Number[]"}],"chainable":1}]},{"file":"src/core/transform.js","line":366,"description":"<p>Shears a shape around the x-axis the amount specified by the angle\nparameter. Angles should be specified in the current angleMode.\nObjects are always sheared around their relative position to the origin\nand positive numbers shear objects in a clockwise direction.\n<br><br>\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearX(PI/2) and then shearX(PI/2) is the same as shearX(PI).\nIf <a href=\"#/p5/shearX\">shearX()</a> is called within the <a href=\"#/p5/draw\">draw()</a>, the transformation is reset when\nthe loop begins again.\n<br><br>\nTechnically, <a href=\"#/p5/shearX\">shearX()</a> multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\n<a href=\"#/p5/push\">push()</a> and <a href=\"#/p5/pop\">pop()</a> functions.</p>\n","itemtype":"method","name":"shearX","params":[{"name":"angle","description":"<p>angle of shear specified in radians or degrees,\n depending on current angleMode</p>\n","type":"Number"}],"chainable":1,"example":["\n<div>\n<code>\ntranslate(width / 4, height / 4);\nshearX(PI / 4.0);\nrect(0, 0, 30, 30);\n</code>\n</div>"],"alt":"white irregular quadrilateral with black outline at top middle.","class":"p5","module":"Transform","submodule":"Transform"},{"file":"src/core/transform.js","line":405,"description":"<p>Shears a shape around the y-axis the amount specified by the angle\nparameter. Angles should be specified in the current angleMode. Objects\nare always sheared around their relative position to the origin and\npositive numbers shear objects in a clockwise direction.\n<br><br>\nTransformations apply to everything that happens after and subsequent\ncalls to the function accumulates the effect. For example, calling\nshearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If\n<a href=\"#/p5/shearY\">shearY()</a> is called within the <a href=\"#/p5/draw\">draw()</a>, the transformation is reset when\nthe loop begins again.\n<br><br>\nTechnically, <a href=\"#/p5/shearY\">shearY()</a> multiplies the current transformation matrix by a\nrotation matrix. This function can be further controlled by the\n<a href=\"#/p5/push\">push()</a> and <a href=\"#/p5/pop\">pop()</a> functions.</p>\n","itemtype":"method","name":"shearY","params":[{"name":"angle","description":"<p>angle of shear specified in radians or degrees,\n depending on current angleMode</p>\n","type":"Number"}],"chainable":1,"example":["\n<div>\n<code>\ntranslate(width / 4, height / 4);\nshearY(PI / 4.0);\nrect(0, 0, 30, 30);\n</code>\n</div>"],"alt":"white irregular quadrilateral with black outline at middle bottom.","class":"p5","module":"Transform","submodule":"Transform"},{"file":"src/core/transform.js","line":444,"description":"<p>Specifies an amount to displace objects within the display window.\nThe x parameter specifies left/right translation, the y parameter\nspecifies up/down translation.\n<br><br>\nTransformations are cumulative and apply to everything that happens after\nand subsequent calls to the function accumulates the effect. For example,\ncalling translate(50, 0) and then translate(20, 0) is the same as\ntranslate(70, 0). If <a href=\"#/p5/translate\">translate()</a> is called within <a href=\"#/p5/draw\">draw()</a>, the\ntransformation is reset when the loop begins again. This function can be\nfurther controlled by using <a href=\"#/p5/push\">push()</a> and <a href=\"#/p5/pop\">pop()</a>.</p>\n","itemtype":"method","name":"translate","chainable":1,"example":["\n<div>\n<code>\ntranslate(30, 20);\nrect(0, 0, 55, 55);\n</code>\n</div>\n\n<div>\n<code>\nrect(0, 0, 55, 55); // Draw rect at original 0,0\ntranslate(30, 20);\nrect(0, 0, 55, 55); // Draw rect at new 0,0\ntranslate(14, 14);\nrect(0, 0, 55, 55); // Draw rect at new 0,0\n</code>\n</div>\n\n\n<div>\n<code>\nfunction draw() {\n background(200);\n rectMode(CENTER);\n translate(width / 2, height / 2);\n translate(p5.Vector.fromAngle(millis() / 1000, 40));\n rect(0, 0, 20, 20);\n}\n</code>\n</div>"],"alt":"white 55x55 rect with black outline at center right.\n3 white 55x55 rects with black outlines at top-l, center-r and bottom-r.\na 20x20 white rect moving in a circle around the canvas","class":"p5","module":"Transform","submodule":"Transform","overloads":[{"line":444,"params":[{"name":"x","description":"<p>left/right translation</p>\n","type":"Number"},{"name":"y","description":"<p>up/down translation</p>\n","type":"Number"},{"name":"z","description":"<p>forward/backward translation (webgl only)</p>\n","type":"Number","optional":true}],"chainable":1},{"line":498,"params":[{"name":"vector","description":"<p>the vector to translate by</p>\n","type":"p5.Vector"}],"chainable":1}]},{"file":"src/data/p5.TypedDict.js","line":16,"description":"<p>Creates a new instance of p5.StringDict using the key-value pair\n or the object you provide.</p>\n","itemtype":"method","name":"createStringDict","return":{"description":"","type":"p5.StringDict"},"example":["\n <div class=\"norender\">\n <code>\n function setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n var anotherDictionary = createStringDict({ happy: 'coding' });\n print(anotherDictionary.hasKey('happy')); // logs true to console\n }\n </code></div>"],"class":"p5","module":"Data","submodule":"Dictionary","overloads":[{"line":16,"params":[{"name":"key","description":"","type":"String"},{"name":"value","description":"","type":"String"}],"return":{"description":"","type":"p5.StringDict"}},{"line":39,"params":[{"name":"object","description":"<p>object</p>\n","type":"Object"}],"return":{"description":"","type":"p5.StringDict"}}]},{"file":"src/data/p5.TypedDict.js","line":50,"description":"<p>Creates a new instance of <a href=\"#/p5.NumberDict\">p5.NumberDict</a> using the key-value pair\n or object you provide.</p>\n","itemtype":"method","name":"createNumberDict","return":{"description":"","type":"p5.NumberDict"},"example":["\n <div class=\"norender\">\n <code>\n function setup() {\n var myDictionary = createNumberDict(100, 42);\n print(myDictionary.hasKey(100)); // logs true to console\n var anotherDictionary = createNumberDict({ 200: 84 });\n print(anotherDictionary.hasKey(200)); // logs true to console\n }\n </code></div>"],"class":"p5","module":"Data","submodule":"Dictionary","overloads":[{"line":50,"params":[{"name":"key","description":"","type":"Number"},{"name":"value","description":"","type":"Number"}],"return":{"description":"","type":"p5.NumberDict"}},{"line":73,"params":[{"name":"object","description":"<p>object</p>\n","type":"Object"}],"return":{"description":"","type":"p5.NumberDict"}}]},{"file":"src/data/p5.TypedDict.js","line":103,"description":"<p>Returns the number of key-value pairs currently stored in the Dictionary.</p>\n","itemtype":"method","name":"size","return":{"description":"the number of key-value pairs in the Dictionary","type":"Integer"},"example":["\n<div class=\"norender\">\n<code>\nfunction setup() {\n var myDictionary = createNumberDict(1, 10);\n myDictionary.create(2, 20);\n myDictionary.create(3, 30);\n print(myDictionary.size()); // logs 3 to the console\n}\n</code></div>\n"],"class":"p5.TypedDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":125,"description":"<p>Returns true if the given key exists in the Dictionary,\notherwise returns false.</p>\n","itemtype":"method","name":"hasKey","params":[{"name":"key","description":"<p>that you want to look up</p>\n","type":"Number|String"}],"return":{"description":"whether that key exists in Dictionary","type":"Boolean"},"example":["\n<div class=\"norender\">\n<code>\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // logs true to console\n}\n</code></div>\n"],"class":"p5.TypedDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":148,"description":"<p>Returns the value stored at the given key.</p>\n","itemtype":"method","name":"get","params":[{"name":"the","description":"<p>key you want to access</p>\n","type":"Number|String"}],"return":{"description":"the value stored at that key","type":"Number|String"},"example":["\n<div class=\"norender\">\n<code>\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n var myValue = myDictionary.get('p5');\n print(myValue === 'js'); // logs true to console\n}\n</code></div>\n"],"class":"p5.TypedDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":175,"description":"<p>Updates the value associated with the given key in case it already exists\nin the Dictionary. Otherwise a new key-value pair is added.</p>\n","itemtype":"method","name":"set","params":[{"name":"key","description":"","type":"Number|String"},{"name":"value","description":"","type":"Number|String"}],"example":["\n<div class=\"norender\">\n<code>\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.set('p5', 'JS');\n myDictionary.print(); // logs \"key: p5 - value: JS\" to console\n}\n</code></div>\n"],"class":"p5.TypedDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":203,"description":"<p>private helper function to handle the user passing in objects\nduring construction or calls to create()</p>\n","class":"p5.TypedDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":214,"description":"<p>Creates a new key-value pair in the Dictionary.</p>\n","itemtype":"method","name":"create","example":["\n<div class=\"norender\">\n<code>\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n</code></div>"],"class":"p5.TypedDict","module":"Data","submodule":"Dictionary","overloads":[{"line":214,"params":[{"name":"key","description":"","type":"Number|String"},{"name":"value","description":"","type":"Number|String"}]},{"line":232,"params":[{"name":"obj","description":"<p>key/value pair</p>\n","type":"Object"}]}]},{"file":"src/data/p5.TypedDict.js","line":250,"description":"<p>Removes all previously stored key-value pairs from the Dictionary.</p>\n","itemtype":"method","name":"clear","example":["\n<div class=\"norender\">\n<code>\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n print(myDictionary.hasKey('p5')); // prints 'true'\n myDictionary.clear();\n print(myDictionary.hasKey('p5')); // prints 'false'\n}\n</code>\n</div>"],"class":"p5.TypedDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":271,"description":"<p>Removes the key-value pair stored at the given key from the Dictionary.</p>\n","itemtype":"method","name":"remove","params":[{"name":"key","description":"<p>for the pair to remove</p>\n","type":"Number|String"}],"example":["\n<div class=\"norender\">\n<code>\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n myDictionary.remove('p5');\n myDictionary.print();\n // above logs \"key: happy value: coding\" to console\n}\n</code></div>\n"],"class":"p5.TypedDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":301,"description":"<p>Logs the set of items currently stored in the Dictionary to the console.</p>\n","itemtype":"method","name":"print","example":["\n<div class=\"norender\">\n<code>\nfunction setup() {\n var myDictionary = createStringDict('p5', 'js');\n myDictionary.create('happy', 'coding');\n myDictionary.print();\n // above logs \"key: p5 - value: js, key: happy - value: coding\" to console\n}\n</code>\n</div>"],"class":"p5.TypedDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":325,"description":"<p>Converts the Dictionary into a CSV file for local download.</p>\n","itemtype":"method","name":"saveTable","example":["\n<div>\n<code>\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveTable('beatles');\n });\n</code>\n</div>"],"class":"p5.TypedDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":357,"description":"<p>Converts the Dictionary into a JSON file for local download.</p>\n","itemtype":"method","name":"saveJSON","example":["\n<div>\n<code>\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n createStringDict({\n john: 1940,\n paul: 1942,\n george: 1943,\n ringo: 1940\n }).saveJSON('beatles');\n });\n</code>\n</div>"],"class":"p5.TypedDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":382,"description":"<p>private helper function to ensure that the user passed in valid\nvalues for the Dictionary type</p>\n","class":"p5.TypedDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":425,"description":"<p>private helper function to ensure that the user passed in valid\nvalues for the Dictionary type</p>\n","class":"p5.NumberDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":434,"description":"<p>Add the given number to the value currently stored at the given key.\nThe sum then replaces the value previously stored in the Dictionary.</p>\n","itemtype":"method","name":"add","params":[{"name":"Key","description":"<p>for the value you wish to add to</p>\n","type":"Number"},{"name":"Number","description":"<p>to add to the value</p>\n","type":"Number"}],"example":["\n<div class='norender'>\n<code>\nfunction setup() {\n var myDictionary = createNumberDict(2, 5);\n myDictionary.add(2, 2);\n print(myDictionary.get(2)); // logs 7 to console.\n}\n</code></div>\n\n"],"class":"p5.NumberDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":462,"description":"<p>Subtract the given number from the value currently stored at the given key.\nThe difference then replaces the value previously stored in the Dictionary.</p>\n","itemtype":"method","name":"sub","params":[{"name":"Key","description":"<p>for the value you wish to subtract from</p>\n","type":"Number"},{"name":"Number","description":"<p>to subtract from the value</p>\n","type":"Number"}],"example":["\n<div class='norender'>\n<code>\nfunction setup() {\n var myDictionary = createNumberDict(2, 5);\n myDictionary.sub(2, 2);\n print(myDictionary.get(2)); // logs 3 to console.\n}\n</code></div>\n\n"],"class":"p5.NumberDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":486,"description":"<p>Multiply the given number with the value currently stored at the given key.\nThe product then replaces the value previously stored in the Dictionary.</p>\n","itemtype":"method","name":"mult","params":[{"name":"Key","description":"<p>for value you wish to multiply</p>\n","type":"Number"},{"name":"Amount","description":"<p>to multiply the value by</p>\n","type":"Number"}],"example":["\n<div class='norender'>\n<code>\nfunction setup() {\n var myDictionary = createNumberDict(2, 4);\n myDictionary.mult(2, 2);\n print(myDictionary.get(2)); // logs 8 to console.\n}\n</code></div>\n\n"],"class":"p5.NumberDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":514,"description":"<p>Divide the given number with the value currently stored at the given key.\nThe quotient then replaces the value previously stored in the Dictionary.</p>\n","itemtype":"method","name":"div","params":[{"name":"Key","description":"<p>for value you wish to divide</p>\n","type":"Number"},{"name":"Amount","description":"<p>to divide the value by</p>\n","type":"Number"}],"example":["\n<div class='norender'>\n<code>\nfunction setup() {\n var myDictionary = createNumberDict(2, 8);\n myDictionary.div(2, 2);\n print(myDictionary.get(2)); // logs 4 to console.\n}\n</code></div>\n\n"],"class":"p5.NumberDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":542,"description":"<p>private helper function for finding lowest or highest value\nthe argument &#39;flip&#39; is used to flip the comparison arrow\nfrom &#39;less than&#39; to &#39;greater than&#39;</p>\n","class":"p5.NumberDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":567,"description":"<p>Return the lowest number currently stored in the Dictionary.</p>\n","itemtype":"method","name":"minValue","return":{"description":"","type":"Number"},"example":["\n<div class='norender'>\n<code>\nfunction setup() {\n var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n var lowestValue = myDictionary.minValue(); // value is -10\n print(lowestValue);\n}\n</code></div>\n"],"class":"p5.NumberDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":588,"description":"<p>Return the highest number currently stored in the Dictionary.</p>\n","itemtype":"method","name":"maxValue","return":{"description":"","type":"Number"},"example":["\n<div class='norender'>\n<code>\nfunction setup() {\n var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 });\n var highestValue = myDictionary.maxValue(); // value is 3\n print(highestValue);\n}\n</code></div>\n"],"class":"p5.NumberDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":609,"description":"<p>private helper function for finding lowest or highest key\nthe argument &#39;flip&#39; is used to flip the comparison arrow\nfrom &#39;less than&#39; to &#39;greater than&#39;</p>\n","class":"p5.NumberDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":632,"description":"<p>Return the lowest key currently used in the Dictionary.</p>\n","itemtype":"method","name":"minKey","return":{"description":"","type":"Number"},"example":["\n<div class='norender'>\n<code>\nfunction setup() {\n var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n var lowestKey = myDictionary.minKey(); // value is 1.2\n print(lowestKey);\n}\n</code></div>\n"],"class":"p5.NumberDict","module":"Data","submodule":"Dictionary"},{"file":"src/data/p5.TypedDict.js","line":653,"description":"<p>Return the highest key currently used in the Dictionary.</p>\n","itemtype":"method","name":"maxKey","return":{"description":"","type":"Number"},"example":["\n<div class='norender'>\n<code>\nfunction setup() {\n var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 });\n var highestKey = myDictionary.maxKey(); // value is 4\n print(highestKey);\n}\n</code></div>\n"],"class":"p5.NumberDict","module":"Data","submodule":"Dictionary"},{"file":"src/events/acceleration.js","line":12,"description":"<p>The system variable deviceOrientation always contains the orientation of\nthe device. The value of this variable will either be set &#39;landscape&#39;\nor &#39;portrait&#39;. If no data is available it will be set to &#39;undefined&#39;.\neither LANDSCAPE or PORTRAIT.</p>\n","itemtype":"property","name":"deviceOrientation","type":"Constant","readonly":"","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":23,"description":"<p>The system variable accelerationX always contains the acceleration of the\ndevice along the x axis. Value is represented as meters per second squared.</p>\n","itemtype":"property","name":"accelerationX","type":"Number","readonly":"","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":32,"description":"<p>The system variable accelerationY always contains the acceleration of the\ndevice along the y axis. Value is represented as meters per second squared.</p>\n","itemtype":"property","name":"accelerationY","type":"Number","readonly":"","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":41,"description":"<p>The system variable accelerationZ always contains the acceleration of the\ndevice along the z axis. Value is represented as meters per second squared.</p>\n","itemtype":"property","name":"accelerationZ","type":"Number","readonly":"","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":50,"description":"<p>The system variable pAccelerationX always contains the acceleration of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as meters per second squared.</p>\n","itemtype":"property","name":"pAccelerationX","type":"Number","readonly":"","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":60,"description":"<p>The system variable pAccelerationY always contains the acceleration of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as meters per second squared.</p>\n","itemtype":"property","name":"pAccelerationY","type":"Number","readonly":"","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":70,"description":"<p>The system variable pAccelerationZ always contains the acceleration of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as meters per second squared.</p>\n","itemtype":"property","name":"pAccelerationZ","type":"Number","readonly":"","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":91,"description":"<p>The system variable rotationX always contains the rotation of the\ndevice along the x axis. Value is represented as 0 to +/-180 degrees.\n<br><br>\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.</p>\n","example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n</code>\n</div>"],"itemtype":"property","name":"rotationX","type":"Number","readonly":"","alt":"red horizontal line right, green vertical line bottom. black background.","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":125,"description":"<p>The system variable rotationY always contains the rotation of the\ndevice along the y axis. Value is represented as 0 to +/-90 degrees.\n<br><br>\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.</p>\n","example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n //rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n</code>\n</div>"],"itemtype":"property","name":"rotationY","type":"Number","readonly":"","alt":"red horizontal line right, green vertical line bottom. black background.","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":158,"description":"<p>The system variable rotationZ always contains the rotation of the\ndevice along the z axis. Value is represented as 0 to 359 degrees.\n<br><br>\nUnlike rotationX and rotationY, this variable is available for devices\nwith a built-in compass only.\n<br><br>\nNote: The order the rotations are called is important, ie. if used\ntogether, it must be called in the order Z-X-Y or there might be\nunexpected behaviour.</p>\n","example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateZ(radians(rotationZ));\n //rotateX(radians(rotationX));\n //rotateY(radians(rotationY));\n box(200, 200, 200);\n}\n</code>\n</div>"],"itemtype":"property","name":"rotationZ","type":"Number","readonly":"","alt":"red horizontal line right, green vertical line bottom. black background.","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":194,"description":"<p>The system variable pRotationX always contains the rotation of the\ndevice along the x axis in the frame previous to the current frame. Value\nis represented as 0 to +/-180 degrees.\n<br><br>\npRotationX can also be used with rotationX to determine the rotate\ndirection of the device along the X-axis.</p>\n","example":["\n<div class='norender'>\n<code>\n// A simple if statement looking at whether\n// rotationX - pRotationX < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nvar rX = rotationX + 180;\nvar pRX = pRotationX + 180;\n\nif ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) {\n rotateDirection = 'clockwise';\n} else if (rX - pRX < 0 || rX - pRX > 270) {\n rotateDirection = 'counter-clockwise';\n}\n\nprint(rotateDirection);\n</code>\n</div>"],"alt":"no image to display.","itemtype":"property","name":"pRotationX","type":"Number","readonly":"","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":239,"description":"<p>The system variable pRotationY always contains the rotation of the\ndevice along the y axis in the frame previous to the current frame. Value\nis represented as 0 to +/-90 degrees.\n<br><br>\npRotationY can also be used with rotationY to determine the rotate\ndirection of the device along the Y-axis.</p>\n","example":["\n<div class='norender'>\n<code>\n// A simple if statement looking at whether\n// rotationY - pRotationY < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\n// Simple range conversion to make things simpler.\n// This is not absolutely necessary but the logic\n// will be different in that case.\n\nvar rY = rotationY + 180;\nvar pRY = pRotationY + 180;\n\nif ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) {\n rotateDirection = 'clockwise';\n} else if (rY - pRY < 0 || rY - pRY > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n</code>\n</div>"],"alt":"no image to display.","itemtype":"property","name":"pRotationY","type":"Number","readonly":"","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":283,"description":"<p>The system variable pRotationZ always contains the rotation of the\ndevice along the z axis in the frame previous to the current frame. Value\nis represented as 0 to 359 degrees.\n<br><br>\npRotationZ can also be used with rotationZ to determine the rotate\ndirection of the device along the Z-axis.</p>\n","example":["\n<div class='norender'>\n<code>\n// A simple if statement looking at whether\n// rotationZ - pRotationZ < 0 is true or not will be\n// sufficient for determining the rotate direction\n// in most cases.\n\n// Some extra logic is needed to account for cases where\n// the angles wrap around.\nvar rotateDirection = 'clockwise';\n\nif (\n (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) ||\n rotationZ - pRotationZ < -270\n) {\n rotateDirection = 'clockwise';\n} else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) {\n rotateDirection = 'counter-clockwise';\n}\nprint(rotateDirection);\n</code>\n</div>"],"alt":"no image to display.","itemtype":"property","name":"pRotationZ","type":"Number","readonly":"","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":341,"itemtype":"property","name":"turnAxis","type":"String","readonly":"","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":350,"description":"<p>The <a href=\"#/p5/setMoveThreshold\">setMoveThreshold()</a> function is used to set the movement threshold for\nthe <a href=\"#/p5/deviceMoved\">deviceMoved()</a> function. The default threshold is set to 0.5.</p>\n","itemtype":"method","name":"setMoveThreshold","params":[{"name":"value","description":"<p>The threshold value</p>\n","type":"Number"}],"example":["\n<div class=\"norender\">\n<code>\n// Run this example on a mobile device\n// You will need to move the device incrementally further\n// the closer the square's color gets to white in order to change the value.\n\nvar value = 0;\nvar threshold = 0.5;\nfunction setup() {\n setMoveThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 0.1;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setMoveThreshold(threshold);\n}\n</code>\n</div>"],"alt":"50x50 black rect in center of canvas. turns white on mobile when device moves","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":393,"description":"<p>The <a href=\"#/p5/setShakeThreshold\">setShakeThreshold()</a> function is used to set the movement threshold for\nthe <a href=\"#/p5/deviceShaken\">deviceShaken()</a> function. The default threshold is set to 30.</p>\n","itemtype":"method","name":"setShakeThreshold","params":[{"name":"value","description":"<p>The threshold value</p>\n","type":"Number"}],"example":["\n<div class=\"norender\">\n<code>\n// Run this example on a mobile device\n// You will need to shake the device more firmly\n// the closer the box's fill gets to white in order to change the value.\n\nvar value = 0;\nvar threshold = 30;\nfunction setup() {\n setShakeThreshold(threshold);\n}\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n threshold = threshold + 5;\n if (value > 255) {\n value = 0;\n threshold = 30;\n }\n setShakeThreshold(threshold);\n}\n</code>\n</div>"],"alt":"50x50 black rect in center of canvas. turns white on mobile when device\nis being shaked","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":437,"description":"<p>The <a href=\"#/p5/deviceMoved\">deviceMoved()</a> function is called when the device is moved by more than\nthe threshold value along X, Y or Z axis. The default threshold is set to\n0.5.</p>\n","itemtype":"method","name":"deviceMoved","example":["\n<div class=\"norender\">\n<code>\n// Run this example on a mobile device\n// Move the device around\n// to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n</code>\n</div>"],"alt":"50x50 black rect in center of canvas. turns white on mobile when device moves","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":468,"description":"<p>The <a href=\"#/p5/deviceTurned\">deviceTurned()</a> function is called when the device rotates by\nmore than 90 degrees continuously.\n<br><br>\nThe axis that triggers the <a href=\"#/p5/deviceTurned\">deviceTurned()</a> method is stored in the turnAxis\nvariable. The <a href=\"#/p5/deviceTurned\">deviceTurned()</a> method can be locked to trigger on any axis:\nX, Y or Z by comparing the turnAxis variable to &#39;X&#39;, &#39;Y&#39; or &#39;Z&#39;.</p>\n","itemtype":"method","name":"deviceTurned","example":["\n<div class=\"norender\">\n<code>\n// Run this example on a mobile device\n// Rotate the device by 90 degrees\n// to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n}\n</code>\n</div>\n<div>\n<code>\n// Run this example on a mobile device\n// Rotate the device by 90 degrees in the\n// X-axis to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceTurned() {\n if (turnAxis === 'X') {\n if (value === 0) {\n value = 255;\n } else if (value === 255) {\n value = 0;\n }\n }\n}\n</code>\n</div>"],"alt":"50x50 black rect in center of canvas. turns white on mobile when device turns\n50x50 black rect in center of canvas. turns white on mobile when x-axis turns","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/acceleration.js","line":527,"description":"<p>The <a href=\"#/p5/deviceShaken\">deviceShaken()</a> function is called when the device total acceleration\nchanges of accelerationX and accelerationY values is more than\nthe threshold value. The default threshold is set to 30.</p>\n","itemtype":"method","name":"deviceShaken","example":["\n<div class=\"norender\">\n<code>\n// Run this example on a mobile device\n// Shake the device to change the value.\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction deviceShaken() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n</code>\n</div>"],"alt":"50x50 black rect in center of canvas. turns white on mobile when device shakes","class":"p5","module":"Events","submodule":"Acceleration"},{"file":"src/events/keyboard.js","line":18,"description":"<p>The boolean system variable <a href=\"#/p5/keyIsPressed\">keyIsPressed</a> is true if any key is pressed\nand false if no keys are pressed.</p>\n","itemtype":"property","name":"keyIsPressed","type":"Boolean","readonly":"","example":["\n<div>\n<code>\nfunction draw() {\n if (keyIsPressed === true) {\n fill(0);\n } else {\n fill(255);\n }\n rect(25, 25, 50, 50);\n}\n</code>\n</div>"],"alt":"50x50 white rect that turns black on keypress.","class":"p5","module":"Events","submodule":"Keyboard"},{"file":"src/events/keyboard.js","line":45,"description":"<p>The system variable key always contains the value of the most recent\nkey on the keyboard that was typed. To get the proper capitalization, it\nis best to use it within <a href=\"#/p5/keyTyped\">keyTyped()</a>. For non-ASCII keys, use the <a href=\"#/p5/keyCode\">keyCode</a>\nvariable.</p>\n","itemtype":"property","name":"key","type":"String","readonly":"","example":["\n<div><code>\n// Click any key to display it!\n// (Not Guaranteed to be Case Sensitive)\nfunction setup() {\n fill(245, 123, 158);\n textSize(50);\n}\n\nfunction draw() {\n background(200);\n text(key, 33, 65); // Display last key pressed.\n}\n</code></div>"],"alt":"canvas displays any key value that is pressed in pink font.","class":"p5","module":"Events","submodule":"Keyboard"},{"file":"src/events/keyboard.js","line":74,"description":"<p>The variable keyCode is used to detect special keys such as BACKSPACE,\nDELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW,\nDOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\nYou can also check for custom keys by looking up the keyCode of any key\non a site like this: <a href=\"http://keycode.info/\">keycode.info</a>.</p>\n","itemtype":"property","name":"keyCode","type":"Integer","readonly":"","example":["\n<div><code>\nvar fillVal = 126;\nfunction draw() {\n fill(fillVal);\n rect(25, 25, 50, 50);\n}\n\nfunction keyPressed() {\n if (keyCode === UP_ARROW) {\n fillVal = 255;\n } else if (keyCode === DOWN_ARROW) {\n fillVal = 0;\n }\n return false; // prevent default\n}\n</code></div>"],"alt":"Grey rect center. turns white when up arrow pressed and black when down","class":"p5","module":"Events","submodule":"Keyboard"},{"file":"src/events/keyboard.js","line":107,"description":"<p>The <a href=\"#/p5/keyPressed\">keyPressed()</a> function is called once every time a key is pressed. The\nkeyCode for the key that was pressed is stored in the <a href=\"#/p5/keyCode\">keyCode</a> variable.\n<br><br>\nFor non-ASCII keys, use the keyCode variable. You can check if the keyCode\nequals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL,\nOPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW.\n<br><br>\nFor ASCII keys that was pressed is stored in the key variable. However, it\ndoes not distinguish between uppercase and lowercase. For this reason, it\nis recommended to use <a href=\"#/p5/keyTyped\">keyTyped()</a> to read the key variable, in which the\ncase of the variable will be distinguished.\n<br><br>\nBecause of how operating systems handle key repeats, holding down a key\nmay cause multiple calls to <a href=\"#/p5/keyTyped\">keyTyped()</a> (and <a href=\"#/p5/keyReleased\">keyReleased()</a> as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.<br><br>\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add &quot;return false&quot; to the end of the method.</p>\n","itemtype":"method","name":"keyPressed","example":["\n<div>\n<code>\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n</code>\n</div>\n<div>\n<code>\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyPressed() {\n if (keyCode === LEFT_ARROW) {\n value = 255;\n } else if (keyCode === RIGHT_ARROW) {\n value = 0;\n }\n}\n</code>\n</div>\n<div class=\"norender\">\n<code>\nfunction keyPressed() {\n // Do something\n return false; // prevent any default behaviour\n}\n</code>\n</div>"],"alt":"black rect center. turns white when key pressed and black when released\nblack rect center. turns white when left arrow pressed and black when right.","class":"p5","module":"Events","submodule":"Keyboard"},{"file":"src/events/keyboard.js","line":194,"description":"<p>The <a href=\"#/p5/keyReleased\">keyReleased()</a> function is called once every time a key is released.\nSee <a href=\"#/p5/key\">key</a> and <a href=\"#/p5/keyCode\">keyCode</a> for more information.<br><br>\nBrowsers may have different default\nbehaviors attached to various key events. To prevent any default\nbehavior for this event, add &quot;return false&quot; to the end of the method.</p>\n","itemtype":"method","name":"keyReleased","example":["\n<div>\n<code>\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n return false; // prevent any default behavior\n}\n</code>\n</div>"],"alt":"black rect center. turns white when key pressed and black when pressed again","class":"p5","module":"Events","submodule":"Keyboard"},{"file":"src/events/keyboard.js","line":246,"description":"<p>The <a href=\"#/p5/keyTyped\">keyTyped()</a> function is called once every time a key is pressed, but\naction keys such as Ctrl, Shift, and Alt are ignored. The most recent\nkey pressed will be stored in the key variable.\n<br><br>\nBecause of how operating systems handle key repeats, holding down a key\nwill cause multiple calls to <a href=\"#/p5/keyTyped\">keyTyped()</a> (and <a href=\"#/p5/keyReleased\">keyReleased()</a> as well). The\nrate of repeat is set by the operating system and how each computer is\nconfigured.<br><br>\nBrowsers may have different default behaviors attached to various key\nevents. To prevent any default behavior for this event, add &quot;return false&quot;\nto the end of the method.</p>\n","itemtype":"method","name":"keyTyped","example":["\n<div>\n<code>\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction keyTyped() {\n if (key === 'a') {\n value = 255;\n } else if (key === 'b') {\n value = 0;\n }\n // uncomment to prevent any default behavior\n // return false;\n}\n</code>\n</div>"],"alt":"black rect center. turns white when 'a' key typed and black when 'b' pressed","class":"p5","module":"Events","submodule":"Keyboard"},{"file":"src/events/keyboard.js","line":300,"description":"<p>The onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released.</p>\n","class":"p5","module":"Events","submodule":"Keyboard"},{"file":"src/events/keyboard.js","line":310,"description":"<p>The <a href=\"#/p5/keyIsDown\">keyIsDown()</a> function checks if the key is currently down, i.e. pressed.\nIt can be used if you have an object that moves, and you want several keys\nto be able to affect its behaviour simultaneously, such as moving a\nsprite diagonally. You can put in any number representing the keyCode of\nthe key, or use any of the variable <a href=\"#/p5/keyCode\">keyCode</a> names listed\n<a href=\"http://p5js.org/reference/#p5/keyCode\">here</a>.</p>\n","itemtype":"method","name":"keyIsDown","params":[{"name":"code","description":"<p>The key to check for.</p>\n","type":"Number"}],"return":{"description":"whether key is down or not","type":"Boolean"},"example":["\n<div><code>\nvar x = 100;\nvar y = 100;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n if (keyIsDown(LEFT_ARROW)) {\n x -= 5;\n }\n\n if (keyIsDown(RIGHT_ARROW)) {\n x += 5;\n }\n\n if (keyIsDown(UP_ARROW)) {\n y -= 5;\n }\n\n if (keyIsDown(DOWN_ARROW)) {\n y += 5;\n }\n\n clear();\n fill(255, 0, 0);\n ellipse(x, y, 50, 50);\n}\n</code></div>\n\n<div><code>\nvar diameter = 50;\n\nfunction setup() {\n createCanvas(512, 512);\n}\n\nfunction draw() {\n // 107 and 187 are keyCodes for \"+\"\n if (keyIsDown(107) || keyIsDown(187)) {\n diameter += 1;\n }\n\n // 109 and 189 are keyCodes for \"-\"\n if (keyIsDown(109) || keyIsDown(189)) {\n diameter -= 1;\n }\n\n clear();\n fill(255, 0, 0);\n ellipse(50, 50, diameter, diameter);\n}\n</code></div>"],"alt":"50x50 red ellipse moves left, right, up and down with arrow presses.\n50x50 red ellipse gets bigger or smaller when + or - are pressed.","class":"p5","module":"Events","submodule":"Keyboard"},{"file":"src/events/mouse.js","line":22,"description":"<p>The system variable mouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the canvas. If touch is\nused instead of mouse input, mouseX will hold the x value of the most\nrecent touch point.</p>\n","itemtype":"property","name":"mouseX","type":"Number","readonly":"","example":["\n<div>\n<code>\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(mouseX, 0, mouseX, 100);\n}\n</code>\n</div>"],"alt":"horizontal black line moves left and right with mouse x-position","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":48,"description":"<p>The system variable mouseY always contains the current vertical position\nof the mouse, relative to (0, 0) of the canvas. If touch is\nused instead of mouse input, mouseY will hold the y value of the most\nrecent touch point.</p>\n","itemtype":"property","name":"mouseY","type":"Number","readonly":"","example":["\n<div>\n<code>\n// Move the mouse across the canvas\nfunction draw() {\n background(244, 248, 252);\n line(0, mouseY, 100, mouseY);\n}\n</code>\n</div>"],"alt":"vertical black line moves up and down with mouse y-position","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":74,"description":"<p>The system variable pmouseX always contains the horizontal position of\nthe mouse or finger in the frame previous to the current frame, relative to\n(0, 0) of the canvas. Note: pmouseX will be reset to the current mouseX\nvalue at the start of each touch event.</p>\n","itemtype":"property","name":"pmouseX","type":"Number","readonly":"","example":["\n<div>\n<code>\n// Move the mouse across the canvas to leave a trail\nfunction setup() {\n //slow down the frameRate to make it more visible\n frameRate(10);\n}\n\nfunction draw() {\n background(244, 248, 252);\n line(mouseX, mouseY, pmouseX, pmouseY);\n print(pmouseX + ' -> ' + mouseX);\n}\n</code>\n</div>"],"alt":"line trail is created from cursor movements. faster movement make longer line.","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":106,"description":"<p>The system variable pmouseY always contains the vertical position of the\nmouse or finger in the frame previous to the current frame, relative to\n(0, 0) of the canvas. Note: pmouseY will be reset to the current mouseY\nvalue at the start of each touch event.</p>\n","itemtype":"property","name":"pmouseY","type":"Number","readonly":"","example":["\n<div>\n<code>\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n //draw a square only if the mouse is not moving\n if (mouseY === pmouseY && mouseX === pmouseX) {\n rect(20, 20, 60, 60);\n }\n\n print(pmouseY + ' -> ' + mouseY);\n}\n</code>\n</div>"],"alt":"60x60 black rect center, fuschia background. rect flickers on mouse movement","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":137,"description":"<p>The system variable winMouseX always contains the current horizontal\nposition of the mouse, relative to (0, 0) of the window.</p>\n","itemtype":"property","name":"winMouseX","type":"Number","readonly":"","example":["\n<div>\n<code>\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the horizontal mouse position\n //rela tive to the window\n myCanvas.position(winMouseX + 1, windowHeight / 2);\n\n //the y of the square is relative to the canvas\n rect(20, mouseY, 60, 60);\n}\n</code>\n</div>"],"alt":"60x60 black rect y moves with mouse y and fuschia canvas moves with mouse x","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":174,"description":"<p>The system variable winMouseY always contains the current vertical\nposition of the mouse, relative to (0, 0) of the window.</p>\n","itemtype":"property","name":"winMouseY","type":"Number","readonly":"","example":["\n<div>\n<code>\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n}\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n //move the canvas to the vertical mouse position\n //rel ative to the window\n myCanvas.position(windowWidth / 2, winMouseY + 1);\n\n //the x of the square is relative to the canvas\n rect(mouseX, 20, 60, 60);\n}\n</code>\n</div>"],"alt":"60x60 black rect x moves with mouse x and fuschia canvas y moves with mouse y","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":211,"description":"<p>The system variable pwinMouseX always contains the horizontal position\nof the mouse in the frame previous to the current frame, relative to\n(0, 0) of the window. Note: pwinMouseX will be reset to the current winMouseX\nvalue at the start of each touch event.</p>\n","itemtype":"property","name":"pwinMouseX","type":"Number","readonly":"","example":["\n<div>\n<code>\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current x position is the horizontal mouse speed\n var speed = abs(winMouseX - pwinMouseX);\n //change the size of the circle\n //according to the horizontal speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n</code>\n</div>"],"alt":"fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":252,"description":"<p>The system variable pwinMouseY always contains the vertical position of\nthe mouse in the frame previous to the current frame, relative to (0, 0)\nof the window. Note: pwinMouseY will be reset to the current winMouseY\nvalue at the start of each touch event.</p>\n","itemtype":"property","name":"pwinMouseY","type":"Number","readonly":"","example":["\n<div>\n<code>\nvar myCanvas;\n\nfunction setup() {\n //use a variable to store a pointer to the canvas\n myCanvas = createCanvas(100, 100);\n noStroke();\n fill(237, 34, 93);\n}\n\nfunction draw() {\n clear();\n //the difference between previous and\n //current y position is the vertical mouse speed\n var speed = abs(winMouseY - pwinMouseY);\n //change the size of the circle\n //according to the vertical speed\n ellipse(50, 50, 10 + speed * 5, 10 + speed * 5);\n //move the canvas to the mouse position\n myCanvas.position(winMouseX + 1, winMouseY + 1);\n}\n</code>\n</div>"],"alt":"fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":294,"description":"<p>Processing automatically tracks if the mouse button is pressed and which\nbutton is pressed. The value of the system variable mouseButton is either\nLEFT, RIGHT, or CENTER depending on which button was pressed last.\nWarning: different browsers may track mouseButton differently.</p>\n","itemtype":"property","name":"mouseButton","type":"Constant","readonly":"","example":["\n<div>\n<code>\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed) {\n if (mouseButton === LEFT) {\n ellipse(50, 50, 50, 50);\n }\n if (mouseButton === RIGHT) {\n rect(25, 25, 50, 50);\n }\n if (mouseButton === CENTER) {\n triangle(23, 75, 50, 20, 78, 75);\n }\n }\n\n print(mouseButton);\n}\n</code>\n</div>"],"alt":"50x50 black ellipse appears on center of fuschia canvas on mouse click/press.","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":333,"description":"<p>The boolean system variable mouseIsPressed is true if the mouse is pressed\nand false if not.</p>\n","itemtype":"property","name":"mouseIsPressed","type":"Boolean","readonly":"","example":["\n<div>\n<code>\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n\n if (mouseIsPressed) {\n ellipse(50, 50, 50, 50);\n } else {\n rect(25, 25, 50, 50);\n }\n\n print(mouseIsPressed);\n}\n</code>\n</div>"],"alt":"black 50x50 rect becomes ellipse with mouse click/press. fuschia background.","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":424,"description":"<p>The <a href=\"#/p5/mouseMoved\">mouseMoved()</a> function is called every time the mouse moves and a mouse\nbutton is not pressed.<br><br>\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add &quot;return false&quot; to the end of the method.</p>\n","itemtype":"method","name":"mouseMoved","example":["\n<div>\n<code>\n// Move the mouse across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nfunction mouseMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n</code>\n</div>"],"alt":"black 50x50 rect becomes lighter with mouse movements until white then resets\nno image displayed","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":468,"description":"<p>The <a href=\"#/p5/mouseDragged\">mouseDragged()</a> function is called once every time the mouse moves and\na mouse button is pressed. If no <a href=\"#/p5/mouseDragged\">mouseDragged()</a> function is defined, the\n<a href=\"#/p5/touchMoved\">touchMoved()</a> function will be called instead if it is defined.<br><br>\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add &quot;return false&quot; to the end of the method.</p>\n","itemtype":"method","name":"mouseDragged","example":["\n<div>\n<code>\n// Drag the mouse across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseDragged() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nfunction mouseDragged() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n</code>\n</div>"],"alt":"black 50x50 rect turns lighter with mouse click and drag until white, resets\nno image displayed","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":538,"description":"<p>The <a href=\"#/p5/mousePressed\">mousePressed()</a> function is called once after every time a mouse button\nis pressed. The mouseButton variable (see the related reference entry)\ncan be used to determine which button has been pressed. If no\n<a href=\"#/p5/mousePressed\">mousePressed()</a> function is defined, the <a href=\"#/p5/touchStarted\">touchStarted()</a> function will be\ncalled instead if it is defined.<br><br>\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add &quot;return false&quot; to the end of the method.</p>\n","itemtype":"method","name":"mousePressed","example":["\n<div>\n<code>\n// Click within the image to change\n// the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mousePressed() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nfunction mousePressed() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n</code>\n</div>"],"alt":"black 50x50 rect turns white with mouse click/press.\nno image displayed","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":604,"description":"<p>The <a href=\"#/p5/mouseReleased\">mouseReleased()</a> function is called every time a mouse button is\nreleased. If no <a href=\"#/p5/mouseReleased\">mouseReleased()</a> function is defined, the <a href=\"#/p5/touchEnded\">touchEnded()</a>\nfunction will be called instead if it is defined.<br><br>\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add &quot;return false&quot; to the end of the method.</p>\n","itemtype":"method","name":"mouseReleased","example":["\n<div>\n<code>\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction mouseReleased() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nfunction mouseReleased() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n</code>\n</div>"],"alt":"black 50x50 rect turns white with mouse click/press.\nno image displayed","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":671,"description":"<p>The <a href=\"#/p5/mouseClicked\">mouseClicked()</a> function is called once after a mouse button has been\npressed and then released.<br><br>\nBrowsers handle clicks differently, so this function is only guaranteed to be\nrun when the left mouse button is clicked. To handle other mouse buttons\nbeing pressed or released, see <a href=\"#/p5/mousePressed\">mousePressed()</a> or <a href=\"#/p5/mouseReleased\">mouseReleased()</a>.<br><br>\nBrowsers may have different default\nbehaviors attached to various mouse events. To prevent any default\nbehavior for this event, add &quot;return false&quot; to the end of the method.</p>\n","itemtype":"method","name":"mouseClicked","example":["\n<div>\n<code>\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction mouseClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nfunction mouseClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n</code>\n</div>"],"alt":"black 50x50 rect turns white with mouse click/press.\nno image displayed","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":730,"description":"<p>The <a href=\"#/p5/doubleClicked\">doubleClicked()</a> function is executed every time a event\nlistener has detected a dblclick event which is a part of the\nDOM L3 specification. The doubleClicked event is fired when a\npointing device button (usually a mouse&#39;s primary button)\nis clicked twice on a single element. For more info on the\ndblclick event refer to mozilla&#39;s documentation here:\n<a href=\"https://developer.mozilla.org/en-US/docs/Web/Events/dblclick\">https://developer.mozilla.org/en-US/docs/Web/Events/dblclick</a></p>\n","itemtype":"method","name":"doubleClicked","example":["\n<div>\n<code>\n// Click within the image to change\n// the value of the rectangle\n// after the mouse has been double clicked\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\n\nfunction doubleClicked() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nfunction doubleClicked() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n</code>\n</div>"],"alt":"black 50x50 rect turns white with mouse doubleClick/press.\nno image displayed","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/mouse.js","line":804,"description":"<p>The function <a href=\"#/p5/mouseWheel\">mouseWheel()</a> is executed every time a vertical mouse wheel\nevent is detected either triggered by an actual mouse wheel or by a\ntouchpad.<br><br>\nThe event.delta property returns the amount the mouse wheel\nhave scrolled. The values can be positive or negative depending on the\nscroll direction (on OS X with &quot;natural&quot; scrolling enabled, the signs\nare inverted).<br><br>\nBrowsers may have different default behaviors attached to various\nmouse events. To prevent any default behavior for this event, add\n&quot;return false&quot; to the end of the method.<br><br>\nDue to the current support of the &quot;wheel&quot; event on Safari, the function\nmay only work as expected if &quot;return false&quot; is included while using Safari.</p>\n","itemtype":"method","name":"mouseWheel","example":["\n<div>\n<code>\nvar pos = 25;\n\nfunction draw() {\n background(237, 34, 93);\n fill(0);\n rect(25, pos, 50, 50);\n}\n\nfunction mouseWheel(event) {\n print(event.delta);\n //move the square according to the vertical scroll amount\n pos += event.delta;\n //uncomment to block page scrolling\n //return false;\n}\n</code>\n</div>"],"alt":"black 50x50 rect moves up and down with vertical scroll. fuschia background","class":"p5","module":"Events","submodule":"Mouse"},{"file":"src/events/touch.js","line":12,"description":"<p>The system variable touches[] contains an array of the positions of all\ncurrent touch points, relative to (0, 0) of the canvas, and IDs identifying a\nunique touch as it moves. Each element in the array is an object with x, y,\nand id properties.</p>\n<p>The touches[] array is not supported on Safari and IE on touch-based\ndesktops (laptops).</p>\n","itemtype":"property","name":"touches","type":"Object[]","readonly":"","example":["\n<div>\n<code>\n// On a touchscreen device, touch\n// the canvas using one or more fingers\n// at the same time\nfunction draw() {\n clear();\n var display = touches.length + ' touches';\n text(display, 5, 10);\n}\n</code>\n</div>"],"alt":"Number of touches currently registered are displayed on the canvas","class":"p5","module":"Events","submodule":"Touch"},{"file":"src/events/touch.js","line":74,"description":"<p>The touchStarted() function is called once after every time a touch is\nregistered. If no <a href=\"#/p5/touchStarted\">touchStarted()</a> function is defined, the <a href=\"#/p5/mousePressed\">mousePressed()</a>\nfunction will be called instead if it is defined.<br><br>\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add &quot;return false&quot;\nto the end of the method.</p>\n","itemtype":"method","name":"touchStarted","example":["\n<div>\n<code>\n// Touch within the image to change\n// the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchStarted() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nfunction touchStarted() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n</code>\n</div>"],"alt":"50x50 black rect turns white with touch event.\nno image displayed","class":"p5","module":"Events","submodule":"Touch"},{"file":"src/events/touch.js","line":138,"description":"<p>The <a href=\"#/p5/touchMoved\">touchMoved()</a> function is called every time a touch move is registered.\nIf no <a href=\"#/p5/touchMoved\">touchMoved()</a> function is defined, the <a href=\"#/p5/mouseDragged\">mouseDragged()</a> function will\nbe called instead if it is defined.<br><br>\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add &quot;return false&quot;\nto the end of the method.</p>\n","itemtype":"method","name":"touchMoved","example":["\n<div>\n<code>\n// Move your finger across the page\n// to change its value\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchMoved() {\n value = value + 5;\n if (value > 255) {\n value = 0;\n }\n}\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nfunction touchMoved() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n</code>\n</div>"],"alt":"50x50 black rect turns lighter with touch until white. resets\nno image displayed","class":"p5","module":"Events","submodule":"Touch"},{"file":"src/events/touch.js","line":200,"description":"<p>The <a href=\"#/p5/touchEnded\">touchEnded()</a> function is called every time a touch ends. If no\n<a href=\"#/p5/touchEnded\">touchEnded()</a> function is defined, the <a href=\"#/p5/mouseReleased\">mouseReleased()</a> function will be\ncalled instead if it is defined.<br><br>\nBrowsers may have different default behaviors attached to various touch\nevents. To prevent any default behavior for this event, add &quot;return false&quot;\nto the end of the method.</p>\n","itemtype":"method","name":"touchEnded","example":["\n<div>\n<code>\n// Release touch within the image to\n// change the value of the rectangle\n\nvar value = 0;\nfunction draw() {\n fill(value);\n rect(25, 25, 50, 50);\n}\nfunction touchEnded() {\n if (value === 0) {\n value = 255;\n } else {\n value = 0;\n }\n}\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nfunction touchEnded() {\n ellipse(mouseX, mouseY, 5, 5);\n // prevent default\n return false;\n}\n</code>\n</div>"],"alt":"50x50 black rect turns white with touch.\nno image displayed","class":"p5","module":"Events","submodule":"Touch"},{"file":"src/image/filters.js","line":3,"description":"<p>This module defines the filters for use with image buffers.</p>\n<p>This module is basically a collection of functions stored in an object\nas opposed to modules. The functions are destructive, modifying\nthe passed in canvas rather than creating a copy.</p>\n<p>Generally speaking users of this module will use the Filters.apply method\non a canvas to create an effect.</p>\n<p>A number of functions are borrowed/adapted from\n<a href=\"http://www.html5rocks.com/en/tutorials/canvas/imagefilters/\">http://www.html5rocks.com/en/tutorials/canvas/imagefilters/</a>\nor the java processing implementation.</p>\n","class":"p5","module":"Events"},{"file":"src/image/image.js","line":8,"description":"<p>This module defines the p5 methods for the <a href=\"#/p5.Image\">p5.Image</a> class\nfor drawing images to the main display canvas.</p>\n","class":"p5","module":"Image","submodule":"Image"},{"file":"src/image/image.js","line":22,"description":"<p>Creates a new <a href=\"#/p5.Image\">p5.Image</a> (the datatype for storing images). This provides a\nfresh buffer of pixels to play with. Set the size of the buffer with the\nwidth and height parameters.\n<br><br>\n.<a href=\"#/p5.Image/pixels\">pixels</a> gives access to an array containing the values for all the pixels\nin the display window.\nThese values are numbers. This array is the size (including an appropriate\nfactor for the <a href=\"#/p5/pixelDensity\">pixelDensity</a>) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. See .<a href=\"#/p5.Image/pixels\">pixels</a> for\nmore info. It may also be simpler to use <a href=\"#/p5.Image/set\">set()</a> or <a href=\"#/p5.Image/get\">get()</a>.\n<br><br>\nBefore accessing the pixels of an image, the data must loaded with the\n<a href=\"#/p5.Image/loadPixels\">loadPixels()</a> function. After the array data has been modified, the\n<a href=\"#/p5.Image/updatePixels\">updatePixels()</a> function must be run to update the changes.</p>\n","itemtype":"method","name":"createImage","params":[{"name":"width","description":"<p>width in pixels</p>\n","type":"Integer"},{"name":"height","description":"<p>height in pixels</p>\n","type":"Integer"}],"return":{"description":"the <a href=\"#/p5.Image\">p5.Image</a> object","type":"p5.Image"},"example":["\n<div>\n<code>\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n</code>\n</div>\n\n<div>\n<code>\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n</code>\n</div>\n\n<div>\n<code>\nvar pink = color(255, 102, 204);\nvar img = createImage(66, 66);\nimg.loadPixels();\nvar d = pixelDensity();\nvar halfImage = 4 * (img.width * d) * (img.height / 2 * d);\nfor (var i = 0; i < halfImage; i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n</code>\n</div>"],"alt":"66x66 dark turquoise rect in center of canvas.\n2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas\nno image displayed","class":"p5","module":"Image","submodule":"Image"},{"file":"src/image/image.js","line":102,"description":"<p>Save the current canvas as an image. The browser will either save the\nfile immediately, or prompt the user with a dialogue window.</p>\n","itemtype":"method","name":"saveCanvas","example":["\n <div class='norender notest'><code>\n function setup() {\n var c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas(c, 'myCanvas', 'jpg');\n }\n </code></div>\n <div class='norender notest'><code>\n // note that this example has the same result as above\n // if no canvas is specified, defaults to main canvas\n function setup() {\n var c = createCanvas(100, 100);\n background(255, 0, 0);\n saveCanvas('myCanvas', 'jpg');\n\n // all of the following are valid\n saveCanvas(c, 'myCanvas', 'jpg');\n saveCanvas(c, 'myCanvas.jpg');\n saveCanvas(c, 'myCanvas');\n saveCanvas(c);\n saveCanvas('myCanvas', 'png');\n saveCanvas('myCanvas');\n saveCanvas();\n }\n </code></div>"],"alt":"no image displayed\n no image displayed\n no image displayed","class":"p5","module":"Image","submodule":"Image","overloads":[{"line":102,"params":[{"name":"selectedCanvas","description":"<p>a variable\n representing a specific html5 canvas (optional)</p>\n","type":"p5.Element|HTMLCanvasElement"},{"name":"filename","description":"","type":"String","optional":true},{"name":"extension","description":"<p>&#39;jpg&#39; or &#39;png&#39;</p>\n","type":"String","optional":true}]},{"line":144,"params":[{"name":"filename","description":"","type":"String","optional":true},{"name":"extension","description":"","type":"String","optional":true}]}]},{"file":"src/image/image.js","line":195,"description":"<p>Capture a sequence of frames that can be used to create a movie.\nAccepts a callback. For example, you may wish to send the frames\nto a server where they can be stored or converted into a movie.\nIf no callback is provided, the browser will pop up save dialogues in an\nattempt to download all of the images that have just been created. With the\ncallback provided the image data isn&#39;t saved by default but instead passed\nas an argument to the callback function as an array of objects, with the\nsize of array equal to the total number of frames.</p>\n<p>Note that <a href=\"#/p5.Image/saveFrames\">saveFrames()</a> will only save the first 15 frames of an animation.\nTo export longer animations, you might look into a library like\n<a href=\"https://github.com/spite/ccapture.js/\">ccapture.js</a>.</p>\n","itemtype":"method","name":"saveFrames","params":[{"name":"filename","description":"","type":"String"},{"name":"extension","description":"<p>&#39;jpg&#39; or &#39;png&#39;</p>\n","type":"String"},{"name":"duration","description":"<p>Duration in seconds to save the frames for.</p>\n","type":"Number"},{"name":"framerate","description":"<p>Framerate to save the frames in.</p>\n","type":"Number"},{"name":"callback","description":"<p>A callback function that will be executed\n to handle the image data. This function\n should accept an array as argument. The\n array will contain the specified number of\n frames of objects. Each object has three\n properties: imageData - an\n image/octet-stream, filename and extension.</p>\n","type":"Function(Array)","optional":true}],"example":["\n<div><code>\n function draw() {\n background(mouseX);\n }\n\n function mousePressed() {\n saveFrames('out', 'png', 1, 25, function(data) {\n print(data);\n });\n }\n</code></div>"],"alt":"canvas background goes from light to dark with mouse x.","class":"p5","module":"Image","submodule":"Image"},{"file":"src/image/loading_displaying.js","line":17,"description":"<p>Loads an image from a path and creates a <a href=\"#/p5.Image\">p5.Image</a> from it.\n<br><br>\nThe image may not be immediately available for rendering\nIf you want to ensure that the image is ready before doing\nanything with it, place the <a href=\"#/p5/loadImage\">loadImage()</a> call in <a href=\"#/p5/preload\">preload()</a>.\nYou may also supply a callback function to handle the image when it&#39;s ready.\n<br><br>\nThe path to the image should be relative to the HTML file\nthat links in your sketch. Loading an image from a URL or other\nremote location may be blocked due to your browser&#39;s built-in\nsecurity.</p>\n","itemtype":"method","name":"loadImage","params":[{"name":"path","description":"<p>Path of the image to be loaded</p>\n","type":"String"},{"name":"successCallback","description":"<p>Function to be called once\n the image is loaded. Will be passed the\n <a href=\"#/p5.Image\">p5.Image</a>.</p>\n","type":"function(p5.Image)","optional":true},{"name":"failureCallback","description":"<p>called with event error if\n the image fails to load.</p>\n","type":"Function(Event)","optional":true}],"return":{"description":"the <a href=\"#/p5.Image\">p5.Image</a> object","type":"p5.Image"},"example":["\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n}\n</code>\n</div>\n<div>\n<code>\nfunction setup() {\n // here we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', function(img) {\n image(img, 0, 0);\n });\n}\n</code>\n</div>"],"alt":"image of the underside of a white umbrella and grided ceililng above\nimage of the underside of a white umbrella and grided ceililng above","class":"p5","module":"Image","submodule":"Loading & Displaying"},{"file":"src/image/loading_displaying.js","line":125,"description":"<p>Draw an image to the p5.js canvas.</p>\n<p>This function can be used with different numbers of parameters. The\nsimplest use requires only three parameters: img, x, and y—where (x, y) is\nthe position of the image. Two more parameters can optionally be added to\nspecify the width and height of the image.</p>\n<p>This function can also be used with all eight Number parameters. To\ndifferentiate between all these parameters, p5.js uses the language of\n&quot;destination rectangle&quot; (which corresponds to &quot;dx&quot;, &quot;dy&quot;, etc.) and &quot;source\nimage&quot; (which corresponds to &quot;sx&quot;, &quot;sy&quot;, etc.) below. Specifying the\n&quot;source image&quot; dimensions can be useful when you want to display a\nsubsection of the source image instead of the whole thing. Here&#39;s a diagram\nto explain further:\n<img src=\"assets/drawImage.png\"></img></p>\n","itemtype":"method","name":"image","example":["\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height\n image(img, 0, 0);\n}\n</code>\n</div>\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n background(50);\n // Top-left corner of the img is at (10, 10)\n // Width and height are 50 x 50\n image(img, 10, 10, 50, 50);\n}\n</code>\n</div>\n<div>\n<code>\nfunction setup() {\n // Here, we use a callback to display the image after loading\n loadImage('assets/laDefense.jpg', function(img) {\n image(img, 0, 0);\n });\n}\n</code>\n</div>\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/gradient.png');\n}\nfunction setup() {\n // 1. Background image\n // Top-left corner of the img is at (0, 0)\n // Width and height are the img's original width and height, 100 x 100\n image(img, 0, 0);\n // 2. Top right image\n // Top-left corner of destination rectangle is at (50, 0)\n // Destination rectangle width and height are 40 x 20\n // The next parameters are relative to the source image:\n // - Starting at position (50, 50) on the source image, capture a 50 x 50\n // subsection\n // - Draw this subsection to fill the dimensions of the destination rectangle\n image(img, 50, 0, 40, 20, 50, 50, 50, 50);\n}\n</code>\n</div>"],"alt":"image of the underside of a white umbrella and gridded ceiling above\nimage of the underside of a white umbrella and gridded ceiling above","class":"p5","module":"Image","submodule":"Loading & Displaying","overloads":[{"line":125,"params":[{"name":"img","description":"<p>the image to display</p>\n","type":"p5.Image|p5.Element"},{"name":"x","description":"<p>the x-coordinate of the top-left corner of the image</p>\n","type":"Number"},{"name":"y","description":"<p>the y-coordinate of the top-left corner of the image</p>\n","type":"Number"},{"name":"width","description":"<p>the width to draw the image</p>\n","type":"Number","optional":true},{"name":"height","description":"<p>the height to draw the image</p>\n","type":"Number","optional":true}]},{"line":213,"params":[{"name":"img","description":"","type":"p5.Image|p5.Element"},{"name":"dx","description":"<p>the x-coordinate of the destination\n rectangle in which to draw the source image</p>\n","type":"Number"},{"name":"dy","description":"<p>the y-coordinate of the destination\n rectangle in which to draw the source image</p>\n","type":"Number"},{"name":"dWidth","description":"<p>the width of the destination rectangle</p>\n","type":"Number"},{"name":"dHeight","description":"<p>the height of the destination rectangle</p>\n","type":"Number"},{"name":"sx","description":"<p>the x-coordinate of the subsection of the source\nimage to draw into the destination rectangle</p>\n","type":"Number"},{"name":"sy","description":"<p>the y-coordinate of the subsection of the source\nimage to draw into the destination rectangle</p>\n","type":"Number"},{"name":"sWidth","description":"<p>the width of the subsection of the\n source image to draw into the destination\n rectangle</p>\n","type":"Number","optional":true},{"name":"sHeight","description":"<p>the height of the subsection of the\n source image to draw into the destination rectangle</p>\n","type":"Number","optional":true}]}]},{"file":"src/image/loading_displaying.js","line":296,"description":"<p>Sets the fill value for displaying images. Images can be tinted to\nspecified colors or made transparent by including an alpha value.\n<br><br>\nTo apply transparency to an image without affecting its color, use\nwhite as the tint color and specify an alpha value. For instance,\ntint(255, 128) will make an image 50% transparent (assuming the default\nalpha range of 0-255, which can be changed with <a href=\"#/p5/colorMode\">colorMode()</a>).\n<br><br>\nThe value for the gray parameter must be less than or equal to the current\nmaximum value as specified by <a href=\"#/p5/colorMode\">colorMode()</a>. The default maximum value is\n255.</p>\n","itemtype":"method","name":"tint","example":["\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204); // Tint blue\n image(img, 50, 0);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(0, 153, 204, 126); // Tint blue and set transparency\n image(img, 50, 0);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n tint(255, 126); // Apply transparency without changing color\n image(img, 50, 0);\n}\n</code>\n</div>"],"alt":"2 side by side images of umbrella and ceiling, one image with blue tint\nImages of umbrella and ceiling, one half of image with blue tint\n2 side by side images of umbrella and ceiling, one image translucent","class":"p5","module":"Image","submodule":"Loading & Displaying","overloads":[{"line":296,"params":[{"name":"v1","description":"<p>red or hue value relative to\n the current color range</p>\n","type":"Number"},{"name":"v2","description":"<p>green or saturation value\n relative to the current color range</p>\n","type":"Number"},{"name":"v3","description":"<p>blue or brightness value\n relative to the current color range</p>\n","type":"Number"},{"name":"alpha","description":"","type":"Number","optional":true}]},{"line":369,"params":[{"name":"value","description":"<p>a color string</p>\n","type":"String"}]},{"line":374,"params":[{"name":"gray","description":"<p>a gray value</p>\n","type":"Number"},{"name":"alpha","description":"","type":"Number","optional":true}]},{"line":380,"params":[{"name":"values","description":"<p>an array containing the red,green,blue &amp;\n and alpha components of the color</p>\n","type":"Number[]"}]},{"line":386,"params":[{"name":"color","description":"<p>the tint color</p>\n","type":"p5.Color"}]}]},{"file":"src/image/loading_displaying.js","line":396,"description":"<p>Removes the current fill value for displaying images and reverts to\ndisplaying images with their original hues.</p>\n","itemtype":"method","name":"noTint","example":["\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n tint(0, 153, 204); // Tint blue\n image(img, 0, 0);\n noTint(); // Disable tint\n image(img, 50, 0);\n}\n</code>\n</div>"],"alt":"2 side by side images of bricks, left image with blue tint","class":"p5","module":"Image","submodule":"Loading & Displaying"},{"file":"src/image/loading_displaying.js","line":462,"description":"<p>Set image mode. Modifies the location from which images are drawn by\nchanging the way in which parameters given to <a href=\"#/p5/image\">image()</a> are interpreted.\nThe default mode is imageMode(CORNER), which interprets the second and\nthird parameters of <a href=\"#/p5/image\">image()</a> as the upper-left corner of the image. If\ntwo additional parameters are specified, they are used to set the image&#39;s\nwidth and height.\n<br><br>\nimageMode(CORNERS) interprets the second and third parameters of <a href=\"#/p5/image\">image()</a>\nas the location of one corner, and the fourth and fifth parameters as the\nopposite corner.\n<br><br>\nimageMode(CENTER) interprets the second and third parameters of <a href=\"#/p5/image\">image()</a>\nas the image&#39;s center point. If two additional parameters are specified,\nthey are used to set the image&#39;s width and height.</p>\n","itemtype":"method","name":"imageMode","params":[{"name":"mode","description":"<p>either CORNER, CORNERS, or CENTER</p>\n","type":"Constant"}],"example":["\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNER);\n image(img, 10, 10, 50, 50);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CORNERS);\n image(img, 10, 10, 90, 40);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n imageMode(CENTER);\n image(img, 50, 50, 80, 80);\n}\n</code>\n</div>"],"alt":"small square image of bricks\nhorizontal rectangle image of bricks\nlarge square image of bricks","class":"p5","module":"Image","submodule":"Loading & Displaying"},{"file":"src/image/p5.Image.js","line":9,"description":"<p>This module defines the <a href=\"#/p5.Image\">p5.Image</a> class and P5 methods for\ndrawing images to the main display canvas.</p>\n","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/p5.Image.js","line":90,"description":"<p>Image width.</p>\n","itemtype":"property","name":"width","type":"Number","readonly":"","example":["\n<div><code>\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (var i = 0; i < img.width; i++) {\n var c = img.get(i, img.height / 2);\n stroke(c);\n line(i, height / 2, i, height);\n }\n}\n</code></div>"],"alt":"rocky mountains in top and horizontal lines in corresponding colors in bottom.","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/p5.Image.js","line":117,"description":"<p>Image height.</p>\n","itemtype":"property","name":"height","type":"Number","readonly":"","example":["\n<div><code>\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n image(img, 0, 0);\n for (var i = 0; i < img.height; i++) {\n var c = img.get(img.width / 2, i);\n stroke(c);\n line(0, i, width / 2, i);\n }\n}\n</code></div>"],"alt":"rocky mountains on right and vertical lines in corresponding colors on left.","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/p5.Image.js","line":152,"description":"<p>Array containing the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for pixelDensity) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh denisty displays may have more pixels (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. With\npixelDensity = 2, there will be 160,000. The first four values\n(indices 0-3) in the array will be the R, G, B, A values of the pixel at\n(0, 0). The second four values (indices 4-7) will contain the R, G, B, A\nvalues of the pixel at (1, 0). More generally, to set values for a pixel\nat (x, y):</p>\n<pre><code class=\"lang-javascript\">var d = pixelDensity();\nfor (var i = 0; i &lt; d; i++) {\n for (var j = 0; j &lt; d; j++) {\n // loop over\n idx = 4 * ((y * d + j) * width * d + (x * d + i));\n pixels[idx] = r;\n pixels[idx+1] = g;\n pixels[idx+2] = b;\n pixels[idx+3] = a;\n }\n}\n</code></pre>\n<p><br><br>\nBefore accessing this array, the data must loaded with the <a href=\"#/p5.Image/loadPixels\">loadPixels()</a>\nfunction. After the array data has been modified, the <a href=\"#/p5.Image/updatePixels\">updatePixels()</a>\nfunction must be run to update the changes.</p>\n","itemtype":"property","name":"pixels","type":"Number[]","example":["\n<div>\n<code>\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\n</code>\n</div>\n<div>\n<code>\nvar pink = color(255, 102, 204);\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < 4 * (width * height / 2); i += 4) {\n img.pixels[i] = red(pink);\n img.pixels[i + 1] = green(pink);\n img.pixels[i + 2] = blue(pink);\n img.pixels[i + 3] = alpha(pink);\n}\nimg.updatePixels();\nimage(img, 17, 17);\n</code>\n</div>"],"alt":"66x66 turquoise rect in center of canvas\n66x66 pink rect in center of canvas","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/p5.Image.js","line":222,"description":"<p>Helper fxn for sharing pixel methods</p>\n","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/p5.Image.js","line":231,"description":"<p>Loads the pixels data for this image into the [pixels] attribute.</p>\n","itemtype":"method","name":"loadPixels","example":["\n<div><code>\nvar myImage;\nvar halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * width * height / 2;\n for (var i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0);\n}\n</code></div>"],"alt":"2 images of rocky mountains vertically stacked","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/p5.Image.js","line":267,"description":"<p>Updates the backing canvas for this image with the contents of\nthe [pixels] array.</p>\n","itemtype":"method","name":"updatePixels","example":["\n<div><code>\nvar myImage;\nvar halfImage;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n myImage.loadPixels();\n halfImage = 4 * width * height / 2;\n for (var i = 0; i < halfImage; i++) {\n myImage.pixels[i + halfImage] = myImage.pixels[i];\n }\n myImage.updatePixels();\n}\n\nfunction draw() {\n image(myImage, 0, 0);\n}\n</code></div>"],"alt":"2 images of rocky mountains vertically stacked","class":"p5.Image","module":"Image","submodule":"Image","overloads":[{"line":267,"params":[{"name":"x","description":"<p>x-offset of the target update area for the\n underlying canvas</p>\n","type":"Integer"},{"name":"y","description":"<p>y-offset of the target update area for the\n underlying canvas</p>\n","type":"Integer"},{"name":"w","description":"<p>height of the target update area for the\n underlying canvas</p>\n","type":"Integer"},{"name":"h","description":"<p>height of the target update area for the\n underlying canvas</p>\n","type":"Integer"}]},{"line":307,"params":[]}]},{"file":"src/image/p5.Image.js","line":315,"description":"<p>Get a region of pixels from an image.</p>\n<p>If no params are passed, those whole image is returned,\nif x and y are the only params passed a single pixel is extracted\nif all params are passed a rectangle region is extracted and a <a href=\"#/p5.Image\">p5.Image</a>\nis returned.</p>\n<p>Returns undefined if the region is outside the bounds of the image</p>\n","itemtype":"method","name":"get","params":[{"name":"x","description":"<p>x-coordinate of the pixel</p>\n","type":"Number","optional":true},{"name":"y","description":"<p>y-coordinate of the pixel</p>\n","type":"Number","optional":true},{"name":"w","description":"<p>width</p>\n","type":"Number","optional":true},{"name":"h","description":"<p>height</p>\n","type":"Number","optional":true}],"return":{"description":"color of pixel at x,y in array format\n [R, G, B, A] or <a href=\"#/p5.Image\">p5.Image</a>","type":"Number[]|Color|p5.Image"},"example":["\n<div><code>\nvar myImage;\nvar c;\n\nfunction preload() {\n myImage = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(myImage);\n noStroke();\n c = myImage.get(60, 90);\n fill(c);\n rect(25, 25, 50, 50);\n}\n\n//get() returns color here\n</code></div>"],"alt":"image of rocky mountains with 50x50 green rect in front","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/p5.Image.js","line":360,"description":"<p>Set the color of a single pixel or write an image into\nthis <a href=\"#/p5.Image\">p5.Image</a>.</p>\n<p>Note that for a large number of pixels this will\nbe slower than directly manipulating the pixels array\nand then calling <a href=\"#/p5.Image/updatePixels\">updatePixels()</a>.</p>\n","itemtype":"method","name":"set","params":[{"name":"x","description":"<p>x-coordinate of the pixel</p>\n","type":"Number"},{"name":"y","description":"<p>y-coordinate of the pixel</p>\n","type":"Number"},{"name":"a","description":"<p>grayscale value | pixel array |\n a <a href=\"#/p5.Color\">p5.Color</a> | image to copy</p>\n","type":"Number|Number[]|Object"}],"example":["\n<div>\n<code>\nvar img = createImage(66, 66);\nimg.loadPixels();\nfor (var i = 0; i < img.width; i++) {\n for (var j = 0; j < img.height; j++) {\n img.set(i, j, color(0, 90, 102, (i % img.width) * 2));\n }\n}\nimg.updatePixels();\nimage(img, 17, 17);\nimage(img, 34, 34);\n</code>\n</div>"],"alt":"2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/p5.Image.js","line":398,"description":"<p>Resize the image to a new width and height. To make the image scale\nproportionally, use 0 as the value for the wide or high parameter.\nFor instance, to make the width of an image 150 pixels, and change\nthe height using the same proportion, use resize(150, 0).</p>\n","itemtype":"method","name":"resize","params":[{"name":"width","description":"<p>the resized image width</p>\n","type":"Number"},{"name":"height","description":"<p>the resized image height</p>\n","type":"Number"}],"example":["\n<div><code>\nvar img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(img, 0, 0);\n}\n\nfunction mousePressed() {\n img.resize(50, 100);\n}\n</code></div>"],"alt":"image of rocky mountains. zoomed in","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/p5.Image.js","line":483,"description":"<p>Copies a region of pixels from one image to another. If no\nsrcImage is specified this is used as the source. If the source\nand destination regions aren&#39;t the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.</p>\n","itemtype":"method","name":"copy","example":["\n<div><code>\nvar photo;\nvar bricks;\nvar x;\nvar y;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks.jpg');\n}\n\nfunction setup() {\n x = bricks.width / 2;\n y = bricks.height / 2;\n photo.copy(bricks, 0, 0, x, y, 0, 0, x, y);\n image(photo, 0, 0);\n}\n</code></div>"],"alt":"image of rocky mountains and smaller image on top of bricks at top left","class":"p5.Image","module":"Image","submodule":"Image","overloads":[{"line":483,"params":[{"name":"srcImage","description":"<p>source image</p>\n","type":"p5.Image|p5.Element"},{"name":"sx","description":"<p>X coordinate of the source&#39;s upper left corner</p>\n","type":"Integer"},{"name":"sy","description":"<p>Y coordinate of the source&#39;s upper left corner</p>\n","type":"Integer"},{"name":"sw","description":"<p>source image width</p>\n","type":"Integer"},{"name":"sh","description":"<p>source image height</p>\n","type":"Integer"},{"name":"dx","description":"<p>X coordinate of the destination&#39;s upper left corner</p>\n","type":"Integer"},{"name":"dy","description":"<p>Y coordinate of the destination&#39;s upper left corner</p>\n","type":"Integer"},{"name":"dw","description":"<p>destination image width</p>\n","type":"Integer"},{"name":"dh","description":"<p>destination image height</p>\n","type":"Integer"}]},{"line":524,"params":[{"name":"sx","description":"","type":"Integer"},{"name":"sy","description":"","type":"Integer"},{"name":"sw","description":"","type":"Integer"},{"name":"sh","description":"","type":"Integer"},{"name":"dx","description":"","type":"Integer"},{"name":"dy","description":"","type":"Integer"},{"name":"dw","description":"","type":"Integer"},{"name":"dh","description":"","type":"Integer"}]}]},{"file":"src/image/p5.Image.js","line":564,"description":"<p>Masks part of an image from displaying by loading another\nimage and using it&#39;s alpha channel as an alpha channel for\nthis image.</p>\n","itemtype":"method","name":"mask","params":[{"name":"srcImage","description":"<p>source image</p>\n","type":"p5.Image"}],"example":["\n<div><code>\nvar photo, maskImage;\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n maskImage = loadImage('assets/mask2.png');\n}\n\nfunction setup() {\n createCanvas(100, 100);\n photo.mask(maskImage);\n image(photo, 0, 0);\n}\n</code></div>"],"alt":"image of rocky mountains with white at right\n\n\nhttp://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/p5.Image.js","line":627,"description":"<p>Applies an image filter to a <a href=\"#/p5.Image\">p5.Image</a></p>\n","itemtype":"method","name":"filter","params":[{"name":"filterType","description":"<p>either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter</p>\n","type":"Constant"},{"name":"filterParam","description":"<p>an optional parameter unique\n to each filter, see above</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar photo1;\nvar photo2;\n\nfunction preload() {\n photo1 = loadImage('assets/rockies.jpg');\n photo2 = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n photo2.filter('gray');\n image(photo1, 0, 0);\n image(photo2, width / 2, 0);\n}\n</code></div>"],"alt":"2 images of rocky mountains left one in color, right in black and white","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/p5.Image.js","line":663,"description":"<p>Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation.</p>\n","itemtype":"method","name":"blend","example":["\n<div><code>\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n</code></div>\n<div><code>\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n</code></div>\n<div><code>\nvar mountains;\nvar bricks;\n\nfunction preload() {\n mountains = loadImage('assets/rockies.jpg');\n bricks = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n image(mountains, 0, 0);\n image(bricks, 0, 0);\n}\n</code></div>"],"alt":"image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent","class":"p5.Image","module":"Image","submodule":"Image","overloads":[{"line":663,"params":[{"name":"srcImage","description":"<p>source image</p>\n","type":"p5.Image"},{"name":"sx","description":"<p>X coordinate of the source&#39;s upper left corner</p>\n","type":"Integer"},{"name":"sy","description":"<p>Y coordinate of the source&#39;s upper left corner</p>\n","type":"Integer"},{"name":"sw","description":"<p>source image width</p>\n","type":"Integer"},{"name":"sh","description":"<p>source image height</p>\n","type":"Integer"},{"name":"dx","description":"<p>X coordinate of the destination&#39;s upper left corner</p>\n","type":"Integer"},{"name":"dy","description":"<p>Y coordinate of the destination&#39;s upper left corner</p>\n","type":"Integer"},{"name":"dw","description":"<p>destination image width</p>\n","type":"Integer"},{"name":"dh","description":"<p>destination image height</p>\n","type":"Integer"},{"name":"blendMode","description":"<p>the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.</p>\n<p>Available blend modes are: normal | multiply | screen | overlay |\n darken | lighten | color-dodge | color-burn | hard-light |\n soft-light | difference | exclusion | hue | saturation |\n color | luminosity</p>\n<p><a href=\"http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/\">http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/</a></p>\n","type":"Constant"}]},{"line":742,"params":[{"name":"sx","description":"","type":"Integer"},{"name":"sy","description":"","type":"Integer"},{"name":"sw","description":"","type":"Integer"},{"name":"sh","description":"","type":"Integer"},{"name":"dx","description":"","type":"Integer"},{"name":"dy","description":"","type":"Integer"},{"name":"dw","description":"","type":"Integer"},{"name":"dh","description":"","type":"Integer"},{"name":"blendMode","description":"","type":"Constant"}]}]},{"file":"src/image/p5.Image.js","line":785,"description":"<p>Saves the image to a file and force the browser to download it.\nAccepts two strings for filename and file extension\nSupports png (default) and jpg.</p>\n","itemtype":"method","name":"save","params":[{"name":"filename","description":"<p>give your file a name</p>\n","type":"String"},{"name":"extension","description":"<p>&#39;png&#39; or &#39;jpg&#39;</p>\n","type":"String"}],"example":["\n<div><code>\nvar photo;\n\nfunction preload() {\n photo = loadImage('assets/rockies.jpg');\n}\n\nfunction draw() {\n image(photo, 0, 0);\n}\n\nfunction keyTyped() {\n if (key === 's') {\n photo.save('photo', 'png');\n }\n}\n</code></div>"],"alt":"image of rocky mountains.","class":"p5.Image","module":"Image","submodule":"Image"},{"file":"src/image/pixels.js","line":14,"description":"<p><a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference\n/Global_Objects/Uint8ClampedArray' target='_blank'>Uint8ClampedArray</a>\ncontaining the values for all the pixels in the display window.\nThese values are numbers. This array is the size (include an appropriate\nfactor for <a href=\"#/p5/pixelDensity\">pixelDensity</a>) of the display window x4,\nrepresenting the R, G, B, A values in order for each pixel, moving from\nleft to right across each row, then down each column. Retina and other\nhigh density displays will have more pixels[] (by a factor of\npixelDensity^2).\nFor example, if the image is 100x100 pixels, there will be 40,000. On a\nretina display, there will be 160,000.\n<br><br>\nThe first four values (indices 0-3) in the array will be the R, G, B, A\nvalues of the pixel at (0, 0). The second four values (indices 4-7) will\ncontain the R, G, B, A values of the pixel at (1, 0). More generally, to\nset values for a pixel at (x, y):</p>\n<pre><code class=\"lang-javascript\">var d = pixelDensity();\nfor (var i = 0; i &lt; d; i++) {\n for (var j = 0; j &lt; d; j++) {\n // loop over\n idx = 4 * ((y * d + j) * width * d + (x * d + i));\n pixels[idx] = r;\n pixels[idx+1] = g;\n pixels[idx+2] = b;\n pixels[idx+3] = a;\n }\n}\n</code></pre>\n<p>While the above method is complex, it is flexible enough to work with\nany pixelDensity. Note that <a href=\"#/p5/set\">set()</a> will automatically take care of\nsetting all the appropriate values in <a href=\"#/p5/pixels\">pixels[]</a> for a given (x, y) at\nany pixelDensity, but the performance may not be as fast when lots of\nmodifications are made to the pixel array.\n<br><br>\nBefore accessing this array, the data must loaded with the <a href=\"#/p5/loadPixels\">loadPixels()</a>\nfunction. After the array data has been modified, the <a href=\"#/p5/updatePixels\">updatePixels()</a>\nfunction must be run to update the changes.\n<br><br>\nNote that this is not a standard javascript array. This means that\nstandard javascript functions such as <a href=\"#/p5/slice\">slice()</a> or\n<a href=\"#/p5/arrayCopy\">arrayCopy()</a> do not\nwork.</p>","itemtype":"property","name":"pixels","type":"Number[]","example":["\n<div>\n<code>\nvar pink = color(255, 102, 204);\nloadPixels();\nvar d = pixelDensity();\nvar halfImage = 4 * (width * d) * (height / 2 * d);\nfor (var i = 0; i < halfImage; i += 4) {\n pixels[i] = red(pink);\n pixels[i + 1] = green(pink);\n pixels[i + 2] = blue(pink);\n pixels[i + 3] = alpha(pink);\n}\nupdatePixels();\n</code>\n</div>"],"alt":"top half of canvas pink, bottom grey","class":"p5","module":"Image","submodule":"Pixels"},{"file":"src/image/pixels.js","line":83,"description":"<p>Copies a region of pixels from one image to another, using a specified\nblend mode to do the operation.</p>\n","itemtype":"method","name":"blend","example":["\n<div><code>\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST);\n}\n</code></div>\n<div><code>\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST);\n}\n</code></div>\n<div><code>\nvar img0;\nvar img1;\n\nfunction preload() {\n img0 = loadImage('assets/rockies.jpg');\n img1 = loadImage('assets/bricks_third.jpg');\n}\n\nfunction setup() {\n background(img0);\n image(img1, 0, 0);\n blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD);\n}\n</code></div>"],"alt":"image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent","class":"p5","module":"Image","submodule":"Pixels","overloads":[{"line":83,"params":[{"name":"srcImage","description":"<p>source image</p>\n","type":"p5.Image"},{"name":"sx","description":"<p>X coordinate of the source&#39;s upper left corner</p>\n","type":"Integer"},{"name":"sy","description":"<p>Y coordinate of the source&#39;s upper left corner</p>\n","type":"Integer"},{"name":"sw","description":"<p>source image width</p>\n","type":"Integer"},{"name":"sh","description":"<p>source image height</p>\n","type":"Integer"},{"name":"dx","description":"<p>X coordinate of the destination&#39;s upper left corner</p>\n","type":"Integer"},{"name":"dy","description":"<p>Y coordinate of the destination&#39;s upper left corner</p>\n","type":"Integer"},{"name":"dw","description":"<p>destination image width</p>\n","type":"Integer"},{"name":"dh","description":"<p>destination image height</p>\n","type":"Integer"},{"name":"blendMode","description":"<p>the blend mode. either\n BLEND, DARKEST, LIGHTEST, DIFFERENCE,\n MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT,\n SOFT_LIGHT, DODGE, BURN, ADD or NORMAL.</p>\n","type":"Constant"}]},{"line":156,"params":[{"name":"sx","description":"","type":"Integer"},{"name":"sy","description":"","type":"Integer"},{"name":"sw","description":"","type":"Integer"},{"name":"sh","description":"","type":"Integer"},{"name":"dx","description":"","type":"Integer"},{"name":"dy","description":"","type":"Integer"},{"name":"dw","description":"","type":"Integer"},{"name":"dh","description":"","type":"Integer"},{"name":"blendMode","description":"","type":"Constant"}]}]},{"file":"src/image/pixels.js","line":177,"description":"<p>Copies a region of the canvas to another region of the canvas\nand copies a region of pixels from an image used as the srcImg parameter\ninto the canvas srcImage is specified this is used as the source. If\nthe source and destination regions aren&#39;t the same size, it will\nautomatically resize source pixels to fit the specified\ntarget region.</p>\n","itemtype":"method","name":"copy","example":["\n<div><code>\nvar img;\n\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n background(img);\n copy(img, 7, 22, 10, 10, 35, 25, 50, 50);\n stroke(255);\n noFill();\n // Rectangle shows area being copied\n rect(7, 22, 10, 10);\n}\n</code></div>"],"alt":"image of rocky mountains. Brick images on left and right. Right overexposed\nimage of rockies. Brickwall images on left and right. Right mortar transparent\nimage of rockies. Brickwall images on left and right. Right translucent","class":"p5","module":"Image","submodule":"Pixels","overloads":[{"line":177,"params":[{"name":"srcImage","description":"<p>source image</p>\n","type":"p5.Image|p5.Element"},{"name":"sx","description":"<p>X coordinate of the source&#39;s upper left corner</p>\n","type":"Integer"},{"name":"sy","description":"<p>Y coordinate of the source&#39;s upper left corner</p>\n","type":"Integer"},{"name":"sw","description":"<p>source image width</p>\n","type":"Integer"},{"name":"sh","description":"<p>source image height</p>\n","type":"Integer"},{"name":"dx","description":"<p>X coordinate of the destination&#39;s upper left corner</p>\n","type":"Integer"},{"name":"dy","description":"<p>Y coordinate of the destination&#39;s upper left corner</p>\n","type":"Integer"},{"name":"dw","description":"<p>destination image width</p>\n","type":"Integer"},{"name":"dh","description":"<p>destination image height</p>\n","type":"Integer"}]},{"line":220,"params":[{"name":"sx","description":"","type":"Integer"},{"name":"sy","description":"","type":"Integer"},{"name":"sw","description":"","type":"Integer"},{"name":"sh","description":"","type":"Integer"},{"name":"dx","description":"","type":"Integer"},{"name":"dy","description":"","type":"Integer"},{"name":"dw","description":"","type":"Integer"},{"name":"dh","description":"","type":"Integer"}]}]},{"file":"src/image/pixels.js","line":236,"description":"<p>Applies a filter to the canvas.\n<br><br></p>\n<p>The presets options are:\n<br><br></p>\n<p>THRESHOLD\nConverts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.\n<br><br></p>\n<p>GRAY\nConverts any colors in the image to grayscale equivalents. No parameter\nis used.\n<br><br></p>\n<p>OPAQUE\nSets the alpha channel to entirely opaque. No parameter is used.\n<br><br></p>\n<p>INVERT\nSets each pixel to its inverse value. No parameter is used.\n<br><br></p>\n<p>POSTERIZE\nLimits each channel of the image to the number of colors specified as the\nparameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.\n<br><br></p>\n<p>BLUR\nExecutes a Gaussian blur with the level parameter specifying the extent\nof the blurring. If no parameter is used, the blur is equivalent to\nGaussian blur of radius 1. Larger values increase the blur.\n<br><br></p>\n<p>ERODE\nReduces the light areas. No parameter is used.\n<br><br></p>\n<p>DILATE\nIncreases the light areas. No parameter is used.</p>\n","itemtype":"method","name":"filter","params":[{"name":"filterType","description":"<p>either THRESHOLD, GRAY, OPAQUE, INVERT,\n POSTERIZE, BLUR, ERODE, DILATE or BLUR.\n See Filters.js for docs on\n each available filter</p>\n","type":"Constant"},{"name":"filterParam","description":"<p>an optional parameter unique\n to each filter, see above</p>\n","type":"Number","optional":true}],"example":["\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(THRESHOLD);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(GRAY);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(OPAQUE);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(INVERT);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(POSTERIZE, 3);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(DILATE);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(BLUR, 3);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/bricks.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n filter(ERODE);\n}\n</code>\n</div>"],"alt":"black and white image of a brick wall.\ngreyscale image of a brickwall\nimage of a brickwall\njade colored image of a brickwall\nred and pink image of a brickwall\nimage of a brickwall\nblurry image of a brickwall\nimage of a brickwall\nimage of a brickwall with less detail","class":"p5","module":"Image","submodule":"Pixels"},{"file":"src/image/pixels.js","line":415,"description":"<p>Returns an array of [R,G,B,A] values for any pixel or grabs a section of\nan image. If no parameters are specified, the entire image is returned.\nUse the x and y parameters to get the value of one pixel. Get a section of\nthe display window by specifying additional w and h parameters. When\ngetting an image, the x and y parameters define the coordinates for the\nupper-left corner of the image, regardless of the current <a href=\"#/p5/imageMode\">imageMode()</a>.\n<br><br>\nIf the pixel requested is outside of the image window, [0,0,0,255] is\nreturned. To get the numbers scaled according to the current color ranges\nand taking into account <a href=\"#/p5/colorMode\">colorMode</a>, use <a href=\"#/p5/getColor\">getColor</a> instead of get.\n<br><br>\nGetting the color of a single pixel with get(x, y) is easy, but not as fast\nas grabbing the data directly from <a href=\"#/p5/pixels\">pixels[]</a>. The equivalent statement to\nget(x, y) using <a href=\"#/p5/pixels\">pixels[]</a> with pixel density d is\n<code>\nvar x, y, d; // set these to the coordinates\nvar off = (y <em> width + x) </em> d * 4;\nvar components = [\n pixels[off],\n pixels[off + 1],\n pixels[off + 2],\n pixels[off + 3]\n];\nprint(components);\n</code>\n<br><br>\nSee the reference for <a href=\"#/p5/pixels\">pixels[]</a> for more information.</p>\n<p>If you want to extract an array of colors or a subimage from an p5.Image object,\ntake a look at <a href=\"#/p5.Image/get\">p5.Image.get()</a></p>\n","itemtype":"method","name":"get","params":[{"name":"x","description":"<p>x-coordinate of the pixel</p>\n","type":"Number","optional":true},{"name":"y","description":"<p>y-coordinate of the pixel</p>\n","type":"Number","optional":true},{"name":"w","description":"<p>width</p>\n","type":"Number","optional":true},{"name":"h","description":"<p>height</p>\n","type":"Number","optional":true}],"return":{"description":"values of pixel at x,y in array format\n [R, G, B, A] or <a href=\"#/p5.Image\">p5.Image</a>","type":"Number[]|p5.Image"},"example":["\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n var c = get();\n image(c, width / 2, 0);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\nfunction setup() {\n image(img, 0, 0);\n var c = get(50, 90);\n fill(c);\n noStroke();\n rect(25, 25, 50, 50);\n}\n</code>\n</div>"],"alt":"2 images of the rocky mountains, side-by-side\nImage of the rocky mountains with 50x50 green rect in center of canvas","class":"p5","module":"Image","submodule":"Pixels"},{"file":"src/image/pixels.js","line":494,"description":"<p>Loads the pixel data for the display window into the <a href=\"#/p5/pixels\">pixels[]</a> array. This\nfunction must always be called before reading from or writing to <a href=\"#/p5/pixels\">pixels[]</a>.\nNote that only changes made with <a href=\"#/p5/set\">set()</a> or direct manipulation of <a href=\"#/p5/pixels\">pixels[]</a>\nwill occur.</p>\n","itemtype":"method","name":"loadPixels","example":["\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0);\n var d = pixelDensity();\n var halfImage = 4 * (img.width * d) * (img.height * d / 2);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n</code>\n</div>"],"alt":"two images of the rocky mountains. one on top, one on bottom of canvas.","class":"p5","module":"Image","submodule":"Pixels"},{"file":"src/image/pixels.js","line":531,"description":"<p>Changes the color of any pixel, or writes an image directly to the\ndisplay window.</p>\n<p>The x and y parameters specify the pixel to change and the c parameter\nspecifies the color value. This can be a <a href=\"#/p5.Color\">p5.Color</a> object, or [R, G, B, A]\npixel array. It can also be a single grayscale value.\nWhen setting an image, the x and y parameters define the coordinates for\nthe upper-left corner of the image, regardless of the current <a href=\"#/p5/imageMode\">imageMode()</a>.\n</p>\n<p>\nAfter using <a href=\"#/p5/set\">set()</a>, you must call <a href=\"#/p5/updatePixels\">updatePixels()</a> for your changes to appear.\nThis should be called once all pixels have been set, and must be called before\ncalling .<a href=\"#/p5/get\">get()</a> or drawing the image.\n</p>\n<p>Setting the color of a single pixel with set(x, y) is easy, but not as\nfast as putting the data directly into <a href=\"#/p5/pixels\">pixels[]</a>. Setting the <a href=\"#/p5/pixels\">pixels[]</a>\nvalues directly may be complicated when working with a retina display,\nbut will perform better when lots of pixels need to be set directly on\nevery loop.</p>\n<p>See the reference for <a href=\"#/p5/pixels\">pixels[]</a> for more information.</p>","itemtype":"method","name":"set","params":[{"name":"x","description":"<p>x-coordinate of the pixel</p>\n","type":"Number"},{"name":"y","description":"<p>y-coordinate of the pixel</p>\n","type":"Number"},{"name":"c","description":"<p>insert a grayscale value | a pixel array |\n a <a href=\"#/p5.Color\">p5.Color</a> object | a <a href=\"#/p5.Image\">p5.Image</a> to copy</p>\n","type":"Number|Number[]|Object"}],"example":["\n<div>\n<code>\nvar black = color(0);\nset(30, 20, black);\nset(85, 20, black);\nset(85, 75, black);\nset(30, 75, black);\nupdatePixels();\n</code>\n</div>\n\n<div>\n<code>\nfor (var i = 30; i < width - 15; i++) {\n for (var j = 20; j < height - 25; j++) {\n var c = color(204 - j, 153 - i, 0);\n set(i, j, c);\n }\n}\nupdatePixels();\n</code>\n</div>\n\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n set(0, 0, img);\n updatePixels();\n line(0, 0, width, height);\n line(0, height, width, 0);\n}\n</code>\n</div>"],"alt":"4 black points in the shape of a square middle-right of canvas.\nsquare with orangey-brown gradient lightening at bottom right.\nimage of the rocky mountains. with lines like an 'x' through the center.","class":"p5","module":"Image","submodule":"Pixels"},{"file":"src/image/pixels.js","line":605,"description":"<p>Updates the display window with the data in the <a href=\"#/p5/pixels\">pixels[]</a> array.\nUse in conjunction with <a href=\"#/p5/loadPixels\">loadPixels()</a>. If you&#39;re only reading pixels from\nthe array, there&#39;s no need to call <a href=\"#/p5/updatePixels\">updatePixels()</a> — updating is only\nnecessary to apply changes. <a href=\"#/p5/updatePixels\">updatePixels()</a> should be called anytime the\npixels array is manipulated or <a href=\"#/p5/set\">set()</a> is called, and only changes made with\n<a href=\"#/p5/set\">set()</a> or direct changes to <a href=\"#/p5/pixels\">pixels[]</a> will occur.</p>\n","itemtype":"method","name":"updatePixels","params":[{"name":"x","description":"<p>x-coordinate of the upper-left corner of region\n to update</p>\n","type":"Number","optional":true},{"name":"y","description":"<p>y-coordinate of the upper-left corner of region\n to update</p>\n","type":"Number","optional":true},{"name":"w","description":"<p>width of region to update</p>\n","type":"Number","optional":true},{"name":"h","description":"<p>height of region to update</p>\n","type":"Number","optional":true}],"example":["\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/rockies.jpg');\n}\n\nfunction setup() {\n image(img, 0, 0);\n var d = pixelDensity();\n var halfImage = 4 * (img.width * d) * (img.height * d / 2);\n loadPixels();\n for (var i = 0; i < halfImage; i++) {\n pixels[i + halfImage] = pixels[i];\n }\n updatePixels();\n}\n</code>\n</div>"],"alt":"two images of the rocky mountains. one on top, one on bottom of canvas.","class":"p5","module":"Image","submodule":"Pixels"},{"file":"src/io/files.js","line":19,"description":"<p>Loads a JSON file from a file or a URL, and returns an Object.\nNote that even if the JSON file contains an Array, an Object will be\nreturned with index numbers as keys.</p>\n<p>This method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. JSONP is supported via a polyfill and you\ncan pass in as the second argument an object with definitions of the json\ncallback following the syntax specified <a href=\"https://github.com/camsong/\nfetch-jsonp\">here</a>.</p>\n<p>This method is suitable for fetching files up to size of 64MB.</p>\n","itemtype":"method","name":"loadJSON","return":{"description":"JSON data","type":"Object|Array"},"example":["\n\n<p>Calling <a href=\"#/p5/loadJSON\">loadJSON()</a> inside <a href=\"#/p5/preload\">preload()</a> guarantees to complete the\noperation before <a href=\"#/p5/setup\">setup()</a> and <a href=\"#/p5/draw\">draw()</a> are called.</p>\n\n<div><code>\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nvar earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n var url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n earthquakes = loadJSON(url);\n}\n\nfunction setup() {\n noLoop();\n}\n\nfunction draw() {\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n</code></div>\n\n\n<p>Outside of preload(), you may supply a callback function to handle the\nobject:</p>\n<div><code>\nfunction setup() {\n noLoop();\n var url =\n 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' +\n 'summary/all_day.geojson';\n loadJSON(url, drawEarthquake);\n}\n\nfunction draw() {\n background(200);\n}\n\nfunction drawEarthquake(earthquakes) {\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n}\n</code></div>"],"alt":"50x50 ellipse that changes from black to white depending on the current humidity\n50x50 ellipse that changes from black to white depending on the current humidity","class":"p5","module":"IO","submodule":"Input","overloads":[{"line":19,"params":[{"name":"path","description":"<p>name of the file or url to load</p>\n","type":"String"},{"name":"jsonpOptions","description":"<p>options object for jsonp related settings</p>\n","type":"Object","optional":true},{"name":"datatype","description":"<p>&quot;json&quot; or &quot;jsonp&quot;</p>\n","type":"String","optional":true},{"name":"callback","description":"<p>function to be executed after\n <a href=\"#/p5/loadJSON\">loadJSON()</a> completes, data is passed\n in as first argument</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n","type":"Function","optional":true}],"return":{"description":"JSON data","type":"Object|Array"}},{"line":105,"params":[{"name":"path","description":"","type":"String"},{"name":"datatype","description":"","type":"String"},{"name":"callback","description":"","type":"Function","optional":true},{"name":"errorCallback","description":"","type":"Function","optional":true}],"return":{"description":"","type":"Object|Array"}},{"line":113,"params":[{"name":"path","description":"","type":"String"},{"name":"callback","description":"","type":"Function"},{"name":"errorCallback","description":"","type":"Function","optional":true}],"return":{"description":"","type":"Object|Array"}}]},{"file":"src/io/files.js","line":180,"description":"<p>Reads the contents of a file and creates a String array of its individual\nlines. If the name of the file is used as the parameter, as in the above\nexample, the file must be located in the sketch directory/folder.\n<br><br>\nAlternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.\n<br><br>\nThis method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed.</p>\n<p>This method is suitable for fetching files up to size of 64MB.</p>\n","itemtype":"method","name":"loadStrings","params":[{"name":"filename","description":"<p>name of the file or url to load</p>\n","type":"String"},{"name":"callback","description":"<p>function to be executed after <a href=\"#/p5/loadStrings\">loadStrings()</a>\n completes, Array is passed in as first\n argument</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n","type":"Function","optional":true}],"return":{"description":"Array of Strings","type":"String[]"},"example":["\n\n<p>Calling loadStrings() inside <a href=\"#/p5/preload\">preload()</a> guarantees to complete the\noperation before <a href=\"#/p5/setup\">setup()</a> and <a href=\"#/p5/draw\">draw()</a> are called.</p>\n\n<div><code>\nvar result;\nfunction preload() {\n result = loadStrings('assets/test.txt');\n}\n\nfunction setup() {\n background(200);\n var ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n</code></div>\n\n<p>Outside of preload(), you may supply a callback function to handle the\nobject:</p>\n\n<div><code>\nfunction setup() {\n loadStrings('assets/test.txt', pickString);\n}\n\nfunction pickString(result) {\n background(200);\n var ind = floor(random(result.length));\n text(result[ind], 10, 10, 80, 80);\n}\n</code></div>"],"alt":"randomly generated text from a file, for example \"i smell like butter\"\nrandomly generated text from a file, for example \"i have three feet\"","class":"p5","module":"IO","submodule":"Input"},{"file":"src/io/files.js","line":293,"description":"<p>Reads the contents of a file or URL and creates a <a href=\"#/p5.Table\">p5.Table</a> object with\nits values. If a file is specified, it must be located in the sketch&#39;s\n&quot;data&quot; folder. The filename parameter can also be a URL to a file found\nonline. By default, the file is assumed to be comma-separated (in CSV\nformat). Table only looks for a header row if the &#39;header&#39; option is\nincluded.</p>\n\n<p>Possible options include:\n<ul>\n<li>csv - parse the table as comma-separated values</li>\n<li>tsv - parse the table as tab-separated values</li>\n<li>header - this table has a header (title) row</li>\n</ul>\n</p>\n\n<p>When passing in multiple options, pass them in as separate parameters,\nseperated by commas. For example:\n<br><br>\n<code>\nloadTable(&#39;my_csv_file.csv&#39;, &#39;csv&#39;, &#39;header&#39;);\n</code>\n</p>\n\n<p> All files loaded and saved use UTF-8 encoding.</p>\n\n<p>This method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling <a href=\"#/p5/loadTable\">loadTable()</a> inside <a href=\"#/p5/preload\">preload()</a>\nguarantees to complete the operation before <a href=\"#/p5/setup\">setup()</a> and <a href=\"#/p5/draw\">draw()</a> are called.\n<p>Outside of <a href=\"#/p5/preload\">preload()</a>, you may supply a callback function to handle the\nobject:</p>\n</p>\n\n<p>This method is suitable for fetching files up to size of 64MB.</p>\n","itemtype":"method","name":"loadTable","return":{"description":"<a href=\"#/p5.Table\">Table</a> object containing data","type":"Object"},"example":["\n<div class='norender'>\n<code>\n// Given the following CSV file called \"mammals.csv\"\n// located in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n //the file can be remote\n //table = loadTable(\"http://p5js.org/reference/assets/mammals.csv\",\n // \"csv\", \"header\");\n}\n\nfunction setup() {\n //count the columns\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n\n print(table.getColumn('name'));\n //[\"Goat\", \"Leopard\", \"Zebra\"]\n\n //cycle through the table\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++) {\n print(table.getString(r, c));\n }\n}\n</code>\n</div>"],"alt":"randomly generated text from a file, for example \"i smell like butter\"\nrandomly generated text from a file, for example \"i have three feet\"","class":"p5","module":"IO","submodule":"Input","overloads":[{"line":293,"params":[{"name":"filename","description":"<p>name of the file or URL to load</p>\n","type":"String"},{"name":"options","description":"<p>&quot;header&quot; &quot;csv&quot; &quot;tsv&quot;</p>\n","type":"String"},{"name":"callback","description":"<p>function to be executed after\n <a href=\"#/p5/loadTable\">loadTable()</a> completes. On success, the\n <a href=\"#/p5.Table\">Table</a> object is passed in as the\n first argument.</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n","type":"Function","optional":true}],"return":{"description":"<a href=\"#/p5.Table\">Table</a> object containing data","type":"Object"}},{"line":383,"params":[{"name":"filename","description":"","type":"String"},{"name":"callback","description":"","type":"Function","optional":true},{"name":"errorCallback","description":"","type":"Function","optional":true}],"return":{"description":"","type":"Object"}}]},{"file":"src/io/files.js","line":626,"description":"<p>Reads the contents of a file and creates an XML object with its values.\nIf the name of the file is used as the parameter, as in the above example,\nthe file must be located in the sketch directory/folder.</p>\n<p>Alternatively, the file maybe be loaded from anywhere on the local\ncomputer using an absolute path (something that starts with / on Unix and\nLinux, or a drive letter on Windows), or the filename parameter can be a\nURL for a file found on a network.</p>\n<p>This method is asynchronous, meaning it may not finish before the next\nline in your sketch is executed. Calling <a href=\"#/p5/loadXML\">loadXML()</a> inside <a href=\"#/p5/preload\">preload()</a>\nguarantees to complete the operation before <a href=\"#/p5/setup\">setup()</a> and <a href=\"#/p5/draw\">draw()</a> are called.</p>\n<p>Outside of <a href=\"#/p5/preload\">preload()</a>, you may supply a callback function to handle the\nobject.</p>\n<p>This method is suitable for fetching files up to size of 64MB.</p>\n","itemtype":"method","name":"loadXML","params":[{"name":"filename","description":"<p>name of the file or URL to load</p>\n","type":"String"},{"name":"callback","description":"<p>function to be executed after <a href=\"#/p5/loadXML\">loadXML()</a>\n completes, XML object is passed in as\n first argument</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n","type":"Function","optional":true}],"return":{"description":"XML object containing data","type":"Object"},"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var children = xml.getChildren('animal');\n\n for (var i = 0; i < children.length; i++) {\n var id = children[i].getNum('id');\n var coloring = children[i].getString('species');\n var name = children[i].getContent();\n print(id + ', ' + coloring + ', ' + name);\n }\n}\n\n// Sketch prints:\n// 0, Capra hircus, Goat\n// 1, Panthera pardus, Leopard\n// 2, Equus zebra, Zebra\n</code></div>"],"alt":"no image displayed","class":"p5","module":"IO","submodule":"Input"},{"file":"src/io/files.js","line":737,"description":"<p>This method is suitable for fetching files up to size of 64MB.</p>\n","itemtype":"method","name":"loadBytes","params":[{"name":"file","description":"<p>name of the file or URL to load</p>\n","type":"String"},{"name":"callback","description":"<p>function to be executed after <a href=\"#/p5/loadBytes\">loadBytes()</a>\n completes</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>function to be executed if there\n is an error</p>\n","type":"Function","optional":true}],"return":{"description":"an object whose 'bytes' property will be the loaded buffer","type":"Object"},"example":["\n<div class='norender'><code>\nvar data;\n\nfunction preload() {\n data = loadBytes('assets/mammals.xml');\n}\n\nfunction setup() {\n for (var i = 0; i < 5; i++) {\n console.log(data.bytes[i].toString(16));\n }\n}\n</code></div>"],"alt":"no image displayed","class":"p5","module":"IO","submodule":"Input"},{"file":"src/io/files.js","line":797,"description":"<p>Method for executing an HTTP GET request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling <code>httpDo(path, &#39;GET&#39;)</code>. The &#39;binary&#39; datatype will return\na Blob object, and the &#39;arrayBuffer&#39; datatype will return an ArrayBuffer\nwhich can be used to initialize typed arrays (such as Uint8Array).</p>\n","itemtype":"method","name":"httpGet","return":{"description":"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.","type":"Promise"},"example":["\n<div class='norender'><code>\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\nvar earthquakes;\nfunction preload() {\n // Get the most recent earthquake in the database\n var url =\n 'https://earthquake.usgs.gov/fdsnws/event/1/query?' +\n 'format=geojson&limit=1&orderby=time';\n httpGet(url, 'jsonp', false, function(response) {\n // when the HTTP request completes, populate the variable that holds the\n // earthquake data used in the visualization.\n earthquakes = response;\n });\n}\n\nfunction draw() {\n if (!earthquakes) {\n // Wait until the earthquake data has loaded before drawing.\n return;\n }\n background(200);\n // Get the magnitude and name of the earthquake out of the loaded JSON\n var earthquakeMag = earthquakes.features[0].properties.mag;\n var earthquakeName = earthquakes.features[0].properties.place;\n ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10);\n textAlign(CENTER);\n text(earthquakeName, 0, height - 30, width, 30);\n noLoop();\n}\n</code></div>"],"class":"p5","module":"IO","submodule":"Input","overloads":[{"line":797,"params":[{"name":"path","description":"<p>name of the file or url to load</p>\n","type":"String"},{"name":"datatype","description":"<p>&quot;json&quot;, &quot;jsonp&quot;, &quot;binary&quot;, &quot;arrayBuffer&quot;,\n &quot;xml&quot;, or &quot;text&quot;</p>\n","type":"String","optional":true},{"name":"data","description":"<p>param data passed sent with request</p>\n","type":"Object|Boolean","optional":true},{"name":"callback","description":"<p>function to be executed after\n <a href=\"#/p5/httpGet\">httpGet()</a> completes, data is passed in\n as first argument</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n","type":"Function","optional":true}],"return":{"description":"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.","type":"Promise"}},{"line":851,"params":[{"name":"path","description":"","type":"String"},{"name":"data","description":"","type":"Object|Boolean"},{"name":"callback","description":"","type":"Function","optional":true},{"name":"errorCallback","description":"","type":"Function","optional":true}],"return":{"description":"","type":"Promise"}},{"line":859,"params":[{"name":"path","description":"","type":"String"},{"name":"callback","description":"","type":"Function"},{"name":"errorCallback","description":"","type":"Function","optional":true}],"return":{"description":"","type":"Promise"}}]},{"file":"src/io/files.js","line":874,"description":"<p>Method for executing an HTTP POST request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text. This is equivalent to\ncalling <code>httpDo(path, &#39;POST&#39;)</code>.</p>\n","itemtype":"method","name":"httpPost","return":{"description":"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.","type":"Promise"},"example":["\n<div>\n<code>\n// Examples use jsonplaceholder.typicode.com for a Mock Data API\n\nvar url = 'https://jsonplaceholder.typicode.com/posts';\nvar postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n var r = random(255);\n var g = random(255);\n var b = random(255);\n\n httpPost(url, 'json', postData, function(result) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n ellipse(mouseX, mouseY, 200, 200);\n text(result.body, mouseX, mouseY);\n });\n}\n</code>\n</div>\n\n\n<div><code>\nvar url = 'https://invalidURL'; // A bad URL that will cause errors\nvar postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' };\n\nfunction setup() {\n createCanvas(800, 800);\n}\n\nfunction mousePressed() {\n // Pick new random color values\n var r = random(255);\n var g = random(255);\n var b = random(255);\n\n httpPost(\n url,\n 'json',\n postData,\n function(result) {\n // ... won't be called\n },\n function(error) {\n strokeWeight(2);\n stroke(r, g, b);\n fill(r, g, b, 127);\n text(error.toString(), mouseX, mouseY);\n }\n );\n}\n</code></div>\n"],"class":"p5","module":"IO","submodule":"Input","overloads":[{"line":874,"params":[{"name":"path","description":"<p>name of the file or url to load</p>\n","type":"String"},{"name":"datatype","description":"<p>&quot;json&quot;, &quot;jsonp&quot;, &quot;xml&quot;, or &quot;text&quot;.\n If omitted, <a href=\"#/p5/httpPost\">httpPost()</a> will guess.</p>\n","type":"String","optional":true},{"name":"data","description":"<p>param data passed sent with request</p>\n","type":"Object|Boolean","optional":true},{"name":"callback","description":"<p>function to be executed after\n <a href=\"#/p5/httpPost\">httpPost()</a> completes, data is passed in\n as first argument</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n","type":"Function","optional":true}],"return":{"description":"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.","type":"Promise"}},{"line":956,"params":[{"name":"path","description":"","type":"String"},{"name":"data","description":"","type":"Object|Boolean"},{"name":"callback","description":"","type":"Function","optional":true},{"name":"errorCallback","description":"","type":"Function","optional":true}],"return":{"description":"","type":"Promise"}},{"line":964,"params":[{"name":"path","description":"","type":"String"},{"name":"callback","description":"","type":"Function"},{"name":"errorCallback","description":"","type":"Function","optional":true}],"return":{"description":"","type":"Promise"}}]},{"file":"src/io/files.js","line":979,"description":"<p>Method for executing an HTTP request. If data type is not specified,\np5 will try to guess based on the URL, defaulting to text.<br><br>\nFor more advanced use, you may also pass in the path as the first argument\nand a object as the second argument, the signature follows the one specified\nin the Fetch API specification.\nThis method is suitable for fetching files up to size of 64MB when &quot;GET&quot; is used.</p>\n","itemtype":"method","name":"httpDo","return":{"description":"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.","type":"Promise"},"example":["\n<div>\n<code>\n// Examples use USGS Earthquake API:\n// https://earthquake.usgs.gov/fdsnws/event/1/#methods\n\n// displays an animation of all USGS earthquakes\nvar earthquakes;\nvar eqFeatureIndex = 0;\n\nfunction preload() {\n var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson';\n httpDo(\n url,\n {\n method: 'GET',\n // Other Request options, like special headers for apis\n headers: { authorization: 'Bearer secretKey' }\n },\n function(res) {\n earthquakes = res;\n }\n );\n}\n\nfunction draw() {\n // wait until the data is loaded\n if (!earthquakes || !earthquakes.features[eqFeatureIndex]) {\n return;\n }\n clear();\n\n var feature = earthquakes.features[eqFeatureIndex];\n var mag = feature.properties.mag;\n var rad = mag / 11 * ((width + height) / 2);\n fill(255, 0, 0, 100);\n ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad);\n\n if (eqFeatureIndex >= earthquakes.features.length) {\n eqFeatureIndex = 0;\n } else {\n eqFeatureIndex += 1;\n }\n}\n</code>\n</div>"],"class":"p5","module":"IO","submodule":"Input","overloads":[{"line":979,"params":[{"name":"path","description":"<p>name of the file or url to load</p>\n","type":"String"},{"name":"method","description":"<p>either &quot;GET&quot;, &quot;POST&quot;, or &quot;PUT&quot;,\n defaults to &quot;GET&quot;</p>\n","type":"String","optional":true},{"name":"datatype","description":"<p>&quot;json&quot;, &quot;jsonp&quot;, &quot;xml&quot;, or &quot;text&quot;</p>\n","type":"String","optional":true},{"name":"data","description":"<p>param data passed sent with request</p>\n","type":"Object","optional":true},{"name":"callback","description":"<p>function to be executed after\n <a href=\"#/p5/httpGet\">httpGet()</a> completes, data is passed in\n as first argument</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>function to be executed if\n there is an error, response is passed\n in as first argument</p>\n","type":"Function","optional":true}],"return":{"description":"A promise that resolves with the data when the operation\n completes successfully or rejects with the error after\n one occurs.","type":"Promise"}},{"line":1050,"params":[{"name":"path","description":"","type":"String"},{"name":"options","description":"<p>Request object options as documented in the\n &quot;fetch&quot; API\n<a href=\"https://developer.mozilla.org/en/docs/Web/API/Fetch_API\">reference</a></p>\n","type":"Object"},{"name":"callback","description":"","type":"Function","optional":true},{"name":"errorCallback","description":"","type":"Function","optional":true}],"return":{"description":"","type":"Promise"}}]},{"file":"src/io/files.js","line":1203,"itemtype":"method","name":"createWriter","params":[{"name":"name","description":"<p>name of the file to be created</p>\n","type":"String"},{"name":"extension","description":"","type":"String","optional":true}],"return":{"description":"","type":"p5.PrintWriter"},"example":["\n<div>\n<code>\ncreateButton('save')\n .position(10, 10)\n .mousePressed(function() {\n var writer = createWriter('squares.txt');\n for (var i = 0; i < 10; i++) {\n writer.print(i * i);\n }\n writer.close();\n writer.clear();\n });\n</code>\n</div>"],"class":"p5","module":"IO","submodule":"Output"},{"file":"src/io/files.js","line":1252,"description":"<p>Writes data to the PrintWriter stream</p>\n","itemtype":"method","name":"write","params":[{"name":"data","description":"<p>all data to be written by the PrintWriter</p>\n","type":"Array"}],"example":["\n<div class=\"norender notest\">\n<code>\n// creates a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// write 'Hello world!'' to the file\nwriter.write(['Hello world!']);\n// close the PrintWriter and save the file\nwriter.close();\n</code>\n</div>\n<div class='norender notest'>\n<code>\n// creates a file called 'newFile2.txt'\nvar writer = createWriter('newFile2.txt');\n// write 'apples,bananas,123' to the file\nwriter.write(['apples', 'bananas', 123]);\n// close the PrintWriter and save the file\nwriter.close();\n</code>\n</div>\n<div class='norender notest'>\n<code>\n// creates a file called 'newFile3.txt'\nvar writer = createWriter('newFile3.txt');\n// write 'My name is: Teddy' to the file\nwriter.write('My name is:');\nwriter.write(' Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n</code>\n</div>"],"class":"p5.PrintWriter","module":"IO","submodule":"Output"},{"file":"src/io/files.js","line":1292,"description":"<p>Writes data to the PrintWriter stream, and adds a new line at the end</p>\n","itemtype":"method","name":"print","params":[{"name":"data","description":"<p>all data to be printed by the PrintWriter</p>\n","type":"Array"}],"example":["\n<div class='norender notest'>\n<code>\n// creates a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// creates a file containing\n// My name is:\n// Teddy\nwriter.print('My name is:');\nwriter.print('Teddy');\n// close the PrintWriter and save the file\nwriter.close();\n</code>\n</div>\n<div class='norender notest'>\n<code>\nvar writer;\n\nfunction setup() {\n createCanvas(400, 400);\n // create a PrintWriter\n writer = createWriter('newFile.txt');\n}\n\nfunction draw() {\n // print all mouseX and mouseY coordinates to the stream\n writer.print([mouseX, mouseY]);\n}\n\nfunction mouseClicked() {\n // close the PrintWriter and save the file\n writer.close();\n}\n</code>\n</div>"],"class":"p5.PrintWriter","module":"IO","submodule":"Output"},{"file":"src/io/files.js","line":1335,"description":"<p>Clears the data already written to the PrintWriter object</p>\n","itemtype":"method","name":"clear","example":["\n<div class =\"norender notest\"><code>\n// create writer object\nvar writer = createWriter('newFile.txt');\nwriter.write(['clear me']);\n// clear writer object here\nwriter.clear();\n// close writer\nwriter.close();\n</code></div>\n"],"class":"p5.PrintWriter","module":"IO","submodule":"Output"},{"file":"src/io/files.js","line":1353,"description":"<p>Closes the PrintWriter</p>\n","itemtype":"method","name":"close","example":["\n<div class=\"norender notest\">\n<code>\n// create a file called 'newFile.txt'\nvar writer = createWriter('newFile.txt');\n// close the PrintWriter and save the file\nwriter.close();\n</code>\n</div>\n<div class='norender notest'>\n<code>\n// create a file called 'newFile2.txt'\nvar writer = createWriter('newFile2.txt');\n// write some data to the file\nwriter.write([100, 101, 102]);\n// close the PrintWriter and save the file\nwriter.close();\n</code>\n</div>"],"class":"p5.PrintWriter","module":"IO","submodule":"Output"},{"file":"src/io/files.js","line":1402,"description":"<p>Save an image, text, json, csv, wav, or html. Prompts download to\nthe client&#39;s computer. <b>Note that it is not recommended to call <a href=\"#/p5/save\">save()</a>\nwithin draw if it&#39;s looping, as the <a href=\"#/p5/save\">save()</a> function will open a new save\ndialog every frame.</b></p>\n<p>The default behavior is to save the canvas as an image. You can\noptionally specify a filename.\nFor example:</p>\n <pre class='language-javascript'><code>\n save();\n save(&#39;myCanvas.jpg&#39;); // save a specific canvas with a filename\n </code></pre>\n\n<p>Alternately, the first parameter can be a pointer to a canvas\n<a href=\"#/p5.Element\">p5.Element</a>, an Array of Strings,\nan Array of JSON, a JSON object, a <a href=\"#/p5.Table\">p5.Table</a>, a <a href=\"#/p5.Image\">p5.Image</a>, or a\np5.SoundFile (requires p5.sound). The second parameter is a filename\n(including extension). The third parameter is for options specific\nto this type of object. This method will save a file that fits the\ngiven paramaters. For example:</p>\n\n <pre class='language-javascript'><code>\n // Saves canvas as an image\n save('myCanvas.jpg');\n\n // Saves pImage as a png image\n var img = createImage(10, 10);\n save(img, 'my.png');\n\n // Saves canvas as an image\n var cnv = createCanvas(100, 100);\n save(cnv, 'myCanvas.jpg');\n\n // Saves p5.Renderer object as an image\n var gb = createGraphics(100, 100);\n save(gb, 'myGraphics.jpg');\n\n var myTable = new p5.Table();\n\n // Saves table as html file\n save(myTable, 'myTable.html');\n\n // Comma Separated Values\n save(myTable, 'myTable.csv');\n\n // Tab Separated Values\n save(myTable, 'myTable.tsv');\n\n var myJSON = { a: 1, b: true };\n\n // Saves pretty JSON\n save(myJSON, 'my.json');\n\n // Optimizes JSON filesize\n save(myJSON, 'my.json', true);\n\n // Saves array of strings to a text file with line breaks after each item\n var arrayOfStrings = ['a', 'b'];\n save(arrayOfStrings, 'my.txt');\n </code></pre>","itemtype":"method","name":"save","params":[{"name":"objectOrFilename","description":"<p>If filename is provided, will\n save canvas as an image with\n either png or jpg extension\n depending on the filename.\n If object is provided, will\n save depending on the object\n and filename (see examples\n above).</p>\n","type":"Object|String","optional":true},{"name":"filename","description":"<p>If an object is provided as the first\n parameter, then the second parameter\n indicates the filename,\n and should include an appropriate\n file extension (see examples above).</p>\n","type":"String","optional":true},{"name":"options","description":"<p>Additional options depend on\n filetype. For example, when saving JSON,\n <code>true</code> indicates that the\n output will be optimized for filesize,\n rather than readability.</p>\n","type":"Boolean|String","optional":true}],"class":"p5","module":"IO","submodule":"Output"},{"file":"src/io/files.js","line":1530,"description":"<p>Writes the contents of an Array or a JSON object to a .json file.\nThe file saving process and location of the saved file will\nvary between web browsers.</p>\n","itemtype":"method","name":"saveJSON","params":[{"name":"json","description":"","type":"Array|Object"},{"name":"filename","description":"","type":"String"},{"name":"optimize","description":"<p>If true, removes line breaks\n and spaces from the output\n file to optimize filesize\n (but not readability).</p>\n","type":"Boolean","optional":true}],"example":["\n <div><code>\n var json = {}; // new JSON Object\n\n json.id = 0;\n json.species = 'Panthera leo';\n json.name = 'Lion';\n\n createButton('save')\n .position(10, 10)\n .mousePressed(function() {\n saveJSON(json, 'lion.json');\n });\n\n // saves the following to a file called \"lion.json\":\n // {\n // \"id\": 0,\n // \"species\": \"Panthera leo\",\n // \"name\": \"Lion\"\n // }\n </code></div>"],"alt":"no image displayed","class":"p5","module":"IO","submodule":"Output"},{"file":"src/io/files.js","line":1582,"description":"<p>Writes an array of Strings to a text file, one line per String.\nThe file saving process and location of the saved file will\nvary between web browsers.</p>\n","itemtype":"method","name":"saveStrings","params":[{"name":"list","description":"<p>string array to be written</p>\n","type":"String[]"},{"name":"filename","description":"<p>filename for output</p>\n","type":"String"},{"name":"extension","description":"<p>the filename&#39;s extension</p>\n","type":"String","optional":true}],"example":["\n <div><code>\n var words = 'apple bear cat dog';\n\n // .split() outputs an Array\n var list = split(words, ' ');\n\n createButton('save')\n .position(10, 10)\n .mousePressed(function() {\n saveStrings(list, 'nouns.txt');\n });\n\n // Saves the following to a file called 'nouns.txt':\n //\n // apple\n // bear\n // cat\n // dog\n </code></div>"],"alt":"no image displayed","class":"p5","module":"IO","submodule":"Output"},{"file":"src/io/files.js","line":1644,"description":"<p>Writes the contents of a <a href=\"#/p5.Table\">Table</a> object to a file. Defaults to a\ntext file with comma-separated-values (&#39;csv&#39;) but can also\nuse tab separation (&#39;tsv&#39;), or generate an HTML table (&#39;html&#39;).\nThe file saving process and location of the saved file will\nvary between web browsers.</p>\n","itemtype":"method","name":"saveTable","params":[{"name":"Table","description":"<p>the <a href=\"#/p5.Table\">Table</a> object to save to a file</p>\n","type":"p5.Table"},{"name":"filename","description":"<p>the filename to which the Table should be saved</p>\n","type":"String"},{"name":"options","description":"<p>can be one of &quot;tsv&quot;, &quot;csv&quot;, or &quot;html&quot;</p>\n","type":"String","optional":true}],"example":["\n<div><code>\n var table;\n\n function setup() {\n table = new p5.Table();\n\n table.addColumn('id');\n table.addColumn('species');\n table.addColumn('name');\n\n var newRow = table.addRow();\n newRow.setNum('id', table.getRowCount() - 1);\n newRow.setString('species', 'Panthera leo');\n newRow.setString('name', 'Lion');\n\n // To save, un-comment next line then click 'run'\n // saveTable(table, 'new.csv');\n }\n\n // Saves the following to a file called 'new.csv':\n // id,species,name\n // 0,Panthera leo,Lion\n </code></div>"],"alt":"no image displayed","class":"p5","module":"IO","submodule":"Output"},{"file":"src/io/p5.Table.js","line":11,"description":"<p>Table Options</p>\n<p>Generic class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.</p>\n<p>CSV files are\n<a href=\"http://en.wikipedia.org/wiki/Comma-separated_values\">\ncomma separated values</a>, often with the data in quotes. TSV\nfiles use tabs as separators, and usually don&#39;t bother with the\nquotes.</p>\n<p>File names should end with .csv if they&#39;re comma separated.</p>\n<p>A rough &quot;spec&quot; for CSV can be found\n<a href=\"http://tools.ietf.org/html/rfc4180\">here</a>.</p>\n<p>To load files, use the <a href=\"#/p5/loadTable\">loadTable</a> method.</p>\n<p>To save tables to your computer, use the <a href=\"#/p5/save\">save</a> method\n or the <a href=\"#/p5/saveTable\">saveTable</a> method.</p>\n\n<p>Possible options include:</p>\n<ul>\n<li>csv - parse the table as comma-separated values\n<li>tsv - parse the table as tab-separated values\n<li>header - this table has a header (title) row\n</ul>","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":45,"itemtype":"property","name":"columns","type":"String[]","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":50,"itemtype":"property","name":"rows","type":"p5.TableRow[]","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":56,"description":"<p>Use <a href=\"#/p5/addRow\">addRow()</a> to add a new row of data to a <a href=\"#/p5.Table\">p5.Table</a> object. By default,\nan empty row is created. Typically, you would store a reference to\nthe new row in a TableRow object (see newRow in the example above),\nand then set individual values using <a href=\"#/p5/set\">set()</a>.</p>\n<p>If a <a href=\"#/p5.TableRow\">p5.TableRow</a> object is included as a parameter, then that row is\nduplicated and added to the table.</p>\n","itemtype":"method","name":"addRow","params":[{"name":"row","description":"<p>row to be added to the table</p>\n","type":"p5.TableRow","optional":true}],"return":{"description":"the row that was added","type":"p5.TableRow"},"example":["\n <div class=\"norender\">\n <code>\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add a row\n var newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n </code>\n </div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":120,"description":"<p>Removes a row from the table object.</p>\n","itemtype":"method","name":"removeRow","params":[{"name":"id","description":"<p>ID number of the row to remove</p>\n","type":"Integer"}],"example":["\n<div class=\"norender\">\n<code>\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //remove the first row\n table.removeRow(0);\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n</code>\n</div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":168,"description":"<p>Returns a reference to the specified <a href=\"#/p5.TableRow\">p5.TableRow</a>. The reference\ncan then be used to get and set values of the selected row.</p>\n","itemtype":"method","name":"getRow","params":[{"name":"rowID","description":"<p>ID number of the row to get</p>\n","type":"Integer"}],"return":{"description":"<a href=\"#/p5.TableRow\">p5.TableRow</a> object","type":"p5.TableRow"},"example":["\n<div class=\"norender\">\n<code>\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n var row = table.getRow(1);\n //print it column by column\n //note: a row is an object, not an array\n for (var c = 0; c < table.getColumnCount(); c++) {\n print(row.getString(c));\n }\n}\n</code>\n</div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":214,"description":"<p>Gets all rows from the table. Returns an array of <a href=\"#/p5.TableRow\">p5.TableRow</a>s.</p>\n","itemtype":"method","name":"getRows","return":{"description":"Array of <a href=\"#/p5.TableRow\">p5.TableRow</a>s","type":"p5.TableRow[]"},"example":["\n <div class=\"norender\">\n <code>\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n\n //warning: rows is an array of objects\n for (var r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n for (r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n </code>\n </div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":263,"description":"<p>Finds the first row in the Table that contains the value\nprovided, and returns a reference to that row. Even if\nmultiple rows are possible matches, only the first matching\nrow is returned. The column to search may be specified by\neither its ID or title.</p>\n","itemtype":"method","name":"findRow","params":[{"name":"value","description":"<p>The value to match</p>\n","type":"String"},{"name":"column","description":"<p>ID number or title of the\n column to search</p>\n","type":"Integer|String"}],"return":{"description":"","type":"p5.TableRow"},"example":["\n <div class=\"norender\">\n <code>\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //find the animal named zebra\n var row = table.findRow('Zebra', 'name');\n //find the corresponding species\n print(row.getString('species'));\n }\n </code>\n </div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":328,"description":"<p>Finds the rows in the Table that contain the value\nprovided, and returns references to those rows. Returns an\nArray, so for must be used to iterate through all the rows,\nas shown in the example above. The column to search may be\nspecified by either its ID or title.</p>\n","itemtype":"method","name":"findRows","params":[{"name":"value","description":"<p>The value to match</p>\n","type":"String"},{"name":"column","description":"<p>ID number or title of the\n column to search</p>\n","type":"Integer|String"}],"return":{"description":"An Array of TableRow objects","type":"p5.TableRow[]"},"example":["\n <div class=\"norender\">\n <code>\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //add another goat\n var newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Scape Goat');\n newRow.setString('name', 'Goat');\n\n //find the rows containing animals named Goat\n var rows = table.findRows('Goat', 'name');\n print(rows.length + ' Goats found');\n }\n </code>\n </div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":397,"description":"<p>Finds the first row in the Table that matches the regular\nexpression provided, and returns a reference to that row.\nEven if multiple rows are possible matches, only the first\nmatching row is returned. The column to search may be\nspecified by either its ID or title.</p>\n","itemtype":"method","name":"matchRow","params":[{"name":"regexp","description":"<p>The regular expression to match</p>\n","type":"String|RegExp"},{"name":"column","description":"<p>The column ID (number) or\n title (string)</p>\n","type":"String|Integer"}],"return":{"description":"TableRow object","type":"p5.TableRow"},"example":["\n<div class=\"norender\">\n<code>\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //Search using specified regex on a given column, return TableRow object\n var mammal = table.matchRow(new RegExp('ant'), 1);\n print(mammal.getString(1));\n //Output \"Panthera pardus\"\n}\n</code>\n</div>\n"],"class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":456,"description":"<p>Finds the rows in the Table that match the regular expression provided,\nand returns references to those rows. Returns an array, so for must be\nused to iterate through all the rows, as shown in the example. The\ncolumn to search may be specified by either its ID or title.</p>\n","itemtype":"method","name":"matchRows","params":[{"name":"regexp","description":"<p>The regular expression to match</p>\n","type":"String"},{"name":"column","description":"<p>The column ID (number) or\n title (string)</p>\n","type":"String|Integer","optional":true}],"return":{"description":"An Array of TableRow objects","type":"p5.TableRow[]"},"example":["\n<div class=\"norender\">\n<code>\nvar table;\n\nfunction setup() {\n table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', 'Lion');\n newRow.setString('type', 'Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', 'Snake');\n newRow.setString('type', 'Reptile');\n\n newRow = table.addRow();\n newRow.setString('name', 'Mosquito');\n newRow.setString('type', 'Insect');\n\n newRow = table.addRow();\n newRow.setString('name', 'Lizard');\n newRow.setString('type', 'Reptile');\n\n var rows = table.matchRows('R.*', 'type');\n for (var i = 0; i < rows.length; i++) {\n print(rows[i].getString('name') + ': ' + rows[i].getString('type'));\n }\n}\n// Sketch prints:\n// Snake: Reptile\n// Lizard: Reptile\n</code>\n</div>"],"class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":523,"description":"<p>Retrieves all values in the specified column, and returns them\nas an array. The column may be specified by either its ID or title.</p>\n","itemtype":"method","name":"getColumn","params":[{"name":"column","description":"<p>String or Number of the column to return</p>\n","type":"String|Number"}],"return":{"description":"Array of column values","type":"Array"},"example":["\n <div class=\"norender\">\n <code>\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n //getColumn returns an array that can be printed directly\n print(table.getColumn('species'));\n //outputs [\"Capra hircus\", \"Panthera pardus\", \"Equus zebra\"]\n }\n </code>\n </div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":576,"description":"<p>Removes all rows from a Table. While all rows are removed,\ncolumns and column titles are maintained.</p>\n","itemtype":"method","name":"clearRows","example":["\n <div class=\"norender\">\n <code>\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.clearRows();\n print(table.getRowCount() + ' total rows in table');\n print(table.getColumnCount() + ' total columns in table');\n }\n </code>\n </div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":618,"description":"<p>Use <a href=\"#/p5/addColumn\">addColumn()</a> to add a new column to a <a href=\"#/p5.Table\">Table</a> object.\nTypically, you will want to specify a title, so the column\nmay be easily referenced later by name. (If no title is\nspecified, the new column&#39;s title will be null.)</p>\n","itemtype":"method","name":"addColumn","params":[{"name":"title","description":"<p>title of the given column</p>\n","type":"String","optional":true}],"example":["\n <div class=\"norender\">\n <code>\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.addColumn('carnivore');\n table.set(0, 'carnivore', 'no');\n table.set(1, 'carnivore', 'yes');\n table.set(2, 'carnivore', 'no');\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n }\n </code>\n </div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":669,"description":"<p>Returns the total number of columns in a Table.</p>\n","itemtype":"method","name":"getColumnCount","return":{"description":"Number of columns in this table","type":"Integer"},"example":["\n <div>\n <code>\n // given the cvs file \"blobs.csv\" in /assets directory\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n var table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n var numOfColumn = table.getColumnCount();\n text('There are ' + numOfColumn + ' columns in the table.', 100, 50);\n }\n </code>\n </div>"],"class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":705,"description":"<p>Returns the total number of rows in a Table.</p>\n","itemtype":"method","name":"getRowCount","return":{"description":"Number of rows in this table","type":"Integer"},"example":["\n <div>\n <code>\n // given the cvs file \"blobs.csv\" in /assets directory\n //\n // ID, Name, Flavor, Shape, Color\n // Blob1, Blobby, Sweet, Blob, Pink\n // Blob2, Saddy, Savory, Blob, Blue\n\n var table;\n\n function preload() {\n table = loadTable('assets/blobs.csv');\n }\n\n function setup() {\n createCanvas(200, 100);\n textAlign(CENTER);\n background(255);\n }\n\n function draw() {\n text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50);\n }\n </code>\n </div>"],"class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":741,"description":"<p>Removes any of the specified characters (or &quot;tokens&quot;).</p>\n\n<p>If no column is specified, then the values in all columns and\nrows are processed. A specific column may be referenced by\neither its ID or title.</p>","itemtype":"method","name":"removeTokens","params":[{"name":"chars","description":"<p>String listing characters to be removed</p>\n","type":"String"},{"name":"column","description":"<p>Column ID (number)\n or name (string)</p>\n","type":"String|Integer","optional":true}],"example":["\n <div class=\"norender\"><code>\n function setup() {\n var table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', ' $Lion ,');\n newRow.setString('type', ',,,Mammal');\n\n newRow = table.addRow();\n newRow.setString('name', '$Snake ');\n newRow.setString('type', ',,,Reptile');\n\n table.removeTokens(',$ ');\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n </code></div>"],"class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":815,"description":"<p>Trims leading and trailing whitespace, such as spaces and tabs,\nfrom String table values. If no column is specified, then the\nvalues in all columns and rows are trimmed. A specific column\nmay be referenced by either its ID or title.</p>\n","itemtype":"method","name":"trim","params":[{"name":"column","description":"<p>Column ID (number)\n or name (string)</p>\n","type":"String|Integer","optional":true}],"example":["\n <div class=\"norender\"><code>\n function setup() {\n var table = new p5.Table();\n\n table.addColumn('name');\n table.addColumn('type');\n\n var newRow = table.addRow();\n newRow.setString('name', ' Lion ,');\n newRow.setString('type', ' Mammal ');\n\n newRow = table.addRow();\n newRow.setString('name', ' Snake ');\n newRow.setString('type', ' Reptile ');\n\n table.trim();\n print(table.getArray());\n }\n\n // prints:\n // 0 \"Lion\" \"Mamal\"\n // 1 \"Snake\" \"Reptile\"\n </code></div>"],"class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":879,"description":"<p>Use <a href=\"#/p5/removeColumn\">removeColumn()</a> to remove an existing column from a Table\nobject. The column to be removed may be identified by either\nits title (a String) or its index value (an int).\nremoveColumn(0) would remove the first column, removeColumn(1)\nwould remove the second column, and so on.</p>\n","itemtype":"method","name":"removeColumn","params":[{"name":"column","description":"<p>columnName (string) or ID (number)</p>\n","type":"String|Integer"}],"example":["\n <div class=\"norender\">\n <code>\n // Given the CSV file \"mammals.csv\"\n // in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n table.removeColumn('id');\n print(table.getColumnCount());\n }\n </code>\n </div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":944,"description":"<p>Stores a value in the Table&#39;s specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.</p>\n","itemtype":"method","name":"set","params":[{"name":"row","description":"<p>row ID</p>\n","type":"Integer"},{"name":"column","description":"<p>column ID (Number)\n or title (String)</p>\n","type":"String|Integer"},{"name":"value","description":"<p>value to assign</p>\n","type":"String|Number"}],"example":["\n<div class=\"norender\">\n<code>\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.set(0, 'species', 'Canis Lupus');\n table.set(0, 'name', 'Wolf');\n\n //print the results\n for (var r = 0; r < table.getRowCount(); r++)\n for (var c = 0; c < table.getColumnCount(); c++)\n print(table.getString(r, c));\n}\n</code>\n</div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":994,"description":"<p>Stores a Float value in the Table&#39;s specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.</p>\n","itemtype":"method","name":"setNum","params":[{"name":"row","description":"<p>row ID</p>\n","type":"Integer"},{"name":"column","description":"<p>column ID (Number)\n or title (String)</p>\n","type":"String|Integer"},{"name":"value","description":"<p>value to assign</p>\n","type":"Number"}],"example":["\n<div class=\"norender\">\n<code>\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n table.setNum(1, 'id', 1);\n\n print(table.getColumn(0));\n //[\"0\", 1, \"2\"]\n}\n</code>\n</div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":1040,"description":"<p>Stores a String value in the Table&#39;s specified row and column.\nThe row is specified by its ID, while the column may be specified\nby either its ID or title.</p>\n","itemtype":"method","name":"setString","params":[{"name":"row","description":"<p>row ID</p>\n","type":"Integer"},{"name":"column","description":"<p>column ID (Number)\n or title (String)</p>\n","type":"String|Integer"},{"name":"value","description":"<p>value to assign</p>\n","type":"String"}],"example":["\n<div class=\"norender\"><code>\n// Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n //add a row\n var newRow = table.addRow();\n newRow.setString('id', table.getRowCount() - 1);\n newRow.setString('species', 'Canis Lupus');\n newRow.setString('name', 'Wolf');\n\n print(table.getArray());\n}\n</code></div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":1085,"description":"<p>Retrieves a value from the Table&#39;s specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.</p>\n","itemtype":"method","name":"get","params":[{"name":"row","description":"<p>row ID</p>\n","type":"Integer"},{"name":"column","description":"<p>columnName (string) or\n ID (number)</p>\n","type":"String|Integer"}],"return":{"description":"","type":"String|Number"},"example":["\n<div class=\"norender\">\n<code>\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.get(0, 1));\n //Capra hircus\n print(table.get(0, 'species'));\n //Capra hircus\n}\n</code>\n</div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":1132,"description":"<p>Retrieves a Float value from the Table&#39;s specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.</p>\n","itemtype":"method","name":"getNum","params":[{"name":"row","description":"<p>row ID</p>\n","type":"Integer"},{"name":"column","description":"<p>columnName (string) or\n ID (number)</p>\n","type":"String|Integer"}],"return":{"description":"","type":"Number"},"example":["\n<div class=\"norender\">\n<code>\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getNum(1, 0) + 100);\n //id 1 + 100 = 101\n}\n</code>\n</div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":1177,"description":"<p>Retrieves a String value from the Table&#39;s specified row and column.\nThe row is specified by its ID, while the column may be specified by\neither its ID or title.</p>\n","itemtype":"method","name":"getString","params":[{"name":"row","description":"<p>row ID</p>\n","type":"Integer"},{"name":"column","description":"<p>columnName (string) or\n ID (number)</p>\n","type":"String|Integer"}],"return":{"description":"","type":"String"},"example":["\n<div class=\"norender\">\n<code>\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n print(table.getString(0, 0)); // 0\n print(table.getString(0, 1)); // Capra hircus\n print(table.getString(0, 2)); // Goat\n print(table.getString(1, 0)); // 1\n print(table.getString(1, 1)); // Panthera pardus\n print(table.getString(1, 2)); // Leopard\n print(table.getString(2, 0)); // 2\n print(table.getString(2, 1)); // Equus zebra\n print(table.getString(2, 2)); // Zebra\n}\n</code>\n</div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":1230,"description":"<p>Retrieves all table data and returns as an object. If a column name is\npassed in, each row object will be stored with that attribute as its\ntitle.</p>\n","itemtype":"method","name":"getObject","params":[{"name":"headerColumn","description":"<p>Name of the column which should be used to\n title each row object (optional)</p>\n","type":"String","optional":true}],"return":{"description":"","type":"Object"},"example":["\n<div class=\"norender\">\n<code>\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder:\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leopard\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n var tableObject = table.getObject();\n\n print(tableObject);\n //outputs an object\n}\n</code>\n</div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.Table.js","line":1296,"description":"<p>Retrieves all table data and returns it as a multidimensional array.</p>\n","itemtype":"method","name":"getArray","return":{"description":"","type":"Array"},"example":["\n<div class=\"norender\">\n<code>\n// Given the CSV file \"mammals.csv\"\n// in the project's \"assets\" folder\n//\n// id,species,name\n// 0,Capra hircus,Goat\n// 1,Panthera pardus,Leoperd\n// 2,Equus zebra,Zebra\n\nvar table;\n\nfunction preload() {\n // table is comma separated value \"CSV\"\n // and has specifiying header for column labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n}\n\nfunction setup() {\n var tableArray = table.getArray();\n for (var i = 0; i < tableArray.length; i++) {\n print(tableArray[i]);\n }\n}\n</code>\n</div>"],"alt":"no image displayed","class":"p5.Table","module":"IO","submodule":"Table"},{"file":"src/io/p5.TableRow.js","line":42,"description":"<p>Stores a value in the TableRow&#39;s specified column.\nThe column may be specified by either its ID or title.</p>\n","itemtype":"method","name":"set","params":[{"name":"column","description":"<p>Column ID (Number)\n or Title (String)</p>\n","type":"String|Integer"},{"name":"value","description":"<p>The value to be stored</p>\n","type":"String|Number"}],"example":["\n <div class=\"norender\"><code>\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n rows[r].set('name', 'Unicorn');\n }\n\n //print the results\n print(table.getArray());\n }\n </code></div>"],"alt":"no image displayed","class":"p5.TableRow","module":"IO","submodule":"Table"},{"file":"src/io/p5.TableRow.js","line":106,"description":"<p>Stores a Float value in the TableRow&#39;s specified column.\nThe column may be specified by either its ID or title.</p>\n","itemtype":"method","name":"setNum","params":[{"name":"column","description":"<p>Column ID (Number)\n or Title (String)</p>\n","type":"String|Integer"},{"name":"value","description":"<p>The value to be stored\n as a Float</p>\n","type":"Number|String"}],"example":["\n <div class=\"norender\"><code>\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n rows[r].setNum('id', r + 10);\n }\n\n print(table.getArray());\n }\n </code></div>"],"alt":"no image displayed","class":"p5.TableRow","module":"IO","submodule":"Table"},{"file":"src/io/p5.TableRow.js","line":150,"description":"<p>Stores a String value in the TableRow&#39;s specified column.\nThe column may be specified by either its ID or title.</p>\n","itemtype":"method","name":"setString","params":[{"name":"column","description":"<p>Column ID (Number)\n or Title (String)</p>\n","type":"String|Integer"},{"name":"value","description":"<p>The value to be stored\n as a String</p>\n","type":"String|Number|Boolean|Object"}],"example":["\n <div class=\"norender\"><code>\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n var name = rows[r].getString('name');\n rows[r].setString('name', 'A ' + name + ' named George');\n }\n\n print(table.getArray());\n }\n </code></div>"],"alt":"no image displayed","class":"p5.TableRow","module":"IO","submodule":"Table"},{"file":"src/io/p5.TableRow.js","line":195,"description":"<p>Retrieves a value from the TableRow&#39;s specified column.\nThe column may be specified by either its ID or title.</p>\n","itemtype":"method","name":"get","params":[{"name":"column","description":"<p>columnName (string) or\n ID (number)</p>\n","type":"String|Integer"}],"return":{"description":"","type":"String|Number"},"example":["\n <div class=\"norender\"><code>\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var names = [];\n var rows = table.getRows();\n for (var r = 0; r < rows.length; r++) {\n names.push(rows[r].get('name'));\n }\n\n print(names);\n }\n </code></div>"],"alt":"no image displayed","class":"p5.TableRow","module":"IO","submodule":"Table"},{"file":"src/io/p5.TableRow.js","line":243,"description":"<p>Retrieves a Float value from the TableRow&#39;s specified\ncolumn. The column may be specified by either its ID or\ntitle.</p>\n","itemtype":"method","name":"getNum","params":[{"name":"column","description":"<p>columnName (string) or\n ID (number)</p>\n","type":"String|Integer"}],"return":{"description":"Float Floating point number","type":"Number"},"example":["\n <div class=\"norender\"><code>\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n var minId = Infinity;\n var maxId = -Infinity;\n for (var r = 0; r < rows.length; r++) {\n var id = rows[r].getNum('id');\n minId = min(minId, id);\n maxId = min(maxId, id);\n }\n print('minimum id = ' + minId + ', maximum id = ' + maxId);\n }\n </code></div>"],"alt":"no image displayed","class":"p5.TableRow","module":"IO","submodule":"Table"},{"file":"src/io/p5.TableRow.js","line":299,"description":"<p>Retrieves an String value from the TableRow&#39;s specified\ncolumn. The column may be specified by either its ID or\ntitle.</p>\n","itemtype":"method","name":"getString","params":[{"name":"column","description":"<p>columnName (string) or\n ID (number)</p>\n","type":"String|Integer"}],"return":{"description":"String","type":"String"},"example":["\n <div class=\"norender\"><code>\n // Given the CSV file \"mammals.csv\" in the project's \"assets\" folder:\n //\n // id,species,name\n // 0,Capra hircus,Goat\n // 1,Panthera pardus,Leopard\n // 2,Equus zebra,Zebra\n\n var table;\n\n function preload() {\n //my table is comma separated value \"csv\"\n //and has a header specifying the columns labels\n table = loadTable('assets/mammals.csv', 'csv', 'header');\n }\n\n function setup() {\n var rows = table.getRows();\n var longest = '';\n for (var r = 0; r < rows.length; r++) {\n var species = rows[r].getString('species');\n if (longest.length < species.length) {\n longest = species;\n }\n }\n\n print('longest: ' + longest);\n }\n </code></div>"],"alt":"no image displayed","class":"p5.TableRow","module":"IO","submodule":"Table"},{"file":"src/io/p5.XML.js","line":64,"description":"<p>Gets a copy of the element&#39;s parent. Returns the parent as another\n<a href=\"#/p5.XML\">p5.XML</a> object.</p>\n","itemtype":"method","name":"getParent","return":{"description":"element parent","type":"p5.XML"},"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var children = xml.getChildren('animal');\n var parent = children[1].getParent();\n print(parent.getName());\n}\n\n// Sketch prints:\n// mammals\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":102,"description":"<p>Gets the element&#39;s full name, which is returned as a String.</p>\n","itemtype":"method","name":"getName","return":{"description":"the name of the node","type":"String"},"example":["&lt;animal\n <div class='norender'><code>\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // <?xml version=\"1.0\"?>\n // &lt;mammals&gt;\n // &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n // &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n // &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n // &lt;/mammals&gt;\n\n var xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n print(xml.getName());\n }\n\n // Sketch prints:\n // mammals\n </code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":137,"description":"<p>Sets the element&#39;s name, which is specified as a String.</p>\n","itemtype":"method","name":"setName","params":[{"name":"the","description":"<p>new name of the node</p>\n","type":"String"}],"example":["&lt;animal\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.getName());\n xml.setName('fish');\n print(xml.getName());\n}\n\n// Sketch prints:\n// mammals\n// fish\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":175,"description":"<p>Checks whether or not the element has any children, and returns the result\nas a boolean.</p>\n","itemtype":"method","name":"hasChildren","return":{"description":"","type":"Boolean"},"example":["&lt;animal\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.hasChildren());\n}\n\n// Sketch prints:\n// true\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":211,"description":"<p>Get the names of all of the element&#39;s children, and returns the names as an\narray of Strings. This is the same as looping through and calling <a href=\"#/p5.XML/getName\">getName()</a>\non each child element individually.</p>\n","itemtype":"method","name":"listChildren","return":{"description":"names of the children of the element","type":"String[]"},"example":["&lt;animal\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n print(xml.listChildren());\n}\n\n// Sketch prints:\n// [\"animal\", \"animal\", \"animal\"]\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":250,"description":"<p>Returns all of the element&#39;s children as an array of <a href=\"#/p5.XML\">p5.XML</a> objects. When\nthe name parameter is specified, then it will return all children that match\nthat name.</p>\n","itemtype":"method","name":"getChildren","params":[{"name":"name","description":"<p>element name</p>\n","type":"String","optional":true}],"return":{"description":"children of the element","type":"p5.XML[]"},"example":["&lt;animal\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var animals = xml.getChildren('animal');\n\n for (var i = 0; i < animals.length; i++) {\n print(animals[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":300,"description":"<p>Returns the first of the element&#39;s children that matches the name parameter\nor the child of the given index.It returns undefined if no matching\nchild is found.</p>\n","itemtype":"method","name":"getChild","params":[{"name":"name","description":"<p>element name or index</p>\n","type":"String|Integer"}],"return":{"description":"","type":"p5.XML"},"example":["&lt;animal\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n</code></div>\n<div class='norender'><code>\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var secondChild = xml.getChild(1);\n print(secondChild.getContent());\n}\n\n// Sketch prints:\n// \"Leopard\"\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":361,"description":"<p>Appends a new child to the element. The child can be specified with\neither a String, which will be used as the new tag&#39;s name, or as a\nreference to an existing <a href=\"#/p5.XML\">p5.XML</a> object.\nA reference to the newly created child is returned as an <a href=\"#/p5.XML\">p5.XML</a> object.</p>\n","itemtype":"method","name":"addChild","params":[{"name":"node","description":"<p>a <a href=\"#/p5.XML\">p5.XML</a> Object which will be the child to be added</p>\n","type":"p5.XML"}],"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var child = new p5.XML();\n child.setAttribute('id', '3');\n child.setAttribute('species', 'Ornithorhynchus anatinus');\n child.setContent('Platypus');\n xml.addChild(child);\n\n var animals = xml.getChildren('animal');\n print(animals[animals.length - 1].getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Leopard\"\n// \"Zebra\"\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":412,"description":"<p>Removes the element specified by name or index.</p>\n","itemtype":"method","name":"removeChild","params":[{"name":"name","description":"<p>element name or index</p>\n","type":"String|Integer"}],"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild('animal');\n var children = xml.getChildren();\n for (var i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Leopard\"\n// \"Zebra\"\n</code></div>\n<div class='norender'><code>\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n xml.removeChild(1);\n var children = xml.getChildren();\n for (var i = 0; i < children.length; i++) {\n print(children[i].getContent());\n }\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Zebra\"\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":484,"description":"<p>Counts the specified element&#39;s number of attributes, returned as an Number.</p>\n","itemtype":"method","name":"getAttributeCount","return":{"description":"","type":"Integer"},"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getAttributeCount());\n}\n\n// Sketch prints:\n// 2\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":520,"description":"<p>Gets all of the specified element&#39;s attributes, and returns them as an\narray of Strings.</p>\n","itemtype":"method","name":"listAttributes","return":{"description":"an array of strings containing the names of attributes","type":"String[]"},"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.listAttributes());\n}\n\n// Sketch prints:\n// [\"id\", \"species\"]\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":557,"description":"<p>Checks whether or not an element has the specified attribute.</p>\n","itemtype":"method","name":"hasAttribute","params":[{"name":"the","description":"<p>attribute to be checked</p>\n","type":"String"}],"return":{"description":"true if attribute found else false","type":"Boolean"},"example":["\n <div class='norender'><code>\n // The following short XML file called \"mammals.xml\" is parsed\n // in the code below.\n //\n // <?xml version=\"1.0\"?>\n // &lt;mammals&gt;\n // &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n // &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n // &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n // &lt;/mammals&gt;\n\n var xml;\n\n function preload() {\n xml = loadXML('assets/mammals.xml');\n }\n\n function setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.hasAttribute('species'));\n print(firstChild.hasAttribute('color'));\n }\n\n // Sketch prints:\n // true\n // false\n </code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":596,"description":"<p>Returns an attribute value of the element as an Number. If the defaultValue\nparameter is specified and the attribute doesn&#39;t exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn&#39;t\nexist, the value 0 is returned.</p>\n","itemtype":"method","name":"getNum","params":[{"name":"name","description":"<p>the non-null full name of the attribute</p>\n","type":"String"},{"name":"defaultValue","description":"<p>the default value of the attribute</p>\n","type":"Number","optional":true}],"return":{"description":"","type":"Number"},"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getNum('id'));\n}\n\n// Sketch prints:\n// 0\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":637,"description":"<p>Returns an attribute value of the element as an String. If the defaultValue\nparameter is specified and the attribute doesn&#39;t exist, then defaultValue\nis returned. If no defaultValue is specified and the attribute doesn&#39;t\nexist, null is returned.</p>\n","itemtype":"method","name":"getString","params":[{"name":"name","description":"<p>the non-null full name of the attribute</p>\n","type":"String"},{"name":"defaultValue","description":"<p>the default value of the attribute</p>\n","type":"Number","optional":true}],"return":{"description":"","type":"String"},"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":678,"description":"<p>Sets the content of an element&#39;s attribute. The first parameter specifies\nthe attribute name, while the second specifies the new content.</p>\n","itemtype":"method","name":"setAttribute","params":[{"name":"name","description":"<p>the full name of the attribute</p>\n","type":"String"},{"name":"value","description":"<p>the value of the attribute</p>\n","type":"Number|String|Boolean"}],"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getString('species'));\n firstChild.setAttribute('species', 'Jamides zebra');\n print(firstChild.getString('species'));\n}\n\n// Sketch prints:\n// \"Capra hircus\"\n// \"Jamides zebra\"\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":721,"description":"<p>Returns the content of an element. If there is no such content,\ndefaultValue is returned if specified, otherwise null is returned.</p>\n","itemtype":"method","name":"getContent","params":[{"name":"defaultValue","description":"<p>value returned if no content is found</p>\n","type":"String","optional":true}],"return":{"description":"","type":"String"},"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":759,"description":"<p>Sets the element&#39;s content.</p>\n","itemtype":"method","name":"setContent","params":[{"name":"text","description":"<p>the new content</p>\n","type":"String"}],"example":["\n<div class='norender'><code>\n// The following short XML file called \"mammals.xml\" is parsed\n// in the code below.\n//\n// <?xml version=\"1.0\"?>\n// &lt;mammals&gt;\n// &lt;animal id=\"0\" species=\"Capra hircus\">Goat&lt;/animal&gt;\n// &lt;animal id=\"1\" species=\"Panthera pardus\">Leopard&lt;/animal&gt;\n// &lt;animal id=\"2\" species=\"Equus zebra\">Zebra&lt;/animal&gt;\n// &lt;/mammals&gt;\n\nvar xml;\n\nfunction preload() {\n xml = loadXML('assets/mammals.xml');\n}\n\nfunction setup() {\n var firstChild = xml.getChild('animal');\n print(firstChild.getContent());\n firstChild.setContent('Mountain Goat');\n print(firstChild.getContent());\n}\n\n// Sketch prints:\n// \"Goat\"\n// \"Mountain Goat\"\n</code></div>"],"class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":801,"description":"<p>This method is called while the parsing of XML (when loadXML() is\ncalled). The difference between this method and the setContent()\nmethod defined later is that this one is used to set the content\nwhen the node in question has more nodes under it and so on and\nnot directly text content. While in the other one is used when\nthe node in question directly has text inside it.</p>\n","class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/io/p5.XML.js","line":818,"description":"<p>This method is called while the parsing of XML (when loadXML() is\ncalled). The XML node is passed and its attributes are stored in the\n<a href=\"#/p5.XML\">p5.XML</a>&#39;s attribute Object.</p>\n","class":"p5.XML","module":"IO","submodule":"XML"},{"file":"src/math/calculation.js","line":12,"description":"<p>Calculates the absolute value (magnitude) of a number. Maps to Math.abs().\nThe absolute value of a number is always positive.</p>\n","itemtype":"method","name":"abs","params":[{"name":"n","description":"<p>number to compute</p>\n","type":"Number"}],"return":{"description":"absolute value of given number","type":"Number"},"example":["\n<div class = \"norender\"><code>\nfunction setup() {\n var x = -3;\n var y = abs(x);\n\n print(x); // -3\n print(y); // 3\n}\n</code></div>"],"alt":"no image displayed","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":36,"description":"<p>Calculates the closest int value that is greater than or equal to the\nvalue of the parameter. Maps to Math.ceil(). For example, ceil(9.03)\nreturns the value 10.</p>\n","itemtype":"method","name":"ceil","params":[{"name":"n","description":"<p>number to round up</p>\n","type":"Number"}],"return":{"description":"rounded up number","type":"Integer"},"example":["\n<div><code>\nfunction draw() {\n background(200);\n // map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n //Get the ceiling of the mapped number.\n var bx = ceil(map(mouseX, 0, 100, 0, 5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n</code></div>"],"alt":"2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":76,"description":"<p>Constrains a value between a minimum and maximum value.</p>\n","itemtype":"method","name":"constrain","params":[{"name":"n","description":"<p>number to constrain</p>\n","type":"Number"},{"name":"low","description":"<p>minimum limit</p>\n","type":"Number"},{"name":"high","description":"<p>maximum limit</p>\n","type":"Number"}],"return":{"description":"constrained number","type":"Number"},"example":["\n<div><code>\nfunction draw() {\n background(200);\n\n var leftWall = 25;\n var rightWall = 75;\n\n // xm is just the mouseX, while\n // xc is the mouseX, but constrained\n // between the leftWall and rightWall!\n var xm = mouseX;\n var xc = constrain(mouseX, leftWall, rightWall);\n\n // Draw the walls.\n stroke(150);\n line(leftWall, 0, leftWall, height);\n line(rightWall, 0, rightWall, height);\n\n // Draw xm and xc as circles.\n noStroke();\n fill(150);\n ellipse(xm, 33, 9, 9); // Not Constrained\n fill(0);\n ellipse(xc, 66, 9, 9); // Constrained\n}\n</code></div>"],"alt":"2 vertical lines. 2 ellipses move with mouse X 1 does not move passed lines","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":121,"description":"<p>Calculates the distance between two points.</p>\n","itemtype":"method","name":"dist","return":{"description":"distance between the two points","type":"Number"},"example":["\n<div><code>\n// Move your mouse inside the canvas to see the\n// change in distance between two points!\nfunction draw() {\n background(200);\n fill(0);\n\n var x1 = 10;\n var y1 = 90;\n var x2 = mouseX;\n var y2 = mouseY;\n\n line(x1, y1, x2, y2);\n ellipse(x1, y1, 7, 7);\n ellipse(x2, y2, 7, 7);\n\n // d is the length of the line\n // the distance from point 1 to point 2.\n var d = int(dist(x1, y1, x2, y2));\n\n // Let's write d along the line we are drawing!\n push();\n translate((x1 + x2) / 2, (y1 + y2) / 2);\n rotate(atan2(y2 - y1, x2 - x1));\n text(nfc(d, 1), 0, -5);\n pop();\n // Fancy!\n}\n</code></div>"],"alt":"2 ellipses joined by line. 1 ellipse moves with mouse X&Y. Distance displayed.","class":"p5","module":"Math","submodule":"Calculation","overloads":[{"line":121,"params":[{"name":"x1","description":"<p>x-coordinate of the first point</p>\n","type":"Number"},{"name":"y1","description":"<p>y-coordinate of the first point</p>\n","type":"Number"},{"name":"x2","description":"<p>x-coordinate of the second point</p>\n","type":"Number"},{"name":"y2","description":"<p>y-coordinate of the second point</p>\n","type":"Number"}],"return":{"description":"distance between the two points","type":"Number"}},{"line":165,"params":[{"name":"x1","description":"","type":"Number"},{"name":"y1","description":"","type":"Number"},{"name":"z1","description":"<p>z-coordinate of the first point</p>\n","type":"Number"},{"name":"x2","description":"","type":"Number"},{"name":"y2","description":"","type":"Number"},{"name":"z2","description":"<p>z-coordinate of the second point</p>\n","type":"Number"}],"return":{"description":"distance between the two points","type":"Number"}}]},{"file":"src/math/calculation.js","line":190,"description":"<p>Returns Euler&#39;s number e (2.71828...) raised to the power of the n\nparameter. Maps to Math.exp().</p>\n","itemtype":"method","name":"exp","params":[{"name":"n","description":"<p>exponent to raise</p>\n","type":"Number"}],"return":{"description":"e^n","type":"Number"},"example":["\n<div><code>\nfunction draw() {\n background(200);\n\n // Compute the exp() function with a value between 0 and 2\n var xValue = map(mouseX, 0, width, 0, 2);\n var yValue = exp(xValue);\n\n var y = map(yValue, 0, 8, height, 0);\n\n var legend = 'exp (' + nfc(xValue, 3) + ')\\n= ' + nf(yValue, 1, 4);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n\n // Draw the exp(x) curve,\n // over the domain of x from 0 to 2\n noFill();\n stroke(0);\n beginShape();\n for (var x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, 2);\n yValue = exp(xValue);\n y = map(yValue, 0, 8, height, 0);\n vertex(x, y);\n }\n\n endShape();\n line(0, 0, 0, height);\n line(0, height - 1, width, height - 1);\n}\n</code></div>"],"alt":"ellipse moves along a curve with mouse x. e^n displayed.","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":240,"description":"<p>Calculates the closest int value that is less than or equal to the\nvalue of the parameter. Maps to Math.floor().</p>\n","itemtype":"method","name":"floor","params":[{"name":"n","description":"<p>number to round down</p>\n","type":"Number"}],"return":{"description":"rounded down number","type":"Integer"},"example":["\n<div><code>\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n //Get the floor of the mapped number.\n var bx = floor(map(mouseX, 0, 100, 0, 5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n</code></div>"],"alt":"2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":279,"description":"<p>Calculates a number between two numbers at a specific increment. The amt\nparameter is the amount to interpolate between the two values where 0.0\nequal to the first point, 0.1 is very near the first point, 0.5 is\nhalf-way in between, etc. The lerp function is convenient for creating\nmotion along a straight path and for drawing dotted lines.</p>\n","itemtype":"method","name":"lerp","params":[{"name":"start","description":"<p>first value</p>\n","type":"Number"},{"name":"stop","description":"<p>second value</p>\n","type":"Number"},{"name":"amt","description":"<p>number between 0.0 and 1.0</p>\n","type":"Number"}],"return":{"description":"lerped value","type":"Number"},"example":["\n<div><code>\nfunction setup() {\n background(200);\n var a = 20;\n var b = 80;\n var c = lerp(a, b, 0.2);\n var d = lerp(a, b, 0.5);\n var e = lerp(a, b, 0.8);\n\n var y = 50;\n\n strokeWeight(5);\n stroke(0); // Draw the original points in black\n point(a, y);\n point(b, y);\n\n stroke(100); // Draw the lerp points in gray\n point(c, y);\n point(d, y);\n point(e, y);\n}\n</code></div>"],"alt":"5 points horizontally staggered mid-canvas. mid 3 are grey, outer black","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":324,"description":"<p>Calculates the natural logarithm (the base-e logarithm) of a number. This\nfunction expects the n parameter to be a value greater than 0.0. Maps to\nMath.log().</p>\n","itemtype":"method","name":"log","params":[{"name":"n","description":"<p>number greater than 0</p>\n","type":"Number"}],"return":{"description":"natural logarithm of n","type":"Number"},"example":["\n<div><code>\nfunction draw() {\n background(200);\n var maxX = 2.8;\n var maxY = 1.5;\n\n // Compute the natural log of a value between 0 and maxX\n var xValue = map(mouseX, 0, width, 0, maxX);\n if (xValue > 0) {\n // Cannot take the log of a negative number.\n var yValue = log(xValue);\n var y = map(yValue, -maxY, maxY, height, 0);\n\n // Display the calculation occurring.\n var legend = 'log(' + nf(xValue, 1, 2) + ')\\n= ' + nf(yValue, 1, 3);\n stroke(150);\n line(mouseX, y, mouseX, height);\n fill(0);\n text(legend, 5, 15);\n noStroke();\n ellipse(mouseX, y, 7, 7);\n }\n\n // Draw the log(x) curve,\n // over the domain of x from 0 to maxX\n noFill();\n stroke(0);\n beginShape();\n for (var x = 0; x < width; x++) {\n xValue = map(x, 0, width, 0, maxX);\n yValue = log(xValue);\n y = map(yValue, -maxY, maxY, height, 0);\n vertex(x, y);\n }\n endShape();\n line(0, 0, 0, height);\n line(0, height / 2, width, height / 2);\n}\n</code></div>"],"alt":"ellipse moves along a curve with mouse x. natural logarithm of n displayed.","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":379,"description":"<p>Calculates the magnitude (or length) of a vector. A vector is a direction\nin space commonly used in computer graphics and linear algebra. Because it\nhas no &quot;start&quot; position, the magnitude of a vector can be thought of as\nthe distance from the coordinate 0,0 to its x,y value. Therefore, <a href=\"#/p5/mag\">mag()</a> is\na shortcut for writing dist(0, 0, x, y).</p>\n","itemtype":"method","name":"mag","params":[{"name":"a","description":"<p>first value</p>\n","type":"Number"},{"name":"b","description":"<p>second value</p>\n","type":"Number"}],"return":{"description":"magnitude of vector from (0,0) to (a,b)","type":"Number"},"example":["\n<div><code>\nfunction setup() {\n var x1 = 20;\n var x2 = 80;\n var y1 = 30;\n var y2 = 70;\n\n line(0, 0, x1, y1);\n print(mag(x1, y1)); // Prints \"36.05551275463989\"\n line(0, 0, x2, y1);\n print(mag(x2, y1)); // Prints \"85.44003745317531\"\n line(0, 0, x1, y2);\n print(mag(x1, y2)); // Prints \"72.80109889280519\"\n line(0, 0, x2, y2);\n print(mag(x2, y2)); // Prints \"106.3014581273465\"\n}\n</code></div>"],"alt":"4 lines of different length radiate from top left of canvas.","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":418,"description":"<p>Re-maps a number from one range to another.\n<br><br>\nIn the first example above, the number 25 is converted from a value in the\nrange of 0 to 100 into a value that ranges from the left edge of the\nwindow (0) to the right edge (width).</p>\n","itemtype":"method","name":"map","params":[{"name":"value","description":"<p>the incoming value to be converted</p>\n","type":"Number"},{"name":"start1","description":"<p>lower bound of the value&#39;s current range</p>\n","type":"Number"},{"name":"stop1","description":"<p>upper bound of the value&#39;s current range</p>\n","type":"Number"},{"name":"start2","description":"<p>lower bound of the value&#39;s target range</p>\n","type":"Number"},{"name":"stop2","description":"<p>upper bound of the value&#39;s target range</p>\n","type":"Number"},{"name":"withinBounds","description":"<p>constrain the value to the newly mapped range</p>\n","type":"Boolean","optional":true}],"return":{"description":"remapped number","type":"Number"},"example":["\n <div><code>\nvar value = 25;\nvar m = map(value, 0, 100, 0, width);\nellipse(m, 50, 10, 10);\n</code></div>\n\n <div><code>\nfunction setup() {\n noStroke();\n}\n\nfunction draw() {\n background(204);\n var x1 = map(mouseX, 0, width, 25, 75);\n ellipse(x1, 25, 25, 25);\n //This ellipse is constrained to the 0-100 range\n //after setting withinBounds to true\n var x2 = map(mouseX, 0, width, 0, 100, true);\n ellipse(x2, 75, 25, 25);\n}\n</code></div>"],"alt":"10 by 10 white ellipse with in mid left canvas\n2 25 by 25 white ellipses move with mouse x. Bottom has more range from X","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":474,"description":"<p>Determines the largest value in a sequence of numbers, and then returns\nthat value. <a href=\"#/p5/max\">max()</a> accepts any number of Number parameters, or an Array\nof any length.</p>\n","itemtype":"method","name":"max","return":{"description":"maximum Number","type":"Number"},"example":["\n<div><code>\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how max() works!\n var numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n var spacing = 15;\n var elemsY = 25;\n for (var i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n var maxX = 33;\n var maxY = 80;\n // Draw the Maximum value in the array.\n textSize(32);\n text(max(numArray), maxX, maxY);\n}\n</code></div>"],"alt":"Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 9","class":"p5","module":"Math","submodule":"Calculation","overloads":[{"line":474,"params":[{"name":"n0","description":"<p>Number to compare</p>\n","type":"Number"},{"name":"n1","description":"<p>Number to compare</p>\n","type":"Number"}],"return":{"description":"maximum Number","type":"Number"}},{"line":510,"params":[{"name":"nums","description":"<p>Numbers to compare</p>\n","type":"Number[]"}],"return":{"description":"","type":"Number"}}]},{"file":"src/math/calculation.js","line":524,"description":"<p>Determines the smallest value in a sequence of numbers, and then returns\nthat value. <a href=\"#/p5/min\">min()</a> accepts any number of Number parameters, or an Array\nof any length.</p>\n","itemtype":"method","name":"min","return":{"description":"minimum Number","type":"Number"},"example":["\n<div><code>\nfunction setup() {\n // Change the elements in the array and run the sketch\n // to show how min() works!\n var numArray = [2, 1, 5, 4, 8, 9];\n fill(0);\n noStroke();\n text('Array Elements', 0, 10);\n // Draw all numbers in the array\n var spacing = 15;\n var elemsY = 25;\n for (var i = 0; i < numArray.length; i++) {\n text(numArray[i], i * spacing, elemsY);\n }\n var maxX = 33;\n var maxY = 80;\n // Draw the Minimum value in the array.\n textSize(32);\n text(min(numArray), maxX, maxY);\n}\n</code></div>"],"alt":"Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 1","class":"p5","module":"Math","submodule":"Calculation","overloads":[{"line":524,"params":[{"name":"n0","description":"<p>Number to compare</p>\n","type":"Number"},{"name":"n1","description":"<p>Number to compare</p>\n","type":"Number"}],"return":{"description":"minimum Number","type":"Number"}},{"line":560,"params":[{"name":"nums","description":"<p>Numbers to compare</p>\n","type":"Number[]"}],"return":{"description":"","type":"Number"}}]},{"file":"src/math/calculation.js","line":574,"description":"<p>Normalizes a number from another range into a value between 0 and 1.\nIdentical to map(value, low, high, 0, 1).\nNumbers outside of the range are not clamped to 0 and 1, because\nout-of-range values are often intentional and useful. (See the second\nexample above.)</p>\n","itemtype":"method","name":"norm","params":[{"name":"value","description":"<p>incoming value to be normalized</p>\n","type":"Number"},{"name":"start","description":"<p>lower bound of the value&#39;s current range</p>\n","type":"Number"},{"name":"stop","description":"<p>upper bound of the value&#39;s current range</p>\n","type":"Number"}],"return":{"description":"normalized number","type":"Number"},"example":["\n<div><code>\nfunction draw() {\n background(200);\n var currentNum = mouseX;\n var lowerBound = 0;\n var upperBound = width; //100;\n var normalized = norm(currentNum, lowerBound, upperBound);\n var lineY = 70;\n line(0, lineY, width, lineY);\n //Draw an ellipse mapped to the non-normalized value.\n noStroke();\n fill(50);\n var s = 7; // ellipse size\n ellipse(currentNum, lineY, s, s);\n\n // Draw the guide\n var guideY = lineY + 15;\n text('0', 0, guideY);\n textAlign(RIGHT);\n text('100', width, guideY);\n\n // Draw the normalized value\n textAlign(LEFT);\n fill(0);\n textSize(32);\n var normalY = 40;\n var normalX = 20;\n text(normalized, normalX, normalY);\n}\n</code></div>"],"alt":"ellipse moves with mouse. 0 shown left & 100 right and updating values center","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":627,"description":"<p>Facilitates exponential expressions. The <a href=\"#/p5/pow\">pow()</a> function is an efficient\nway of multiplying numbers by themselves (or their reciprocals) in large\nquantities. For example, pow(3, 5) is equivalent to the expression\n3<em>3</em>3<em>3</em>3 and pow(3, -5) is equivalent to 1 / 3<em>3</em>3<em>3</em>3. Maps to\nMath.pow().</p>\n","itemtype":"method","name":"pow","params":[{"name":"n","description":"<p>base of the exponential expression</p>\n","type":"Number"},{"name":"e","description":"<p>power by which to raise the base</p>\n","type":"Number"}],"return":{"description":"n^e","type":"Number"},"example":["\n<div><code>\nfunction setup() {\n //Exponentially increase the size of an ellipse.\n var eSize = 3; // Original Size\n var eLoc = 10; // Original Location\n\n ellipse(eLoc, eLoc, eSize, eSize);\n\n ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2));\n\n ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3));\n\n ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4));\n}\n</code></div>"],"alt":"small to large ellipses radiating from top left of canvas","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":661,"description":"<p>Calculates the integer closest to the n parameter. For example,\nround(133.8) returns the value 134. Maps to Math.round().</p>\n","itemtype":"method","name":"round","params":[{"name":"n","description":"<p>number to round</p>\n","type":"Number"}],"return":{"description":"rounded number","type":"Integer"},"example":["\n<div><code>\nfunction draw() {\n background(200);\n //map, mouseX between 0 and 5.\n var ax = map(mouseX, 0, 100, 0, 5);\n var ay = 66;\n\n // Round the mapped number.\n var bx = round(map(mouseX, 0, 100, 0, 5));\n var by = 33;\n\n // Multiply the mapped numbers by 20 to more easily\n // see the changes.\n stroke(0);\n fill(0);\n line(0, ay, ax * 20, ay);\n line(0, by, bx * 20, by);\n\n // Reformat the float returned by map and draw it.\n noStroke();\n text(nfc(ax, 2), ax, ay - 5);\n text(nfc(bx, 1), bx, by - 5);\n}\n</code></div>"],"alt":"horizontal center line squared values displayed on top and regular on bottom.","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":700,"description":"<p>Squares a number (multiplies a number by itself). The result is always a\npositive number, as multiplying two negative numbers always yields a\npositive result. For example, -1 * -1 = 1.</p>\n","itemtype":"method","name":"sq","params":[{"name":"n","description":"<p>number to square</p>\n","type":"Number"}],"return":{"description":"squared number","type":"Number"},"example":["\n<div><code>\nfunction draw() {\n background(200);\n var eSize = 7;\n var x1 = map(mouseX, 0, width, 0, 10);\n var y1 = 80;\n var x2 = sq(x1);\n var y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n var spacing = 15;\n noStroke();\n fill(0);\n text('x = ' + x1, 0, y1 + spacing);\n text('sq(x) = ' + x2, 0, y2 + spacing);\n}\n</code></div>"],"alt":"horizontal center line squared values displayed on top and regular on bottom.","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/calculation.js","line":747,"description":"<p>Calculates the square root of a number. The square root of a number is\nalways positive, even though there may be a valid negative root. The\nsquare root s of number a is such that s*s = a. It is the opposite of\nsquaring. Maps to Math.sqrt().</p>\n","itemtype":"method","name":"sqrt","params":[{"name":"n","description":"<p>non-negative number to square root</p>\n","type":"Number"}],"return":{"description":"square root of number","type":"Number"},"example":["\n<div><code>\nfunction draw() {\n background(200);\n var eSize = 7;\n var x1 = mouseX;\n var y1 = 80;\n var x2 = sqrt(x1);\n var y2 = 20;\n\n // Draw the non-squared.\n line(0, y1, width, y1);\n ellipse(x1, y1, eSize, eSize);\n\n // Draw the squared.\n line(0, y2, width, y2);\n ellipse(x2, y2, eSize, eSize);\n\n // Draw dividing line.\n stroke(100);\n line(0, height / 2, width, height / 2);\n\n // Draw text.\n noStroke();\n fill(0);\n var spacing = 15;\n text('x = ' + x1, 0, y1 + spacing);\n text('sqrt(x) = ' + x2, 0, y2 + spacing);\n}\n</code></div>"],"alt":"horizontal center line squareroot values displayed on top and regular on bottom.","class":"p5","module":"Math","submodule":"Calculation"},{"file":"src/math/math.js","line":12,"description":"<p>Creates a new <a href=\"#/p5.Vector\">p5.Vector</a> (the datatype for storing vectors). This provides a\ntwo or three dimensional vector, specifically a Euclidean (also known as\ngeometric) vector. A vector is an entity that has both magnitude and\ndirection.</p>\n","itemtype":"method","name":"createVector","params":[{"name":"x","description":"<p>x component of the vector</p>\n","type":"Number","optional":true},{"name":"y","description":"<p>y component of the vector</p>\n","type":"Number","optional":true},{"name":"z","description":"<p>z component of the vector</p>\n","type":"Number","optional":true}],"return":{"description":"","type":"p5.Vector"},"example":["\n<div modernizr='webgl'><code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255, 102, 204);\n}\n\nfunction draw() {\n background(255);\n pointLight(color(255), createVector(sin(millis() / 1000) * 20, -40, -10));\n scale(0.75);\n sphere();\n}\n</code></div>"],"alt":"a purple sphere lit by a point light oscillating horizontally","class":"p5","module":"Math","submodule":"Math"},{"file":"src/math/noise.js","line":40,"description":"<p>Returns the Perlin noise value at specified coordinates. Perlin noise is\na random sequence generator producing a more natural ordered, harmonic\nsuccession of numbers compared to the standard <b>random()</b> function.\nIt was invented by Ken Perlin in the 1980s and been used since in\ngraphical applications to produce procedural textures, natural motion,\nshapes, terrains etc.<br /><br /> The main difference to the\n<b>random()</b> function is that Perlin noise is defined in an infinite\nn-dimensional space where each pair of coordinates corresponds to a\nfixed semi-random value (fixed only for the lifespan of the program; see\nthe <a href=\"#/p5/noiseSeed\">noiseSeed()</a> function). p5.js can compute 1D, 2D and 3D noise,\ndepending on the number of coordinates given. The resulting value will\nalways be between 0.0 and 1.0. The noise value can be animated by moving\nthrough the noise space as demonstrated in the example above. The 2nd\nand 3rd dimension can also be interpreted as time.<br /><br />The actual\nnoise is structured similar to an audio signal, in respect to the\nfunction&#39;s use of frequencies. Similar to the concept of harmonics in\nphysics, perlin noise is computed over several octaves which are added\ntogether for the final result. <br /><br />Another way to adjust the\ncharacter of the resulting sequence is the scale of the input\ncoordinates. As the function works within an infinite space the value of\nthe coordinates doesn&#39;t matter as such, only the distance between\nsuccessive coordinates does (eg. when using <b>noise()</b> within a\nloop). As a general rule the smaller the difference between coordinates,\nthe smoother the resulting noise sequence will be. Steps of 0.005-0.03\nwork best for most applications, but this will differ depending on use.</p>\n","itemtype":"method","name":"noise","params":[{"name":"x","description":"<p>x-coordinate in noise space</p>\n","type":"Number"},{"name":"y","description":"<p>y-coordinate in noise space</p>\n","type":"Number","optional":true},{"name":"z","description":"<p>z-coordinate in noise space</p>\n","type":"Number","optional":true}],"return":{"description":"Perlin noise value (between 0 and 1) at specified\n coordinates","type":"Number"},"example":["\n<div>\n<code>\nvar xoff = 0.0;\n\nfunction draw() {\n background(204);\n xoff = xoff + 0.01;\n var n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n</code>\n</div>\n<div>\n<code>var noiseScale=0.02;\n\nfunction draw() {\n background(0);\n for (var x=0; x < width; x++) {\n var noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale);\n stroke(noiseVal*255);\n line(x, mouseY+noiseVal*80, x, height);\n }\n}\n</code>\n</div>"],"alt":"vertical line moves left to right with updating noise values.\nhorizontal wave pattern effected by mouse x-position & updating noise values.","class":"p5","module":"Math","submodule":"Noise"},{"file":"src/math/noise.js","line":187,"description":"<p>Adjusts the character and level of detail produced by the Perlin noise\n function. Similar to harmonics in physics, noise is computed over\n several octaves. Lower octaves contribute more to the output signal and\n as such define the overall intensity of the noise, whereas higher octaves\n create finer grained details in the noise sequence.\n <br><br>\n By default, noise is computed over 4 octaves with each octave contributing\n exactly half than its predecessor, starting at 50% strength for the 1st\n octave. This falloff amount can be changed by adding an additional function\n parameter. Eg. a falloff factor of 0.75 means each octave will now have\n 75% impact (25% less) of the previous lower octave. Any value between\n 0.0 and 1.0 is valid, however note that values greater than 0.5 might\n result in greater than 1.0 values returned by <b>noise()</b>.\n <br><br>\n By changing these parameters, the signal created by the <b>noise()</b>\n function can be adapted to fit very specific needs and characteristics.</p>\n","itemtype":"method","name":"noiseDetail","params":[{"name":"lod","description":"<p>number of octaves to be used by the noise</p>\n","type":"Number"},{"name":"falloff","description":"<p>falloff factor for each octave</p>\n","type":"Number"}],"example":["\n <div>\n <code>\n var noiseVal;\n var noiseScale = 0.02;\nfunction setup() {\n createCanvas(100, 100);\n }\nfunction draw() {\n background(0);\n for (var y = 0; y < height; y++) {\n for (var x = 0; x < width / 2; x++) {\n noiseDetail(2, 0.2);\n noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale);\n stroke(noiseVal * 255);\n point(x, y);\n noiseDetail(8, 0.65);\n noiseVal = noise(\n (mouseX + x + width / 2) * noiseScale,\n (mouseY + y) * noiseScale\n );\n stroke(noiseVal * 255);\n point(x + width / 2, y);\n }\n }\n }\n </code>\n </div>"],"alt":"2 vertical grey smokey patterns affected my mouse x-position and noise.","class":"p5","module":"Math","submodule":"Noise"},{"file":"src/math/noise.js","line":253,"description":"<p>Sets the seed value for <b>noise()</b>. By default, <b>noise()</b>\nproduces different results each time the program is run. Set the\n<b>value</b> parameter to a constant to return the same pseudo-random\nnumbers each time the software is run.</p>\n","itemtype":"method","name":"noiseSeed","params":[{"name":"seed","description":"<p>the seed value</p>\n","type":"Number"}],"example":["\n<div>\n<code>var xoff = 0.0;\n\nfunction setup() {\n noiseSeed(99);\n stroke(0, 10);\n}\n\nfunction draw() {\n xoff = xoff + .01;\n var n = noise(xoff) * width;\n line(n, 0, n, height);\n}\n</code>\n</div>"],"alt":"vertical grey lines drawing in pattern affected by noise.","class":"p5","module":"Math","submodule":"Noise"},{"file":"src/math/p5.Vector.js","line":67,"description":"<p>The x component of the vector</p>\n","itemtype":"property","name":"x","type":"Number","class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":72,"description":"<p>The y component of the vector</p>\n","itemtype":"property","name":"y","type":"Number","class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":77,"description":"<p>The z component of the vector</p>\n","itemtype":"property","name":"z","type":"Number","class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":84,"description":"<p>Returns a string representation of a vector v by calling String(v)\nor v.toString(). This method is useful for logging vectors in the\nconsole.</p>\n","itemtype":"method","name":"toString","return":{"description":"","type":"String"},"example":["\n<div class = \"norender\">\n<code>\nfunction setup() {\n var v = createVector(20, 30);\n print(String(v)); // prints \"p5.Vector Object : [20, 30, 0]\"\n}\n</code>\n</div>\n\n<div>\n<code>\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text(v1.toString(), 10, 25, 90, 75);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":134,"description":"<p>Sets the x, y, and z component of the vector using two or three separate\nvariables, the data from a <a href=\"#/p5.Vector\">p5.Vector</a>, or the values from a float array.</p>\n","itemtype":"method","name":"set","chainable":1,"example":["\n<div class=\"norender\">\n<code>\nfunction setup() {\n var v = createVector(1, 2, 3);\n v.set(4, 5, 6); // Sets vector to [4, 5, 6]\n\n var v1 = createVector(0, 0, 0);\n var arr = [1, 2, 3];\n v1.set(arr); // Sets vector to [1, 2, 3]\n}\n</code>\n</div>\n\n<div>\n<code>\nvar v0, v1;\nfunction setup() {\n createCanvas(100, 100);\n\n v0 = createVector(0, 0);\n v1 = createVector(50, 50);\n}\n\nfunction draw() {\n background(240);\n\n drawArrow(v0, v1, 'black');\n v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1));\n\n noStroke();\n text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math","overloads":[{"line":134,"params":[{"name":"x","description":"<p>the x component of the vector</p>\n","type":"Number","optional":true},{"name":"y","description":"<p>the y component of the vector</p>\n","type":"Number","optional":true},{"name":"z","description":"<p>the z component of the vector</p>\n","type":"Number","optional":true}],"chainable":1},{"line":193,"params":[{"name":"value","description":"<p>the vector to set</p>\n","type":"p5.Vector|Number[]"}],"chainable":1}]},{"file":"src/math/p5.Vector.js","line":217,"description":"<p>Gets a copy of the vector, returns a <a href=\"#/p5.Vector\">p5.Vector</a> object.</p>\n","itemtype":"method","name":"copy","return":{"description":"the copy of the <a href=\"#/p5.Vector\">p5.Vector</a> object","type":"p5.Vector"},"example":["\n<div class=\"norender\">\n<code>\nvar v1 = createVector(1, 2, 3);\nvar v2 = v1.copy();\nprint(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z);\n// Prints \"true\"\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":240,"description":"<p>Adds x, y, and z components to a vector, adds one vector to another, or\nadds two independent vectors together. The version of the method that adds\ntwo vectors together is a static method and returns a <a href=\"#/p5.Vector\">p5.Vector</a>, the others\nacts directly on the vector. See the examples for more context.</p>\n","itemtype":"method","name":"add","chainable":1,"example":["\n<div class=\"norender\">\n<code>\nvar v = createVector(1, 2, 3);\nv.add(4, 5, 6);\n// v's components are set to [5, 7, 9]\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\n// Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(2, 3, 4);\n\nvar v3 = p5.Vector.add(v1, v2);\n// v3 has components [3, 5, 7]\nprint(v3);\n</code>\n</div>\n\n<div>\n<code>\n// red vector + blue vector = purple vector\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(-30, 20);\n drawArrow(v1, v2, 'blue');\n\n var v3 = p5.Vector.add(v1, v2);\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math","overloads":[{"line":240,"params":[{"name":"x","description":"<p>the x component of the vector to be added</p>\n","type":"Number"},{"name":"y","description":"<p>the y component of the vector to be added</p>\n","type":"Number","optional":true},{"name":"z","description":"<p>the z component of the vector to be added</p>\n","type":"Number","optional":true}],"chainable":1},{"line":306,"params":[{"name":"value","description":"<p>the vector to add</p>\n","type":"p5.Vector|Number[]"}],"chainable":1},{"line":1556,"params":[{"name":"v1","description":"<p>a <a href=\"#/p5.Vector\">p5.Vector</a> to add</p>\n","type":"p5.Vector"},{"name":"v2","description":"<p>a <a href=\"#/p5.Vector\">p5.Vector</a> to add</p>\n","type":"p5.Vector"},{"name":"target","description":"<p>the vector to receive the result</p>\n","type":"p5.Vector"}],"static":1},{"line":1563,"params":[{"name":"v1","description":"","type":"p5.Vector"},{"name":"v2","description":"","type":"p5.Vector"}],"static":1,"return":{"description":"the resulting <a href=\"#/p5.Vector\">p5.Vector</a>","type":"p5.Vector"}}]},{"file":"src/math/p5.Vector.js","line":330,"description":"<p>Subtracts x, y, and z components from a vector, subtracts one vector from\nanother, or subtracts two independent vectors. The version of the method\nthat subtracts two vectors is a static method and returns a <a href=\"#/p5.Vector\">p5.Vector</a>, the\nother acts directly on the vector. See the examples for more context.</p>\n","itemtype":"method","name":"sub","chainable":1,"example":["\n<div class=\"norender\">\n<code>\nvar v = createVector(4, 5, 6);\nv.sub(1, 1, 1);\n// v's components are set to [3, 4, 5]\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\n// Static method\nvar v1 = createVector(2, 3, 4);\nvar v2 = createVector(1, 2, 3);\n\nvar v3 = p5.Vector.sub(v1, v2);\n// v3 has components [1, 1, 1]\nprint(v3);\n</code>\n</div>\n\n<div>\n<code>\n// red vector - blue vector = purple vector\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n var v3 = p5.Vector.sub(v1, v2);\n drawArrow(v2, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math","overloads":[{"line":330,"params":[{"name":"x","description":"<p>the x component of the vector to subtract</p>\n","type":"Number"},{"name":"y","description":"<p>the y component of the vector to subtract</p>\n","type":"Number","optional":true},{"name":"z","description":"<p>the z component of the vector to subtract</p>\n","type":"Number","optional":true}],"chainable":1},{"line":396,"params":[{"name":"value","description":"<p>the vector to subtract</p>\n","type":"p5.Vector|Number[]"}],"chainable":1},{"line":1586,"params":[{"name":"v1","description":"<p>a <a href=\"#/p5.Vector\">p5.Vector</a> to subtract from</p>\n","type":"p5.Vector"},{"name":"v2","description":"<p>a <a href=\"#/p5.Vector\">p5.Vector</a> to subtract</p>\n","type":"p5.Vector"},{"name":"target","description":"<p>if undefined a new vector will be created</p>\n","type":"p5.Vector"}],"static":1},{"line":1593,"params":[{"name":"v1","description":"","type":"p5.Vector"},{"name":"v2","description":"","type":"p5.Vector"}],"static":1,"return":{"description":"the resulting <a href=\"#/p5.Vector\">p5.Vector</a>","type":"p5.Vector"}}]},{"file":"src/math/p5.Vector.js","line":420,"description":"<p>Multiply the vector by a scalar. The static version of this method\ncreates a new <a href=\"#/p5.Vector\">p5.Vector</a> while the non static version acts on the vector\ndirectly. See the examples for more context.</p>\n","itemtype":"method","name":"mult","chainable":1,"example":["\n<div class=\"norender\">\n<code>\nvar v = createVector(1, 2, 3);\nv.mult(2);\n// v's components are set to [2, 4, 6]\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\n// Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = p5.Vector.mult(v1, 2);\n// v2 has components [2, 4, 6]\nprint(v2);\n</code>\n</div>\n\n<div>\n<code>\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(25, -25);\n drawArrow(v0, v1, 'red');\n\n var num = map(mouseX, 0, width, -2, 2, true);\n var v2 = p5.Vector.mult(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('multiplied by ' + num.toFixed(2), 5, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math","overloads":[{"line":420,"params":[{"name":"n","description":"<p>the number to multiply with the vector</p>\n","type":"Number"}],"chainable":1},{"line":1614,"params":[{"name":"v","description":"<p>the vector to multiply</p>\n","type":"p5.Vector"},{"name":"n","description":"","type":"Number"},{"name":"target","description":"<p>if undefined a new vector will be created</p>\n","type":"p5.Vector"}],"static":1},{"line":1621,"params":[{"name":"v","description":"","type":"p5.Vector"},{"name":"n","description":"","type":"Number"}],"static":1,"return":{"description":"the resulting new <a href=\"#/p5.Vector\">p5.Vector</a>","type":"p5.Vector"}}]},{"file":"src/math/p5.Vector.js","line":495,"description":"<p>Divide the vector by a scalar. The static version of this method creates a\nnew <a href=\"#/p5.Vector\">p5.Vector</a> while the non static version acts on the vector directly.\nSee the examples for more context.</p>\n","itemtype":"method","name":"div","chainable":1,"example":["\n<div class=\"norender\">\n<code>\nvar v = createVector(6, 4, 2);\nv.div(2); //v's components are set to [3, 2, 1]\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\n// Static method\nvar v1 = createVector(6, 4, 2);\nvar v2 = p5.Vector.div(v1, 2);\n// v2 has components [3, 2, 1]\nprint(v2);\n</code>\n</div>\n\n<div>\n<code>\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 100);\n var v1 = createVector(50, -50);\n drawArrow(v0, v1, 'red');\n\n var num = map(mouseX, 0, width, 10, 0.5, true);\n var v2 = p5.Vector.div(v1, num);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('divided by ' + num.toFixed(2), 10, 90);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math","overloads":[{"line":495,"params":[{"name":"n","description":"<p>the number to divide the vector by</p>\n","type":"Number"}],"chainable":1},{"line":1641,"params":[{"name":"v","description":"<p>the vector to divide</p>\n","type":"p5.Vector"},{"name":"n","description":"","type":"Number"},{"name":"target","description":"<p>if undefined a new vector will be created</p>\n","type":"p5.Vector"}],"static":1},{"line":1648,"params":[{"name":"v","description":"","type":"p5.Vector"},{"name":"n","description":"","type":"Number"}],"static":1,"return":{"description":"the resulting new <a href=\"#/p5.Vector\">p5.Vector</a>","type":"p5.Vector"}}]},{"file":"src/math/p5.Vector.js","line":573,"description":"<p>Calculates the magnitude (length) of the vector and returns the result as\na float (this is simply the equation sqrt(x<em>x + y</em>y + z*z).)</p>\n","itemtype":"method","name":"mag","return":{"description":"magnitude of the vector","type":"Number"},"example":["\n<div>\n<code>\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length: ' + v1.mag().toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>\n<div class=\"norender\">\n<code>\nvar v = createVector(20.0, 30.0, 40.0);\nvar m = v.mag();\nprint(m); // Prints \"53.85164807134504\"\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math","overloads":[{"line":573,"params":[],"return":{"description":"magnitude of the vector","type":"Number"}},{"line":1738,"params":[{"name":"vecT","description":"<p>the vector to return the magnitude of</p>\n","type":"p5.Vector"}],"static":1,"return":{"description":"the magnitude of vecT","type":"Number"}}]},{"file":"src/math/p5.Vector.js","line":621,"description":"<p>Calculates the squared magnitude of the vector and returns the result\nas a float (this is simply the equation <em>(x<em>x + y</em>y + z*z)</em>.)\nFaster if the real length is not required in the\ncase of comparing vectors, etc.</p>\n","itemtype":"method","name":"magSq","return":{"description":"squared magnitude of the vector","type":"Number"},"example":["\n<div class=\"norender\">\n<code>\n// Static method\nvar v1 = createVector(6, 4, 2);\nprint(v1.magSq()); // Prints \"56\"\n</code>\n</div>\n\n<div>\n<code>\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'black');\n\n noStroke();\n text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":675,"description":"<p>Calculates the dot product of two vectors. The version of the method\nthat computes the dot product of two independent vectors is a static\nmethod. See the examples for more context.</p>\n","itemtype":"method","name":"dot","return":{"description":"the dot product","type":"Number"},"example":["\n<div class=\"norender\">\n<code>\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(2, 3, 4);\n\nprint(v1.dot(v2)); // Prints \"20\"\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\n//Static method\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(3, 2, 1);\nprint(p5.Vector.dot(v1, v2)); // Prints \"10\"\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math","overloads":[{"line":675,"params":[{"name":"x","description":"<p>x component of the vector</p>\n","type":"Number"},{"name":"y","description":"<p>y component of the vector</p>\n","type":"Number","optional":true},{"name":"z","description":"<p>z component of the vector</p>\n","type":"Number","optional":true}],"return":{"description":"the dot product","type":"Number"}},{"line":706,"params":[{"name":"value","description":"<p>value component of the vector or a <a href=\"#/p5.Vector\">p5.Vector</a></p>\n","type":"p5.Vector"}],"return":{"description":"","type":"Number"}},{"line":1668,"params":[{"name":"v1","description":"<p>the first <a href=\"#/p5.Vector\">p5.Vector</a></p>\n","type":"p5.Vector"},{"name":"v2","description":"<p>the second <a href=\"#/p5.Vector\">p5.Vector</a></p>\n","type":"p5.Vector"}],"static":1,"return":{"description":"the dot product","type":"Number"}}]},{"file":"src/math/p5.Vector.js","line":718,"description":"<p>Calculates and returns a vector composed of the cross product between\ntwo vectors. Both the static and non static methods return a new <a href=\"#/p5.Vector\">p5.Vector</a>.\nSee the examples for more context.</p>\n","itemtype":"method","name":"cross","return":{"description":"<a href=\"#/p5.Vector\">p5.Vector</a> composed of cross product","type":"p5.Vector"},"example":["\n<div class=\"norender\">\n<code>\nvar v1 = createVector(1, 2, 3);\nvar v2 = createVector(1, 2, 3);\n\nv1.cross(v2); // v's components are [0, 0, 0]\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\n// Static method\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar crossProduct = p5.Vector.cross(v1, v2);\n// crossProduct has components [0, 0, 1]\nprint(crossProduct);\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math","overloads":[{"line":718,"params":[{"name":"v","description":"<p><a href=\"#/p5.Vector\">p5.Vector</a> to be crossed</p>\n","type":"p5.Vector"}],"return":{"description":"<a href=\"#/p5.Vector\">p5.Vector</a> composed of cross product","type":"p5.Vector"}},{"line":1682,"params":[{"name":"v1","description":"<p>the first <a href=\"#/p5.Vector\">p5.Vector</a></p>\n","type":"p5.Vector"},{"name":"v2","description":"<p>the second <a href=\"#/p5.Vector\">p5.Vector</a></p>\n","type":"p5.Vector"}],"static":1,"return":{"description":"the cross product","type":"Number"}}]},{"file":"src/math/p5.Vector.js","line":759,"description":"<p>Calculates the Euclidean distance between two points (considering a\npoint as a vector object).</p>\n","itemtype":"method","name":"dist","return":{"description":"the distance","type":"Number"},"example":["\n<div class=\"norender\">\n<code>\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar distance = v1.dist(v2); // distance is 1.4142...\nprint(distance);\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\n// Static method\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar distance = p5.Vector.dist(v1, v2);\n// distance is 1.4142...\nprint(distance);\n</code>\n</div>\n\n<div>\n<code>\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n\n var v1 = createVector(70, 50);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX, mouseY);\n drawArrow(v0, v2, 'blue');\n\n noStroke();\n text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math","overloads":[{"line":759,"params":[{"name":"v","description":"<p>the x, y, and z coordinates of a <a href=\"#/p5.Vector\">p5.Vector</a></p>\n","type":"p5.Vector"}],"return":{"description":"the distance","type":"Number"}},{"line":1697,"params":[{"name":"v1","description":"<p>the first <a href=\"#/p5.Vector\">p5.Vector</a></p>\n","type":"p5.Vector"},{"name":"v2","description":"<p>the second <a href=\"#/p5.Vector\">p5.Vector</a></p>\n","type":"p5.Vector"}],"static":1,"return":{"description":"the distance","type":"Number"}}]},{"file":"src/math/p5.Vector.js","line":830,"description":"<p>Normalize the vector to length 1 (make it a unit vector).</p>\n","itemtype":"method","name":"normalize","return":{"description":"normalized <a href=\"#/p5.Vector\">p5.Vector</a>","type":"p5.Vector"},"example":["\n<div class=\"norender\">\n<code>\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.normalize();\n// v's components are set to\n// [0.4454354, 0.8908708, 0.089087084]\n</code>\n</div>\n<div>\n<code>\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n v1.normalize();\n drawArrow(v0, v1.mult(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":886,"description":"<p>Limit the magnitude of this vector to the value used for the <b>max</b>\nparameter.</p>\n","itemtype":"method","name":"limit","params":[{"name":"max","description":"<p>the maximum magnitude for the vector</p>\n","type":"Number"}],"chainable":1,"example":["\n<div class=\"norender\">\n<code>\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.limit(5);\n// v's components are set to\n// [2.2271771, 4.4543543, 0.4454354]\n</code>\n</div>\n<div>\n<code>\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'red');\n drawArrow(v0, v1.limit(35), 'blue');\n\n noFill();\n ellipse(50, 50, 35 * 2);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":944,"description":"<p>Set the magnitude of this vector to the value used for the <b>len</b>\nparameter.</p>\n","itemtype":"method","name":"setMag","params":[{"name":"len","description":"<p>the new length for this vector</p>\n","type":"Number"}],"chainable":1,"example":["\n<div class=\"norender\">\n<code>\nvar v = createVector(10, 20, 2);\n// v has components [10.0, 20.0, 2.0]\nv.setMag(10);\n// v's components are set to [6.0, 8.0, 0.0]\n</code>\n</div>\n\n<div>\n<code>\nfunction draw() {\n background(240);\n\n var v0 = createVector(0, 0);\n var v1 = createVector(50, 50);\n\n drawArrow(v0, v1, 'red');\n\n var length = map(mouseX, 0, width, 0, 141, true);\n v1.setMag(length);\n drawArrow(v0, v1, 'blue');\n\n noStroke();\n text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30);\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1000,"description":"<p>Calculate the angle of rotation for this vector (only 2D vectors)</p>\n","itemtype":"method","name":"heading","return":{"description":"the angle of rotation","type":"Number"},"example":["\n<div class = \"norender\">\n<code>\nfunction setup() {\n var v1 = createVector(30, 50);\n print(v1.heading()); // 1.0303768265243125\n\n v1 = createVector(40, 50);\n print(v1.heading()); // 0.8960553845713439\n\n v1 = createVector(30, 70);\n print(v1.heading()); // 1.1659045405098132\n}\n</code>\n</div>\n\n<div>\n<code>\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(mouseX - 50, mouseY - 50);\n\n drawArrow(v0, v1, 'black');\n\n var myHeading = v1.heading();\n noStroke();\n text(\n 'vector heading: ' +\n myHeading.toFixed(2) +\n ' radians or ' +\n degrees(myHeading).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1069,"description":"<p>Rotate the vector by an angle (only 2D vectors), magnitude remains the\nsame</p>\n","itemtype":"method","name":"rotate","params":[{"name":"angle","description":"<p>the angle of rotation</p>\n","type":"Number"}],"chainable":1,"example":["\n<div class=\"norender\">\n<code>\nvar v = createVector(10.0, 20.0);\n// v has components [10.0, 20.0, 0.0]\nv.rotate(HALF_PI);\n// v's components are set to [-20.0, 9.999999, 0.0]\n</code>\n</div>\n\n<div>\n<code>\nvar angle = 0;\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = createVector(50, 0);\n\n drawArrow(v0, v1.rotate(angle), 'black');\n angle += 0.01;\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1125,"description":"<p>Calculates and returns the angle (in radians) between two vectors.</p>\n","itemtype":"method","name":"angleBetween","params":[{"name":"the","description":"<p>x, y, and z components of a <a href=\"#/p5.Vector\">p5.Vector</a></p>\n","type":"p5.Vector"}],"return":{"description":"the angle between (in radians)","type":"Number"},"example":["\n<div class=\"norender\">\n<code>\nvar v1 = createVector(1, 0, 0);\nvar v2 = createVector(0, 1, 0);\n\nvar angle = v1.angleBetween(v2);\n// angle is PI/2\nprint(angle);\n</code>\n</div>\n\n<div>\n<code>\nfunction draw() {\n background(240);\n var v0 = createVector(50, 50);\n\n var v1 = createVector(50, 0);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(mouseX - 50, mouseY - 50);\n drawArrow(v0, v2, 'blue');\n\n var angleBetween = v1.angleBetween(v2);\n noStroke();\n text(\n 'angle between: ' +\n angleBetween.toFixed(2) +\n ' radians or ' +\n degrees(angleBetween).toFixed(2) +\n ' degrees',\n 10,\n 50,\n 90,\n 50\n );\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1198,"description":"<p>Linear interpolate the vector to another vector</p>\n","itemtype":"method","name":"lerp","chainable":1,"example":["\n<div class=\"norender\">\n<code>\nvar v = createVector(1, 1, 0);\n\nv.lerp(3, 3, 0, 0.5); // v now has components [2,2,0]\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nvar v1 = createVector(0, 0, 0);\nvar v2 = createVector(100, 100, 0);\n\nvar v3 = p5.Vector.lerp(v1, v2, 0.5);\n// v3 has components [50,50,0]\nprint(v3);\n</code>\n</div>\n\n<div>\n<code>\nvar step = 0.01;\nvar amount = 0;\n\nfunction draw() {\n background(240);\n var v0 = createVector(0, 0);\n\n var v1 = createVector(mouseX, mouseY);\n drawArrow(v0, v1, 'red');\n\n var v2 = createVector(90, 90);\n drawArrow(v0, v2, 'blue');\n\n if (amount > 1 || amount < 0) {\n step *= -1;\n }\n amount += step;\n var v3 = p5.Vector.lerp(v1, v2, amount);\n\n drawArrow(v0, v3, 'purple');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math","overloads":[{"line":1198,"params":[{"name":"x","description":"<p>the x component</p>\n","type":"Number"},{"name":"y","description":"<p>the y component</p>\n","type":"Number"},{"name":"z","description":"<p>the z component</p>\n","type":"Number"},{"name":"amt","description":"<p>the amount of interpolation; some value between 0.0\n (old vector) and 1.0 (new vector). 0.9 is very near\n the new vector. 0.5 is halfway in between.</p>\n","type":"Number"}],"chainable":1},{"line":1271,"params":[{"name":"v","description":"<p>the <a href=\"#/p5.Vector\">p5.Vector</a> to lerp to</p>\n","type":"p5.Vector"},{"name":"amt","description":"","type":"Number"}],"chainable":1},{"line":1712,"params":[{"name":"v1","description":"","type":"p5.Vector"},{"name":"v2","description":"","type":"p5.Vector"},{"name":"amt","description":"","type":"Number"},{"name":"target","description":"<p>if undefined a new vector will be created</p>\n","type":"p5.Vector"}],"static":1},{"line":1720,"params":[{"name":"v1","description":"","type":"p5.Vector"},{"name":"v2","description":"","type":"p5.Vector"},{"name":"amt","description":"","type":"Number"}],"static":1,"return":{"description":"the lerped value","type":"Number"}}]},{"file":"src/math/p5.Vector.js","line":1287,"description":"<p>Return a representation of this vector as a float array. This is only\nfor temporary use. If used in any other fashion, the contents should be\ncopied by using the <b>p5.Vector.<a href=\"#/p5.Vector/copy\">copy()</a></b> method to copy into your own\narray.</p>\n","itemtype":"method","name":"array","return":{"description":"an Array with the 3 values","type":"Number[]"},"example":["\n<div class = \"norender\">\n<code>\nfunction setup() {\n var v = createVector(20, 30);\n print(v.array()); // Prints : Array [20, 30, 0]\n}\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nvar v = createVector(10.0, 20.0, 30.0);\nvar f = v.array();\nprint(f[0]); // Prints \"10.0\"\nprint(f[1]); // Prints \"20.0\"\nprint(f[2]); // Prints \"30.0\"\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1319,"description":"<p>Equality check against a <a href=\"#/p5.Vector\">p5.Vector</a></p>\n","itemtype":"method","name":"equals","return":{"description":"whether the vectors are equals","type":"Boolean"},"example":["\n<div class = \"norender\">\n<code>\nvar v1 = createVector(5, 10, 20);\nvar v2 = createVector(5, 10, 20);\nvar v3 = createVector(13, 10, 19);\n\nprint(v1.equals(v2.x, v2.y, v2.z)); // true\nprint(v1.equals(v3.x, v3.y, v3.z)); // false\n</code>\n</div>\n\n<div class=\"norender\">\n<code>\nvar v1 = createVector(10.0, 20.0, 30.0);\nvar v2 = createVector(10.0, 20.0, 30.0);\nvar v3 = createVector(0.0, 0.0, 0.0);\nprint(v1.equals(v2)); // true\nprint(v1.equals(v3)); // false\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math","overloads":[{"line":1319,"params":[{"name":"x","description":"<p>the x component of the vector</p>\n","type":"Number","optional":true},{"name":"y","description":"<p>the y component of the vector</p>\n","type":"Number","optional":true},{"name":"z","description":"<p>the z component of the vector</p>\n","type":"Number","optional":true}],"return":{"description":"whether the vectors are equals","type":"Boolean"}},{"line":1349,"params":[{"name":"value","description":"<p>the vector to compare</p>\n","type":"p5.Vector|Array"}],"return":{"description":"","type":"Boolean"}}]},{"file":"src/math/p5.Vector.js","line":1374,"description":"<p>Make a new 2D vector from an angle</p>\n","itemtype":"method","name":"fromAngle","static":1,"params":[{"name":"angle","description":"<p>the desired angle, in radians</p>\n","type":"Number"},{"name":"length","description":"<p>the length of the new vector (defaults to 1)</p>\n","type":"Number","optional":true}],"return":{"description":"the new <a href=\"#/p5.Vector\">p5.Vector</a> object","type":"p5.Vector"},"example":["\n<div>\n<code>\nfunction draw() {\n background(200);\n\n // Create a variable, proportional to the mouseX,\n // varying from 0-360, to represent an angle in degrees.\n angleMode(DEGREES);\n var myDegrees = map(mouseX, 0, width, 0, 360);\n\n // Display that variable in an onscreen text.\n // (Note the nfc() function to truncate additional decimal places,\n // and the \"\\xB0\" character for the degree symbol.)\n var readout = 'angle = ' + nfc(myDegrees, 1) + '\\xB0';\n noStroke();\n fill(0);\n text(readout, 5, 15);\n\n // Create a p5.Vector using the fromAngle function,\n // and extract its x and y components.\n var v = p5.Vector.fromAngle(radians(myDegrees), 30);\n var vx = v.x;\n var vy = v.y;\n\n push();\n translate(width / 2, height / 2);\n noFill();\n stroke(150);\n line(0, 0, 30, 0);\n stroke(0);\n line(0, 0, vx, vy);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1426,"description":"<p>Make a new 3D vector from a pair of ISO spherical angles</p>\n","itemtype":"method","name":"fromAngles","static":1,"params":[{"name":"theta","description":"<p>the polar angle, in radians (zero is up)</p>\n","type":"Number"},{"name":"phi","description":"<p>the azimuthal angle, in radians\n (zero is out of the screen)</p>\n","type":"Number"},{"name":"length","description":"<p>the length of the new vector (defaults to 1)</p>\n","type":"Number","optional":true}],"return":{"description":"the new <a href=\"#/p5.Vector\">p5.Vector</a> object","type":"p5.Vector"},"example":["\n<div modernizr='webgl'>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n fill(255);\n noStroke();\n}\nfunction draw() {\n background(255);\n\n var t = millis() / 1000;\n\n // add three point lights\n pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100));\n pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100));\n pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100));\n\n sphere(35);\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1475,"description":"<p>Make a new 2D unit vector from a random angle</p>\n","itemtype":"method","name":"random2D","static":1,"return":{"description":"the new <a href=\"#/p5.Vector\">p5.Vector</a> object","type":"p5.Vector"},"example":["\n<div class=\"norender\">\n<code>\nvar v = p5.Vector.random2D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.0] or\n// [-0.4695841, -0.14366731, 0.0] or\n// [0.6091097, -0.22805278, 0.0]\nprint(v);\n</code>\n</div>\n\n<div>\n<code>\nfunction setup() {\n frameRate(1);\n}\n\nfunction draw() {\n background(240);\n\n var v0 = createVector(50, 50);\n var v1 = p5.Vector.random2D();\n drawArrow(v0, v1.mult(50), 'black');\n}\n\n// draw an arrow for a vector at a given base position\nfunction drawArrow(base, vec, myColor) {\n push();\n stroke(myColor);\n strokeWeight(3);\n fill(myColor);\n translate(base.x, base.y);\n line(0, 0, vec.x, vec.y);\n rotate(vec.heading());\n var arrowSize = 7;\n translate(vec.mag() - arrowSize, 0);\n triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0);\n pop();\n}\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1528,"description":"<p>Make a new random 3D unit vector.</p>\n","itemtype":"method","name":"random3D","static":1,"return":{"description":"the new <a href=\"#/p5.Vector\">p5.Vector</a> object","type":"p5.Vector"},"example":["\n<div class=\"norender\">\n<code>\nvar v = p5.Vector.random3D();\n// May make v's attributes something like:\n// [0.61554617, -0.51195765, 0.599168] or\n// [-0.4695841, -0.14366731, -0.8711202] or\n// [0.6091097, -0.22805278, -0.7595902]\nprint(v);\n</code>\n</div>"],"class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1611,"description":"<p>Multiplies a vector by a scalar and returns a new vector.</p>\n","class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1638,"description":"<p>Divides a vector by a scalar and returns a new vector.</p>\n","class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1665,"description":"<p>Calculates the dot product of two vectors.</p>\n","class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1679,"description":"<p>Calculates the cross product of two vectors.</p>\n","class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1693,"description":"<p>Calculates the Euclidean distance between two points (considering a\npoint as a vector object).</p>\n","class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/p5.Vector.js","line":1708,"description":"<p>Linear interpolate a vector to another vector and return the result as a\nnew vector.</p>\n","class":"p5.Vector","module":"Math","submodule":"Math"},{"file":"src/math/random.js","line":48,"description":"<p>Sets the seed value for <a href=\"#/p5/random\">random()</a>.</p>\n<p>By default, <a href=\"#/p5/random\">random()</a> produces different results each time the program\nis run. Set the seed parameter to a constant to return the same\npseudo-random numbers each time the software is run.</p>\n","itemtype":"method","name":"randomSeed","params":[{"name":"seed","description":"<p>the seed value</p>\n","type":"Number"}],"example":["\n<div>\n<code>\nrandomSeed(99);\nfor (var i = 0; i < 100; i++) {\n var r = random(0, 255);\n stroke(r);\n line(i, 0, i, 100);\n}\n</code>\n</div>"],"alt":"many vertical lines drawn in white, black or grey.","class":"p5","module":"Math","submodule":"Random"},{"file":"src/math/random.js","line":79,"description":"<p>Return a random floating-point number.</p>\n<p>Takes either 0, 1 or 2 arguments.</p>\n<p>If no argument is given, returns a random number from 0\nup to (but not including) 1.</p>\n<p>If one argument is given and it is a number, returns a random number from 0\nup to (but not including) the number.</p>\n<p>If one argument is given and it is an array, returns a random element from\nthat array.</p>\n<p>If two arguments are given, returns a random number from the\nfirst argument up to (but not including) the second argument.</p>\n","itemtype":"method","name":"random","return":{"description":"the random number","type":"Number"},"example":["\n<div>\n<code>\nfor (var i = 0; i < 100; i++) {\n var r = random(50);\n stroke(r * 5);\n line(50, i, 50 + r, i);\n}\n</code>\n</div>\n<div>\n<code>\nfor (var i = 0; i < 100; i++) {\n var r = random(-50, 50);\n line(50, i, 50 + r, i);\n}\n</code>\n</div>\n<div>\n<code>\n// Get a random element from an array using the random(Array) syntax\nvar words = ['apple', 'bear', 'cat', 'dog'];\nvar word = random(words); // select random word\ntext(word, 10, 50); // draw the word\n</code>\n</div>"],"alt":"100 horizontal lines from center canvas to right. size+fill change each time\n100 horizontal lines from center of canvas. height & side change each render\nword displayed at random. Either apple, bear, cat, or dog","class":"p5","module":"Math","submodule":"Random","overloads":[{"line":79,"params":[{"name":"min","description":"<p>the lower bound (inclusive)</p>\n","type":"Number","optional":true},{"name":"max","description":"<p>the upper bound (exclusive)</p>\n","type":"Number","optional":true}],"return":{"description":"the random number","type":"Number"}},{"line":133,"params":[{"name":"choices","description":"<p>the array to choose from</p>\n","type":"Array"}],"return":{"description":"the random element from the array","type":"*"}}]},{"file":"src/math/random.js","line":166,"description":"<p>Returns a random number fitting a Gaussian, or\n normal, distribution. There is theoretically no minimum or maximum\n value that <a href=\"#/p5/randomGaussian\">randomGaussian()</a> might return. Rather, there is\n just a very low probability that values far from the mean will be\n returned; and a higher probability that numbers near the mean will\n be returned.\n <br><br>\n Takes either 0, 1 or 2 arguments.<br>\n If no args, returns a mean of 0 and standard deviation of 1.<br>\n If one arg, that arg is the mean (standard deviation is 1).<br>\n If two args, first is mean, second is standard deviation.</p>\n","itemtype":"method","name":"randomGaussian","params":[{"name":"mean","description":"<p>the mean</p>\n","type":"Number"},{"name":"sd","description":"<p>the standard deviation</p>\n","type":"Number"}],"return":{"description":"the random number","type":"Number"},"example":["\n <div>\n <code>\n for (var y = 0; y < 100; y++) {\n var x = randomGaussian(50, 15);\n line(50, y, x, y);\n }\n </code>\n </div>\n <div>\n <code>\n var distribution = new Array(360);\nfunction setup() {\n createCanvas(100, 100);\n for (var i = 0; i < distribution.length; i++) {\n distribution[i] = floor(randomGaussian(0, 15));\n }\n }\nfunction draw() {\n background(204);\n translate(width / 2, width / 2);\n for (var i = 0; i < distribution.length; i++) {\n rotate(TWO_PI / distribution.length);\n stroke(0);\n var dist = abs(distribution[i]);\n line(0, 0, dist, 0);\n }\n }\n </code>\n </div>"],"alt":"100 horizontal lines from center of canvas. height & side change each render\n black lines radiate from center of canvas. size determined each render","class":"p5","module":"Math","submodule":"Random"},{"file":"src/math/trigonometry.js","line":20,"description":"<p>The inverse of <a href=\"#/p5/cos\">cos()</a>, returns the arc cosine of a value. This function\nexpects the values in the range of -1 to 1 and values are returned in\nthe range 0 to PI (3.1415927).</p>\n","itemtype":"method","name":"acos","params":[{"name":"value","description":"<p>the value whose arc cosine is to be returned</p>\n","type":"Number"}],"return":{"description":"the arc cosine of the given value","type":"Number"},"example":["\n<div class= “norender\">\n<code>\nvar a = PI;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: \"3.1415927 : -1.0 : 3.1415927\"\nprint(a + ' : ' + c + ' : ' + ac);\n</code>\n</div>\n\n<div class= “norender\">\n<code>\nvar a = PI + PI / 4.0;\nvar c = cos(a);\nvar ac = acos(c);\n// Prints: \"3.926991 : -0.70710665 : 2.3561943\"\nprint(a + ' : ' + c + ' : ' + ac);\n</code>\n</div>"],"class":"p5","module":"Math","submodule":"Trigonometry"},{"file":"src/math/trigonometry.js","line":54,"description":"<p>The inverse of <a href=\"#/p5/sin\">sin()</a>, returns the arc sine of a value. This function\nexpects the values in the range of -1 to 1 and values are returned\nin the range -PI/2 to PI/2.</p>\n","itemtype":"method","name":"asin","params":[{"name":"value","description":"<p>the value whose arc sine is to be returned</p>\n","type":"Number"}],"return":{"description":"the arc sine of the given value","type":"Number"},"example":["\n<div class= “norender\">\n<code>\nvar a = PI + PI / 3;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: \"1.0471976 : 0.86602545 : 1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n</code>\n</div>\n\n<div class= “norender\">\n<code>\nvar a = PI + PI / 3.0;\nvar s = sin(a);\nvar as = asin(s);\n// Prints: \"4.1887903 : -0.86602545 : -1.0471976\"\nprint(a + ' : ' + s + ' : ' + as);\n</code>\n</div>\n"],"class":"p5","module":"Math","submodule":"Trigonometry"},{"file":"src/math/trigonometry.js","line":89,"description":"<p>The inverse of <a href=\"#/p5/tan\">tan()</a>, returns the arc tangent of a value. This function\nexpects the values in the range of -Infinity to Infinity (exclusive) and\nvalues are returned in the range -PI/2 to PI/2.</p>\n","itemtype":"method","name":"atan","params":[{"name":"value","description":"<p>the value whose arc tangent is to be returned</p>\n","type":"Number"}],"return":{"description":"the arc tangent of the given value","type":"Number"},"example":["\n<div class= “norender\">\n<code>\nvar a = PI + PI / 3;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: \"1.0471976 : 1.7320509 : 1.0471976\"\nprint(a + ' : ' + t + ' : ' + at);\n</code>\n</div>\n\n<div class= “norender\">\n<code>\nvar a = PI + PI / 3.0;\nvar t = tan(a);\nvar at = atan(t);\n// Prints: \"4.1887903 : 1.7320513 : 1.0471977\"\nprint(a + ' : ' + t + ' : ' + at);\n</code>\n</div>\n"],"class":"p5","module":"Math","submodule":"Trigonometry"},{"file":"src/math/trigonometry.js","line":124,"description":"<p>Calculates the angle (in radians) from a specified point to the coordinate\norigin as measured from the positive x-axis. Values are returned as a\nfloat in the range from PI to -PI. The atan2<a href=\"#/p5/\">()</a> function is most often used\nfor orienting geometry to the position of the cursor.\n<br><br>\nNote: The y-coordinate of the point is the first parameter, and the\nx-coordinate is the second parameter, due the the structure of calculating\nthe tangent.</p>\n","itemtype":"method","name":"atan2","params":[{"name":"y","description":"<p>y-coordinate of the point</p>\n","type":"Number"},{"name":"x","description":"<p>x-coordinate of the point</p>\n","type":"Number"}],"return":{"description":"the arc tangent of the given point","type":"Number"},"example":["\n<div>\n<code>\nfunction draw() {\n background(204);\n translate(width / 2, height / 2);\n var a = atan2(mouseY - height / 2, mouseX - width / 2);\n rotate(a);\n rect(-30, -5, 60, 10);\n}\n</code>\n</div>"],"alt":"60 by 10 rect at center of canvas rotates with mouse movements","class":"p5","module":"Math","submodule":"Trigonometry"},{"file":"src/math/trigonometry.js","line":160,"description":"<p>Calculates the cosine of an angle. This function takes into account the\ncurrent <a href=\"#/p5/angleMode\">angleMode</a>. Values are returned in the range -1 to 1.</p>\n","itemtype":"method","name":"cos","params":[{"name":"angle","description":"<p>the angle</p>\n","type":"Number"}],"return":{"description":"the cosine of the angle","type":"Number"},"example":["\n<div>\n<code>\nvar a = 0.0;\nvar inc = TWO_PI / 25.0;\nfor (var i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + cos(a) * 40.0);\n a = a + inc;\n}\n</code>\n</div>"],"alt":"vertical black lines form wave patterns, extend-down on left and right side","class":"p5","module":"Math","submodule":"Trigonometry"},{"file":"src/math/trigonometry.js","line":188,"description":"<p>Calculates the sine of an angle. This function takes into account the\ncurrent <a href=\"#/p5/angleMode\">angleMode</a>. Values are returned in the range -1 to 1.</p>\n","itemtype":"method","name":"sin","params":[{"name":"angle","description":"<p>the angle</p>\n","type":"Number"}],"return":{"description":"the sine of the angle","type":"Number"},"example":["\n<div>\n<code>\nvar a = 0.0;\nvar inc = TWO_PI / 25.0;\nfor (var i = 0; i < 25; i++) {\n line(i * 4, 50, i * 4, 50 + sin(a) * 40.0);\n a = a + inc;\n}\n</code>\n</div>"],"alt":"vertical black lines extend down and up from center to form wave pattern","class":"p5","module":"Math","submodule":"Trigonometry"},{"file":"src/math/trigonometry.js","line":216,"description":"<p>Calculates the tangent of an angle. This function takes into account\nthe current <a href=\"#/p5/angleMode\">angleMode</a>. Values are returned in the range -1 to 1.</p>\n","itemtype":"method","name":"tan","params":[{"name":"angle","description":"<p>the angle</p>\n","type":"Number"}],"return":{"description":"the tangent of the angle","type":"Number"},"example":["\n<div>\n<code>\nvar a = 0.0;\nvar inc = TWO_PI / 50.0;\nfor (var i = 0; i < 100; i = i + 2) {\n line(i, 50, i, 50 + tan(a) * 2.0);\n a = a + inc;\n}\n</code>"],"alt":"vertical black lines end down and up from center to form spike pattern","class":"p5","module":"Math","submodule":"Trigonometry"},{"file":"src/math/trigonometry.js","line":244,"description":"<p>Converts a radian measurement to its corresponding value in degrees.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964. This function does not take into account the\ncurrent <a href=\"#/p5/angleMode\">angleMode</a>.</p>\n","itemtype":"method","name":"degrees","params":[{"name":"radians","description":"<p>the radians value to convert to degrees</p>\n","type":"Number"}],"return":{"description":"the converted angle","type":"Number"},"example":["\n<div class= “norender\">\n<code>\nvar rad = PI / 4;\nvar deg = degrees(rad);\nprint(rad + ' radians is ' + deg + ' degrees');\n// Prints: 0.7853981633974483 radians is 45 degrees\n</code>\n</div>\n"],"class":"p5","module":"Math","submodule":"Trigonometry"},{"file":"src/math/trigonometry.js","line":271,"description":"<p>Converts a degree measurement to its corresponding value in radians.\nRadians and degrees are two ways of measuring the same thing. There are\n360 degrees in a circle and 2*PI radians in a circle. For example,\n90° = PI/2 = 1.5707964. This function does not take into account the\ncurrent <a href=\"#/p5/angleMode\">angleMode</a>.</p>\n","itemtype":"method","name":"radians","params":[{"name":"degrees","description":"<p>the degree value to convert to radians</p>\n","type":"Number"}],"return":{"description":"the converted angle","type":"Number"},"example":["\n<div class= “norender\">\n<code>\nvar deg = 45.0;\nvar rad = radians(deg);\nprint(deg + ' degrees is ' + rad + ' radians');\n// Prints: 45 degrees is 0.7853981633974483 radians\n</code>\n</div>"],"class":"p5","module":"Math","submodule":"Trigonometry"},{"file":"src/math/trigonometry.js","line":296,"description":"<p>Sets the current mode of p5 to given mode. Default mode is RADIANS.</p>\n","itemtype":"method","name":"angleMode","params":[{"name":"mode","description":"<p>either RADIANS or DEGREES</p>\n","type":"Constant"}],"example":["\n<div>\n<code>\nfunction draw() {\n background(204);\n angleMode(DEGREES); // Change the mode to DEGREES\n var a = atan2(mouseY - height / 2, mouseX - width / 2);\n translate(width / 2, height / 2);\n push();\n rotate(a);\n rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees\n pop();\n angleMode(RADIANS); // Change the mode to RADIANS\n rotate(a); // var a stays the same\n rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians\n}\n</code>\n</div>"],"alt":"40 by 10 rect in center rotates with mouse moves. 20 by 10 rect moves faster.","class":"p5","module":"Math","submodule":"Trigonometry"},{"file":"src/typography/attributes.js","line":13,"description":"<p>Sets the current alignment for drawing text. Accepts two\narguments: horizAlign (LEFT, CENTER, or RIGHT) and\nvertAlign (TOP, BOTTOM, CENTER, or BASELINE).</p>\n<p>The horizAlign parameter is in reference to the x value\nof the <a href=\"#/p5/text\">text()</a> function, while the vertAlign parameter is\nin reference to the y value.</p>\n<p>So if you write textAlign(LEFT), you are aligning the left\nedge of your text to the x value you give in <a href=\"#/p5/text\">text()</a>. If you\nwrite textAlign(RIGHT, TOP), you are aligning the right edge\nof your text to the x value and the top of edge of the text\nto the y value.</p>\n","itemtype":"method","name":"textAlign","chainable":1,"example":["\n<div>\n<code>\ntextSize(16);\ntextAlign(RIGHT);\ntext('ABCD', 50, 30);\ntextAlign(CENTER);\ntext('EFGH', 50, 50);\ntextAlign(LEFT);\ntext('IJKL', 50, 70);\n</code>\n</div>\n\n<div>\n<code>\ntextSize(16);\nstrokeWeight(0.5);\n\nline(0, 12, width, 12);\ntextAlign(CENTER, TOP);\ntext('TOP', 0, 12, width);\n\nline(0, 37, width, 37);\ntextAlign(CENTER, CENTER);\ntext('CENTER', 0, 37, width);\n\nline(0, 62, width, 62);\ntextAlign(CENTER, BASELINE);\ntext('BASELINE', 0, 62, width);\n\nline(0, 87, width, 87);\ntextAlign(CENTER, BOTTOM);\ntext('BOTTOM', 0, 87, width);\n</code>\n</div>"],"alt":"Letters ABCD displayed at top right, EFGH at center and IJKL at bottom left.\nThe names of the four vertical alignments rendered each showing that alignment's placement relative to a horizontal line.","class":"p5","module":"Typography","submodule":"Attributes","overloads":[{"line":13,"params":[{"name":"horizAlign","description":"<p>horizontal alignment, either LEFT,\n CENTER, or RIGHT</p>\n","type":"Constant"},{"name":"vertAlign","description":"<p>vertical alignment, either TOP,\n BOTTOM, CENTER, or BASELINE</p>\n","type":"Constant","optional":true}],"chainable":1},{"line":75,"params":[],"return":{"description":"","type":"Object"}}]},{"file":"src/typography/attributes.js","line":84,"description":"<p>Sets/gets the spacing, in pixels, between lines of text. This\nsetting will be used in all subsequent calls to the <a href=\"#/p5/text\">text()</a> function.</p>\n","itemtype":"method","name":"textLeading","chainable":1,"example":["\n<div>\n<code>\n// Text to display. The \"\\n\" is a \"new line\" character\nvar lines = 'L1\\nL2\\nL3';\ntextSize(12);\n\ntextLeading(10); // Set leading to 10\ntext(lines, 10, 25);\n\ntextLeading(20); // Set leading to 20\ntext(lines, 40, 25);\n\ntextLeading(30); // Set leading to 30\ntext(lines, 70, 25);\n</code>\n</div>"],"alt":"set L1 L2 & L3 displayed vertically 3 times. spacing increases for each set","class":"p5","module":"Typography","submodule":"Attributes","overloads":[{"line":84,"params":[{"name":"leading","description":"<p>the size in pixels for spacing between lines</p>\n","type":"Number"}],"chainable":1},{"line":113,"params":[],"return":{"description":"","type":"Number"}}]},{"file":"src/typography/attributes.js","line":122,"description":"<p>Sets/gets the current font size. This size will be used in all subsequent\ncalls to the <a href=\"#/p5/text\">text()</a> function. Font size is measured in pixels.</p>\n","itemtype":"method","name":"textSize","chainable":1,"example":["\n<div>\n<code>\ntextSize(12);\ntext('Font Size 12', 10, 30);\ntextSize(14);\ntext('Font Size 14', 10, 60);\ntextSize(16);\ntext('Font Size 16', 10, 90);\n</code>\n</div>"],"alt":"Font Size 12 displayed small, Font Size 14 medium & Font Size 16 large","class":"p5","module":"Typography","submodule":"Attributes","overloads":[{"line":122,"params":[{"name":"theSize","description":"<p>the size of the letters in units of pixels</p>\n","type":"Number"}],"chainable":1},{"line":145,"params":[],"return":{"description":"","type":"Number"}}]},{"file":"src/typography/attributes.js","line":154,"description":"<p>Sets/gets the style of the text for system fonts to NORMAL, ITALIC, or BOLD.\nNote: this may be is overridden by CSS styling. For non-system fonts\n(opentype, truetype, etc.) please load styled fonts instead.</p>\n","itemtype":"method","name":"textStyle","chainable":1,"example":["\n<div>\n<code>\nstrokeWeight(0);\ntextSize(12);\ntextStyle(NORMAL);\ntext('Font Style Normal', 10, 30);\ntextStyle(ITALIC);\ntext('Font Style Italic', 10, 60);\ntextStyle(BOLD);\ntext('Font Style Bold', 10, 90);\n</code>\n</div>"],"alt":"words Font Style Normal displayed normally, Italic in italic and bold in bold","class":"p5","module":"Typography","submodule":"Attributes","overloads":[{"line":154,"params":[{"name":"theStyle","description":"<p>styling for text, either NORMAL,\n ITALIC, or BOLD</p>\n","type":"Constant"}],"chainable":1},{"line":180,"params":[],"return":{"description":"","type":"String"}}]},{"file":"src/typography/attributes.js","line":189,"description":"<p>Calculates and returns the width of any character or text string.</p>\n","itemtype":"method","name":"textWidth","params":[{"name":"theText","description":"<p>the String of characters to measure</p>\n","type":"String"}],"return":{"description":"","type":"Number"},"example":["\n<div>\n<code>\ntextSize(28);\n\nvar aChar = 'P';\nvar cWidth = textWidth(aChar);\ntext(aChar, 0, 40);\nline(cWidth, 0, cWidth, 50);\n\nvar aString = 'p5.js';\nvar sWidth = textWidth(aString);\ntext(aString, 0, 85);\nline(sWidth, 50, sWidth, 100);\n</code>\n</div>"],"alt":"Letter P and p5.js are displayed with vertical lines at end. P is wide","class":"p5","module":"Typography","submodule":"Attributes"},{"file":"src/typography/attributes.js","line":224,"description":"<p>Returns the ascent of the current font at its current size. The ascent\nrepresents the distance, in pixels, of the tallest character above\nthe baseline.</p>\n","itemtype":"method","name":"textAscent","return":{"description":"","type":"Number"},"example":["\n<div>\n<code>\nvar base = height * 0.75;\nvar scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nvar asc = textAscent() * scalar; // Calc ascent\nline(0, base - asc, width, base - asc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\nasc = textAscent() * scalar; // Recalc ascent\nline(40, base - asc, width, base - asc);\ntext('dp', 40, base); // Draw text on baseline\n</code>\n</div>"],"class":"p5","module":"Typography","submodule":"Attributes"},{"file":"src/typography/attributes.js","line":253,"description":"<p>Returns the descent of the current font at its current size. The descent\nrepresents the distance, in pixels, of the character with the longest\ndescender below the baseline.</p>\n","itemtype":"method","name":"textDescent","return":{"description":"","type":"Number"},"example":["\n<div>\n<code>\nvar base = height * 0.75;\nvar scalar = 0.8; // Different for each font\n\ntextSize(32); // Set initial text size\nvar desc = textDescent() * scalar; // Calc ascent\nline(0, base + desc, width, base + desc);\ntext('dp', 0, base); // Draw text on baseline\n\ntextSize(64); // Increase text size\ndesc = textDescent() * scalar; // Recalc ascent\nline(40, base + desc, width, base + desc);\ntext('dp', 40, base); // Draw text on baseline\n</code>\n</div>"],"class":"p5","module":"Typography","submodule":"Attributes"},{"file":"src/typography/attributes.js","line":282,"description":"<p>Helper function to measure ascent and descent.</p>\n","class":"p5","module":"Typography","submodule":"Attributes"},{"file":"src/typography/loading_displaying.js","line":16,"description":"<p>Loads an opentype font file (.otf, .ttf) from a file or a URL,\nand returns a PFont Object. This method is asynchronous,\nmeaning it may not finish before the next line in your sketch\nis executed.\n<br><br>\nThe path to the font should be relative to the HTML file\nthat links in your sketch. Loading an from a URL or other\nremote location may be blocked due to your browser&#39;s built-in\nsecurity.</p>\n","itemtype":"method","name":"loadFont","params":[{"name":"path","description":"<p>name of the file or url to load</p>\n","type":"String"},{"name":"callback","description":"<p>function to be executed after\n <a href=\"#/p5/loadFont\">loadFont()</a> completes</p>\n","type":"Function","optional":true},{"name":"onError","description":"<p>function to be executed if\n an error occurs</p>\n","type":"Function","optional":true}],"return":{"description":"<a href=\"#/p5.Font\">p5.Font</a> object","type":"p5.Font"},"example":["\n\n<p>Calling loadFont() inside <a href=\"#/p5/preload\">preload()</a> guarantees that the load\noperation will have completed before <a href=\"#/p5/setup\">setup()</a> and <a href=\"#/p5/draw\">draw()</a> are called.</p>\n\n<div><code>\nvar myFont;\nfunction preload() {\n myFont = loadFont('assets/AvenirNextLTPro-Demi.otf');\n}\n\nfunction setup() {\n fill('#ED225D');\n textFont(myFont);\n textSize(36);\n text('p5*js', 10, 50);\n}\n</code></div>\n\nOutside of <a href=\"#/p5/preload\">preload()</a>, you may supply a callback function to handle the\nobject:\n\n<div><code>\nfunction setup() {\n loadFont('assets/AvenirNextLTPro-Demi.otf', drawText);\n}\n\nfunction drawText(font) {\n fill('#ED225D');\n textFont(font, 36);\n text('p5*js', 10, 50);\n}\n</code></div>\n\n<p>You can also use the string name of the font to style other HTML\nelements.</p>\n\n<div><code>\nfunction preload() {\n loadFont('assets/Avenir.otf');\n}\n\nfunction setup() {\n var myDiv = createDiv('hello there');\n myDiv.style('font-family', 'Avenir');\n}\n</code></div>"],"alt":"p5*js in p5's theme dark pink\np5*js in p5's theme dark pink","class":"p5","module":"Typography","submodule":"Loading & Displaying"},{"file":"src/typography/loading_displaying.js","line":143,"description":"<p>Draws text to the screen. Displays the information specified in the first\nparameter on the screen in the position specified by the additional\nparameters. A default font will be used unless a font is set with the\n<a href=\"#/p5/textFont\">textFont()</a> function and a default size will be used unless a font is set\nwith <a href=\"#/p5/textSize\">textSize()</a>. Change the color of the text with the <a href=\"#/p5/fill\">fill()</a> function.\nChange the outline of the text with the <a href=\"#/p5/stroke\">stroke()</a> and <a href=\"#/p5/strokeWeight\">strokeWeight()</a>\nfunctions.\n<br><br>\nThe text displays in relation to the <a href=\"#/p5/textAlign\">textAlign()</a> function, which gives the\noption to draw to the left, right, and center of the coordinates.\n<br><br>\nThe x2 and y2 parameters define a rectangular area to display within and\nmay only be used with string data. When these parameters are specified,\nthey are interpreted based on the current <a href=\"#/p5/rectMode\">rectMode()</a> setting. Text that\ndoes not fit completely within the rectangle specified will not be drawn\nto the screen. If x2 and y2 are not specified, the baseline alignment is the\ndefault, which means that the text will be drawn upwards from x and y.\n<br><br>\n<b>WEBGL</b>: Only opentype/truetype fonts are supported. You must load a font using the\n<a href=\"#/p5/loadFont\">loadFont()</a> method (see the example above).\n<a href=\"#/p5/stroke\">stroke()</a> currently has no effect in webgl mode.</p>\n","itemtype":"method","name":"text","params":[{"name":"str","description":"<p>the alphanumeric\n symbols to be displayed</p>\n","type":"String|Object|Array|Number|Boolean"},{"name":"x","description":"<p>x-coordinate of text</p>\n","type":"Number"},{"name":"y","description":"<p>y-coordinate of text</p>\n","type":"Number"},{"name":"x2","description":"<p>by default, the width of the text box,\n see <a href=\"#/p5/rectMode\">rectMode()</a> for more info</p>\n","type":"Number","optional":true},{"name":"y2","description":"<p>by default, the height of the text box,\n see <a href=\"#/p5/rectMode\">rectMode()</a> for more info</p>\n","type":"Number","optional":true}],"chainable":1,"example":["\n<div>\n<code>\ntextSize(32);\ntext('word', 10, 30);\nfill(0, 102, 153);\ntext('word', 10, 60);\nfill(0, 102, 153, 51);\ntext('word', 10, 90);\n</code>\n</div>\n<div>\n<code>\nvar s = 'The quick brown fox jumped over the lazy dog.';\nfill(50);\ntext(s, 10, 10, 70, 80); // Text wraps within text box\n</code>\n</div>\n\n<div modernizr='webgl'>\n<code>\nvar avenir;\nfunction preload() {\n avenir = loadFont('assets/Avenir.otf');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n textFont(avenir);\n textSize(width / 3);\n textAlign(CENTER, CENTER);\n}\nfunction draw() {\n background(0);\n var time = millis();\n rotateX(time / 1000);\n rotateZ(time / 1234);\n text('p5.js', 0, 0);\n}\n</code>\n</div>"],"alt":"'word' displayed 3 times going from black, blue to translucent blue\nThe quick brown fox jumped over the lazy dog.\nthe text 'p5.js' spinning in 3d","class":"p5","module":"Typography","submodule":"Loading & Displaying"},{"file":"src/typography/loading_displaying.js","line":230,"description":"<p>Sets the current font that will be drawn with the <a href=\"#/p5/text\">text()</a> function.\n<br><br>\n<b>WEBGL</b>: Only fonts loaded via <a href=\"#/p5/loadFont\">loadFont()</a> are supported.</p>\n","itemtype":"method","name":"textFont","return":{"description":"the current font","type":"Object"},"example":["\n<div>\n<code>\nfill(0);\ntextSize(12);\ntextFont('Georgia');\ntext('Georgia', 12, 30);\ntextFont('Helvetica');\ntext('Helvetica', 12, 60);\n</code>\n</div>\n<div>\n<code>\nvar fontRegular, fontItalic, fontBold;\nfunction preload() {\n fontRegular = loadFont('assets/Regular.otf');\n fontItalic = loadFont('assets/Italic.ttf');\n fontBold = loadFont('assets/Bold.ttf');\n}\nfunction setup() {\n background(210);\n fill(0)\n .strokeWeight(0)\n .textSize(10);\n textFont(fontRegular);\n text('Font Style Normal', 10, 30);\n textFont(fontItalic);\n text('Font Style Italic', 10, 50);\n textFont(fontBold);\n text('Font Style Bold', 10, 70);\n}\n</code>\n</div>"],"alt":"words Font Style Normal displayed normally, Italic in italic and bold in bold","class":"p5","module":"Typography","submodule":"Loading & Displaying","overloads":[{"line":230,"params":[],"return":{"description":"the current font","type":"Object"}},{"line":275,"params":[{"name":"font","description":"<p>a font loaded via <a href=\"#/p5/loadFont\">loadFont()</a>, or a String\nrepresenting a <a href=\"https://mzl.la/2dOw8WD\">web safe font</a> (a font\nthat is generally available across all systems)</p>\n","type":"Object|String"},{"name":"size","description":"<p>the font size to use</p>\n","type":"Number","optional":true}],"chainable":1}]},{"file":"src/typography/p5.Font.js","line":31,"description":"<p>Underlying opentype font implementation</p>\n","itemtype":"property","name":"font","class":"p5.Font","module":"Typography","submodule":"Font"},{"file":"src/typography/p5.Font.js","line":43,"description":"<p>Returns a tight bounding box for the given text string using this\nfont (currently only supports single lines)</p>\n","itemtype":"method","name":"textBounds","params":[{"name":"line","description":"<p>a line of text</p>\n","type":"String"},{"name":"x","description":"<p>x-position</p>\n","type":"Number"},{"name":"y","description":"<p>y-position</p>\n","type":"Number"},{"name":"fontSize","description":"<p>font size to use (optional)</p>\n","type":"Number","optional":true},{"name":"options","description":"<p>opentype options (optional)</p>\n","type":"Object","optional":true}],"return":{"description":"a rectangle object with properties: x, y, w, h","type":"Object"},"example":["\n<div>\n<code>\nvar font;\nvar textString = 'Lorem ipsum dolor sit amet.';\nfunction preload() {\n font = loadFont('./assets/Regular.otf');\n}\nfunction setup() {\n background(210);\n\n var bbox = font.textBounds(textString, 10, 30, 12);\n fill(255);\n stroke(0);\n rect(bbox.x, bbox.y, bbox.w, bbox.h);\n fill(0);\n noStroke();\n\n textFont(font);\n textSize(12);\n text(textString, 10, 30);\n}\n</code>\n</div>"],"alt":"words Lorem ipsum dol go off canvas and contained by white bounding box","class":"p5.Font","module":"Typography","submodule":"Font"},{"file":"src/typography/p5.Font.js","line":157,"description":"<p>Computes an array of points following the path for specified text</p>\n","itemtype":"method","name":"textToPoints","params":[{"name":"txt","description":"<p>a line of text</p>\n","type":"String"},{"name":"x","description":"<p>x-position</p>\n","type":"Number"},{"name":"y","description":"<p>y-position</p>\n","type":"Number"},{"name":"fontSize","description":"<p>font size to use (optional)</p>\n","type":"Number"},{"name":"options","description":"<p>an (optional) object that can contain:</p>\n<p><br>sampleFactor - the ratio of path-length to number of samples\n(default=.25); higher values yield more points and are therefore\nmore precise</p>\n<p><br>simplifyThreshold - if set to a non-zero value, collinear points will be\nbe removed from the polygon; the value represents the threshold angle to use\nwhen determining whether two edges are collinear</p>\n","type":"Object","optional":true}],"return":{"description":"an array of points, each with x, y, alpha (the path angle)","type":"Array"},"example":["\n<div>\n<code>\nvar font;\nfunction preload() {\n font = loadFont('./assets/Avenir.otf');\n}\n\nvar points;\nvar bounds;\nfunction setup() {\n createCanvas(100, 100);\n stroke(0);\n fill(255, 104, 204);\n\n points = font.textToPoints('p5', 0, 0, 10, {\n sampleFactor: 5,\n simplifyThreshold: 0\n });\n bounds = font.textBounds(' p5 ', 0, 0, 10);\n}\n\nfunction draw() {\n background(255);\n beginShape();\n translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h);\n for (var i = 0; i < points.length; i++) {\n var p = points[i];\n vertex(\n p.x * width / bounds.w +\n sin(20 * p.y / bounds.h + millis() / 1000) * width / 30,\n p.y * height / bounds.h\n );\n }\n endShape(CLOSE);\n}\n</code>\n</div>\n"],"class":"p5.Font","module":"Typography","submodule":"Font"},{"file":"src/utilities/array_functions.js","line":12,"description":"<p>Adds a value to the end of an array. Extends the length of\nthe array by one. Maps to Array.push().</p>\n","itemtype":"method","name":"append","deprecated":true,"deprecationMessage":"Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push\">array.push(value)</a> instead.","params":[{"name":"array","description":"<p>Array to append</p>\n","type":"Array"},{"name":"value","description":"<p>to be added to the Array</p>\n","type":"Any"}],"return":{"description":"the array that was appended to","type":"Array"},"example":["\n<div class='norender'><code>\nfunction setup() {\n var myArray = ['Mango', 'Apple', 'Papaya'];\n print(myArray); // ['Mango', 'Apple', 'Papaya']\n\n append(myArray, 'Peach');\n print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach']\n}\n</code></div>"],"class":"p5","module":"Data","submodule":"Array Functions"},{"file":"src/utilities/array_functions.js","line":37,"description":"<p>Copies an array (or part of an array) to another array. The src array is\ncopied to the dst array, beginning at the position specified by\nsrcPosition and into the position specified by dstPosition. The number of\nelements to copy is determined by length. Note that copying values\noverwrites existing values in the destination array. To append values\ninstead of overwriting them, use <a href=\"#/p5/concat\">concat()</a>.\n<br><br>\nThe simplified version with only two arguments, arrayCopy(src, dst),\ncopies an entire array to another of the same size. It is equivalent to\narrayCopy(src, 0, dst, 0, src.length).\n<br><br>\nUsing this function is far more efficient for copying array data than\niterating through a for() loop and copying each element individually.</p>\n","itemtype":"method","name":"arrayCopy","deprecated":true,"example":["\n<div class='norender'><code>\nvar src = ['A', 'B', 'C'];\nvar dst = [1, 2, 3];\nvar srcPosition = 1;\nvar dstPosition = 0;\nvar length = 2;\n\nprint(src); // ['A', 'B', 'C']\nprint(dst); // [ 1 , 2 , 3 ]\n\narrayCopy(src, srcPosition, dst, dstPosition, length);\nprint(dst); // ['B', 'C', 3]\n</code></div>"],"class":"p5","module":"Data","submodule":"Array Functions","overloads":[{"line":37,"params":[{"name":"src","description":"<p>the source Array</p>\n","type":"Array"},{"name":"srcPosition","description":"<p>starting position in the source Array</p>\n","type":"Integer"},{"name":"dst","description":"<p>the destination Array</p>\n","type":"Array"},{"name":"dstPosition","description":"<p>starting position in the destination Array</p>\n","type":"Integer"},{"name":"length","description":"<p>number of Array elements to be copied</p>\n","type":"Integer"}]},{"line":75,"params":[{"name":"src","description":"","type":"Array"},{"name":"dst","description":"","type":"Array"},{"name":"length","description":"","type":"Integer","optional":true}]}]},{"file":"src/utilities/array_functions.js","line":114,"description":"<p>Concatenates two arrays, maps to Array.concat(). Does not modify the\ninput arrays.</p>\n","itemtype":"method","name":"concat","deprecated":true,"deprecationMessage":"Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat\">arr1.concat(arr2)</a> instead.","params":[{"name":"a","description":"<p>first Array to concatenate</p>\n","type":"Array"},{"name":"b","description":"<p>second Array to concatenate</p>\n","type":"Array"}],"return":{"description":"concatenated array","type":"Array"},"example":["\n<div class = 'norender'><code>\nfunction setup() {\n var arr1 = ['A', 'B', 'C'];\n var arr2 = [1, 2, 3];\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1,2,3]\n\n var arr3 = concat(arr1, arr2);\n\n print(arr1); // ['A','B','C']\n print(arr2); // [1, 2, 3]\n print(arr3); // ['A','B','C', 1, 2, 3]\n}\n</code></div>"],"class":"p5","module":"Data","submodule":"Array Functions"},{"file":"src/utilities/array_functions.js","line":145,"description":"<p>Reverses the order of an array, maps to Array.reverse()</p>\n","itemtype":"method","name":"reverse","deprecated":true,"deprecationMessage":"Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse\">array.reverse()</a> instead.","params":[{"name":"list","description":"<p>Array to reverse</p>\n","type":"Array"}],"return":{"description":"the reversed list","type":"Array"},"example":["\n<div class='norender'><code>\nfunction setup() {\n var myArray = ['A', 'B', 'C'];\n print(myArray); // ['A','B','C']\n\n reverse(myArray);\n print(myArray); // ['C','B','A']\n}\n</code></div>"],"class":"p5","module":"Data","submodule":"Array Functions"},{"file":"src/utilities/array_functions.js","line":167,"description":"<p>Decreases an array by one element and returns the shortened array,\nmaps to Array.pop().</p>\n","itemtype":"method","name":"shorten","deprecated":true,"deprecationMessage":"Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop\">array.pop()</a> instead.","params":[{"name":"list","description":"<p>Array to shorten</p>\n","type":"Array"}],"return":{"description":"shortened Array","type":"Array"},"example":["\n<div class = 'norender'><code>\nfunction setup() {\n var myArray = ['A', 'B', 'C'];\n print(myArray); // ['A', 'B', 'C']\n var newArray = shorten(myArray);\n print(myArray); // ['A','B','C']\n print(newArray); // ['A','B']\n}\n</code></div>"],"class":"p5","module":"Data","submodule":"Array Functions"},{"file":"src/utilities/array_functions.js","line":191,"description":"<p>Randomizes the order of the elements of an array. Implements\n<a href='http://Bost.Ocks.org/mike/shuffle/' target=_blank>\nFisher-Yates Shuffle Algorithm</a>.</p>\n","itemtype":"method","name":"shuffle","deprecated":true,"deprecationMessage":"See <a href=\"https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array\">shuffling an array with JS</a> instead.","params":[{"name":"array","description":"<p>Array to shuffle</p>\n","type":"Array"},{"name":"bool","description":"<p>modify passed array</p>\n","type":"Boolean","optional":true}],"return":{"description":"shuffled Array","type":"Array"},"example":["\n<div><code>\nfunction setup() {\n var regularArr = ['ABC', 'def', createVector(), TAU, Math.E];\n print(regularArr);\n shuffle(regularArr, true); // force modifications to passed array\n print(regularArr);\n\n // By default shuffle() returns a shuffled cloned array:\n var newArr = shuffle(regularArr);\n print(regularArr);\n print(newArr);\n}\n</code></div>"],"class":"p5","module":"Data","submodule":"Array Functions"},{"file":"src/utilities/array_functions.js","line":234,"description":"<p>Sorts an array of numbers from smallest to largest, or puts an array of\nwords in alphabetical order. The original array is not modified; a\nre-ordered array is returned. The count parameter states the number of\nelements to sort. For example, if there are 12 elements in an array and\ncount is set to 5, only the first 5 elements in the array will be sorted.</p>\n","itemtype":"method","name":"sort","deprecated":true,"deprecationMessage":"Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\">array.sort()</a> instead.","params":[{"name":"list","description":"<p>Array to sort</p>\n","type":"Array"},{"name":"count","description":"<p>number of elements to sort, starting from 0</p>\n","type":"Integer","optional":true}],"return":{"description":"the sorted list","type":"Array"},"example":["\n<div class = 'norender'><code>\nfunction setup() {\n var words = ['banana', 'apple', 'pear', 'lime'];\n print(words); // ['banana', 'apple', 'pear', 'lime']\n var count = 4; // length of array\n\n words = sort(words, count);\n print(words); // ['apple', 'banana', 'lime', 'pear']\n}\n</code></div>\n<div class = 'norender'><code>\nfunction setup() {\n var numbers = [2, 6, 1, 5, 14, 9, 8, 12];\n print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12]\n var count = 5; // Less than the length of the array\n\n numbers = sort(numbers, count);\n print(numbers); // [1,2,5,6,14,9,8,12]\n}\n</code></div>"],"class":"p5","module":"Data","submodule":"Array Functions"},{"file":"src/utilities/array_functions.js","line":282,"description":"<p>Inserts a value or an array of values into an existing array. The first\nparameter specifies the initial array to be modified, and the second\nparameter defines the data to be inserted. The third parameter is an index\nvalue which specifies the array position from which to insert data.\n(Remember that array index numbering starts at zero, so the first position\nis 0, the second position is 1, and so on.)</p>\n","itemtype":"method","name":"splice","deprecated":true,"deprecationMessage":"Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\">array.splice()</a> instead.","params":[{"name":"list","description":"<p>Array to splice into</p>\n","type":"Array"},{"name":"value","description":"<p>value to be spliced in</p>\n","type":"Any"},{"name":"position","description":"<p>in the array from which to insert data</p>\n","type":"Integer"}],"return":{"description":"the list","type":"Array"},"example":["\n<div class = 'norender'><code>\nfunction setup() {\n var myArray = [0, 1, 2, 3, 4];\n var insArray = ['A', 'B', 'C'];\n print(myArray); // [0, 1, 2, 3, 4]\n print(insArray); // ['A','B','C']\n\n splice(myArray, insArray, 3);\n print(myArray); // [0,1,2,'A','B','C',3,4]\n}\n</code></div>"],"class":"p5","module":"Data","submodule":"Array Functions"},{"file":"src/utilities/array_functions.js","line":317,"description":"<p>Extracts an array of elements from an existing array. The list parameter\ndefines the array from which the elements will be copied, and the start\nand count parameters specify which elements to extract. If no count is\ngiven, elements will be extracted from the start to the end of the array.\nWhen specifying the start, remember that the first array element is 0.\nThis function does not change the source array.</p>\n","itemtype":"method","name":"subset","deprecated":true,"deprecationMessage":"Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice\">array.slice()</a> instead.","params":[{"name":"list","description":"<p>Array to extract from</p>\n","type":"Array"},{"name":"start","description":"<p>position to begin</p>\n","type":"Integer"},{"name":"count","description":"<p>number of values to extract</p>\n","type":"Integer","optional":true}],"return":{"description":"Array of extracted elements","type":"Array"},"example":["\n<div class = 'norender'><code>\nfunction setup() {\n var myArray = [1, 2, 3, 4, 5];\n print(myArray); // [1, 2, 3, 4, 5]\n\n var sub1 = subset(myArray, 0, 3);\n var sub2 = subset(myArray, 2, 2);\n print(sub1); // [1,2,3]\n print(sub2); // [3,4]\n}\n</code></div>"],"class":"p5","module":"Data","submodule":"Array Functions"},{"file":"src/utilities/conversion.js","line":12,"description":"<p>Converts a string to its floating point representation. The contents of a\nstring must resemble a number, or NaN (not a number) will be returned.\nFor example, float(&quot;1234.56&quot;) evaluates to 1234.56, but float(&quot;giraffe&quot;)\nwill return NaN.</p>\n<p>When an array of values is passed in, then an array of floats of the same\nlength is returned.</p>\n","itemtype":"method","name":"float","params":[{"name":"str","description":"<p>float string to parse</p>\n","type":"String"}],"return":{"description":"floating point representation of string","type":"Number"},"example":["\n<div><code>\nvar str = '20';\nvar diameter = float(str);\nellipse(width / 2, height / 2, diameter, diameter);\n</code></div>"],"alt":"20 by 20 white ellipse in the center of the canvas","class":"p5","module":"Data","submodule":"Conversion"},{"file":"src/utilities/conversion.js","line":42,"description":"<p>Converts a boolean, string, or float to its integer representation.\nWhen an array of values is passed in, then an int array of the same length\nis returned.</p>\n","itemtype":"method","name":"int","return":{"description":"integer representation of value","type":"Number"},"example":["\n<div class='norender'><code>\nprint(int('10')); // 10\nprint(int(10.31)); // 10\nprint(int(-10)); // -10\nprint(int(true)); // 1\nprint(int(false)); // 0\nprint(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9]\n</code></div>"],"class":"p5","module":"Data","submodule":"Conversion","overloads":[{"line":42,"params":[{"name":"n","description":"<p>value to parse</p>\n","type":"String|Boolean|Number"},{"name":"radix","description":"<p>the radix to convert to (default: 10)</p>\n","type":"Integer","optional":true}],"return":{"description":"integer representation of value","type":"Number"}},{"line":62,"params":[{"name":"ns","description":"<p>values to parse</p>\n","type":"Array"}],"return":{"description":"integer representation of values","type":"Number[]"}}]},{"file":"src/utilities/conversion.js","line":82,"description":"<p>Converts a boolean, string or number to its string representation.\nWhen an array of values is passed in, then an array of strings of the same\nlength is returned.</p>\n","itemtype":"method","name":"str","params":[{"name":"n","description":"<p>value to parse</p>\n","type":"String|Boolean|Number|Array"}],"return":{"description":"string representation of value","type":"String"},"example":["\n<div class='norender'><code>\nprint(str('10')); // \"10\"\nprint(str(10.31)); // \"10.31\"\nprint(str(-10)); // \"-10\"\nprint(str(true)); // \"true\"\nprint(str(false)); // \"false\"\nprint(str([true, '10.3', 9.8])); // [ \"true\", \"10.3\", \"9.8\" ]\n</code></div>"],"class":"p5","module":"Data","submodule":"Conversion"},{"file":"src/utilities/conversion.js","line":108,"description":"<p>Converts a number or string to its boolean representation.\nFor a number, any non-zero value (positive or negative) evaluates to true,\nwhile zero evaluates to false. For a string, the value &quot;true&quot; evaluates to\ntrue, while any other value evaluates to false. When an array of number or\nstring values is passed in, then a array of booleans of the same length is\nreturned.</p>\n","itemtype":"method","name":"boolean","params":[{"name":"n","description":"<p>value to parse</p>\n","type":"String|Boolean|Number|Array"}],"return":{"description":"boolean representation of value","type":"Boolean"},"example":["\n<div class='norender'><code>\nprint(boolean(0)); // false\nprint(boolean(1)); // true\nprint(boolean('true')); // true\nprint(boolean('abcd')); // false\nprint(boolean([0, 12, 'true'])); // [false, true, false]\n</code></div>"],"class":"p5","module":"Data","submodule":"Conversion"},{"file":"src/utilities/conversion.js","line":140,"description":"<p>Converts a number, string representation of a number, or boolean to its byte\nrepresentation. A byte can be only a whole number between -128 and 127, so\nwhen a value outside of this range is converted, it wraps around to the\ncorresponding byte representation. When an array of number, string or boolean\nvalues is passed in, then an array of bytes the same length is returned.</p>\n","itemtype":"method","name":"byte","return":{"description":"byte representation of value","type":"Number"},"example":["\n<div class='norender'><code>\nprint(byte(127)); // 127\nprint(byte(128)); // -128\nprint(byte(23.4)); // 23\nprint(byte('23.4')); // 23\nprint(byte('hello')); // NaN\nprint(byte(true)); // 1\nprint(byte([0, 255, '100'])); // [0, -1, 100]\n</code></div>"],"class":"p5","module":"Data","submodule":"Conversion","overloads":[{"line":140,"params":[{"name":"n","description":"<p>value to parse</p>\n","type":"String|Boolean|Number"}],"return":{"description":"byte representation of value","type":"Number"}},{"line":162,"params":[{"name":"ns","description":"<p>values to parse</p>\n","type":"Array"}],"return":{"description":"array of byte representation of values","type":"Number[]"}}]},{"file":"src/utilities/conversion.js","line":176,"description":"<p>Converts a number or string to its corresponding single-character\nstring representation. If a string parameter is provided, it is first\nparsed as an integer and then translated into a single-character string.\nWhen an array of number or string values is passed in, then an array of\nsingle-character strings of the same length is returned.</p>\n","itemtype":"method","name":"char","return":{"description":"string representation of value","type":"String"},"example":["\n<div class='norender'><code>\nprint(char(65)); // \"A\"\nprint(char('65')); // \"A\"\nprint(char([65, 66, 67])); // [ \"A\", \"B\", \"C\" ]\nprint(join(char([65, 66, 67]), '')); // \"ABC\"\n</code></div>"],"class":"p5","module":"Data","submodule":"Conversion","overloads":[{"line":176,"params":[{"name":"n","description":"<p>value to parse</p>\n","type":"String|Number"}],"return":{"description":"string representation of value","type":"String"}},{"line":195,"params":[{"name":"ns","description":"<p>values to parse</p>\n","type":"Array"}],"return":{"description":"array of string representation of values","type":"String[]"}}]},{"file":"src/utilities/conversion.js","line":210,"description":"<p>Converts a single-character string to its corresponding integer\nrepresentation. When an array of single-character string values is passed\nin, then an array of integers of the same length is returned.</p>\n","itemtype":"method","name":"unchar","return":{"description":"integer representation of value","type":"Number"},"example":["\n<div class='norender'><code>\nprint(unchar('A')); // 65\nprint(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ]\nprint(unchar(split('ABC', ''))); // [ 65, 66, 67 ]\n</code></div>"],"class":"p5","module":"Data","submodule":"Conversion","overloads":[{"line":210,"params":[{"name":"n","description":"<p>value to parse</p>\n","type":"String"}],"return":{"description":"integer representation of value","type":"Number"}},{"line":226,"params":[{"name":"ns","description":"<p>values to parse</p>\n","type":"Array"}],"return":{"description":"integer representation of values","type":"Number[]"}}]},{"file":"src/utilities/conversion.js","line":239,"description":"<p>Converts a number to a string in its equivalent hexadecimal notation. If a\nsecond parameter is passed, it is used to set the number of characters to\ngenerate in the hexadecimal notation. When an array is passed in, an\narray of strings in hexadecimal notation of the same length is returned.</p>\n","itemtype":"method","name":"hex","return":{"description":"hexadecimal string representation of value","type":"String"},"example":["\n<div class='norender'><code>\nprint(hex(255)); // \"000000FF\"\nprint(hex(255, 6)); // \"0000FF\"\nprint(hex([0, 127, 255], 6)); // [ \"000000\", \"00007F\", \"0000FF\" ]\n</code></div>"],"class":"p5","module":"Data","submodule":"Conversion","overloads":[{"line":239,"params":[{"name":"n","description":"<p>value to parse</p>\n","type":"Number"},{"name":"digits","description":"","type":"Number","optional":true}],"return":{"description":"hexadecimal string representation of value","type":"String"}},{"line":257,"params":[{"name":"ns","description":"<p>array of values to parse</p>\n","type":"Number[]"},{"name":"digits","description":"","type":"Number","optional":true}],"return":{"description":"hexadecimal string representation of values","type":"String[]"}}]},{"file":"src/utilities/conversion.js","line":286,"description":"<p>Converts a string representation of a hexadecimal number to its equivalent\ninteger value. When an array of strings in hexadecimal notation is passed\nin, an array of integers of the same length is returned.</p>\n","itemtype":"method","name":"unhex","return":{"description":"integer representation of hexadecimal value","type":"Number"},"example":["\n<div class='norender'><code>\nprint(unhex('A')); // 10\nprint(unhex('FF')); // 255\nprint(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ]\n</code></div>"],"class":"p5","module":"Data","submodule":"Conversion","overloads":[{"line":286,"params":[{"name":"n","description":"<p>value to parse</p>\n","type":"String"}],"return":{"description":"integer representation of hexadecimal value","type":"Number"}},{"line":302,"params":[{"name":"ns","description":"<p>values to parse</p>\n","type":"Array"}],"return":{"description":"integer representations of hexadecimal value","type":"Number[]"}}]},{"file":"src/utilities/string_functions.js","line":15,"description":"<p>Combines an array of Strings into one String, each separated by the\ncharacter(s) used for the separator parameter. To join arrays of ints or\nfloats, it&#39;s necessary to first convert them to Strings using <a href=\"#/p5/nf\">nf()</a> or\nnfs().</p>\n","itemtype":"method","name":"join","params":[{"name":"list","description":"<p>array of Strings to be joined</p>\n","type":"Array"},{"name":"separator","description":"<p>String to be placed between each item</p>\n","type":"String"}],"return":{"description":"joined String","type":"String"},"example":["\n<div>\n<code>\nvar array = ['Hello', 'world!'];\nvar separator = ' ';\nvar message = join(array, separator);\ntext(message, 5, 50);\n</code>\n</div>"],"alt":"\"hello world!\" displayed middle left of canvas.","class":"p5","module":"Data","submodule":"String Functions"},{"file":"src/utilities/string_functions.js","line":44,"description":"<p>This function is used to apply a regular expression to a piece of text,\nand return matching groups (elements found inside parentheses) as a\nString array. If there are no matches, a null value will be returned.\nIf no groups are specified in the regular expression, but the sequence\nmatches, an array of length 1 (with the matched text as the first element\nof the array) will be returned.\n<br><br>\nTo use the function, first check to see if the result is null. If the\nresult is null, then the sequence did not match at all. If the sequence\ndid match, an array is returned.\n<br><br>\nIf there are groups (specified by sets of parentheses) in the regular\nexpression, then the contents of each will be returned in the array.\nElement [0] of a regular expression match returns the entire matching\nstring, and the match groups start at element [1] (the first group is [1],\nthe second [2], and so on).</p>\n","itemtype":"method","name":"match","params":[{"name":"str","description":"<p>the String to be searched</p>\n","type":"String"},{"name":"regexp","description":"<p>the regexp to be used for matching</p>\n","type":"String"}],"return":{"description":"Array of Strings found","type":"String[]"},"example":["\n<div>\n<code>\nvar string = 'Hello p5js*!';\nvar regexp = 'p5js\\\\*';\nvar m = match(string, regexp);\ntext(m, 5, 50);\n</code>\n</div>"],"alt":"\"p5js*\" displayed middle left of canvas.","class":"p5","module":"Data","submodule":"String Functions"},{"file":"src/utilities/string_functions.js","line":85,"description":"<p>This function is used to apply a regular expression to a piece of text,\nand return a list of matching groups (elements found inside parentheses)\nas a two-dimensional String array. If there are no matches, a null value\nwill be returned. If no groups are specified in the regular expression,\nbut the sequence matches, a two dimensional array is still returned, but\nthe second dimension is only of length one.\n<br><br>\nTo use the function, first check to see if the result is null. If the\nresult is null, then the sequence did not match at all. If the sequence\ndid match, a 2D array is returned.\n<br><br>\nIf there are groups (specified by sets of parentheses) in the regular\nexpression, then the contents of each will be returned in the array.\nAssuming a loop with counter variable i, element [i][0] of a regular\nexpression match returns the entire matching string, and the match groups\nstart at element [i][1] (the first group is [i][1], the second [i][2],\nand so on).</p>\n","itemtype":"method","name":"matchAll","params":[{"name":"str","description":"<p>the String to be searched</p>\n","type":"String"},{"name":"regexp","description":"<p>the regexp to be used for matching</p>\n","type":"String"}],"return":{"description":"2d Array of Strings found","type":"String[]"},"example":["\n<div class=\"norender\">\n<code>\nvar string = 'Hello p5js*! Hello world!';\nvar regexp = 'Hello';\nmatchAll(string, regexp);\n</code>\n</div>"],"class":"p5","module":"Data","submodule":"String Functions"},{"file":"src/utilities/string_functions.js","line":132,"description":"<p>Utility function for formatting numbers into strings. There are two\nversions: one for formatting floats, and one for formatting ints.\nThe values for the digits, left, and right parameters should always\nbe positive integers.</p>\n","itemtype":"method","name":"nf","return":{"description":"formatted String","type":"String"},"example":["\n<div>\n<code>\nfunction setup() {\n background(200);\n var num = 112.53106115;\n\n noStroke();\n fill(0);\n textSize(14);\n // Draw formatted numbers\n text(nf(num, 5, 2), 10, 20);\n\n text(nf(num, 4, 3), 10, 55);\n\n text(nf(num, 3, 6), 10, 85);\n\n // Draw dividing lines\n stroke(120);\n line(0, 30, width, 30);\n line(0, 65, width, 65);\n}\n</code>\n</div>"],"alt":"\"0011253\" top left, \"0112.531\" mid left, \"112.531061\" bottom left canvas","class":"p5","module":"Data","submodule":"String Functions","overloads":[{"line":132,"params":[{"name":"num","description":"<p>the Number to format</p>\n","type":"Number|String"},{"name":"left","description":"<p>number of digits to the left of the\n decimal point</p>\n","type":"Integer|String","optional":true},{"name":"right","description":"<p>number of digits to the right of the\n decimal point</p>\n","type":"Integer|String","optional":true}],"return":{"description":"formatted String","type":"String"}},{"line":174,"params":[{"name":"nums","description":"<p>the Numbers to format</p>\n","type":"Array"},{"name":"left","description":"","type":"Integer|String","optional":true},{"name":"right","description":"","type":"Integer|String","optional":true}],"return":{"description":"formatted Strings","type":"String[]"}}]},{"file":"src/utilities/string_functions.js","line":237,"description":"<p>Utility function for formatting numbers into strings and placing\nappropriate commas to mark units of 1000. There are two versions: one\nfor formatting ints, and one for formatting an array of ints. The value\nfor the right parameter should always be a positive integer.</p>\n","itemtype":"method","name":"nfc","return":{"description":"formatted String","type":"String"},"example":["\n<div>\n<code>\nfunction setup() {\n background(200);\n var num = 11253106.115;\n var numArr = [1, 1, 2];\n\n noStroke();\n fill(0);\n textSize(12);\n\n // Draw formatted numbers\n text(nfc(num, 4), 10, 30);\n text(nfc(numArr, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n</code>\n</div>"],"alt":"\"11,253,106.115\" top middle and \"1.00,1.00,2.00\" displayed bottom mid","class":"p5","module":"Data","submodule":"String Functions","overloads":[{"line":237,"params":[{"name":"num","description":"<p>the Number to format</p>\n","type":"Number|String"},{"name":"right","description":"<p>number of digits to the right of the\n decimal point</p>\n","type":"Integer|String","optional":true}],"return":{"description":"formatted String","type":"String"}},{"line":275,"params":[{"name":"nums","description":"<p>the Numbers to format</p>\n","type":"Array"},{"name":"right","description":"","type":"Integer|String","optional":true}],"return":{"description":"formatted Strings","type":"String[]"}}]},{"file":"src/utilities/string_functions.js","line":313,"description":"<p>Utility function for formatting numbers into strings. Similar to <a href=\"#/p5/nf\">nf()</a> but\nputs a &quot;+&quot; in front of positive numbers and a &quot;-&quot; in front of negative\nnumbers. There are two versions: one for formatting floats, and one for\nformatting ints. The values for left, and right parameters\nshould always be positive integers.</p>\n","itemtype":"method","name":"nfp","return":{"description":"formatted String","type":"String"},"example":["\n<div>\n<code>\nfunction setup() {\n background(200);\n var num1 = 11253106.115;\n var num2 = -11253106.115;\n\n noStroke();\n fill(0);\n textSize(12);\n\n // Draw formatted numbers\n text(nfp(num1, 4, 2), 10, 30);\n text(nfp(num2, 4, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n</code>\n</div>"],"alt":"\"+11253106.11\" top middle and \"-11253106.11\" displayed bottom middle","class":"p5","module":"Data","submodule":"String Functions","overloads":[{"line":313,"params":[{"name":"num","description":"<p>the Number to format</p>\n","type":"Number"},{"name":"left","description":"<p>number of digits to the left of the decimal\n point</p>\n","type":"Integer","optional":true},{"name":"right","description":"<p>number of digits to the right of the\n decimal point</p>\n","type":"Integer","optional":true}],"return":{"description":"formatted String","type":"String"}},{"line":354,"params":[{"name":"nums","description":"<p>the Numbers to format</p>\n","type":"Number[]"},{"name":"left","description":"","type":"Integer","optional":true},{"name":"right","description":"","type":"Integer","optional":true}],"return":{"description":"formatted Strings","type":"String[]"}}]},{"file":"src/utilities/string_functions.js","line":375,"description":"<p>Utility function for formatting numbers into strings. Similar to <a href=\"#/p5/nf\">nf()</a> but\nputs a &quot; &quot; (space) in front of positive numbers and a &quot;-&quot; in front of\nnegative numbers. There are two versions: one for formatting floats, and\none for formatting ints. The values for the digits, left, and right\nparameters should always be positive integers.</p>\n","itemtype":"method","name":"nfs","return":{"description":"formatted String","type":"String"},"example":["\n<div>\n<code>\nfunction setup() {\n background(200);\n var num1 = 11253106.115;\n var num2 = -11253106.115;\n\n noStroke();\n fill(0);\n textSize(12);\n // Draw formatted numbers\n text(nfs(num1, 4, 2), 10, 30);\n\n text(nfs(num2, 4, 2), 10, 80);\n\n // Draw dividing line\n stroke(120);\n line(0, 50, width, 50);\n}\n</code>\n</div>"],"alt":"\"11253106.11\" top middle and \"-11253106.11\" displayed bottom middle","class":"p5","module":"Data","submodule":"String Functions","overloads":[{"line":375,"params":[{"name":"num","description":"<p>the Number to format</p>\n","type":"Number"},{"name":"left","description":"<p>number of digits to the left of the decimal\n point</p>\n","type":"Integer","optional":true},{"name":"right","description":"<p>number of digits to the right of the\n decimal point</p>\n","type":"Integer","optional":true}],"return":{"description":"formatted String","type":"String"}},{"line":416,"params":[{"name":"nums","description":"<p>the Numbers to format</p>\n","type":"Array"},{"name":"left","description":"","type":"Integer","optional":true},{"name":"right","description":"","type":"Integer","optional":true}],"return":{"description":"formatted Strings","type":"String[]"}}]},{"file":"src/utilities/string_functions.js","line":437,"description":"<p>The <a href=\"#/p5/split\">split()</a> function maps to String.split(), it breaks a String into\npieces using a character or string as the delimiter. The delim parameter\nspecifies the character or characters that mark the boundaries between\neach piece. A String[] array is returned that contains each of the pieces.</p>\n<p>The <a href=\"#/p5/splitTokens\">splitTokens()</a> function works in a similar fashion, except that it\nsplits using a range of characters instead of a specific character or\nsequence.</p>\n","itemtype":"method","name":"split","params":[{"name":"value","description":"<p>the String to be split</p>\n","type":"String"},{"name":"delim","description":"<p>the String used to separate the data</p>\n","type":"String"}],"return":{"description":"Array of Strings","type":"String[]"},"example":["\n<div>\n<code>\nvar names = 'Pat,Xio,Alex';\nvar splitString = split(names, ',');\ntext(splitString[0], 5, 30);\ntext(splitString[1], 5, 50);\ntext(splitString[2], 5, 70);\n</code>\n</div>"],"alt":"\"pat\" top left, \"Xio\" mid left and \"Alex\" displayed bottom left","class":"p5","module":"Data","submodule":"String Functions"},{"file":"src/utilities/string_functions.js","line":471,"description":"<p>The <a href=\"#/p5/splitTokens\">splitTokens()</a> function splits a String at one or many character\ndelimiters or &quot;tokens.&quot; The delim parameter specifies the character or\ncharacters to be used as a boundary.\n<br><br>\nIf no delim characters are specified, any whitespace character is used to\nsplit. Whitespace characters include tab (\\t), line feed (\\n), carriage\nreturn (\\r), form feed (\\f), and space.</p>\n","itemtype":"method","name":"splitTokens","params":[{"name":"value","description":"<p>the String to be split</p>\n","type":"String"},{"name":"delim","description":"<p>list of individual Strings that will be used as\n separators</p>\n","type":"String","optional":true}],"return":{"description":"Array of Strings","type":"String[]"},"example":["\n<div class = \"norender\">\n<code>\nfunction setup() {\n var myStr = 'Mango, Banana, Lime';\n var myStrArr = splitTokens(myStr, ',');\n\n print(myStrArr); // prints : [\"Mango\",\" Banana\",\" Lime\"]\n}\n</code>\n</div>"],"class":"p5","module":"Data","submodule":"String Functions"},{"file":"src/utilities/string_functions.js","line":526,"description":"<p>Removes whitespace characters from the beginning and end of a String. In\naddition to standard whitespace characters such as space, carriage return,\nand tab, this function also removes the Unicode &quot;nbsp&quot; character.</p>\n","itemtype":"method","name":"trim","return":{"description":"a trimmed String","type":"String"},"example":["\n<div>\n<code>\nvar string = trim(' No new lines\\n ');\ntext(string + ' here', 2, 50);\n</code>\n</div>"],"alt":"\"No new lines here\" displayed center canvas","class":"p5","module":"Data","submodule":"String Functions","overloads":[{"line":526,"params":[{"name":"str","description":"<p>a String to be trimmed</p>\n","type":"String"}],"return":{"description":"a trimmed String","type":"String"}},{"line":546,"params":[{"name":"strs","description":"<p>an Array of Strings to be trimmed</p>\n","type":"Array"}],"return":{"description":"an Array of trimmed Strings","type":"String[]"}}]},{"file":"src/utilities/time_date.js","line":12,"description":"<p>p5.js communicates with the clock on your computer. The <a href=\"#/p5/day\">day()</a> function\nreturns the current day as a value from 1 - 31.</p>\n","itemtype":"method","name":"day","return":{"description":"the current day","type":"Integer"},"example":["\n<div>\n<code>\nvar d = day();\ntext('Current day: \\n' + d, 5, 50);\n</code>\n</div>"],"alt":"Current day is displayed","class":"p5","module":"IO","submodule":"Time & Date"},{"file":"src/utilities/time_date.js","line":34,"description":"<p>p5.js communicates with the clock on your computer. The <a href=\"#/p5/hour\">hour()</a> function\nreturns the current hour as a value from 0 - 23.</p>\n","itemtype":"method","name":"hour","return":{"description":"the current hour","type":"Integer"},"example":["\n<div>\n<code>\nvar h = hour();\ntext('Current hour:\\n' + h, 5, 50);\n</code>\n</div>"],"alt":"Current hour is displayed","class":"p5","module":"IO","submodule":"Time & Date"},{"file":"src/utilities/time_date.js","line":56,"description":"<p>p5.js communicates with the clock on your computer. The <a href=\"#/p5/minute\">minute()</a> function\nreturns the current minute as a value from 0 - 59.</p>\n","itemtype":"method","name":"minute","return":{"description":"the current minute","type":"Integer"},"example":["\n<div>\n<code>\nvar m = minute();\ntext('Current minute: \\n' + m, 5, 50);\n</code>\n</div>"],"alt":"Current minute is displayed","class":"p5","module":"IO","submodule":"Time & Date"},{"file":"src/utilities/time_date.js","line":78,"description":"<p>Returns the number of milliseconds (thousandths of a second) since\nstarting the program. This information is often used for timing events and\nanimation sequences.</p>\n","itemtype":"method","name":"millis","return":{"description":"the number of milliseconds since starting the program","type":"Number"},"example":["\n<div>\n<code>\nvar millisecond = millis();\ntext('Milliseconds \\nrunning: \\n' + millisecond, 5, 40);\n</code>\n</div>"],"alt":"number of milliseconds since program has started displayed","class":"p5","module":"IO","submodule":"Time & Date"},{"file":"src/utilities/time_date.js","line":101,"description":"<p>p5.js communicates with the clock on your computer. The <a href=\"#/p5/month\">month()</a> function\nreturns the current month as a value from 1 - 12.</p>\n","itemtype":"method","name":"month","return":{"description":"the current month","type":"Integer"},"example":["\n<div>\n<code>\nvar m = month();\ntext('Current month: \\n' + m, 5, 50);\n</code>\n</div>"],"alt":"Current month is displayed","class":"p5","module":"IO","submodule":"Time & Date"},{"file":"src/utilities/time_date.js","line":123,"description":"<p>p5.js communicates with the clock on your computer. The <a href=\"#/p5/second\">second()</a> function\nreturns the current second as a value from 0 - 59.</p>\n","itemtype":"method","name":"second","return":{"description":"the current second","type":"Integer"},"example":["\n<div>\n<code>\nvar s = second();\ntext('Current second: \\n' + s, 5, 50);\n</code>\n</div>"],"alt":"Current second is displayed","class":"p5","module":"IO","submodule":"Time & Date"},{"file":"src/utilities/time_date.js","line":145,"description":"<p>p5.js communicates with the clock on your computer. The <a href=\"#/p5/year\">year()</a> function\nreturns the current year as an integer (2014, 2015, 2016, etc).</p>\n","itemtype":"method","name":"year","return":{"description":"the current year","type":"Integer"},"example":["\n<div>\n<code>\nvar y = year();\ntext('Current year: \\n' + y, 5, 50);\n</code>\n</div>"],"alt":"Current year is displayed","class":"p5","module":"IO","submodule":"Time & Date"},{"file":"src/webgl/3d_primitives.js","line":15,"description":"<p>Draw a plane with given a width and height</p>\n","itemtype":"method","name":"plane","params":[{"name":"width","description":"<p>width of the plane</p>\n","type":"Number","optional":true},{"name":"height","description":"<p>height of the plane</p>\n","type":"Number","optional":true},{"name":"detailX","description":"<p>Optional number of triangle\n subdivisions in x-dimension</p>\n","type":"Integer","optional":true},{"name":"detailY","description":"<p>Optional number of triangle\n subdivisions in y-dimension</p>\n","type":"Integer","optional":true}],"chainable":1,"example":["\n<div>\n<code>\n//draw a plane with width 50 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n plane(50, 50);\n}\n</code>\n</div>"],"alt":"Nothing displayed on canvas\nRotating interior view of a box with sides that change color.\n3d red and green gradient.\nRotating interior view of a cylinder with sides that change color.\nRotating view of a cylinder with sides that change color.\n3d red and green gradient.\nrotating view of a multi-colored cylinder with concave sides.","class":"p5","module":"Shape","submodule":"3D Primitives"},{"file":"src/webgl/3d_primitives.js","line":98,"description":"<p>Draw a box with given width, height and depth</p>\n","itemtype":"method","name":"box","params":[{"name":"width","description":"<p>width of the box</p>\n","type":"Number","optional":true},{"name":"Height","description":"<p>height of the box</p>\n","type":"Number","optional":true},{"name":"depth","description":"<p>depth of the box</p>\n","type":"Number","optional":true},{"name":"detailX","description":"<p>Optional number of triangle\n subdivisions in x-dimension</p>\n","type":"Integer","optional":true},{"name":"detailY","description":"<p>Optional number of triangle\n subdivisions in y-dimension</p>\n","type":"Integer","optional":true}],"chainable":1,"example":["\n<div>\n<code>\n//draw a spinning box with width, height and depth 200\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n box(50);\n}\n</code>\n</div>"],"class":"p5","module":"Shape","submodule":"3D Primitives"},{"file":"src/webgl/3d_primitives.js","line":215,"description":"<p>Draw a sphere with given radius</p>\n","itemtype":"method","name":"sphere","params":[{"name":"radius","description":"<p>radius of circle</p>\n","type":"Number","optional":true},{"name":"detailX","description":"<p>number of segments,\n the more segments the smoother geometry\n default is 24</p>\n","type":"Integer","optional":true},{"name":"detailY","description":"<p>number of segments,\n the more segments the smoother geometry\n default is 16</p>\n","type":"Integer","optional":true}],"chainable":1,"example":["\n<div>\n<code>\n// draw a sphere with radius 200\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n sphere(40);\n}\n</code>\n</div>"],"class":"p5","module":"Shape","submodule":"3D Primitives"},{"file":"src/webgl/3d_primitives.js","line":393,"description":"<p>Draw a cylinder with given radius and height</p>\n","itemtype":"method","name":"cylinder","params":[{"name":"radius","description":"<p>radius of the surface</p>\n","type":"Number","optional":true},{"name":"height","description":"<p>height of the cylinder</p>\n","type":"Number","optional":true},{"name":"detailX","description":"<p>number of segments,\n the more segments the smoother geometry\n default is 24</p>\n","type":"Integer","optional":true},{"name":"detailY","description":"<p>number of segments in y-dimension,\n the more segments the smoother geometry\n default is 1</p>\n","type":"Integer","optional":true},{"name":"bottomCap","description":"<p>whether to draw the bottom of the cylinder</p>\n","type":"Boolean","optional":true},{"name":"topCap","description":"<p>whether to draw the top of the cylinder</p>\n","type":"Boolean","optional":true}],"chainable":1,"example":["\n<div>\n<code>\n//draw a spinning cylinder with radius 20 and height 50\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cylinder(20, 50);\n}\n</code>\n</div>"],"class":"p5","module":"Shape","submodule":"3D Primitives"},{"file":"src/webgl/3d_primitives.js","line":484,"description":"<p>Draw a cone with given radius and height</p>\n","itemtype":"method","name":"cone","params":[{"name":"radius","description":"<p>radius of the bottom surface</p>\n","type":"Number","optional":true},{"name":"height","description":"<p>height of the cone</p>\n","type":"Number","optional":true},{"name":"detailX","description":"<p>number of segments,\n the more segments the smoother geometry\n default is 24</p>\n","type":"Integer","optional":true},{"name":"detailY","description":"<p>number of segments,\n the more segments the smoother geometry\n default is 1</p>\n","type":"Integer","optional":true},{"name":"cap","description":"<p>whether to draw the base of the cone</p>\n","type":"Boolean","optional":true}],"chainable":1,"example":["\n<div>\n<code>\n//draw a spinning cone with radius 40 and height 70\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateZ(frameCount * 0.01);\n cone(40, 70);\n}\n</code>\n</div>"],"class":"p5","module":"Shape","submodule":"3D Primitives"},{"file":"src/webgl/3d_primitives.js","line":555,"description":"<p>Draw an ellipsoid with given radius</p>\n","itemtype":"method","name":"ellipsoid","params":[{"name":"radiusx","description":"<p>xradius of circle</p>\n","type":"Number","optional":true},{"name":"radiusy","description":"<p>yradius of circle</p>\n","type":"Number","optional":true},{"name":"radiusz","description":"<p>zradius of circle</p>\n","type":"Number","optional":true},{"name":"detailX","description":"<p>number of segments,\n the more segments the smoother geometry\n default is 24. Avoid detail number above\n 150, it may crash the browser.</p>\n","type":"Integer","optional":true},{"name":"detailY","description":"<p>number of segments,\n the more segments the smoother geometry\n default is 16. Avoid detail number above\n 150, it may crash the browser.</p>\n","type":"Integer","optional":true}],"chainable":1,"example":["\n<div>\n<code>\n// draw an ellipsoid with radius 20, 30 and 40.\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n ellipsoid(20, 30, 40);\n}\n</code>\n</div>"],"class":"p5","module":"Shape","submodule":"3D Primitives"},{"file":"src/webgl/3d_primitives.js","line":645,"description":"<p>Draw a torus with given radius and tube radius</p>\n","itemtype":"method","name":"torus","params":[{"name":"radius","description":"<p>radius of the whole ring</p>\n","type":"Number","optional":true},{"name":"tubeRadius","description":"<p>radius of the tube</p>\n","type":"Number","optional":true},{"name":"detailX","description":"<p>number of segments in x-dimension,\n the more segments the smoother geometry\n default is 24</p>\n","type":"Integer","optional":true},{"name":"detailY","description":"<p>number of segments in y-dimension,\n the more segments the smoother geometry\n default is 16</p>\n","type":"Integer","optional":true}],"chainable":1,"example":["\n<div>\n<code>\n//draw a spinning torus with radius 200 and tube radius 60\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n torus(50, 15);\n}\n</code>\n</div>"],"class":"p5","module":"Shape","submodule":"3D Primitives"},{"file":"src/webgl/interaction.js","line":13,"description":"<p>Allows movement around a 3D sketch using a mouse or trackpad. Left-clicking\nand dragging will rotate the camera position about the center of the sketch,\nright-clicking and dragging will pan the camera position without rotation,\nand using the mouse wheel (scrolling) will move the camera closer or further\nfrom the center of the sketch. This function can be called with parameters\ndictating sensitivity to mouse movement along the X and Y axes. Calling\nthis function without parameters is equivalent to calling orbitControl(1,1).\nTo reverse direction of movement in either axis, enter a negative number\nfor sensitivity.</p>\n","itemtype":"method","name":"orbitControl","params":[{"name":"sensitivityX","description":"<p>sensitivity to mouse movement along X axis</p>\n","type":"Number","optional":true},{"name":"sensitivityY","description":"<p>sensitivity to mouse movement along Y axis</p>\n","type":"Number","optional":true}],"chainable":1,"example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n}\nfunction draw() {\n background(200);\n orbitControl();\n rotateY(0.5);\n box(30, 50);\n}\n</code>\n</div>"],"alt":"Camera orbits around a box when mouse is hold-clicked & then moved.","class":"p5","module":"Lights, Camera","submodule":"Interaction"},{"file":"src/webgl/interaction.js","line":146,"description":"<p>debugMode() helps visualize 3D space by adding a grid to indicate where the\n‘ground’ is in a sketch and an axes icon which indicates the +X, +Y, and +Z\ndirections. This function can be called without parameters to create a\ndefault grid and axes icon, or it can be called according to the examples\nabove to customize the size and position of the grid and/or axes icon. The\ngrid is drawn using the most recently set stroke color and weight. To\nspecify these parameters, add a call to stroke() and strokeWeight()\njust before the end of the draw() loop.</p>\n<p>By default, the grid will run through the origin (0,0,0) of the sketch\nalong the XZ plane\nand the axes icon will be offset from the origin. Both the grid and axes\nicon will be sized according to the current canvas size. Note that because the\ngrid runs parallel to the default camera view, it is often helpful to use\ndebugMode along with orbitControl to allow full view of the grid.</p>\n","itemtype":"method","name":"debugMode","example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode();\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n // Press the spacebar to turn debugMode off!\n if (keyIsDown(32)) {\n noDebugMode();\n }\n}\n</code>\n</div>","\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(GRID);\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n}\n</code>\n</div>","\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(AXES);\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n}\n</code>\n</div>","\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(GRID, 100, 10, 0, 0, 0);\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n}\n</code>\n</div>","\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode(100, 10, 0, 0, 0, 20, 0, -40, 0);\n}\n\nfunction draw() {\n noStroke();\n background(200);\n orbitControl();\n box(15, 30);\n // set the stroke color and weight for the grid!\n stroke(255, 0, 150);\n strokeWeight(0.8);\n}\n</code>\n</div>"],"alt":"a 3D box is centered on a grid in a 3D sketch. an icon\nindicates the direction of each axis: a red line points +X,\na green line +Y, and a blue line +Z.","class":"p5","module":"Lights, Camera","submodule":"Interaction","overloads":[{"line":146,"params":[]},{"line":279,"params":[{"name":"mode","description":"<p>either GRID or AXES</p>\n","type":"Constant"}]},{"line":284,"params":[{"name":"mode","description":"","type":"Constant"},{"name":"gridSize","description":"<p>size of one side of the grid</p>\n","type":"Number","optional":true},{"name":"gridDivisions","description":"<p>number of divisions in the grid</p>\n","type":"Number","optional":true},{"name":"xOff","description":"<p>X axis offset from origin (0,0,0)</p>\n","type":"Number","optional":true},{"name":"yOff","description":"<p>Y axis offset from origin (0,0,0)</p>\n","type":"Number","optional":true},{"name":"zOff","description":"<p>Z axis offset from origin (0,0,0)</p>\n","type":"Number","optional":true}]},{"line":294,"params":[{"name":"mode","description":"","type":"Constant"},{"name":"axesSize","description":"<p>size of axes icon</p>\n","type":"Number","optional":true},{"name":"xOff","description":"","type":"Number","optional":true},{"name":"yOff","description":"","type":"Number","optional":true},{"name":"zOff","description":"","type":"Number","optional":true}]},{"line":303,"params":[{"name":"gridSize","description":"","type":"Number","optional":true},{"name":"gridDivisions","description":"","type":"Number","optional":true},{"name":"xOff","description":"","type":"Number","optional":true},{"name":"yOff","description":"","type":"Number","optional":true},{"name":"zOff","description":"","type":"Number","optional":true},{"name":"axesSize","description":"","type":"Number","optional":true},{"name":"xOff","description":"","type":"Number","optional":true},{"name":"yOff","description":"","type":"Number","optional":true},{"name":"zOff","description":"","type":"Number","optional":true}]}]},{"file":"src/webgl/interaction.js","line":380,"description":"<p>Turns off debugMode() in a 3D sketch.</p>\n","itemtype":"method","name":"noDebugMode","example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n camera(0, -30, 100, 0, 0, 0, 0, 1, 0);\n normalMaterial();\n debugMode();\n}\n\nfunction draw() {\n background(200);\n orbitControl();\n box(15, 30);\n // Press the spacebar to turn debugMode off!\n if (keyIsDown(32)) {\n noDebugMode();\n }\n}\n</code>\n</div>"],"alt":"a 3D box is centered on a grid in a 3D sketch. an icon\nindicates the direction of each axis: a red line points +X,\na green line +Y, and a blue line +Z. the grid and icon disappear when the\nspacebar is pressed.","class":"p5","module":"Lights, Camera","submodule":"Interaction"},{"file":"src/webgl/light.js","line":12,"description":"<p>Creates an ambient light with a color</p>\n","itemtype":"method","name":"ambientLight","chainable":1,"example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(150);\n ambientMaterial(250);\n noStroke();\n sphere(25);\n}\n</code>\n</div>"],"alt":"evenly distributed light across a sphere","class":"p5","module":"Lights, Camera","submodule":"Lights","overloads":[{"line":12,"params":[{"name":"v1","description":"<p>red or hue value relative to\n the current color range</p>\n","type":"Number"},{"name":"v2","description":"<p>green or saturation value\n relative to the current color range</p>\n","type":"Number"},{"name":"v3","description":"<p>blue or brightness value\n relative to the current color range</p>\n","type":"Number"},{"name":"alpha","description":"<p>the alpha value</p>\n","type":"Number","optional":true}],"chainable":1},{"line":46,"params":[{"name":"value","description":"<p>a color string</p>\n","type":"String"}],"chainable":1},{"line":52,"params":[{"name":"gray","description":"<p>a gray value</p>\n","type":"Number"},{"name":"alpha","description":"","type":"Number","optional":true}],"chainable":1},{"line":59,"params":[{"name":"values","description":"<p>an array containing the red,green,blue &amp;\n and alpha components of the color</p>\n","type":"Number[]"}],"chainable":1},{"line":66,"params":[{"name":"color","description":"<p>the ambient light color</p>\n","type":"p5.Color"}],"chainable":1}]},{"file":"src/webgl/light.js","line":101,"description":"<p>Creates a directional light with a color and a direction</p>\n","itemtype":"method","name":"directionalLight","chainable":1,"example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light direction\n var dirX = (mouseX / width - 0.5) * 2;\n var dirY = (mouseY / height - 0.5) * 2;\n directionalLight(250, 250, 250, -dirX, -dirY, 0.25);\n ambientMaterial(250);\n noStroke();\n sphere(25);\n}\n</code>\n</div>"],"alt":"light source on canvas changeable with mouse position","class":"p5","module":"Lights, Camera","submodule":"Lights","overloads":[{"line":101,"params":[{"name":"v1","description":"<p>red or hue value (depending on the current\ncolor mode),</p>\n","type":"Number"},{"name":"v2","description":"<p>green or saturation value</p>\n","type":"Number"},{"name":"v3","description":"<p>blue or brightness value</p>\n","type":"Number"},{"name":"position","description":"<p>the direction of the light</p>\n","type":"p5.Vector"}],"chainable":1},{"line":134,"params":[{"name":"color","description":"<p>color Array, CSS color string,\n or <a href=\"#/p5.Color\">p5.Color</a> value</p>\n","type":"Number[]|String|p5.Color"},{"name":"x","description":"<p>x axis direction</p>\n","type":"Number"},{"name":"y","description":"<p>y axis direction</p>\n","type":"Number"},{"name":"z","description":"<p>z axis direction</p>\n","type":"Number"}],"chainable":1},{"line":144,"params":[{"name":"color","description":"","type":"Number[]|String|p5.Color"},{"name":"position","description":"","type":"p5.Vector"}],"chainable":1},{"line":151,"params":[{"name":"v1","description":"","type":"Number"},{"name":"v2","description":"","type":"Number"},{"name":"v3","description":"","type":"Number"},{"name":"x","description":"","type":"Number"},{"name":"y","description":"","type":"Number"},{"name":"z","description":"","type":"Number"}],"chainable":1}]},{"file":"src/webgl/light.js","line":212,"description":"<p>Creates a point light with a color and a light position</p>\n","itemtype":"method","name":"pointLight","chainable":1,"example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n //move your mouse to change light position\n var locX = mouseX - width / 2;\n var locY = mouseY - height / 2;\n // to set the light position,\n // think of the world's coordinate as:\n // -width/2,-height/2 -------- width/2,-height/2\n // | |\n // | 0,0 |\n // | |\n // -width/2,height/2--------width/2,height/2\n pointLight(250, 250, 250, locX, locY, 50);\n ambientMaterial(250);\n noStroke();\n sphere(25);\n}\n</code>\n</div>"],"alt":"spot light on canvas changes position with mouse","class":"p5","module":"Lights, Camera","submodule":"Lights","overloads":[{"line":212,"params":[{"name":"v1","description":"<p>red or hue value (depending on the current\ncolor mode),</p>\n","type":"Number"},{"name":"v2","description":"<p>green or saturation value</p>\n","type":"Number"},{"name":"v3","description":"<p>blue or brightness value</p>\n","type":"Number"},{"name":"x","description":"<p>x axis position</p>\n","type":"Number"},{"name":"y","description":"<p>y axis position</p>\n","type":"Number"},{"name":"z","description":"<p>z axis position</p>\n","type":"Number"}],"chainable":1},{"line":254,"params":[{"name":"v1","description":"","type":"Number"},{"name":"v2","description":"","type":"Number"},{"name":"v3","description":"","type":"Number"},{"name":"position","description":"<p>the position of the light</p>\n","type":"p5.Vector"}],"chainable":1},{"line":263,"params":[{"name":"color","description":"<p>color Array, CSS color string,\nor <a href=\"#/p5.Color\">p5.Color</a> value</p>\n","type":"Number[]|String|p5.Color"},{"name":"x","description":"","type":"Number"},{"name":"y","description":"","type":"Number"},{"name":"z","description":"","type":"Number"}],"chainable":1},{"line":273,"params":[{"name":"color","description":"","type":"Number[]|String|p5.Color"},{"name":"position","description":"","type":"p5.Vector"}],"chainable":1}]},{"file":"src/webgl/loading.js","line":14,"description":"<p>Load a 3d model from an OBJ file.\n<br><br>\nOne of the limitations of the OBJ format is that it doesn&#39;t have a built-in\nsense of scale. This means that models exported from different programs might\nbe very different sizes. If your model isn&#39;t displaying, try calling\n<a href=\"#/p5/loadModel\">loadModel()</a> with the normalized parameter set to true. This will resize the\nmodel to a scale appropriate for p5. You can also make additional changes to\nthe final size of your model with the <a href=\"#/p5/scale\">scale()</a> function.</p>\n","itemtype":"method","name":"loadModel","return":{"description":"the <a href=\"#/p5.Geometry\">p5.Geometry</a> object","type":"p5.Geometry"},"example":["\n<div>\n<code>\n//draw a spinning octahedron\nvar octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n</code>\n</div>","\n<div>\n<code>\n//draw a spinning teapot\nvar teapot;\n\nfunction preload() {\n // Load model with normalise parameter set to true\n teapot = loadModel('assets/teapot.obj', true);\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n scale(0.4); // Scaled to make model fit into canvas\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n normalMaterial(); // For effect\n model(teapot);\n}\n</code>\n</div>"],"alt":"Vertically rotating 3-d teapot with red, green and blue gradient.","class":"p5","module":"Shape","submodule":"3D Models","overloads":[{"line":14,"params":[{"name":"path","description":"<p>Path of the model to be loaded</p>\n","type":"String"},{"name":"normalize","description":"<p>If true, scale the model to a\n standardized size when loading</p>\n","type":"Boolean"},{"name":"successCallback","description":"<p>Function to be called\n once the model is loaded. Will be passed\n the 3D model object.</p>\n","type":"function(p5.Geometry)","optional":true},{"name":"failureCallback","description":"<p>called with event error if\n the image fails to load.</p>\n","type":"Function(Event)","optional":true}],"return":{"description":"the <a href=\"#/p5.Geometry\">p5.Geometry</a> object","type":"p5.Geometry"}},{"line":90,"params":[{"name":"path","description":"","type":"String"},{"name":"successCallback","description":"","type":"function(p5.Geometry)","optional":true},{"name":"failureCallback","description":"","type":"Function(Event)","optional":true}],"return":{"description":"the <a href=\"#/p5.Geometry\">p5.Geometry</a> object","type":"p5.Geometry"}}]},{"file":"src/webgl/loading.js","line":135,"description":"<p>Parse OBJ lines into model. For reference, this is what a simple model of a\nsquare might look like:</p>\n<p>v -0.5 -0.5 0.5\nv -0.5 -0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 0.5 0.5</p>\n<p>f 4 3 2 1</p>\n","class":"p5","module":"Shape","submodule":"3D Models"},{"file":"src/webgl/loading.js","line":244,"description":"<p>Render a 3d model to the screen.</p>\n","itemtype":"method","name":"model","params":[{"name":"model","description":"<p>Loaded 3d model to be rendered</p>\n","type":"p5.Geometry"}],"example":["\n<div>\n<code>\n//draw a spinning octahedron\nvar octahedron;\n\nfunction preload() {\n octahedron = loadModel('assets/octahedron.obj');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n model(octahedron);\n}\n</code>\n</div>"],"alt":"Vertically rotating 3-d octahedron.","class":"p5","module":"Shape","submodule":"3D Models"},{"file":"src/webgl/material.js","line":14,"description":"<p>Loads a custom shader from the provided vertex and fragment\nshader paths. The shader files are loaded asynchronously in the\nbackground, so this method should be used in <a href=\"#/p5/preload\">preload()</a>.</p>\n<p>For now, there are three main types of shaders. p5 will automatically\nsupply appropriate vertices, normals, colors, and lighting attributes\nif the parameters defined in the shader match the names.</p>\n","itemtype":"method","name":"loadShader","params":[{"name":"vertFilename","description":"<p>path to file containing vertex shader\nsource code</p>\n","type":"String","optional":true},{"name":"fragFilename","description":"<p>path to file containing fragment shader\nsource code</p>\n","type":"String","optional":true}],"return":{"description":"a shader object created from the provided\nvertex and fragment shader files.","type":"p5.Shader"},"example":["\n<div modernizr='webgl'>\n<code>\nvar mandel;\nfunction preload() {\n // load the shader definitions from files\n mandel = loadShader('assets/shader.vert', 'assets/shader.frag');\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n // use the shader\n shader(mandel);\n noStroke();\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n</code>\n</div>"],"alt":"zooming Mandelbrot set. a colorful, infinitely detailed fractal.","class":"p5","module":"Lights, Camera","submodule":"Material"},{"file":"src/webgl/material.js","line":83,"itemtype":"method","name":"createShader","params":[{"name":"vertSrc","description":"<p>source code for the vertex shader</p>\n","type":"String"},{"name":"fragSrc","description":"<p>source code for the fragment shader</p>\n","type":"String"}],"return":{"description":"a shader object created from the provided\nvertex and fragment shaders.","type":"p5.Shader"},"example":["\n<div modernizr='webgl'>\n<code>\n// the 'varying's are shared between both vertex & fragment shaders\nvar varying = 'precision highp float; varying vec2 vPos;';\n\n// the vertex shader is called for each vertex\nvar vs =\n varying +\n 'attribute vec3 aPosition;' +\n 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }';\n\n// the fragment shader is called for each pixel\nvar fs =\n varying +\n 'uniform vec2 p;' +\n 'uniform float r;' +\n 'const int I = 500;' +\n 'void main() {' +\n ' vec2 c = p + vPos * r, z = c;' +\n ' float n = 0.0;' +\n ' for (int i = I; i > 0; i --) {' +\n ' if(z.x*z.x+z.y*z.y > 4.0) {' +\n ' n = float(i)/float(I);' +\n ' break;' +\n ' }' +\n ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' +\n ' }' +\n ' gl_FragColor = vec4(0.5-cos(n*17.0)/2.0,0.5-cos(n*13.0)/2.0,0.5-cos(n*23.0)/2.0,1.0);' +\n '}';\n\nvar mandel;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n\n // create and initialize the shader\n mandel = createShader(vs, fs);\n shader(mandel);\n noStroke();\n\n // 'p' is the center point of the Mandelbrot image\n mandel.setUniform('p', [-0.74364388703, 0.13182590421]);\n}\n\nfunction draw() {\n // 'r' is the size of the image in Mandelbrot-space\n mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000))));\n quad(-1, -1, 1, -1, 1, 1, -1, 1);\n}\n</code>\n</div>"],"alt":"zooming Mandelbrot set. a colorful, infinitely detailed fractal.","class":"p5","module":"Lights, Camera","submodule":"Material"},{"file":"src/webgl/material.js","line":151,"description":"<p>The <a href=\"#/p5/shader\">shader()</a> function lets the user provide a custom shader\nto fill in shapes in WEBGL mode. Users can create their\nown shaders by loading vertex and fragment shaders with\n<a href=\"#/p5/loadShader\">loadShader()</a>.</p>\n","itemtype":"method","name":"shader","chainable":1,"params":[{"name":"s","description":"<p>the desired <a href=\"#/p5.Shader\">p5.Shader</a> to use for rendering\nshapes.</p>\n","type":"p5.Shader","optional":true}],"class":"p5","module":"Lights, Camera","submodule":"Material"},{"file":"src/webgl/material.js","line":176,"description":"<p>Normal material for geometry. You can view all\npossible materials in this\n<a href=\"https://p5js.org/examples/3d-materials.html\">example</a>.</p>\n","itemtype":"method","name":"normalMaterial","chainable":1,"example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(200);\n normalMaterial();\n sphere(50);\n}\n</code>\n</div>"],"alt":"Red, green and blue gradient.","class":"p5","module":"Lights, Camera","submodule":"Material"},{"file":"src/webgl/material.js","line":211,"description":"<p>Texture for geometry. You can view other possible materials in this\n<a href=\"https://p5js.org/examples/3d-materials.html\">example</a>.</p>\n","itemtype":"method","name":"texture","params":[{"name":"tex","description":"<p>2-dimensional graphics\n to render as texture</p>\n","type":"p5.Image|p5.MediaElement|p5.Graphics"}],"chainable":1,"example":["\n<div>\n<code>\nvar img;\nfunction preload() {\n img = loadImage('assets/laDefense.jpg');\n}\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n rotateZ(frameCount * 0.01);\n rotateX(frameCount * 0.01);\n rotateY(frameCount * 0.01);\n //pass image as texture\n texture(img);\n box(200, 200, 200);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar pg;\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n pg = createGraphics(200, 200);\n pg.textSize(100);\n}\n\nfunction draw() {\n background(0);\n pg.background(255);\n pg.text('hello!', 0, 100);\n //pass image as texture\n texture(pg);\n plane(200);\n}\n</code>\n</div>\n\n<div>\n<code>\nvar vid;\nfunction preload() {\n vid = createVideo('assets/fingers.mov');\n vid.hide();\n vid.loop();\n}\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(0);\n //pass video frame as texture\n texture(vid);\n plane(200);\n}\n</code>\n</div>"],"alt":"Rotating view of many images umbrella and grid roof on a 3d plane\nblack canvas\nblack canvas","class":"p5","module":"Lights, Camera","submodule":"Material"},{"file":"src/webgl/material.js","line":301,"description":"<p>Ambient material for geometry with a given color. You can view all\npossible materials in this\n<a href=\"https://p5js.org/examples/3d-materials.html\">example</a>.</p>\n","itemtype":"method","name":"ambientMaterial","chainable":1,"example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(100);\n pointLight(250, 250, 250, 100, 100, 0);\n ambientMaterial(250);\n sphere(50);\n}\n</code>\n</div>"],"alt":"radiating light source from top right of canvas","class":"p5","module":"Lights, Camera","submodule":"Material","overloads":[{"line":301,"params":[{"name":"v1","description":"<p>gray value, red or hue value\n (depending on the current color mode),</p>\n","type":"Number"},{"name":"v2","description":"<p>green or saturation value</p>\n","type":"Number","optional":true},{"name":"v3","description":"<p>blue or brightness value</p>\n","type":"Number","optional":true},{"name":"a","description":"<p>opacity</p>\n","type":"Number","optional":true}],"chainable":1},{"line":332,"params":[{"name":"color","description":"<p>color, color Array, or CSS color string</p>\n","type":"Number[]|String|p5.Color"}],"chainable":1}]},{"file":"src/webgl/material.js","line":350,"description":"<p>Specular material for geometry with a given color. You can view all\npossible materials in this\n<a href=\"https://p5js.org/examples/3d-materials.html\">example</a>.</p>\n","itemtype":"method","name":"specularMaterial","chainable":1,"example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(0);\n ambientLight(100);\n pointLight(250, 250, 250, 100, 100, 0);\n specularMaterial(250);\n sphere(50);\n}\n</code>\n</div>"],"alt":"diffused radiating light source from top right of canvas","class":"p5","module":"Lights, Camera","submodule":"Material","overloads":[{"line":350,"params":[{"name":"v1","description":"<p>gray value, red or hue value\n (depending on the current color mode),</p>\n","type":"Number"},{"name":"v2","description":"<p>green or saturation value</p>\n","type":"Number","optional":true},{"name":"v3","description":"<p>blue or brightness value</p>\n","type":"Number","optional":true},{"name":"a","description":"<p>opacity</p>\n","type":"Number","optional":true}],"chainable":1},{"line":381,"params":[{"name":"color","description":"<p>color Array, or CSS color string</p>\n","type":"Number[]|String|p5.Color"}],"chainable":1}]},{"file":"src/webgl/p5.Camera.js","line":15,"description":"<p>Sets the camera position for a 3D sketch. Parameters for this function define\nthe position for the camera, the center of the sketch (where the camera is\npointing), and an up direction (the orientation of the camera).</p>\n<p>When called with no arguments, this function creates a default camera\nequivalent to\ncamera(0, 0, (height/2.0) / tan(PI*30.0 / 180.0), 0, 0, 0, 0, 1, 0);</p>\n","itemtype":"method","name":"camera","params":[{"name":"x","description":"<p>camera position value on x axis</p>\n","type":"Number","optional":true},{"name":"y","description":"<p>camera position value on y axis</p>\n","type":"Number","optional":true},{"name":"z","description":"<p>camera position value on z axis</p>\n","type":"Number","optional":true},{"name":"centerX","description":"<p>x coordinate representing center of the sketch</p>\n","type":"Number","optional":true},{"name":"centerY","description":"<p>y coordinate representing center of the sketch</p>\n","type":"Number","optional":true},{"name":"centerZ","description":"<p>z coordinate representing center of the sketch</p>\n","type":"Number","optional":true},{"name":"upX","description":"<p>x component of direction &#39;up&#39; from camera</p>\n","type":"Number","optional":true},{"name":"upY","description":"<p>y component of direction &#39;up&#39; from camera</p>\n","type":"Number","optional":true},{"name":"upZ","description":"<p>z component of direction &#39;up&#39; from camera</p>\n","type":"Number","optional":true}],"chainable":1,"example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\nfunction draw() {\n background(204);\n //move the camera away from the plane by a sin wave\n camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0);\n plane(10, 10);\n}\n</code>\n</div>"],"alt":"White square repeatedly grows to fill canvas and then shrinks.","class":"p5","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":61,"description":"<p>Sets a perspective projection for the camera in a 3D sketch. This projection\nrepresents depth through foreshortening: objects that are close to the camera\nappear their actual size while those that are further away from the camera\nappear smaller. The parameters to this function define the viewing frustum\n(the truncated pyramid within which objects are seen by the camera) through\nvertical field of view, aspect ratio (usually width/height), and near and far\nclipping planes.</p>\n<p>When called with no arguments, the defaults\nprovided are equivalent to\nperspective(PI/3.0, width/height, eyeZ/10.0, eyeZ<em>10.0), where eyeZ\nis equal to ((height/2.0) / tan(PI</em>60.0/360.0));</p>\n","itemtype":"method","name":"perspective","params":[{"name":"fovy","description":"<p>camera frustum vertical field of view,\n from bottom to top of view, in <a href=\"#/p5/angleMode\">angleMode</a> units</p>\n","type":"Number","optional":true},{"name":"aspect","description":"<p>camera frustum aspect ratio</p>\n","type":"Number","optional":true},{"name":"near","description":"<p>frustum near plane length</p>\n","type":"Number","optional":true},{"name":"far","description":"<p>frustum far plane length</p>\n","type":"Number","optional":true}],"chainable":1,"example":["\n<div>\n<code>\n//drag the mouse to look around!\n//you will see there's a vanishing point\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n perspective(PI / 3.0, width / height, 0.1, 500);\n}\nfunction draw() {\n background(200);\n orbitControl();\n normalMaterial();\n\n rotateX(-0.3);\n rotateY(-0.2);\n translate(0, 0, -50);\n\n push();\n translate(-15, 0, sin(frameCount / 30) * 95);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 95);\n box(30);\n pop();\n}\n</code>\n</div>"],"alt":"two colored 3D boxes move back and forth, rotating as mouse is dragged.","class":"p5","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":126,"description":"<p>Sets an orthographic projection for the camera in a 3D sketch and defines a\nbox-shaped viewing frustum within which objects are seen. In this projection,\nall objects with the same dimension appear the same size, regardless of\nwhether they are near or far from the camera. The parameters to this\nfunction specify the viewing frustum where left and right are the minimum and\nmaximum x values, top and bottom are the minimum and maximum y values, and near\nand far are the minimum and maximum z values. If no parameters are given, the\ndefault is used: ortho(-width/2, width/2, -height/2, height/2).</p>\n","itemtype":"method","name":"ortho","params":[{"name":"left","description":"<p>camera frustum left plane</p>\n","type":"Number","optional":true},{"name":"right","description":"<p>camera frustum right plane</p>\n","type":"Number","optional":true},{"name":"bottom","description":"<p>camera frustum bottom plane</p>\n","type":"Number","optional":true},{"name":"top","description":"<p>camera frustum top plane</p>\n","type":"Number","optional":true},{"name":"near","description":"<p>camera frustum near plane</p>\n","type":"Number","optional":true},{"name":"far","description":"<p>camera frustum far plane</p>\n","type":"Number","optional":true}],"chainable":1,"example":["\n<div>\n<code>\n//drag the mouse to look around!\n//there's no vanishing point\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n ortho(-width / 2, width / 2, height / 2, -height / 2, 0, 500);\n}\nfunction draw() {\n background(200);\n orbitControl();\n normalMaterial();\n\n rotateX(0.2);\n rotateY(-0.2);\n push();\n translate(-15, 0, sin(frameCount / 30) * 65);\n box(30);\n pop();\n push();\n translate(15, 0, sin(frameCount / 30 + PI) * 65);\n box(30);\n pop();\n}\n</code>\n</div>"],"alt":"two 3D boxes move back and forth along same plane, rotating as mouse is dragged.","class":"p5","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":187,"description":"<p>Creates a new <a href=\"#/p5.Camera\">p5.Camera</a> object and tells the\nrenderer to use that camera.\nReturns the p5.Camera object.</p>\n","itemtype":"method","name":"createCamera","return":{"description":"The newly created camera object.","type":"p5.Camera"},"class":"p5","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":298,"description":"<p>Sets a perspective projection for a p5.Camera object and sets parameters\nfor that projection according to <a href=\"#/p5/perspective\">perspective()</a>\nsyntax.</p>\n","itemtype":"method","name":"perspective","class":"p5.Camera","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":380,"description":"<p>Sets an orthographic projection for a p5.Camera object and sets parameters\nfor that projection according to <a href=\"#/p5/ortho\">ortho()</a> syntax.</p>\n","itemtype":"method","name":"ortho","class":"p5.Camera","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":487,"description":"<p>Panning rotates the camera view to the left and right.</p>\n","itemtype":"method","name":"pan","params":[{"name":"angle","description":"<p>amount to rotate camera in current\n<a href=\"#/p5/angleMode\">angleMode</a> units.\nGreater than 0 values rotate counterclockwise (to the left).</p>\n","type":"Number"}],"example":["\n<div>\n<code>\nvar cam;\nvar delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial pan angle\n cam.pan(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.pan(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n</code>\n</div>"],"alt":"camera view pans left and right across a series of rotating 3D boxes.","class":"p5.Camera","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":546,"description":"<p>Tilting rotates the camera view up and down.</p>\n","itemtype":"method","name":"tilt","params":[{"name":"angle","description":"<p>amount to rotate camera in current\n<a href=\"#/p5/angleMode\">angleMode</a> units.\nGreater than 0 values rotate counterclockwise (to the left).</p>\n","type":"Number"}],"example":["\n<div>\n<code>\nvar cam;\nvar delta = 0.01;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n // set initial tilt\n cam.tilt(-0.8);\n}\n\nfunction draw() {\n background(200);\n\n // pan camera according to angle 'delta'\n cam.tilt(delta);\n\n // every 160 frames, switch direction\n if (frameCount % 160 === 0) {\n delta *= -1;\n }\n\n rotateY(frameCount * 0.01);\n translate(0, -100, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n translate(0, 35, 0);\n box(20);\n}\n</code>\n</div>"],"alt":"camera view tilts up and down across a series of rotating 3D boxes.","class":"p5.Camera","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":604,"description":"<p>Reorients the camera to look at a position in world space.</p>\n","itemtype":"method","name":"lookAt","params":[{"name":"x","description":"<p>x position of a point in world space</p>\n","type":"Number"},{"name":"y","description":"<p>y position of a point in world space</p>\n","type":"Number"},{"name":"z","description":"<p>z position of a point in world space</p>\n","type":"Number"}],"example":["\n<div>\n<code>\nvar cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // look at a new random point every 60 frames\n if (frameCount % 60 === 0) {\n cam.lookAt(random(-100, 100), random(-50, 50), 0);\n }\n\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n</code>\n</div>"],"alt":"camera view of rotating 3D cubes changes to look at a new random\npoint every second .","class":"p5.Camera","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":671,"description":"<p>Sets a camera&#39;s position and orientation. This is equivalent to calling\n<a href=\"#/p5/camera\">camera()</a> on a p5.Camera object.</p>\n","itemtype":"method","name":"camera","class":"p5.Camera","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":752,"description":"<p>Move camera along its local axes while maintaining current camera orientation.</p>\n","itemtype":"method","name":"move","params":[{"name":"x","description":"<p>amount to move along camera&#39;s left-right axis</p>\n","type":"Number"},{"name":"y","description":"<p>amount to move along camera&#39;s up-down axis</p>\n","type":"Number"},{"name":"z","description":"<p>amount to move along camera&#39;s forward-backward axis</p>\n","type":"Number"}],"example":["\n<div>\n<code>\n// see the camera move along its own axes while maintaining its orientation\nvar cam;\nvar delta = 0.5;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // move the camera along its local axes\n cam.move(delta, delta, 0);\n\n // every 100 frames, switch direction\n if (frameCount % 150 === 0) {\n delta *= -1;\n }\n\n translate(-10, -10, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n translate(15, 15, 0);\n box(50, 8, 50);\n}\n</code>\n</div>"],"alt":"camera view moves along a series of 3D boxes, maintaining the same\norientation throughout the move","class":"p5.Camera","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":824,"description":"<p>Set camera position in world-space while maintaining current camera\norientation.</p>\n","itemtype":"method","name":"setPosition","params":[{"name":"x","description":"<p>x position of a point in world space</p>\n","type":"Number"},{"name":"y","description":"<p>y position of a point in world space</p>\n","type":"Number"},{"name":"z","description":"<p>z position of a point in world space</p>\n","type":"Number"}],"example":["\n<div>\n<code>\n// press '1' '2' or '3' keys to set camera position\n\nvar cam;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n cam = createCamera();\n}\n\nfunction draw() {\n background(200);\n\n // '1' key\n if (keyIsDown(49)) {\n cam.setPosition(30, 0, 80);\n }\n // '2' key\n if (keyIsDown(50)) {\n cam.setPosition(0, 0, 80);\n }\n // '3' key\n if (keyIsDown(51)) {\n cam.setPosition(-30, 0, 80);\n }\n\n box(20);\n}\n</code>\n</div>"],"alt":"camera position changes as the user presses keys, altering view of a 3D box","class":"p5.Camera","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Camera.js","line":1089,"description":"<p>Sets rendererGL&#39;s current camera to a p5.Camera object. Allows switching\nbetween multiple cameras.</p>\n","itemtype":"method","name":"setCamera","params":[{"name":"cam","description":"<p>p5.Camera object</p>\n","type":"p5.Camera"}],"example":["\n<div>\n<code>\nvar cam1, cam2;\nvar currentCamera;\n\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n normalMaterial();\n\n cam1 = createCamera();\n cam2 = createCamera();\n cam2.setPosition(30, 0, 50);\n cam2.lookAt(0, 0, 0);\n cam2.ortho();\n\n // set variable for previously active camera:\n currentCamera = 1;\n}\n\nfunction draw() {\n background(200);\n\n // camera 1:\n cam1.lookAt(0, 0, 0);\n cam1.setPosition(sin(frameCount / 60) * 200, 0, 100);\n\n // every 100 frames, switch between the two cameras\n if (frameCount % 100 === 0) {\n if (currentCamera === 1) {\n setCamera(cam1);\n currentCamera = 0;\n } else {\n setCamera(cam2);\n currentCamera = 1;\n }\n }\n\n drawBoxes();\n}\n\nfunction drawBoxes() {\n rotateX(frameCount * 0.01);\n translate(-100, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n translate(35, 0, 0);\n box(20);\n}\n</code>\n</div>"],"alt":"Canvas switches between two camera views, each showing a series of spinning\n3D boxes.","class":"p5","module":"Lights, Camera","submodule":"Camera"},{"file":"src/webgl/p5.Geometry.js","line":50,"itemtype":"method","name":"computeFaces","chainable":1,"class":"p5.Geometry","module":"Lights, Camera"},{"file":"src/webgl/p5.Geometry.js","line":92,"description":"<p>computes smooth normals per vertex as an average of each\nface.</p>\n","itemtype":"method","name":"computeNormals","chainable":1,"class":"p5.Geometry","module":"Lights, Camera"},{"file":"src/webgl/p5.Geometry.js","line":131,"description":"<p>Averages the vertex normals. Used in curved\nsurfaces</p>\n","itemtype":"method","name":"averageNormals","chainable":1,"class":"p5.Geometry","module":"Lights, Camera"},{"file":"src/webgl/p5.Geometry.js","line":152,"description":"<p>Averages pole normals. Used in spherical primitives</p>\n","itemtype":"method","name":"averagePoleNormals","chainable":1,"class":"p5.Geometry","module":"Lights, Camera"},{"file":"src/webgl/p5.Geometry.js","line":245,"description":"<p>Modifies all vertices to be centered within the range -100 to 100.</p>\n","itemtype":"method","name":"normalize","chainable":1,"class":"p5.Geometry","module":"Lights, Camera"},{"file":"src/webgl/p5.RendererGL.js","line":215,"description":"<p>Set attributes for the WebGL Drawing context.\nThis is a way of adjusting ways that the WebGL\nrenderer works to fine-tune the display and performance.\nThis should be put in setup().\nThe available attributes are:\n<br>\nalpha - indicates if the canvas contains an alpha buffer\ndefault is true\n<br><br>\ndepth - indicates whether the drawing buffer has a depth buffer\nof at least 16 bits - default is true\n<br><br>\nstencil - indicates whether the drawing buffer has a stencil buffer\nof at least 8 bits\n<br><br>\nantialias - indicates whether or not to perform anti-aliasing\ndefault is false\n<br><br>\npremultipliedAlpha - indicates that the page compositor will assume\nthe drawing buffer contains colors with pre-multiplied alpha\ndefault is false\n<br><br>\npreserveDrawingBuffer - if true the buffers will not be cleared and\nand will preserve their values until cleared or overwritten by author\n(note that p5 clears automatically on draw loop)\ndefault is true\n<br><br>\nperPixelLighting - if true, per-pixel lighting will be used in the\nlighting shader.\ndefault is false\n<br><br></p>\n","itemtype":"method","name":"setAttributes","example":["\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n</code>\n</div>\n<br>\nNow with the antialias attribute set to true.\n<br>\n<div>\n<code>\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n setAttributes('antialias', true);\n}\n\nfunction draw() {\n background(255);\n push();\n rotateZ(frameCount * 0.02);\n rotateX(frameCount * 0.02);\n rotateY(frameCount * 0.02);\n fill(0, 0, 0);\n box(50);\n pop();\n}\n</code>\n</div>\n\n<div>\n<code>\n// press the mouse button to enable perPixelLighting\nfunction setup() {\n createCanvas(100, 100, WEBGL);\n noStroke();\n fill(255);\n}\n\nvar lights = [\n { c: '#f00', t: 1.12, p: 1.91, r: 0.2 },\n { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 },\n { c: '#00f', t: 1.37, p: 1.57, r: 0.2 },\n { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 },\n { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 },\n { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 }\n];\n\nfunction draw() {\n var t = millis() / 1000 + 1000;\n background(0);\n directionalLight(color('#222'), 1, 1, 1);\n\n for (var i = 0; i < lights.length; i++) {\n var light = lights[i];\n pointLight(\n color(light.c),\n p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r)\n );\n }\n\n specularMaterial(255);\n sphere(width * 0.1);\n\n rotateX(t * 0.77);\n rotateY(t * 0.83);\n rotateZ(t * 0.91);\n torus(width * 0.3, width * 0.07, 30, 10);\n}\n\nfunction mousePressed() {\n setAttributes('perPixelLighting', true);\n noStroke();\n fill(255);\n}\nfunction mouseReleased() {\n setAttributes('perPixelLighting', false);\n noStroke();\n fill(255);\n}\n</code>\n</div>"],"alt":"a rotating cube with smoother edges","class":"p5","module":"Rendering","submodule":"Rendering","overloads":[{"line":215,"params":[{"name":"key","description":"<p>Name of attribute</p>\n","type":"String"},{"name":"value","description":"<p>New value of named attribute</p>\n","type":"Boolean"}]},{"line":348,"params":[{"name":"obj","description":"<p>object with key-value pairs</p>\n","type":"Object"}]}]},{"file":"src/webgl/p5.Shader.js","line":274,"description":"<p>Wrapper around gl.uniform functions.\nAs we store uniform info in the shader we can use that\nto do type checking on the supplied data and call\nthe appropriate function.</p>\n","itemtype":"method","name":"setUniform","chainable":1,"params":[{"name":"uniformName","description":"<p>the name of the uniform in the\nshader program</p>\n","type":"String"},{"name":"data","description":"<p>the data to be associated\nwith that uniform; type varies (could be a single numerical value, array,\nmatrix, or texture / sampler reference)</p>\n","type":"Object|Number|Boolean|Number[]"}],"class":"p5.Shader","module":"Lights, Camera","submodule":"Shaders"},{"file":"lib/addons/p5.dom.js","line":40,"description":"<p>Searches the page for an element with the given ID, class, or tag name (using the &#39;#&#39; or &#39;.&#39;\nprefixes to specify an ID or class respectively, and none for a tag) and returns it as\na <a href=\"#/p5.Element\">p5.Element</a>. If a class or tag name is given with more than 1 element,\nonly the first element will be returned.\nThe DOM node itself can be accessed with .elt.\nReturns null if none found. You can also specify a container to search within.</p>\n","itemtype":"method","name":"select","params":[{"name":"name","description":"<p>id, class, or tag name of element to search for</p>\n","type":"String"},{"name":"container","description":"<p>id, <a href=\"#/p5.Element\">p5.Element</a>, or\n HTML element to search within</p>\n","type":"String|p5.Element|HTMLElement","optional":true}],"return":{"description":"<a href=\"#/p5.Element\">p5.Element</a> containing node found","type":"p5.Element|null"},"example":["\n<div ><code class='norender'>\nfunction setup() {\n createCanvas(100, 100);\n //translates canvas 50px down\n select('canvas').position(100, 100);\n}\n</code></div>\n<div><code class='norender'>\n// these are all valid calls to select()\nvar a = select('#moo');\nvar b = select('#blah', '#myContainer');\nvar c, e;\nif (b) {\n c = select('#foo', b);\n}\nvar d = document.getElementById('beep');\nif (d) {\n e = select('p', d);\n}\n[a, b, c, d, e]; // unused\n</code></div>\n"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":107,"description":"<p>Searches the page for elements with the given class or tag name (using the &#39;.&#39; prefix\nto specify a class and no prefix for a tag) and returns them as <a href=\"#/p5.Element\">p5.Element</a>s\nin an array.\nThe DOM node itself can be accessed with .elt.\nReturns an empty array if none found.\nYou can also specify a container to search within.</p>\n","itemtype":"method","name":"selectAll","params":[{"name":"name","description":"<p>class or tag name of elements to search for</p>\n","type":"String"},{"name":"container","description":"<p>id, <a href=\"#/p5.Element\">p5.Element</a>, or HTML element to search within</p>\n","type":"String","optional":true}],"return":{"description":"Array of <a href=\"#/p5.Element\">p5.Element</a>s containing nodes found","type":"p5.Element[]"},"example":["\n<div class='norender'><code>\nfunction setup() {\n createButton('btn');\n createButton('2nd btn');\n createButton('3rd btn');\n var buttons = selectAll('button');\n\n for (var i = 0; i < buttons.length; i++) {\n buttons[i].size(100, 100);\n }\n}\n</code></div>\n<div class='norender'><code>\n// these are all valid calls to selectAll()\nvar a = selectAll('.moo');\na = selectAll('div');\na = selectAll('button', '#myContainer');\n\nvar d = select('#container');\na = selectAll('p', d);\n\nvar f = document.getElementById('beep');\na = select('.blah', f);\n\na; // unused\n</code></div>\n"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":168,"description":"<p>Helper function for select and selectAll</p>\n","class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":184,"description":"<p>Helper function for getElement and getElements.</p>\n","class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":218,"description":"<p>Removes all elements created by p5, except any canvas / graphics\nelements created by <a href=\"#/p5/createCanvas\">createCanvas</a> or <a href=\"#/p5/createGraphics\">createGraphics</a>.\nEvent handlers are removed, and element is removed from the DOM.</p>\n","itemtype":"method","name":"removeElements","example":["\n<div class='norender'><code>\nfunction setup() {\n createCanvas(100, 100);\n createDiv('this is some text');\n createP('this is a paragraph');\n}\nfunction mousePressed() {\n removeElements(); // this will remove the div and p, not canvas\n}\n</code></div>\n"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":245,"description":"<p>Helpers for create methods.</p>\n","class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":258,"description":"<p>Creates a &lt;div&gt;&lt;/div&gt; element in the DOM with given inner HTML.\nAppends to the container node if one is specified, otherwise\nappends to body.</p>\n","itemtype":"method","name":"createDiv","params":[{"name":"html","description":"<p>inner HTML for element created</p>\n","type":"String","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div class='norender'><code>\ncreateDiv('this is some text');\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":272,"description":"<p>Creates a &lt;p&gt;&lt;/p&gt; element in the DOM with given inner HTML. Used\nfor paragraph length text.\nAppends to the container node if one is specified, otherwise\nappends to body.</p>\n","itemtype":"method","name":"createP","params":[{"name":"html","description":"<p>inner HTML for element created</p>\n","type":"String","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div class='norender'><code>\ncreateP('this is some text');\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":287,"description":"<p>Creates a &lt;span&gt;&lt;/span&gt; element in the DOM with given inner HTML.\nAppends to the container node if one is specified, otherwise\nappends to body.</p>\n","itemtype":"method","name":"createSpan","params":[{"name":"html","description":"<p>inner HTML for element created</p>\n","type":"String","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div class='norender'><code>\ncreateSpan('this is some text');\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":310,"description":"<p>Creates an &lt;img&gt; element in the DOM with given src and\nalternate text.\nAppends to the container node if one is specified, otherwise\nappends to body.</p>\n","itemtype":"method","name":"createImg","return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div class='norender'><code>\ncreateImg('http://p5js.org/img/asterisk-01.png');\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":310,"params":[{"name":"src","description":"<p>src path or url for image</p>\n","type":"String"},{"name":"alt","description":"<p>alternate text to be used if image does not load</p>\n","type":"String","optional":true},{"name":"successCallback","description":"<p>callback to be called once image data is loaded</p>\n","type":"Function","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"}},{"line":326,"params":[{"name":"src","description":"","type":"String"},{"name":"successCallback","description":"","type":"Function"}],"return":{"description":"","type":"Object|p5.Element"}}]},{"file":"lib/addons/p5.dom.js","line":359,"description":"<p>Creates an &lt;a&gt;&lt;/a&gt; element in the DOM for including a hyperlink.\nAppends to the container node if one is specified, otherwise\nappends to body.</p>\n","itemtype":"method","name":"createA","params":[{"name":"href","description":"<p>url of page to link to</p>\n","type":"String"},{"name":"html","description":"<p>inner html of link element to display</p>\n","type":"String"},{"name":"target","description":"<p>target where new link should open,\n could be _blank, _self, _parent, _top.</p>\n","type":"String","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div class='norender'><code>\ncreateA('http://p5js.org/', 'this is a link');\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":384,"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":386,"description":"<p>Creates a slider &lt;input&gt;&lt;/input&gt; element in the DOM.\nUse .size() to set the display length of the slider.\nAppends to the container node if one is specified, otherwise\nappends to body.</p>\n","itemtype":"method","name":"createSlider","params":[{"name":"min","description":"<p>minimum value of the slider</p>\n","type":"Number"},{"name":"max","description":"<p>maximum value of the slider</p>\n","type":"Number"},{"name":"value","description":"<p>default value of the slider</p>\n","type":"Number","optional":true},{"name":"step","description":"<p>step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value)</p>\n","type":"Number","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div><code>\nvar slider;\nfunction setup() {\n slider = createSlider(0, 255, 100);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n var val = slider.value();\n background(val);\n}\n</code></div>\n\n<div><code>\nvar slider;\nfunction setup() {\n colorMode(HSB);\n slider = createSlider(0, 360, 60, 40);\n slider.position(10, 10);\n slider.style('width', '80px');\n}\n\nfunction draw() {\n var val = slider.value();\n background(val, 100, 100, 1);\n}\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":443,"description":"<p>Creates a &lt;button&gt;&lt;/button&gt; element in the DOM.\nUse .size() to set the display size of the button.\nUse .mousePressed() to specify behavior on press.\nAppends to the container node if one is specified, otherwise\nappends to body.</p>\n","itemtype":"method","name":"createButton","params":[{"name":"label","description":"<p>label displayed on the button</p>\n","type":"String"},{"name":"value","description":"<p>value of the button</p>\n","type":"String","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div class='norender'><code>\nvar button;\nfunction setup() {\n createCanvas(100, 100);\n background(0);\n button = createButton('click me');\n button.position(19, 19);\n button.mousePressed(changeBG);\n}\n\nfunction changeBG() {\n var val = random(255);\n background(val);\n}\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":479,"description":"<p>Creates a checkbox &lt;input&gt;&lt;/input&gt; element in the DOM.\nCalling .checked() on a checkbox returns if it is checked or not</p>\n","itemtype":"method","name":"createCheckbox","params":[{"name":"label","description":"<p>label displayed after checkbox</p>\n","type":"String","optional":true},{"name":"value","description":"<p>value of the checkbox; checked is true, unchecked is false</p>\n","type":"Boolean","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div class='norender'><code>\nvar checkbox;\n\nfunction setup() {\n checkbox = createCheckbox('label', false);\n checkbox.changed(myCheckedEvent);\n}\n\nfunction myCheckedEvent() {\n if (this.checked()) {\n console.log('Checking!');\n } else {\n console.log('Unchecking!');\n }\n}\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":547,"description":"<p>Creates a dropdown menu &lt;select&gt;&lt;/select&gt; element in the DOM.\nIt also helps to assign select-box methods to <a href=\"#/p5.Element\">p5.Element</a> when selecting existing select box</p>\n","itemtype":"method","name":"createSelect","return":{"description":"","type":"p5.Element"},"example":["\n<div><code>\nvar sel;\n\nfunction setup() {\n textAlign(CENTER);\n background(200);\n sel = createSelect();\n sel.position(10, 10);\n sel.option('pear');\n sel.option('kiwi');\n sel.option('grape');\n sel.changed(mySelectEvent);\n}\n\nfunction mySelectEvent() {\n var item = sel.value();\n background(200);\n text('it is a' + item + '!', 50, 50);\n}\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":547,"params":[{"name":"multiple","description":"<p>true if dropdown should support multiple selections</p>\n","type":"Boolean","optional":true}],"return":{"description":"","type":"p5.Element"}},{"line":575,"params":[{"name":"existing","description":"<p>DOM select element</p>\n","type":"Object"}],"return":{"description":"","type":"p5.Element"}}]},{"file":"lib/addons/p5.dom.js","line":651,"description":"<p>Creates a radio button &lt;input&gt;&lt;/input&gt; element in the DOM.\nThe .option() method can be used to set options for the radio after it is\ncreated. The .value() method will return the currently selected option.</p>\n","itemtype":"method","name":"createRadio","params":[{"name":"divId","description":"<p>the id and name of the created div and input field respectively</p>\n","type":"String","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div><code>\nvar radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option('black');\n radio.option('white');\n radio.option('gray');\n radio.style('width', '60px');\n textAlign(CENTER);\n fill(255, 0, 0);\n}\n\nfunction draw() {\n var val = radio.value();\n background(val);\n text(val, width / 2, height / 2);\n}\n</code></div>\n<div><code>\nvar radio;\n\nfunction setup() {\n radio = createRadio();\n radio.option('apple', 1);\n radio.option('bread', 2);\n radio.option('juice', 3);\n radio.style('width', '60px');\n textAlign(CENTER);\n}\n\nfunction draw() {\n background(200);\n var val = radio.value();\n if (val) {\n text('item cost is $' + val, width / 2, height / 2);\n }\n}\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":789,"description":"<p>Creates a colorPicker element in the DOM for color input.\nThe .value() method will return a hex string (#rrggbb) of the color.\nThe .color() method will return a p5.Color object with the current chosen color.</p>\n","itemtype":"method","name":"createColorPicker","params":[{"name":"value","description":"<p>default color of element</p>\n","type":"String|p5.Color","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div>\n<code>\nvar inp1, inp2;\nfunction setup() {\n createCanvas(100, 100);\n background('grey');\n inp1 = createColorPicker('#ff0000');\n inp2 = createColorPicker(color('yellow'));\n inp1.input(setShade1);\n inp2.input(setShade2);\n setMidShade();\n}\n\nfunction setMidShade() {\n // Finding a shade between the two\n var commonShade = lerpColor(inp1.color(), inp2.color(), 0.5);\n fill(commonShade);\n rect(20, 20, 60, 60);\n}\n\nfunction setShade1() {\n setMidShade();\n console.log('You are choosing shade 1 to be : ', this.value());\n}\nfunction setShade2() {\n setMidShade();\n console.log('You are choosing shade 2 to be : ', this.value());\n}\n</code>\n</div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":863,"description":"<p>Creates an &lt;input&gt;&lt;/input&gt; element in the DOM for text input.\nUse .<a href=\"#/p5.Element/size\">size()</a> to set the display length of the box.\nAppends to the container node if one is specified, otherwise\nappends to body.</p>\n","itemtype":"method","name":"createInput","params":[{"name":"value","description":"<p>default value of the input box</p>\n","type":"String","optional":true},{"name":"type","description":"<p>type of text, ie text, password etc. Defaults to text</p>\n","type":"String","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div class='norender'><code>\nfunction setup() {\n var inp = createInput('');\n inp.input(myInputEvent);\n}\n\nfunction myInputEvent() {\n console.log('you are typing: ', this.value());\n}\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":893,"description":"<p>Creates an &lt;input&gt;&lt;/input&gt; element in the DOM of type &#39;file&#39;.\nThis allows users to select local files for use in a sketch.</p>\n","itemtype":"method","name":"createFileInput","params":[{"name":"callback","description":"<p>callback function for when a file loaded</p>\n","type":"Function","optional":true},{"name":"multiple","description":"<p>optional to allow multiple files selected</p>\n","type":"String","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created DOM element","type":"p5.Element"},"example":["\n<div class='norender'><code>\nvar input;\nvar img;\n\nfunction setup() {\n input = createFileInput(handleFile);\n input.position(0, 0);\n}\n\nfunction draw() {\n if (img) {\n image(img, 0, 0, width, height);\n }\n}\n\nfunction handleFile(file) {\n print(file);\n if (file.type === 'image') {\n img = createImg(file.data);\n img.hide();\n }\n}\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":981,"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1023,"description":"<p>Creates an HTML5 &lt;video&gt; element in the DOM for simple playback\nof audio/video. Shown by default, can be hidden with .<a href=\"#/p5.Element/hide\">hide()</a>\nand drawn into canvas using video(). Appends to the container\nnode if one is specified, otherwise appends to body. The first parameter\ncan be either a single string path to a video file, or an array of string\npaths to different formats of the same video. This is useful for ensuring\nthat your video can play across different browsers, as each supports\ndifferent formats. See <a href='https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats'>this\npage</a> for further information about supported formats.</p>\n","itemtype":"method","name":"createVideo","params":[{"name":"src","description":"<p>path to a video file, or array of paths for\n supporting different browsers</p>\n","type":"String|String[]"},{"name":"callback","description":"<p>callback function to be called upon\n &#39;canplaythrough&#39; event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content</p>\n","type":"Function","optional":true}],"return":{"description":"pointer to video <a href=\"#/p5.Element\">p5.Element</a>","type":"p5.MediaElement"},"example":["\n<div><code>\nvar vid;\nfunction setup() {\n vid = createVideo(['small.mp4', 'small.ogv', 'small.webm'], vidLoad);\n}\n\n// This function is called when the video loads\nfunction vidLoad() {\n vid.play();\n}\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1062,"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1064,"description":"<p>Creates a hidden HTML5 &lt;audio&gt; element in the DOM for simple audio\nplayback. Appends to the container node if one is specified,\notherwise appends to body. The first parameter\ncan be either a single string path to a audio file, or an array of string\npaths to different formats of the same audio. This is useful for ensuring\nthat your audio can play across different browsers, as each supports\ndifferent formats. See <a href='https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats'>this\npage for further information about supported formats</a>.</p>\n","itemtype":"method","name":"createAudio","params":[{"name":"src","description":"<p>path to an audio file, or array of paths\n for supporting different browsers</p>\n","type":"String|String[]","optional":true},{"name":"callback","description":"<p>callback function to be called upon\n &#39;canplaythrough&#39; event fire, that is, when the\n browser can play the media, and estimates that\n enough data has been loaded to play the media\n up to its end without having to stop for\n further buffering of content</p>\n","type":"Function","optional":true}],"return":{"description":"pointer to audio <a href=\"#/p5.Element\">p5.Element</a>","type":"p5.MediaElement"},"example":["\n<div><code>\nvar ele;\nfunction setup() {\n ele = createAudio('assets/beat.mp3');\n\n // here we set the element to autoplay\n // The element will play as soon\n // as it is able to do so.\n ele.autoplay(true);\n}\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1102,"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1104,"itemtype":"property","name":"VIDEO","type":"String","final":1,"category":["Constants"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1110,"itemtype":"property","name":"AUDIO","type":"String","final":1,"category":["Constants"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1147,"description":"<p>Creates a new HTML5 &lt;video&gt; element that contains the audio/video\nfeed from a webcam. The element is separate from the canvas and is\ndisplayed by default. The element can be hidden using .<a href=\"#/p5.Element/hide\">hide()</a>. The feed\ncan be drawn onto the canvas using <a href=\"#/p5/image\">image()</a>. The loadedmetadata property can\nbe used to detect when the element has fully loaded (see second example).</p>\n<p>More specific properties of the feed can be passing in a Constraints object.\nSee the\n<a href='http://w3c.github.io/mediacapture-main/getusermedia.html#media-track-constraints'> W3C\nspec</a> for possible properties. Note that not all of these are supported\nby all browsers.</p>\n<p>Security note: A new browser security specification requires that getUserMedia,\nwhich is behind <a href=\"#/p5/createCapture\">createCapture()</a>, only works when you&#39;re running the code locally,\nor on HTTPS. Learn more <a href='http://stackoverflow.com/questions/34197653/getusermedia-in-chrome-47-without-using-https'>here</a>\nand <a href='https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia'>here</a>.</p>","itemtype":"method","name":"createCapture","params":[{"name":"type","description":"<p>type of capture, either VIDEO or\n AUDIO if none specified, default both,\n or a Constraints object</p>\n","type":"String|Constant|Object"},{"name":"callback","description":"<p>function to be called once\n stream has loaded</p>\n","type":"Function","optional":true}],"return":{"description":"capture video <a href=\"#/p5.Element\">p5.Element</a>","type":"p5.Element"},"example":["\n<div class='norender notest'><code>\nvar capture;\n\nfunction setup() {\n createCanvas(480, 480);\n capture = createCapture(VIDEO);\n capture.hide();\n}\n\nfunction draw() {\n image(capture, 0, 0, width, width * capture.height / capture.width);\n filter(INVERT);\n}\n</code></div>\n<div class='norender notest'><code>\nfunction setup() {\n createCanvas(480, 120);\n var constraints = {\n video: {\n mandatory: {\n minWidth: 1280,\n minHeight: 720\n },\n optional: [{ maxFrameRate: 10 }]\n },\n audio: true\n };\n createCapture(constraints, function(stream) {\n console.log(stream);\n });\n}\n</code></div>\n<code><div class='norender notest'>\nvar capture;\n\nfunction setup() {\n createCanvas(640, 480);\n capture = createCapture(VIDEO);\n}\nfunction draw() {\n background(0);\n if (capture.loadedmetadata) {\n var c = capture.get(0, 0, 100, 100);\n image(c, 0, 0);\n }\n}"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1283,"description":"<p>Creates element with given tag in the DOM with given content.\nAppends to the container node if one is specified, otherwise\nappends to body.</p>\n","itemtype":"method","name":"createElement","params":[{"name":"tag","description":"<p>tag for the new element</p>\n","type":"String"},{"name":"content","description":"<p>html content to be inserted into the element</p>\n","type":"String","optional":true}],"return":{"description":"pointer to <a href=\"#/p5.Element\">p5.Element</a> holding created node","type":"p5.Element"},"example":["\n<div class='norender'><code>\ncreateElement('h2', 'im an h2 p5.element!');\n</code></div>"],"class":"p5","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1309,"description":"<p>Adds specified class to the element.</p>\n","itemtype":"method","name":"addClass","params":[{"name":"class","description":"<p>name of class to add</p>\n","type":"String"}],"chainable":1,"example":["\n <div class='norender'><code>\n var div = createDiv('div');\n div.addClass('myClass');\n </code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1336,"description":"<p>Removes specified class from the element.</p>\n","itemtype":"method","name":"removeClass","params":[{"name":"class","description":"<p>name of class to remove</p>\n","type":"String"}],"chainable":1,"example":["\n <div class='norender'><code>\n // In this example, a class is set when the div is created\n // and removed when mouse is pressed. This could link up\n // with a CSS style rule to toggle style properties.\nvar div;\nfunction setup() {\n div = createDiv('div');\n div.addClass('myClass');\n }\nfunction mousePressed() {\n div.removeClass('myClass');\n }\n </code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1368,"description":"<p>Attaches the element as a child to the parent specified.\n Accepts either a string ID, DOM node, or <a href=\"#/p5.Element\">p5.Element</a>.\n If no argument is specified, an array of children DOM nodes is returned.</p>\n","itemtype":"method","name":"child","return":{"description":"an array of child nodes","type":"Node[]"},"example":["\n <div class='norender'><code>\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div0.child(div1); // use p5.Element\n </code></div>\n <div class='norender'><code>\n var div0 = createDiv('this is the parent');\n var div1 = createDiv('this is the child');\n div1.id('apples');\n div0.child('apples'); // use id\n </code></div>\n <div class='norender notest'><code>\n var div0 = createDiv('this is the parent');\n var elt = document.getElementById('myChildDiv');\n div0.child(elt); // use element from page\n </code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":1368,"params":[],"return":{"description":"an array of child nodes","type":"Node[]"}},{"line":1394,"params":[{"name":"child","description":"<p>the ID, DOM node, or <a href=\"#/p5.Element\">p5.Element</a>\n to add to the current element</p>\n","type":"String|p5.Element","optional":true}],"chainable":1}]},{"file":"lib/addons/p5.dom.js","line":1416,"description":"<p>Centers a p5 Element either vertically, horizontally,\nor both, relative to its parent or according to\nthe body if the Element has no parent. If no argument is passed\nthe Element is aligned both vertically and horizontally.</p>\n","itemtype":"method","name":"center","params":[{"name":"align","description":"<p>passing &#39;vertical&#39;, &#39;horizontal&#39; aligns element accordingly</p>\n","type":"String","optional":true}],"chainable":1,"example":["\n<div><code>\nfunction setup() {\n var div = createDiv('').size(10, 10);\n div.style('background-color', 'orange');\n div.center();\n}\n</code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1470,"description":"<p>If an argument is given, sets the inner HTML of the element,\n replacing any existing html. If true is included as a second\n argument, html is appended instead of replacing existing html.\n If no arguments are given, returns\n the inner HTML of the element.</p>\n","itemtype":"method","name":"html","return":{"description":"the inner HTML of the element","type":"String"},"example":["\n <div class='norender'><code>\n var div = createDiv('').size(100, 100);\n div.html('hi');\n </code></div>\n <div class='norender'><code>\n var div = createDiv('Hello ').size(100, 100);\n div.html('World', true);\n </code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":1470,"params":[],"return":{"description":"the inner HTML of the element","type":"String"}},{"line":1491,"params":[{"name":"html","description":"<p>the HTML to be placed inside the element</p>\n","type":"String","optional":true},{"name":"append","description":"<p>whether to append HTML to existing</p>\n","type":"Boolean","optional":true}],"chainable":1}]},{"file":"lib/addons/p5.dom.js","line":1509,"description":"<p>Sets the position of the element relative to (0, 0) of the\n window. Essentially, sets position:absolute and left and top\n properties of style. If no arguments given returns the x and y position\n of the element in an object.</p>\n","itemtype":"method","name":"position","return":{"description":"the x and y position of the element in an object","type":"Object"},"example":["\n <div><code class='norender'>\n function setup() {\n var cnv = createCanvas(100, 100);\n // positions canvas 50px to the right and 100px\n // below upper left corner of the window\n cnv.position(50, 100);\n }\n </code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":1509,"params":[],"return":{"description":"the x and y position of the element in an object","type":"Object"}},{"line":1528,"params":[{"name":"x","description":"<p>x-position relative to upper left of window</p>\n","type":"Number","optional":true},{"name":"y","description":"<p>y-position relative to upper left of window</p>\n","type":"Number","optional":true}],"chainable":1}]},{"file":"lib/addons/p5.dom.js","line":1603,"description":"<p>Sets the given style (css) property (1st arg) of the element with the\ngiven value (2nd arg). If a single argument is given, .style()\nreturns the value of the given property; however, if the single argument\nis given in css syntax (&#39;text-align:center&#39;), .style() sets the css\nappropriatly. .style() also handles 2d and 3d css transforms. If\nthe 1st arg is &#39;rotate&#39;, &#39;translate&#39;, or &#39;position&#39;, the following arguments\naccept Numbers as values. (&#39;translate&#39;, 10, 100, 50);</p>\n","itemtype":"method","name":"style","return":{"description":"value of property","type":"String"},"example":["\n<div><code class='norender'>\nvar myDiv = createDiv('I like pandas.');\nmyDiv.style('font-size', '18px');\nmyDiv.style('color', '#ff0000');\n</code></div>\n<div><code class='norender'>\nvar col = color(25, 23, 200, 50);\nvar button = createButton('button');\nbutton.style('background-color', col);\nbutton.position(10, 10);\n</code></div>\n<div><code class='norender'>\nvar myDiv = createDiv('I like lizards.');\nmyDiv.style('position', 20, 20);\nmyDiv.style('rotate', 45);\n</code></div>\n<div><code class='norender'>\nvar myDiv;\nfunction setup() {\n background(200);\n myDiv = createDiv('I like gray.');\n myDiv.position(20, 20);\n}\n\nfunction draw() {\n myDiv.style('font-size', mouseX + 'px');\n}\n</code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":1603,"params":[{"name":"property","description":"<p>property to be set</p>\n","type":"String"}],"return":{"description":"value of property","type":"String"}},{"line":1645,"params":[{"name":"property","description":"","type":"String"},{"name":"value","description":"<p>value to assign to property (only String|Number for rotate/translate)</p>\n","type":"String|Number|p5.Color"},{"name":"value2","description":"<p>position can take a 2nd value</p>\n","type":"String|Number|p5.Color","optional":true},{"name":"value3","description":"<p>translate can take a 2nd &amp; 3rd value</p>\n","type":"String|Number|p5.Color","optional":true}],"chainable":1}]},{"file":"lib/addons/p5.dom.js","line":1704,"description":"<p>Adds a new attribute or changes the value of an existing attribute\n on the specified element. If no value is specified, returns the\n value of the given attribute, or null if attribute is not set.</p>\n","itemtype":"method","name":"attribute","return":{"description":"value of attribute","type":"String"},"example":["\n <div class='norender'><code>\n var myDiv = createDiv('I like pandas.');\n myDiv.attribute('align', 'center');\n </code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":1704,"params":[],"return":{"description":"value of attribute","type":"String"}},{"line":1719,"params":[{"name":"attr","description":"<p>attribute to set</p>\n","type":"String"},{"name":"value","description":"<p>value to assign to attribute</p>\n","type":"String"}],"chainable":1}]},{"file":"lib/addons/p5.dom.js","line":1748,"description":"<p>Removes an attribute on the specified element.</p>\n","itemtype":"method","name":"removeAttribute","params":[{"name":"attr","description":"<p>attribute to remove</p>\n","type":"String"}],"chainable":1,"example":["\n <div><code>\n var button;\n var checkbox;\nfunction setup() {\n checkbox = createCheckbox('enable', true);\n checkbox.changed(enableButton);\n button = createButton('button');\n button.position(10, 10);\n }\nfunction enableButton() {\n if (this.checked()) {\n // Re-enable the button\n button.removeAttribute('disabled');\n } else {\n // Disable the button\n button.attribute('disabled', '');\n }\n }\n </code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1793,"description":"<p>Either returns the value of the element if no arguments\ngiven, or sets the value of the element.</p>\n","itemtype":"method","name":"value","return":{"description":"value of the element","type":"String|Number"},"example":["\n<div class='norender'><code>\n// gets the value\nvar inp;\nfunction setup() {\n inp = createInput('');\n}\n\nfunction mousePressed() {\n print(inp.value());\n}\n</code></div>\n<div class='norender'><code>\n// sets the value\nvar inp;\nfunction setup() {\n inp = createInput('myValue');\n}\n\nfunction mousePressed() {\n inp.value('myValue');\n}\n</code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":1793,"params":[],"return":{"description":"value of the element","type":"String|Number"}},{"line":1823,"params":[{"name":"value","description":"","type":"String|Number"}],"chainable":1}]},{"file":"lib/addons/p5.dom.js","line":1839,"description":"<p>Shows the current element. Essentially, setting display:block for the style.</p>\n","itemtype":"method","name":"show","chainable":1,"example":["\n <div class='norender'><code>\n var div = createDiv('div');\n div.style('display', 'none');\n div.show(); // turns display to block\n </code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1857,"description":"<p>Hides the current element. Essentially, setting display:none for the style.</p>\n","itemtype":"method","name":"hide","chainable":1,"example":["\n<div class='norender'><code>\nvar div = createDiv('this is a div');\ndiv.hide();\n</code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1873,"description":"<p>Sets the width and height of the element. AUTO can be used to\n only adjust one dimension. If no arguments given returns the width and height\n of the element in an object.</p>\n","itemtype":"method","name":"size","return":{"description":"the width and height of the element in an object","type":"Object"},"example":["\n <div class='norender'><code>\n var div = createDiv('this is a div');\n div.size(100, 100);\n </code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":1873,"params":[],"return":{"description":"the width and height of the element in an object","type":"Object"}},{"line":1887,"params":[{"name":"w","description":"<p>width of the element, either AUTO, or a number</p>\n","type":"Number|Constant"},{"name":"h","description":"<p>height of the element, either AUTO, or a number</p>\n","type":"Number|Constant","optional":true}],"chainable":1}]},{"file":"lib/addons/p5.dom.js","line":1951,"description":"<p>Removes the element and deregisters all listeners.</p>\n","itemtype":"method","name":"remove","example":["\n<div class='norender'><code>\nvar myDiv = createDiv('this is some text');\nmyDiv.remove();\n</code></div>"],"class":"p5.Element","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":1999,"description":"<p>Path to the media element source.</p>\n","itemtype":"property","name":"src","return":{"description":"src","type":"String"},"example":["\n<div><code>\nvar ele;\n\nfunction setup() {\n background(250);\n\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/beat.mp3');\n\n //We'll set up our example so that\n //when you click on the text,\n //an alert box displays the MediaElement's\n //src field.\n textAlign(CENTER);\n text('Click Me!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n //Show our p5.MediaElement's src field\n alert(ele.src);\n }\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2065,"description":"<p>Play an HTML5 media element.</p>\n","itemtype":"method","name":"play","chainable":1,"example":["\n<div><code>\nvar ele;\n\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/beat.mp3');\n\n background(250);\n textAlign(CENTER);\n text('Click to Play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n //Here we call the play() function on\n //the p5.MediaElement we created above.\n //This will start the audio sample.\n ele.play();\n\n background(200);\n text('You clicked Play!', width / 2, height / 2);\n }\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2126,"description":"<p>Stops an HTML5 media element (sets current time to zero).</p>\n","itemtype":"method","name":"stop","chainable":1,"example":["\n<div><code>\n//This example both starts\n//and stops a sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\n\n//while our audio is playing,\n//this will be set to true\nvar sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n //if the sample is currently playing\n //calling the stop() function on\n //our p5.MediaElement will stop\n //it and reset its current\n //time to 0 (i.e. it will start\n //at the beginning the next time\n //you play it)\n ele.stop();\n\n sampleIsPlaying = false;\n text('Click to play!', width / 2, height / 2);\n } else {\n //loop our sound element until we\n //call ele.stop() on it.\n ele.loop();\n\n sampleIsPlaying = true;\n text('Click to stop!', width / 2, height / 2);\n }\n }\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2190,"description":"<p>Pauses an HTML5 media element.</p>\n","itemtype":"method","name":"pause","chainable":1,"example":["\n<div><code>\n//This example both starts\n//and pauses a sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\n\n//while our audio is playing,\n//this will be set to true\nvar sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n //Calling pause() on our\n //p5.MediaElement will stop it\n //playing, but when we call the\n //loop() or play() functions\n //the sample will start from\n //where we paused it.\n ele.pause();\n\n sampleIsPlaying = false;\n text('Click to resume!', width / 2, height / 2);\n } else {\n //loop our sound element until we\n //call ele.pause() on it.\n ele.loop();\n\n sampleIsPlaying = true;\n text('Click to pause!', width / 2, height / 2);\n }\n }\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2252,"description":"<p>Set &#39;loop&#39; to true for an HTML5 media element, and starts playing.</p>\n","itemtype":"method","name":"loop","chainable":1,"example":["\n<div><code>\n//Clicking the canvas will loop\n//the audio sample until the user\n//clicks again to stop it\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\n\n//while our audio is playing,\n//this will be set to true\nvar sampleIsLooping = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to loop!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (!sampleIsLooping) {\n //loop our sound element until we\n //call ele.stop() on it.\n ele.loop();\n\n sampleIsLooping = true;\n text('Click to stop!', width / 2, height / 2);\n } else {\n ele.stop();\n\n sampleIsLooping = false;\n text('Click to loop!', width / 2, height / 2);\n }\n }\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2308,"description":"<p>Set &#39;loop&#39; to false for an HTML5 media element. Element will stop\nwhen it reaches the end.</p>\n","itemtype":"method","name":"noLoop","chainable":1,"example":["\n<div><code>\n//This example both starts\n//and stops loop of sound sample\n//when the user clicks the canvas\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\n//while our audio is playing,\n//this will be set to true\nvar sampleIsPlaying = false;\n\nfunction setup() {\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to play!', width / 2, height / 2);\n}\n\nfunction mouseClicked() {\n //here we test if the mouse is over the\n //canvas element when it's clicked\n if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) {\n background(200);\n\n if (sampleIsPlaying) {\n ele.noLoop();\n text('No more Loops!', width / 2, height / 2);\n } else {\n ele.loop();\n sampleIsPlaying = true;\n text('Click to stop looping!', width / 2, height / 2);\n }\n }\n}\n</code></div>\n"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2360,"description":"<p>Set HTML5 media element to autoplay or not.</p>\n","itemtype":"method","name":"autoplay","params":[{"name":"autoplay","description":"<p>whether the element should autoplay</p>\n","type":"Boolean"}],"chainable":1,"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2372,"description":"<p>Sets volume for this HTML5 media element. If no argument is given,\nreturns the current volume.</p>\n","itemtype":"method","name":"volume","return":{"description":"current volume","type":"Number"},"example":["\n<div><code>\nvar ele;\nfunction setup() {\n // p5.MediaElement objects are usually created\n // by calling the createAudio(), createVideo(),\n // and createCapture() functions.\n // In this example we create\n // a new p5.MediaElement via createAudio().\n ele = createAudio('assets/lucky_dragons.mp3');\n background(250);\n textAlign(CENTER);\n text('Click to Play!', width / 2, height / 2);\n}\nfunction mouseClicked() {\n // Here we call the volume() function\n // on the sound element to set its volume\n // Volume must be between 0.0 and 1.0\n ele.volume(0.2);\n ele.play();\n background(200);\n text('You clicked Play!', width / 2, height / 2);\n}\n</code></div>\n<div><code>\nvar audio;\nvar counter = 0;\n\nfunction loaded() {\n audio.play();\n}\n\nfunction setup() {\n audio = createAudio('assets/lucky_dragons.mp3', loaded);\n textAlign(CENTER);\n}\n\nfunction draw() {\n if (counter === 0) {\n background(0, 255, 0);\n text('volume(0.9)', width / 2, height / 2);\n } else if (counter === 1) {\n background(255, 255, 0);\n text('volume(0.5)', width / 2, height / 2);\n } else if (counter === 2) {\n background(255, 0, 0);\n text('volume(0.1)', width / 2, height / 2);\n }\n}\n\nfunction mousePressed() {\n counter++;\n if (counter === 0) {\n audio.volume(0.9);\n } else if (counter === 1) {\n audio.volume(0.5);\n } else if (counter === 2) {\n audio.volume(0.1);\n } else {\n counter = 0;\n audio.volume(0.9);\n }\n}\n</code>\n</div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":2372,"params":[],"return":{"description":"current volume","type":"Number"}},{"line":2445,"params":[{"name":"val","description":"<p>volume between 0.0 and 1.0</p>\n","type":"Number"}],"chainable":1}]},{"file":"lib/addons/p5.dom.js","line":2458,"description":"<p>If no arguments are given, returns the current playback speed of the\nelement. The speed parameter sets the speed where 2.0 will play the\nelement twice as fast, 0.5 will play at half the speed, and -1 will play\nthe element in normal speed in reverse.(Note that not all browsers support\nbackward playback and even if they do, playback might not be smooth.)</p>\n","itemtype":"method","name":"speed","return":{"description":"current playback speed of the element","type":"Number"},"example":["\n<div class='norender notest'><code>\n//Clicking the canvas will loop\n//the audio sample until the user\n//clicks again to stop it\n\n//We will store the p5.MediaElement\n//object in here\nvar ele;\nvar button;\n\nfunction setup() {\n createCanvas(710, 400);\n //Here we create a p5.MediaElement object\n //using the createAudio() function.\n ele = createAudio('assets/beat.mp3');\n ele.loop();\n background(200);\n\n button = createButton('2x speed');\n button.position(100, 68);\n button.mousePressed(twice_speed);\n\n button = createButton('half speed');\n button.position(200, 68);\n button.mousePressed(half_speed);\n\n button = createButton('reverse play');\n button.position(300, 68);\n button.mousePressed(reverse_speed);\n\n button = createButton('STOP');\n button.position(400, 68);\n button.mousePressed(stop_song);\n\n button = createButton('PLAY!');\n button.position(500, 68);\n button.mousePressed(play_speed);\n}\n\nfunction twice_speed() {\n ele.speed(2);\n}\n\nfunction half_speed() {\n ele.speed(0.5);\n}\n\nfunction reverse_speed() {\n ele.speed(-1);\n}\n\nfunction stop_song() {\n ele.stop();\n}\n\nfunction play_speed() {\n ele.play();\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":2458,"params":[],"return":{"description":"current playback speed of the element","type":"Number"}},{"line":2529,"params":[{"name":"speed","description":"<p>speed multiplier for element playback</p>\n","type":"Number"}],"chainable":1}]},{"file":"lib/addons/p5.dom.js","line":2546,"description":"<p>If no arguments are given, returns the current time of the element.\nIf an argument is given the current time of the element is set to it.</p>\n","itemtype":"method","name":"time","return":{"description":"current time (in seconds)","type":"Number"},"example":["\n<div><code>\nvar ele;\nvar beginning = true;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/lucky_dragons.mp3');\n background(250);\n textAlign(CENTER);\n text('start at beginning', width / 2, height / 2);\n}\n\n// this function fires with click anywhere\nfunction mousePressed() {\n if (beginning === true) {\n // here we start the sound at the beginning\n // time(0) is not necessary here\n // as this produces the same result as\n // play()\n ele.play().time(0);\n background(200);\n text('jump 2 sec in', width / 2, height / 2);\n beginning = false;\n } else {\n // here we jump 2 seconds into the sound\n ele.play().time(2);\n background(250);\n text('start at beginning', width / 2, height / 2);\n beginning = true;\n }\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom","overloads":[{"line":2546,"params":[],"return":{"description":"current time (in seconds)","type":"Number"}},{"line":2591,"params":[{"name":"time","description":"<p>time to jump to (in seconds)</p>\n","type":"Number"}],"chainable":1}]},{"file":"lib/addons/p5.dom.js","line":2605,"description":"<p>Returns the duration of the HTML5 media element.</p>\n","itemtype":"method","name":"duration","return":{"description":"duration","type":"Number"},"example":["\n<div><code>\nvar ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio().\n ele = createAudio('assets/doorbell.mp3');\n background(250);\n textAlign(CENTER);\n text('Click to know the duration!', 10, 25, 70, 80);\n}\nfunction mouseClicked() {\n ele.play();\n background(200);\n //ele.duration dislpays the duration\n text(ele.duration() + ' seconds', width / 2, height / 2);\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2746,"description":"<p>Schedule an event to be called when the audio or video\nelement reaches the end. If the element is looping,\nthis will not be called. The element is passed in\nas the argument to the onended callback.</p>\n","itemtype":"method","name":"onended","params":[{"name":"callback","description":"<p>function to call when the\n soundfile has ended. The\n media element will be passed\n in as the argument to the\n callback.</p>\n","type":"Function"}],"chainable":1,"example":["\n<div><code>\nfunction setup() {\n var audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n audioEl.onended(sayDone);\n}\n\nfunction sayDone(elt) {\n alert('done playing ' + elt.src);\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2777,"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2779,"description":"<p>Send the audio output of this element to a specified audioNode or\np5.sound object. If no element is provided, connects to p5&#39;s master\noutput. That connection is established when this method is first called.\nAll connections are removed by the .disconnect() method.</p>\n<p>This method is meant to be used with the p5.sound.js addon library.</p>\n","itemtype":"method","name":"connect","params":[{"name":"audioNode","description":"<p>AudioNode from the Web Audio API,\nor an object from the p5.sound library</p>\n","type":"AudioNode|Object"}],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2828,"description":"<p>Disconnect all Web Audio routing, including to master output.\nThis is useful if you want to re-route the output through\naudio effects, for example.</p>\n","itemtype":"method","name":"disconnect","class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2843,"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2845,"description":"<p>Show the default MediaElement controls, as determined by the web browser.</p>\n","itemtype":"method","name":"showControls","example":["\n<div><code>\nvar ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio()\n ele = createAudio('assets/lucky_dragons.mp3');\n background(200);\n textAlign(CENTER);\n text('Click to Show Controls!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n ele.showControls();\n background(200);\n text('Controls Shown', width / 2, height / 2);\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2876,"description":"<p>Hide the default mediaElement controls.</p>\n","itemtype":"method","name":"hideControls","example":["\n<div><code>\nvar ele;\nfunction setup() {\n //p5.MediaElement objects are usually created\n //by calling the createAudio(), createVideo(),\n //and createCapture() functions.\n //In this example we create\n //a new p5.MediaElement via createAudio()\n ele = createAudio('assets/lucky_dragons.mp3');\n ele.showControls();\n background(200);\n textAlign(CENTER);\n text('Click to hide Controls!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n ele.hideControls();\n background(200);\n text('Controls hidden', width / 2, height / 2);\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2905,"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2916,"description":"<p>Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.</p>\n<p>Accepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.</p>\n<p>Time will be passed as the first parameter to the callback function,\nand param will be the second parameter.</p>\n","itemtype":"method","name":"addCue","params":[{"name":"time","description":"<p>Time in seconds, relative to this media\n element&#39;s playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.</p>\n","type":"Number"},{"name":"callback","description":"<p>Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.</p>\n","type":"Function"},{"name":"value","description":"<p>An object to be passed as the\n second parameter to the\n callback function.</p>\n","type":"Object","optional":true}],"return":{"description":"id ID of this cue,\n useful for removeCue(id)","type":"Number"},"example":["\n<div><code>\n//\n//\nfunction setup() {\n noCanvas();\n\n var audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n\n // schedule three calls to changeBackground\n audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n audioEl.addCue(5.0, changeBackground, color(255, 255, 0));\n}\n\nfunction changeBackground(val) {\n background(val);\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":2980,"description":"<p>Remove a callback based on its ID. The ID is returned by the\naddCue method.</p>\n","itemtype":"method","name":"removeCue","params":[{"name":"id","description":"<p>ID of the cue, as returned by addCue</p>\n","type":"Number"}],"example":["\n<div><code>\nvar audioEl, id1, id2;\nfunction setup() {\n background(255, 255, 255);\n audioEl = createAudio('assets/beat.mp3');\n audioEl.showControls();\n // schedule five calls to changeBackground\n id1 = audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n id2 = audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n text('Click to remove first and last Cue!', 10, 25, 70, 80);\n}\nfunction mousePressed() {\n audioEl.removeCue(id1);\n audioEl.removeCue(id2);\n}\nfunction changeBackground(val) {\n background(val);\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":3022,"description":"<p>Remove all of the callbacks that had originally been scheduled\nvia the addCue method.</p>\n","itemtype":"method","name":"clearCues","params":[{"name":"id","description":"<p>ID of the cue, as returned by addCue</p>\n","type":"Number"}],"example":["\n<div><code>\nvar audioEl;\nfunction setup() {\n background(255, 255, 255);\n audioEl = createAudio('assets/beat.mp3');\n //Show the default MediaElement controls, as determined by the web browser\n audioEl.showControls();\n // schedule calls to changeBackground\n background(200);\n text('Click to change Cue!', 10, 25, 70, 80);\n audioEl.addCue(0.5, changeBackground, color(255, 0, 0));\n audioEl.addCue(1.0, changeBackground, color(0, 255, 0));\n audioEl.addCue(2.5, changeBackground, color(0, 0, 255));\n audioEl.addCue(3.0, changeBackground, color(0, 255, 255));\n audioEl.addCue(4.2, changeBackground, color(255, 255, 0));\n}\nfunction mousePressed() {\n // here we clear the scheduled callbacks\n audioEl.clearCues();\n // then we add some more callbacks\n audioEl.addCue(1, changeBackground, color(2, 2, 2));\n audioEl.addCue(3, changeBackground, color(255, 255, 0));\n}\nfunction changeBackground(val) {\n background(val);\n}\n</code></div>"],"class":"p5.MediaElement","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":3092,"description":"<p>Underlying File object. All normal File methods can be called on this.</p>\n","itemtype":"property","name":"file","class":"p5.File","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":3104,"description":"<p>File type (image, text, etc.)</p>\n","itemtype":"property","name":"type","class":"p5.File","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":3110,"description":"<p>File subtype (usually the file extension jpg, png, xml, etc.)</p>\n","itemtype":"property","name":"subtype","class":"p5.File","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":3116,"description":"<p>File name</p>\n","itemtype":"property","name":"name","class":"p5.File","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":3122,"description":"<p>File size</p>\n","itemtype":"property","name":"size","class":"p5.File","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.dom.js","line":3129,"description":"<p>URL string containing image data.</p>\n","itemtype":"property","name":"data","class":"p5.File","module":"p5.dom","submodule":"p5.dom"},{"file":"lib/addons/p5.sound.js","line":46,"description":"<p>p5.sound \n<a href=\"https://p5js.org/reference/#/libraries/p5.sound\">https://p5js.org/reference/#/libraries/p5.sound</a></p>\n<p>From the Processing Foundation and contributors\n<a href=\"https://github.com/processing/p5.js-sound/graphs/contributors\">https://github.com/processing/p5.js-sound/graphs/contributors</a></p>\n<p>MIT License (MIT)\n<a href=\"https://github.com/processing/p5.js-sound/blob/master/LICENSE\">https://github.com/processing/p5.js-sound/blob/master/LICENSE</a></p>\n<p>Some of the many audio libraries &amp; resources that inspire p5.sound:</p>\n<ul>\n<li>TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). <a href=\"https://github.com/TONEnoTONE/Tone.js\">https://github.com/TONEnoTONE/Tone.js</a></li>\n<li>buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). <a href=\"http://buzz.jaysalvat.com/\">http://buzz.jaysalvat.com/</a></li>\n<li>Boris Smus Web Audio API book, 2013. Licensed under the Apache License <a href=\"http://www.apache.org/licenses/LICENSE-2.0\">http://www.apache.org/licenses/LICENSE-2.0</a></li>\n<li>wavesurfer.js <a href=\"https://github.com/katspaugh/wavesurfer.js\">https://github.com/katspaugh/wavesurfer.js</a></li>\n<li>Web Audio Components by Jordan Santell <a href=\"https://github.com/web-audio-components\">https://github.com/web-audio-components</a></li>\n<li><p>Wilm Thoben&#39;s Sound library for Processing <a href=\"https://github.com/processing/processing/tree/master/java/libraries/sound\">https://github.com/processing/processing/tree/master/java/libraries/sound</a></p>\n<p>Web Audio API: <a href=\"http://w3.org/TR/webaudio/\">http://w3.org/TR/webaudio/</a></p>\n</li>\n</ul>\n","class":"p5.sound","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":214,"description":"<p>Determine which filetypes are supported (inspired by buzz.js)\nThe audio element (el) will only be used to test browser support for various audio formats</p>\n","class":"p5.sound","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":262,"description":"<p>Returns the Audio Context for this sketch. Useful for users\nwho would like to dig deeper into the <a target='_blank' href=\n'http://webaudio.github.io/web-audio-api/'>Web Audio API\n</a>.</p>\n\n<p>Some browsers require users to startAudioContext\nwith a user gesture, such as touchStarted in the example below.</p>","itemtype":"method","name":"getAudioContext","return":{"description":"AudioContext for this sketch","type":"Object"},"example":["\n<div><code>\n function draw() {\n background(255);\n textAlign(CENTER);\n\n if (getAudioContext().state !== 'running') {\n text('click to start audio', width/2, height/2);\n } else {\n text('audio is enabled', width/2, height/2);\n }\n }\n\n function touchStarted() {\n if (getAudioContext().state !== 'running') {\n getAudioContext().resume();\n }\n var synth = new p5.MonoSynth();\n synth.play('A4', 0.5, 0, 0.2);\n }\n\n</div></code>"],"class":"p5.sound","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":328,"description":"<p>Master contains AudioContext and the master sound output.</p>\n","class":"p5.sound","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":361,"description":"<p>Returns a number representing the master amplitude (volume) for sound\nin this sketch.</p>\n","itemtype":"method","name":"getMasterVolume","return":{"description":"Master amplitude (volume) for sound in this sketch.\n Should be between 0.0 (silence) and 1.0.","type":"Number"},"class":"p5.sound","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":372,"description":"<p>Scale the output of all sound in this sketch</p>\nScaled between 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a <code>rampTime</code> parameter. For more\ncomplex fades, see the Envelope class.\n\nAlternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.\n\n<p><b>How This Works</b>: When you load the p5.sound module, it\ncreates a single instance of p5sound. All sound objects in this\nmodule output to p5sound before reaching your computer&#39;s output.\nSo if you change the amplitude of p5sound, it impacts all of the\nsound in this module.</p>\n\n<p>If no value is provided, returns a Web Audio API Gain Node</p>","itemtype":"method","name":"masterVolume","params":[{"name":"volume","description":"<p>Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator</p>\n","type":"Number|Object"},{"name":"rampTime","description":"<p>Fade for t seconds</p>\n","type":"Number","optional":true},{"name":"timeFromNow","description":"<p>Schedule this event to happen at\n t seconds in the future</p>\n","type":"Number","optional":true}],"class":"p5.sound","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":414,"description":"<p><code>p5.soundOut</code> is the p5.sound master output. It sends output to\nthe destination of this window&#39;s web audio context. It contains\nWeb Audio API nodes including a dyanmicsCompressor (<code>.limiter</code>),\nand Gain Nodes for <code>.input</code> and <code>.output</code>.</p>\n","itemtype":"property","name":"soundOut","type":"Object","class":"p5.sound","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":439,"class":"p5","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":442,"description":"<p>Returns a number representing the sample rate, in samples per second,\nof all sound objects in this audio context. It is determined by the\nsampling rate of your operating system&#39;s sound card, and it is not\ncurrently possile to change.\nIt is often 44100, or twice the range of human hearing.</p>\n","itemtype":"method","name":"sampleRate","return":{"description":"samplerate samples per second","type":"Number"},"class":"p5","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":455,"description":"<p>Returns the closest MIDI note value for\na given frequency.</p>\n","itemtype":"method","name":"freqToMidi","params":[{"name":"frequency","description":"<p>A freqeuncy, for example, the &quot;A&quot;\n above Middle C is 440Hz</p>\n","type":"Number"}],"return":{"description":"MIDI note value","type":"Number"},"class":"p5","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":469,"description":"<p>Returns the frequency value of a MIDI note value.\nGeneral MIDI treats notes as integers where middle C\nis 60, C# is 61, D is 62 etc. Useful for generating\nmusical frequencies with oscillators.</p>\n","itemtype":"method","name":"midiToFreq","params":[{"name":"midiNote","description":"<p>The number of a MIDI note</p>\n","type":"Number"}],"return":{"description":"Frequency value of the given MIDI note","type":"Number"},"example":["\n<div><code>\nvar notes = [60, 64, 67, 72];\nvar i = 0;\n\nfunction setup() {\n osc = new p5.Oscillator('Triangle');\n osc.start();\n frameRate(1);\n}\n\nfunction draw() {\n var freq = midiToFreq(notes[i]);\n osc.freq(freq);\n i++;\n if (i >= notes.length){\n i = 0;\n }\n}\n</code></div>"],"class":"p5","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":531,"description":"<p>List the SoundFile formats that you will include. LoadSound\nwill search your directory for these extensions, and will pick\na format that is compatable with the client&#39;s web browser.\n<a href=\"http://media.io/\">Here</a> is a free online file\nconverter.</p>\n","itemtype":"method","name":"soundFormats","params":[{"name":"formats","description":"<p>i.e. &#39;mp3&#39;, &#39;wav&#39;, &#39;ogg&#39;</p>\n","type":"String","optional":true,"multiple":true}],"example":["\n<div><code>\nfunction preload() {\n // set the global sound formats\n soundFormats('mp3', 'ogg');\n\n // load either beatbox.mp3, or .ogg, depending on browser\n mySound = loadSound('assets/beatbox.mp3');\n}\n\nfunction setup() {\n mySound.play();\n}\n</code></div>"],"class":"p5","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":644,"description":"<p>Used by Osc and Envelope to chain signal math</p>\n","class":"p5","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":923,"description":"<p>loadSound() returns a new p5.SoundFile from a specified\npath. If called during preload(), the p5.SoundFile will be ready\nto play in time for setup() and draw(). If called outside of\npreload, the p5.SoundFile will not be ready immediately, so\nloadSound accepts a callback as the second parameter. Using a\n<a href=\"https://github.com/processing/p5.js/wiki/Local-server\">\nlocal server</a> is recommended when loading external files.</p>\n","itemtype":"method","name":"loadSound","params":[{"name":"path","description":"<p>Path to the sound file, or an array with\n paths to soundfiles in multiple formats\n i.e. [&#39;sound.ogg&#39;, &#39;sound.mp3&#39;].\n Alternately, accepts an object: either\n from the HTML5 File API, or a p5.File.</p>\n","type":"String|Array"},{"name":"successCallback","description":"<p>Name of a function to call once file loads</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>Name of a function to call if there is\n an error loading the file.</p>\n","type":"Function","optional":true},{"name":"whileLoading","description":"<p>Name of a function to call while file is loading.\n This function will receive the percentage loaded\n so far, from 0.0 to 1.0.</p>\n","type":"Function","optional":true}],"return":{"description":"Returns a p5.SoundFile","type":"SoundFile"},"example":["\n<div><code>\nfunction preload() {\n mySound = loadSound('assets/doorbell.mp3');\n}\n\nfunction setup() {\n mySound.setVolume(0.1);\n mySound.play();\n}\n</code></div>"],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1065,"description":"<p>Returns true if the sound file finished loading successfully.</p>\n","itemtype":"method","name":"isLoaded","return":{"description":"","type":"Boolean"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1078,"description":"<p>Play the p5.SoundFile</p>\n","itemtype":"method","name":"play","params":[{"name":"startTime","description":"<p>(optional) schedule playback to start (in seconds from now).</p>\n","type":"Number","optional":true},{"name":"rate","description":"<p>(optional) playback rate</p>\n","type":"Number","optional":true},{"name":"amp","description":"<p>(optional) amplitude (volume)\n of playback</p>\n","type":"Number","optional":true},{"name":"cueStart","description":"<p>(optional) cue start time in seconds</p>\n","type":"Number","optional":true},{"name":"duration","description":"<p>(optional) duration of playback in seconds</p>\n","type":"Number","optional":true}],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1183,"description":"<p>p5.SoundFile has two play modes: <code>restart</code> and\n<code>sustain</code>. Play Mode determines what happens to a\np5.SoundFile if it is triggered while in the middle of playback.\nIn sustain mode, playback will continue simultaneous to the\nnew playback. In restart mode, play() will stop playback\nand start over. With untilDone, a sound will play only if it&#39;s\nnot already playing. Sustain is the default mode.</p>\n","itemtype":"method","name":"playMode","params":[{"name":"str","description":"<p>&#39;restart&#39; or &#39;sustain&#39; or &#39;untilDone&#39;</p>\n","type":"String"}],"example":["\n<div><code>\nvar mySound;\nfunction preload(){\n mySound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\nfunction mouseClicked() {\n mySound.playMode('sustain');\n mySound.play();\n}\nfunction keyPressed() {\n mySound.playMode('restart');\n mySound.play();\n}\n\n </code></div>"],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1227,"description":"<p>Pauses a file that is currently playing. If the file is not\nplaying, then nothing will happen.</p>\n<p>After pausing, .play() will resume from the paused\nposition.\nIf p5.SoundFile had been set to loop before it was paused,\nit will continue to loop after it is unpaused with .play().</p>\n","itemtype":"method","name":"pause","params":[{"name":"startTime","description":"<p>(optional) schedule event to occur\n seconds from now</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar soundFile;\n\nfunction preload() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/Damscray_-_Dancing_Tiger_02.mp3');\n}\nfunction setup() {\n background(0, 255, 0);\n soundFile.setVolume(0.1);\n soundFile.loop();\n}\nfunction keyTyped() {\n if (key == 'p') {\n soundFile.pause();\n background(255, 0, 0);\n }\n}\n\nfunction keyReleased() {\n if (key == 'p') {\n soundFile.play();\n background(0, 255, 0);\n }\n}\n</code>\n</div>"],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1283,"description":"<p>Loop the p5.SoundFile. Accepts optional parameters to set the\nplayback rate, playback volume, loopStart, loopEnd.</p>\n","itemtype":"method","name":"loop","params":[{"name":"startTime","description":"<p>(optional) schedule event to occur\n seconds from now</p>\n","type":"Number","optional":true},{"name":"rate","description":"<p>(optional) playback rate</p>\n","type":"Number","optional":true},{"name":"amp","description":"<p>(optional) playback volume</p>\n","type":"Number","optional":true},{"name":"cueLoopStart","description":"<p>(optional) startTime in seconds</p>\n","type":"Number","optional":true},{"name":"duration","description":"<p>(optional) loop duration in seconds</p>\n","type":"Number","optional":true}],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1299,"description":"<p>Set a p5.SoundFile&#39;s looping flag to true or false. If the sound\nis currently playing, this change will take effect when it\nreaches the end of the current playback.</p>\n","itemtype":"method","name":"setLoop","params":[{"name":"Boolean","description":"<p>set looping to true or false</p>\n","type":"Boolean"}],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1320,"description":"<p>Returns &#39;true&#39; if a p5.SoundFile is currently looping and playing, &#39;false&#39; if not.</p>\n","itemtype":"method","name":"isLooping","return":{"description":"","type":"Boolean"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1335,"description":"<p>Returns true if a p5.SoundFile is playing, false if not (i.e.\npaused or stopped).</p>\n","itemtype":"method","name":"isPlaying","return":{"description":"","type":"Boolean"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1345,"description":"<p>Returns true if a p5.SoundFile is paused, false if not (i.e.\nplaying or stopped).</p>\n","itemtype":"method","name":"isPaused","return":{"description":"","type":"Boolean"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1355,"description":"<p>Stop soundfile playback.</p>\n","itemtype":"method","name":"stop","params":[{"name":"startTime","description":"<p>(optional) schedule event to occur\n in seconds from now</p>\n","type":"Number","optional":true}],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1401,"description":"<p>Multiply the output volume (amplitude) of a sound file\nbetween 0.0 (silence) and 1.0 (full volume).\n1.0 is the maximum amplitude of a digital sound, so multiplying\nby greater than 1.0 may cause digital distortion. To\nfade, provide a <code>rampTime</code> parameter. For more\ncomplex fades, see the Envelope class.</p>\n<p>Alternately, you can pass in a signal source such as an\noscillator to modulate the amplitude with an audio signal.</p>\n","itemtype":"method","name":"setVolume","params":[{"name":"volume","description":"<p>Volume (amplitude) between 0.0\n and 1.0 or modulating signal/oscillator</p>\n","type":"Number|Object"},{"name":"rampTime","description":"<p>Fade for t seconds</p>\n","type":"Number","optional":true},{"name":"timeFromNow","description":"<p>Schedule this event to happen at\n t seconds in the future</p>\n","type":"Number","optional":true}],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1442,"description":"<p>Set the stereo panning of a p5.sound object to\na floating point number between -1.0 (left) and 1.0 (right).\nDefault is 0.0 (center).</p>\n","itemtype":"method","name":"pan","params":[{"name":"panValue","description":"<p>Set the stereo panner</p>\n","type":"Number","optional":true},{"name":"timeFromNow","description":"<p>schedule this event to happen\n seconds from now</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\n\n var ball = {};\n var soundFile;\n\n function preload() {\n soundFormats('ogg', 'mp3');\n soundFile = loadSound('assets/beatbox.mp3');\n }\n\n function draw() {\n background(0);\n ball.x = constrain(mouseX, 0, width);\n ellipse(ball.x, height/2, 20, 20)\n }\n\n function mousePressed(){\n // map the ball's x location to a panning degree\n // between -1.0 (left) and 1.0 (right)\n var panning = map(ball.x, 0., width,-1.0, 1.0);\n soundFile.pan(panning);\n soundFile.play();\n }\n </div></code>"],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1481,"description":"<p>Returns the current stereo pan position (-1.0 to 1.0)</p>\n","itemtype":"method","name":"getPan","return":{"description":"Returns the stereo pan setting of the Oscillator\n as a number between -1.0 (left) and 1.0 (right).\n 0.0 is center and default.","type":"Number"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1492,"description":"<p>Set the playback rate of a sound file. Will change the speed and the pitch.\nValues less than zero will reverse the audio buffer.</p>\n","itemtype":"method","name":"rate","params":[{"name":"playbackRate","description":"<p>Set the playback rate. 1.0 is normal,\n .5 is half-speed, 2.0 is twice as fast.\n Values less than zero play backwards.</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar song;\n\nfunction preload() {\n song = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n song.loop();\n}\n\nfunction draw() {\n background(200);\n\n // Set the rate to a range between 0.1 and 4\n // Changing the rate also alters the pitch\n var speed = map(mouseY, 0.1, height, 0, 2);\n speed = constrain(speed, 0.01, 4);\n song.rate(speed);\n\n // Draw a circle to show what is going on\n stroke(0);\n fill(51, 100);\n ellipse(mouseX, 100, 48, 48);\n}\n\n </code>\n </div>\n"],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1565,"description":"<p>Returns the duration of a sound file in seconds.</p>\n","itemtype":"method","name":"duration","return":{"description":"The duration of the soundFile in seconds.","type":"Number"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1579,"description":"<p>Return the current position of the p5.SoundFile playhead, in seconds.\nTime is relative to the normal buffer direction, so if <code>reverseBuffer</code>\nhas been called, currentTime will count backwards.</p>\n","itemtype":"method","name":"currentTime","return":{"description":"currentTime of the soundFile in seconds.","type":"Number"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1590,"description":"<p>Move the playhead of the song to a position, in seconds. Start timing\nand playback duration. If none are given, will reset the file to play\nentire duration from start to finish.</p>\n","itemtype":"method","name":"jump","params":[{"name":"cueTime","description":"<p>cueTime of the soundFile in seconds.</p>\n","type":"Number"},{"name":"duration","description":"<p>duration in seconds.</p>\n","type":"Number"}],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1613,"description":"<p>Return the number of channels in a sound file.\nFor example, Mono = 1, Stereo = 2.</p>\n","itemtype":"method","name":"channels","return":{"description":"[channels]","type":"Number"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1623,"description":"<p>Return the sample rate of the sound file.</p>\n","itemtype":"method","name":"sampleRate","return":{"description":"[sampleRate]","type":"Number"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1632,"description":"<p>Return the number of samples in a sound file.\nEqual to sampleRate * duration.</p>\n","itemtype":"method","name":"frames","return":{"description":"[sampleCount]","type":"Number"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1642,"description":"<p>Returns an array of amplitude peaks in a p5.SoundFile that can be\nused to draw a static waveform. Scans through the p5.SoundFile&#39;s\naudio buffer to find the greatest amplitudes. Accepts one\nparameter, &#39;length&#39;, which determines size of the array.\nLarger arrays result in more precise waveform visualizations.</p>\n<p>Inspired by Wavesurfer.js.</p>\n","itemtype":"method","name":"getPeaks","params":[{"name":"length","description":"<p>length is the size of the returned array.\n Larger length results in more precision.\n Defaults to 5*width of the browser window.</p>\n","type":"Number","optional":true}],"return":{"description":"Array of peaks.","type":"Float32Array"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1694,"description":"<p>Reverses the p5.SoundFile&#39;s buffer source.\nPlayback must be handled separately (see example).</p>\n","itemtype":"method","name":"reverseBuffer","example":["\n<div><code>\nvar drum;\n\nfunction preload() {\n drum = loadSound('assets/drum.mp3');\n}\n\nfunction setup() {\n drum.reverseBuffer();\n drum.play();\n}\n\n </code>\n </div>"],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1734,"description":"<p>Schedule an event to be called when the soundfile\nreaches the end of a buffer. If the soundfile is\nplaying through once, this will be called when it\nends. If it is looping, it will be called when\nstop is called.</p>\n","itemtype":"method","name":"onended","params":[{"name":"callback","description":"<p>function to call when the\n soundfile has ended.</p>\n","type":"Function"}],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1787,"description":"<p>Connects the output of a p5sound object to input of another\np5.sound object. For example, you may connect a p5.SoundFile to an\nFFT or an Effect. If no parameter is given, it will connect to\nthe master output. Most p5sound objects connect to the master\noutput when they are created.</p>\n","itemtype":"method","name":"connect","params":[{"name":"object","description":"<p>Audio object that accepts an input</p>\n","type":"Object","optional":true}],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1808,"description":"<p>Disconnects the output of this p5sound object.</p>\n","itemtype":"method","name":"disconnect","class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1818,"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1823,"description":"<p>Reset the source for this SoundFile to a\nnew path (URL).</p>\n","itemtype":"method","name":"setPath","params":[{"name":"path","description":"<p>path to audio file</p>\n","type":"String"},{"name":"callback","description":"<p>Callback</p>\n","type":"Function"}],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1836,"description":"<p>Replace the current Audio Buffer with a new Buffer.</p>\n","itemtype":"method","name":"setBuffer","params":[{"name":"buf","description":"<p>Array of Float32 Array(s). 2 Float32 Arrays\n will create a stereo source. 1 will create\n a mono source.</p>\n","type":"Array"}],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":1908,"description":"<p>processPeaks returns an array of timestamps where it thinks there is a beat.</p>\n<p>This is an asynchronous function that processes the soundfile in an offline audio context,\nand sends the results to your callback function.</p>\n<p>The process involves running the soundfile through a lowpass filter, and finding all of the\npeaks above the initial threshold. If the total number of peaks are below the minimum number of peaks,\nit decreases the threshold and re-runs the analysis until either minPeaks or minThreshold are reached.</p>\n","itemtype":"method","name":"processPeaks","params":[{"name":"callback","description":"<p>a function to call once this data is returned</p>\n","type":"Function"},{"name":"initThreshold","description":"<p>initial threshold defaults to 0.9</p>\n","type":"Number","optional":true},{"name":"minThreshold","description":"<p>minimum threshold defaults to 0.22</p>\n","type":"Number","optional":true},{"name":"minPeaks","description":"<p>minimum number of peaks defaults to 200</p>\n","type":"Number","optional":true}],"return":{"description":"Array of timestamped peaks","type":"Array"},"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2099,"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2108,"description":"<p>Schedule events to trigger every time a MediaElement\n(audio/video) reaches a playback cue point.</p>\n<p>Accepts a callback function, a time (in seconds) at which to trigger\nthe callback, and an optional parameter for the callback.</p>\n<p>Time will be passed as the first parameter to the callback function,\nand param will be the second parameter.</p>\n","itemtype":"method","name":"addCue","params":[{"name":"time","description":"<p>Time in seconds, relative to this media\n element&#39;s playback. For example, to trigger\n an event every time playback reaches two\n seconds, pass in the number 2. This will be\n passed as the first parameter to\n the callback function.</p>\n","type":"Number"},{"name":"callback","description":"<p>Name of a function that will be\n called at the given time. The callback will\n receive time and (optionally) param as its\n two parameters.</p>\n","type":"Function"},{"name":"value","description":"<p>An object to be passed as the\n second parameter to the\n callback function.</p>\n","type":"Object","optional":true}],"return":{"description":"id ID of this cue,\n useful for removeCue(id)","type":"Number"},"example":["\n<div><code>\nvar mySound;\nfunction preload() {\n mySound = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n // schedule calls to changeText\n mySound.addCue(0.50, changeText, \"hello\" );\n mySound.addCue(1.00, changeText, \"p5\" );\n mySound.addCue(1.50, changeText, \"what\" );\n mySound.addCue(2.00, changeText, \"do\" );\n mySound.addCue(2.50, changeText, \"you\" );\n mySound.addCue(3.00, changeText, \"want\" );\n mySound.addCue(4.00, changeText, \"to\" );\n mySound.addCue(5.00, changeText, \"make\" );\n mySound.addCue(6.00, changeText, \"?\" );\n}\n\nfunction changeText(val) {\n background(0);\n text(val, width/2, height/2);\n}\n\nfunction mouseClicked() {\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n if (mySound.isPlaying() ) {\n mySound.stop();\n } else {\n mySound.play();\n }\n }\n}\n</code></div>"],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2186,"description":"<p>Remove a callback based on its ID. The ID is returned by the\naddCue method.</p>\n","itemtype":"method","name":"removeCue","params":[{"name":"id","description":"<p>ID of the cue, as returned by addCue</p>\n","type":"Number"}],"class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2204,"description":"<p>Remove all of the callbacks that had originally been scheduled\nvia the addCue method.</p>\n","itemtype":"method","name":"clearCues","class":"p5.SoundFile","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2312,"description":"<p>Connects to the p5sound instance (master output) by default.\nOptionally, you can pass in a specific source (i.e. a soundfile).</p>\n","itemtype":"method","name":"setInput","params":[{"name":"snd","description":"<p>set the sound source\n (optional, defaults to\n master output)</p>\n","type":"SoundObject|undefined","optional":true},{"name":"smoothing","description":"<p>a range between 0.0 and 1.0\n to smooth amplitude readings</p>\n","type":"Number|undefined","optional":true}],"example":["\n<div><code>\nfunction preload(){\n sound1 = loadSound('assets/beat.mp3');\n sound2 = loadSound('assets/drum.mp3');\n}\nfunction setup(){\n amplitude = new p5.Amplitude();\n sound1.play();\n sound2.play();\n amplitude.setInput(sound2);\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\nfunction mouseClicked(){\n sound1.stop();\n sound2.stop();\n}\n</code></div>"],"class":"p5.Amplitude","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2419,"description":"<p>Returns a single Amplitude reading at the moment it is called.\nFor continuous readings, run in the draw loop.</p>\n","itemtype":"method","name":"getLevel","params":[{"name":"channel","description":"<p>Optionally return only channel 0 (left) or 1 (right)</p>\n","type":"Number","optional":true}],"return":{"description":"Amplitude as a number between 0.0 and 1.0","type":"Number"},"example":["\n<div><code>\nfunction preload(){\n sound = loadSound('assets/beat.mp3');\n}\nfunction setup() {\n amplitude = new p5.Amplitude();\n sound.play();\n}\nfunction draw() {\n background(0);\n fill(255);\n var level = amplitude.getLevel();\n var size = map(level, 0, 1, 0, 200);\n ellipse(width/2, height/2, size, size);\n}\nfunction mouseClicked(){\n sound.stop();\n}\n</code></div>"],"class":"p5.Amplitude","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2460,"description":"<p>Determines whether the results of Amplitude.process() will be\nNormalized. To normalize, Amplitude finds the difference the\nloudest reading it has processed and the maximum amplitude of\n1.0. Amplitude adds this difference to all values to produce\nresults that will reliably map between 0.0 and 1.0. However,\nif a louder moment occurs, the amount that Normalize adds to\nall the values will change. Accepts an optional boolean parameter\n(true or false). Normalizing is off by default.</p>\n","itemtype":"method","name":"toggleNormalize","params":[{"name":"boolean","description":"<p>set normalize to true (1) or false (0)</p>\n","type":"Boolean","optional":true}],"class":"p5.Amplitude","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2480,"description":"<p>Smooth Amplitude analysis by averaging with the last analysis\nframe. Off by default.</p>\n","itemtype":"method","name":"smooth","params":[{"name":"set","description":"<p>smoothing from 0.0 &lt;= 1</p>\n","type":"Number"}],"class":"p5.Amplitude","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2654,"description":"<p>Set the input source for the FFT analysis. If no source is\nprovided, FFT will analyze all sound in the sketch.</p>\n","itemtype":"method","name":"setInput","params":[{"name":"source","description":"<p>p5.sound object (or web audio API source node)</p>\n","type":"Object","optional":true}],"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2673,"description":"<p>Returns an array of amplitude values (between -1.0 and +1.0) that represent\na snapshot of amplitude readings in a single buffer. Length will be\nequal to bins (defaults to 1024). Can be used to draw the waveform\nof a sound.</p>\n","itemtype":"method","name":"waveform","params":[{"name":"bins","description":"<p>Must be a power of two between\n 16 and 1024. Defaults to 1024.</p>\n","type":"Number","optional":true},{"name":"precision","description":"<p>If any value is provided, will return results\n in a Float32 Array which is more precise\n than a regular array.</p>\n","type":"String","optional":true}],"return":{"description":"Array Array of amplitude values (-1 to 1)\n over time. Array length = bins.","type":"Array"},"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2716,"description":"<p>Returns an array of amplitude values (between 0 and 255)\nacross the frequency spectrum. Length is equal to FFT bins\n(1024 by default). The array indices correspond to frequencies\n(i.e. pitches), from the lowest to the highest that humans can\nhear. Each value represents amplitude at that slice of the\nfrequency spectrum. Must be called prior to using\n<code>getEnergy()</code>.</p>\n","itemtype":"method","name":"analyze","params":[{"name":"bins","description":"<p>Must be a power of two between\n 16 and 1024. Defaults to 1024.</p>\n","type":"Number","optional":true},{"name":"scale","description":"<p>If &quot;dB,&quot; returns decibel\n float measurements between\n -140 and 0 (max).\n Otherwise returns integers from 0-255.</p>\n","type":"Number","optional":true}],"return":{"description":"spectrum Array of energy (amplitude/volume)\n values across the frequency spectrum.\n Lowest energy (silence) = 0, highest\n possible is 255.","type":"Array"},"example":["\n<div><code>\nvar osc;\nvar fft;\n\nfunction setup(){\n createCanvas(100,100);\n osc = new p5.Oscillator();\n osc.amp(0);\n osc.start();\n fft = new p5.FFT();\n}\n\nfunction draw(){\n background(0);\n\n var freq = map(mouseX, 0, 800, 20, 15000);\n freq = constrain(freq, 1, 20000);\n osc.freq(freq);\n\n var spectrum = fft.analyze();\n noStroke();\n fill(0,255,0); // spectrum is green\n for (var i = 0; i< spectrum.length; i++){\n var x = map(i, 0, spectrum.length, 0, width);\n var h = -height + map(spectrum[i], 0, 255, height, 0);\n rect(x, height, width / spectrum.length, h );\n }\n\n stroke(255);\n text('Freq: ' + round(freq)+'Hz', 10, 10);\n\n isMouseOverCanvas();\n}\n\n// only play sound when mouse is over canvas\nfunction isMouseOverCanvas() {\n var mX = mouseX, mY = mouseY;\n if (mX > 0 && mX < width && mY < height && mY > 0) {\n osc.amp(0.5, 0.2);\n } else {\n osc.amp(0, 0.2);\n }\n}\n</code></div>\n\n"],"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2808,"description":"<p>Returns the amount of energy (volume) at a specific\n<a href=\"https://en.wikipedia.org/wiki/Audio_frequency\" target=\"_blank\">\nfrequency</a>, or the average amount of energy between two\nfrequencies. Accepts Number(s) corresponding\nto frequency (in Hz), or a String corresponding to predefined\nfrequency ranges (&quot;bass&quot;, &quot;lowMid&quot;, &quot;mid&quot;, &quot;highMid&quot;, &quot;treble&quot;).\nReturns a range between 0 (no energy/volume at that frequency) and\n255 (maximum energy).\n<em>NOTE: analyze() must be called prior to getEnergy(). Analyze()\ntells the FFT to analyze frequency data, and getEnergy() uses\nthe results determine the value at a specific frequency or\nrange of frequencies.</em></p></p>\n","itemtype":"method","name":"getEnergy","params":[{"name":"frequency1","description":"<p>Will return a value representing\n energy at this frequency. Alternately,\n the strings &quot;bass&quot;, &quot;lowMid&quot; &quot;mid&quot;,\n &quot;highMid&quot;, and &quot;treble&quot; will return\n predefined frequency ranges.</p>\n","type":"Number|String"},{"name":"frequency2","description":"<p>If a second frequency is given,\n will return average amount of\n energy that exists between the\n two frequencies.</p>\n","type":"Number","optional":true}],"return":{"description":"Energy Energy (volume/amplitude) from\n 0 and 255.","type":"Number"},"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2890,"description":"<p>Returns the\n<a href=\"http://en.wikipedia.org/wiki/Spectral_centroid\" target=\"_blank\">\nspectral centroid</a> of the input signal.\n<em>NOTE: analyze() must be called prior to getCentroid(). Analyze()\ntells the FFT to analyze frequency data, and getCentroid() uses\nthe results determine the spectral centroid.</em></p></p>\n","itemtype":"method","name":"getCentroid","return":{"description":"Spectral Centroid Frequency Frequency of the spectral centroid in Hz.","type":"Number"},"example":["\n<div><code>\n\n\nfunction setup(){\ncnv = createCanvas(100,100);\nsound = new p5.AudioIn();\nsound.start();\nfft = new p5.FFT();\nsound.connect(fft);\n}\n\n\nfunction draw(){\n\nvar centroidplot = 0.0;\nvar spectralCentroid = 0;\n\n\nbackground(0);\nstroke(0,255,0);\nvar spectrum = fft.analyze();\nfill(0,255,0); // spectrum is green\n\n//draw the spectrum\nfor (var i = 0; i< spectrum.length; i++){\n var x = map(log(i), 0, log(spectrum.length), 0, width);\n var h = map(spectrum[i], 0, 255, 0, height);\n var rectangle_width = (log(i+1)-log(i))*(width/log(spectrum.length));\n rect(x, height, rectangle_width, -h )\n}\n\nvar nyquist = 22050;\n\n// get the centroid\nspectralCentroid = fft.getCentroid();\n\n// the mean_freq_index calculation is for the display.\nvar mean_freq_index = spectralCentroid/(nyquist/spectrum.length);\n\ncentroidplot = map(log(mean_freq_index), 0, log(spectrum.length), 0, width);\n\n\nstroke(255,0,0); // the line showing where the centroid is will be red\n\nrect(centroidplot, 0, width / spectrum.length, height)\nnoStroke();\nfill(255,255,255); // text is white\ntext(\"centroid: \", 10, 20);\ntext(round(spectralCentroid)+\" Hz\", 10, 40);\n}\n </code></div>"],"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2970,"description":"<p>Smooth FFT analysis by averaging with the last analysis frame.</p>\n","itemtype":"method","name":"smooth","params":[{"name":"smoothing","description":"<p>0.0 &lt; smoothing &lt; 1.0.\n Defaults to 0.8.</p>\n","type":"Number"}],"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":2992,"description":"<p>Returns an array of average amplitude values for a given number\nof frequency bands split equally. N defaults to 16.\n<em>NOTE: analyze() must be called prior to linAverages(). Analyze()\ntells the FFT to analyze frequency data, and linAverages() uses\nthe results to group them into a smaller set of averages.</em></p></p>\n","itemtype":"method","name":"linAverages","params":[{"name":"N","description":"<p>Number of returned frequency groups</p>\n","type":"Number"}],"return":{"description":"linearAverages Array of average amplitude values for each group","type":"Array"},"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":3022,"description":"<p>Returns an array of average amplitude values of the spectrum, for a given\nset of <a href=\"https://en.wikipedia.org/wiki/Octave_band\" target=\"_blank\">\nOctave Bands</a>\n<em>NOTE: analyze() must be called prior to logAverages(). Analyze()\ntells the FFT to analyze frequency data, and logAverages() uses\nthe results to group them into a smaller set of averages.</em></p></p>\n","itemtype":"method","name":"logAverages","params":[{"name":"octaveBands","description":"<p>Array of Octave Bands objects for grouping</p>\n","type":"Array"}],"return":{"description":"logAverages Array of average amplitude values for each group","type":"Array"},"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":3052,"description":"<p>Calculates and Returns the 1/N\n<a href=\"https://en.wikipedia.org/wiki/Octave_band\" target=\"_blank\">Octave Bands</a>\nN defaults to 3 and minimum central frequency to 15.625Hz.\n(1/3 Octave Bands ~= 31 Frequency Bands)\nSetting fCtr0 to a central value of a higher octave will ignore the lower bands\nand produce less frequency groups.</p>\n","itemtype":"method","name":"getOctaveBands","params":[{"name":"N","description":"<p>Specifies the 1/N type of generated octave bands</p>\n","type":"Number"},{"name":"fCtr0","description":"<p>Minimum central frequency for the lowest band</p>\n","type":"Number"}],"return":{"description":"octaveBands Array of octave band objects with their bounds","type":"Array"},"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":3110,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":3487,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":3508,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":3567,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":3885,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4057,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4215,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4256,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4326,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4514,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4571,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4739,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4787,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4818,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4839,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4859,"class":"p5.FFT","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4961,"description":"<p>Fade to value, for smooth transitions</p>\n","itemtype":"method","name":"fade","params":[{"name":"value","description":"<p>Value to set this signal</p>\n","type":"Number"},{"name":"secondsFromNow","description":"<p>Length of fade, in seconds from now</p>\n","type":"Number","optional":true}],"class":"p5.Signal","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4972,"description":"<p>Connect a p5.sound object or Web Audio node to this\np5.Signal so that its amplitude values can be scaled.</p>\n","itemtype":"method","name":"setInput","params":[{"name":"input","description":"","type":"Object"}],"class":"p5.Signal","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":4986,"description":"<p>Add a constant value to this audio signal,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalAdd.</p>\n","itemtype":"method","name":"add","params":[{"name":"number","description":"","type":"Number"}],"return":{"description":"object","type":"p5.Signal"},"class":"p5.Signal","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5005,"description":"<p>Multiply this signal by a constant value,\nand return the resulting audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalMult.</p>\n","itemtype":"method","name":"mult","params":[{"name":"number","description":"<p>to multiply</p>\n","type":"Number"}],"return":{"description":"object","type":"p5.Signal"},"class":"p5.Signal","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5024,"description":"<p>Scale this signal value to a given range,\nand return the result as an audio signal. Does\nnot change the value of the original signal,\ninstead it returns a new p5.SignalScale.</p>\n","itemtype":"method","name":"scale","params":[{"name":"number","description":"<p>to multiply</p>\n","type":"Number"},{"name":"inMin","description":"<p>input range minumum</p>\n","type":"Number"},{"name":"inMax","description":"<p>input range maximum</p>\n","type":"Number"},{"name":"outMin","description":"<p>input range minumum</p>\n","type":"Number"},{"name":"outMax","description":"<p>input range maximum</p>\n","type":"Number"}],"return":{"description":"object","type":"p5.Signal"},"class":"p5.Signal","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5158,"description":"<p>Start an oscillator. Accepts an optional parameter to\ndetermine how long (in seconds from now) until the\noscillator starts.</p>\n","itemtype":"method","name":"start","params":[{"name":"time","description":"<p>startTime in seconds from now.</p>\n","type":"Number","optional":true},{"name":"frequency","description":"<p>frequency in Hz.</p>\n","type":"Number","optional":true}],"class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5198,"description":"<p>Stop an oscillator. Accepts an optional parameter\nto determine how long (in seconds from now) until the\noscillator stops.</p>\n","itemtype":"method","name":"stop","params":[{"name":"secondsFromNow","description":"<p>Time, in seconds from now.</p>\n","type":"Number"}],"class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5214,"description":"<p>Set the amplitude between 0 and 1.0. Or, pass in an object\nsuch as an oscillator to modulate amplitude with an audio signal.</p>\n","itemtype":"method","name":"amp","params":[{"name":"vol","description":"<p>between 0 and 1.0\n or a modulating signal/oscillator</p>\n","type":"Number|Object"},{"name":"rampTime","description":"<p>create a fade that lasts rampTime</p>\n","type":"Number","optional":true},{"name":"timeFromNow","description":"<p>schedule this event to happen\n seconds from now</p>\n","type":"Number","optional":true}],"return":{"description":"gain If no value is provided,\n returns the Web Audio API\n AudioParam that controls\n this oscillator's\n gain/amplitude/volume)","type":"AudioParam"},"class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5249,"description":"<p>Set frequency of an oscillator to a value. Or, pass in an object\nsuch as an oscillator to modulate the frequency with an audio signal.</p>\n","itemtype":"method","name":"freq","params":[{"name":"Frequency","description":"<p>Frequency in Hz\n or modulating signal/oscillator</p>\n","type":"Number|Object"},{"name":"rampTime","description":"<p>Ramp time (in seconds)</p>\n","type":"Number","optional":true},{"name":"timeFromNow","description":"<p>Schedule this event to happen\n at x seconds from now</p>\n","type":"Number","optional":true}],"return":{"description":"Frequency If no value is provided,\n returns the Web Audio API\n AudioParam that controls\n this oscillator's frequency","type":"AudioParam"},"example":["\n<div><code>\nvar osc = new p5.Oscillator(300);\nosc.start();\nosc.freq(40, 10);\n</code></div>"],"class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5308,"description":"<p>Set type to &#39;sine&#39;, &#39;triangle&#39;, &#39;sawtooth&#39; or &#39;square&#39;.</p>\n","itemtype":"method","name":"setType","params":[{"name":"type","description":"<p>&#39;sine&#39;, &#39;triangle&#39;, &#39;sawtooth&#39; or &#39;square&#39;.</p>\n","type":"String"}],"class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5320,"description":"<p>Connect to a p5.sound / Web Audio object.</p>\n","itemtype":"method","name":"connect","params":[{"name":"unit","description":"<p>A p5.sound or Web Audio object</p>\n","type":"Object"}],"class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5337,"description":"<p>Disconnect all outputs</p>\n","itemtype":"method","name":"disconnect","class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5354,"description":"<p>Pan between Left (-1) and Right (1)</p>\n","itemtype":"method","name":"pan","params":[{"name":"panning","description":"<p>Number between -1 and 1</p>\n","type":"Number"},{"name":"timeFromNow","description":"<p>schedule this event to happen\n seconds from now</p>\n","type":"Number"}],"class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5386,"description":"<p>Set the phase of an oscillator between 0.0 and 1.0.\nIn this implementation, phase is a delay time\nbased on the oscillator&#39;s current frequency.</p>\n","itemtype":"method","name":"phase","params":[{"name":"phase","description":"<p>float between 0.0 and 1.0</p>\n","type":"Number"}],"class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5440,"description":"<p>Add a value to the p5.Oscillator&#39;s output amplitude,\nand return the oscillator. Calling this method again\nwill override the initial add() with a new value.</p>\n","itemtype":"method","name":"add","params":[{"name":"number","description":"<p>Constant number to add</p>\n","type":"Number"}],"return":{"description":"Oscillator Returns this oscillator\n with scaled output","type":"p5.Oscillator"},"class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5457,"description":"<p>Multiply the p5.Oscillator&#39;s output amplitude\nby a fixed value (i.e. turn it up!). Calling this method\nagain will override the initial mult() with a new value.</p>\n","itemtype":"method","name":"mult","params":[{"name":"number","description":"<p>Constant number to multiply</p>\n","type":"Number"}],"return":{"description":"Oscillator Returns this oscillator\n with multiplied output","type":"p5.Oscillator"},"class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5473,"description":"<p>Scale this oscillator&#39;s amplitude values to a given\nrange, and return the oscillator. Calling this method\nagain will override the initial scale() with new values.</p>\n","itemtype":"method","name":"scale","params":[{"name":"inMin","description":"<p>input range minumum</p>\n","type":"Number"},{"name":"inMax","description":"<p>input range maximum</p>\n","type":"Number"},{"name":"outMin","description":"<p>input range minumum</p>\n","type":"Number"},{"name":"outMax","description":"<p>input range maximum</p>\n","type":"Number"}],"return":{"description":"Oscillator Returns this oscillator\n with scaled output","type":"p5.Oscillator"},"class":"p5.Oscillator","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5572,"class":"p5.SqrOsc","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":5775,"class":"p5.SqrOsc","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6064,"description":"<p>Time until envelope reaches attackLevel</p>\n","itemtype":"property","name":"attackTime","class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6069,"description":"<p>Level once attack is complete.</p>\n","itemtype":"property","name":"attackLevel","class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6074,"description":"<p>Time until envelope reaches decayLevel.</p>\n","itemtype":"property","name":"decayTime","class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6079,"description":"<p>Level after decay. The envelope will sustain here until it is released.</p>\n","itemtype":"property","name":"decayLevel","class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6084,"description":"<p>Duration of the release portion of the envelope.</p>\n","itemtype":"property","name":"releaseTime","class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6089,"description":"<p>Level at the end of the release.</p>\n","itemtype":"property","name":"releaseLevel","class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6125,"description":"<p>Reset the envelope with a series of time/value pairs.</p>\n","itemtype":"method","name":"set","params":[{"name":"attackTime","description":"<p>Time (in seconds) before level\n reaches attackLevel</p>\n","type":"Number"},{"name":"attackLevel","description":"<p>Typically an amplitude between\n 0.0 and 1.0</p>\n","type":"Number"},{"name":"decayTime","description":"<p>Time</p>\n","type":"Number"},{"name":"decayLevel","description":"<p>Amplitude (In a standard ADSR envelope,\n decayLevel = sustainLevel)</p>\n","type":"Number"},{"name":"releaseTime","description":"<p>Release Time (in seconds)</p>\n","type":"Number"},{"name":"releaseLevel","description":"<p>Amplitude</p>\n","type":"Number"}],"example":["\n<div><code>\nvar t1 = 0.1; // attack time in seconds\nvar l1 = 0.7; // attack level 0.0 to 1.0\nvar t2 = 0.3; // decay time in seconds\nvar l2 = 0.1; // decay level 0.0 to 1.0\nvar t3 = 0.2; // sustain time in seconds\nvar l3 = 0.5; // sustain level 0.0 to 1.0\n// release level defaults to zero\n\nvar env;\nvar triOsc;\n\nfunction setup() {\n background(0);\n noStroke();\n fill(255);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope(t1, l1, t2, l2, t3, l3);\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env); // give the env control of the triOsc's amp\n triOsc.start();\n}\n\n// mouseClick triggers envelope if over canvas\nfunction mouseClicked() {\n // is mouse over canvas?\n if (mouseX > 0 && mouseX < width && mouseY > 0 && mouseY < height) {\n env.play(triOsc);\n }\n}\n</code></div>\n"],"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6184,"description":"<p>Set values like a traditional\n<a href=\"https://en.wikipedia.org/wiki/Synthesizer#/media/File:ADSR_parameter.svg\">\nADSR envelope\n</a>.</p>\n","itemtype":"method","name":"setADSR","params":[{"name":"attackTime","description":"<p>Time (in seconds before envelope\n reaches Attack Level</p>\n","type":"Number"},{"name":"decayTime","description":"<p>Time (in seconds) before envelope\n reaches Decay/Sustain Level</p>\n","type":"Number","optional":true},{"name":"susRatio","description":"<p>Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using <code>setRange</code>),\n then decayLevel would increase proportionally, to become 0.5.</p>\n","type":"Number","optional":true},{"name":"releaseTime","description":"<p>Time in seconds from now (defaults to 0)</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n</code></div>"],"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6249,"description":"<p>Set max (attackLevel) and min (releaseLevel) of envelope.</p>\n","itemtype":"method","name":"setRange","params":[{"name":"aLevel","description":"<p>attack level (defaults to 1)</p>\n","type":"Number"},{"name":"rLevel","description":"<p>release level (defaults to 0)</p>\n","type":"Number"}],"example":["\n<div><code>\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n env.play();\n}\n</code></div>"],"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6328,"description":"<p>Assign a parameter to be controlled by this envelope.\nIf a p5.Sound object is given, then the p5.Envelope will control its\noutput gain. If multiple inputs are provided, the env will\ncontrol all of them.</p>\n","itemtype":"method","name":"setInput","params":[{"name":"inputs","description":"<p>A p5.sound object or\n Web Audio Param.</p>\n","type":"Object","optional":true,"multiple":true}],"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6343,"description":"<p>Set whether the envelope ramp is linear (default) or exponential.\nExponential ramps can be useful because we perceive amplitude\nand frequency logarithmically.</p>\n","itemtype":"method","name":"setExp","params":[{"name":"isExp","description":"<p>true is exponential, false is linear</p>\n","type":"Boolean"}],"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6361,"description":"<p>Play tells the envelope to start acting on a given input.\nIf the input is a p5.sound object (i.e. AudioIn, Oscillator,\nSoundFile), then Envelope will control its output volume.\nEnvelopes can also be used to control any <a href=\"\nhttp://docs.webplatform.org/wiki/apis/webaudio/AudioParam\">\nWeb Audio Audio Param.</a></p>\n","itemtype":"method","name":"play","params":[{"name":"unit","description":"<p>A p5.sound object or\n Web Audio Param.</p>\n","type":"Object"},{"name":"startTime","description":"<p>time from now (in seconds) at which to play</p>\n","type":"Number","optional":true},{"name":"sustainTime","description":"<p>time to sustain before releasing the envelope</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.2;\nvar susPercent = 0.2;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(playEnv);\n}\n\nfunction playEnv(){\n // trigger env on triOsc, 0 seconds from now\n // After decay, sustain for 0.2 seconds before release\n env.play(triOsc, 0, 0.2);\n}\n</code></div>"],"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6422,"description":"<p>Trigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go. Input can be\nany p5.sound object, or a <a href=\"\nhttp://docs.webplatform.org/wiki/apis/webaudio/AudioParam\">\nWeb Audio Param</a>.</p>\n","itemtype":"method","name":"triggerAttack","params":[{"name":"unit","description":"<p>p5.sound Object or Web Audio Param</p>\n","type":"Object"},{"name":"secondsFromNow","description":"<p>time from now (in seconds)</p>\n","type":"Number"}],"example":["\n<div><code>\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.3;\nvar susPercent = 0.4;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack(){\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\n</code></div>"],"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6529,"description":"<p>Trigger the Release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.</p>\n","itemtype":"method","name":"triggerRelease","params":[{"name":"unit","description":"<p>p5.sound Object or Web Audio Param</p>\n","type":"Object"},{"name":"secondsFromNow","description":"<p>time to trigger the release</p>\n","type":"Number"}],"example":["\n<div><code>\n\nvar attackLevel = 1.0;\nvar releaseLevel = 0;\n\nvar attackTime = 0.001\nvar decayTime = 0.3;\nvar susPercent = 0.4;\nvar releaseTime = 0.5;\n\nvar env, triOsc;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n background(200);\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime, susPercent, releaseTime);\n env.setRange(attackLevel, releaseLevel);\n\n triOsc = new p5.Oscillator('triangle');\n triOsc.amp(env);\n triOsc.start();\n triOsc.freq(220);\n\n cnv.mousePressed(envAttack);\n}\n\nfunction envAttack(){\n console.log('trigger attack');\n env.triggerAttack();\n\n background(0,255,0);\n text('attack!', width/2, height/2);\n}\n\nfunction mouseReleased() {\n env.triggerRelease();\n\n background(200);\n text('click to play', width/2, height/2);\n}\n</code></div>"],"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6626,"description":"<p>Exponentially ramp to a value using the first two\nvalues from <code><a href=\"#/p5.Envelope/setADSR\">setADSR(attackTime, decayTime)</a></code>\nas <a href=\"https://en.wikipedia.org/wiki/RC_time_constant\">\ntime constants</a> for simple exponential ramps.\nIf the value is higher than current value, it uses attackTime,\nwhile a decrease uses decayTime.</p>\n","itemtype":"method","name":"ramp","params":[{"name":"unit","description":"<p>p5.sound Object or Web Audio Param</p>\n","type":"Object"},{"name":"secondsFromNow","description":"<p>When to trigger the ramp</p>\n","type":"Number"},{"name":"v","description":"<p>Target value</p>\n","type":"Number"},{"name":"v2","description":"<p>Second target value (optional)</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar env, osc, amp, cnv;\n\nvar attackTime = 0.001;\nvar decayTime = 0.2;\nvar attackLevel = 1;\nvar decayLevel = 0;\n\nfunction setup() {\n cnv = createCanvas(100, 100);\n fill(0,255,0);\n noStroke();\n\n env = new p5.Envelope();\n env.setADSR(attackTime, decayTime);\n\n osc = new p5.Oscillator();\n osc.amp(env);\n osc.start();\n\n amp = new p5.Amplitude();\n\n cnv.mousePressed(triggerRamp);\n}\n\nfunction triggerRamp() {\n env.ramp(osc, 0, attackLevel, decayLevel);\n}\n\nfunction draw() {\n background(20,20,20);\n text('click me', 10, 20);\n var h = map(amp.getLevel(), 0, 0.4, 0, height);;\n\n rect(0, height, width, -h);\n}\n</code></div>"],"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6733,"description":"<p>Add a value to the p5.Oscillator&#39;s output amplitude,\nand return the oscillator. Calling this method\nagain will override the initial add() with new values.</p>\n","itemtype":"method","name":"add","params":[{"name":"number","description":"<p>Constant number to add</p>\n","type":"Number"}],"return":{"description":"Envelope Returns this envelope\n with scaled output","type":"p5.Envelope"},"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6749,"description":"<p>Multiply the p5.Envelope&#39;s output amplitude\nby a fixed value. Calling this method\nagain will override the initial mult() with new values.</p>\n","itemtype":"method","name":"mult","params":[{"name":"number","description":"<p>Constant number to multiply</p>\n","type":"Number"}],"return":{"description":"Envelope Returns this envelope\n with scaled output","type":"p5.Envelope"},"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6765,"description":"<p>Scale this envelope&#39;s amplitude values to a given\nrange, and return the envelope. Calling this method\nagain will override the initial scale() with new values.</p>\n","itemtype":"method","name":"scale","params":[{"name":"inMin","description":"<p>input range minumum</p>\n","type":"Number"},{"name":"inMax","description":"<p>input range maximum</p>\n","type":"Number"},{"name":"outMin","description":"<p>input range minumum</p>\n","type":"Number"},{"name":"outMax","description":"<p>input range maximum</p>\n","type":"Number"}],"return":{"description":"Envelope Returns this envelope\n with scaled output","type":"p5.Envelope"},"class":"p5.Envelope","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":6873,"description":"<p>Set the width of a Pulse object (an oscillator that implements\nPulse Width Modulation).</p>\n","itemtype":"method","name":"width","params":[{"name":"width","description":"<p>Width between the pulses (0 to 1.0,\n defaults to 0)</p>\n","type":"Number","optional":true}],"class":"p5.Pulse","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7060,"description":"<p>Set type of noise to &#39;white&#39;, &#39;pink&#39; or &#39;brown&#39;.\nWhite is the default.</p>\n","itemtype":"method","name":"setType","params":[{"name":"type","description":"<p>&#39;white&#39;, &#39;pink&#39; or &#39;brown&#39;</p>\n","type":"String","optional":true}],"class":"p5.Noise","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7178,"description":"<p>Client must allow browser to access their microphone / audioin source.\nDefault: false. Will become true when the client enables acces.</p>\n","itemtype":"property","name":"enabled","type":"Boolean","class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7194,"description":"<p>Start processing audio input. This enables the use of other\nAudioIn methods like getLevel(). Note that by default, AudioIn\nis not connected to p5.sound&#39;s output. So you won&#39;t hear\nanything unless you use the connect() method.<br/></p>\n<p>Certain browsers limit access to the user&#39;s microphone. For example,\nChrome only allows access from localhost and over https. For this reason,\nyou may want to include an errorCallback—a function that is called in case\nthe browser won&#39;t provide mic access.</p>\n","itemtype":"method","name":"start","params":[{"name":"successCallback","description":"<p>Name of a function to call on\n success.</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>Name of a function to call if\n there was an error. For example,\n some browsers do not support\n getUserMedia.</p>\n","type":"Function","optional":true}],"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7247,"description":"<p>Turn the AudioIn off. If the AudioIn is stopped, it cannot getLevel().\nIf re-starting, the user may be prompted for permission access.</p>\n","itemtype":"method","name":"stop","class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7263,"description":"<p>Connect to an audio unit. If no parameter is provided, will\nconnect to the master output (i.e. your speakers).<br/></p>\n","itemtype":"method","name":"connect","params":[{"name":"unit","description":"<p>An object that accepts audio input,\n such as an FFT</p>\n","type":"Object","optional":true}],"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7284,"description":"<p>Disconnect the AudioIn from all audio units. For example, if\nconnect() had been called, disconnect() will stop sending\nsignal to your speakers.<br/></p>\n","itemtype":"method","name":"disconnect","class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7298,"description":"<p>Read the Amplitude (volume level) of an AudioIn. The AudioIn\nclass contains its own instance of the Amplitude class to help\nmake it easy to get a microphone&#39;s volume level. Accepts an\noptional smoothing value (0.0 &lt; 1.0). <em>NOTE: AudioIn must\n.start() before using .getLevel().</em><br/></p>\n","itemtype":"method","name":"getLevel","params":[{"name":"smoothing","description":"<p>Smoothing is 0.0 by default.\n Smooths values based on previous values.</p>\n","type":"Number","optional":true}],"return":{"description":"Volume level (between 0.0 and 1.0)","type":"Number"},"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7316,"description":"<p>Set amplitude (volume) of a mic input between 0 and 1.0. <br/></p>\n","itemtype":"method","name":"amp","params":[{"name":"vol","description":"<p>between 0 and 1.0</p>\n","type":"Number"},{"name":"time","description":"<p>ramp time (optional)</p>\n","type":"Number","optional":true}],"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7335,"description":"<p>Returns a list of available input sources. This is a wrapper\nfor &lt;a title=&quot;MediaDevices.enumerateDevices() - Web APIs | MDN&quot; target=&quot;_blank&quot; href=\n &quot;<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices\">https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices</a>&quot;</p>\n<blockquote>\n<p>and it returns a Promise.</p>\n</blockquote>\n","itemtype":"method","name":"getSources","params":[{"name":"successCallback","description":"<p>This callback function handles the sources when they\n have been enumerated. The callback function\n receives the deviceList array as its only argument</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>This optional callback receives the error\n message as its argument.</p>\n","type":"Function","optional":true}],"return":{"description":"Returns a Promise that can be used in place of the callbacks, similar\n to the enumerateDevices() method","type":"Promise"},"example":["\n <div><code>\n var audiograb;\n\n function setup(){\n //new audioIn\n audioGrab = new p5.AudioIn();\n\n audioGrab.getSources(function(deviceList) {\n //print out the array of available sources\n console.log(deviceList);\n //set the source to the first item in the deviceList array\n audioGrab.setSource(0);\n });\n }\n </code></div>"],"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7386,"description":"<p>Set the input source. Accepts a number representing a\nposition in the array returned by getSources().\nThis is only available in browsers that support\n&lt;a title=&quot;MediaDevices.enumerateDevices() - Web APIs | MDN&quot; target=&quot;_blank&quot; href=\n&quot;<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices\">https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices</a>&quot;</p>\n<blockquote>\n<p>navigator.mediaDevices.enumerateDevices()</a>.<br/></p>\n</blockquote>\n","itemtype":"method","name":"setSource","params":[{"name":"num","description":"<p>position of input source in the array</p>\n","type":"Number"}],"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7426,"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7442,"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7466,"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7492,"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7514,"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7536,"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7582,"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7613,"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7631,"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7968,"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":7990,"class":"p5.AudioIn","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8066,"description":"<p>In classes that extend\np5.Effect, connect effect nodes\nto the wet parameter</p>\n","class":"p5.Effect","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8079,"description":"<p>Set the output volume of the filter.</p>\n","itemtype":"method","name":"amp","params":[{"name":"vol","description":"<p>amplitude between 0 and 1.0</p>\n","type":"Number","optional":true},{"name":"rampTime","description":"<p>create a fade that lasts until rampTime</p>\n","type":"Number","optional":true},{"name":"tFromNow","description":"<p>schedule this event to happen in tFromNow seconds</p>\n","type":"Number","optional":true}],"class":"p5.Effect","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8096,"description":"<p>Link effects together in a chain<br>Example usage: filter.chain(reverb, delay, panner);\nMay be used with an open-ended number of arguments</p>\n","itemtype":"method","name":"chain","params":[{"name":"arguments","description":"<p>Chain together multiple sound objects</p>\n","type":"Object","optional":true}],"class":"p5.Effect","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8113,"description":"<p>Adjust the dry/wet value.</p>\n","itemtype":"method","name":"drywet","params":[{"name":"fade","description":"<p>The desired drywet value (0 - 1.0)</p>\n","type":"Number","optional":true}],"class":"p5.Effect","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8125,"description":"<p>Send output to a p5.js-sound, Web Audio Node, or use signal to\ncontrol an AudioParam</p>\n","itemtype":"method","name":"connect","params":[{"name":"unit","description":"","type":"Object"}],"class":"p5.Effect","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8136,"description":"<p>Disconnect all output.</p>\n","itemtype":"method","name":"disconnect","class":"p5.Effect","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8254,"description":"<p>The p5.Filter is built with a\n<a href=\"http://www.w3.org/TR/webaudio/#BiquadFilterNode\">\nWeb Audio BiquadFilter Node</a>.</p>\n","itemtype":"property","name":"biquadFilter","type":"DelayNode","class":"p5.Filter","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8272,"description":"<p>Filter an audio signal according to a set\nof filter parameters.</p>\n","itemtype":"method","name":"process","params":[{"name":"Signal","description":"<p>An object that outputs audio</p>\n","type":"Object"},{"name":"freq","description":"<p>Frequency in Hz, from 10 to 22050</p>\n","type":"Number","optional":true},{"name":"res","description":"<p>Resonance/Width of the filter frequency\n from 0.001 to 1000</p>\n","type":"Number","optional":true}],"class":"p5.Filter","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8286,"description":"<p>Set the frequency and the resonance of the filter.</p>\n","itemtype":"method","name":"set","params":[{"name":"freq","description":"<p>Frequency in Hz, from 10 to 22050</p>\n","type":"Number","optional":true},{"name":"res","description":"<p>Resonance (Q) from 0.001 to 1000</p>\n","type":"Number","optional":true},{"name":"timeFromNow","description":"<p>schedule this event to happen\n seconds from now</p>\n","type":"Number","optional":true}],"class":"p5.Filter","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8303,"description":"<p>Set the filter frequency, in Hz, from 10 to 22050 (the range of\nhuman hearing, although in reality most people hear in a narrower\nrange).</p>\n","itemtype":"method","name":"freq","params":[{"name":"freq","description":"<p>Filter Frequency</p>\n","type":"Number"},{"name":"timeFromNow","description":"<p>schedule this event to happen\n seconds from now</p>\n","type":"Number","optional":true}],"return":{"description":"value Returns the current frequency value","type":"Number"},"class":"p5.Filter","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8328,"description":"<p>Controls either width of a bandpass frequency,\nor the resonance of a low/highpass cutoff frequency.</p>\n","itemtype":"method","name":"res","params":[{"name":"res","description":"<p>Resonance/Width of filter freq\n from 0.001 to 1000</p>\n","type":"Number"},{"name":"timeFromNow","description":"<p>schedule this event to happen\n seconds from now</p>\n","type":"Number","optional":true}],"return":{"description":"value Returns the current res value","type":"Number"},"class":"p5.Filter","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8350,"description":"<p>Controls the gain attribute of a Biquad Filter.\nThis is distinctly different from .amp() which is inherited from p5.Effect\n.amp() controls the volume via the output gain node\np5.Filter.gain() controls the gain parameter of a Biquad Filter node.</p>\n","itemtype":"method","name":"gain","params":[{"name":"gain","description":"","type":"Number"}],"return":{"description":"Returns the current or updated gain value","type":"Number"},"class":"p5.Filter","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8371,"description":"<p>Toggle function. Switches between the specified type and allpass</p>\n","itemtype":"method","name":"toggle","return":{"description":"[Toggle value]","type":"Boolean"},"class":"p5.Filter","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8386,"description":"<p>Set the type of a p5.Filter. Possible types include:\n&quot;lowpass&quot; (default), &quot;highpass&quot;, &quot;bandpass&quot;,\n&quot;lowshelf&quot;, &quot;highshelf&quot;, &quot;peaking&quot;, &quot;notch&quot;,\n&quot;allpass&quot;.</p>\n","itemtype":"method","name":"setType","params":[{"name":"t","description":"","type":"String"}],"class":"p5.Filter","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8593,"description":"<p>The p5.EQ is built with abstracted p5.Filter objects.\nTo modify any bands, use methods of the <a \nhref=\"/reference/#/p5.Filter\" title=\"p5.Filter reference\">\np5.Filter</a> API, especially <code>gain</code> and <code>freq</code>.\nBands are stored in an array, with indices 0 - 3, or 0 - 7</p>\n","itemtype":"property","name":"bands","type":"Array","class":"p5.EQ","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8628,"description":"<p>Process an input by connecting it to the EQ</p>\n","itemtype":"method","name":"process","params":[{"name":"src","description":"<p>Audio source</p>\n","type":"Object"}],"class":"p5.EQ","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8716,"description":"<p><a title=\"Web Audio Panner docs\" href=\n\"https://developer.mozilla.org/en-US/docs/Web/API/PannerNode\">\nWeb Audio Spatial Panner Node</a></p>\n<p>Properties include</p>\n<ul>\n<li>&lt;a title=&quot;w3 spec for Panning Model&quot;\nhref=&quot;<a href=\"https://www.w3.org/TR/webaudio/#idl-def-PanningModelType\">https://www.w3.org/TR/webaudio/#idl-def-PanningModelType</a>&quot;<blockquote>\n<p>panningModel</a>: &quot;equal power&quot; or &quot;HRTF&quot;</p>\n</blockquote>\n</li>\n<li>&lt;a title=&quot;w3 spec for Distance Model&quot;\nhref=&quot;<a href=\"https://www.w3.org/TR/webaudio/#idl-def-DistanceModelType\">https://www.w3.org/TR/webaudio/#idl-def-DistanceModelType</a>&quot;<blockquote>\n<p>distanceModel</a>: &quot;linear&quot;, &quot;inverse&quot;, or &quot;exponential&quot;</p>\n</blockquote>\n</li>\n</ul>\n","itemtype":"property","name":"panner","type":"AudioNode","class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8739,"description":"<p>Connect an audio sorce</p>\n","itemtype":"method","name":"process","params":[{"name":"src","description":"<p>Input source</p>\n","type":"Object"}],"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8748,"description":"<p>Set the X,Y,Z position of the Panner</p>\n","itemtype":"method","name":"set","params":[{"name":"xVal","description":"","type":"Number"},{"name":"yVal","description":"","type":"Number"},{"name":"zVal","description":"","type":"Number"},{"name":"time","description":"","type":"Number"}],"return":{"description":"Updated x, y, z values as an array","type":"Array"},"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8767,"description":"<p>Getter and setter methods for position coordinates</p>\n","itemtype":"method","name":"positionX","return":{"description":"updated coordinate value","type":"Number"},"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8772,"description":"<p>Getter and setter methods for position coordinates</p>\n","itemtype":"method","name":"positionY","return":{"description":"updated coordinate value","type":"Number"},"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8777,"description":"<p>Getter and setter methods for position coordinates</p>\n","itemtype":"method","name":"positionZ","return":{"description":"updated coordinate value","type":"Number"},"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8815,"description":"<p>Set the X,Y,Z position of the Panner</p>\n","itemtype":"method","name":"orient","params":[{"name":"xVal","description":"","type":"Number"},{"name":"yVal","description":"","type":"Number"},{"name":"zVal","description":"","type":"Number"},{"name":"time","description":"","type":"Number"}],"return":{"description":"Updated x, y, z values as an array","type":"Array"},"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8834,"description":"<p>Getter and setter methods for orient coordinates</p>\n","itemtype":"method","name":"orientX","return":{"description":"updated coordinate value","type":"Number"},"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8839,"description":"<p>Getter and setter methods for orient coordinates</p>\n","itemtype":"method","name":"orientY","return":{"description":"updated coordinate value","type":"Number"},"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8844,"description":"<p>Getter and setter methods for orient coordinates</p>\n","itemtype":"method","name":"orientZ","return":{"description":"updated coordinate value","type":"Number"},"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8882,"description":"<p>Set the rolloff factor and max distance</p>\n","itemtype":"method","name":"setFalloff","params":[{"name":"maxDistance","description":"","type":"Number","optional":true},{"name":"rolloffFactor","description":"","type":"Number","optional":true}],"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8892,"description":"<p>Maxium distance between the source and the listener</p>\n","itemtype":"method","name":"maxDist","params":[{"name":"maxDistance","description":"","type":"Number"}],"return":{"description":"updated value","type":"Number"},"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":8904,"description":"<p>How quickly the volume is reduced as the source moves away from the listener</p>\n","itemtype":"method","name":"rollof","params":[{"name":"rolloffFactor","description":"","type":"Number"}],"return":{"description":"updated value","type":"Number"},"class":"p5.Panner3D","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9209,"description":"<p>The p5.Delay is built with two\n<a href=\"http://www.w3.org/TR/webaudio/#DelayNode\">\nWeb Audio Delay Nodes</a>, one for each stereo channel.</p>\n","itemtype":"property","name":"leftDelay","type":"DelayNode","class":"p5.Delay","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9217,"description":"<p>The p5.Delay is built with two\n<a href=\"http://www.w3.org/TR/webaudio/#DelayNode\">\nWeb Audio Delay Nodes</a>, one for each stereo channel.</p>\n","itemtype":"property","name":"rightDelay","type":"DelayNode","class":"p5.Delay","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9249,"description":"<p>Add delay to an audio signal according to a set\nof delay parameters.</p>\n","itemtype":"method","name":"process","params":[{"name":"Signal","description":"<p>An object that outputs audio</p>\n","type":"Object"},{"name":"delayTime","description":"<p>Time (in seconds) of the delay/echo.\n Some browsers limit delayTime to\n 1 second.</p>\n","type":"Number","optional":true},{"name":"feedback","description":"<p>sends the delay back through itself\n in a loop that decreases in volume\n each time.</p>\n","type":"Number","optional":true},{"name":"lowPass","description":"<p>Cutoff frequency. Only frequencies\n below the lowPass will be part of the\n delay.</p>\n","type":"Number","optional":true}],"class":"p5.Delay","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9284,"description":"<p>Set the delay (echo) time, in seconds. Usually this value will be\na floating point number between 0.0 and 1.0.</p>\n","itemtype":"method","name":"delayTime","params":[{"name":"delayTime","description":"<p>Time (in seconds) of the delay</p>\n","type":"Number"}],"class":"p5.Delay","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9303,"description":"<p>Feedback occurs when Delay sends its signal back through its input\nin a loop. The feedback amount determines how much signal to send each\ntime through the loop. A feedback greater than 1.0 is not desirable because\nit will increase the overall output each time through the loop,\ncreating an infinite feedback loop. The default value is 0.5</p>\n","itemtype":"method","name":"feedback","params":[{"name":"feedback","description":"<p>0.0 to 1.0, or an object such as an\n Oscillator that can be used to\n modulate this param</p>\n","type":"Number|Object"}],"return":{"description":"Feedback value","type":"Number"},"class":"p5.Delay","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9331,"description":"<p>Set a lowpass filter frequency for the delay. A lowpass filter\nwill cut off any frequencies higher than the filter frequency.</p>\n","itemtype":"method","name":"filter","params":[{"name":"cutoffFreq","description":"<p>A lowpass filter will cut off any\n frequencies higher than the filter frequency.</p>\n","type":"Number|Object"},{"name":"res","description":"<p>Resonance of the filter frequency\n cutoff, or an object (i.e. a p5.Oscillator)\n that can be used to modulate this parameter.\n High numbers (i.e. 15) will produce a resonance,\n low numbers (i.e. .2) will produce a slope.</p>\n","type":"Number|Object"}],"class":"p5.Delay","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9348,"description":"<p>Choose a preset type of delay. &#39;pingPong&#39; bounces the signal\nfrom the left to the right channel to produce a stereo effect.\nAny other parameter will revert to the default delay setting.</p>\n","itemtype":"method","name":"setType","params":[{"name":"type","description":"<p>&#39;pingPong&#39; (1) or &#39;default&#39; (0)</p>\n","type":"String|Number"}],"class":"p5.Delay","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9381,"description":"<p>Set the output level of the delay effect.</p>\n","itemtype":"method","name":"amp","params":[{"name":"volume","description":"<p>amplitude between 0 and 1.0</p>\n","type":"Number"},{"name":"rampTime","description":"<p>create a fade that lasts rampTime</p>\n","type":"Number","optional":true},{"name":"timeFromNow","description":"<p>schedule this event to happen\n seconds from now</p>\n","type":"Number","optional":true}],"class":"p5.Delay","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9390,"description":"<p>Send output to a p5.sound or web audio object</p>\n","itemtype":"method","name":"connect","params":[{"name":"unit","description":"","type":"Object"}],"class":"p5.Delay","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9396,"description":"<p>Disconnect all output.</p>\n","itemtype":"method","name":"disconnect","class":"p5.Delay","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9475,"description":"<p>Connect a source to the reverb, and assign reverb parameters.</p>\n","itemtype":"method","name":"process","params":[{"name":"src","description":"<p>p5.sound / Web Audio object with a sound\n output.</p>\n","type":"Object"},{"name":"seconds","description":"<p>Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.</p>\n","type":"Number","optional":true},{"name":"decayRate","description":"<p>Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.</p>\n","type":"Number","optional":true},{"name":"reverse","description":"<p>Play the reverb backwards or forwards.</p>\n","type":"Boolean","optional":true}],"class":"p5.Reverb","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9504,"description":"<p>Set the reverb settings. Similar to .process(), but without\nassigning a new input.</p>\n","itemtype":"method","name":"set","params":[{"name":"seconds","description":"<p>Duration of the reverb, in seconds.\n Min: 0, Max: 10. Defaults to 3.</p>\n","type":"Number","optional":true},{"name":"decayRate","description":"<p>Percentage of decay with each echo.\n Min: 0, Max: 100. Defaults to 2.</p>\n","type":"Number","optional":true},{"name":"reverse","description":"<p>Play the reverb backwards or forwards.</p>\n","type":"Boolean","optional":true}],"class":"p5.Reverb","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9532,"description":"<p>Set the output level of the reverb effect.</p>\n","itemtype":"method","name":"amp","params":[{"name":"volume","description":"<p>amplitude between 0 and 1.0</p>\n","type":"Number"},{"name":"rampTime","description":"<p>create a fade that lasts rampTime</p>\n","type":"Number","optional":true},{"name":"timeFromNow","description":"<p>schedule this event to happen\n seconds from now</p>\n","type":"Number","optional":true}],"class":"p5.Reverb","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9541,"description":"<p>Send output to a p5.sound or web audio object</p>\n","itemtype":"method","name":"connect","params":[{"name":"unit","description":"","type":"Object"}],"class":"p5.Reverb","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9547,"description":"<p>Disconnect all output.</p>\n","itemtype":"method","name":"disconnect","class":"p5.Reverb","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9641,"description":"<p>Internally, the p5.Convolver uses the a\n<a href=\"http://www.w3.org/TR/webaudio/#ConvolverNode\">\nWeb Audio Convolver Node</a>.</p>\n","itemtype":"property","name":"convolverNod","type":"ConvolverNode","class":"p5.Convolver","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9666,"description":"<p>Create a p5.Convolver. Accepts a path to a soundfile\nthat will be used to generate an impulse response.</p>\n","itemtype":"method","name":"createConvolver","params":[{"name":"path","description":"<p>path to a sound file</p>\n","type":"String"},{"name":"callback","description":"<p>function to call if loading is successful.\n The object will be passed in as the argument\n to the callback function.</p>\n","type":"Function","optional":true},{"name":"errorCallback","description":"<p>function to call if loading is not successful.\n A custom error will be passed in as the argument\n to the callback function.</p>\n","type":"Function","optional":true}],"return":{"description":"","type":"p5.Convolver"},"example":["\n<div><code>\nvar cVerb, sound;\nfunction preload() {\n // We have both MP3 and OGG versions of all sound assets\n soundFormats('ogg', 'mp3');\n\n // Try replacing 'bx-spring' with other soundfiles like\n // 'concrete-tunnel' 'small-plate' 'drum' 'beatbox'\n cVerb = createConvolver('assets/bx-spring.mp3');\n\n // Try replacing 'Damscray_DancingTiger' with\n // 'beat', 'doorbell', lucky_dragons_-_power_melody'\n sound = loadSound('assets/Damscray_DancingTiger.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\n</code></div>"],"class":"p5.Convolver","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9790,"description":"<p>Connect a source to the reverb, and assign reverb parameters.</p>\n","itemtype":"method","name":"process","params":[{"name":"src","description":"<p>p5.sound / Web Audio object with a sound\n output.</p>\n","type":"Object"}],"example":["\n<div><code>\nvar cVerb, sound;\nfunction preload() {\n soundFormats('ogg', 'mp3');\n\n cVerb = createConvolver('assets/concrete-tunnel.mp3');\n\n sound = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n // disconnect from master output...\n sound.disconnect();\n\n // ...and process with (i.e. connect to) cVerb\n // so that we only hear the convolution\n cVerb.process(sound);\n\n sound.play();\n}\n</code></div>"],"class":"p5.Convolver","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9822,"description":"<p>If you load multiple impulse files using the .addImpulse method,\nthey will be stored as Objects in this Array. Toggle between them\nwith the <code>toggleImpulse(id)</code> method.</p>\n","itemtype":"property","name":"impulses","type":"Array","class":"p5.Convolver","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9830,"description":"<p>Load and assign a new Impulse Response to the p5.Convolver.\nThe impulse is added to the <code>.impulses</code> array. Previous\nimpulses can be accessed with the <code>.toggleImpulse(id)</code>\nmethod.</p>\n","itemtype":"method","name":"addImpulse","params":[{"name":"path","description":"<p>path to a sound file</p>\n","type":"String"},{"name":"callback","description":"<p>function (optional)</p>\n","type":"Function"},{"name":"errorCallback","description":"<p>function (optional)</p>\n","type":"Function"}],"class":"p5.Convolver","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9848,"description":"<p>Similar to .addImpulse, except that the <code>.impulses</code>\nArray is reset to save memory. A new <code>.impulses</code>\narray is created with this impulse as the only item.</p>\n","itemtype":"method","name":"resetImpulse","params":[{"name":"path","description":"<p>path to a sound file</p>\n","type":"String"},{"name":"callback","description":"<p>function (optional)</p>\n","type":"Function"},{"name":"errorCallback","description":"<p>function (optional)</p>\n","type":"Function"}],"class":"p5.Convolver","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9866,"description":"<p>If you have used <code>.addImpulse()</code> to add multiple impulses\nto a p5.Convolver, then you can use this method to toggle between\nthe items in the <code>.impulses</code> Array. Accepts a parameter\nto identify which impulse you wish to use, identified either by its\noriginal filename (String) or by its position in the <code>.impulses\n</code> Array (Number).<br/>\nYou can access the objects in the .impulses Array directly. Each\nObject has two attributes: an <code>.audioBuffer</code> (type:\nWeb Audio <a href=\"\nhttp://webaudio.github.io/web-audio-api/#the-audiobuffer-interface\">\nAudioBuffer)</a> and a <code>.name</code>, a String that corresponds\nwith the original filename.</p>\n","itemtype":"method","name":"toggleImpulse","params":[{"name":"id","description":"<p>Identify the impulse by its original filename\n (String), or by its position in the\n <code>.impulses</code> Array (Number).</p>\n","type":"String|Number"}],"class":"p5.Convolver","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9912,"class":"p5.Convolver","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":9937,"class":"p5.Convolver","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10132,"description":"<p>Set the global tempo, in beats per minute, for all\np5.Parts. This method will impact all active p5.Parts.</p>\n","itemtype":"method","name":"setBPM","params":[{"name":"BPM","description":"<p>Beats Per Minute</p>\n","type":"Number"},{"name":"rampTime","description":"<p>Seconds from now</p>\n","type":"Number"}],"class":"p5.Convolver","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10222,"description":"<p>Array of values to pass into the callback\nat each step of the phrase. Depending on the callback\nfunction&#39;s requirements, these values may be numbers,\nstrings, or an object with multiple parameters.\nZero (0) indicates a rest.</p>\n","itemtype":"property","name":"sequence","type":"Array","class":"p5.Phrase","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10310,"description":"<p>Set the tempo of this part, in Beats Per Minute.</p>\n","itemtype":"method","name":"setBPM","params":[{"name":"BPM","description":"<p>Beats Per Minute</p>\n","type":"Number"},{"name":"rampTime","description":"<p>Seconds from now</p>\n","type":"Number","optional":true}],"class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10320,"description":"<p>Returns the Beats Per Minute of this currently part.</p>\n","itemtype":"method","name":"getBPM","return":{"description":"","type":"Number"},"class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10329,"description":"<p>Start playback of this part. It will play\nthrough all of its phrases at a speed\ndetermined by setBPM.</p>\n","itemtype":"method","name":"start","params":[{"name":"time","description":"<p>seconds from now</p>\n","type":"Number","optional":true}],"class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10345,"description":"<p>Loop playback of this part. It will begin\nlooping through all of its phrases at a speed\ndetermined by setBPM.</p>\n","itemtype":"method","name":"loop","params":[{"name":"time","description":"<p>seconds from now</p>\n","type":"Number","optional":true}],"class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10362,"description":"<p>Tell the part to stop looping.</p>\n","itemtype":"method","name":"noLoop","class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10374,"description":"<p>Stop the part and cue it to step 0.</p>\n","itemtype":"method","name":"stop","params":[{"name":"time","description":"<p>seconds from now</p>\n","type":"Number","optional":true}],"class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10384,"description":"<p>Pause the part. Playback will resume\nfrom the current step.</p>\n","itemtype":"method","name":"pause","params":[{"name":"time","description":"<p>seconds from now</p>\n","type":"Number"}],"class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10396,"description":"<p>Add a p5.Phrase to this Part.</p>\n","itemtype":"method","name":"addPhrase","params":[{"name":"phrase","description":"<p>reference to a p5.Phrase</p>\n","type":"p5.Phrase"}],"class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10417,"description":"<p>Remove a phrase from this part, based on the name it was\ngiven when it was created.</p>\n","itemtype":"method","name":"removePhrase","params":[{"name":"phraseName","description":"","type":"String"}],"class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10431,"description":"<p>Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.</p>\n","itemtype":"method","name":"getPhrase","params":[{"name":"phraseName","description":"","type":"String"}],"class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10445,"description":"<p>Get a phrase from this part, based on the name it was\ngiven when it was created. Now you can modify its array.</p>\n","itemtype":"method","name":"replaceSequence","params":[{"name":"phraseName","description":"","type":"String"},{"name":"sequence","description":"<p>Array of values to pass into the callback\n at each step of the phrase.</p>\n","type":"Array"}],"class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10473,"description":"<p>Fire a callback function at every step.</p>\n","itemtype":"method","name":"onStep","params":[{"name":"callback","description":"<p>The name of the callback\n you want to fire\n on every beat/tatum.</p>\n","type":"Function"}],"class":"p5.Part","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10526,"description":"<p>Start playback of the score.</p>\n","itemtype":"method","name":"start","class":"p5.Score","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10535,"description":"<p>Stop playback of the score.</p>\n","itemtype":"method","name":"stop","class":"p5.Score","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10545,"description":"<p>Pause playback of the score.</p>\n","itemtype":"method","name":"pause","class":"p5.Score","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10553,"description":"<p>Loop playback of the score.</p>\n","itemtype":"method","name":"loop","class":"p5.Score","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10562,"description":"<p>Stop looping playback of the score. If it\nis currently playing, this will go into effect\nafter the current round of playback completes.</p>\n","itemtype":"method","name":"noLoop","class":"p5.Score","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10587,"description":"<p>Set the tempo for all parts in the score</p>\n","itemtype":"method","name":"setBPM","params":[{"name":"BPM","description":"<p>Beats Per Minute</p>\n","type":"Number"},{"name":"rampTime","description":"<p>Seconds from now</p>\n","type":"Number"}],"class":"p5.Score","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10655,"description":"<p>musicalTimeMode uses <a href = \"https://github.com/Tonejs/Tone.js/wiki/Time\">Tone.Time</a> convention\ntrue if string, false if number</p>\n","itemtype":"property","name":"musicalTimeMode","type":"Boolean","class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10662,"description":"<p>musicalTimeMode variables\nmodify these only when the interval is specified in musicalTime format as a string</p>\n","class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10669,"description":"<p>Set a limit to the number of loops to play. defaults to Infinity</p>\n","itemtype":"property","name":"maxIterations","type":"Number","class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10678,"description":"<p>Do not initiate the callback if timeFromNow is &lt; 0\nThis ususually occurs for a few milliseconds when the page\nis not fully loaded</p>\n<p>The callback should only be called until maxIterations is reached</p>\n","class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10692,"description":"<p>Start the loop</p>\n","itemtype":"method","name":"start","params":[{"name":"timeFromNow","description":"<p>schedule a starting time</p>\n","type":"Number","optional":true}],"class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10705,"description":"<p>Stop the loop</p>\n","itemtype":"method","name":"stop","params":[{"name":"timeFromNow","description":"<p>schedule a stopping time</p>\n","type":"Number","optional":true}],"class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10718,"description":"<p>Pause the loop</p>\n","itemtype":"method","name":"pause","params":[{"name":"timeFromNow","description":"<p>schedule a pausing time</p>\n","type":"Number","optional":true}],"class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10731,"description":"<p>Synchronize loops. Use this method to start two more more loops in synchronization\nor to start a loop in synchronization with a loop that is already playing\nThis method will schedule the implicit loop in sync with the explicit master loop\ni.e. loopToStart.syncedStart(loopToSyncWith)</p>\n","itemtype":"method","name":"syncedStart","params":[{"name":"otherLoop","description":"<p>a p5.SoundLoop to sync with</p>\n","type":"Object"},{"name":"timeFromNow","description":"<p>Start the loops in sync after timeFromNow seconds</p>\n","type":"Number","optional":true}],"class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10812,"description":"<p>Getters and Setters, setting any paramter will result in a change in the clock&#39;s\nfrequency, that will be reflected after the next callback\nbeats per minute (defaults to 60)</p>\n","itemtype":"property","name":"bpm","type":"Number","class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10830,"description":"<p>number of quarter notes in a measure (defaults to 4)</p>\n","itemtype":"property","name":"timeSignature","type":"Number","class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10846,"description":"<p>length of the loops interval</p>\n","itemtype":"property","name":"interval","type":"Number|String","class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10860,"description":"<p>how many times the callback has been called so far</p>\n","itemtype":"property","name":"iterations","type":"Number","readonly":"","class":"p5.SoundLoop","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10901,"description":"<p>The p5.Compressor is built with a <a href=\"https://www.w3.org/TR/webaudio/#the-dynamicscompressornode-interface\" \n target=\"_blank\" title=\"W3 spec for Dynamics Compressor Node\">Web Audio Dynamics Compressor Node\n </a></p>\n","itemtype":"property","name":"compressor","type":"AudioNode","class":"p5.Compressor","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10912,"description":"<p>Performs the same function as .connect, but also accepts\noptional parameters to set compressor&#39;s audioParams</p>\n","itemtype":"method","name":"process","params":[{"name":"src","description":"<p>Sound source to be connected</p>\n","type":"Object"},{"name":"attack","description":"<p>The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1</p>\n","type":"Number","optional":true},{"name":"knee","description":"<p>A decibel value representing the range above the \n threshold where the curve smoothly transitions to the &quot;ratio&quot; portion.\n default = 30, range 0 - 40</p>\n","type":"Number","optional":true},{"name":"ratio","description":"<p>The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20</p>\n","type":"Number","optional":true},{"name":"threshold","description":"<p>The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0</p>\n","type":"Number","optional":true},{"name":"release","description":"<p>The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1</p>\n","type":"Number","optional":true}],"class":"p5.Compressor","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10935,"description":"<p>Set the paramters of a compressor.</p>\n","itemtype":"method","name":"set","params":[{"name":"attack","description":"<p>The amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1</p>\n","type":"Number"},{"name":"knee","description":"<p>A decibel value representing the range above the \n threshold where the curve smoothly transitions to the &quot;ratio&quot; portion.\n default = 30, range 0 - 40</p>\n","type":"Number"},{"name":"ratio","description":"<p>The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20</p>\n","type":"Number"},{"name":"threshold","description":"<p>The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0</p>\n","type":"Number"},{"name":"release","description":"<p>The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1</p>\n","type":"Number"}],"class":"p5.Compressor","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10967,"description":"<p>Get current attack or set value w/ time ramp</p>\n","itemtype":"method","name":"attack","params":[{"name":"attack","description":"<p>Attack is the amount of time (in seconds) to reduce the gain by 10dB,\n default = .003, range 0 - 1</p>\n","type":"Number","optional":true},{"name":"time","description":"<p>Assign time value to schedule the change in value</p>\n","type":"Number","optional":true}],"class":"p5.Compressor","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":10987,"description":"<p>Get current knee or set value w/ time ramp</p>\n","itemtype":"method","name":"knee","params":[{"name":"knee","description":"<p>A decibel value representing the range above the \n threshold where the curve smoothly transitions to the &quot;ratio&quot; portion.\n default = 30, range 0 - 40</p>\n","type":"Number","optional":true},{"name":"time","description":"<p>Assign time value to schedule the change in value</p>\n","type":"Number","optional":true}],"class":"p5.Compressor","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11007,"description":"<p>Get current ratio or set value w/ time ramp</p>\n","itemtype":"method","name":"ratio","params":[{"name":"ratio","description":"<p>The amount of dB change in input for a 1 dB change in output\n default = 12, range 1 - 20</p>\n","type":"Number","optional":true},{"name":"time","description":"<p>Assign time value to schedule the change in value</p>\n","type":"Number","optional":true}],"class":"p5.Compressor","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11026,"description":"<p>Get current threshold or set value w/ time ramp</p>\n","itemtype":"method","name":"threshold","params":[{"name":"threshold","description":"<p>The decibel value above which the compression will start taking effect\n default = -24, range -100 - 0</p>\n","type":"Number"},{"name":"time","description":"<p>Assign time value to schedule the change in value</p>\n","type":"Number","optional":true}],"class":"p5.Compressor","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11045,"description":"<p>Get current release or set value w/ time ramp</p>\n","itemtype":"method","name":"release","params":[{"name":"release","description":"<p>The amount of time (in seconds) to increase the gain by 10dB\n default = .25, range 0 - 1</p>\n","type":"Number"},{"name":"time","description":"<p>Assign time value to schedule the change in value</p>\n","type":"Number","optional":true}],"class":"p5.Compressor","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11065,"description":"<p>Return the current reduction value</p>\n","itemtype":"method","name":"reduction","return":{"description":"Value of the amount of gain reduction that is applied to the signal","type":"Number"},"class":"p5.Compressor","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11180,"description":"<p>Connect a specific device to the p5.SoundRecorder.\nIf no parameter is given, p5.SoundRecorer will record\nall audible p5.sound from your sketch.</p>\n","itemtype":"method","name":"setInput","params":[{"name":"unit","description":"<p>p5.sound object or a web audio unit\n that outputs sound</p>\n","type":"Object","optional":true}],"class":"p5.SoundRecorder","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11201,"description":"<p>Start recording. To access the recording, provide\na p5.SoundFile as the first parameter. The p5.SoundRecorder\nwill send its recording to that p5.SoundFile for playback once\nrecording is complete. Optional parameters include duration\n(in seconds) of the recording, and a callback function that\nwill be called once the complete recording has been\ntransfered to the p5.SoundFile.</p>\n","itemtype":"method","name":"record","params":[{"name":"soundFile","description":"<p>p5.SoundFile</p>\n","type":"p5.SoundFile"},{"name":"duration","description":"<p>Time (in seconds)</p>\n","type":"Number","optional":true},{"name":"callback","description":"<p>The name of a function that will be\n called once the recording completes</p>\n","type":"Function","optional":true}],"class":"p5.SoundRecorder","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11234,"description":"<p>Stop the recording. Once the recording is stopped,\nthe results will be sent to the p5.SoundFile that\nwas given on .record(), and if a callback function\nwas provided on record, that function will be called.</p>\n","itemtype":"method","name":"stop","class":"p5.SoundRecorder","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11307,"description":"<p>Save a p5.SoundFile as a .wav audio file.</p>\n","itemtype":"method","name":"saveSound","params":[{"name":"soundFile","description":"<p>p5.SoundFile that you wish to save</p>\n","type":"p5.SoundFile"},{"name":"name","description":"<p>name of the resulting .wav file.</p>\n","type":"String"}],"class":"p5.SoundRecorder","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11484,"description":"<p>isDetected is set to true when a peak is detected.</p>\n","itemtype":"attribute","name":"isDetected","type":"Boolean","default":"false","class":"p5.PeakDetect","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11497,"description":"<p>The update method is run in the draw loop.</p>\n<p>Accepts an FFT object. You must call .analyze()\non the FFT object prior to updating the peakDetect\nbecause it relies on a completed FFT analysis.</p>\n","itemtype":"method","name":"update","params":[{"name":"fftObject","description":"<p>A p5.FFT object</p>\n","type":"p5.FFT"}],"class":"p5.PeakDetect","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11528,"description":"<p>onPeak accepts two arguments: a function to call when\na peak is detected. The value of the peak,\nbetween 0.0 and 1.0, is passed to the callback.</p>\n","itemtype":"method","name":"onPeak","params":[{"name":"callback","description":"<p>Name of a function that will\n be called when a peak is\n detected.</p>\n","type":"Function"},{"name":"val","description":"<p>Optional value to pass\n into the function when\n a peak is detected.</p>\n","type":"Object","optional":true}],"example":["\n<div><code>\nvar cnv, soundFile, fft, peakDetect;\nvar ellipseWidth = 0;\n\nfunction preload() {\n soundFile = loadSound('assets/beat.mp3');\n}\n\nfunction setup() {\n cnv = createCanvas(100,100);\n textAlign(CENTER);\n\n fft = new p5.FFT();\n peakDetect = new p5.PeakDetect();\n\n setupSound();\n\n // when a beat is detected, call triggerBeat()\n peakDetect.onPeak(triggerBeat);\n}\n\nfunction draw() {\n background(0);\n fill(255);\n text('click to play', width/2, height/2);\n\n fft.analyze();\n peakDetect.update(fft);\n\n ellipseWidth *= 0.95;\n ellipse(width/2, height/2, ellipseWidth, ellipseWidth);\n}\n\n// this function is called by peakDetect.onPeak\nfunction triggerBeat() {\n ellipseWidth = 50;\n}\n\n// mouseclick starts/stops sound\nfunction setupSound() {\n cnv.mouseClicked( function() {\n if (soundFile.isPlaying() ) {\n soundFile.stop();\n } else {\n soundFile.play();\n }\n });\n}\n</code></div>"],"class":"p5.PeakDetect","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11677,"description":"<p>Connect a source to the gain node.</p>\n","itemtype":"method","name":"setInput","params":[{"name":"src","description":"<p>p5.sound / Web Audio object with a sound\n output.</p>\n","type":"Object"}],"class":"p5.Gain","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11687,"description":"<p>Send output to a p5.sound or web audio object</p>\n","itemtype":"method","name":"connect","params":[{"name":"unit","description":"","type":"Object"}],"class":"p5.Gain","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11697,"description":"<p>Disconnect all output.</p>\n","itemtype":"method","name":"disconnect","class":"p5.Gain","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11707,"description":"<p>Set the output level of the gain node.</p>\n","itemtype":"method","name":"amp","params":[{"name":"volume","description":"<p>amplitude between 0 and 1.0</p>\n","type":"Number"},{"name":"rampTime","description":"<p>create a fade that lasts rampTime</p>\n","type":"Number","optional":true},{"name":"timeFromNow","description":"<p>schedule this event to happen\n seconds from now</p>\n","type":"Number","optional":true}],"class":"p5.Gain","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11765,"description":"<p>Connect to p5 objects or Web Audio Nodes</p>\n","itemtype":"method","name":"connect","params":[{"name":"unit","description":"","type":"Object"}],"class":"p5.AudioVoice","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11774,"description":"<p>Disconnect from soundOut</p>\n","itemtype":"method","name":"disconnect","class":"p5.AudioVoice","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11860,"description":"<p>Play tells the MonoSynth to start playing a note. This method schedules\nthe calling of .triggerAttack and .triggerRelease.</p>\n","itemtype":"method","name":"play","params":[{"name":"note","description":"<p>the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format (&quot;C4&quot;, &quot;Eb3&quot;...etc&quot;)\n See <a href = \"https://github.com/Tonejs/Tone.js/wiki/Instruments\">\n Tone</a>. Defaults to 440 hz.</p>\n","type":"String | Number"},{"name":"velocity","description":"<p>velocity of the note to play (ranging from 0 to 1)</p>\n","type":"Number","optional":true},{"name":"secondsFromNow","description":"<p>time from now (in seconds) at which to play</p>\n","type":"Number","optional":true},{"name":"sustainTime","description":"<p>time to sustain before releasing the envelope</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar monoSynth;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n\n monoSynth = new p5.MonoSynth();\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n}\n\nfunction playSynth() {\n // time from now (in seconds)\n var time = 0;\n // note duration (in seconds)\n var dur = 1/6;\n // note velocity (volume, from 0 to 1)\n var v = random();\n\n monoSynth.play(\"Fb3\", v, 0, dur);\n monoSynth.play(\"Gb3\", v, time += dur, dur);\n\n background(random(255), random(255), 255);\n text('click to play', width/2, height/2);\n}\n</code></div>\n"],"class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11908,"description":"<p>Trigger the Attack, and Decay portion of the Envelope.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.</p>\n","params":[{"name":"note","description":"<p>the note you want to play, specified as a\n frequency in Hertz (Number) or as a midi\n value in Note/Octave format (&quot;C4&quot;, &quot;Eb3&quot;...etc&quot;)\n See <a href = \"https://github.com/Tonejs/Tone.js/wiki/Instruments\">\n Tone</a>. Defaults to 440 hz</p>\n","type":"String | Number"},{"name":"velocity","description":"<p>velocity of the note to play (ranging from 0 to 1)</p>\n","type":"Number","optional":true},{"name":"secondsFromNow","description":"<p>time from now (in seconds) at which to play</p>\n","type":"Number","optional":true}],"itemtype":"method","name":"triggerAttack","example":["\n<div><code>\nvar monoSynth = new p5.MonoSynth();\n\nfunction mousePressed() {\n monoSynth.triggerAttack(\"E3\");\n}\n\nfunction mouseReleased() {\n monoSynth.triggerRelease();\n}\n</code></div>"],"class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11942,"description":"<p>Trigger the release of the Envelope. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.</p>\n","params":[{"name":"secondsFromNow","description":"<p>time to trigger the release</p>\n","type":"Number"}],"itemtype":"method","name":"triggerRelease","example":["\n<div><code>\nvar monoSynth = new p5.MonoSynth();\n\nfunction mousePressed() {\n monoSynth.triggerAttack(\"E3\");\n}\n\nfunction mouseReleased() {\n monoSynth.triggerRelease();\n}\n</code></div>"],"class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11967,"description":"<p>Set values like a traditional\n<a href=\"https://en.wikipedia.org/wiki/Synthesizer#/media/File:ADSR_parameter.svg\">\nADSR envelope\n</a>.</p>\n","itemtype":"method","name":"setADSR","params":[{"name":"attackTime","description":"<p>Time (in seconds before envelope\n reaches Attack Level</p>\n","type":"Number"},{"name":"decayTime","description":"<p>Time (in seconds) before envelope\n reaches Decay/Sustain Level</p>\n","type":"Number","optional":true},{"name":"susRatio","description":"<p>Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using <code>setRange</code>),\n then decayLevel would increase proportionally, to become 0.5.</p>\n","type":"Number","optional":true},{"name":"releaseTime","description":"<p>Time in seconds from now (defaults to 0)</p>\n","type":"Number","optional":true}],"class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11991,"description":"<p>Getters and Setters</p>\n","itemtype":"property","name":"attack","type":"Number","class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11995,"itemtype":"property","name":"decay","type":"Number","class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":11998,"itemtype":"property","name":"sustain","type":"Number","class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12001,"itemtype":"property","name":"release","type":"Number","class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12038,"description":"<p>MonoSynth amp</p>\n","itemtype":"method","name":"amp","params":[{"name":"vol","description":"<p>desired volume</p>\n","type":"Number"},{"name":"rampTime","description":"<p>Time to reach new volume</p>\n","type":"Number","optional":true}],"return":{"description":"new volume value","type":"Number"},"class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12052,"description":"<p>Connect to a p5.sound / Web Audio object.</p>\n","itemtype":"method","name":"connect","params":[{"name":"unit","description":"<p>A p5.sound or Web Audio object</p>\n","type":"Object"}],"class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12062,"description":"<p>Disconnect all outputs</p>\n","itemtype":"method","name":"disconnect","class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12072,"description":"<p>Get rid of the MonoSynth and free up its resources / memory.</p>\n","itemtype":"method","name":"dispose","class":"p5.MonoSynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12145,"description":"<p>An object that holds information about which notes have been played and\nwhich notes are currently being played. New notes are added as keys\non the fly. While a note has been attacked, but not released, the value of the\nkey is the audiovoice which is generating that note. When notes are released,\nthe value of the key becomes undefined.</p>\n","itemtype":"property","name":"notes","class":"p5.PolySynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12157,"description":"<p>A PolySynth must have at least 1 voice, defaults to 8</p>\n","itemtype":"property","name":"polyvalue","class":"p5.PolySynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12162,"description":"<p>Monosynth that generates the sound for each note that is triggered. The\np5.PolySynth defaults to using the p5.MonoSynth as its voice.</p>\n","itemtype":"property","name":"AudioVoice","class":"p5.PolySynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12193,"description":"<p>Play a note by triggering noteAttack and noteRelease with sustain time</p>\n","itemtype":"method","name":"play","params":[{"name":"note","description":"<p>midi note to play (ranging from 0 to 127 - 60 being a middle C)</p>\n","type":"Number","optional":true},{"name":"velocity","description":"<p>velocity of the note to play (ranging from 0 to 1)</p>\n","type":"Number","optional":true},{"name":"secondsFromNow","description":"<p>time from now (in seconds) at which to play</p>\n","type":"Number","optional":true},{"name":"sustainTime","description":"<p>time to sustain before releasing the envelope</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar polySynth;\n\nfunction setup() {\n var cnv = createCanvas(100, 100);\n cnv.mousePressed(playSynth);\n\n polySynth = new p5.PolySynth();\n\n textAlign(CENTER);\n text('click to play', width/2, height/2);\n}\n\nfunction playSynth() {\n // note duration (in seconds)\n var dur = 0.1;\n\n // time from now (in seconds)\n var time = 0;\n\n // velocity (volume, from 0 to 1)\n var vel = 0.1;\n\n polySynth.play(\"G2\", vel, 0, dur);\n polySynth.play(\"C3\", vel, 0, dur);\n polySynth.play(\"G3\", vel, 0, dur);\n\n background(random(255), random(255), 255);\n text('click to play', width/2, height/2);\n}\n</code></div>"],"class":"p5.PolySynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12239,"description":"<p>noteADSR sets the envelope for a specific note that has just been triggered.\nUsing this method modifies the envelope of whichever audiovoice is being used\nto play the desired note. The envelope should be reset before noteRelease is called\nin order to prevent the modified envelope from being used on other notes.</p>\n","itemtype":"method","name":"noteADSR","params":[{"name":"note","description":"<p>Midi note on which ADSR should be set.</p>\n","type":"Number","optional":true},{"name":"attackTime","description":"<p>Time (in seconds before envelope\n reaches Attack Level</p>\n","type":"Number","optional":true},{"name":"decayTime","description":"<p>Time (in seconds) before envelope\n reaches Decay/Sustain Level</p>\n","type":"Number","optional":true},{"name":"susRatio","description":"<p>Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using <code>setRange</code>),\n then decayLevel would increase proportionally, to become 0.5.</p>\n","type":"Number","optional":true},{"name":"releaseTime","description":"<p>Time in seconds from now (defaults to 0)</p>\n","type":"Number","optional":true}],"class":"p5.PolySynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12267,"description":"<p>Set the PolySynths global envelope. This method modifies the envelopes of each\nmonosynth so that all notes are played with this envelope.</p>\n","itemtype":"method","name":"setADSR","params":[{"name":"attackTime","description":"<p>Time (in seconds before envelope\n reaches Attack Level</p>\n","type":"Number","optional":true},{"name":"decayTime","description":"<p>Time (in seconds) before envelope\n reaches Decay/Sustain Level</p>\n","type":"Number","optional":true},{"name":"susRatio","description":"<p>Ratio between attackLevel and releaseLevel, on a scale from 0 to 1,\n where 1.0 = attackLevel, 0.0 = releaseLevel.\n The susRatio determines the decayLevel and the level at which the\n sustain portion of the envelope will sustain.\n For example, if attackLevel is 0.4, releaseLevel is 0,\n and susAmt is 0.5, the decayLevel would be 0.2. If attackLevel is\n increased to 1.0 (using <code>setRange</code>),\n then decayLevel would increase proportionally, to become 0.5.</p>\n","type":"Number","optional":true},{"name":"releaseTime","description":"<p>Time in seconds from now (defaults to 0)</p>\n","type":"Number","optional":true}],"class":"p5.PolySynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12291,"description":"<p>Trigger the Attack, and Decay portion of a MonoSynth.\nSimilar to holding down a key on a piano, but it will\nhold the sustain level until you let go.</p>\n","itemtype":"method","name":"noteAttack","params":[{"name":"note","description":"<p>midi note on which attack should be triggered.</p>\n","type":"Number","optional":true},{"name":"velocity","description":"<p>velocity of the note to play (ranging from 0 to 1)/</p>\n","type":"Number","optional":true},{"name":"secondsFromNow","description":"<p>time from now (in seconds)</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar polySynth = new p5.PolySynth();\nvar pitches = [\"G\", \"D\", \"G\", \"C\"];\nvar octaves = [2, 3, 4];\n\nfunction mousePressed() {\n // play a chord: multiple notes at the same time\n for (var i = 0; i < 4; i++) {\n var note = random(pitches) + random(octaves);\n polySynth.noteAttack(note, 0.1);\n }\n}\n\nfunction mouseReleased() {\n // release all voices\n polySynth.noteRelease();\n}\n</code></div>"],"class":"p5.PolySynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12381,"description":"<p>Trigger the Release of an AudioVoice note. This is similar to releasing\nthe key on a piano and letting the sound fade according to the\nrelease level and release time.</p>\n","itemtype":"method","name":"noteRelease","params":[{"name":"note","description":"<p>midi note on which attack should be triggered.\n If no value is provided, all notes will be released.</p>\n","type":"Number","optional":true},{"name":"secondsFromNow","description":"<p>time to trigger the release</p>\n","type":"Number","optional":true}],"example":["\n<div><code>\nvar pitches = [\"G\", \"D\", \"G\", \"C\"];\nvar octaves = [2, 3, 4];\nvar polySynth = new p5.PolySynth();\n\nfunction mousePressed() {\n // play a chord: multiple notes at the same time\n for (var i = 0; i < 4; i++) {\n var note = random(pitches) + random(octaves);\n polySynth.noteAttack(note, 0.1);\n }\n}\n\nfunction mouseReleased() {\n // release all voices\n polySynth.noteRelease();\n}\n</code></div>\n"],"class":"p5.PolySynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12446,"description":"<p>Connect to a p5.sound / Web Audio object.</p>\n","itemtype":"method","name":"connect","params":[{"name":"unit","description":"<p>A p5.sound or Web Audio object</p>\n","type":"Object"}],"class":"p5.PolySynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12456,"description":"<p>Disconnect all outputs</p>\n","itemtype":"method","name":"disconnect","class":"p5.PolySynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12466,"description":"<p>Get rid of the MonoSynth and free up its resources / memory.</p>\n","itemtype":"method","name":"dispose","class":"p5.PolySynth","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12534,"description":"<p>The p5.Distortion is built with a\n<a href=\"http://www.w3.org/TR/webaudio/#WaveShaperNode\">\nWeb Audio WaveShaper Node</a>.</p>\n","itemtype":"property","name":"WaveShaperNode","type":"AudioNode","class":"p5.Distortion","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12549,"description":"<p>Process a sound source, optionally specify amount and oversample values.</p>\n","itemtype":"method","name":"process","params":[{"name":"amount","description":"<p>Unbounded distortion amount.\n Normal values range from 0-1.</p>\n","type":"Number","optional":true,"optdefault":"0.25"},{"name":"oversample","description":"<p>&#39;none&#39;, &#39;2x&#39;, or &#39;4x&#39;.</p>\n","type":"String","optional":true,"optdefault":"'none'"}],"class":"p5.Distortion","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12561,"description":"<p>Set the amount and oversample of the waveshaper distortion.</p>\n","itemtype":"method","name":"set","params":[{"name":"amount","description":"<p>Unbounded distortion amount.\n Normal values range from 0-1.</p>\n","type":"Number","optional":true,"optdefault":"0.25"},{"name":"oversample","description":"<p>&#39;none&#39;, &#39;2x&#39;, or &#39;4x&#39;.</p>\n","type":"String","optional":true,"optdefault":"'none'"}],"class":"p5.Distortion","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12579,"description":"<p>Return the distortion amount, typically between 0-1.</p>\n","itemtype":"method","name":"getAmount","return":{"description":"Unbounded distortion amount.\n Normal values range from 0-1.","type":"Number"},"class":"p5.Distortion","module":"p5.sound","submodule":"p5.sound"},{"file":"lib/addons/p5.sound.js","line":12589,"description":"<p>Return the oversampling.</p>\n","itemtype":"method","name":"getOversample","return":{"description":"Oversample can either be 'none', '2x', or '4x'.","type":"String"},"class":"p5.Distortion","module":"p5.sound","submodule":"p5.sound"}],"warnings":[{"message":"unknown tag: alt","line":" src/color/creating_reading.js:16"},{"message":"unknown tag: alt","line":" src/color/creating_reading.js:61"},{"message":"unknown tag: alt","line":" src/color/creating_reading.js:91"},{"message":"unknown tag: alt","line":" src/color/creating_reading.js:121"},{"message":"unknown tag: alt","line":" src/color/creating_reading.js:319"},{"message":"unknown tag: alt","line":" src/color/creating_reading.js:350"},{"message":"unknown tag: alt","line":" src/color/creating_reading.js:387"},{"message":"unknown tag: alt","line":" src/color/creating_reading.js:484"},{"message":"unknown tag: alt","line":" src/color/creating_reading.js:514"},{"message":"unknown tag: alt","line":" src/color/creating_reading.js:554"},{"message":"unknown tag: alt","line":" src/color/p5.Color.js:52"},{"message":"unknown tag: alt","line":" src/color/p5.Color.js:248"},{"message":"unknown tag: alt","line":" src/color/p5.Color.js:275"},{"message":"unknown tag: alt","line":" src/color/p5.Color.js:302"},{"message":"unknown tag: alt","line":" src/color/p5.Color.js:329"},{"message":"unknown tag: alt","line":" src/color/p5.Color.js:763"},{"message":"unknown tag: alt","line":" src/color/setting.js:15"},{"message":"unknown tag: alt","line":" src/color/setting.js:185"},{"message":"unknown tag: alt","line":" src/color/setting.js:223"},{"message":"unknown tag: alt","line":" src/color/setting.js:344"},{"message":"unknown tag: alt","line":" src/color/setting.js:501"},{"message":"unknown tag: alt","line":" src/color/setting.js:542"},{"message":"unknown tag: alt","line":" src/color/setting.js:582"},{"message":"unknown tag: alt","line":" src/core/shape/2d_primitives.js:16"},{"message":"unknown tag: alt","line":" src/core/shape/2d_primitives.js:149"},{"message":"unknown tag: alt","line":" src/core/shape/2d_primitives.js:208"},{"message":"unknown tag: alt","line":" src/core/shape/2d_primitives.js:264"},{"message":"unknown tag: alt","line":" src/core/shape/2d_primitives.js:299"},{"message":"unknown tag: alt","line":" src/core/shape/2d_primitives.js:353"},{"message":"unknown tag: alt","line":" src/core/shape/2d_primitives.js:436"},{"message":"unknown tag: alt","line":" src/core/shape/attributes.js:14"},{"message":"unknown tag: alt","line":" src/core/shape/attributes.js:83"},{"message":"unknown tag: alt","line":" src/core/shape/attributes.js:113"},{"message":"unknown tag: alt","line":" src/core/shape/attributes.js:182"},{"message":"unknown tag: alt","line":" src/core/shape/attributes.js:213"},{"message":"unknown tag: alt","line":" src/core/shape/attributes.js:250"},{"message":"unknown tag: alt","line":" src/core/shape/attributes.js:317"},{"message":"unknown tag: alt","line":" src/core/shape/curves.js:13"},{"message":"unknown tag: alt","line":" src/core/shape/curves.js:96"},{"message":"unknown tag: alt","line":" src/core/shape/curves.js:139"},{"message":"unknown tag: alt","line":" src/core/shape/curves.js:194"},{"message":"unknown tag: alt","line":" src/core/shape/curves.js:273"},{"message":"unknown tag: alt","line":" src/core/shape/curves.js:364"},{"message":"unknown tag: alt","line":" src/core/shape/curves.js:406"},{"message":"unknown tag: alt","line":" src/core/shape/curves.js:502"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:22"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:70"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:270"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:317"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:390"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:435"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:500"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:560"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:646"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:709"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:800"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:800"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:800"},{"message":"unknown tag: alt","line":" src/core/shape/vertex.js:800"},{"message":"unknown tag: alt","line":" src/core/constants.js:58"},{"message":"unknown tag: alt","line":" src/core/constants.js:77"},{"message":"unknown tag: alt","line":" src/core/constants.js:96"},{"message":"unknown tag: alt","line":" src/core/constants.js:115"},{"message":"unknown tag: alt","line":" src/core/constants.js:134"},{"message":"unknown tag: alt","line":" src/core/environment.js:22"},{"message":"unknown tag: alt","line":" src/core/environment.js:49"},{"message":"unknown tag: alt","line":" src/core/environment.js:76"},{"message":"unknown tag: alt","line":" src/core/environment.js:108"},{"message":"unknown tag: alt","line":" src/core/environment.js:167"},{"message":"unknown tag: alt","line":" src/core/environment.js:268"},{"message":"unknown tag: alt","line":" src/core/environment.js:293"},{"message":"unknown tag: alt","line":" src/core/environment.js:312"},{"message":"unknown tag: alt","line":" src/core/environment.js:331"},{"message":"unknown tag: alt","line":" src/core/environment.js:347"},{"message":"unknown tag: alt","line":" src/core/environment.js:363"},{"message":"unknown tag: alt","line":" src/core/environment.js:441"},{"message":"unknown tag: alt","line":" src/core/environment.js:492"},{"message":"replacing incorrect tag: returns with return","line":" src/core/environment.js:527"},{"message":"replacing incorrect tag: returns with return","line":" src/core/environment.js:547"},{"message":"unknown tag: alt","line":" src/core/environment.js:547"},{"message":"unknown tag: alt","line":" src/core/environment.js:604"},{"message":"unknown tag: alt","line":" src/core/environment.js:635"},{"message":"unknown tag: alt","line":" src/core/environment.js:658"},{"message":"unknown tag: alt","line":" src/core/main.js:49"},{"message":"unknown tag: alt","line":" src/core/main.js:90"},{"message":"unknown tag: alt","line":" src/core/main.js:121"},{"message":"unknown tag: alt","line":" src/core/main.js:408"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:51"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:116"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:153"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:188"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:249"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:298"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:364"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:418"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:474"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:532"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:575"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:642"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:677"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:719"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:767"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:807"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:856"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:894"},{"message":"unknown tag: alt","line":" src/core/p5.Element.js:932"},{"message":"unknown tag: alt","line":" src/core/p5.Graphics.js:65"},{"message":"unknown tag: alt","line":" src/core/rendering.js:17"},{"message":"unknown tag: alt","line":" src/core/rendering.js:119"},{"message":"unknown tag: alt","line":" src/core/rendering.js:174"},{"message":"unknown tag: alt","line":" src/core/rendering.js:197"},{"message":"unknown tag: alt","line":" src/core/rendering.js:236"},{"message":"unknown tag: alt","line":" src/core/structure.js:12"},{"message":"unknown tag: alt","line":" src/core/structure.js:74"},{"message":"unknown tag: alt","line":" src/core/structure.js:116"},{"message":"unknown tag: alt","line":" src/core/structure.js:181"},{"message":"unknown tag: alt","line":" src/core/structure.js:247"},{"message":"unknown tag: alt","line":" src/core/transform.js:13"},{"message":"unknown tag: alt","line":" src/core/transform.js:135"},{"message":"unknown tag: alt","line":" src/core/transform.js:161"},{"message":"unknown tag: alt","line":" src/core/transform.js:201"},{"message":"unknown tag: alt","line":" src/core/transform.js:231"},{"message":"unknown tag: alt","line":" src/core/transform.js:261"},{"message":"unknown tag: alt","line":" src/core/transform.js:291"},{"message":"unknown tag: alt","line":" src/core/transform.js:366"},{"message":"unknown tag: alt","line":" src/core/transform.js:405"},{"message":"unknown tag: alt","line":" src/core/transform.js:444"},{"message":"unknown tag: alt","line":" src/events/acceleration.js:91"},{"message":"unknown tag: alt","line":" src/events/acceleration.js:125"},{"message":"unknown tag: alt","line":" src/events/acceleration.js:158"},{"message":"unknown tag: alt","line":" src/events/acceleration.js:194"},{"message":"unknown tag: alt","line":" src/events/acceleration.js:239"},{"message":"unknown tag: alt","line":" src/events/acceleration.js:283"},{"message":"unknown tag: alt","line":" src/events/acceleration.js:350"},{"message":"unknown tag: alt","line":" src/events/acceleration.js:393"},{"message":"unknown tag: alt","line":" src/events/acceleration.js:437"},{"message":"unknown tag: alt","line":" src/events/acceleration.js:468"},{"message":"unknown tag: alt","line":" src/events/acceleration.js:527"},{"message":"unknown tag: alt","line":" src/events/keyboard.js:18"},{"message":"unknown tag: alt","line":" src/events/keyboard.js:45"},{"message":"unknown tag: alt","line":" src/events/keyboard.js:74"},{"message":"unknown tag: alt","line":" src/events/keyboard.js:107"},{"message":"unknown tag: alt","line":" src/events/keyboard.js:194"},{"message":"unknown tag: alt","line":" src/events/keyboard.js:246"},{"message":"unknown tag: alt","line":" src/events/keyboard.js:310"},{"message":"unknown tag: alt","line":" src/events/mouse.js:22"},{"message":"unknown tag: alt","line":" src/events/mouse.js:48"},{"message":"unknown tag: alt","line":" src/events/mouse.js:74"},{"message":"unknown tag: alt","line":" src/events/mouse.js:106"},{"message":"unknown tag: alt","line":" src/events/mouse.js:137"},{"message":"unknown tag: alt","line":" src/events/mouse.js:174"},{"message":"unknown tag: alt","line":" src/events/mouse.js:211"},{"message":"unknown tag: alt","line":" src/events/mouse.js:252"},{"message":"unknown tag: alt","line":" src/events/mouse.js:294"},{"message":"unknown tag: alt","line":" src/events/mouse.js:333"},{"message":"unknown tag: alt","line":" src/events/mouse.js:424"},{"message":"unknown tag: alt","line":" src/events/mouse.js:468"},{"message":"unknown tag: alt","line":" src/events/mouse.js:538"},{"message":"unknown tag: alt","line":" src/events/mouse.js:604"},{"message":"unknown tag: alt","line":" src/events/mouse.js:671"},{"message":"unknown tag: alt","line":" src/events/mouse.js:730"},{"message":"unknown tag: alt","line":" src/events/mouse.js:804"},{"message":"unknown tag: alt","line":" src/events/touch.js:12"},{"message":"unknown tag: alt","line":" src/events/touch.js:74"},{"message":"unknown tag: alt","line":" src/events/touch.js:138"},{"message":"unknown tag: alt","line":" src/events/touch.js:200"},{"message":"unknown tag: alt","line":" src/image/image.js:22"},{"message":"unknown tag: alt","line":" src/image/image.js:102"},{"message":"unknown tag: alt","line":" src/image/image.js:195"},{"message":"unknown tag: alt","line":" src/image/loading_displaying.js:17"},{"message":"replacing incorrect tag: returns with return","line":" src/image/loading_displaying.js:108"},{"message":"unknown tag: alt","line":" src/image/loading_displaying.js:125"},{"message":"unknown tag: alt","line":" src/image/loading_displaying.js:296"},{"message":"unknown tag: alt","line":" src/image/loading_displaying.js:396"},{"message":"unknown tag: alt","line":" src/image/loading_displaying.js:462"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:90"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:117"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:152"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:231"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:267"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:315"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:360"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:398"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:483"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:564"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:627"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:663"},{"message":"unknown tag: alt","line":" src/image/p5.Image.js:785"},{"message":"unknown tag: alt","line":" src/image/pixels.js:14"},{"message":"unknown tag: alt","line":" src/image/pixels.js:83"},{"message":"unknown tag: alt","line":" src/image/pixels.js:177"},{"message":"unknown tag: alt","line":" src/image/pixels.js:236"},{"message":"unknown tag: alt","line":" src/image/pixels.js:415"},{"message":"unknown tag: alt","line":" src/image/pixels.js:494"},{"message":"unknown tag: alt","line":" src/image/pixels.js:531"},{"message":"unknown tag: alt","line":" src/image/pixels.js:605"},{"message":"unknown tag: alt","line":" src/io/files.js:19"},{"message":"unknown tag: alt","line":" src/io/files.js:180"},{"message":"unknown tag: alt","line":" src/io/files.js:293"},{"message":"unknown tag: alt","line":" src/io/files.js:626"},{"message":"replacing incorrect tag: returns with return","line":" src/io/files.js:737"},{"message":"unknown tag: alt","line":" src/io/files.js:737"},{"message":"unknown tag: alt","line":" src/io/files.js:1530"},{"message":"unknown tag: alt","line":" src/io/files.js:1582"},{"message":"unknown tag: alt","line":" src/io/files.js:1644"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:56"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:120"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:168"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:214"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:263"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:328"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:523"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:576"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:618"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:879"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:944"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:994"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:1040"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:1085"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:1132"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:1177"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:1230"},{"message":"unknown tag: alt","line":" src/io/p5.Table.js:1296"},{"message":"unknown tag: alt","line":" src/io/p5.TableRow.js:42"},{"message":"unknown tag: alt","line":" src/io/p5.TableRow.js:106"},{"message":"unknown tag: alt","line":" src/io/p5.TableRow.js:150"},{"message":"unknown tag: alt","line":" src/io/p5.TableRow.js:195"},{"message":"unknown tag: alt","line":" src/io/p5.TableRow.js:243"},{"message":"unknown tag: alt","line":" src/io/p5.TableRow.js:299"},{"message":"unknown tag: alt","line":" src/io/p5.XML.js:11"},{"message":"unknown tag: alt","line":" src/math/calculation.js:12"},{"message":"unknown tag: alt","line":" src/math/calculation.js:36"},{"message":"unknown tag: alt","line":" src/math/calculation.js:76"},{"message":"unknown tag: alt","line":" src/math/calculation.js:121"},{"message":"unknown tag: alt","line":" src/math/calculation.js:190"},{"message":"unknown tag: alt","line":" src/math/calculation.js:240"},{"message":"unknown tag: alt","line":" src/math/calculation.js:279"},{"message":"unknown tag: alt","line":" src/math/calculation.js:324"},{"message":"unknown tag: alt","line":" src/math/calculation.js:379"},{"message":"unknown tag: alt","line":" src/math/calculation.js:418"},{"message":"unknown tag: alt","line":" src/math/calculation.js:474"},{"message":"unknown tag: alt","line":" src/math/calculation.js:524"},{"message":"unknown tag: alt","line":" src/math/calculation.js:574"},{"message":"unknown tag: alt","line":" src/math/calculation.js:627"},{"message":"unknown tag: alt","line":" src/math/calculation.js:661"},{"message":"unknown tag: alt","line":" src/math/calculation.js:700"},{"message":"unknown tag: alt","line":" src/math/calculation.js:747"},{"message":"unknown tag: alt","line":" src/math/math.js:12"},{"message":"unknown tag: alt","line":" src/math/noise.js:40"},{"message":"unknown tag: alt","line":" src/math/noise.js:187"},{"message":"unknown tag: alt","line":" src/math/noise.js:253"},{"message":"unknown tag: alt","line":" src/math/p5.Vector.js:12"},{"message":"unknown tag: alt","line":" src/math/random.js:48"},{"message":"unknown tag: alt","line":" src/math/random.js:79"},{"message":"unknown tag: alt","line":" src/math/random.js:166"},{"message":"unknown tag: alt","line":" src/math/trigonometry.js:124"},{"message":"unknown tag: alt","line":" src/math/trigonometry.js:160"},{"message":"unknown tag: alt","line":" src/math/trigonometry.js:188"},{"message":"unknown tag: alt","line":" src/math/trigonometry.js:216"},{"message":"unknown tag: alt","line":" src/math/trigonometry.js:296"},{"message":"replacing incorrect tag: returns with return","line":" src/math/trigonometry.js:332"},{"message":"replacing incorrect tag: returns with return","line":" src/math/trigonometry.js:347"},{"message":"replacing incorrect tag: returns with return","line":" src/math/trigonometry.js:362"},{"message":"unknown tag: alt","line":" src/typography/attributes.js:13"},{"message":"unknown tag: alt","line":" src/typography/attributes.js:84"},{"message":"unknown tag: alt","line":" src/typography/attributes.js:122"},{"message":"unknown tag: alt","line":" src/typography/attributes.js:154"},{"message":"unknown tag: alt","line":" src/typography/attributes.js:189"},{"message":"unknown tag: alt","line":" src/typography/loading_displaying.js:16"},{"message":"unknown tag: alt","line":" src/typography/loading_displaying.js:143"},{"message":"unknown tag: alt","line":" src/typography/loading_displaying.js:230"},{"message":"unknown tag: alt","line":" src/typography/p5.Font.js:43"},{"message":"unknown tag: alt","line":" src/utilities/conversion.js:12"},{"message":"unknown tag: alt","line":" src/utilities/string_functions.js:15"},{"message":"unknown tag: alt","line":" src/utilities/string_functions.js:44"},{"message":"unknown tag: alt","line":" src/utilities/string_functions.js:132"},{"message":"unknown tag: alt","line":" src/utilities/string_functions.js:237"},{"message":"unknown tag: alt","line":" src/utilities/string_functions.js:313"},{"message":"unknown tag: alt","line":" src/utilities/string_functions.js:375"},{"message":"unknown tag: alt","line":" src/utilities/string_functions.js:437"},{"message":"unknown tag: alt","line":" src/utilities/string_functions.js:526"},{"message":"unknown tag: alt","line":" src/utilities/time_date.js:12"},{"message":"unknown tag: alt","line":" src/utilities/time_date.js:34"},{"message":"unknown tag: alt","line":" src/utilities/time_date.js:56"},{"message":"unknown tag: alt","line":" src/utilities/time_date.js:78"},{"message":"unknown tag: alt","line":" src/utilities/time_date.js:101"},{"message":"unknown tag: alt","line":" src/utilities/time_date.js:123"},{"message":"unknown tag: alt","line":" src/utilities/time_date.js:145"},{"message":"unknown tag: alt","line":" src/webgl/3d_primitives.js:15"},{"message":"unknown tag: alt","line":" src/webgl/interaction.js:13"},{"message":"unknown tag: alt","line":" src/webgl/interaction.js:146"},{"message":"unknown tag: alt","line":" src/webgl/interaction.js:146"},{"message":"unknown tag: alt","line":" src/webgl/interaction.js:146"},{"message":"unknown tag: alt","line":" src/webgl/interaction.js:146"},{"message":"unknown tag: alt","line":" src/webgl/interaction.js:146"},{"message":"unknown tag: alt","line":" src/webgl/interaction.js:380"},{"message":"unknown tag: alt","line":" src/webgl/light.js:12"},{"message":"unknown tag: alt","line":" src/webgl/light.js:101"},{"message":"unknown tag: alt","line":" src/webgl/light.js:212"},{"message":"unknown tag: alt","line":" src/webgl/loading.js:14"},{"message":"unknown tag: alt","line":" src/webgl/loading.js:14"},{"message":"unknown tag: alt","line":" src/webgl/loading.js:244"},{"message":"unknown tag: alt","line":" src/webgl/material.js:14"},{"message":"replacing incorrect tag: returns with return","line":" src/webgl/material.js:83"},{"message":"unknown tag: alt","line":" src/webgl/material.js:83"},{"message":"unknown tag: alt","line":" src/webgl/material.js:176"},{"message":"unknown tag: alt","line":" src/webgl/material.js:211"},{"message":"unknown tag: alt","line":" src/webgl/material.js:301"},{"message":"unknown tag: alt","line":" src/webgl/material.js:350"},{"message":"unknown tag: alt","line":" src/webgl/p5.Camera.js:15"},{"message":"unknown tag: alt","line":" src/webgl/p5.Camera.js:61"},{"message":"unknown tag: alt","line":" src/webgl/p5.Camera.js:126"},{"message":"unknown tag: alt","line":" src/webgl/p5.Camera.js:209"},{"message":"unknown tag: alt","line":" src/webgl/p5.Camera.js:487"},{"message":"unknown tag: alt","line":" src/webgl/p5.Camera.js:546"},{"message":"unknown tag: alt","line":" src/webgl/p5.Camera.js:604"},{"message":"unknown tag: alt","line":" src/webgl/p5.Camera.js:752"},{"message":"unknown tag: alt","line":" src/webgl/p5.Camera.js:824"},{"message":"unknown tag: alt","line":" src/webgl/p5.Camera.js:1089"},{"message":"unknown tag: alt","line":" src/webgl/p5.RendererGL.js:215"},{"message":"unknown tag: alt","line":" src/webgl/p5.RendererGL.js:427"},{"message":"unknown tag: alt","line":" src/webgl/p5.RendererGL.js:474"},{"message":"unknown tag: alt","line":" src/webgl/p5.RendererGL.js:515"},{"message":"replacing incorrect tag: function with method","line":" src/webgl/text.js:117"},{"message":"replacing incorrect tag: returns with return","line":" src/webgl/text.js:160"},{"message":"replacing incorrect tag: function with method","line":" src/webgl/text.js:193"},{"message":"replacing incorrect tag: function with method","line":" src/webgl/text.js:205"},{"message":"replacing incorrect tag: function with method","line":" src/webgl/text.js:235"},{"message":"replacing incorrect tag: function with method","line":" src/webgl/text.js:249"},{"message":"replacing incorrect tag: function with method","line":" src/webgl/text.js:387"},{"message":"replacing incorrect tag: returns with return","line":" src/webgl/text.js:387"},{"message":"replacing incorrect tag: function with method","line":" src/webgl/text.js:457"},{"message":"replacing incorrect tag: function with method","line":" src/webgl/text.js:472"},{"message":"replacing incorrect tag: function with method","line":" src/webgl/text.js:547"},{"message":"replacing incorrect tag: returns with return","line":" lib/addons/p5.dom.js:1368"},{"message":"replacing incorrect tag: returns with return","line":" lib/addons/p5.dom.js:1470"},{"message":"replacing incorrect tag: returns with return","line":" lib/addons/p5.dom.js:1509"},{"message":"replacing incorrect tag: returns with return","line":" lib/addons/p5.dom.js:1603"},{"message":"replacing incorrect tag: params with param","line":" lib/addons/p5.sound.js:1642"},{"message":"replacing incorrect tag: returns with return","line":" lib/addons/p5.sound.js:1642"},{"message":"replacing incorrect tag: returns with return","line":" lib/addons/p5.sound.js:7335"},{"message":"replacing incorrect tag: returns with return","line":" lib/addons/p5.sound.js:9303"},{"message":"Missing item type\nConversions adapted from <http://www.easyrgb.com/en/math.php>.\n\nIn these functions, hue is always in the range [0, 1], just like all other\ncomponents are in the range [0, 1]. 'Brightness' and 'value' are used\ninterchangeably.","line":" src/color/color_conversion.js:10"},{"message":"Missing item type\nConvert an HSBA array to HSLA.","line":" src/color/color_conversion.js:21"},{"message":"Missing item type\nConvert an HSBA array to RGBA.","line":" src/color/color_conversion.js:47"},{"message":"Missing item type\nConvert an HSLA array to HSBA.","line":" src/color/color_conversion.js:102"},{"message":"Missing item type\nConvert an HSLA array to RGBA.\n\nWe need to change basis from HSLA to something that can be more easily be\nprojected onto RGBA. We will choose hue and brightness as our first two\ncomponents, and pick a convenient third one ('zest') so that we don't need\nto calculate formal HSBA saturation.","line":" src/color/color_conversion.js:125"},{"message":"Missing item type\nConvert an RGBA array to HSBA.","line":" src/color/color_conversion.js:189"},{"message":"Missing item type\nConvert an RGBA array to HSLA.","line":" src/color/color_conversion.js:228"},{"message":"Missing item type\nHue is the same in HSB and HSL, but the maximum value may be different.\nThis function will return the HSB-normalized saturation when supplied with\nan HSB color object, but will default to the HSL-normalized saturation\notherwise.","line":" src/color/p5.Color.js:410"},{"message":"Missing item type\nSaturation is scaled differently in HSB and HSL. This function will return\nthe HSB saturation when supplied with an HSB color object, but will default\nto the HSL saturation otherwise.","line":" src/color/p5.Color.js:441"},{"message":"Missing item type\nCSS named colors.","line":" src/color/p5.Color.js:460"},{"message":"Missing item type\nThese regular expressions are used to build up the patterns for matching\nviable CSS color strings: fragmenting the regexes in this way increases the\nlegibility and comprehensibility of the code.\n\nNote that RGB values of .9 are not parsed by IE, but are supported here for\ncolor string consistency.","line":" src/color/p5.Color.js:613"},{"message":"Missing item type\nFull color string patterns. The capture groups are necessary.","line":" src/color/p5.Color.js:626"},{"message":"Missing item type\nFor a number of different inputs, returns a color formatted as [r, g, b, a]\narrays, with each component normalized between 0 and 1.","line":" src/color/p5.Color.js:763"},{"message":"Missing item type\nFor HSB and HSL, interpret the gray level as a brightness/lightness\nvalue (they are equivalent when chroma is zero). For RGB, normalize the\ngray level according to the blue maximum.","line":" src/color/p5.Color.js:989"},{"message":"Missing item type\nReturns the current framerate.","line":" src/core/environment.js:242"},{"message":"Missing item type\nSpecifies the number of frames to be displayed every second. For example,\nthe function call frameRate(30) will attempt to refresh 30 times a second.\nIf the processor is not fast enough to maintain the specified rate, the\nframe rate will not be achieved. Setting the frame rate within <a href=\"#/p5/setup\">setup()</a> is\nrecommended. The default rate is 60 frames per second.\n\nCalling <a href=\"#/p5/frameRate\">frameRate()</a> with no arguments returns the current framerate.","line":" src/core/environment.js:252"},{"message":"Missing item type","line":" src/core/error_helpers.js:1"},{"message":"Missing item type\nPrints out a fancy, colorful message to the console log","line":" src/core/error_helpers.js:65"},{"message":"Missing item type\nValidates parameters\nparam {String} func the name of the function\nparam {Array} args user input arguments\n\nexample:\n var a;\n ellipse(10,10,a,5);\nconsole ouput:\n \"It looks like ellipse received an empty variable in spot #2.\"\n\nexample:\n ellipse(10,\"foo\",5,5);\nconsole output:\n \"ellipse was expecting a number for parameter #1,\n received \"foo\" instead.\"","line":" src/core/error_helpers.js:563"},{"message":"Missing item type\nPrints out all the colors in the color pallete with white text.\nFor color blindness testing.","line":" src/core/error_helpers.js:624"},{"message":"Missing item type","line":" src/core/helpers.js:1"},{"message":"Missing item type\n_globalInit\n\nTODO: ???\nif sketch is on window\nassume \"global\" mode\nand instantiate p5 automatically\notherwise do nothing","line":" src/core/init.js:5"},{"message":"Missing item type","line":" src/core/legacy.js:1"},{"message":"Missing item type\nHelper fxn for sharing pixel methods","line":" src/core/p5.Element.js:1088"},{"message":"Missing item type\nResize our canvas element.","line":" src/core/p5.Renderer.js:96"},{"message":"Missing item type\nHelper fxn to check font type (system or otf)","line":" src/core/p5.Renderer.js:300"},{"message":"Missing item type\nHelper fxn to measure ascent and descent.\nAdapted from http://stackoverflow.com/a/25355178","line":" src/core/p5.Renderer.js:353"},{"message":"Missing item type\np5.Renderer2D\nThe 2D graphics canvas renderer class.\nextends p5.Renderer","line":" src/core/p5.Renderer2D.js:9"},{"message":"Missing item type\nGenerate a cubic Bezier representing an arc on the unit circle of total\nangle `size` radians, beginning `start` radians above the x-axis. Up to\nfour of these curves are combined to make a full arc.\n\nSee www.joecridge.me/bezier.pdf for an explanation of the method.","line":" src/core/p5.Renderer2D.js:414"},{"message":"Missing item type\nshim for Uint8ClampedArray.slice\n(allows arrayCopy to work with pixels[])\nwith thanks to http://halfpapstudios.com/blog/tag/html5-canvas/\nEnumerable set to false to protect for...in from\nUint8ClampedArray.prototype pollution.","line":" src/core/shim.js:23"},{"message":"Missing item type\nthis is implementation of Object.assign() which is unavailable in\nIE11 and (non-Chrome) Android browsers.\nThe assign() method is used to copy the values of all enumerable\nown properties from one or more source objects to a target object.\nIt will return the target object.\nModified from https://github.com/ljharb/object.assign","line":" src/core/shim.js:45"},{"message":"Missing item type\nprivate helper function to handle the user passing in objects\nduring construction or calls to create()","line":" src/data/p5.TypedDict.js:203"},{"message":"Missing item type\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type","line":" src/data/p5.TypedDict.js:382"},{"message":"Missing item type\nprivate helper function to ensure that the user passed in valid\nvalues for the Dictionary type","line":" src/data/p5.TypedDict.js:425"},{"message":"Missing item type\nprivate helper function for finding lowest or highest value\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'","line":" src/data/p5.TypedDict.js:542"},{"message":"Missing item type\nprivate helper function for finding lowest or highest key\nthe argument 'flip' is used to flip the comparison arrow\nfrom 'less than' to 'greater than'","line":" src/data/p5.TypedDict.js:609"},{"message":"Missing item type\n_updatePAccelerations updates the pAcceleration values","line":" src/events/acceleration.js:80"},{"message":"Missing item type\nHolds the key codes of currently pressed keys.","line":" src/events/keyboard.js:12"},{"message":"Missing item type\nThe onblur function is called when the user is no longer focused\non the p5 element. Because the keyup events will not fire if the user is\nnot focused on the element we must assume all keys currently down have\nbeen released.","line":" src/events/keyboard.js:300"},{"message":"Missing item type\nThe checkDownKeys function returns a boolean true if any keys pressed\nand a false if no keys are currently pressed.\n\nHelps avoid instances where a multiple keys are pressed simultaneously and\nreleasing a single key will then switch the\nkeyIsPressed property to true.","line":" src/events/keyboard.js:387"},{"message":"Missing item type\nThis module defines the filters for use with image buffers.\n\nThis module is basically a collection of functions stored in an object\nas opposed to modules. The functions are destructive, modifying\nthe passed in canvas rather than creating a copy.\n\nGenerally speaking users of this module will use the Filters.apply method\non a canvas to create an effect.\n\nA number of functions are borrowed/adapted from\nhttp://www.html5rocks.com/en/tutorials/canvas/imagefilters/\nor the java processing implementation.","line":" src/image/filters.js:3"},{"message":"Missing item type\nReturns the pixel buffer for a canvas","line":" src/image/filters.js:26"},{"message":"Missing item type\nReturns a 32 bit number containing ARGB data at ith pixel in the\n1D array containing pixels data.","line":" src/image/filters.js:46"},{"message":"Missing item type\nModifies pixels RGBA values to values contained in the data object.","line":" src/image/filters.js:67"},{"message":"Missing item type\nReturns the ImageData object for a canvas\nhttps://developer.mozilla.org/en-US/docs/Web/API/ImageData","line":" src/image/filters.js:87"},{"message":"Missing item type\nReturns a blank ImageData object.","line":" src/image/filters.js:107"},{"message":"Missing item type\nApplys a filter function to a canvas.\n\nThe difference between this and the actual filter functions defined below\nis that the filter functions generally modify the pixel buffer but do\nnot actually put that data back to the canvas (where it would actually\nupdate what is visible). By contrast this method does make the changes\nactually visible in the canvas.\n\nThe apply method is the method that callers of this module would generally\nuse. It has been separated from the actual filters to support an advanced\nuse case of creating a filter chain that executes without actually updating\nthe canvas in between everystep.","line":" src/image/filters.js:122"},{"message":"Missing item type\nConverts the image to black and white pixels depending if they are above or\nbelow the threshold defined by the level parameter. The parameter must be\nbetween 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used.\n\nBorrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/","line":" src/image/filters.js:159"},{"message":"Missing item type\nConverts any colors in the image to grayscale equivalents.\nNo parameter is used.\n\nBorrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/","line":" src/image/filters.js:193"},{"message":"Missing item type\nSets the alpha channel to entirely opaque. No parameter is used.","line":" src/image/filters.js:216"},{"message":"Missing item type\nSets each pixel to its inverse value. No parameter is used.","line":" src/image/filters.js:232"},{"message":"Missing item type\nLimits each channel of the image to the number of colors specified as\nthe parameter. The parameter can be set to values between 2 and 255, but\nresults are most noticeable in the lower ranges.\n\nAdapted from java based processing implementation","line":" src/image/filters.js:247"},{"message":"Missing item type\nreduces the bright areas in an image","line":" src/image/filters.js:279"},{"message":"Missing item type\nincreases the bright areas in an image","line":" src/image/filters.js:367"},{"message":"Missing item type\nThis module defines the p5 methods for the <a href=\"#/p5.Image\">p5.Image</a> class\nfor drawing images to the main display canvas.","line":" src/image/image.js:8"},{"message":"Missing item type\nValidates clipping params. Per drawImage spec sWidth and sHight cannot be\nnegative or greater than image intrinsic width and height","line":" src/image/loading_displaying.js:108"},{"message":"Missing item type\nApply the current tint color to the input image, return the resulting\ncanvas.","line":" src/image/loading_displaying.js:425"},{"message":"Missing item type\nThis module defines the <a href=\"#/p5.Image\">p5.Image</a> class and P5 methods for\ndrawing images to the main display canvas.","line":" src/image/p5.Image.js:9"},{"message":"Missing item type\nHelper fxn for sharing pixel methods","line":" src/image/p5.Image.js:222"},{"message":"Missing item type\nGenerate a blob of file data as a url to prepare for download.\nAccepts an array of data, a filename, and an extension (optional).\nThis is a private function because it does not do any formatting,\nbut it is used by <a href=\"#/p5/saveStrings\">saveStrings</a>, <a href=\"#/p5/saveJSON\">saveJSON</a>, <a href=\"#/p5/saveTable\">saveTable</a> etc.","line":" src/io/files.js:1770"},{"message":"Missing item type\nReturns a file extension, or another string\nif the provided parameter has no extension.","line":" src/io/files.js:1839"},{"message":"Missing item type\nReturns true if the browser is Safari, false if not.\nSafari makes trouble for downloading files.","line":" src/io/files.js:1872"},{"message":"Missing item type\nHelper function, a callback for download that deletes\nan invisible anchor element from the DOM once the file\nhas been automatically downloaded.","line":" src/io/files.js:1884"},{"message":"Missing item type\nTable Options\n<p>Generic class for handling tabular data, typically from a\nCSV, TSV, or other sort of spreadsheet file.</p>\n<p>CSV files are\n<a href=\"http://en.wikipedia.org/wiki/Comma-separated_values\">\ncomma separated values</a>, often with the data in quotes. TSV\nfiles use tabs as separators, and usually don't bother with the\nquotes.</p>\n<p>File names should end with .csv if they're comma separated.</p>\n<p>A rough \"spec\" for CSV can be found\n<a href=\"http://tools.ietf.org/html/rfc4180\">here</a>.</p>\n<p>To load files, use the <a href=\"#/p5/loadTable\">loadTable</a> method.</p>\n<p>To save tables to your computer, use the <a href=\"#/p5/save\">save</a> method\n or the <a href=\"#/p5/saveTable\">saveTable</a> method.</p>\n\nPossible options include:\n<ul>\n<li>csv - parse the table as comma-separated values\n<li>tsv - parse the table as tab-separated values\n<li>header - this table has a header (title) row\n</ul>","line":" src/io/p5.Table.js:11"},{"message":"Missing item type\nThis method is called while the parsing of XML (when loadXML() is\ncalled). The difference between this method and the setContent()\nmethod defined later is that this one is used to set the content\nwhen the node in question has more nodes under it and so on and\nnot directly text content. While in the other one is used when\nthe node in question directly has text inside it.","line":" src/io/p5.XML.js:801"},{"message":"Missing item type\nThis method is called while the parsing of XML (when loadXML() is\ncalled). The XML node is passed and its attributes are stored in the\n<a href=\"#/p5.XML\">p5.XML</a>'s attribute Object.","line":" src/io/p5.XML.js:818"},{"message":"Missing item type\nMultiplies a vector by a scalar and returns a new vector.","line":" src/math/p5.Vector.js:1611"},{"message":"Missing item type\nDivides a vector by a scalar and returns a new vector.","line":" src/math/p5.Vector.js:1638"},{"message":"Missing item type\nCalculates the dot product of two vectors.","line":" src/math/p5.Vector.js:1665"},{"message":"Missing item type\nCalculates the cross product of two vectors.","line":" src/math/p5.Vector.js:1679"},{"message":"Missing item type\nCalculates the Euclidean distance between two points (considering a\npoint as a vector object).","line":" src/math/p5.Vector.js:1693"},{"message":"Missing item type\nLinear interpolate a vector to another vector and return the result as a\nnew vector.","line":" src/math/p5.Vector.js:1708"},{"message":"Missing item type\nHelper function to measure ascent and descent.","line":" src/typography/attributes.js:282"},{"message":"Missing item type\nReturns the set of opentype glyphs for the supplied string.\n\nNote that there is not a strict one-to-one mapping between characters\nand glyphs, so the list of returned glyphs can be larger or smaller\n than the length of the given string.","line":" src/typography/p5.Font.js:256"},{"message":"Missing item type\nReturns an opentype path for the supplied string and position.","line":" src/typography/p5.Font.js:271"},{"message":"Missing item type","line":" src/webgl/3d_primitives.js:259"},{"message":"Missing item type\nDraws a point, a coordinate in space at the dimension of one pixel,\ngiven x, y and z coordinates. The color of the point is determined\nby the current stroke, while the point size is determined by current\nstroke weight.","line":" src/webgl/3d_primitives.js:745"},{"message":"Missing item type\nDraw a line given two points","line":" src/webgl/3d_primitives.js:1162"},{"message":"Missing item type\nParse OBJ lines into model. For reference, this is what a simple model of a\nsquare might look like:\n\nv -0.5 -0.5 0.5\nv -0.5 -0.5 -0.5\nv -0.5 0.5 -0.5\nv -0.5 0.5 0.5\n\nf 4 3 2 1","line":" src/webgl/loading.js:135"},{"message":"Missing item type","line":" src/webgl/material.js:399"},{"message":"Missing item type\nCreate a 2D array for establishing stroke connections","line":" src/webgl/p5.Geometry.js:190"},{"message":"Missing item type\nCreate 4 vertices for each stroke line, two at the beginning position\nand two at the end position. These vertices are displaced relative to\nthat line's normal on the GPU","line":" src/webgl/p5.Geometry.js:211"},{"message":"Missing item type","line":" src/webgl/p5.Matrix.js:1"},{"message":"Missing item type\nPRIVATE","line":" src/webgl/p5.Matrix.js:673"},{"message":"Missing item type\nWelcome to RendererGL Immediate Mode.\nImmediate mode is used for drawing custom shapes\nfrom a set of vertices. Immediate Mode is activated\nwhen you call <a href=\"#/p5/beginShape\">beginShape()</a> & de-activated when you call <a href=\"#/p5/endShape\">endShape()</a>.\nImmediate mode is a style of programming borrowed\nfrom OpenGL's (now-deprecated) immediate mode.\nIt differs from p5.js' default, Retained Mode, which caches\ngeometries and buffers on the CPU to reduce the number of webgl\ndraw calls. Retained mode is more efficient & performative,\nhowever, Immediate Mode is useful for sketching quick\ngeometric ideas.","line":" src/webgl/p5.RendererGL.Immediate.js:1"},{"message":"Missing item type\nEnd shape drawing and render vertices to screen.","line":" src/webgl/p5.RendererGL.Immediate.js:118"},{"message":"Missing item type\ninitializes buffer defaults. runs each time a new geometry is\nregistered","line":" src/webgl/p5.RendererGL.Retained.js:8"},{"message":"Missing item type\ncreateBuffers description","line":" src/webgl/p5.RendererGL.Retained.js:47"},{"message":"Missing item type\nDraws buffers given a geometry key ID","line":" src/webgl/p5.RendererGL.Retained.js:191"},{"message":"Missing item type\nmodel view, projection, & normal\nmatrices","line":" src/webgl/p5.RendererGL.js:83"},{"message":"Missing item type\n[background description]","line":" src/webgl/p5.RendererGL.js:405"},{"message":"Missing item type\n[resize description]","line":" src/webgl/p5.RendererGL.js:644"},{"message":"Missing item type\nclears color and depth buffers\nwith r,g,b,a","line":" src/webgl/p5.RendererGL.js:670"},{"message":"Missing item type\n[translate description]","line":" src/webgl/p5.RendererGL.js:688"},{"message":"Missing item type\nScales the Model View Matrix by a vector","line":" src/webgl/p5.RendererGL.js:707"},{"message":"Missing item type\nturn a two dimensional array into one dimensional array","line":" src/webgl/p5.RendererGL.js:1028"},{"message":"Missing item type\nturn a p5.Vector Array into a one dimensional number array","line":" src/webgl/p5.RendererGL.js:1065"},{"message":"Missing item type\nensures that p5 is using a 3d renderer. throws an error if not.","line":" src/webgl/p5.RendererGL.js:1081"},{"message":"Missing item type\nHelper function for select and selectAll","line":" lib/addons/p5.dom.js:168"},{"message":"Missing item type\nHelper function for getElement and getElements.","line":" lib/addons/p5.dom.js:184"},{"message":"Missing item type\nHelpers for create methods.","line":" lib/addons/p5.dom.js:245"},{"message":"Missing item type","line":" lib/addons/p5.dom.js:384"},{"message":"Missing item type","line":" lib/addons/p5.dom.js:981"},{"message":"Missing item type","line":" lib/addons/p5.dom.js:1062"},{"message":"Missing item type","line":" lib/addons/p5.dom.js:1102"},{"message":"Missing item type","line":" lib/addons/p5.dom.js:2777"},{"message":"Missing item type","line":" lib/addons/p5.dom.js:2843"},{"message":"Missing item type","line":" lib/addons/p5.dom.js:2905"},{"message":"Missing item type\np5.sound \nhttps://p5js.org/reference/#/libraries/p5.sound\n\nFrom the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors\n\nMIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE\n\nSome of the many audio libraries & resources that inspire p5.sound:\n - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js\n - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/\n - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0\n - wavesurfer.js https://github.com/katspaugh/wavesurfer.js\n - Web Audio Components by Jordan Santell https://github.com/web-audio-components\n - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound\n\n Web Audio API: http://w3.org/TR/webaudio/","line":" lib/addons/p5.sound.js:46"},{"message":"Missing item type\nDetermine which filetypes are supported (inspired by buzz.js)\nThe audio element (el) will only be used to test browser support for various audio formats","line":" lib/addons/p5.sound.js:214"},{"message":"Missing item type\nMaster contains AudioContext and the master sound output.","line":" lib/addons/p5.sound.js:328"},{"message":"Missing item type\na silent connection to the DesinationNode\nwhich will ensure that anything connected to it\nwill not be garbage collected","line":" lib/addons/p5.sound.js:423"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:439"},{"message":"Missing item type\nUsed by Osc and Envelope to chain signal math","line":" lib/addons/p5.sound.js:644"},{"message":"Missing item type\nThis is a helper function that the p5.SoundFile calls to load\nitself. Accepts a callback (the name of another function)\nas an optional parameter.","line":" lib/addons/p5.sound.js:973"},{"message":"Missing item type\nStop playback on all of this soundfile's sources.","line":" lib/addons/p5.sound.js:1379"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:1818"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:2099"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:3110"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:3487"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:3508"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:3567"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:3885"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:4057"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:4215"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:4256"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:4326"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:4514"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:4571"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:4739"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:4787"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:4818"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:4839"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:4859"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:5572"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:5775"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:7426"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:7442"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:7466"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:7492"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:7514"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:7536"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:7582"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:7613"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:7631"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:7968"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:7990"},{"message":"Missing item type\nThe p5.Effect class is built\n \tusing Tone.js CrossFade","line":" lib/addons/p5.sound.js:8060"},{"message":"Missing item type\nIn classes that extend\np5.Effect, connect effect nodes\nto the wet parameter","line":" lib/addons/p5.sound.js:8066"},{"message":"Missing item type\nEQFilter extends p5.Filter with constraints\nnecessary for the p5.EQ","line":" lib/addons/p5.sound.js:8456"},{"message":"Missing item type\nInspired by Simple Reverb by Jordan Santell\nhttps://github.com/web-audio-components/simple-reverb/blob/master/index.js\n\nUtility function for building an impulse response\nbased on the module parameters.","line":" lib/addons/p5.sound.js:9552"},{"message":"Missing item type\nPrivate method to load a buffer as an Impulse Response,\nassign it to the convolverNode, and add to the Array of .impulses.","line":" lib/addons/p5.sound.js:9724"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:9912"},{"message":"Missing item type","line":" lib/addons/p5.sound.js:9937"},{"message":"Missing item type\nmusicalTimeMode variables\nmodify these only when the interval is specified in musicalTime format as a string","line":" lib/addons/p5.sound.js:10662"},{"message":"Missing item type\nDo not initiate the callback if timeFromNow is < 0\nThis ususually occurs for a few milliseconds when the page\nis not fully loaded\n\nThe callback should only be called until maxIterations is reached","line":" lib/addons/p5.sound.js:10678"},{"message":"Missing item type\ncallback invoked when the recording is over","line":" lib/addons/p5.sound.js:11167"},{"message":"Missing item type\ninternal method called on audio process","line":" lib/addons/p5.sound.js:11253"},{"message":"Missing item type\nPrivate method to ensure accurate values of this._voicesInUse\nAny time a new value is scheduled, it is necessary to increment all subsequent\nscheduledValues after attack, and decrement all subsequent\nscheduledValues after release","line":" lib/addons/p5.sound.js:12361"},{"message":"Missing item type\np5.sound \nhttps://p5js.org/reference/#/libraries/p5.sound\n\nFrom the Processing Foundation and contributors\nhttps://github.com/processing/p5.js-sound/graphs/contributors\n\nMIT License (MIT)\nhttps://github.com/processing/p5.js-sound/blob/master/LICENSE\n\nSome of the many audio libraries & resources that inspire p5.sound:\n - TONE.js (c) Yotam Mann. Licensed under The MIT License (MIT). https://github.com/TONEnoTONE/Tone.js\n - buzz.js (c) Jay Salvat. Licensed under The MIT License (MIT). http://buzz.jaysalvat.com/\n - Boris Smus Web Audio API book, 2013. Licensed under the Apache License http://www.apache.org/licenses/LICENSE-2.0\n - wavesurfer.js https://github.com/katspaugh/wavesurfer.js\n - Web Audio Components by Jordan Santell https://github.com/web-audio-components\n - Wilm Thoben's Sound library for Processing https://github.com/processing/processing/tree/master/java/libraries/sound\n\n Web Audio API: http://w3.org/TR/webaudio/","line":" lib/addons/p5.sound.min.js:3"}],"consts":{"RGB":["p5.colorMode"],"HSB":["p5.colorMode"],"HSL":["p5.colorMode"],"CHORD":["p5.arc"],"PIE":["p5.arc"],"OPEN":["p5.arc"],"CENTER":["p5.ellipseMode","p5.rectMode","p5.imageMode","p5.textAlign"],"RADIUS":["p5.ellipseMode","p5.rectMode"],"CORNER":["p5.ellipseMode","p5.rectMode","p5.imageMode"],"CORNERS":["p5.ellipseMode","p5.rectMode","p5.imageMode"],"SQUARE":["p5.strokeCap"],"PROJECT":["p5.strokeCap"],"ROUND":["p5.strokeCap","p5.strokeJoin"],"MITER":["p5.strokeJoin"],"BEVEL":["p5.strokeJoin"],"POINTS":["p5.beginShape"],"LINES":["p5.beginShape"],"TRIANGLES":["p5.beginShape"],"TRIANGLE_FAN":["p5.beginShape"],"TRIANGLE_STRIP":["p5.beginShape"],"QUADS":["p5.beginShape"],"QUAD_STRIP":["p5.beginShape"],"CLOSE":["p5.endShape"],"ARROW":["p5.cursor"],"CROSS":["p5.cursor"],"HAND":["p5.cursor"],"MOVE":["p5.cursor"],"TEXT":["p5.cursor"],"WAIT":["p5.cursor"],"P2D":["p5.createCanvas","p5.createGraphics"],"WEBGL":["p5.createCanvas","p5.createGraphics"],"BLEND":["p5.blendMode","p5.Image.blend","p5.blend"],"DARKEST":["p5.blendMode","p5.Image.blend","p5.blend"],"LIGHTEST":["p5.blendMode","p5.Image.blend","p5.blend"],"DIFFERENCE":["p5.blendMode","p5.Image.blend","p5.blend"],"MULTIPLY":["p5.blendMode","p5.Image.blend","p5.blend"],"EXCLUSION":["p5.blendMode","p5.Image.blend","p5.blend"],"SCREEN":["p5.blendMode","p5.Image.blend","p5.blend"],"REPLACE":["p5.blendMode","p5.Image.blend","p5.blend"],"OVERLAY":["p5.blendMode","p5.Image.blend","p5.blend"],"HARD_LIGHT":["p5.blendMode","p5.Image.blend","p5.blend"],"SOFT_LIGHT":["p5.blendMode","p5.Image.blend","p5.blend"],"DODGE":["p5.blendMode","p5.Image.blend","p5.blend"],"BURN":["p5.blendMode","p5.Image.blend","p5.blend"],"ADD":["p5.blendMode","p5.Image.blend","p5.blend"],"NORMAL":["p5.blendMode","p5.Image.blend","p5.blend","p5.textStyle"],"THRESHOLD":["p5.Image.filter","p5.filter"],"GRAY":["p5.Image.filter","p5.filter"],"OPAQUE":["p5.Image.filter","p5.filter"],"INVERT":["p5.Image.filter","p5.filter"],"POSTERIZE":["p5.Image.filter","p5.filter"],"BLUR":["p5.Image.filter","p5.filter"],"ERODE":["p5.Image.filter","p5.filter"],"DILATE":["p5.Image.filter","p5.filter"],"RADIANS":["p5.angleMode"],"DEGREES":["p5.angleMode"],"LEFT":["p5.textAlign"],"RIGHT":["p5.textAlign"],"TOP":["p5.textAlign"],"BOTTOM":["p5.textAlign"],"BASELINE":["p5.textAlign"],"ITALIC":["p5.textStyle"],"BOLD":["p5.textStyle"],"VIDEO":["p5.createCapture"],"AUDIO":["p5.createCapture"]}};},{}],2:[function(_dereq_,module,exports){var lookup='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';;(function(exports){'use strict';var Arr=typeof Uint8Array!=='undefined'?Uint8Array:Array;var PLUS='+'.charCodeAt(0);var SLASH='/'.charCodeAt(0);var NUMBER='0'.charCodeAt(0);var LOWER='a'.charCodeAt(0);var UPPER='A'.charCodeAt(0);var PLUS_URL_SAFE='-'.charCodeAt(0);var SLASH_URL_SAFE='_'.charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS||code===PLUS_URL_SAFE)return 62;// '+' if(code===SLASH||code===SLASH_URL_SAFE)return 63;// '/' if(code<NUMBER)return-1;//no match if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26;}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error('Invalid string. Length must be a multiple of 4');}// the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len=b64.length;placeHolders='='===b64.charAt(len-2)?2:'='===b64.charAt(len-1)?1:0;// base64 is 4/3 + up to two characters of the original data arr=new Arr(b64.length*3/4-placeHolders);// if there are placeholders, only get up to the last complete 4 chars l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v;}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&0xFF0000)>>16);push((tmp&0xFF00)>>8);push(tmp&0xFF);}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&0xFF);}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&0xFF);push(tmp&0xFF);}return arr;}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,// if we have 1 byte left, pad 2 bytes output="",temp,length;function encode(num){return lookup.charAt(num);}function tripletToBase64(num){return encode(num>>18&0x3F)+encode(num>>12&0x3F)+encode(num>>6&0x3F)+encode(num&0x3F);}// go through the array every three bytes, we'll deal with trailing stuff later for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp);}// pad the end with zeros, but make sure to not forget the extra bytes switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&0x3F);output+='==';break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&0x3F);output+=encode(temp<<2&0x3F);output+='=';break;}return output;}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64;})(typeof exports==='undefined'?this.base64js={}:exports);},{}],3:[function(_dereq_,module,exports){},{}],4:[function(_dereq_,module,exports){(function(global){/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT *//* eslint-disable no-proto */'use strict';var base64=_dereq_('base64-js');var ieee754=_dereq_('ieee754');var isArray=_dereq_('isarray');exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;// not used by this implementation var rootParent={};/** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property * on objects. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();function typedArraySupport(){function Bar(){}try{var arr=new Uint8Array(1);arr.foo=function(){return 42;};arr.constructor=Bar;return arr.foo()===42&&// typed array instances can be augmented arr.constructor===Bar&&// constructor can be set typeof arr.subarray==='function'&&// chrome 9-10 lack `subarray` arr.subarray(1,1).byteLength===0;// ie10 has broken `subarray` }catch(e){return false;}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?0x7fffffff:0x3fffffff;}/** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */function Buffer(arg){if(!(this instanceof Buffer)){// Avoid going through an ArgumentsAdaptorTrampoline in the common case. if(arguments.length>1)return new Buffer(arg,arguments[1]);return new Buffer(arg);}if(!Buffer.TYPED_ARRAY_SUPPORT){this.length=0;this.parent=undefined;}// Common case. if(typeof arg==='number'){return fromNumber(this,arg);}// Slightly less common case. if(typeof arg==='string'){return fromString(this,arg,arguments.length>1?arguments[1]:'utf8');}// Unusual. return fromObject(this,arg);}function fromNumber(that,length){that=allocate(that,length<0?0:checked(length)|0);if(!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<length;i++){that[i]=0;}}return that;}function fromString(that,string,encoding){if(typeof encoding!=='string'||encoding==='')encoding='utf8';// Assumption: byteLength() return value is always < kMaxLength. var length=byteLength(string,encoding)|0;that=allocate(that,length);that.write(string,encoding);return that;}function fromObject(that,object){if(Buffer.isBuffer(object))return fromBuffer(that,object);if(isArray(object))return fromArray(that,object);if(object==null){throw new TypeError('must start with number, buffer, array or string');}if(typeof ArrayBuffer!=='undefined'){if(object.buffer instanceof ArrayBuffer){return fromTypedArray(that,object);}if(object instanceof ArrayBuffer){return fromArrayBuffer(that,object);}}if(object.length)return fromArrayLike(that,object);return fromJsonObject(that,object);}function fromBuffer(that,buffer){var length=checked(buffer.length)|0;that=allocate(that,length);buffer.copy(that,0,0,length);return that;}function fromArray(that,array){var length=checked(array.length)|0;that=allocate(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255;}return that;}// Duplicate of fromArray() to keep fromArray() monomorphic. function fromTypedArray(that,array){var length=checked(array.length)|0;that=allocate(that,length);// Truncating the elements is probably not what people expect from typed // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior // of the old Buffer constructor. for(var i=0;i<length;i+=1){that[i]=array[i]&255;}return that;}function fromArrayBuffer(that,array){if(Buffer.TYPED_ARRAY_SUPPORT){// Return an augmented `Uint8Array` instance, for best performance array.byteLength;that=Buffer._augment(new Uint8Array(array));}else{// Fallback: Return an object instance of the Buffer class that=fromTypedArray(that,new Uint8Array(array));}return that;}function fromArrayLike(that,array){var length=checked(array.length)|0;that=allocate(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255;}return that;}// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. // Returns a zero-length buffer for inputs that don't conform to the spec. function fromJsonObject(that,object){var array;var length=0;if(object.type==='Buffer'&&isArray(object.data)){array=object.data;length=checked(array.length)|0;}that=allocate(that,length);for(var i=0;i<length;i+=1){that[i]=array[i]&255;}return that;}if(Buffer.TYPED_ARRAY_SUPPORT){Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;}else{// pre-set for values that may exist in the future Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined;}function allocate(that,length){if(Buffer.TYPED_ARRAY_SUPPORT){// Return an augmented `Uint8Array` instance, for best performance that=Buffer._augment(new Uint8Array(length));that.__proto__=Buffer.prototype;}else{// Fallback: Return an object instance of the Buffer class that.length=length;that._isBuffer=true;}var fromPool=length!==0&&length<=Buffer.poolSize>>>1;if(fromPool)that.parent=rootParent;return that;}function checked(length){// Note: cannot use `length < kMaxLength` here because that fails when // length is NaN (which is otherwise coerced to zero.) if(length>=kMaxLength()){throw new RangeError('Attempt to allocate Buffer larger than maximum '+'size: 0x'+kMaxLength().toString(16)+' bytes');}return length|0;}function SlowBuffer(subject,encoding){if(!(this instanceof SlowBuffer))return new SlowBuffer(subject,encoding);var buf=new Buffer(subject,encoding);delete buf.parent;return buf;}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer);};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('Arguments must be Buffers');}if(a===b)return 0;var x=a.length;var y=b.length;var i=0;var len=Math.min(x,y);while(i<len){if(a[i]!==b[i])break;++i;}if(i!==len){x=a[i];y=b[i];}if(x<y)return-1;if(y<x)return 1;return 0;};Buffer.isEncoding=function isEncoding(encoding){switch(String(encoding).toLowerCase()){case'hex':case'utf8':case'utf-8':case'ascii':case'binary':case'base64':case'raw':case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return true;default:return false;}};Buffer.concat=function concat(list,length){if(!isArray(list))throw new TypeError('list argument must be an Array of Buffers.');if(list.length===0){return new Buffer(0);}var i;if(length===undefined){length=0;for(i=0;i<list.length;i++){length+=list[i].length;}}var buf=new Buffer(length);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length;}return buf;};function byteLength(string,encoding){if(typeof string!=='string')string=''+string;var len=string.length;if(len===0)return 0;// Use a for loop to avoid recursion var loweredCase=false;for(;;){switch(encoding){case'ascii':case'binary':// Deprecated case'raw':case'raws':return len;case'utf8':case'utf-8':return utf8ToBytes(string).length;case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return len*2;case'hex':return len>>>1;case'base64':return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;// assume utf8 encoding=(''+encoding).toLowerCase();loweredCase=true;}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;start=start|0;end=end===undefined||end===Infinity?this.length:end|0;if(!encoding)encoding='utf8';if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return'';while(true){switch(encoding){case'hex':return hexSlice(this,start,end);case'utf8':case'utf-8':return utf8Slice(this,start,end);case'ascii':return asciiSlice(this,start,end);case'binary':return binarySlice(this,start,end);case'base64':return base64Slice(this,start,end);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding);encoding=(encoding+'').toLowerCase();loweredCase=true;}}}Buffer.prototype.toString=function toString(){var length=this.length|0;if(length===0)return'';if(arguments.length===0)return utf8Slice(this,0,length);return slowToString.apply(this,arguments);};Buffer.prototype.equals=function equals(b){if(!Buffer.isBuffer(b))throw new TypeError('Argument must be a Buffer');if(this===b)return true;return Buffer.compare(this,b)===0;};Buffer.prototype.inspect=function inspect(){var str='';var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString('hex',0,max).match(/.{2}/g).join(' ');if(this.length>max)str+=' ... ';}return'<Buffer '+str+'>';};Buffer.prototype.compare=function compare(b){if(!Buffer.isBuffer(b))throw new TypeError('Argument must be a Buffer');if(this===b)return 0;return Buffer.compare(this,b);};Buffer.prototype.indexOf=function indexOf(val,byteOffset){if(byteOffset>0x7fffffff)byteOffset=0x7fffffff;else if(byteOffset<-0x80000000)byteOffset=-0x80000000;byteOffset>>=0;if(this.length===0)return-1;if(byteOffset>=this.length)return-1;// Negative offsets start from the end of the buffer if(byteOffset<0)byteOffset=Math.max(this.length+byteOffset,0);if(typeof val==='string'){if(val.length===0)return-1;// special case: looking for empty string always fails return String.prototype.indexOf.call(this,val,byteOffset);}if(Buffer.isBuffer(val)){return arrayIndexOf(this,val,byteOffset);}if(typeof val==='number'){if(Buffer.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==='function'){return Uint8Array.prototype.indexOf.call(this,val,byteOffset);}return arrayIndexOf(this,[val],byteOffset);}function arrayIndexOf(arr,val,byteOffset){var foundIndex=-1;for(var i=0;byteOffset+i<arr.length;i++){if(arr[byteOffset+i]===val[foundIndex===-1?0:i-foundIndex]){if(foundIndex===-1)foundIndex=i;if(i-foundIndex+1===val.length)return byteOffset+foundIndex;}else{foundIndex=-1;}}return-1;}throw new TypeError('val must be string, number or Buffer');};// `get` is deprecated Buffer.prototype.get=function get(offset){console.log('.get() is deprecated. Access using array indexes instead.');return this.readUInt8(offset);};// `set` is deprecated Buffer.prototype.set=function set(v,offset){console.log('.set() is deprecated. Access using array indexes instead.');return this.writeUInt8(v,offset);};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining;}else{length=Number(length);if(length>remaining){length=remaining;}}// must be an even number of digits var strLen=string.length;if(strLen%2!==0)throw new Error('Invalid hex string');if(length>strLen/2){length=strLen/2;}for(var i=0;i<length;i++){var parsed=parseInt(string.substr(i*2,2),16);if(isNaN(parsed))throw new Error('Invalid hex string');buf[offset+i]=parsed;}return i;}function utf8Write(buf,string,offset,length){return blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length);}function asciiWrite(buf,string,offset,length){return blitBuffer(asciiToBytes(string),buf,offset,length);}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length);}function base64Write(buf,string,offset,length){return blitBuffer(base64ToBytes(string),buf,offset,length);}function ucs2Write(buf,string,offset,length){return blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length);}Buffer.prototype.write=function write(string,offset,length,encoding){// Buffer#write(string) if(offset===undefined){encoding='utf8';length=this.length;offset=0;// Buffer#write(string, encoding) }else if(length===undefined&&typeof offset==='string'){encoding=offset;length=this.length;offset=0;// Buffer#write(string, offset[, length][, encoding]) }else if(isFinite(offset)){offset=offset|0;if(isFinite(length)){length=length|0;if(encoding===undefined)encoding='utf8';}else{encoding=length;length=undefined;}// legacy write(string, encoding, offset, length) - remove in v0.13 }else{var swap=encoding;encoding=offset;offset=length|0;length=swap;}var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError('attempt to write outside buffer bounds');}if(!encoding)encoding='utf8';var loweredCase=false;for(;;){switch(encoding){case'hex':return hexWrite(this,string,offset,length);case'utf8':case'utf-8':return utf8Write(this,string,offset,length);case'ascii':return asciiWrite(this,string,offset,length);case'binary':return binaryWrite(this,string,offset,length);case'base64':// Warning: maxLength not taken into account in base64Write return base64Write(this,string,offset,length);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding);encoding=(''+encoding).toLowerCase();loweredCase=true;}}};Buffer.prototype.toJSON=function toJSON(){return{type:'Buffer',data:Array.prototype.slice.call(this._arr||this,0)};};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf);}else{return base64.fromByteArray(buf.slice(start,end));}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i<end){var firstByte=buf[i];var codePoint=null;var bytesPerSequence=firstByte>0xEF?4:firstByte>0xDF?3:firstByte>0xBF?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<0x80){codePoint=firstByte;}break;case 2:secondByte=buf[i+1];if((secondByte&0xC0)===0x80){tempCodePoint=(firstByte&0x1F)<<0x6|secondByte&0x3F;if(tempCodePoint>0x7F){codePoint=tempCodePoint;}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0xC|(secondByte&0x3F)<<0x6|thirdByte&0x3F;if(tempCodePoint>0x7FF&&(tempCodePoint<0xD800||tempCodePoint>0xDFFF)){codePoint=tempCodePoint;}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80&&(fourthByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0x12|(secondByte&0x3F)<<0xC|(thirdByte&0x3F)<<0x6|fourthByte&0x3F;if(tempCodePoint>0xFFFF&&tempCodePoint<0x110000){codePoint=tempCodePoint;}}}}if(codePoint===null){// we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint=0xFFFD;bytesPerSequence=1;}else if(codePoint>0xFFFF){// encode to utf16 (surrogate pair dance) codePoint-=0x10000;res.push(codePoint>>>10&0x3FF|0xD800);codePoint=0xDC00|codePoint&0x3FF;}res.push(codePoint);i+=bytesPerSequence;}return decodeCodePointsArray(res);}// Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH=0x1000;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints);// avoid extra slice() }// Decode in chunks to avoid "call stack size exceeded". var res='';var i=0;while(i<len){res+=String.fromCharCode.apply(String,codePoints.slice(i,i+=MAX_ARGUMENTS_LENGTH));}return res;}function asciiSlice(buf,start,end){var ret='';end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i]&0x7F);}return ret;}function binarySlice(buf,start,end){var ret='';end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i]);}return ret;}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out='';for(var i=start;i<end;i++){out+=toHex(buf[i]);}return out;}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res='';for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256);}return res;}Buffer.prototype.slice=function slice(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0;}else if(start>len){start=len;}if(end<0){end+=len;if(end<0)end=0;}else if(end>len){end=len;}if(end<start)end=start;var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=Buffer._augment(this.subarray(start,end));}else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,undefined);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start];}}if(newBuf.length)newBuf.parent=this.parent||this;return newBuf;};/* * Need to make sure that buffer isn't trying to write out of bounds. */function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError('offset is not uint');if(offset+ext>length)throw new RangeError('Trying to access beyond buffer length');}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=0x100)){val+=this[offset+i]*mul;}return val;};Buffer.prototype.readUIntBE=function readUIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert){checkOffset(offset,byteLength,this.length);}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=0x100)){val+=this[offset+--byteLength]*mul;}return val;};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset];};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8;};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1];};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*0x1000000;};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*0x1000000+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3]);};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=0x100)){val+=this[offset+i]*mul;}mul*=0x80;if(val>=mul)val-=Math.pow(2,8*byteLength);return val;};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=0x100)){val+=this[offset+--i]*mul;}mul*=0x80;if(val>=mul)val-=Math.pow(2,8*byteLength);return val;};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&0x80))return this[offset];return(0xff-this[offset]+1)*-1;};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&0x8000?val|0xFFFF0000:val;};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&0x8000?val|0xFFFF0000:val;};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24;};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3];};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4);};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4);};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8);};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8);};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('buffer must be a Buffer instance');if(value>max||value<min)throw new RangeError('value is out of bounds');if(offset+ext>buf.length)throw new RangeError('index out of range');}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var mul=1;var i=0;this[offset]=value&0xFF;while(++i<byteLength&&(mul*=0x100)){this[offset+i]=value/mul&0xFF;}return offset+byteLength;};Buffer.prototype.writeUIntBE=function writeUIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var i=byteLength-1;var mul=1;this[offset+i]=value&0xFF;while(--i>=0&&(mul*=0x100)){this[offset+i]=value/mul&0xFF;}return offset+byteLength;};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,0xff,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&0xff;return offset+1;};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=0xffff+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&0xff<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8;}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0xffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;}else{objectWriteUInt16(this,value,offset,true);}return offset+2;};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0xffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&0xff;}else{objectWriteUInt16(this,value,offset,false);}return offset+2;};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=0xffffffff+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&0xff;}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&0xff;}else{objectWriteUInt32(this,value,offset,true);}return offset+4;};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&0xff;}else{objectWriteUInt32(this,value,offset,false);}return offset+4;};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit);}var i=0;var mul=1;var sub=value<0?1:0;this[offset]=value&0xFF;while(++i<byteLength&&(mul*=0x100)){this[offset+i]=(value/mul>>0)-sub&0xFF;}return offset+byteLength;};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit);}var i=byteLength-1;var mul=1;var sub=value<0?1:0;this[offset+i]=value&0xFF;while(--i>=0&&(mul*=0x100)){this[offset+i]=(value/mul>>0)-sub&0xFF;}return offset+byteLength;};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,0x7f,-0x80);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=0xff+value+1;this[offset]=value&0xff;return offset+1;};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;}else{objectWriteUInt16(this,value,offset,true);}return offset+2;};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&0xff;}else{objectWriteUInt16(this,value,offset,false);}return offset+2;};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;}else{objectWriteUInt32(this,value,offset,true);}return offset+4;};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000);if(value<0)value=0xffffffff+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&0xff;}else{objectWriteUInt32(this,value,offset,false);}return offset+4;};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||value<min)throw new RangeError('value is out of bounds');if(offset+ext>buf.length)throw new RangeError('index out of range');if(offset<0)throw new RangeError('index out of range');}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e+38,-3.4028234663852886e+38);}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4;}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert);};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert);};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157E+308,-1.7976931348623157E+308);}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8;}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert);};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert);};// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end<start)end=start;// Copy 0 bytes; we're done if(end===start)return 0;if(target.length===0||this.length===0)return 0;// Fatal error conditions if(targetStart<0){throw new RangeError('targetStart out of bounds');}if(start<0||start>=this.length)throw new RangeError('sourceStart out of bounds');if(end<0)throw new RangeError('sourceEnd out of bounds');// Are we oob? if(end>this.length)end=this.length;if(target.length-targetStart<end-start){end=target.length-targetStart+start;}var len=end-start;var i;if(this===target&&start<targetStart&&targetStart<end){// descending copy from end for(i=len-1;i>=0;i--){target[i+targetStart]=this[i+start];}}else if(len<1000||!Buffer.TYPED_ARRAY_SUPPORT){// ascending copy from start for(i=0;i<len;i++){target[i+targetStart]=this[i+start];}}else{target._set(this.subarray(start,start+len),targetStart);}return len;};// fill(value, start=0, end=buffer.length) Buffer.prototype.fill=function fill(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new RangeError('end < start');// Fill 0 bytes; we're done if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new RangeError('start out of bounds');if(end<0||end>this.length)throw new RangeError('end out of bounds');var i;if(typeof value==='number'){for(i=start;i<end;i++){this[i]=value;}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len];}}return this;};/** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */Buffer.prototype.toArrayBuffer=function toArrayBuffer(){if(typeof Uint8Array!=='undefined'){if(Buffer.TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer;}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i];}return buf.buffer;}}else{throw new TypeError('Buffer.toArrayBuffer not supported in this browser');}};// HELPER FUNCTIONS // ================ var BP=Buffer.prototype;/** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */Buffer._augment=function _augment(arr){arr.constructor=Buffer;arr._isBuffer=true;// save reference to original Uint8Array set method before overwriting arr._set=arr.set;// deprecated arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.indexOf=BP.indexOf;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUIntLE=BP.readUIntLE;arr.readUIntBE=BP.readUIntBE;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readIntLE=BP.readIntLE;arr.readIntBE=BP.readIntBE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUIntLE=BP.writeUIntLE;arr.writeUIntBE=BP.writeUIntBE;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeIntLE=BP.writeIntLE;arr.writeIntBE=BP.writeIntBE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr;};var INVALID_BASE64_RE=/[^+\/0-9A-Za-z-_]/g;function base64clean(str){// Node strips out invalid characters like \n and \t from the string, base64-js does not str=stringtrim(str).replace(INVALID_BASE64_RE,'');// Node converts strings with length < 2 to '' if(str.length<2)return'';// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while(str.length%4!==0){str=str+'=';}return str;}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,'');}function toHex(n){if(n<16)return'0'+n.toString(16);return n.toString(16);}function utf8ToBytes(string,units){units=units||Infinity;var codePoint;var length=string.length;var leadSurrogate=null;var bytes=[];for(var i=0;i<length;i++){codePoint=string.charCodeAt(i);// is surrogate component if(codePoint>0xD7FF&&codePoint<0xE000){// last char was a lead if(!leadSurrogate){// no lead yet if(codePoint>0xDBFF){// unexpected trail if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);continue;}else if(i+1===length){// unpaired lead if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);continue;}// valid lead leadSurrogate=codePoint;continue;}// 2 leads in a row if(codePoint<0xDC00){if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);leadSurrogate=codePoint;continue;}// valid surrogate pair codePoint=(leadSurrogate-0xD800<<10|codePoint-0xDC00)+0x10000;}else if(leadSurrogate){// valid bmp char, but last char was a lead if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);}leadSurrogate=null;// encode utf8 if(codePoint<0x80){if((units-=1)<0)break;bytes.push(codePoint);}else if(codePoint<0x800){if((units-=2)<0)break;bytes.push(codePoint>>0x6|0xC0,codePoint&0x3F|0x80);}else if(codePoint<0x10000){if((units-=3)<0)break;bytes.push(codePoint>>0xC|0xE0,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80);}else if(codePoint<0x110000){if((units-=4)<0)break;bytes.push(codePoint>>0x12|0xF0,codePoint>>0xC&0x3F|0x80,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80);}else{throw new Error('Invalid code point');}}return bytes;}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){// Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i)&0xFF);}return byteArray;}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi);}return byteArray;}function base64ToBytes(str){return base64.toByteArray(base64clean(str));}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i];}return i;}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"base64-js":2,"ieee754":8,"isarray":9}],5:[function(_dereq_,module,exports){(function(process,global){/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version 4.1.1 */(function(global,factory){(typeof exports==="undefined"?"undefined":_typeof(exports))==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):global.ES6Promise=factory();})(this,function(){'use strict';function objectOrFunction(x){var type=typeof x==="undefined"?"undefined":_typeof(x);return x!==null&&(type==='object'||type==='function');}function isFunction(x){return typeof x==='function';}var _isArray=undefined;if(Array.isArray){_isArray=Array.isArray;}else{_isArray=function _isArray(x){return Object.prototype.toString.call(x)==='[object Array]';};}var isArray=_isArray;var len=0;var vertxNext=undefined;var customSchedulerFn=undefined;var asap=function asap(callback,arg){queue[len]=callback;queue[len+1]=arg;len+=2;if(len===2){// If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if(customSchedulerFn){customSchedulerFn(flush);}else{scheduleFlush();}}};function setScheduler(scheduleFn){customSchedulerFn=scheduleFn;}function setAsap(asapFn){asap=asapFn;}var browserWindow=typeof window!=='undefined'?window:undefined;var browserGlobal=browserWindow||{};var BrowserMutationObserver=browserGlobal.MutationObserver||browserGlobal.WebKitMutationObserver;var isNode=typeof self==='undefined'&&typeof process!=='undefined'&&{}.toString.call(process)==='[object process]';// test for web worker but not in IE10 var isWorker=typeof Uint8ClampedArray!=='undefined'&&typeof importScripts!=='undefined'&&typeof MessageChannel!=='undefined';// node function useNextTick(){// node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function(){return process.nextTick(flush);};}// vertx function useVertxTimer(){if(typeof vertxNext!=='undefined'){return function(){vertxNext(flush);};}return useSetTimeout();}function useMutationObserver(){var iterations=0;var observer=new BrowserMutationObserver(flush);var node=document.createTextNode('');observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2;};}// web worker function useMessageChannel(){var channel=new MessageChannel();channel.port1.onmessage=flush;return function(){return channel.port2.postMessage(0);};}function useSetTimeout(){// Store setTimeout reference so es6-promise will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var globalSetTimeout=setTimeout;return function(){return globalSetTimeout(flush,1);};}var queue=new Array(1000);function flush(){for(var i=0;i<len;i+=2){var callback=queue[i];var arg=queue[i+1];callback(arg);queue[i]=undefined;queue[i+1]=undefined;}len=0;}function attemptVertx(){try{var r=_dereq_;var vertx=r('vertx');vertxNext=vertx.runOnLoop||vertx.runOnContext;return useVertxTimer();}catch(e){return useSetTimeout();}}var scheduleFlush=undefined;// Decide what async method to use to triggering processing of queued callbacks: if(isNode){scheduleFlush=useNextTick();}else if(BrowserMutationObserver){scheduleFlush=useMutationObserver();}else if(isWorker){scheduleFlush=useMessageChannel();}else if(browserWindow===undefined&&typeof _dereq_==='function'){scheduleFlush=attemptVertx();}else{scheduleFlush=useSetTimeout();}function then(onFulfillment,onRejection){var _arguments=arguments;var parent=this;var child=new this.constructor(noop);if(child[PROMISE_ID]===undefined){makePromise(child);}var _state=parent._state;if(_state){(function(){var callback=_arguments[_state-1];asap(function(){return invokeCallback(_state,child,callback,parent._result);});})();}else{subscribe(parent,child,onFulfillment,onRejection);}return child;}/** `Promise.resolve` returns a promise that will become resolved with the passed `value`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ resolve(1); }); promise.then(function(value){ // value === 1 }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.resolve(1); promise.then(function(value){ // value === 1 }); ``` @method resolve @static @param {Any} value value that the returned promise will be resolved with Useful for tooling. @return {Promise} a promise that will become fulfilled with the given `value` */function resolve$1(object){/*jshint validthis:true */var Constructor=this;if(object&&(typeof object==="undefined"?"undefined":_typeof(object))==='object'&&object.constructor===Constructor){return object;}var promise=new Constructor(noop);resolve(promise,object);return promise;}var PROMISE_ID=Math.random().toString(36).substring(16);function noop(){}var PENDING=void 0;var FULFILLED=1;var REJECTED=2;var GET_THEN_ERROR=new ErrorObject();function selfFulfillment(){return new TypeError("You cannot resolve a promise with itself");}function cannotReturnOwn(){return new TypeError('A promises callback cannot return that same promise.');}function getThen(promise){try{return promise.then;}catch(error){GET_THEN_ERROR.error=error;return GET_THEN_ERROR;}}function tryThen(then$$1,value,fulfillmentHandler,rejectionHandler){try{then$$1.call(value,fulfillmentHandler,rejectionHandler);}catch(e){return e;}}function handleForeignThenable(promise,thenable,then$$1){asap(function(promise){var sealed=false;var error=tryThen(then$$1,thenable,function(value){if(sealed){return;}sealed=true;if(thenable!==value){resolve(promise,value);}else{fulfill(promise,value);}},function(reason){if(sealed){return;}sealed=true;reject(promise,reason);},'Settle: '+(promise._label||' unknown promise'));if(!sealed&&error){sealed=true;reject(promise,error);}},promise);}function handleOwnThenable(promise,thenable){if(thenable._state===FULFILLED){fulfill(promise,thenable._result);}else if(thenable._state===REJECTED){reject(promise,thenable._result);}else{subscribe(thenable,undefined,function(value){return resolve(promise,value);},function(reason){return reject(promise,reason);});}}function handleMaybeThenable(promise,maybeThenable,then$$1){if(maybeThenable.constructor===promise.constructor&&then$$1===then&&maybeThenable.constructor.resolve===resolve$1){handleOwnThenable(promise,maybeThenable);}else{if(then$$1===GET_THEN_ERROR){reject(promise,GET_THEN_ERROR.error);GET_THEN_ERROR.error=null;}else if(then$$1===undefined){fulfill(promise,maybeThenable);}else if(isFunction(then$$1)){handleForeignThenable(promise,maybeThenable,then$$1);}else{fulfill(promise,maybeThenable);}}}function resolve(promise,value){if(promise===value){reject(promise,selfFulfillment());}else if(objectOrFunction(value)){handleMaybeThenable(promise,value,getThen(value));}else{fulfill(promise,value);}}function publishRejection(promise){if(promise._onerror){promise._onerror(promise._result);}publish(promise);}function fulfill(promise,value){if(promise._state!==PENDING){return;}promise._result=value;promise._state=FULFILLED;if(promise._subscribers.length!==0){asap(publish,promise);}}function reject(promise,reason){if(promise._state!==PENDING){return;}promise._state=REJECTED;promise._result=reason;asap(publishRejection,promise);}function subscribe(parent,child,onFulfillment,onRejection){var _subscribers=parent._subscribers;var length=_subscribers.length;parent._onerror=null;_subscribers[length]=child;_subscribers[length+FULFILLED]=onFulfillment;_subscribers[length+REJECTED]=onRejection;if(length===0&&parent._state){asap(publish,parent);}}function publish(promise){var subscribers=promise._subscribers;var settled=promise._state;if(subscribers.length===0){return;}var child=undefined,callback=undefined,detail=promise._result;for(var i=0;i<subscribers.length;i+=3){child=subscribers[i];callback=subscribers[i+settled];if(child){invokeCallback(settled,child,callback,detail);}else{callback(detail);}}promise._subscribers.length=0;}function ErrorObject(){this.error=null;}var TRY_CATCH_ERROR=new ErrorObject();function tryCatch(callback,detail){try{return callback(detail);}catch(e){TRY_CATCH_ERROR.error=e;return TRY_CATCH_ERROR;}}function invokeCallback(settled,promise,callback,detail){var hasCallback=isFunction(callback),value=undefined,error=undefined,succeeded=undefined,failed=undefined;if(hasCallback){value=tryCatch(callback,detail);if(value===TRY_CATCH_ERROR){failed=true;error=value.error;value.error=null;}else{succeeded=true;}if(promise===value){reject(promise,cannotReturnOwn());return;}}else{value=detail;succeeded=true;}if(promise._state!==PENDING){// noop }else if(hasCallback&&succeeded){resolve(promise,value);}else if(failed){reject(promise,error);}else if(settled===FULFILLED){fulfill(promise,value);}else if(settled===REJECTED){reject(promise,value);}}function initializePromise(promise,resolver){try{resolver(function resolvePromise(value){resolve(promise,value);},function rejectPromise(reason){reject(promise,reason);});}catch(e){reject(promise,e);}}var id=0;function nextId(){return id++;}function makePromise(promise){promise[PROMISE_ID]=id++;promise._state=undefined;promise._result=undefined;promise._subscribers=[];}function Enumerator$1(Constructor,input){this._instanceConstructor=Constructor;this.promise=new Constructor(noop);if(!this.promise[PROMISE_ID]){makePromise(this.promise);}if(isArray(input)){this.length=input.length;this._remaining=input.length;this._result=new Array(this.length);if(this.length===0){fulfill(this.promise,this._result);}else{this.length=this.length||0;this._enumerate(input);if(this._remaining===0){fulfill(this.promise,this._result);}}}else{reject(this.promise,validationError());}}function validationError(){return new Error('Array Methods must be provided an Array');}Enumerator$1.prototype._enumerate=function(input){for(var i=0;this._state===PENDING&&i<input.length;i++){this._eachEntry(input[i],i);}};Enumerator$1.prototype._eachEntry=function(entry,i){var c=this._instanceConstructor;var resolve$$1=c.resolve;if(resolve$$1===resolve$1){var _then=getThen(entry);if(_then===then&&entry._state!==PENDING){this._settledAt(entry._state,i,entry._result);}else if(typeof _then!=='function'){this._remaining--;this._result[i]=entry;}else if(c===Promise$2){var promise=new c(noop);handleMaybeThenable(promise,entry,_then);this._willSettleAt(promise,i);}else{this._willSettleAt(new c(function(resolve$$1){return resolve$$1(entry);}),i);}}else{this._willSettleAt(resolve$$1(entry),i);}};Enumerator$1.prototype._settledAt=function(state,i,value){var promise=this.promise;if(promise._state===PENDING){this._remaining--;if(state===REJECTED){reject(promise,value);}else{this._result[i]=value;}}if(this._remaining===0){fulfill(promise,this._result);}};Enumerator$1.prototype._willSettleAt=function(promise,i){var enumerator=this;subscribe(promise,undefined,function(value){return enumerator._settledAt(FULFILLED,i,value);},function(reason){return enumerator._settledAt(REJECTED,i,reason);});};/** `Promise.all` accepts an array of promises, and returns a new promise which is fulfilled with an array of fulfillment values for the passed promises, or rejected with the reason of the first passed promise to be rejected. It casts all elements of the passed iterable to promises as it runs this algorithm. Example: ```javascript let promise1 = resolve(1); let promise2 = resolve(2); let promise3 = resolve(3); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `all` are rejected, the first promise that is rejected will be given as an argument to the returned promises's rejection handler. For example: Example: ```javascript let promise1 = resolve(1); let promise2 = reject(new Error("2")); let promise3 = reject(new Error("3")); let promises = [ promise1, promise2, promise3 ]; Promise.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @static @param {Array} entries array of promises @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. @static */function all$1(entries){return new Enumerator$1(this,entries).promise;}/** `Promise.race` returns a new promise which is settled in the same way as the first passed promise to settle. Example: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 2'); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // result === 'promise 2' because it was resolved before promise1 // was resolved. }); ``` `Promise.race` is deterministic in that only the state of the first settled promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first settled promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript let promise1 = new Promise(function(resolve, reject){ setTimeout(function(){ resolve('promise 1'); }, 200); }); let promise2 = new Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error('promise 2')); }, 100); }); Promise.race([promise1, promise2]).then(function(result){ // Code here never runs }, function(reason){ // reason.message === 'promise 2' because promise 2 became rejected before // promise 1 became fulfilled }); ``` An example real-world use case is implementing timeouts: ```javascript Promise.race([ajax('foo.json'), timeout(5000)]) ``` @method race @static @param {Array} promises array of promises to observe Useful for tooling. @return {Promise} a promise which settles in the same way as the first passed promise to settle. */function race$1(entries){/*jshint validthis:true */var Constructor=this;if(!isArray(entries)){return new Constructor(function(_,reject){return reject(new TypeError('You must pass an array to race.'));});}else{return new Constructor(function(resolve,reject){var length=entries.length;for(var i=0;i<length;i++){Constructor.resolve(entries[i]).then(resolve,reject);}});}}/** `Promise.reject` returns a promise rejected with the passed `reason`. It is shorthand for the following: ```javascript let promise = new Promise(function(resolve, reject){ reject(new Error('WHOOPS')); }); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` Instead of writing the above, your code now simply becomes the following: ```javascript let promise = Promise.reject(new Error('WHOOPS')); promise.then(function(value){ // Code here doesn't run because the promise is rejected! }, function(reason){ // reason.message === 'WHOOPS' }); ``` @method reject @static @param {Any} reason value that the returned promise will be rejected with. Useful for tooling. @return {Promise} a promise rejected with the given `reason`. */function reject$1(reason){/*jshint validthis:true */var Constructor=this;var promise=new Constructor(noop);reject(promise,reason);return promise;}function needsResolver(){throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');}function needsNew(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");}/** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js let promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */function Promise$2(resolver){this[PROMISE_ID]=nextId();this._result=this._state=undefined;this._subscribers=[];if(noop!==resolver){typeof resolver!=='function'&&needsResolver();this instanceof Promise$2?initializePromise(this,resolver):needsNew();}}Promise$2.all=all$1;Promise$2.race=race$1;Promise$2.resolve=resolve$1;Promise$2.reject=reject$1;Promise$2._setScheduler=setScheduler;Promise$2._setAsap=setAsap;Promise$2._asap=asap;Promise$2.prototype={constructor:Promise$2,/** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript let result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript let author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */then:then,/** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */'catch':function _catch(onRejection){return this.then(null,onRejection);}};/*global self*/function polyfill$1(){var local=undefined;if(typeof global!=='undefined'){local=global;}else if(typeof self!=='undefined'){local=self;}else{try{local=Function('return this')();}catch(e){throw new Error('polyfill failed because global object is unavailable in this environment');}}var P=local.Promise;if(P){var promiseToString=null;try{promiseToString=Object.prototype.toString.call(P.resolve());}catch(e){// silently ignored }if(promiseToString==='[object Promise]'&&!P.cast){return;}}local.Promise=Promise$2;}// Strange compat.. Promise$2.polyfill=polyfill$1;Promise$2.Promise=Promise$2;return Promise$2;});}).call(this,_dereq_('_process'),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"_process":12}],6:[function(_dereq_,module,exports){(function(global,factory){if(typeof define==='function'&&define.amd){define(['exports','module'],factory);}else if(typeof exports!=='undefined'&&typeof module!=='undefined'){factory(exports,module);}else{var mod={exports:{}};factory(mod.exports,mod);global.fetchJsonp=mod.exports;}})(this,function(exports,module){'use strict';var defaultOptions={timeout:5000,jsonpCallback:'callback',jsonpCallbackFunction:null};function generateCallbackFunction(){return'jsonp_'+Date.now()+'_'+Math.ceil(Math.random()*100000);}function clearFunction(functionName){// IE8 throws an exception when you try to delete a property on window // http://stackoverflow.com/a/1824228/751089 try{delete window[functionName];}catch(e){window[functionName]=undefined;}}function removeScript(scriptId){var script=document.getElementById(scriptId);if(script){document.getElementsByTagName('head')[0].removeChild(script);}}function fetchJsonp(_url){var options=arguments.length<=1||arguments[1]===undefined?{}:arguments[1];// to avoid param reassign var url=_url;var timeout=options.timeout||defaultOptions.timeout;var jsonpCallback=options.jsonpCallback||defaultOptions.jsonpCallback;var timeoutId=undefined;return new Promise(function(resolve,reject){var callbackFunction=options.jsonpCallbackFunction||generateCallbackFunction();var scriptId=jsonpCallback+'_'+callbackFunction;window[callbackFunction]=function(response){resolve({ok:true,// keep consistent with fetch API json:function json(){return Promise.resolve(response);}});if(timeoutId)clearTimeout(timeoutId);removeScript(scriptId);clearFunction(callbackFunction);};// Check if the user set their own params, and if not add a ? to start a list of params url+=url.indexOf('?')===-1?'?':'&';var jsonpScript=document.createElement('script');jsonpScript.setAttribute('src',''+url+jsonpCallback+'='+callbackFunction);if(options.charset){jsonpScript.setAttribute('charset',options.charset);}jsonpScript.id=scriptId;document.getElementsByTagName('head')[0].appendChild(jsonpScript);timeoutId=setTimeout(function(){reject(new Error('JSONP request to '+_url+' timed out'));clearFunction(callbackFunction);removeScript(scriptId);window[callbackFunction]=function(){clearFunction(callbackFunction);};},timeout);// Caught if got 404/500 jsonpScript.onerror=function(){reject(new Error('JSONP request to '+_url+' failed'));clearFunction(callbackFunction);removeScript(scriptId);if(timeoutId)clearTimeout(timeoutId);};});}// export as global function /* let local; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } local.fetchJsonp = fetchJsonp; */module.exports=fetchJsonp;});},{}],7:[function(_dereq_,module,exports){/* FileSaver.js * A saveAs() FileSaver implementation. * 1.3.2 * 2016-06-16 18:25:19 * * By Eli Grey, http://eligrey.com * License: MIT * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md *//*global self *//*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true *//*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */var saveAs=saveAs||function(view){"use strict";// IE <10 is explicitly unsupported if(typeof view==="undefined"||typeof navigator!=="undefined"&&/MSIE [1-9]\./.test(navigator.userAgent)){return;}var doc=view.document// only get URL when necessary in case Blob.js hasn't overridden it yet ,get_URL=function get_URL(){return view.URL||view.webkitURL||view;},save_link=doc.createElementNS("http://www.w3.org/1999/xhtml","a"),can_use_save_link="download"in save_link,click=function click(node){var event=new MouseEvent("click");node.dispatchEvent(event);},is_safari=/constructor/i.test(view.HTMLElement)||view.safari,is_chrome_ios=/CriOS\/[\d]+/.test(navigator.userAgent),throw_outside=function throw_outside(ex){(view.setImmediate||view.setTimeout)(function(){throw ex;},0);},force_saveable_type="application/octet-stream"// the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to ,arbitrary_revoke_timeout=1000*40// in ms ,revoke=function revoke(file){var revoker=function revoker(){if(typeof file==="string"){// file is an object URL get_URL().revokeObjectURL(file);}else{// file is a File file.remove();}};setTimeout(revoker,arbitrary_revoke_timeout);},dispatch=function dispatch(filesaver,event_types,event){event_types=[].concat(event_types);var i=event_types.length;while(i--){var listener=filesaver["on"+event_types[i]];if(typeof listener==="function"){try{listener.call(filesaver,event||filesaver);}catch(ex){throw_outside(ex);}}}},auto_bom=function auto_bom(blob){// prepend BOM for UTF-8 XML and text/* types (including HTML) // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF if(/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)){return new Blob([String.fromCharCode(0xFEFF),blob],{type:blob.type});}return blob;},FileSaver=function FileSaver(blob,name,no_auto_bom){if(!no_auto_bom){blob=auto_bom(blob);}// First try a.download, then web filesystem, then object URLs var filesaver=this,type=blob.type,force=type===force_saveable_type,object_url,dispatch_all=function dispatch_all(){dispatch(filesaver,"writestart progress write writeend".split(" "));}// on any filesys errors revert to saving with object URLs ,fs_error=function fs_error(){if((is_chrome_ios||force&&is_safari)&&view.FileReader){// Safari doesn't allow downloading of blob urls var reader=new FileReader();reader.onloadend=function(){var url=is_chrome_ios?reader.result:reader.result.replace(/^data:[^;]*;/,'data:attachment/file;');var popup=view.open(url,'_blank');if(!popup)view.location.href=url;url=undefined;// release reference before dispatching filesaver.readyState=filesaver.DONE;dispatch_all();};reader.readAsDataURL(blob);filesaver.readyState=filesaver.INIT;return;}// don't create more object URLs than needed if(!object_url){object_url=get_URL().createObjectURL(blob);}if(force){view.location.href=object_url;}else{var opened=view.open(object_url,"_blank");if(!opened){// Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html view.location.href=object_url;}}filesaver.readyState=filesaver.DONE;dispatch_all();revoke(object_url);};filesaver.readyState=filesaver.INIT;if(can_use_save_link){object_url=get_URL().createObjectURL(blob);setTimeout(function(){save_link.href=object_url;save_link.download=name;click(save_link);dispatch_all();revoke(object_url);filesaver.readyState=filesaver.DONE;});return;}fs_error();},FS_proto=FileSaver.prototype,saveAs=function saveAs(blob,name,no_auto_bom){return new FileSaver(blob,name||blob.name||"download",no_auto_bom);};// IE 10+ (native saveAs) if(typeof navigator!=="undefined"&&navigator.msSaveOrOpenBlob){return function(blob,name,no_auto_bom){name=name||blob.name||"download";if(!no_auto_bom){blob=auto_bom(blob);}return navigator.msSaveOrOpenBlob(blob,name);};}FS_proto.abort=function(){};FS_proto.readyState=FS_proto.INIT=0;FS_proto.WRITING=1;FS_proto.DONE=2;FS_proto.error=FS_proto.onwritestart=FS_proto.onprogress=FS_proto.onwrite=FS_proto.onabort=FS_proto.onerror=FS_proto.onwriteend=null;return saveAs;}(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||this.content);// `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window if(typeof module!=="undefined"&&module.exports){module.exports.saveAs=saveAs;}else if(typeof define!=="undefined"&&define!==null&&define.amd!==null){define("FileSaver.js",function(){return saveAs;});}},{}],8:[function(_dereq_,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias;}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity;}else{m=m+Math.pow(2,mLen);e=e-eBias;}return(s?-1:1)*m*Math.pow(2,e-mLen);};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<<eLen)-1;var eBias=eMax>>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax;}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2;}if(e+eBias>=1){value+=rt/c;}else{value+=rt*Math.pow(2,1-eBias);}if(value*c>=2){e++;c/=2;}if(e+eBias>=eMax){m=0;e=eMax;}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias;}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0;}}for(;mLen>=8;buffer[offset+i]=m&0xff,i+=d,m/=256,mLen-=8){}e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&0xff,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128;};},{}],9:[function(_dereq_,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=='[object Array]';};},{}],10:[function(_dereq_,module,exports){/* Copyright 2000, Silicon Graphics, Inc. All Rights Reserved. Copyright 2015, Google Inc. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice including the dates of first publication and either this permission notice or a reference to http://oss.sgi.com/projects/FreeB/ shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL SILICON GRAPHICS, INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Original Code. The Original Code is: OpenGL Sample Implementation, Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. Copyright in any portions created by third parties is as indicated elsewhere herein. All Rights Reserved. */'use strict';var n;function t(a,b){return a.b===b.b&&a.a===b.a;}function u(a,b){return a.b<b.b||a.b===b.b&&a.a<=b.a;}function v(a,b,c){var d=b.b-a.b,e=c.b-b.b;return 0<d+e?d<e?b.a-a.a+d/(d+e)*(a.a-c.a):b.a-c.a+e/(d+e)*(c.a-a.a):0;}function x(a,b,c){var d=b.b-a.b,e=c.b-b.b;return 0<d+e?(b.a-c.a)*d+(b.a-a.a)*e:0;}function z(a,b){return a.a<b.a||a.a===b.a&&a.b<=b.b;}function aa(a,b,c){var d=b.a-a.a,e=c.a-b.a;return 0<d+e?d<e?b.b-a.b+d/(d+e)*(a.b-c.b):b.b-c.b+e/(d+e)*(c.b-a.b):0;}function ba(a,b,c){var d=b.a-a.a,e=c.a-b.a;return 0<d+e?(b.b-c.b)*d+(b.b-a.b)*e:0;}function ca(a){return u(a.b.a,a.a);}function da(a){return u(a.a,a.b.a);}function A(a,b,c,d){a=0>a?0:a;c=0>c?0:c;return a<=c?0===c?(b+d)/2:b+a/(a+c)*(d-b):d+c/(a+c)*(b-d);};function ea(a){var b=B(a.b);C(b,a.c);C(b.b,a.c);D(b,a.a);return b;}function E(a,b){var c=!1,d=!1;a!==b&&(b.a!==a.a&&(d=!0,F(b.a,a.a)),b.d!==a.d&&(c=!0,G(b.d,a.d)),H(b,a),d||(C(b,a.a),a.a.c=a),c||(D(b,a.d),a.d.a=a));}function I(a){var b=a.b,c=!1;a.d!==a.b.d&&(c=!0,G(a.d,a.b.d));a.c===a?F(a.a,null):(a.b.d.a=J(a),a.a.c=a.c,H(a,J(a)),c||D(a,a.d));b.c===b?(F(b.a,null),G(b.d,null)):(a.d.a=J(b),b.a.c=b.c,H(b,J(b)));fa(a);}function K(a){var b=B(a),c=b.b;H(b,a.e);b.a=a.b.a;C(c,b.a);b.d=c.d=a.d;b=b.b;H(a.b,J(a.b));H(a.b,b);a.b.a=b.a;b.b.a.c=b.b;b.b.d=a.b.d;b.f=a.f;b.b.f=a.b.f;return b;}function L(a,b){var c=!1,d=B(a),e=d.b;b.d!==a.d&&(c=!0,G(b.d,a.d));H(d,a.e);H(e,b);d.a=a.b.a;e.a=b.a;d.d=e.d=a.d;a.d.a=e;c||D(d,a.d);return d;}function B(a){var b=new M(),c=new M(),d=a.b.h;c.h=d;d.b.h=b;b.h=a;a.b.h=c;b.b=c;b.c=b;b.e=c;c.b=b;c.c=c;return c.e=b;}function H(a,b){var c=a.c,d=b.c;c.b.e=b;d.b.e=a;a.c=d;b.c=c;}function C(a,b){var c=b.f,d=new N(b,c);c.e=d;b.f=d;c=d.c=a;do{c.a=d,c=c.c;}while(c!==a);}function D(a,b){var c=b.d,d=new ga(b,c);c.b=d;b.d=d;d.a=a;d.c=b.c;c=a;do{c.d=d,c=c.e;}while(c!==a);}function fa(a){var b=a.h;a=a.b.h;b.b.h=a;a.b.h=b;}function F(a,b){var c=a.c,d=c;do{d.a=b,d=d.c;}while(d!==c);c=a.f;d=a.e;d.f=c;c.e=d;}function G(a,b){var c=a.a,d=c;do{d.d=b,d=d.e;}while(d!==c);c=a.d;d=a.b;d.d=c;c.b=d;};function ha(a){var b=0;Math.abs(a[1])>Math.abs(a[0])&&(b=1);Math.abs(a[2])>Math.abs(a[b])&&(b=2);return b;};var O=4*1E150;function P(a,b){a.f+=b.f;a.b.f+=b.b.f;}function ia(a,b,c){a=a.a;b=b.a;c=c.a;if(b.b.a===a)return c.b.a===a?u(b.a,c.a)?0>=x(c.b.a,b.a,c.a):0<=x(b.b.a,c.a,b.a):0>=x(c.b.a,a,c.a);if(c.b.a===a)return 0<=x(b.b.a,a,b.a);b=v(b.b.a,a,b.a);a=v(c.b.a,a,c.a);return b>=a;}function Q(a){a.a.i=null;var b=a.e;b.a.c=b.c;b.c.a=b.a;a.e=null;}function ja(a,b){I(a.a);a.c=!1;a.a=b;b.i=a;}function ka(a){var b=a.a.a;do{a=R(a);}while(a.a.a===b);a.c&&(b=L(S(a).a.b,a.a.e),ja(a,b),a=R(a));return a;}function la(a,b,c){var d=new ma();d.a=c;d.e=na(a.f,b.e,d);return c.i=d;}function oa(a,b){switch(a.s){case 100130:return 0!==(b&1);case 100131:return 0!==b;case 100132:return 0<b;case 100133:return 0>b;case 100134:return 2<=b||-2>=b;}return!1;}function pa(a){var b=a.a,c=b.d;c.c=a.d;c.a=b;Q(a);}function T(a,b,c){a=b;for(b=b.a;a!==c;){a.c=!1;var d=S(a),e=d.a;if(e.a!==b.a){if(!d.c){pa(a);break;}e=L(b.c.b,e.b);ja(d,e);}b.c!==e&&(E(J(e),e),E(b,e));pa(a);b=d.a;a=d;}return b;}function U(a,b,c,d,e,f){var g=!0;do{la(a,b,c.b),c=c.c;}while(c!==d);for(null===e&&(e=S(b).a.b.c);;){d=S(b);c=d.a.b;if(c.a!==e.a)break;c.c!==e&&(E(J(c),c),E(J(e),c));d.f=b.f-c.f;d.d=oa(a,d.f);b.b=!0;!g&&qa(a,b)&&(P(c,e),Q(b),I(e));g=!1;b=d;e=c;}b.b=!0;f&&ra(a,b);}function sa(a,b,c,d,e){var f=[b.g[0],b.g[1],b.g[2]];b.d=null;b.d=a.o?a.o(f,c,d,a.c)||null:null;null===b.d&&(e?a.n||(V(a,100156),a.n=!0):b.d=c[0]);}function ta(a,b,c){var d=[null,null,null,null];d[0]=b.a.d;d[1]=c.a.d;sa(a,b.a,d,[.5,.5,0,0],!1);E(b,c);}function ua(a,b,c,d,e){var f=Math.abs(b.b-a.b)+Math.abs(b.a-a.a),g=Math.abs(c.b-a.b)+Math.abs(c.a-a.a),h=e+1;d[e]=.5*g/(f+g);d[h]=.5*f/(f+g);a.g[0]+=d[e]*b.g[0]+d[h]*c.g[0];a.g[1]+=d[e]*b.g[1]+d[h]*c.g[1];a.g[2]+=d[e]*b.g[2]+d[h]*c.g[2];}function qa(a,b){var c=S(b),d=b.a,e=c.a;if(u(d.a,e.a)){if(0<x(e.b.a,d.a,e.a))return!1;if(!t(d.a,e.a))K(e.b),E(d,J(e)),b.b=c.b=!0;else if(d.a!==e.a){var c=a.e,f=d.a.h;if(0<=f){var c=c.b,g=c.d,h=c.e,k=c.c,l=k[f];g[l]=g[c.a];k[g[l]]=l;l<=--c.a&&(1>=l?W(c,l):u(h[g[l>>1]],h[g[l]])?W(c,l):va(c,l));h[f]=null;k[f]=c.b;c.b=f;}else for(c.c[-(f+1)]=null;0<c.a&&null===c.c[c.d[c.a-1]];){--c.a;}ta(a,J(e),d);}}else{if(0>x(d.b.a,e.a,d.a))return!1;R(b).b=b.b=!0;K(d.b);E(J(e),d);}return!0;}function wa(a,b){var c=S(b),d=b.a,e=c.a,f=d.a,g=e.a,h=d.b.a,k=e.b.a,l=new N();x(h,a.a,f);x(k,a.a,g);if(f===g||Math.min(f.a,h.a)>Math.max(g.a,k.a))return!1;if(u(f,g)){if(0<x(k,f,g))return!1;}else if(0>x(h,g,f))return!1;var r=h,p=f,q=k,y=g,m,w;u(r,p)||(m=r,r=p,p=m);u(q,y)||(m=q,q=y,y=m);u(r,q)||(m=r,r=q,q=m,m=p,p=y,y=m);u(q,p)?u(p,y)?(m=v(r,q,p),w=v(q,p,y),0>m+w&&(m=-m,w=-w),l.b=A(m,q.b,w,p.b)):(m=x(r,q,p),w=-x(r,y,p),0>m+w&&(m=-m,w=-w),l.b=A(m,q.b,w,y.b)):l.b=(q.b+p.b)/2;z(r,p)||(m=r,r=p,p=m);z(q,y)||(m=q,q=y,y=m);z(r,q)||(m=r,r=q,q=m,m=p,p=y,y=m);z(q,p)?z(p,y)?(m=aa(r,q,p),w=aa(q,p,y),0>m+w&&(m=-m,w=-w),l.a=A(m,q.a,w,p.a)):(m=ba(r,q,p),w=-ba(r,y,p),0>m+w&&(m=-m,w=-w),l.a=A(m,q.a,w,y.a)):l.a=(q.a+p.a)/2;u(l,a.a)&&(l.b=a.a.b,l.a=a.a.a);r=u(f,g)?f:g;u(r,l)&&(l.b=r.b,l.a=r.a);if(t(l,f)||t(l,g))return qa(a,b),!1;if(!t(h,a.a)&&0<=x(h,a.a,l)||!t(k,a.a)&&0>=x(k,a.a,l)){if(k===a.a)return K(d.b),E(e.b,d),b=ka(b),d=S(b).a,T(a,S(b),c),U(a,b,J(d),d,d,!0),!0;if(h===a.a){K(e.b);E(d.e,J(e));f=c=b;g=f.a.b.a;do{f=R(f);}while(f.a.b.a===g);b=f;f=S(b).a.b.c;c.a=J(e);e=T(a,c,null);U(a,b,e.c,d.b.c,f,!0);return!0;}0<=x(h,a.a,l)&&(R(b).b=b.b=!0,K(d.b),d.a.b=a.a.b,d.a.a=a.a.a);0>=x(k,a.a,l)&&(b.b=c.b=!0,K(e.b),e.a.b=a.a.b,e.a.a=a.a.a);return!1;}K(d.b);K(e.b);E(J(e),d);d.a.b=l.b;d.a.a=l.a;d.a.h=xa(a.e,d.a);d=d.a;e=[0,0,0,0];l=[f.d,h.d,g.d,k.d];d.g[0]=d.g[1]=d.g[2]=0;ua(d,f,h,e,0);ua(d,g,k,e,2);sa(a,d,l,e,!0);R(b).b=b.b=c.b=!0;return!1;}function ra(a,b){for(var c=S(b);;){for(;c.b;){b=c,c=S(c);}if(!b.b&&(c=b,b=R(b),null===b||!b.b))break;b.b=!1;var d=b.a,e=c.a,f;if(f=d.b.a!==e.b.a)a:{f=b;var g=S(f),h=f.a,k=g.a,l=void 0;if(u(h.b.a,k.b.a)){if(0>x(h.b.a,k.b.a,h.a)){f=!1;break a;}R(f).b=f.b=!0;l=K(h);E(k.b,l);l.d.c=f.d;}else{if(0<x(k.b.a,h.b.a,k.a)){f=!1;break a;}f.b=g.b=!0;l=K(k);E(h.e,k.b);l.b.d.c=f.d;}f=!0;}f&&(c.c?(Q(c),I(e),c=S(b),e=c.a):b.c&&(Q(b),I(d),b=R(c),d=b.a));if(d.a!==e.a)if(d.b.a===e.b.a||b.c||c.c||d.b.a!==a.a&&e.b.a!==a.a)qa(a,b);else if(wa(a,b))break;d.a===e.a&&d.b.a===e.b.a&&(P(e,d),Q(b),I(d),b=R(c));}}function ya(a,b){a.a=b;for(var c=b.c;null===c.i;){if(c=c.c,c===b.c){var c=a,d=b,e=new ma();e.a=d.c.b;var f=c.f,g=f.a;do{g=g.a;}while(null!==g.b&&!f.c(f.b,e,g.b));var f=g.b,h=S(f),e=f.a,g=h.a;if(0===x(e.b.a,d,e.a))e=f.a,t(e.a,d)||t(e.b.a,d)||(K(e.b),f.c&&(I(e.c),f.c=!1),E(d.c,e),ya(c,d));else{var k=u(g.b.a,e.b.a)?f:h,h=void 0;f.d||k.c?(k===f?h=L(d.c.b,e.e):h=L(g.b.c.b,d.c).b,k.c?ja(k,h):(e=c,f=la(c,f,h),f.f=R(f).f+f.a.f,f.d=oa(e,f.f)),ya(c,d)):U(c,f,d.c,d.c,null,!0);}return;}}c=ka(c.i);e=S(c);f=e.a;e=T(a,e,null);if(e.c===f){var f=e,e=f.c,g=S(c),h=c.a,k=g.a,l=!1;h.b.a!==k.b.a&&wa(a,c);t(h.a,a.a)&&(E(J(e),h),c=ka(c),e=S(c).a,T(a,S(c),g),l=!0);t(k.a,a.a)&&(E(f,J(k)),f=T(a,g,null),l=!0);l?U(a,c,f.c,e,e,!0):(u(k.a,h.a)?d=J(k):d=h,d=L(f.c.b,d),U(a,c,d,d.c,d.c,!1),d.b.i.c=!0,ra(a,c));}else U(a,c,e.c,f,f,!0);}function za(a,b){var c=new ma(),d=ea(a.b);d.a.b=O;d.a.a=b;d.b.a.b=-O;d.b.a.a=b;a.a=d.b.a;c.a=d;c.f=0;c.d=!1;c.c=!1;c.h=!0;c.b=!1;d=a.f;d=na(d,d.a,c);c.e=d;};function Aa(a){this.a=new Ba();this.b=a;this.c=ia;}function na(a,b,c){do{b=b.c;}while(null!==b.b&&!a.c(a.b,b.b,c));a=new Ba(c,b.a,b);b.a.c=a;return b.a=a;};function Ba(a,b,c){this.b=a||null;this.a=b||this;this.c=c||this;};function X(){this.d=Y;this.p=this.b=this.q=null;this.j=[0,0,0];this.s=100130;this.n=!1;this.o=this.a=this.e=this.f=null;this.m=!1;this.c=this.r=this.i=this.k=this.l=this.h=null;}var Y=0;n=X.prototype;n.x=function(){Z(this,Y);};n.B=function(a,b){switch(a){case 100142:return;case 100140:switch(b){case 100130:case 100131:case 100132:case 100133:case 100134:this.s=b;return;}break;case 100141:this.m=!!b;return;default:V(this,100900);return;}V(this,100901);};n.y=function(a){switch(a){case 100142:return 0;case 100140:return this.s;case 100141:return this.m;default:V(this,100900);}return!1;};n.A=function(a,b,c){this.j[0]=a;this.j[1]=b;this.j[2]=c;};n.z=function(a,b){var c=b?b:null;switch(a){case 100100:case 100106:this.h=c;break;case 100104:case 100110:this.l=c;break;case 100101:case 100107:this.k=c;break;case 100102:case 100108:this.i=c;break;case 100103:case 100109:this.p=c;break;case 100105:case 100111:this.o=c;break;case 100112:this.r=c;break;default:V(this,100900);}};n.C=function(a,b){var c=!1,d=[0,0,0];Z(this,2);for(var e=0;3>e;++e){var f=a[e];-1E150>f&&(f=-1E150,c=!0);1E150<f&&(f=1E150,c=!0);d[e]=f;}c&&V(this,100155);c=this.q;null===c?(c=ea(this.b),E(c,c.b)):(K(c),c=c.e);c.a.d=b;c.a.g[0]=d[0];c.a.g[1]=d[1];c.a.g[2]=d[2];c.f=1;c.b.f=-1;this.q=c;};n.u=function(a){Z(this,Y);this.d=1;this.b=new Ca();this.c=a;};n.t=function(){Z(this,1);this.d=2;this.q=null;};n.v=function(){Z(this,2);this.d=1;};n.w=function(){Z(this,1);this.d=Y;var a=this.j[0],b=this.j[1],c=this.j[2],d=!1,e=[a,b,c];if(0===a&&0===b&&0===c){for(var b=[-2*1E150,-2*1E150,-2*1E150],f=[2*1E150,2*1E150,2*1E150],c=[],g=[],d=this.b.c,a=d.e;a!==d;a=a.e){for(var h=0;3>h;++h){var k=a.g[h];k<f[h]&&(f[h]=k,g[h]=a);k>b[h]&&(b[h]=k,c[h]=a);}}a=0;b[1]-f[1]>b[0]-f[0]&&(a=1);b[2]-f[2]>b[a]-f[a]&&(a=2);if(f[a]>=b[a])e[0]=0,e[1]=0,e[2]=1;else{b=0;f=g[a];c=c[a];g=[0,0,0];f=[f.g[0]-c.g[0],f.g[1]-c.g[1],f.g[2]-c.g[2]];h=[0,0,0];for(a=d.e;a!==d;a=a.e){h[0]=a.g[0]-c.g[0],h[1]=a.g[1]-c.g[1],h[2]=a.g[2]-c.g[2],g[0]=f[1]*h[2]-f[2]*h[1],g[1]=f[2]*h[0]-f[0]*h[2],g[2]=f[0]*h[1]-f[1]*h[0],k=g[0]*g[0]+g[1]*g[1]+g[2]*g[2],k>b&&(b=k,e[0]=g[0],e[1]=g[1],e[2]=g[2]);}0>=b&&(e[0]=e[1]=e[2]=0,e[ha(f)]=1);}d=!0;}g=ha(e);a=this.b.c;b=(g+1)%3;c=(g+2)%3;g=0<e[g]?1:-1;for(e=a.e;e!==a;e=e.e){e.b=e.g[b],e.a=g*e.g[c];}if(d){e=0;d=this.b.a;for(a=d.b;a!==d;a=a.b){if(b=a.a,!(0>=b.f)){do{e+=(b.a.b-b.b.a.b)*(b.a.a+b.b.a.a),b=b.e;}while(b!==a.a);}}if(0>e)for(e=this.b.c,d=e.e;d!==e;d=d.e){d.a=-d.a;}}this.n=!1;e=this.b.b;for(a=e.h;a!==e;a=d){if(d=a.h,b=a.e,t(a.a,a.b.a)&&a.e.e!==a&&(ta(this,b,a),I(a),a=b,b=a.e),b.e===a){if(b!==a){if(b===d||b===d.b)d=d.h;I(b);}if(a===d||a===d.b)d=d.h;I(a);}}this.e=e=new Da();d=this.b.c;for(a=d.e;a!==d;a=a.e){a.h=xa(e,a);}Ea(e);this.f=new Aa(this);za(this,-O);for(za(this,O);null!==(e=Fa(this.e));){for(;;){a:if(a=this.e,0===a.a)d=Ga(a.b);else if(d=a.c[a.d[a.a-1]],0!==a.b.a&&(a=Ga(a.b),u(a,d))){d=a;break a;}if(null===d||!t(d,e))break;d=Fa(this.e);ta(this,e.c,d.c);}ya(this,e);}this.a=this.f.a.a.b.a.a;for(e=0;null!==(d=this.f.a.a.b);){d.h||++e,Q(d);}this.f=null;e=this.e;e.b=null;e.d=null;this.e=e.c=null;e=this.b;for(a=e.a.b;a!==e.a;a=d){d=a.b,a=a.a,a.e.e===a&&(P(a.c,a),I(a));}if(!this.n){e=this.b;if(this.m)for(a=e.b.h;a!==e.b;a=d){d=a.h,a.b.d.c!==a.d.c?a.f=a.d.c?1:-1:I(a);}else for(a=e.a.b;a!==e.a;a=d){if(d=a.b,a.c){for(a=a.a;u(a.b.a,a.a);a=a.c.b){}for(;u(a.a,a.b.a);a=a.e){}b=a.c.b;for(c=void 0;a.e!==b;){if(u(a.b.a,b.a)){for(;b.e!==a&&(ca(b.e)||0>=x(b.a,b.b.a,b.e.b.a));){c=L(b.e,b),b=c.b;}b=b.c.b;}else{for(;b.e!==a&&(da(a.c.b)||0<=x(a.b.a,a.a,a.c.b.a));){c=L(a,a.c.b),a=c.b;}a=a.e;}}for(;b.e.e!==a;){c=L(b.e,b),b=c.b;}}}if(this.h||this.i||this.k||this.l)if(this.m)for(e=this.b,d=e.a.b;d!==e.a;d=d.b){if(d.c){this.h&&this.h(2,this.c);a=d.a;do{this.k&&this.k(a.a.d,this.c),a=a.e;}while(a!==d.a);this.i&&this.i(this.c);}}else{e=this.b;d=!!this.l;a=!1;b=-1;for(c=e.a.d;c!==e.a;c=c.d){if(c.c){a||(this.h&&this.h(4,this.c),a=!0);g=c.a;do{d&&(f=g.b.d.c?0:1,b!==f&&(b=f,this.l&&this.l(!!b,this.c))),this.k&&this.k(g.a.d,this.c),g=g.e;}while(g!==c.a);}}a&&this.i&&this.i(this.c);}if(this.r){e=this.b;for(a=e.a.b;a!==e.a;a=d){if(d=a.b,!a.c){b=a.a;c=b.e;g=void 0;do{g=c,c=g.e,g.d=null,null===g.b.d&&(g.c===g?F(g.a,null):(g.a.c=g.c,H(g,J(g))),f=g.b,f.c===f?F(f.a,null):(f.a.c=f.c,H(f,J(f))),fa(g));}while(g!==b);b=a.d;a=a.b;a.d=b;b.b=a;}}this.r(this.b);this.c=this.b=null;return;}}this.b=this.c=null;};function Z(a,b){if(a.d!==b)for(;a.d!==b;){if(a.d<b)switch(a.d){case Y:V(a,100151);a.u(null);break;case 1:V(a,100152),a.t();}else switch(a.d){case 2:V(a,100154);a.v();break;case 1:V(a,100153),a.w();}}}function V(a,b){a.p&&a.p(b,a.c);};function ga(a,b){this.b=a||this;this.d=b||this;this.a=null;this.c=!1;};function M(){this.h=this;this.i=this.d=this.a=this.e=this.c=this.b=null;this.f=0;}function J(a){return a.b.e;};function Ca(){this.c=new N();this.a=new ga();this.b=new M();this.d=new M();this.b.b=this.d;this.d.b=this.b;};function N(a,b){this.e=a||this;this.f=b||this;this.d=this.c=null;this.g=[0,0,0];this.h=this.a=this.b=0;};function Da(){this.c=[];this.d=null;this.a=0;this.e=!1;this.b=new Ha();}function Ea(a){a.d=[];for(var b=0;b<a.a;b++){a.d[b]=b;}a.d.sort(function(a){return function(b,e){return u(a[b],a[e])?1:-1;};}(a.c));a.e=!0;Ia(a.b);}function xa(a,b){if(a.e){var c=a.b,d=++c.a;2*d>c.f&&(c.f*=2,c.c=Ja(c.c,c.f+1));var e;0===c.b?e=d:(e=c.b,c.b=c.c[c.b]);c.e[e]=b;c.c[e]=d;c.d[d]=e;c.h&&va(c,d);return e;}c=a.a++;a.c[c]=b;return-(c+1);}function Fa(a){if(0===a.a)return Ka(a.b);var b=a.c[a.d[a.a-1]];if(0!==a.b.a&&u(Ga(a.b),b))return Ka(a.b);do{--a.a;}while(0<a.a&&null===a.c[a.d[a.a-1]]);return b;};function Ha(){this.d=Ja([0],33);this.e=[null,null];this.c=[0,0];this.a=0;this.f=32;this.b=0;this.h=!1;this.d[1]=1;}function Ja(a,b){for(var c=Array(b),d=0;d<a.length;d++){c[d]=a[d];}for(;d<b;d++){c[d]=0;}return c;}function Ia(a){for(var b=a.a;1<=b;--b){W(a,b);}a.h=!0;}function Ga(a){return a.e[a.d[1]];}function Ka(a){var b=a.d,c=a.e,d=a.c,e=b[1],f=c[e];0<a.a&&(b[1]=b[a.a],d[b[1]]=1,c[e]=null,d[e]=a.b,a.b=e,0<--a.a&&W(a,1));return f;}function W(a,b){for(var c=a.d,d=a.e,e=a.c,f=b,g=c[f];;){var h=f<<1;h<a.a&&u(d[c[h+1]],d[c[h]])&&(h+=1);var k=c[h];if(h>a.a||u(d[g],d[k])){c[f]=g;e[g]=f;break;}c[f]=k;e[k]=f;f=h;}}function va(a,b){for(var c=a.d,d=a.e,e=a.c,f=b,g=c[f];;){var h=f>>1,k=c[h];if(0===h||u(d[k],d[g])){c[f]=g;e[g]=f;break;}c[f]=k;e[k]=f;f=h;}};function ma(){this.e=this.a=null;this.f=0;this.c=this.b=this.h=this.d=!1;}function S(a){return a.e.c.b;}function R(a){return a.e.a.b;};this.libtess={GluTesselator:X,windingRule:{GLU_TESS_WINDING_ODD:100130,GLU_TESS_WINDING_NONZERO:100131,GLU_TESS_WINDING_POSITIVE:100132,GLU_TESS_WINDING_NEGATIVE:100133,GLU_TESS_WINDING_ABS_GEQ_TWO:100134},primitiveType:{GL_LINE_LOOP:2,GL_TRIANGLES:4,GL_TRIANGLE_STRIP:5,GL_TRIANGLE_FAN:6},errorType:{GLU_TESS_MISSING_BEGIN_POLYGON:100151,GLU_TESS_MISSING_END_POLYGON:100153,GLU_TESS_MISSING_BEGIN_CONTOUR:100152,GLU_TESS_MISSING_END_CONTOUR:100154,GLU_TESS_COORD_TOO_LARGE:100155,GLU_TESS_NEED_COMBINE_CALLBACK:100156},gluEnum:{GLU_TESS_MESH:100112,GLU_TESS_TOLERANCE:100142,GLU_TESS_WINDING_RULE:100140,GLU_TESS_BOUNDARY_ONLY:100141,GLU_INVALID_ENUM:100900,GLU_INVALID_VALUE:100901,GLU_TESS_BEGIN:100100,GLU_TESS_VERTEX:100101,GLU_TESS_END:100102,GLU_TESS_ERROR:100103,GLU_TESS_EDGE_FLAG:100104,GLU_TESS_COMBINE:100105,GLU_TESS_BEGIN_DATA:100106,GLU_TESS_VERTEX_DATA:100107,GLU_TESS_END_DATA:100108,GLU_TESS_ERROR_DATA:100109,GLU_TESS_EDGE_FLAG_DATA:100110,GLU_TESS_COMBINE_DATA:100111}};X.prototype.gluDeleteTess=X.prototype.x;X.prototype.gluTessProperty=X.prototype.B;X.prototype.gluGetTessProperty=X.prototype.y;X.prototype.gluTessNormal=X.prototype.A;X.prototype.gluTessCallback=X.prototype.z;X.prototype.gluTessVertex=X.prototype.C;X.prototype.gluTessBeginPolygon=X.prototype.u;X.prototype.gluTessBeginContour=X.prototype.t;X.prototype.gluTessEndContour=X.prototype.v;X.prototype.gluTessEndPolygon=X.prototype.w;if(typeof module!=='undefined'){module.exports=this.libtess;}},{}],11:[function(_dereq_,module,exports){(function(Buffer){/** * https://opentype.js.org v0.9.0 | (c) Frederik De Bleser and other contributors | MIT License | Uses tiny-inflate by Devon Govett and string.prototype.codepointat polyfill by Mathias Bynens */(function(global,factory){(typeof exports==="undefined"?"undefined":_typeof(exports))==='object'&&typeof module!=='undefined'?factory(exports):typeof define==='function'&&define.amd?define(['exports'],factory):factory(global.opentype={});})(this,function(exports){'use strict';/*! https://mths.be/codepointat v0.2.0 by @mathias */if(!String.prototype.codePointAt){(function(){var defineProperty=function(){// IE 8 only supports `Object.defineProperty` on DOM elements try{var object={};var $defineProperty=Object.defineProperty;var result=$defineProperty(object,object,object)&&$defineProperty;}catch(error){}return result;}();var codePointAt=function codePointAt(position){if(this==null){throw TypeError();}var string=String(this);var size=string.length;// `ToInteger` var index=position?Number(position):0;if(index!=index){// better `isNaN` index=0;}// Account for out-of-bounds indices: if(index<0||index>=size){return undefined;}// Get the first code unit var first=string.charCodeAt(index);var second;if(// check if it’s the start of a surrogate pair first>=0xD800&&first<=0xDBFF&&// high surrogate size>index+1// there is a next code unit ){second=string.charCodeAt(index+1);if(second>=0xDC00&&second<=0xDFFF){// low surrogate // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return(first-0xD800)*0x400+second-0xDC00+0x10000;}}return first;};if(defineProperty){defineProperty(String.prototype,'codePointAt',{'value':codePointAt,'configurable':true,'writable':true});}else{String.prototype.codePointAt=codePointAt;}})();}var TINF_OK=0;var TINF_DATA_ERROR=-3;function Tree(){this.table=new Uint16Array(16);/* table of code length counts */this.trans=new Uint16Array(288);/* code -> symbol translation table */}function Data(source,dest){this.source=source;this.sourceIndex=0;this.tag=0;this.bitcount=0;this.dest=dest;this.destLen=0;this.ltree=new Tree();/* dynamic length/symbol tree */this.dtree=new Tree();/* dynamic distance tree */}/* --------------------------------------------------- * * -- uninitialized global data (static structures) -- * * --------------------------------------------------- */var sltree=new Tree();var sdtree=new Tree();/* extra bits and base tables for length codes */var length_bits=new Uint8Array(30);var length_base=new Uint16Array(30);/* extra bits and base tables for distance codes */var dist_bits=new Uint8Array(30);var dist_base=new Uint16Array(30);/* special ordering of code length codes */var clcidx=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);/* used by tinf_decode_trees, avoids allocations every call */var code_tree=new Tree();var lengths=new Uint8Array(288+32);/* ----------------------- * * -- utility functions -- * * ----------------------- *//* build extra bits and base tables */function tinf_build_bits_base(bits,base,delta,first){var i,sum;/* build bits table */for(i=0;i<delta;++i){bits[i]=0;}for(i=0;i<30-delta;++i){bits[i+delta]=i/delta|0;}/* build base table */for(sum=first,i=0;i<30;++i){base[i]=sum;sum+=1<<bits[i];}}/* build the fixed huffman trees */function tinf_build_fixed_trees(lt,dt){var i;/* build fixed length tree */for(i=0;i<7;++i){lt.table[i]=0;}lt.table[7]=24;lt.table[8]=152;lt.table[9]=112;for(i=0;i<24;++i){lt.trans[i]=256+i;}for(i=0;i<144;++i){lt.trans[24+i]=i;}for(i=0;i<8;++i){lt.trans[24+144+i]=280+i;}for(i=0;i<112;++i){lt.trans[24+144+8+i]=144+i;}/* build fixed distance tree */for(i=0;i<5;++i){dt.table[i]=0;}dt.table[5]=32;for(i=0;i<32;++i){dt.trans[i]=i;}}/* given an array of code lengths, build a tree */var offs=new Uint16Array(16);function tinf_build_tree(t,lengths,off,num){var i,sum;/* clear code length count table */for(i=0;i<16;++i){t.table[i]=0;}/* scan symbol lengths, and sum code length counts */for(i=0;i<num;++i){t.table[lengths[off+i]]++;}t.table[0]=0;/* compute offset table for distribution sort */for(sum=0,i=0;i<16;++i){offs[i]=sum;sum+=t.table[i];}/* create code->symbol translation table (symbols sorted by code) */for(i=0;i<num;++i){if(lengths[off+i]){t.trans[offs[lengths[off+i]]++]=i;}}}/* ---------------------- * * -- decode functions -- * * ---------------------- *//* get one bit from source stream */function tinf_getbit(d){/* check if tag is empty */if(!d.bitcount--){/* load next tag */d.tag=d.source[d.sourceIndex++];d.bitcount=7;}/* shift bit out of tag */var bit=d.tag&1;d.tag>>>=1;return bit;}/* read a num bit value from a stream and add base */function tinf_read_bits(d,num,base){if(!num){return base;}while(d.bitcount<24){d.tag|=d.source[d.sourceIndex++]<<d.bitcount;d.bitcount+=8;}var val=d.tag&0xffff>>>16-num;d.tag>>>=num;d.bitcount-=num;return val+base;}/* given a data stream and a tree, decode a symbol */function tinf_decode_symbol(d,t){while(d.bitcount<24){d.tag|=d.source[d.sourceIndex++]<<d.bitcount;d.bitcount+=8;}var sum=0,cur=0,len=0;var tag=d.tag;/* get more bits while code value is above sum */do{cur=2*cur+(tag&1);tag>>>=1;++len;sum+=t.table[len];cur-=t.table[len];}while(cur>=0);d.tag=tag;d.bitcount-=len;return t.trans[sum+cur];}/* given a data stream, decode dynamic trees from it */function tinf_decode_trees(d,lt,dt){var hlit,hdist,hclen;var i,num,length;/* get 5 bits HLIT (257-286) */hlit=tinf_read_bits(d,5,257);/* get 5 bits HDIST (1-32) */hdist=tinf_read_bits(d,5,1);/* get 4 bits HCLEN (4-19) */hclen=tinf_read_bits(d,4,4);for(i=0;i<19;++i){lengths[i]=0;}/* read code lengths for code length alphabet */for(i=0;i<hclen;++i){/* get 3 bits code length (0-7) */var clen=tinf_read_bits(d,3,0);lengths[clcidx[i]]=clen;}/* build code length tree */tinf_build_tree(code_tree,lengths,0,19);/* decode code lengths for the dynamic trees */for(num=0;num<hlit+hdist;){var sym=tinf_decode_symbol(d,code_tree);switch(sym){case 16:/* copy previous code length 3-6 times (read 2 bits) */var prev=lengths[num-1];for(length=tinf_read_bits(d,2,3);length;--length){lengths[num++]=prev;}break;case 17:/* repeat code length 0 for 3-10 times (read 3 bits) */for(length=tinf_read_bits(d,3,3);length;--length){lengths[num++]=0;}break;case 18:/* repeat code length 0 for 11-138 times (read 7 bits) */for(length=tinf_read_bits(d,7,11);length;--length){lengths[num++]=0;}break;default:/* values 0-15 represent the actual code lengths */lengths[num++]=sym;break;}}/* build dynamic trees */tinf_build_tree(lt,lengths,0,hlit);tinf_build_tree(dt,lengths,hlit,hdist);}/* ----------------------------- * * -- block inflate functions -- * * ----------------------------- *//* given a stream and two trees, inflate a block of data */function tinf_inflate_block_data(d,lt,dt){while(1){var sym=tinf_decode_symbol(d,lt);/* check for end of block */if(sym===256){return TINF_OK;}if(sym<256){d.dest[d.destLen++]=sym;}else{var length,dist,offs;var i;sym-=257;/* possibly get more bits from length code */length=tinf_read_bits(d,length_bits[sym],length_base[sym]);dist=tinf_decode_symbol(d,dt);/* possibly get more bits from distance code */offs=d.destLen-tinf_read_bits(d,dist_bits[dist],dist_base[dist]);/* copy match */for(i=offs;i<offs+length;++i){d.dest[d.destLen++]=d.dest[i];}}}}/* inflate an uncompressed block of data */function tinf_inflate_uncompressed_block(d){var length,invlength;var i;/* unread from bitbuffer */while(d.bitcount>8){d.sourceIndex--;d.bitcount-=8;}/* get length */length=d.source[d.sourceIndex+1];length=256*length+d.source[d.sourceIndex];/* get one's complement of length */invlength=d.source[d.sourceIndex+3];invlength=256*invlength+d.source[d.sourceIndex+2];/* check length */if(length!==(~invlength&0x0000ffff)){return TINF_DATA_ERROR;}d.sourceIndex+=4;/* copy block */for(i=length;i;--i){d.dest[d.destLen++]=d.source[d.sourceIndex++];}/* make sure we start next block on a byte boundary */d.bitcount=0;return TINF_OK;}/* inflate stream from source to dest */function tinf_uncompress(source,dest){var d=new Data(source,dest);var bfinal,btype,res;do{/* read final block flag */bfinal=tinf_getbit(d);/* read block type (2 bits) */btype=tinf_read_bits(d,2,0);/* decompress block */switch(btype){case 0:/* decompress uncompressed block */res=tinf_inflate_uncompressed_block(d);break;case 1:/* decompress block with fixed huffman trees */res=tinf_inflate_block_data(d,sltree,sdtree);break;case 2:/* decompress block with dynamic huffman trees */tinf_decode_trees(d,d.ltree,d.dtree);res=tinf_inflate_block_data(d,d.ltree,d.dtree);break;default:res=TINF_DATA_ERROR;}if(res!==TINF_OK){throw new Error('Data error');}}while(!bfinal);if(d.destLen<d.dest.length){if(typeof d.dest.slice==='function'){return d.dest.slice(0,d.destLen);}else{return d.dest.subarray(0,d.destLen);}}return d.dest;}/* -------------------- * * -- initialization -- * * -------------------- *//* build fixed huffman trees */tinf_build_fixed_trees(sltree,sdtree);/* build extra bits and base tables */tinf_build_bits_base(length_bits,length_base,4,3);tinf_build_bits_base(dist_bits,dist_base,2,1);/* fix a special case */length_bits[28]=0;length_base[28]=258;var tinyInflate=tinf_uncompress;// The Bounding Box object function derive(v0,v1,v2,v3,t){return Math.pow(1-t,3)*v0+3*Math.pow(1-t,2)*t*v1+3*(1-t)*Math.pow(t,2)*v2+Math.pow(t,3)*v3;}/** * A bounding box is an enclosing box that describes the smallest measure within which all the points lie. * It is used to calculate the bounding box of a glyph or text path. * * On initialization, x1/y1/x2/y2 will be NaN. Check if the bounding box is empty using `isEmpty()`. * * @exports opentype.BoundingBox * @class * @constructor */function BoundingBox(){this.x1=Number.NaN;this.y1=Number.NaN;this.x2=Number.NaN;this.y2=Number.NaN;}/** * Returns true if the bounding box is empty, that is, no points have been added to the box yet. */BoundingBox.prototype.isEmpty=function(){return isNaN(this.x1)||isNaN(this.y1)||isNaN(this.x2)||isNaN(this.y2);};/** * Add the point to the bounding box. * The x1/y1/x2/y2 coordinates of the bounding box will now encompass the given point. * @param {number} x - The X coordinate of the point. * @param {number} y - The Y coordinate of the point. */BoundingBox.prototype.addPoint=function(x,y){if(typeof x==='number'){if(isNaN(this.x1)||isNaN(this.x2)){this.x1=x;this.x2=x;}if(x<this.x1){this.x1=x;}if(x>this.x2){this.x2=x;}}if(typeof y==='number'){if(isNaN(this.y1)||isNaN(this.y2)){this.y1=y;this.y2=y;}if(y<this.y1){this.y1=y;}if(y>this.y2){this.y2=y;}}};/** * Add a X coordinate to the bounding box. * This extends the bounding box to include the X coordinate. * This function is used internally inside of addBezier. * @param {number} x - The X coordinate of the point. */BoundingBox.prototype.addX=function(x){this.addPoint(x,null);};/** * Add a Y coordinate to the bounding box. * This extends the bounding box to include the Y coordinate. * This function is used internally inside of addBezier. * @param {number} y - The Y coordinate of the point. */BoundingBox.prototype.addY=function(y){this.addPoint(null,y);};/** * Add a Bézier curve to the bounding box. * This extends the bounding box to include the entire Bézier. * @param {number} x0 - The starting X coordinate. * @param {number} y0 - The starting Y coordinate. * @param {number} x1 - The X coordinate of the first control point. * @param {number} y1 - The Y coordinate of the first control point. * @param {number} x2 - The X coordinate of the second control point. * @param {number} y2 - The Y coordinate of the second control point. * @param {number} x - The ending X coordinate. * @param {number} y - The ending Y coordinate. */BoundingBox.prototype.addBezier=function(x0,y0,x1,y1,x2,y2,x,y){var this$1=this;// This code is based on http://nishiohirokazu.blogspot.com/2009/06/how-to-calculate-bezier-curves-bounding.html // and https://github.com/icons8/svg-path-bounding-box var p0=[x0,y0];var p1=[x1,y1];var p2=[x2,y2];var p3=[x,y];this.addPoint(x0,y0);this.addPoint(x,y);for(var i=0;i<=1;i++){var b=6*p0[i]-12*p1[i]+6*p2[i];var a=-3*p0[i]+9*p1[i]-9*p2[i]+3*p3[i];var c=3*p1[i]-3*p0[i];if(a===0){if(b===0){continue;}var t=-c/b;if(0<t&&t<1){if(i===0){this$1.addX(derive(p0[i],p1[i],p2[i],p3[i],t));}if(i===1){this$1.addY(derive(p0[i],p1[i],p2[i],p3[i],t));}}continue;}var b2ac=Math.pow(b,2)-4*c*a;if(b2ac<0){continue;}var t1=(-b+Math.sqrt(b2ac))/(2*a);if(0<t1&&t1<1){if(i===0){this$1.addX(derive(p0[i],p1[i],p2[i],p3[i],t1));}if(i===1){this$1.addY(derive(p0[i],p1[i],p2[i],p3[i],t1));}}var t2=(-b-Math.sqrt(b2ac))/(2*a);if(0<t2&&t2<1){if(i===0){this$1.addX(derive(p0[i],p1[i],p2[i],p3[i],t2));}if(i===1){this$1.addY(derive(p0[i],p1[i],p2[i],p3[i],t2));}}}};/** * Add a quadratic curve to the bounding box. * This extends the bounding box to include the entire quadratic curve. * @param {number} x0 - The starting X coordinate. * @param {number} y0 - The starting Y coordinate. * @param {number} x1 - The X coordinate of the control point. * @param {number} y1 - The Y coordinate of the control point. * @param {number} x - The ending X coordinate. * @param {number} y - The ending Y coordinate. */BoundingBox.prototype.addQuad=function(x0,y0,x1,y1,x,y){var cp1x=x0+2/3*(x1-x0);var cp1y=y0+2/3*(y1-y0);var cp2x=cp1x+1/3*(x-x0);var cp2y=cp1y+1/3*(y-y0);this.addBezier(x0,y0,cp1x,cp1y,cp2x,cp2y,x,y);};// Geometric objects /** * A bézier path containing a set of path commands similar to a SVG path. * Paths can be drawn on a context using `draw`. * @exports opentype.Path * @class * @constructor */function Path(){this.commands=[];this.fill='black';this.stroke=null;this.strokeWidth=1;}/** * @param {number} x * @param {number} y */Path.prototype.moveTo=function(x,y){this.commands.push({type:'M',x:x,y:y});};/** * @param {number} x * @param {number} y */Path.prototype.lineTo=function(x,y){this.commands.push({type:'L',x:x,y:y});};/** * Draws cubic curve * @function * curveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control 1 * @param {number} y1 - y of control 1 * @param {number} x2 - x of control 2 * @param {number} y2 - y of control 2 * @param {number} x - x of path point * @param {number} y - y of path point *//** * Draws cubic curve * @function * bezierCurveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control 1 * @param {number} y1 - y of control 1 * @param {number} x2 - x of control 2 * @param {number} y2 - y of control 2 * @param {number} x - x of path point * @param {number} y - y of path point * @see curveTo */Path.prototype.curveTo=Path.prototype.bezierCurveTo=function(x1,y1,x2,y2,x,y){this.commands.push({type:'C',x1:x1,y1:y1,x2:x2,y2:y2,x:x,y:y});};/** * Draws quadratic curve * @function * quadraticCurveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control * @param {number} y1 - y of control * @param {number} x - x of path point * @param {number} y - y of path point *//** * Draws quadratic curve * @function * quadTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control * @param {number} y1 - y of control * @param {number} x - x of path point * @param {number} y - y of path point */Path.prototype.quadTo=Path.prototype.quadraticCurveTo=function(x1,y1,x,y){this.commands.push({type:'Q',x1:x1,y1:y1,x:x,y:y});};/** * Closes the path * @function closePath * @memberof opentype.Path.prototype *//** * Close the path * @function close * @memberof opentype.Path.prototype */Path.prototype.close=Path.prototype.closePath=function(){this.commands.push({type:'Z'});};/** * Add the given path or list of commands to the commands of this path. * @param {Array} pathOrCommands - another opentype.Path, an opentype.BoundingBox, or an array of commands. */Path.prototype.extend=function(pathOrCommands){if(pathOrCommands.commands){pathOrCommands=pathOrCommands.commands;}else if(pathOrCommands instanceof BoundingBox){var box=pathOrCommands;this.moveTo(box.x1,box.y1);this.lineTo(box.x2,box.y1);this.lineTo(box.x2,box.y2);this.lineTo(box.x1,box.y2);this.close();return;}Array.prototype.push.apply(this.commands,pathOrCommands);};/** * Calculate the bounding box of the path. * @returns {opentype.BoundingBox} */Path.prototype.getBoundingBox=function(){var this$1=this;var box=new BoundingBox();var startX=0;var startY=0;var prevX=0;var prevY=0;for(var i=0;i<this.commands.length;i++){var cmd=this$1.commands[i];switch(cmd.type){case'M':box.addPoint(cmd.x,cmd.y);startX=prevX=cmd.x;startY=prevY=cmd.y;break;case'L':box.addPoint(cmd.x,cmd.y);prevX=cmd.x;prevY=cmd.y;break;case'Q':box.addQuad(prevX,prevY,cmd.x1,cmd.y1,cmd.x,cmd.y);prevX=cmd.x;prevY=cmd.y;break;case'C':box.addBezier(prevX,prevY,cmd.x1,cmd.y1,cmd.x2,cmd.y2,cmd.x,cmd.y);prevX=cmd.x;prevY=cmd.y;break;case'Z':prevX=startX;prevY=startY;break;default:throw new Error('Unexpected path command '+cmd.type);}}if(box.isEmpty()){box.addPoint(0,0);}return box;};/** * Draw the path to a 2D context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context. */Path.prototype.draw=function(ctx){var this$1=this;ctx.beginPath();for(var i=0;i<this.commands.length;i+=1){var cmd=this$1.commands[i];if(cmd.type==='M'){ctx.moveTo(cmd.x,cmd.y);}else if(cmd.type==='L'){ctx.lineTo(cmd.x,cmd.y);}else if(cmd.type==='C'){ctx.bezierCurveTo(cmd.x1,cmd.y1,cmd.x2,cmd.y2,cmd.x,cmd.y);}else if(cmd.type==='Q'){ctx.quadraticCurveTo(cmd.x1,cmd.y1,cmd.x,cmd.y);}else if(cmd.type==='Z'){ctx.closePath();}}if(this.fill){ctx.fillStyle=this.fill;ctx.fill();}if(this.stroke){ctx.strokeStyle=this.stroke;ctx.lineWidth=this.strokeWidth;ctx.stroke();}};/** * Convert the Path to a string of path data instructions * See http://www.w3.org/TR/SVG/paths.html#PathData * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values * @return {string} */Path.prototype.toPathData=function(decimalPlaces){var this$1=this;decimalPlaces=decimalPlaces!==undefined?decimalPlaces:2;function floatToString(v){if(Math.round(v)===v){return''+Math.round(v);}else{return v.toFixed(decimalPlaces);}}function packValues(){var arguments$1=arguments;var s='';for(var i=0;i<arguments.length;i+=1){var v=arguments$1[i];if(v>=0&&i>0){s+=' ';}s+=floatToString(v);}return s;}var d='';for(var i=0;i<this.commands.length;i+=1){var cmd=this$1.commands[i];if(cmd.type==='M'){d+='M'+packValues(cmd.x,cmd.y);}else if(cmd.type==='L'){d+='L'+packValues(cmd.x,cmd.y);}else if(cmd.type==='C'){d+='C'+packValues(cmd.x1,cmd.y1,cmd.x2,cmd.y2,cmd.x,cmd.y);}else if(cmd.type==='Q'){d+='Q'+packValues(cmd.x1,cmd.y1,cmd.x,cmd.y);}else if(cmd.type==='Z'){d+='Z';}}return d;};/** * Convert the path to an SVG <path> element, as a string. * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values * @return {string} */Path.prototype.toSVG=function(decimalPlaces){var svg='<path d="';svg+=this.toPathData(decimalPlaces);svg+='"';if(this.fill&&this.fill!=='black'){if(this.fill===null){svg+=' fill="none"';}else{svg+=' fill="'+this.fill+'"';}}if(this.stroke){svg+=' stroke="'+this.stroke+'" stroke-width="'+this.strokeWidth+'"';}svg+='/>';return svg;};/** * Convert the path to a DOM element. * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values * @return {SVGPathElement} */Path.prototype.toDOMElement=function(decimalPlaces){var temporaryPath=this.toPathData(decimalPlaces);var newPath=document.createElementNS('http://www.w3.org/2000/svg','path');newPath.setAttribute('d',temporaryPath);return newPath;};// Run-time checking of preconditions. function fail(message){throw new Error(message);}// Precondition function that checks if the given predicate is true. // If not, it will throw an error. function argument(predicate,message){if(!predicate){fail(message);}}var check={fail:fail,argument:argument,assert:argument};// Data types used in the OpenType font file. var LIMIT16=32768;// The limit at which a 16-bit number switches signs == 2^15 var LIMIT32=2147483648;// The limit at which a 32-bit number switches signs == 2 ^ 31 /** * @exports opentype.decode * @class */var decode={};/** * @exports opentype.encode * @class */var encode={};/** * @exports opentype.sizeOf * @class */var sizeOf={};// Return a function that always returns the same value. function constant(v){return function(){return v;};}// OpenType data types ////////////////////////////////////////////////////// /** * Convert an 8-bit unsigned integer to a list of 1 byte. * @param {number} * @returns {Array} */encode.BYTE=function(v){check.argument(v>=0&&v<=255,'Byte value should be between 0 and 255.');return[v];};/** * @constant * @type {number} */sizeOf.BYTE=constant(1);/** * Convert a 8-bit signed integer to a list of 1 byte. * @param {string} * @returns {Array} */encode.CHAR=function(v){return[v.charCodeAt(0)];};/** * @constant * @type {number} */sizeOf.CHAR=constant(1);/** * Convert an ASCII string to a list of bytes. * @param {string} * @returns {Array} */encode.CHARARRAY=function(v){var b=[];for(var i=0;i<v.length;i+=1){b[i]=v.charCodeAt(i);}return b;};/** * @param {Array} * @returns {number} */sizeOf.CHARARRAY=function(v){return v.length;};/** * Convert a 16-bit unsigned integer to a list of 2 bytes. * @param {number} * @returns {Array} */encode.USHORT=function(v){return[v>>8&0xFF,v&0xFF];};/** * @constant * @type {number} */sizeOf.USHORT=constant(2);/** * Convert a 16-bit signed integer to a list of 2 bytes. * @param {number} * @returns {Array} */encode.SHORT=function(v){// Two's complement if(v>=LIMIT16){v=-(2*LIMIT16-v);}return[v>>8&0xFF,v&0xFF];};/** * @constant * @type {number} */sizeOf.SHORT=constant(2);/** * Convert a 24-bit unsigned integer to a list of 3 bytes. * @param {number} * @returns {Array} */encode.UINT24=function(v){return[v>>16&0xFF,v>>8&0xFF,v&0xFF];};/** * @constant * @type {number} */sizeOf.UINT24=constant(3);/** * Convert a 32-bit unsigned integer to a list of 4 bytes. * @param {number} * @returns {Array} */encode.ULONG=function(v){return[v>>24&0xFF,v>>16&0xFF,v>>8&0xFF,v&0xFF];};/** * @constant * @type {number} */sizeOf.ULONG=constant(4);/** * Convert a 32-bit unsigned integer to a list of 4 bytes. * @param {number} * @returns {Array} */encode.LONG=function(v){// Two's complement if(v>=LIMIT32){v=-(2*LIMIT32-v);}return[v>>24&0xFF,v>>16&0xFF,v>>8&0xFF,v&0xFF];};/** * @constant * @type {number} */sizeOf.LONG=constant(4);encode.FIXED=encode.ULONG;sizeOf.FIXED=sizeOf.ULONG;encode.FWORD=encode.SHORT;sizeOf.FWORD=sizeOf.SHORT;encode.UFWORD=encode.USHORT;sizeOf.UFWORD=sizeOf.USHORT;/** * Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp. * @param {number} * @returns {Array} */encode.LONGDATETIME=function(v){return[0,0,0,0,v>>24&0xFF,v>>16&0xFF,v>>8&0xFF,v&0xFF];};/** * @constant * @type {number} */sizeOf.LONGDATETIME=constant(8);/** * Convert a 4-char tag to a list of 4 bytes. * @param {string} * @returns {Array} */encode.TAG=function(v){check.argument(v.length===4,'Tag should be exactly 4 ASCII characters.');return[v.charCodeAt(0),v.charCodeAt(1),v.charCodeAt(2),v.charCodeAt(3)];};/** * @constant * @type {number} */sizeOf.TAG=constant(4);// CFF data types /////////////////////////////////////////////////////////// encode.Card8=encode.BYTE;sizeOf.Card8=sizeOf.BYTE;encode.Card16=encode.USHORT;sizeOf.Card16=sizeOf.USHORT;encode.OffSize=encode.BYTE;sizeOf.OffSize=sizeOf.BYTE;encode.SID=encode.USHORT;sizeOf.SID=sizeOf.USHORT;// Convert a numeric operand or charstring number to a variable-size list of bytes. /** * Convert a numeric operand or charstring number to a variable-size list of bytes. * @param {number} * @returns {Array} */encode.NUMBER=function(v){if(v>=-107&&v<=107){return[v+139];}else if(v>=108&&v<=1131){v=v-108;return[(v>>8)+247,v&0xFF];}else if(v>=-1131&&v<=-108){v=-v-108;return[(v>>8)+251,v&0xFF];}else if(v>=-32768&&v<=32767){return encode.NUMBER16(v);}else{return encode.NUMBER32(v);}};/** * @param {number} * @returns {number} */sizeOf.NUMBER=function(v){return encode.NUMBER(v).length;};/** * Convert a signed number between -32768 and +32767 to a three-byte value. * This ensures we always use three bytes, but is not the most compact format. * @param {number} * @returns {Array} */encode.NUMBER16=function(v){return[28,v>>8&0xFF,v&0xFF];};/** * @constant * @type {number} */sizeOf.NUMBER16=constant(3);/** * Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value. * This is useful if you want to be sure you always use four bytes, * at the expense of wasting a few bytes for smaller numbers. * @param {number} * @returns {Array} */encode.NUMBER32=function(v){return[29,v>>24&0xFF,v>>16&0xFF,v>>8&0xFF,v&0xFF];};/** * @constant * @type {number} */sizeOf.NUMBER32=constant(5);/** * @param {number} * @returns {Array} */encode.REAL=function(v){var value=v.toString();// Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7) // This code converts it back to a number without the epsilon. var m=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);if(m){var epsilon=parseFloat('1e'+((m[2]?+m[2]:0)+m[1].length));value=(Math.round(v*epsilon)/epsilon).toString();}var nibbles='';for(var i=0,ii=value.length;i<ii;i+=1){var c=value[i];if(c==='e'){nibbles+=value[++i]==='-'?'c':'b';}else if(c==='.'){nibbles+='a';}else if(c==='-'){nibbles+='e';}else{nibbles+=c;}}nibbles+=nibbles.length&1?'f':'ff';var out=[30];for(var i$1=0,ii$1=nibbles.length;i$1<ii$1;i$1+=2){out.push(parseInt(nibbles.substr(i$1,2),16));}return out;};/** * @param {number} * @returns {number} */sizeOf.REAL=function(v){return encode.REAL(v).length;};encode.NAME=encode.CHARARRAY;sizeOf.NAME=sizeOf.CHARARRAY;encode.STRING=encode.CHARARRAY;sizeOf.STRING=sizeOf.CHARARRAY;/** * @param {DataView} data * @param {number} offset * @param {number} numBytes * @returns {string} */decode.UTF8=function(data,offset,numBytes){var codePoints=[];var numChars=numBytes;for(var j=0;j<numChars;j++,offset+=1){codePoints[j]=data.getUint8(offset);}return String.fromCharCode.apply(null,codePoints);};/** * @param {DataView} data * @param {number} offset * @param {number} numBytes * @returns {string} */decode.UTF16=function(data,offset,numBytes){var codePoints=[];var numChars=numBytes/2;for(var j=0;j<numChars;j++,offset+=2){codePoints[j]=data.getUint16(offset);}return String.fromCharCode.apply(null,codePoints);};/** * Convert a JavaScript string to UTF16-BE. * @param {string} * @returns {Array} */encode.UTF16=function(v){var b=[];for(var i=0;i<v.length;i+=1){var codepoint=v.charCodeAt(i);b[b.length]=codepoint>>8&0xFF;b[b.length]=codepoint&0xFF;}return b;};/** * @param {string} * @returns {number} */sizeOf.UTF16=function(v){return v.length*2;};// Data for converting old eight-bit Macintosh encodings to Unicode. // This representation is optimized for decoding; encoding is slower // and needs more memory. The assumption is that all opentype.js users // want to open fonts, but saving a font will be comparatively rare // so it can be more expensive. Keyed by IANA character set name. // // Python script for generating these strings: // // s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)]) // print(s.encode('utf-8')) /** * @private */var eightBitMacEncodings={'x-mac-croatian':// Python: 'mac_croatian' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø'+'¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ','x-mac-cyrillic':// Python: 'mac_cyrillic' 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ'+'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю','x-mac-gaelic':// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø'+'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ','x-mac-greek':// Python: 'mac_greek' 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ'+"\u03AC\u039D\xAC\u039F\u03A1\u2248\u03A4\xAB\xBB\u2026\xA0\u03A5\u03A7\u0386\u0388\u0153\u2013\u2015\u201C\u201D\u2018\u2019\xF7\u0389\u038A\u038C\u038E\u03AD\u03AE\u03AF\u03CC\u038F\u03CD\u03B1\u03B2\u03C8\u03B4\u03B5\u03C6\u03B3\u03B7\u03B9\u03BE\u03BA\u03BB\u03BC\u03BD\u03BF\u03C0\u03CE\u03C1\u03C3\u03C4\u03B8\u03C9\u03C2\u03C7\u03C5\u03B6\u03CA\u03CB\u0390\u03B0\xAD",'x-mac-icelandic':// Python: 'mac_iceland' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø'+'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ','x-mac-inuit':// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ'+'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł','x-mac-ce':// Python: 'mac_latin2' 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ'+'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ',macintosh:// Python: 'mac_roman' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø'+'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ','x-mac-romanian':// Python: 'mac_romanian' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș'+'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ','x-mac-turkish':// Python: 'mac_turkish' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø'+'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ'};/** * Decodes an old-style Macintosh string. Returns either a Unicode JavaScript * string, or 'undefined' if the encoding is unsupported. For example, we do * not support Chinese, Japanese or Korean because these would need large * mapping tables. * @param {DataView} dataView * @param {number} offset * @param {number} dataLength * @param {string} encoding * @returns {string} */decode.MACSTRING=function(dataView,offset,dataLength,encoding){var table=eightBitMacEncodings[encoding];if(table===undefined){return undefined;}var result='';for(var i=0;i<dataLength;i++){var c=dataView.getUint8(offset+i);// In all eight-bit Mac encodings, the characters 0x00..0x7F are // mapped to U+0000..U+007F; we only need to look up the others. if(c<=0x7F){result+=String.fromCharCode(c);}else{result+=table[c&0x7F];}}return result;};// Helper function for encode.MACSTRING. Returns a dictionary for mapping // Unicode character codes to their 8-bit MacOS equivalent. This table // is not exactly a super cheap data structure, but we do not care because // encoding Macintosh strings is only rarely needed in typical applications. var macEncodingTableCache=typeof WeakMap==='function'&&new WeakMap();var macEncodingCacheKeys;var getMacEncodingTable=function getMacEncodingTable(encoding){// Since we use encoding as a cache key for WeakMap, it has to be // a String object and not a literal. And at least on NodeJS 2.10.1, // WeakMap requires that the same String instance is passed for cache hits. if(!macEncodingCacheKeys){macEncodingCacheKeys={};for(var e in eightBitMacEncodings){/*jshint -W053 */// Suppress "Do not use String as a constructor." macEncodingCacheKeys[e]=new String(e);}}var cacheKey=macEncodingCacheKeys[encoding];if(cacheKey===undefined){return undefined;}// We can't do "if (cache.has(key)) {return cache.get(key)}" here: // since garbage collection may run at any time, it could also kick in // between the calls to cache.has() and cache.get(). In that case, // we would return 'undefined' even though we do support the encoding. if(macEncodingTableCache){var cachedTable=macEncodingTableCache.get(cacheKey);if(cachedTable!==undefined){return cachedTable;}}var decodingTable=eightBitMacEncodings[encoding];if(decodingTable===undefined){return undefined;}var encodingTable={};for(var i=0;i<decodingTable.length;i++){encodingTable[decodingTable.charCodeAt(i)]=i+0x80;}if(macEncodingTableCache){macEncodingTableCache.set(cacheKey,encodingTable);}return encodingTable;};/** * Encodes an old-style Macintosh string. Returns a byte array upon success. * If the requested encoding is unsupported, or if the input string contains * a character that cannot be expressed in the encoding, the function returns * 'undefined'. * @param {string} str * @param {string} encoding * @returns {Array} */encode.MACSTRING=function(str,encoding){var table=getMacEncodingTable(encoding);if(table===undefined){return undefined;}var result=[];for(var i=0;i<str.length;i++){var c=str.charCodeAt(i);// In all eight-bit Mac encodings, the characters 0x00..0x7F are // mapped to U+0000..U+007F; we only need to look up the others. if(c>=0x80){c=table[c];if(c===undefined){// str contains a Unicode character that cannot be encoded // in the requested encoding. return undefined;}}result[i]=c;// result.push(c); }return result;};/** * @param {string} str * @param {string} encoding * @returns {number} */sizeOf.MACSTRING=function(str,encoding){var b=encode.MACSTRING(str,encoding);if(b!==undefined){return b.length;}else{return 0;}};// Helper for encode.VARDELTAS function isByteEncodable(value){return value>=-128&&value<=127;}// Helper for encode.VARDELTAS function encodeVarDeltaRunAsZeroes(deltas,pos,result){var runLength=0;var numDeltas=deltas.length;while(pos<numDeltas&&runLength<64&&deltas[pos]===0){++pos;++runLength;}result.push(0x80|runLength-1);return pos;}// Helper for encode.VARDELTAS function encodeVarDeltaRunAsBytes(deltas,offset,result){var runLength=0;var numDeltas=deltas.length;var pos=offset;while(pos<numDeltas&&runLength<64){var value=deltas[pos];if(!isByteEncodable(value)){break;}// Within a byte-encoded run of deltas, a single zero is best // stored literally as 0x00 value. However, if we have two or // more zeroes in a sequence, it is better to start a new run. // Fore example, the sequence of deltas [15, 15, 0, 15, 15] // becomes 6 bytes (04 0F 0F 00 0F 0F) when storing the zero // within the current run, but 7 bytes (01 0F 0F 80 01 0F 0F) // when starting a new run. if(value===0&&pos+1<numDeltas&&deltas[pos+1]===0){break;}++pos;++runLength;}result.push(runLength-1);for(var i=offset;i<pos;++i){result.push(deltas[i]+256&0xff);}return pos;}// Helper for encode.VARDELTAS function encodeVarDeltaRunAsWords(deltas,offset,result){var runLength=0;var numDeltas=deltas.length;var pos=offset;while(pos<numDeltas&&runLength<64){var value=deltas[pos];// Within a word-encoded run of deltas, it is easiest to start // a new run (with a different encoding) whenever we encounter // a zero value. For example, the sequence [0x6666, 0, 0x7777] // needs 7 bytes when storing the zero inside the current run // (42 66 66 00 00 77 77), and equally 7 bytes when starting a // new run (40 66 66 80 40 77 77). if(value===0){break;}// Within a word-encoded run of deltas, a single value in the // range (-128..127) should be encoded within the current run // because it is more compact. For example, the sequence // [0x6666, 2, 0x7777] becomes 7 bytes when storing the value // literally (42 66 66 00 02 77 77), but 8 bytes when starting // a new run (40 66 66 00 02 40 77 77). if(isByteEncodable(value)&&pos+1<numDeltas&&isByteEncodable(deltas[pos+1])){break;}++pos;++runLength;}result.push(0x40|runLength-1);for(var i=offset;i<pos;++i){var val=deltas[i];result.push(val+0x10000>>8&0xff,val+0x100&0xff);}return pos;}/** * Encode a list of variation adjustment deltas. * * Variation adjustment deltas are used in ‘gvar’ and ‘cvar’ tables. * They indicate how points (in ‘gvar’) or values (in ‘cvar’) get adjusted * when generating instances of variation fonts. * * @see https://www.microsoft.com/typography/otspec/gvar.htm * @see https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html * @param {Array} * @return {Array} */encode.VARDELTAS=function(deltas){var pos=0;var result=[];while(pos<deltas.length){var value=deltas[pos];if(value===0){pos=encodeVarDeltaRunAsZeroes(deltas,pos,result);}else if(value>=-128&&value<=127){pos=encodeVarDeltaRunAsBytes(deltas,pos,result);}else{pos=encodeVarDeltaRunAsWords(deltas,pos,result);}}return result;};// Convert a list of values to a CFF INDEX structure. // The values should be objects containing name / type / value. /** * @param {Array} l * @returns {Array} */encode.INDEX=function(l){//var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data, // i, v; // Because we have to know which data type to use to encode the offsets, // we have to go through the values twice: once to encode the data and // calculate the offsets, then again to encode the offsets using the fitting data type. var offset=1;// First offset is always 1. var offsets=[offset];var data=[];for(var i=0;i<l.length;i+=1){var v=encode.OBJECT(l[i]);Array.prototype.push.apply(data,v);offset+=v.length;offsets.push(offset);}if(data.length===0){return[0,0];}var encodedOffsets=[];var offSize=1+Math.floor(Math.log(offset)/Math.log(2))/8|0;var offsetEncoder=[undefined,encode.BYTE,encode.USHORT,encode.UINT24,encode.ULONG][offSize];for(var i$1=0;i$1<offsets.length;i$1+=1){var encodedOffset=offsetEncoder(offsets[i$1]);Array.prototype.push.apply(encodedOffsets,encodedOffset);}return Array.prototype.concat(encode.Card16(l.length),encode.OffSize(offSize),encodedOffsets,data);};/** * @param {Array} * @returns {number} */sizeOf.INDEX=function(v){return encode.INDEX(v).length;};/** * Convert an object to a CFF DICT structure. * The keys should be numeric. * The values should be objects containing name / type / value. * @param {Object} m * @returns {Array} */encode.DICT=function(m){var d=[];var keys=Object.keys(m);var length=keys.length;for(var i=0;i<length;i+=1){// Object.keys() return string keys, but our keys are always numeric. var k=parseInt(keys[i],0);var v=m[k];// Value comes before the key. d=d.concat(encode.OPERAND(v.value,v.type));d=d.concat(encode.OPERATOR(k));}return d;};/** * @param {Object} * @returns {number} */sizeOf.DICT=function(m){return encode.DICT(m).length;};/** * @param {number} * @returns {Array} */encode.OPERATOR=function(v){if(v<1200){return[v];}else{return[12,v-1200];}};/** * @param {Array} v * @param {string} * @returns {Array} */encode.OPERAND=function(v,type){var d=[];if(Array.isArray(type)){for(var i=0;i<type.length;i+=1){check.argument(v.length===type.length,'Not enough arguments given for type'+type);d=d.concat(encode.OPERAND(v[i],type[i]));}}else{if(type==='SID'){d=d.concat(encode.NUMBER(v));}else if(type==='offset'){// We make it easy for ourselves and always encode offsets as // 4 bytes. This makes offset calculation for the top dict easier. d=d.concat(encode.NUMBER32(v));}else if(type==='number'){d=d.concat(encode.NUMBER(v));}else if(type==='real'){d=d.concat(encode.REAL(v));}else{throw new Error('Unknown operand type '+type);// FIXME Add support for booleans }}return d;};encode.OP=encode.BYTE;sizeOf.OP=sizeOf.BYTE;// memoize charstring encoding using WeakMap if available var wmm=typeof WeakMap==='function'&&new WeakMap();/** * Convert a list of CharString operations to bytes. * @param {Array} * @returns {Array} */encode.CHARSTRING=function(ops){// See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))". if(wmm){var cachedValue=wmm.get(ops);if(cachedValue!==undefined){return cachedValue;}}var d=[];var length=ops.length;for(var i=0;i<length;i+=1){var op=ops[i];d=d.concat(encode[op.type](op.value));}if(wmm){wmm.set(ops,d);}return d;};/** * @param {Array} * @returns {number} */sizeOf.CHARSTRING=function(ops){return encode.CHARSTRING(ops).length;};// Utility functions //////////////////////////////////////////////////////// /** * Convert an object containing name / type / value to bytes. * @param {Object} * @returns {Array} */encode.OBJECT=function(v){var encodingFunction=encode[v.type];check.argument(encodingFunction!==undefined,'No encoding function for type '+v.type);return encodingFunction(v.value);};/** * @param {Object} * @returns {number} */sizeOf.OBJECT=function(v){var sizeOfFunction=sizeOf[v.type];check.argument(sizeOfFunction!==undefined,'No sizeOf function for type '+v.type);return sizeOfFunction(v.value);};/** * Convert a table object to bytes. * A table contains a list of fields containing the metadata (name, type and default value). * The table itself has the field values set as attributes. * @param {opentype.Table} * @returns {Array} */encode.TABLE=function(table){var d=[];var length=table.fields.length;var subtables=[];var subtableOffsets=[];for(var i=0;i<length;i+=1){var field=table.fields[i];var encodingFunction=encode[field.type];check.argument(encodingFunction!==undefined,'No encoding function for field type '+field.type+' ('+field.name+')');var value=table[field.name];if(value===undefined){value=field.value;}var bytes=encodingFunction(value);if(field.type==='TABLE'){subtableOffsets.push(d.length);d=d.concat([0,0]);subtables.push(bytes);}else{d=d.concat(bytes);}}for(var i$1=0;i$1<subtables.length;i$1+=1){var o=subtableOffsets[i$1];var offset=d.length;check.argument(offset<65536,'Table '+table.tableName+' too big.');d[o]=offset>>8;d[o+1]=offset&0xff;d=d.concat(subtables[i$1]);}return d;};/** * @param {opentype.Table} * @returns {number} */sizeOf.TABLE=function(table){var numBytes=0;var length=table.fields.length;for(var i=0;i<length;i+=1){var field=table.fields[i];var sizeOfFunction=sizeOf[field.type];check.argument(sizeOfFunction!==undefined,'No sizeOf function for field type '+field.type+' ('+field.name+')');var value=table[field.name];if(value===undefined){value=field.value;}numBytes+=sizeOfFunction(value);// Subtables take 2 more bytes for offsets. if(field.type==='TABLE'){numBytes+=2;}}return numBytes;};encode.RECORD=encode.TABLE;sizeOf.RECORD=sizeOf.TABLE;// Merge in a list of bytes. encode.LITERAL=function(v){return v;};sizeOf.LITERAL=function(v){return v.length;};// Table metadata /** * @exports opentype.Table * @class * @param {string} tableName * @param {Array} fields * @param {Object} options * @constructor */function Table(tableName,fields,options){var this$1=this;for(var i=0;i<fields.length;i+=1){var field=fields[i];this$1[field.name]=field.value;}this.tableName=tableName;this.fields=fields;if(options){var optionKeys=Object.keys(options);for(var i$1=0;i$1<optionKeys.length;i$1+=1){var k=optionKeys[i$1];var v=options[k];if(this$1[k]!==undefined){this$1[k]=v;}}}}/** * Encodes the table and returns an array of bytes * @return {Array} */Table.prototype.encode=function(){return encode.TABLE(this);};/** * Get the size of the table. * @return {number} */Table.prototype.sizeOf=function(){return sizeOf.TABLE(this);};/** * @private */function ushortList(itemName,list,count){if(count===undefined){count=list.length;}var fields=new Array(list.length+1);fields[0]={name:itemName+'Count',type:'USHORT',value:count};for(var i=0;i<list.length;i++){fields[i+1]={name:itemName+i,type:'USHORT',value:list[i]};}return fields;}/** * @private */function tableList(itemName,records,itemCallback){var count=records.length;var fields=new Array(count+1);fields[0]={name:itemName+'Count',type:'USHORT',value:count};for(var i=0;i<count;i++){fields[i+1]={name:itemName+i,type:'TABLE',value:itemCallback(records[i],i)};}return fields;}/** * @private */function recordList(itemName,records,itemCallback){var count=records.length;var fields=[];fields[0]={name:itemName+'Count',type:'USHORT',value:count};for(var i=0;i<count;i++){fields=fields.concat(itemCallback(records[i],i));}return fields;}// Common Layout Tables /** * @exports opentype.Coverage * @class * @param {opentype.Table} * @constructor * @extends opentype.Table */function Coverage(coverageTable){if(coverageTable.format===1){Table.call(this,'coverageTable',[{name:'coverageFormat',type:'USHORT',value:1}].concat(ushortList('glyph',coverageTable.glyphs)));}else{check.assert(false,'Can\'t create coverage table format 2 yet.');}}Coverage.prototype=Object.create(Table.prototype);Coverage.prototype.constructor=Coverage;function ScriptList(scriptListTable){Table.call(this,'scriptListTable',recordList('scriptRecord',scriptListTable,function(scriptRecord,i){var script=scriptRecord.script;var defaultLangSys=script.defaultLangSys;check.assert(!!defaultLangSys,'Unable to write GSUB: script '+scriptRecord.tag+' has no default language system.');return[{name:'scriptTag'+i,type:'TAG',value:scriptRecord.tag},{name:'script'+i,type:'TABLE',value:new Table('scriptTable',[{name:'defaultLangSys',type:'TABLE',value:new Table('defaultLangSys',[{name:'lookupOrder',type:'USHORT',value:0},{name:'reqFeatureIndex',type:'USHORT',value:defaultLangSys.reqFeatureIndex}].concat(ushortList('featureIndex',defaultLangSys.featureIndexes)))}].concat(recordList('langSys',script.langSysRecords,function(langSysRecord,i){var langSys=langSysRecord.langSys;return[{name:'langSysTag'+i,type:'TAG',value:langSysRecord.tag},{name:'langSys'+i,type:'TABLE',value:new Table('langSys',[{name:'lookupOrder',type:'USHORT',value:0},{name:'reqFeatureIndex',type:'USHORT',value:langSys.reqFeatureIndex}].concat(ushortList('featureIndex',langSys.featureIndexes)))}];})))}];}));}ScriptList.prototype=Object.create(Table.prototype);ScriptList.prototype.constructor=ScriptList;/** * @exports opentype.FeatureList * @class * @param {opentype.Table} * @constructor * @extends opentype.Table */function FeatureList(featureListTable){Table.call(this,'featureListTable',recordList('featureRecord',featureListTable,function(featureRecord,i){var feature=featureRecord.feature;return[{name:'featureTag'+i,type:'TAG',value:featureRecord.tag},{name:'feature'+i,type:'TABLE',value:new Table('featureTable',[{name:'featureParams',type:'USHORT',value:feature.featureParams}].concat(ushortList('lookupListIndex',feature.lookupListIndexes)))}];}));}FeatureList.prototype=Object.create(Table.prototype);FeatureList.prototype.constructor=FeatureList;/** * @exports opentype.LookupList * @class * @param {opentype.Table} * @param {Object} * @constructor * @extends opentype.Table */function LookupList(lookupListTable,subtableMakers){Table.call(this,'lookupListTable',tableList('lookup',lookupListTable,function(lookupTable){var subtableCallback=subtableMakers[lookupTable.lookupType];check.assert(!!subtableCallback,'Unable to write GSUB lookup type '+lookupTable.lookupType+' tables.');return new Table('lookupTable',[{name:'lookupType',type:'USHORT',value:lookupTable.lookupType},{name:'lookupFlag',type:'USHORT',value:lookupTable.lookupFlag}].concat(tableList('subtable',lookupTable.subtables,subtableCallback)));}));}LookupList.prototype=Object.create(Table.prototype);LookupList.prototype.constructor=LookupList;// Record = same as Table, but inlined (a Table has an offset and its data is further in the stream) // Don't use offsets inside Records (probable bug), only in Tables. var table={Table:Table,Record:Table,Coverage:Coverage,ScriptList:ScriptList,FeatureList:FeatureList,LookupList:LookupList,ushortList:ushortList,tableList:tableList,recordList:recordList};// Parsing utility functions // Retrieve an unsigned byte from the DataView. function getByte(dataView,offset){return dataView.getUint8(offset);}// Retrieve an unsigned 16-bit short from the DataView. // The value is stored in big endian. function getUShort(dataView,offset){return dataView.getUint16(offset,false);}// Retrieve a signed 16-bit short from the DataView. // The value is stored in big endian. function getShort(dataView,offset){return dataView.getInt16(offset,false);}// Retrieve an unsigned 32-bit long from the DataView. // The value is stored in big endian. function getULong(dataView,offset){return dataView.getUint32(offset,false);}// Retrieve a 32-bit signed fixed-point number (16.16) from the DataView. // The value is stored in big endian. function getFixed(dataView,offset){var decimal=dataView.getInt16(offset,false);var fraction=dataView.getUint16(offset+2,false);return decimal+fraction/65535;}// Retrieve a 4-character tag from the DataView. // Tags are used to identify tables. function getTag(dataView,offset){var tag='';for(var i=offset;i<offset+4;i+=1){tag+=String.fromCharCode(dataView.getInt8(i));}return tag;}// Retrieve an offset from the DataView. // Offsets are 1 to 4 bytes in length, depending on the offSize argument. function getOffset(dataView,offset,offSize){var v=0;for(var i=0;i<offSize;i+=1){v<<=8;v+=dataView.getUint8(offset+i);}return v;}// Retrieve a number of bytes from start offset to the end offset from the DataView. function getBytes(dataView,startOffset,endOffset){var bytes=[];for(var i=startOffset;i<endOffset;i+=1){bytes.push(dataView.getUint8(i));}return bytes;}// Convert the list of bytes to a string. function bytesToString(bytes){var s='';for(var i=0;i<bytes.length;i+=1){s+=String.fromCharCode(bytes[i]);}return s;}var typeOffsets={byte:1,uShort:2,short:2,uLong:4,fixed:4,longDateTime:8,tag:4};// A stateful parser that changes the offset whenever a value is retrieved. // The data is a DataView. function Parser(data,offset){this.data=data;this.offset=offset;this.relativeOffset=0;}Parser.prototype.parseByte=function(){var v=this.data.getUint8(this.offset+this.relativeOffset);this.relativeOffset+=1;return v;};Parser.prototype.parseChar=function(){var v=this.data.getInt8(this.offset+this.relativeOffset);this.relativeOffset+=1;return v;};Parser.prototype.parseCard8=Parser.prototype.parseByte;Parser.prototype.parseUShort=function(){var v=this.data.getUint16(this.offset+this.relativeOffset);this.relativeOffset+=2;return v;};Parser.prototype.parseCard16=Parser.prototype.parseUShort;Parser.prototype.parseSID=Parser.prototype.parseUShort;Parser.prototype.parseOffset16=Parser.prototype.parseUShort;Parser.prototype.parseShort=function(){var v=this.data.getInt16(this.offset+this.relativeOffset);this.relativeOffset+=2;return v;};Parser.prototype.parseF2Dot14=function(){var v=this.data.getInt16(this.offset+this.relativeOffset)/16384;this.relativeOffset+=2;return v;};Parser.prototype.parseULong=function(){var v=getULong(this.data,this.offset+this.relativeOffset);this.relativeOffset+=4;return v;};Parser.prototype.parseOffset32=Parser.prototype.parseULong;Parser.prototype.parseFixed=function(){var v=getFixed(this.data,this.offset+this.relativeOffset);this.relativeOffset+=4;return v;};Parser.prototype.parseString=function(length){var dataView=this.data;var offset=this.offset+this.relativeOffset;var string='';this.relativeOffset+=length;for(var i=0;i<length;i++){string+=String.fromCharCode(dataView.getUint8(offset+i));}return string;};Parser.prototype.parseTag=function(){return this.parseString(4);};// LONGDATETIME is a 64-bit integer. // JavaScript and unix timestamps traditionally use 32 bits, so we // only take the last 32 bits. // + Since until 2038 those bits will be filled by zeros we can ignore them. Parser.prototype.parseLongDateTime=function(){var v=getULong(this.data,this.offset+this.relativeOffset+4);// Subtract seconds between 01/01/1904 and 01/01/1970 // to convert Apple Mac timestamp to Standard Unix timestamp v-=2082844800;this.relativeOffset+=8;return v;};Parser.prototype.parseVersion=function(minorBase){var major=getUShort(this.data,this.offset+this.relativeOffset);// How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1 // Default returns the correct number if minor = 0xN000 where N is 0-9 // Set minorBase to 1 for tables that use minor = N where N is 0-9 var minor=getUShort(this.data,this.offset+this.relativeOffset+2);this.relativeOffset+=4;if(minorBase===undefined){minorBase=0x1000;}return major+minor/minorBase/10;};Parser.prototype.skip=function(type,amount){if(amount===undefined){amount=1;}this.relativeOffset+=typeOffsets[type]*amount;};///// Parsing lists and records /////////////////////////////// // Parse a list of 32 bit unsigned integers. Parser.prototype.parseULongList=function(count){if(count===undefined){count=this.parseULong();}var offsets=new Array(count);var dataView=this.data;var offset=this.offset+this.relativeOffset;for(var i=0;i<count;i++){offsets[i]=dataView.getUint32(offset);offset+=4;}this.relativeOffset+=count*4;return offsets;};// Parse a list of 16 bit unsigned integers. The length of the list can be read on the stream // or provided as an argument. Parser.prototype.parseOffset16List=Parser.prototype.parseUShortList=function(count){if(count===undefined){count=this.parseUShort();}var offsets=new Array(count);var dataView=this.data;var offset=this.offset+this.relativeOffset;for(var i=0;i<count;i++){offsets[i]=dataView.getUint16(offset);offset+=2;}this.relativeOffset+=count*2;return offsets;};// Parses a list of 16 bit signed integers. Parser.prototype.parseShortList=function(count){var list=new Array(count);var dataView=this.data;var offset=this.offset+this.relativeOffset;for(var i=0;i<count;i++){list[i]=dataView.getInt16(offset);offset+=2;}this.relativeOffset+=count*2;return list;};// Parses a list of bytes. Parser.prototype.parseByteList=function(count){var list=new Array(count);var dataView=this.data;var offset=this.offset+this.relativeOffset;for(var i=0;i<count;i++){list[i]=dataView.getUint8(offset++);}this.relativeOffset+=count;return list;};/** * Parse a list of items. * Record count is optional, if omitted it is read from the stream. * itemCallback is one of the Parser methods. */Parser.prototype.parseList=function(count,itemCallback){var this$1=this;if(!itemCallback){itemCallback=count;count=this.parseUShort();}var list=new Array(count);for(var i=0;i<count;i++){list[i]=itemCallback.call(this$1);}return list;};Parser.prototype.parseList32=function(count,itemCallback){var this$1=this;if(!itemCallback){itemCallback=count;count=this.parseULong();}var list=new Array(count);for(var i=0;i<count;i++){list[i]=itemCallback.call(this$1);}return list;};/** * Parse a list of records. * Record count is optional, if omitted it is read from the stream. * Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } */Parser.prototype.parseRecordList=function(count,recordDescription){var this$1=this;// If the count argument is absent, read it in the stream. if(!recordDescription){recordDescription=count;count=this.parseUShort();}var records=new Array(count);var fields=Object.keys(recordDescription);for(var i=0;i<count;i++){var rec={};for(var j=0;j<fields.length;j++){var fieldName=fields[j];var fieldType=recordDescription[fieldName];rec[fieldName]=fieldType.call(this$1);}records[i]=rec;}return records;};Parser.prototype.parseRecordList32=function(count,recordDescription){var this$1=this;// If the count argument is absent, read it in the stream. if(!recordDescription){recordDescription=count;count=this.parseULong();}var records=new Array(count);var fields=Object.keys(recordDescription);for(var i=0;i<count;i++){var rec={};for(var j=0;j<fields.length;j++){var fieldName=fields[j];var fieldType=recordDescription[fieldName];rec[fieldName]=fieldType.call(this$1);}records[i]=rec;}return records;};// Parse a data structure into an object // Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } Parser.prototype.parseStruct=function(description){var this$1=this;if(typeof description==='function'){return description.call(this);}else{var fields=Object.keys(description);var struct={};for(var j=0;j<fields.length;j++){var fieldName=fields[j];var fieldType=description[fieldName];struct[fieldName]=fieldType.call(this$1);}return struct;}};/** * Parse a GPOS valueRecord * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record * valueFormat is optional, if omitted it is read from the stream. */Parser.prototype.parseValueRecord=function(valueFormat){if(valueFormat===undefined){valueFormat=this.parseUShort();}if(valueFormat===0){// valueFormat2 in kerning pairs is most often 0 // in this case return undefined instead of an empty object, to save space return;}var valueRecord={};if(valueFormat&0x0001){valueRecord.xPlacement=this.parseShort();}if(valueFormat&0x0002){valueRecord.yPlacement=this.parseShort();}if(valueFormat&0x0004){valueRecord.xAdvance=this.parseShort();}if(valueFormat&0x0008){valueRecord.yAdvance=this.parseShort();}// Device table (non-variable font) / VariationIndex table (variable font) not supported // https://docs.microsoft.com/fr-fr/typography/opentype/spec/chapter2#devVarIdxTbls if(valueFormat&0x0010){valueRecord.xPlaDevice=undefined;this.parseShort();}if(valueFormat&0x0020){valueRecord.yPlaDevice=undefined;this.parseShort();}if(valueFormat&0x0040){valueRecord.xAdvDevice=undefined;this.parseShort();}if(valueFormat&0x0080){valueRecord.yAdvDevice=undefined;this.parseShort();}return valueRecord;};/** * Parse a list of GPOS valueRecords * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record * valueFormat and valueCount are read from the stream. */Parser.prototype.parseValueRecordList=function(){var this$1=this;var valueFormat=this.parseUShort();var valueCount=this.parseUShort();var values=new Array(valueCount);for(var i=0;i<valueCount;i++){values[i]=this$1.parseValueRecord(valueFormat);}return values;};Parser.prototype.parsePointer=function(description){var structOffset=this.parseOffset16();if(structOffset>0){// NULL offset => return undefined return new Parser(this.data,this.offset+structOffset).parseStruct(description);}return undefined;};Parser.prototype.parsePointer32=function(description){var structOffset=this.parseOffset32();if(structOffset>0){// NULL offset => return undefined return new Parser(this.data,this.offset+structOffset).parseStruct(description);}return undefined;};/** * Parse a list of offsets to lists of 16-bit integers, * or a list of offsets to lists of offsets to any kind of items. * If itemCallback is not provided, a list of list of UShort is assumed. * If provided, itemCallback is called on each item and must parse the item. * See examples in tables/gsub.js */Parser.prototype.parseListOfLists=function(itemCallback){var this$1=this;var offsets=this.parseOffset16List();var count=offsets.length;var relativeOffset=this.relativeOffset;var list=new Array(count);for(var i=0;i<count;i++){var start=offsets[i];if(start===0){// NULL offset // Add i as owned property to list. Convenient with assert. list[i]=undefined;continue;}this$1.relativeOffset=start;if(itemCallback){var subOffsets=this$1.parseOffset16List();var subList=new Array(subOffsets.length);for(var j=0;j<subOffsets.length;j++){this$1.relativeOffset=start+subOffsets[j];subList[j]=itemCallback.call(this$1);}list[i]=subList;}else{list[i]=this$1.parseUShortList();}}this.relativeOffset=relativeOffset;return list;};///// Complex tables parsing ////////////////////////////////// // Parse a coverage table in a GSUB, GPOS or GDEF table. // https://www.microsoft.com/typography/OTSPEC/chapter2.htm // parser.offset must point to the start of the table containing the coverage. Parser.prototype.parseCoverage=function(){var this$1=this;var startOffset=this.offset+this.relativeOffset;var format=this.parseUShort();var count=this.parseUShort();if(format===1){return{format:1,glyphs:this.parseUShortList(count)};}else if(format===2){var ranges=new Array(count);for(var i=0;i<count;i++){ranges[i]={start:this$1.parseUShort(),end:this$1.parseUShort(),index:this$1.parseUShort()};}return{format:2,ranges:ranges};}throw new Error('0x'+startOffset.toString(16)+': Coverage format must be 1 or 2.');};// Parse a Class Definition Table in a GSUB, GPOS or GDEF table. // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Parser.prototype.parseClassDef=function(){var startOffset=this.offset+this.relativeOffset;var format=this.parseUShort();if(format===1){return{format:1,startGlyph:this.parseUShort(),classes:this.parseUShortList()};}else if(format===2){return{format:2,ranges:this.parseRecordList({start:Parser.uShort,end:Parser.uShort,classId:Parser.uShort})};}throw new Error('0x'+startOffset.toString(16)+': ClassDef format must be 1 or 2.');};///// Static methods /////////////////////////////////// // These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance. Parser.list=function(count,itemCallback){return function(){return this.parseList(count,itemCallback);};};Parser.list32=function(count,itemCallback){return function(){return this.parseList32(count,itemCallback);};};Parser.recordList=function(count,recordDescription){return function(){return this.parseRecordList(count,recordDescription);};};Parser.recordList32=function(count,recordDescription){return function(){return this.parseRecordList32(count,recordDescription);};};Parser.pointer=function(description){return function(){return this.parsePointer(description);};};Parser.pointer32=function(description){return function(){return this.parsePointer32(description);};};Parser.tag=Parser.prototype.parseTag;Parser.byte=Parser.prototype.parseByte;Parser.uShort=Parser.offset16=Parser.prototype.parseUShort;Parser.uShortList=Parser.prototype.parseUShortList;Parser.uLong=Parser.offset32=Parser.prototype.parseULong;Parser.uLongList=Parser.prototype.parseULongList;Parser.struct=Parser.prototype.parseStruct;Parser.coverage=Parser.prototype.parseCoverage;Parser.classDef=Parser.prototype.parseClassDef;///// Script, Feature, Lookup lists /////////////////////////////////////////////// // https://www.microsoft.com/typography/OTSPEC/chapter2.htm var langSysTable={reserved:Parser.uShort,reqFeatureIndex:Parser.uShort,featureIndexes:Parser.uShortList};Parser.prototype.parseScriptList=function(){return this.parsePointer(Parser.recordList({tag:Parser.tag,script:Parser.pointer({defaultLangSys:Parser.pointer(langSysTable),langSysRecords:Parser.recordList({tag:Parser.tag,langSys:Parser.pointer(langSysTable)})})}))||[];};Parser.prototype.parseFeatureList=function(){return this.parsePointer(Parser.recordList({tag:Parser.tag,feature:Parser.pointer({featureParams:Parser.offset16,lookupListIndexes:Parser.uShortList})}))||[];};Parser.prototype.parseLookupList=function(lookupTableParsers){return this.parsePointer(Parser.list(Parser.pointer(function(){var lookupType=this.parseUShort();check.argument(1<=lookupType&&lookupType<=9,'GPOS/GSUB lookup type '+lookupType+' unknown.');var lookupFlag=this.parseUShort();var useMarkFilteringSet=lookupFlag&0x10;return{lookupType:lookupType,lookupFlag:lookupFlag,subtables:this.parseList(Parser.pointer(lookupTableParsers[lookupType])),markFilteringSet:useMarkFilteringSet?this.parseUShort():undefined};})))||[];};Parser.prototype.parseFeatureVariationsList=function(){return this.parsePointer32(function(){var majorVersion=this.parseUShort();var minorVersion=this.parseUShort();check.argument(majorVersion===1&&minorVersion<1,'GPOS/GSUB feature variations table unknown.');var featureVariations=this.parseRecordList32({conditionSetOffset:Parser.offset32,featureTableSubstitutionOffset:Parser.offset32});return featureVariations;})||[];};var parse={getByte:getByte,getCard8:getByte,getUShort:getUShort,getCard16:getUShort,getShort:getShort,getULong:getULong,getFixed:getFixed,getTag:getTag,getOffset:getOffset,getBytes:getBytes,bytesToString:bytesToString,Parser:Parser};// The `cmap` table stores the mappings from characters to glyphs. function parseCmapTableFormat12(cmap,p){//Skip reserved. p.parseUShort();// Length in bytes of the sub-tables. cmap.length=p.parseULong();cmap.language=p.parseULong();var groupCount;cmap.groupCount=groupCount=p.parseULong();cmap.glyphIndexMap={};for(var i=0;i<groupCount;i+=1){var startCharCode=p.parseULong();var endCharCode=p.parseULong();var startGlyphId=p.parseULong();for(var c=startCharCode;c<=endCharCode;c+=1){cmap.glyphIndexMap[c]=startGlyphId;startGlyphId++;}}}function parseCmapTableFormat4(cmap,p,data,start,offset){// Length in bytes of the sub-tables. cmap.length=p.parseUShort();cmap.language=p.parseUShort();// segCount is stored x 2. var segCount;cmap.segCount=segCount=p.parseUShort()>>1;// Skip searchRange, entrySelector, rangeShift. p.skip('uShort',3);// The "unrolled" mapping from character codes to glyph indices. cmap.glyphIndexMap={};var endCountParser=new parse.Parser(data,start+offset+14);var startCountParser=new parse.Parser(data,start+offset+16+segCount*2);var idDeltaParser=new parse.Parser(data,start+offset+16+segCount*4);var idRangeOffsetParser=new parse.Parser(data,start+offset+16+segCount*6);var glyphIndexOffset=start+offset+16+segCount*8;for(var i=0;i<segCount-1;i+=1){var glyphIndex=void 0;var endCount=endCountParser.parseUShort();var startCount=startCountParser.parseUShort();var idDelta=idDeltaParser.parseShort();var idRangeOffset=idRangeOffsetParser.parseUShort();for(var c=startCount;c<=endCount;c+=1){if(idRangeOffset!==0){// The idRangeOffset is relative to the current position in the idRangeOffset array. // Take the current offset in the idRangeOffset array. glyphIndexOffset=idRangeOffsetParser.offset+idRangeOffsetParser.relativeOffset-2;// Add the value of the idRangeOffset, which will move us into the glyphIndex array. glyphIndexOffset+=idRangeOffset;// Then add the character index of the current segment, multiplied by 2 for USHORTs. glyphIndexOffset+=(c-startCount)*2;glyphIndex=parse.getUShort(data,glyphIndexOffset);if(glyphIndex!==0){glyphIndex=glyphIndex+idDelta&0xFFFF;}}else{glyphIndex=c+idDelta&0xFFFF;}cmap.glyphIndexMap[c]=glyphIndex;}}}// Parse the `cmap` table. This table stores the mappings from characters to glyphs. // There are many available formats, but we only support the Windows format 4 and 12. // This function returns a `CmapEncoding` object or null if no supported format could be found. function parseCmapTable(data,start){var cmap={};cmap.version=parse.getUShort(data,start);check.argument(cmap.version===0,'cmap table version should be 0.');// The cmap table can contain many sub-tables, each with their own format. // We're only interested in a "platform 0" (Unicode format) and "platform 3" (Windows format) table. cmap.numTables=parse.getUShort(data,start+2);var offset=-1;for(var i=cmap.numTables-1;i>=0;i-=1){var platformId=parse.getUShort(data,start+4+i*8);var encodingId=parse.getUShort(data,start+4+i*8+2);if(platformId===3&&(encodingId===0||encodingId===1||encodingId===10)||platformId===0&&(encodingId===0||encodingId===1||encodingId===2||encodingId===3||encodingId===4)){offset=parse.getULong(data,start+4+i*8+4);break;}}if(offset===-1){// There is no cmap table in the font that we support. throw new Error('No valid cmap sub-tables found.');}var p=new parse.Parser(data,start+offset);cmap.format=p.parseUShort();if(cmap.format===12){parseCmapTableFormat12(cmap,p);}else if(cmap.format===4){parseCmapTableFormat4(cmap,p,data,start,offset);}else{throw new Error('Only format 4 and 12 cmap tables are supported (found format '+cmap.format+').');}return cmap;}function addSegment(t,code,glyphIndex){t.segments.push({end:code,start:code,delta:-(code-glyphIndex),offset:0,glyphIndex:glyphIndex});}function addTerminatorSegment(t){t.segments.push({end:0xFFFF,start:0xFFFF,delta:1,offset:0});}// Make cmap table, format 4 by default, 12 if needed only function makeCmapTable(glyphs){// Plan 0 is the base Unicode Plan but emojis, for example are on another plan, and needs cmap 12 format (with 32bit) var isPlan0Only=true;var i;// Check if we need to add cmap format 12 or if format 4 only is fine for(i=glyphs.length-1;i>0;i-=1){var g=glyphs.get(i);if(g.unicode>65535){console.log('Adding CMAP format 12 (needed!)');isPlan0Only=false;break;}}var cmapTable=[{name:'version',type:'USHORT',value:0},{name:'numTables',type:'USHORT',value:isPlan0Only?1:2},// CMAP 4 header {name:'platformID',type:'USHORT',value:3},{name:'encodingID',type:'USHORT',value:1},{name:'offset',type:'ULONG',value:isPlan0Only?12:12+8}];if(!isPlan0Only){cmapTable=cmapTable.concat([// CMAP 12 header {name:'cmap12PlatformID',type:'USHORT',value:3},// We encode only for PlatformID = 3 (Windows) because it is supported everywhere {name:'cmap12EncodingID',type:'USHORT',value:10},{name:'cmap12Offset',type:'ULONG',value:0}]);}cmapTable=cmapTable.concat([// CMAP 4 Subtable {name:'format',type:'USHORT',value:4},{name:'cmap4Length',type:'USHORT',value:0},{name:'language',type:'USHORT',value:0},{name:'segCountX2',type:'USHORT',value:0},{name:'searchRange',type:'USHORT',value:0},{name:'entrySelector',type:'USHORT',value:0},{name:'rangeShift',type:'USHORT',value:0}]);var t=new table.Table('cmap',cmapTable);t.segments=[];for(i=0;i<glyphs.length;i+=1){var glyph=glyphs.get(i);for(var j=0;j<glyph.unicodes.length;j+=1){addSegment(t,glyph.unicodes[j],i);}t.segments=t.segments.sort(function(a,b){return a.start-b.start;});}addTerminatorSegment(t);var segCount=t.segments.length;var segCountToRemove=0;// CMAP 4 // Set up parallel segment arrays. var endCounts=[];var startCounts=[];var idDeltas=[];var idRangeOffsets=[];var glyphIds=[];// CMAP 12 var cmap12Groups=[];// Reminder this loop is not following the specification at 100% // The specification -> find suites of characters and make a group // Here we're doing one group for each letter // Doing as the spec can save 8 times (or more) space for(i=0;i<segCount;i+=1){var segment=t.segments[i];// CMAP 4 if(segment.end<=65535&&segment.start<=65535){endCounts=endCounts.concat({name:'end_'+i,type:'USHORT',value:segment.end});startCounts=startCounts.concat({name:'start_'+i,type:'USHORT',value:segment.start});idDeltas=idDeltas.concat({name:'idDelta_'+i,type:'SHORT',value:segment.delta});idRangeOffsets=idRangeOffsets.concat({name:'idRangeOffset_'+i,type:'USHORT',value:segment.offset});if(segment.glyphId!==undefined){glyphIds=glyphIds.concat({name:'glyph_'+i,type:'USHORT',value:segment.glyphId});}}else{// Skip Unicode > 65535 (16bit unsigned max) for CMAP 4, will be added in CMAP 12 segCountToRemove+=1;}// CMAP 12 // Skip Terminator Segment if(!isPlan0Only&&segment.glyphIndex!==undefined){cmap12Groups=cmap12Groups.concat({name:'cmap12Start_'+i,type:'ULONG',value:segment.start});cmap12Groups=cmap12Groups.concat({name:'cmap12End_'+i,type:'ULONG',value:segment.end});cmap12Groups=cmap12Groups.concat({name:'cmap12Glyph_'+i,type:'ULONG',value:segment.glyphIndex});}}// CMAP 4 Subtable t.segCountX2=(segCount-segCountToRemove)*2;t.searchRange=Math.pow(2,Math.floor(Math.log(segCount-segCountToRemove)/Math.log(2)))*2;t.entrySelector=Math.log(t.searchRange/2)/Math.log(2);t.rangeShift=t.segCountX2-t.searchRange;t.fields=t.fields.concat(endCounts);t.fields.push({name:'reservedPad',type:'USHORT',value:0});t.fields=t.fields.concat(startCounts);t.fields=t.fields.concat(idDeltas);t.fields=t.fields.concat(idRangeOffsets);t.fields=t.fields.concat(glyphIds);t.cmap4Length=14+// Subtable header endCounts.length*2+2+// reservedPad startCounts.length*2+idDeltas.length*2+idRangeOffsets.length*2+glyphIds.length*2;if(!isPlan0Only){// CMAP 12 Subtable var cmap12Length=16+// Subtable header cmap12Groups.length*4;t.cmap12Offset=12+2*2+4+t.cmap4Length;t.fields=t.fields.concat([{name:'cmap12Format',type:'USHORT',value:12},{name:'cmap12Reserved',type:'USHORT',value:0},{name:'cmap12Length',type:'ULONG',value:cmap12Length},{name:'cmap12Language',type:'ULONG',value:0},{name:'cmap12nGroups',type:'ULONG',value:cmap12Groups.length/3}]);t.fields=t.fields.concat(cmap12Groups);}return t;}var cmap={parse:parseCmapTable,make:makeCmapTable};// Glyph encoding var cffStandardStrings=['.notdef','space','exclam','quotedbl','numbersign','dollar','percent','ampersand','quoteright','parenleft','parenright','asterisk','plus','comma','hyphen','period','slash','zero','one','two','three','four','five','six','seven','eight','nine','colon','semicolon','less','equal','greater','question','at','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','bracketleft','backslash','bracketright','asciicircum','underscore','quoteleft','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','braceleft','bar','braceright','asciitilde','exclamdown','cent','sterling','fraction','yen','florin','section','currency','quotesingle','quotedblleft','guillemotleft','guilsinglleft','guilsinglright','fi','fl','endash','dagger','daggerdbl','periodcentered','paragraph','bullet','quotesinglbase','quotedblbase','quotedblright','guillemotright','ellipsis','perthousand','questiondown','grave','acute','circumflex','tilde','macron','breve','dotaccent','dieresis','ring','cedilla','hungarumlaut','ogonek','caron','emdash','AE','ordfeminine','Lslash','Oslash','OE','ordmasculine','ae','dotlessi','lslash','oslash','oe','germandbls','onesuperior','logicalnot','mu','trademark','Eth','onehalf','plusminus','Thorn','onequarter','divide','brokenbar','degree','thorn','threequarters','twosuperior','registered','minus','eth','multiply','threesuperior','copyright','Aacute','Acircumflex','Adieresis','Agrave','Aring','Atilde','Ccedilla','Eacute','Ecircumflex','Edieresis','Egrave','Iacute','Icircumflex','Idieresis','Igrave','Ntilde','Oacute','Ocircumflex','Odieresis','Ograve','Otilde','Scaron','Uacute','Ucircumflex','Udieresis','Ugrave','Yacute','Ydieresis','Zcaron','aacute','acircumflex','adieresis','agrave','aring','atilde','ccedilla','eacute','ecircumflex','edieresis','egrave','iacute','icircumflex','idieresis','igrave','ntilde','oacute','ocircumflex','odieresis','ograve','otilde','scaron','uacute','ucircumflex','udieresis','ugrave','yacute','ydieresis','zcaron','exclamsmall','Hungarumlautsmall','dollaroldstyle','dollarsuperior','ampersandsmall','Acutesmall','parenleftsuperior','parenrightsuperior','266 ff','onedotenleader','zerooldstyle','oneoldstyle','twooldstyle','threeoldstyle','fouroldstyle','fiveoldstyle','sixoldstyle','sevenoldstyle','eightoldstyle','nineoldstyle','commasuperior','threequartersemdash','periodsuperior','questionsmall','asuperior','bsuperior','centsuperior','dsuperior','esuperior','isuperior','lsuperior','msuperior','nsuperior','osuperior','rsuperior','ssuperior','tsuperior','ff','ffi','ffl','parenleftinferior','parenrightinferior','Circumflexsmall','hyphensuperior','Gravesmall','Asmall','Bsmall','Csmall','Dsmall','Esmall','Fsmall','Gsmall','Hsmall','Ismall','Jsmall','Ksmall','Lsmall','Msmall','Nsmall','Osmall','Psmall','Qsmall','Rsmall','Ssmall','Tsmall','Usmall','Vsmall','Wsmall','Xsmall','Ysmall','Zsmall','colonmonetary','onefitted','rupiah','Tildesmall','exclamdownsmall','centoldstyle','Lslashsmall','Scaronsmall','Zcaronsmall','Dieresissmall','Brevesmall','Caronsmall','Dotaccentsmall','Macronsmall','figuredash','hypheninferior','Ogoneksmall','Ringsmall','Cedillasmall','questiondownsmall','oneeighth','threeeighths','fiveeighths','seveneighths','onethird','twothirds','zerosuperior','foursuperior','fivesuperior','sixsuperior','sevensuperior','eightsuperior','ninesuperior','zeroinferior','oneinferior','twoinferior','threeinferior','fourinferior','fiveinferior','sixinferior','seveninferior','eightinferior','nineinferior','centinferior','dollarinferior','periodinferior','commainferior','Agravesmall','Aacutesmall','Acircumflexsmall','Atildesmall','Adieresissmall','Aringsmall','AEsmall','Ccedillasmall','Egravesmall','Eacutesmall','Ecircumflexsmall','Edieresissmall','Igravesmall','Iacutesmall','Icircumflexsmall','Idieresissmall','Ethsmall','Ntildesmall','Ogravesmall','Oacutesmall','Ocircumflexsmall','Otildesmall','Odieresissmall','OEsmall','Oslashsmall','Ugravesmall','Uacutesmall','Ucircumflexsmall','Udieresissmall','Yacutesmall','Thornsmall','Ydieresissmall','001.000','001.001','001.002','001.003','Black','Bold','Book','Light','Medium','Regular','Roman','Semibold'];var cffStandardEncoding=['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','space','exclam','quotedbl','numbersign','dollar','percent','ampersand','quoteright','parenleft','parenright','asterisk','plus','comma','hyphen','period','slash','zero','one','two','three','four','five','six','seven','eight','nine','colon','semicolon','less','equal','greater','question','at','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','bracketleft','backslash','bracketright','asciicircum','underscore','quoteleft','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','braceleft','bar','braceright','asciitilde','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','exclamdown','cent','sterling','fraction','yen','florin','section','currency','quotesingle','quotedblleft','guillemotleft','guilsinglleft','guilsinglright','fi','fl','','endash','dagger','daggerdbl','periodcentered','','paragraph','bullet','quotesinglbase','quotedblbase','quotedblright','guillemotright','ellipsis','perthousand','','questiondown','','grave','acute','circumflex','tilde','macron','breve','dotaccent','dieresis','','ring','cedilla','','hungarumlaut','ogonek','caron','emdash','','','','','','','','','','','','','','','','','AE','','ordfeminine','','','','','Lslash','Oslash','OE','ordmasculine','','','','','','ae','','','','dotlessi','','','lslash','oslash','oe','germandbls'];var cffExpertEncoding=['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','space','exclamsmall','Hungarumlautsmall','','dollaroldstyle','dollarsuperior','ampersandsmall','Acutesmall','parenleftsuperior','parenrightsuperior','twodotenleader','onedotenleader','comma','hyphen','period','fraction','zerooldstyle','oneoldstyle','twooldstyle','threeoldstyle','fouroldstyle','fiveoldstyle','sixoldstyle','sevenoldstyle','eightoldstyle','nineoldstyle','colon','semicolon','commasuperior','threequartersemdash','periodsuperior','questionsmall','','asuperior','bsuperior','centsuperior','dsuperior','esuperior','','','isuperior','','','lsuperior','msuperior','nsuperior','osuperior','','','rsuperior','ssuperior','tsuperior','','ff','fi','fl','ffi','ffl','parenleftinferior','','parenrightinferior','Circumflexsmall','hyphensuperior','Gravesmall','Asmall','Bsmall','Csmall','Dsmall','Esmall','Fsmall','Gsmall','Hsmall','Ismall','Jsmall','Ksmall','Lsmall','Msmall','Nsmall','Osmall','Psmall','Qsmall','Rsmall','Ssmall','Tsmall','Usmall','Vsmall','Wsmall','Xsmall','Ysmall','Zsmall','colonmonetary','onefitted','rupiah','Tildesmall','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','exclamdownsmall','centoldstyle','Lslashsmall','','','Scaronsmall','Zcaronsmall','Dieresissmall','Brevesmall','Caronsmall','','Dotaccentsmall','','','Macronsmall','','','figuredash','hypheninferior','','','Ogoneksmall','Ringsmall','Cedillasmall','','','','onequarter','onehalf','threequarters','questiondownsmall','oneeighth','threeeighths','fiveeighths','seveneighths','onethird','twothirds','','','zerosuperior','onesuperior','twosuperior','threesuperior','foursuperior','fivesuperior','sixsuperior','sevensuperior','eightsuperior','ninesuperior','zeroinferior','oneinferior','twoinferior','threeinferior','fourinferior','fiveinferior','sixinferior','seveninferior','eightinferior','nineinferior','centinferior','dollarinferior','periodinferior','commainferior','Agravesmall','Aacutesmall','Acircumflexsmall','Atildesmall','Adieresissmall','Aringsmall','AEsmall','Ccedillasmall','Egravesmall','Eacutesmall','Ecircumflexsmall','Edieresissmall','Igravesmall','Iacutesmall','Icircumflexsmall','Idieresissmall','Ethsmall','Ntildesmall','Ogravesmall','Oacutesmall','Ocircumflexsmall','Otildesmall','Odieresissmall','OEsmall','Oslashsmall','Ugravesmall','Uacutesmall','Ucircumflexsmall','Udieresissmall','Yacutesmall','Thornsmall','Ydieresissmall'];var standardNames=['.notdef','.null','nonmarkingreturn','space','exclam','quotedbl','numbersign','dollar','percent','ampersand','quotesingle','parenleft','parenright','asterisk','plus','comma','hyphen','period','slash','zero','one','two','three','four','five','six','seven','eight','nine','colon','semicolon','less','equal','greater','question','at','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','bracketleft','backslash','bracketright','asciicircum','underscore','grave','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','braceleft','bar','braceright','asciitilde','Adieresis','Aring','Ccedilla','Eacute','Ntilde','Odieresis','Udieresis','aacute','agrave','acircumflex','adieresis','atilde','aring','ccedilla','eacute','egrave','ecircumflex','edieresis','iacute','igrave','icircumflex','idieresis','ntilde','oacute','ograve','ocircumflex','odieresis','otilde','uacute','ugrave','ucircumflex','udieresis','dagger','degree','cent','sterling','section','bullet','paragraph','germandbls','registered','copyright','trademark','acute','dieresis','notequal','AE','Oslash','infinity','plusminus','lessequal','greaterequal','yen','mu','partialdiff','summation','product','pi','integral','ordfeminine','ordmasculine','Omega','ae','oslash','questiondown','exclamdown','logicalnot','radical','florin','approxequal','Delta','guillemotleft','guillemotright','ellipsis','nonbreakingspace','Agrave','Atilde','Otilde','OE','oe','endash','emdash','quotedblleft','quotedblright','quoteleft','quoteright','divide','lozenge','ydieresis','Ydieresis','fraction','currency','guilsinglleft','guilsinglright','fi','fl','daggerdbl','periodcentered','quotesinglbase','quotedblbase','perthousand','Acircumflex','Ecircumflex','Aacute','Edieresis','Egrave','Iacute','Icircumflex','Idieresis','Igrave','Oacute','Ocircumflex','apple','Ograve','Uacute','Ucircumflex','Ugrave','dotlessi','circumflex','tilde','macron','breve','dotaccent','ring','cedilla','hungarumlaut','ogonek','caron','Lslash','lslash','Scaron','scaron','Zcaron','zcaron','brokenbar','Eth','eth','Yacute','yacute','Thorn','thorn','minus','multiply','onesuperior','twosuperior','threesuperior','onehalf','onequarter','threequarters','franc','Gbreve','gbreve','Idotaccent','Scedilla','scedilla','Cacute','cacute','Ccaron','ccaron','dcroat'];/** * This is the encoding used for fonts created from scratch. * It loops through all glyphs and finds the appropriate unicode value. * Since it's linear time, other encodings will be faster. * @exports opentype.DefaultEncoding * @class * @constructor * @param {opentype.Font} */function DefaultEncoding(font){this.font=font;}DefaultEncoding.prototype.charToGlyphIndex=function(c){var code=c.codePointAt(0);var glyphs=this.font.glyphs;if(glyphs){for(var i=0;i<glyphs.length;i+=1){var glyph=glyphs.get(i);for(var j=0;j<glyph.unicodes.length;j+=1){if(glyph.unicodes[j]===code){return i;}}}}return null;};/** * @exports opentype.CmapEncoding * @class * @constructor * @param {Object} cmap - a object with the cmap encoded data */function CmapEncoding(cmap){this.cmap=cmap;}/** * @param {string} c - the character * @return {number} The glyph index. */CmapEncoding.prototype.charToGlyphIndex=function(c){return this.cmap.glyphIndexMap[c.codePointAt(0)]||0;};/** * @exports opentype.CffEncoding * @class * @constructor * @param {string} encoding - The encoding * @param {Array} charset - The character set. */function CffEncoding(encoding,charset){this.encoding=encoding;this.charset=charset;}/** * @param {string} s - The character * @return {number} The index. */CffEncoding.prototype.charToGlyphIndex=function(s){var code=s.codePointAt(0);var charName=this.encoding[code];return this.charset.indexOf(charName);};/** * @exports opentype.GlyphNames * @class * @constructor * @param {Object} post */function GlyphNames(post){var this$1=this;switch(post.version){case 1:this.names=standardNames.slice();break;case 2:this.names=new Array(post.numberOfGlyphs);for(var i=0;i<post.numberOfGlyphs;i++){if(post.glyphNameIndex[i]<standardNames.length){this$1.names[i]=standardNames[post.glyphNameIndex[i]];}else{this$1.names[i]=post.names[post.glyphNameIndex[i]-standardNames.length];}}break;case 2.5:this.names=new Array(post.numberOfGlyphs);for(var i$1=0;i$1<post.numberOfGlyphs;i$1++){this$1.names[i$1]=standardNames[i$1+post.glyphNameIndex[i$1]];}break;case 3:this.names=[];break;default:this.names=[];break;}}/** * Gets the index of a glyph by name. * @param {string} name - The glyph name * @return {number} The index */GlyphNames.prototype.nameToGlyphIndex=function(name){return this.names.indexOf(name);};/** * @param {number} gid * @return {string} */GlyphNames.prototype.glyphIndexToName=function(gid){return this.names[gid];};/** * @alias opentype.addGlyphNames * @param {opentype.Font} */function addGlyphNames(font){var glyph;var glyphIndexMap=font.tables.cmap.glyphIndexMap;var charCodes=Object.keys(glyphIndexMap);for(var i=0;i<charCodes.length;i+=1){var c=charCodes[i];var glyphIndex=glyphIndexMap[c];glyph=font.glyphs.get(glyphIndex);glyph.addUnicode(parseInt(c));}for(var i$1=0;i$1<font.glyphs.length;i$1+=1){glyph=font.glyphs.get(i$1);if(font.cffEncoding){if(font.isCIDFont){glyph.name='gid'+i$1;}else{glyph.name=font.cffEncoding.charset[i$1];}}else if(font.glyphNames.names){glyph.name=font.glyphNames.glyphIndexToName(i$1);}}}// Drawing utility functions. // Draw a line on the given context from point `x1,y1` to point `x2,y2`. function line(ctx,x1,y1,x2,y2){ctx.beginPath();ctx.moveTo(x1,y1);ctx.lineTo(x2,y2);ctx.stroke();}var draw={line:line};// The Glyph object // import glyf from './tables/glyf' Can't be imported here, because it's a circular dependency function getPathDefinition(glyph,path){var _path=path||new Path();return{configurable:true,get:function get(){if(typeof _path==='function'){_path=_path();}return _path;},set:function set(p){_path=p;}};}/** * @typedef GlyphOptions * @type Object * @property {string} [name] - The glyph name * @property {number} [unicode] * @property {Array} [unicodes] * @property {number} [xMin] * @property {number} [yMin] * @property {number} [xMax] * @property {number} [yMax] * @property {number} [advanceWidth] */// A Glyph is an individual mark that often corresponds to a character. // Some glyphs, such as ligatures, are a combination of many characters. // Glyphs are the basic building blocks of a font. // // The `Glyph` class contains utility methods for drawing the path and its points. /** * @exports opentype.Glyph * @class * @param {GlyphOptions} * @constructor */function Glyph(options){// By putting all the code on a prototype function (which is only declared once) // we reduce the memory requirements for larger fonts by some 2% this.bindConstructorValues(options);}/** * @param {GlyphOptions} */Glyph.prototype.bindConstructorValues=function(options){this.index=options.index||0;// These three values cannot be deferred for memory optimization: this.name=options.name||null;this.unicode=options.unicode||undefined;this.unicodes=options.unicodes||options.unicode!==undefined?[options.unicode]:[];// But by binding these values only when necessary, we reduce can // the memory requirements by almost 3% for larger fonts. if(options.xMin){this.xMin=options.xMin;}if(options.yMin){this.yMin=options.yMin;}if(options.xMax){this.xMax=options.xMax;}if(options.yMax){this.yMax=options.yMax;}if(options.advanceWidth){this.advanceWidth=options.advanceWidth;}// The path for a glyph is the most memory intensive, and is bound as a value // with a getter/setter to ensure we actually do path parsing only once the // path is actually needed by anything. Object.defineProperty(this,'path',getPathDefinition(this,options.path));};/** * @param {number} */Glyph.prototype.addUnicode=function(unicode){if(this.unicodes.length===0){this.unicode=unicode;}this.unicodes.push(unicode);};/** * Calculate the minimum bounding box for this glyph. * @return {opentype.BoundingBox} */Glyph.prototype.getBoundingBox=function(){return this.path.getBoundingBox();};/** * Convert the glyph to a Path we can draw on a drawing context. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {Object=} options - xScale, yScale to stretch the glyph. * @param {opentype.Font} if hinting is to be used, the font * @return {opentype.Path} */Glyph.prototype.getPath=function(x,y,fontSize,options,font){x=x!==undefined?x:0;y=y!==undefined?y:0;fontSize=fontSize!==undefined?fontSize:72;var commands;var hPoints;if(!options){options={};}var xScale=options.xScale;var yScale=options.yScale;if(options.hinting&&font&&font.hinting){// in case of hinting, the hinting engine takes care // of scaling the points (not the path) before hinting. hPoints=this.path&&font.hinting.exec(this,fontSize);// in case the hinting engine failed hPoints is undefined // and thus reverts to plain rending }if(hPoints){// Call font.hinting.getCommands instead of `glyf.getPath(hPoints).commands` to avoid a circular dependency commands=font.hinting.getCommands(hPoints);x=Math.round(x);y=Math.round(y);// TODO in case of hinting xyScaling is not yet supported xScale=yScale=1;}else{commands=this.path.commands;var scale=1/this.path.unitsPerEm*fontSize;if(xScale===undefined){xScale=scale;}if(yScale===undefined){yScale=scale;}}var p=new Path();for(var i=0;i<commands.length;i+=1){var cmd=commands[i];if(cmd.type==='M'){p.moveTo(x+cmd.x*xScale,y+-cmd.y*yScale);}else if(cmd.type==='L'){p.lineTo(x+cmd.x*xScale,y+-cmd.y*yScale);}else if(cmd.type==='Q'){p.quadraticCurveTo(x+cmd.x1*xScale,y+-cmd.y1*yScale,x+cmd.x*xScale,y+-cmd.y*yScale);}else if(cmd.type==='C'){p.curveTo(x+cmd.x1*xScale,y+-cmd.y1*yScale,x+cmd.x2*xScale,y+-cmd.y2*yScale,x+cmd.x*xScale,y+-cmd.y*yScale);}else if(cmd.type==='Z'){p.closePath();}}return p;};/** * Split the glyph into contours. * This function is here for backwards compatibility, and to * provide raw access to the TrueType glyph outlines. * @return {Array} */Glyph.prototype.getContours=function(){var this$1=this;if(this.points===undefined){return[];}var contours=[];var currentContour=[];for(var i=0;i<this.points.length;i+=1){var pt=this$1.points[i];currentContour.push(pt);if(pt.lastPointOfContour){contours.push(currentContour);currentContour=[];}}check.argument(currentContour.length===0,'There are still points left in the current contour.');return contours;};/** * Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph. * @return {Object} */Glyph.prototype.getMetrics=function(){var commands=this.path.commands;var xCoords=[];var yCoords=[];for(var i=0;i<commands.length;i+=1){var cmd=commands[i];if(cmd.type!=='Z'){xCoords.push(cmd.x);yCoords.push(cmd.y);}if(cmd.type==='Q'||cmd.type==='C'){xCoords.push(cmd.x1);yCoords.push(cmd.y1);}if(cmd.type==='C'){xCoords.push(cmd.x2);yCoords.push(cmd.y2);}}var metrics={xMin:Math.min.apply(null,xCoords),yMin:Math.min.apply(null,yCoords),xMax:Math.max.apply(null,xCoords),yMax:Math.max.apply(null,yCoords),leftSideBearing:this.leftSideBearing};if(!isFinite(metrics.xMin)){metrics.xMin=0;}if(!isFinite(metrics.xMax)){metrics.xMax=this.advanceWidth;}if(!isFinite(metrics.yMin)){metrics.yMin=0;}if(!isFinite(metrics.yMax)){metrics.yMax=0;}metrics.rightSideBearing=this.advanceWidth-metrics.leftSideBearing-(metrics.xMax-metrics.xMin);return metrics;};/** * Draw the glyph on the given context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {Object=} options - xScale, yScale to stretch the glyph. */Glyph.prototype.draw=function(ctx,x,y,fontSize,options){this.getPath(x,y,fontSize,options).draw(ctx);};/** * Draw the points of the glyph. * On-curve points will be drawn in blue, off-curve points will be drawn in red. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. */Glyph.prototype.drawPoints=function(ctx,x,y,fontSize){function drawCircles(l,x,y,scale){var PI_SQ=Math.PI*2;ctx.beginPath();for(var j=0;j<l.length;j+=1){ctx.moveTo(x+l[j].x*scale,y+l[j].y*scale);ctx.arc(x+l[j].x*scale,y+l[j].y*scale,2,0,PI_SQ,false);}ctx.closePath();ctx.fill();}x=x!==undefined?x:0;y=y!==undefined?y:0;fontSize=fontSize!==undefined?fontSize:24;var scale=1/this.path.unitsPerEm*fontSize;var blueCircles=[];var redCircles=[];var path=this.path;for(var i=0;i<path.commands.length;i+=1){var cmd=path.commands[i];if(cmd.x!==undefined){blueCircles.push({x:cmd.x,y:-cmd.y});}if(cmd.x1!==undefined){redCircles.push({x:cmd.x1,y:-cmd.y1});}if(cmd.x2!==undefined){redCircles.push({x:cmd.x2,y:-cmd.y2});}}ctx.fillStyle='blue';drawCircles(blueCircles,x,y,scale);ctx.fillStyle='red';drawCircles(redCircles,x,y,scale);};/** * Draw lines indicating important font measurements. * Black lines indicate the origin of the coordinate system (point 0,0). * Blue lines indicate the glyph bounding box. * Green line indicates the advance width of the glyph. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. */Glyph.prototype.drawMetrics=function(ctx,x,y,fontSize){var scale;x=x!==undefined?x:0;y=y!==undefined?y:0;fontSize=fontSize!==undefined?fontSize:24;scale=1/this.path.unitsPerEm*fontSize;ctx.lineWidth=1;// Draw the origin ctx.strokeStyle='black';draw.line(ctx,x,-10000,x,10000);draw.line(ctx,-10000,y,10000,y);// This code is here due to memory optimization: by not using // defaults in the constructor, we save a notable amount of memory. var xMin=this.xMin||0;var yMin=this.yMin||0;var xMax=this.xMax||0;var yMax=this.yMax||0;var advanceWidth=this.advanceWidth||0;// Draw the glyph box ctx.strokeStyle='blue';draw.line(ctx,x+xMin*scale,-10000,x+xMin*scale,10000);draw.line(ctx,x+xMax*scale,-10000,x+xMax*scale,10000);draw.line(ctx,-10000,y+-yMin*scale,10000,y+-yMin*scale);draw.line(ctx,-10000,y+-yMax*scale,10000,y+-yMax*scale);// Draw the advance width ctx.strokeStyle='green';draw.line(ctx,x+advanceWidth*scale,-10000,x+advanceWidth*scale,10000);};// The GlyphSet object // Define a property on the glyph that depends on the path being loaded. function defineDependentProperty(glyph,externalName,internalName){Object.defineProperty(glyph,externalName,{get:function get(){// Request the path property to make sure the path is loaded. glyph.path;// jshint ignore:line return glyph[internalName];},set:function set(newValue){glyph[internalName]=newValue;},enumerable:true,configurable:true});}/** * A GlyphSet represents all glyphs available in the font, but modelled using * a deferred glyph loader, for retrieving glyphs only once they are absolutely * necessary, to keep the memory footprint down. * @exports opentype.GlyphSet * @class * @param {opentype.Font} * @param {Array} */function GlyphSet(font,glyphs){var this$1=this;this.font=font;this.glyphs={};if(Array.isArray(glyphs)){for(var i=0;i<glyphs.length;i++){this$1.glyphs[i]=glyphs[i];}}this.length=glyphs&&glyphs.length||0;}/** * @param {number} index * @return {opentype.Glyph} */GlyphSet.prototype.get=function(index){if(typeof this.glyphs[index]==='function'){this.glyphs[index]=this.glyphs[index]();}return this.glyphs[index];};/** * @param {number} index * @param {Object} */GlyphSet.prototype.push=function(index,loader){this.glyphs[index]=loader;this.length++;};/** * @alias opentype.glyphLoader * @param {opentype.Font} font * @param {number} index * @return {opentype.Glyph} */function glyphLoader(font,index){return new Glyph({index:index,font:font});}/** * Generate a stub glyph that can be filled with all metadata *except* * the "points" and "path" properties, which must be loaded only once * the glyph's path is actually requested for text shaping. * @alias opentype.ttfGlyphLoader * @param {opentype.Font} font * @param {number} index * @param {Function} parseGlyph * @param {Object} data * @param {number} position * @param {Function} buildPath * @return {opentype.Glyph} */function ttfGlyphLoader(font,index,parseGlyph,data,position,buildPath){return function(){var glyph=new Glyph({index:index,font:font});glyph.path=function(){parseGlyph(glyph,data,position);var path=buildPath(font.glyphs,glyph);path.unitsPerEm=font.unitsPerEm;return path;};defineDependentProperty(glyph,'xMin','_xMin');defineDependentProperty(glyph,'xMax','_xMax');defineDependentProperty(glyph,'yMin','_yMin');defineDependentProperty(glyph,'yMax','_yMax');return glyph;};}/** * @alias opentype.cffGlyphLoader * @param {opentype.Font} font * @param {number} index * @param {Function} parseCFFCharstring * @param {string} charstring * @return {opentype.Glyph} */function cffGlyphLoader(font,index,parseCFFCharstring,charstring){return function(){var glyph=new Glyph({index:index,font:font});glyph.path=function(){var path=parseCFFCharstring(font,glyph,charstring);path.unitsPerEm=font.unitsPerEm;return path;};return glyph;};}var glyphset={GlyphSet:GlyphSet,glyphLoader:glyphLoader,ttfGlyphLoader:ttfGlyphLoader,cffGlyphLoader:cffGlyphLoader};// The `CFF` table contains the glyph outlines in PostScript format. // Custom equals function that can also check lists. function equals(a,b){if(a===b){return true;}else if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length){return false;}for(var i=0;i<a.length;i+=1){if(!equals(a[i],b[i])){return false;}}return true;}else{return false;}}// Subroutines are encoded using the negative half of the number space. // See type 2 chapter 4.7 "Subroutine operators". function calcCFFSubroutineBias(subrs){var bias;if(subrs.length<1240){bias=107;}else if(subrs.length<33900){bias=1131;}else{bias=32768;}return bias;}// Parse a `CFF` INDEX array. // An index array consists of a list of offsets, then a list of objects at those offsets. function parseCFFIndex(data,start,conversionFn){var offsets=[];var objects=[];var count=parse.getCard16(data,start);var objectOffset;var endOffset;if(count!==0){var offsetSize=parse.getByte(data,start+2);objectOffset=start+(count+1)*offsetSize+2;var pos=start+3;for(var i=0;i<count+1;i+=1){offsets.push(parse.getOffset(data,pos,offsetSize));pos+=offsetSize;}// The total size of the index array is 4 header bytes + the value of the last offset. endOffset=objectOffset+offsets[count];}else{endOffset=start+2;}for(var i$1=0;i$1<offsets.length-1;i$1+=1){var value=parse.getBytes(data,objectOffset+offsets[i$1],objectOffset+offsets[i$1+1]);if(conversionFn){value=conversionFn(value);}objects.push(value);}return{objects:objects,startOffset:start,endOffset:endOffset};}// Parse a `CFF` DICT real value. function parseFloatOperand(parser){var s='';var eof=15;var lookup=['0','1','2','3','4','5','6','7','8','9','.','E','E-',null,'-'];while(true){var b=parser.parseByte();var n1=b>>4;var n2=b&15;if(n1===eof){break;}s+=lookup[n1];if(n2===eof){break;}s+=lookup[n2];}return parseFloat(s);}// Parse a `CFF` DICT operand. function parseOperand(parser,b0){var b1;var b2;var b3;var b4;if(b0===28){b1=parser.parseByte();b2=parser.parseByte();return b1<<8|b2;}if(b0===29){b1=parser.parseByte();b2=parser.parseByte();b3=parser.parseByte();b4=parser.parseByte();return b1<<24|b2<<16|b3<<8|b4;}if(b0===30){return parseFloatOperand(parser);}if(b0>=32&&b0<=246){return b0-139;}if(b0>=247&&b0<=250){b1=parser.parseByte();return(b0-247)*256+b1+108;}if(b0>=251&&b0<=254){b1=parser.parseByte();return-(b0-251)*256-b1-108;}throw new Error('Invalid b0 '+b0);}// Convert the entries returned by `parseDict` to a proper dictionary. // If a value is a list of one, it is unpacked. function entriesToObject(entries){var o={};for(var i=0;i<entries.length;i+=1){var key=entries[i][0];var values=entries[i][1];var value=void 0;if(values.length===1){value=values[0];}else{value=values;}if(o.hasOwnProperty(key)&&!isNaN(o[key])){throw new Error('Object '+o+' already has key '+key);}o[key]=value;}return o;}// Parse a `CFF` DICT object. // A dictionary contains key-value pairs in a compact tokenized format. function parseCFFDict(data,start,size){start=start!==undefined?start:0;var parser=new parse.Parser(data,start);var entries=[];var operands=[];size=size!==undefined?size:data.length;while(parser.relativeOffset<size){var op=parser.parseByte();// The first byte for each dict item distinguishes between operator (key) and operand (value). // Values <= 21 are operators. if(op<=21){// Two-byte operators have an initial escape byte of 12. if(op===12){op=1200+parser.parseByte();}entries.push([op,operands]);operands=[];}else{// Since the operands (values) come before the operators (keys), we store all operands in a list // until we encounter an operator. operands.push(parseOperand(parser,op));}}return entriesToObject(entries);}// Given a String Index (SID), return the value of the string. // Strings below index 392 are standard CFF strings and are not encoded in the font. function getCFFString(strings,index){if(index<=390){index=cffStandardStrings[index];}else{index=strings[index-391];}return index;}// Interpret a dictionary and return a new dictionary with readable keys and values for missing entries. // This function takes `meta` which is a list of objects containing `operand`, `name` and `default`. function interpretDict(dict,meta,strings){var newDict={};var value;// Because we also want to include missing values, we start out from the meta list // and lookup values in the dict. for(var i=0;i<meta.length;i+=1){var m=meta[i];if(Array.isArray(m.type)){var values=[];values.length=m.type.length;for(var j=0;j<m.type.length;j++){value=dict[m.op]!==undefined?dict[m.op][j]:undefined;if(value===undefined){value=m.value!==undefined&&m.value[j]!==undefined?m.value[j]:null;}if(m.type[j]==='SID'){value=getCFFString(strings,value);}values[j]=value;}newDict[m.name]=values;}else{value=dict[m.op];if(value===undefined){value=m.value!==undefined?m.value:null;}if(m.type==='SID'){value=getCFFString(strings,value);}newDict[m.name]=value;}}return newDict;}// Parse the CFF header. function parseCFFHeader(data,start){var header={};header.formatMajor=parse.getCard8(data,start);header.formatMinor=parse.getCard8(data,start+1);header.size=parse.getCard8(data,start+2);header.offsetSize=parse.getCard8(data,start+3);header.startOffset=start;header.endOffset=start+4;return header;}var TOP_DICT_META=[{name:'version',op:0,type:'SID'},{name:'notice',op:1,type:'SID'},{name:'copyright',op:1200,type:'SID'},{name:'fullName',op:2,type:'SID'},{name:'familyName',op:3,type:'SID'},{name:'weight',op:4,type:'SID'},{name:'isFixedPitch',op:1201,type:'number',value:0},{name:'italicAngle',op:1202,type:'number',value:0},{name:'underlinePosition',op:1203,type:'number',value:-100},{name:'underlineThickness',op:1204,type:'number',value:50},{name:'paintType',op:1205,type:'number',value:0},{name:'charstringType',op:1206,type:'number',value:2},{name:'fontMatrix',op:1207,type:['real','real','real','real','real','real'],value:[0.001,0,0,0.001,0,0]},{name:'uniqueId',op:13,type:'number'},{name:'fontBBox',op:5,type:['number','number','number','number'],value:[0,0,0,0]},{name:'strokeWidth',op:1208,type:'number',value:0},{name:'xuid',op:14,type:[],value:null},{name:'charset',op:15,type:'offset',value:0},{name:'encoding',op:16,type:'offset',value:0},{name:'charStrings',op:17,type:'offset',value:0},{name:'private',op:18,type:['number','offset'],value:[0,0]},{name:'ros',op:1230,type:['SID','SID','number']},{name:'cidFontVersion',op:1231,type:'number',value:0},{name:'cidFontRevision',op:1232,type:'number',value:0},{name:'cidFontType',op:1233,type:'number',value:0},{name:'cidCount',op:1234,type:'number',value:8720},{name:'uidBase',op:1235,type:'number'},{name:'fdArray',op:1236,type:'offset'},{name:'fdSelect',op:1237,type:'offset'},{name:'fontName',op:1238,type:'SID'}];var PRIVATE_DICT_META=[{name:'subrs',op:19,type:'offset',value:0},{name:'defaultWidthX',op:20,type:'number',value:0},{name:'nominalWidthX',op:21,type:'number',value:0}];// Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary. // The top dictionary contains the essential metadata for the font, together with the private dictionary. function parseCFFTopDict(data,strings){var dict=parseCFFDict(data,0,data.byteLength);return interpretDict(dict,TOP_DICT_META,strings);}// Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need. function parseCFFPrivateDict(data,start,size,strings){var dict=parseCFFDict(data,start,size);return interpretDict(dict,PRIVATE_DICT_META,strings);}// Returns a list of "Top DICT"s found using an INDEX list. // Used to read both the usual high-level Top DICTs and also the FDArray // discovered inside CID-keyed fonts. When a Top DICT has a reference to // a Private DICT that is read and saved into the Top DICT. // // In addition to the expected/optional values as outlined in TOP_DICT_META // the following values might be saved into the Top DICT. // // _subrs [] array of local CFF subroutines from Private DICT // _subrsBias bias value computed from number of subroutines // (see calcCFFSubroutineBias() and parseCFFCharstring()) // _defaultWidthX default widths for CFF characters // _nominalWidthX bias added to width embedded within glyph description // // _privateDict saved copy of parsed Private DICT from Top DICT function gatherCFFTopDicts(data,start,cffIndex,strings){var topDictArray=[];for(var iTopDict=0;iTopDict<cffIndex.length;iTopDict+=1){var topDictData=new DataView(new Uint8Array(cffIndex[iTopDict]).buffer);var topDict=parseCFFTopDict(topDictData,strings);topDict._subrs=[];topDict._subrsBias=0;var privateSize=topDict.private[0];var privateOffset=topDict.private[1];if(privateSize!==0&&privateOffset!==0){var privateDict=parseCFFPrivateDict(data,privateOffset+start,privateSize,strings);topDict._defaultWidthX=privateDict.defaultWidthX;topDict._nominalWidthX=privateDict.nominalWidthX;if(privateDict.subrs!==0){var subrOffset=privateOffset+privateDict.subrs;var subrIndex=parseCFFIndex(data,subrOffset+start);topDict._subrs=subrIndex.objects;topDict._subrsBias=calcCFFSubroutineBias(topDict._subrs);}topDict._privateDict=privateDict;}topDictArray.push(topDict);}return topDictArray;}// Parse the CFF charset table, which contains internal names for all the glyphs. // This function will return a list of glyph names. // See Adobe TN #5176 chapter 13, "Charsets". function parseCFFCharset(data,start,nGlyphs,strings){var sid;var count;var parser=new parse.Parser(data,start);// The .notdef glyph is not included, so subtract 1. nGlyphs-=1;var charset=['.notdef'];var format=parser.parseCard8();if(format===0){for(var i=0;i<nGlyphs;i+=1){sid=parser.parseSID();charset.push(getCFFString(strings,sid));}}else if(format===1){while(charset.length<=nGlyphs){sid=parser.parseSID();count=parser.parseCard8();for(var i$1=0;i$1<=count;i$1+=1){charset.push(getCFFString(strings,sid));sid+=1;}}}else if(format===2){while(charset.length<=nGlyphs){sid=parser.parseSID();count=parser.parseCard16();for(var i$2=0;i$2<=count;i$2+=1){charset.push(getCFFString(strings,sid));sid+=1;}}}else{throw new Error('Unknown charset format '+format);}return charset;}// Parse the CFF encoding data. Only one encoding can be specified per font. // See Adobe TN #5176 chapter 12, "Encodings". function parseCFFEncoding(data,start,charset){var code;var enc={};var parser=new parse.Parser(data,start);var format=parser.parseCard8();if(format===0){var nCodes=parser.parseCard8();for(var i=0;i<nCodes;i+=1){code=parser.parseCard8();enc[code]=i;}}else if(format===1){var nRanges=parser.parseCard8();code=1;for(var i$1=0;i$1<nRanges;i$1+=1){var first=parser.parseCard8();var nLeft=parser.parseCard8();for(var j=first;j<=first+nLeft;j+=1){enc[j]=code;code+=1;}}}else{throw new Error('Unknown encoding format '+format);}return new CffEncoding(enc,charset);}// Take in charstring code and return a Glyph object. // The encoding is described in the Type 2 Charstring Format // https://www.microsoft.com/typography/OTSPEC/charstr2.htm function parseCFFCharstring(font,glyph,code){var c1x;var c1y;var c2x;var c2y;var p=new Path();var stack=[];var nStems=0;var haveWidth=false;var open=false;var x=0;var y=0;var subrs;var subrsBias;var defaultWidthX;var nominalWidthX;if(font.isCIDFont){var fdIndex=font.tables.cff.topDict._fdSelect[glyph.index];var fdDict=font.tables.cff.topDict._fdArray[fdIndex];subrs=fdDict._subrs;subrsBias=fdDict._subrsBias;defaultWidthX=fdDict._defaultWidthX;nominalWidthX=fdDict._nominalWidthX;}else{subrs=font.tables.cff.topDict._subrs;subrsBias=font.tables.cff.topDict._subrsBias;defaultWidthX=font.tables.cff.topDict._defaultWidthX;nominalWidthX=font.tables.cff.topDict._nominalWidthX;}var width=defaultWidthX;function newContour(x,y){if(open){p.closePath();}p.moveTo(x,y);open=true;}function parseStems(){var hasWidthArg;// The number of stem operators on the stack is always even. // If the value is uneven, that means a width is specified. hasWidthArg=stack.length%2!==0;if(hasWidthArg&&!haveWidth){width=stack.shift()+nominalWidthX;}nStems+=stack.length>>1;stack.length=0;haveWidth=true;}function parse$$1(code){var b1;var b2;var b3;var b4;var codeIndex;var subrCode;var jpx;var jpy;var c3x;var c3y;var c4x;var c4y;var i=0;while(i<code.length){var v=code[i];i+=1;switch(v){case 1:// hstem parseStems();break;case 3:// vstem parseStems();break;case 4:// vmoveto if(stack.length>1&&!haveWidth){width=stack.shift()+nominalWidthX;haveWidth=true;}y+=stack.pop();newContour(x,y);break;case 5:// rlineto while(stack.length>0){x+=stack.shift();y+=stack.shift();p.lineTo(x,y);}break;case 6:// hlineto while(stack.length>0){x+=stack.shift();p.lineTo(x,y);if(stack.length===0){break;}y+=stack.shift();p.lineTo(x,y);}break;case 7:// vlineto while(stack.length>0){y+=stack.shift();p.lineTo(x,y);if(stack.length===0){break;}x+=stack.shift();p.lineTo(x,y);}break;case 8:// rrcurveto while(stack.length>0){c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y);}break;case 10:// callsubr codeIndex=stack.pop()+subrsBias;subrCode=subrs[codeIndex];if(subrCode){parse$$1(subrCode);}break;case 11:// return return;case 12:// flex operators v=code[i];i+=1;switch(v){case 35:// flex // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |- c1x=x+stack.shift();// dx1 c1y=y+stack.shift();// dy1 c2x=c1x+stack.shift();// dx2 c2y=c1y+stack.shift();// dy2 jpx=c2x+stack.shift();// dx3 jpy=c2y+stack.shift();// dy3 c3x=jpx+stack.shift();// dx4 c3y=jpy+stack.shift();// dy4 c4x=c3x+stack.shift();// dx5 c4y=c3y+stack.shift();// dy5 x=c4x+stack.shift();// dx6 y=c4y+stack.shift();// dy6 stack.shift();// flex depth p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;case 34:// hflex // |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |- c1x=x+stack.shift();// dx1 c1y=y;// dy1 c2x=c1x+stack.shift();// dx2 c2y=c1y+stack.shift();// dy2 jpx=c2x+stack.shift();// dx3 jpy=c2y;// dy3 c3x=jpx+stack.shift();// dx4 c3y=c2y;// dy4 c4x=c3x+stack.shift();// dx5 c4y=y;// dy5 x=c4x+stack.shift();// dx6 p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;case 36:// hflex1 // |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |- c1x=x+stack.shift();// dx1 c1y=y+stack.shift();// dy1 c2x=c1x+stack.shift();// dx2 c2y=c1y+stack.shift();// dy2 jpx=c2x+stack.shift();// dx3 jpy=c2y;// dy3 c3x=jpx+stack.shift();// dx4 c3y=c2y;// dy4 c4x=c3x+stack.shift();// dx5 c4y=c3y+stack.shift();// dy5 x=c4x+stack.shift();// dx6 p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;case 37:// flex1 // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |- c1x=x+stack.shift();// dx1 c1y=y+stack.shift();// dy1 c2x=c1x+stack.shift();// dx2 c2y=c1y+stack.shift();// dy2 jpx=c2x+stack.shift();// dx3 jpy=c2y+stack.shift();// dy3 c3x=jpx+stack.shift();// dx4 c3y=jpy+stack.shift();// dy4 c4x=c3x+stack.shift();// dx5 c4y=c3y+stack.shift();// dy5 if(Math.abs(c4x-x)>Math.abs(c4y-y)){x=c4x+stack.shift();}else{y=c4y+stack.shift();}p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;default:console.log('Glyph '+glyph.index+': unknown operator '+1200+v);stack.length=0;}break;case 14:// endchar if(stack.length>0&&!haveWidth){width=stack.shift()+nominalWidthX;haveWidth=true;}if(open){p.closePath();open=false;}break;case 18:// hstemhm parseStems();break;case 19:// hintmask case 20:// cntrmask parseStems();i+=nStems+7>>3;break;case 21:// rmoveto if(stack.length>2&&!haveWidth){width=stack.shift()+nominalWidthX;haveWidth=true;}y+=stack.pop();x+=stack.pop();newContour(x,y);break;case 22:// hmoveto if(stack.length>1&&!haveWidth){width=stack.shift()+nominalWidthX;haveWidth=true;}x+=stack.pop();newContour(x,y);break;case 23:// vstemhm parseStems();break;case 24:// rcurveline while(stack.length>2){c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y);}x+=stack.shift();y+=stack.shift();p.lineTo(x,y);break;case 25:// rlinecurve while(stack.length>6){x+=stack.shift();y+=stack.shift();p.lineTo(x,y);}c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y);break;case 26:// vvcurveto if(stack.length%2){x+=stack.shift();}while(stack.length>0){c1x=x;c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x;y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y);}break;case 27:// hhcurveto if(stack.length%2){y+=stack.shift();}while(stack.length>0){c1x=x+stack.shift();c1y=y;c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y;p.curveTo(c1x,c1y,c2x,c2y,x,y);}break;case 28:// shortint b1=code[i];b2=code[i+1];stack.push((b1<<24|b2<<16)>>16);i+=2;break;case 29:// callgsubr codeIndex=stack.pop()+font.gsubrsBias;subrCode=font.gsubrs[codeIndex];if(subrCode){parse$$1(subrCode);}break;case 30:// vhcurveto while(stack.length>0){c1x=x;c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y);if(stack.length===0){break;}c1x=x+stack.shift();c1y=y;c2x=c1x+stack.shift();c2y=c1y+stack.shift();y=c2y+stack.shift();x=c2x+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y);}break;case 31:// hvcurveto while(stack.length>0){c1x=x+stack.shift();c1y=y;c2x=c1x+stack.shift();c2y=c1y+stack.shift();y=c2y+stack.shift();x=c2x+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y);if(stack.length===0){break;}c1x=x;c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y);}break;default:if(v<32){console.log('Glyph '+glyph.index+': unknown operator '+v);}else if(v<247){stack.push(v-139);}else if(v<251){b1=code[i];i+=1;stack.push((v-247)*256+b1+108);}else if(v<255){b1=code[i];i+=1;stack.push(-(v-251)*256-b1-108);}else{b1=code[i];b2=code[i+1];b3=code[i+2];b4=code[i+3];i+=4;stack.push((b1<<24|b2<<16|b3<<8|b4)/65536);}}}}parse$$1(code);glyph.advanceWidth=width;return p;}function parseCFFFDSelect(data,start,nGlyphs,fdArrayCount){var fdSelect=[];var fdIndex;var parser=new parse.Parser(data,start);var format=parser.parseCard8();if(format===0){// Simple list of nGlyphs elements for(var iGid=0;iGid<nGlyphs;iGid++){fdIndex=parser.parseCard8();if(fdIndex>=fdArrayCount){throw new Error('CFF table CID Font FDSelect has bad FD index value '+fdIndex+' (FD count '+fdArrayCount+')');}fdSelect.push(fdIndex);}}else if(format===3){// Ranges var nRanges=parser.parseCard16();var first=parser.parseCard16();if(first!==0){throw new Error('CFF Table CID Font FDSelect format 3 range has bad initial GID '+first);}var next;for(var iRange=0;iRange<nRanges;iRange++){fdIndex=parser.parseCard8();next=parser.parseCard16();if(fdIndex>=fdArrayCount){throw new Error('CFF table CID Font FDSelect has bad FD index value '+fdIndex+' (FD count '+fdArrayCount+')');}if(next>nGlyphs){throw new Error('CFF Table CID Font FDSelect format 3 range has bad GID '+next);}for(;first<next;first++){fdSelect.push(fdIndex);}first=next;}if(next!==nGlyphs){throw new Error('CFF Table CID Font FDSelect format 3 range has bad final GID '+next);}}else{throw new Error('CFF Table CID Font FDSelect table has unsupported format '+format);}return fdSelect;}// Parse the `CFF` table, which contains the glyph outlines in PostScript format. function parseCFFTable(data,start,font){font.tables.cff={};var header=parseCFFHeader(data,start);var nameIndex=parseCFFIndex(data,header.endOffset,parse.bytesToString);var topDictIndex=parseCFFIndex(data,nameIndex.endOffset);var stringIndex=parseCFFIndex(data,topDictIndex.endOffset,parse.bytesToString);var globalSubrIndex=parseCFFIndex(data,stringIndex.endOffset);font.gsubrs=globalSubrIndex.objects;font.gsubrsBias=calcCFFSubroutineBias(font.gsubrs);var topDictArray=gatherCFFTopDicts(data,start,topDictIndex.objects,stringIndex.objects);if(topDictArray.length!==1){throw new Error('CFF table has too many fonts in \'FontSet\' - count of fonts NameIndex.length = '+topDictArray.length);}var topDict=topDictArray[0];font.tables.cff.topDict=topDict;if(topDict._privateDict){font.defaultWidthX=topDict._privateDict.defaultWidthX;font.nominalWidthX=topDict._privateDict.nominalWidthX;}if(topDict.ros[0]!==undefined&&topDict.ros[1]!==undefined){font.isCIDFont=true;}if(font.isCIDFont){var fdArrayOffset=topDict.fdArray;var fdSelectOffset=topDict.fdSelect;if(fdArrayOffset===0||fdSelectOffset===0){throw new Error('Font is marked as a CID font, but FDArray and/or FDSelect information is missing');}fdArrayOffset+=start;var fdArrayIndex=parseCFFIndex(data,fdArrayOffset);var fdArray=gatherCFFTopDicts(data,start,fdArrayIndex.objects,stringIndex.objects);topDict._fdArray=fdArray;fdSelectOffset+=start;topDict._fdSelect=parseCFFFDSelect(data,fdSelectOffset,font.numGlyphs,fdArray.length);}var privateDictOffset=start+topDict.private[1];var privateDict=parseCFFPrivateDict(data,privateDictOffset,topDict.private[0],stringIndex.objects);font.defaultWidthX=privateDict.defaultWidthX;font.nominalWidthX=privateDict.nominalWidthX;if(privateDict.subrs!==0){var subrOffset=privateDictOffset+privateDict.subrs;var subrIndex=parseCFFIndex(data,subrOffset);font.subrs=subrIndex.objects;font.subrsBias=calcCFFSubroutineBias(font.subrs);}else{font.subrs=[];font.subrsBias=0;}// Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset. var charStringsIndex=parseCFFIndex(data,start+topDict.charStrings);font.nGlyphs=charStringsIndex.objects.length;var charset=parseCFFCharset(data,start+topDict.charset,font.nGlyphs,stringIndex.objects);if(topDict.encoding===0){// Standard encoding font.cffEncoding=new CffEncoding(cffStandardEncoding,charset);}else if(topDict.encoding===1){// Expert encoding font.cffEncoding=new CffEncoding(cffExpertEncoding,charset);}else{font.cffEncoding=parseCFFEncoding(data,start+topDict.encoding,charset);}// Prefer the CMAP encoding to the CFF encoding. font.encoding=font.encoding||font.cffEncoding;font.glyphs=new glyphset.GlyphSet(font);for(var i=0;i<font.nGlyphs;i+=1){var charString=charStringsIndex.objects[i];font.glyphs.push(i,glyphset.cffGlyphLoader(font,i,parseCFFCharstring,charString));}}// Convert a string to a String ID (SID). // The list of strings is modified in place. function encodeString(s,strings){var sid;// Is the string in the CFF standard strings? var i=cffStandardStrings.indexOf(s);if(i>=0){sid=i;}// Is the string already in the string index? i=strings.indexOf(s);if(i>=0){sid=i+cffStandardStrings.length;}else{sid=cffStandardStrings.length+strings.length;strings.push(s);}return sid;}function makeHeader(){return new table.Record('Header',[{name:'major',type:'Card8',value:1},{name:'minor',type:'Card8',value:0},{name:'hdrSize',type:'Card8',value:4},{name:'major',type:'Card8',value:1}]);}function makeNameIndex(fontNames){var t=new table.Record('Name INDEX',[{name:'names',type:'INDEX',value:[]}]);t.names=[];for(var i=0;i<fontNames.length;i+=1){t.names.push({name:'name_'+i,type:'NAME',value:fontNames[i]});}return t;}// Given a dictionary's metadata, create a DICT structure. function makeDict(meta,attrs,strings){var m={};for(var i=0;i<meta.length;i+=1){var entry=meta[i];var value=attrs[entry.name];if(value!==undefined&&!equals(value,entry.value)){if(entry.type==='SID'){value=encodeString(value,strings);}m[entry.op]={name:entry.name,type:entry.type,value:value};}}return m;}// The Top DICT houses the global font attributes. function makeTopDict(attrs,strings){var t=new table.Record('Top DICT',[{name:'dict',type:'DICT',value:{}}]);t.dict=makeDict(TOP_DICT_META,attrs,strings);return t;}function makeTopDictIndex(topDict){var t=new table.Record('Top DICT INDEX',[{name:'topDicts',type:'INDEX',value:[]}]);t.topDicts=[{name:'topDict_0',type:'TABLE',value:topDict}];return t;}function makeStringIndex(strings){var t=new table.Record('String INDEX',[{name:'strings',type:'INDEX',value:[]}]);t.strings=[];for(var i=0;i<strings.length;i+=1){t.strings.push({name:'string_'+i,type:'STRING',value:strings[i]});}return t;}function makeGlobalSubrIndex(){// Currently we don't use subroutines. return new table.Record('Global Subr INDEX',[{name:'subrs',type:'INDEX',value:[]}]);}function makeCharsets(glyphNames,strings){var t=new table.Record('Charsets',[{name:'format',type:'Card8',value:0}]);for(var i=0;i<glyphNames.length;i+=1){var glyphName=glyphNames[i];var glyphSID=encodeString(glyphName,strings);t.fields.push({name:'glyph_'+i,type:'SID',value:glyphSID});}return t;}function glyphToOps(glyph){var ops=[];var path=glyph.path;ops.push({name:'width',type:'NUMBER',value:glyph.advanceWidth});var x=0;var y=0;for(var i=0;i<path.commands.length;i+=1){var dx=void 0;var dy=void 0;var cmd=path.commands[i];if(cmd.type==='Q'){// CFF only supports bézier curves, so convert the quad to a bézier. var _13=1/3;var _23=2/3;// We're going to create a new command so we don't change the original path. cmd={type:'C',x:cmd.x,y:cmd.y,x1:_13*x+_23*cmd.x1,y1:_13*y+_23*cmd.y1,x2:_13*cmd.x+_23*cmd.x1,y2:_13*cmd.y+_23*cmd.y1};}if(cmd.type==='M'){dx=Math.round(cmd.x-x);dy=Math.round(cmd.y-y);ops.push({name:'dx',type:'NUMBER',value:dx});ops.push({name:'dy',type:'NUMBER',value:dy});ops.push({name:'rmoveto',type:'OP',value:21});x=Math.round(cmd.x);y=Math.round(cmd.y);}else if(cmd.type==='L'){dx=Math.round(cmd.x-x);dy=Math.round(cmd.y-y);ops.push({name:'dx',type:'NUMBER',value:dx});ops.push({name:'dy',type:'NUMBER',value:dy});ops.push({name:'rlineto',type:'OP',value:5});x=Math.round(cmd.x);y=Math.round(cmd.y);}else if(cmd.type==='C'){var dx1=Math.round(cmd.x1-x);var dy1=Math.round(cmd.y1-y);var dx2=Math.round(cmd.x2-cmd.x1);var dy2=Math.round(cmd.y2-cmd.y1);dx=Math.round(cmd.x-cmd.x2);dy=Math.round(cmd.y-cmd.y2);ops.push({name:'dx1',type:'NUMBER',value:dx1});ops.push({name:'dy1',type:'NUMBER',value:dy1});ops.push({name:'dx2',type:'NUMBER',value:dx2});ops.push({name:'dy2',type:'NUMBER',value:dy2});ops.push({name:'dx',type:'NUMBER',value:dx});ops.push({name:'dy',type:'NUMBER',value:dy});ops.push({name:'rrcurveto',type:'OP',value:8});x=Math.round(cmd.x);y=Math.round(cmd.y);}// Contours are closed automatically. }ops.push({name:'endchar',type:'OP',value:14});return ops;}function makeCharStringsIndex(glyphs){var t=new table.Record('CharStrings INDEX',[{name:'charStrings',type:'INDEX',value:[]}]);for(var i=0;i<glyphs.length;i+=1){var glyph=glyphs.get(i);var ops=glyphToOps(glyph);t.charStrings.push({name:glyph.name,type:'CHARSTRING',value:ops});}return t;}function makePrivateDict(attrs,strings){var t=new table.Record('Private DICT',[{name:'dict',type:'DICT',value:{}}]);t.dict=makeDict(PRIVATE_DICT_META,attrs,strings);return t;}function makeCFFTable(glyphs,options){var t=new table.Table('CFF ',[{name:'header',type:'RECORD'},{name:'nameIndex',type:'RECORD'},{name:'topDictIndex',type:'RECORD'},{name:'stringIndex',type:'RECORD'},{name:'globalSubrIndex',type:'RECORD'},{name:'charsets',type:'RECORD'},{name:'charStringsIndex',type:'RECORD'},{name:'privateDict',type:'RECORD'}]);var fontScale=1/options.unitsPerEm;// We use non-zero values for the offsets so that the DICT encodes them. // This is important because the size of the Top DICT plays a role in offset calculation, // and the size shouldn't change after we've written correct offsets. var attrs={version:options.version,fullName:options.fullName,familyName:options.familyName,weight:options.weightName,fontBBox:options.fontBBox||[0,0,0,0],fontMatrix:[fontScale,0,0,fontScale,0,0],charset:999,encoding:0,charStrings:999,private:[0,999]};var privateAttrs={};var glyphNames=[];var glyph;// Skip first glyph (.notdef) for(var i=1;i<glyphs.length;i+=1){glyph=glyphs.get(i);glyphNames.push(glyph.name);}var strings=[];t.header=makeHeader();t.nameIndex=makeNameIndex([options.postScriptName]);var topDict=makeTopDict(attrs,strings);t.topDictIndex=makeTopDictIndex(topDict);t.globalSubrIndex=makeGlobalSubrIndex();t.charsets=makeCharsets(glyphNames,strings);t.charStringsIndex=makeCharStringsIndex(glyphs);t.privateDict=makePrivateDict(privateAttrs,strings);// Needs to come at the end, to encode all custom strings used in the font. t.stringIndex=makeStringIndex(strings);var startOffset=t.header.sizeOf()+t.nameIndex.sizeOf()+t.topDictIndex.sizeOf()+t.stringIndex.sizeOf()+t.globalSubrIndex.sizeOf();attrs.charset=startOffset;// We use the CFF standard encoding; proper encoding will be handled in cmap. attrs.encoding=0;attrs.charStrings=attrs.charset+t.charsets.sizeOf();attrs.private[1]=attrs.charStrings+t.charStringsIndex.sizeOf();// Recreate the Top DICT INDEX with the correct offsets. topDict=makeTopDict(attrs,strings);t.topDictIndex=makeTopDictIndex(topDict);return t;}var cff={parse:parseCFFTable,make:makeCFFTable};// The `head` table contains global information about the font. // Parse the header `head` table function parseHeadTable(data,start){var head={};var p=new parse.Parser(data,start);head.version=p.parseVersion();head.fontRevision=Math.round(p.parseFixed()*1000)/1000;head.checkSumAdjustment=p.parseULong();head.magicNumber=p.parseULong();check.argument(head.magicNumber===0x5F0F3CF5,'Font header has wrong magic number.');head.flags=p.parseUShort();head.unitsPerEm=p.parseUShort();head.created=p.parseLongDateTime();head.modified=p.parseLongDateTime();head.xMin=p.parseShort();head.yMin=p.parseShort();head.xMax=p.parseShort();head.yMax=p.parseShort();head.macStyle=p.parseUShort();head.lowestRecPPEM=p.parseUShort();head.fontDirectionHint=p.parseShort();head.indexToLocFormat=p.parseShort();head.glyphDataFormat=p.parseShort();return head;}function makeHeadTable(options){// Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970 var timestamp=Math.round(new Date().getTime()/1000)+2082844800;var createdTimestamp=timestamp;if(options.createdTimestamp){createdTimestamp=options.createdTimestamp+2082844800;}return new table.Table('head',[{name:'version',type:'FIXED',value:0x00010000},{name:'fontRevision',type:'FIXED',value:0x00010000},{name:'checkSumAdjustment',type:'ULONG',value:0},{name:'magicNumber',type:'ULONG',value:0x5F0F3CF5},{name:'flags',type:'USHORT',value:0},{name:'unitsPerEm',type:'USHORT',value:1000},{name:'created',type:'LONGDATETIME',value:createdTimestamp},{name:'modified',type:'LONGDATETIME',value:timestamp},{name:'xMin',type:'SHORT',value:0},{name:'yMin',type:'SHORT',value:0},{name:'xMax',type:'SHORT',value:0},{name:'yMax',type:'SHORT',value:0},{name:'macStyle',type:'USHORT',value:0},{name:'lowestRecPPEM',type:'USHORT',value:0},{name:'fontDirectionHint',type:'SHORT',value:2},{name:'indexToLocFormat',type:'SHORT',value:0},{name:'glyphDataFormat',type:'SHORT',value:0}],options);}var head={parse:parseHeadTable,make:makeHeadTable};// The `hhea` table contains information for horizontal layout. // Parse the horizontal header `hhea` table function parseHheaTable(data,start){var hhea={};var p=new parse.Parser(data,start);hhea.version=p.parseVersion();hhea.ascender=p.parseShort();hhea.descender=p.parseShort();hhea.lineGap=p.parseShort();hhea.advanceWidthMax=p.parseUShort();hhea.minLeftSideBearing=p.parseShort();hhea.minRightSideBearing=p.parseShort();hhea.xMaxExtent=p.parseShort();hhea.caretSlopeRise=p.parseShort();hhea.caretSlopeRun=p.parseShort();hhea.caretOffset=p.parseShort();p.relativeOffset+=8;hhea.metricDataFormat=p.parseShort();hhea.numberOfHMetrics=p.parseUShort();return hhea;}function makeHheaTable(options){return new table.Table('hhea',[{name:'version',type:'FIXED',value:0x00010000},{name:'ascender',type:'FWORD',value:0},{name:'descender',type:'FWORD',value:0},{name:'lineGap',type:'FWORD',value:0},{name:'advanceWidthMax',type:'UFWORD',value:0},{name:'minLeftSideBearing',type:'FWORD',value:0},{name:'minRightSideBearing',type:'FWORD',value:0},{name:'xMaxExtent',type:'FWORD',value:0},{name:'caretSlopeRise',type:'SHORT',value:1},{name:'caretSlopeRun',type:'SHORT',value:0},{name:'caretOffset',type:'SHORT',value:0},{name:'reserved1',type:'SHORT',value:0},{name:'reserved2',type:'SHORT',value:0},{name:'reserved3',type:'SHORT',value:0},{name:'reserved4',type:'SHORT',value:0},{name:'metricDataFormat',type:'SHORT',value:0},{name:'numberOfHMetrics',type:'USHORT',value:0}],options);}var hhea={parse:parseHheaTable,make:makeHheaTable};// The `hmtx` table contains the horizontal metrics for all glyphs. // Parse the `hmtx` table, which contains the horizontal metrics for all glyphs. // This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph. function parseHmtxTable(data,start,numMetrics,numGlyphs,glyphs){var advanceWidth;var leftSideBearing;var p=new parse.Parser(data,start);for(var i=0;i<numGlyphs;i+=1){// If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. if(i<numMetrics){advanceWidth=p.parseUShort();leftSideBearing=p.parseShort();}var glyph=glyphs.get(i);glyph.advanceWidth=advanceWidth;glyph.leftSideBearing=leftSideBearing;}}function makeHmtxTable(glyphs){var t=new table.Table('hmtx',[]);for(var i=0;i<glyphs.length;i+=1){var glyph=glyphs.get(i);var advanceWidth=glyph.advanceWidth||0;var leftSideBearing=glyph.leftSideBearing||0;t.fields.push({name:'advanceWidth_'+i,type:'USHORT',value:advanceWidth});t.fields.push({name:'leftSideBearing_'+i,type:'SHORT',value:leftSideBearing});}return t;}var hmtx={parse:parseHmtxTable,make:makeHmtxTable};// The `ltag` table stores IETF BCP-47 language tags. It allows supporting function makeLtagTable(tags){var result=new table.Table('ltag',[{name:'version',type:'ULONG',value:1},{name:'flags',type:'ULONG',value:0},{name:'numTags',type:'ULONG',value:tags.length}]);var stringPool='';var stringPoolOffset=12+tags.length*4;for(var i=0;i<tags.length;++i){var pos=stringPool.indexOf(tags[i]);if(pos<0){pos=stringPool.length;stringPool+=tags[i];}result.fields.push({name:'offset '+i,type:'USHORT',value:stringPoolOffset+pos});result.fields.push({name:'length '+i,type:'USHORT',value:tags[i].length});}result.fields.push({name:'stringPool',type:'CHARARRAY',value:stringPool});return result;}function parseLtagTable(data,start){var p=new parse.Parser(data,start);var tableVersion=p.parseULong();check.argument(tableVersion===1,'Unsupported ltag table version.');// The 'ltag' specification does not define any flags; skip the field. p.skip('uLong',1);var numTags=p.parseULong();var tags=[];for(var i=0;i<numTags;i++){var tag='';var offset=start+p.parseUShort();var length=p.parseUShort();for(var j=offset;j<offset+length;++j){tag+=String.fromCharCode(data.getInt8(j));}tags.push(tag);}return tags;}var ltag={make:makeLtagTable,parse:parseLtagTable};// The `maxp` table establishes the memory requirements for the font. // Parse the maximum profile `maxp` table. function parseMaxpTable(data,start){var maxp={};var p=new parse.Parser(data,start);maxp.version=p.parseVersion();maxp.numGlyphs=p.parseUShort();if(maxp.version===1.0){maxp.maxPoints=p.parseUShort();maxp.maxContours=p.parseUShort();maxp.maxCompositePoints=p.parseUShort();maxp.maxCompositeContours=p.parseUShort();maxp.maxZones=p.parseUShort();maxp.maxTwilightPoints=p.parseUShort();maxp.maxStorage=p.parseUShort();maxp.maxFunctionDefs=p.parseUShort();maxp.maxInstructionDefs=p.parseUShort();maxp.maxStackElements=p.parseUShort();maxp.maxSizeOfInstructions=p.parseUShort();maxp.maxComponentElements=p.parseUShort();maxp.maxComponentDepth=p.parseUShort();}return maxp;}function makeMaxpTable(numGlyphs){return new table.Table('maxp',[{name:'version',type:'FIXED',value:0x00005000},{name:'numGlyphs',type:'USHORT',value:numGlyphs}]);}var maxp={parse:parseMaxpTable,make:makeMaxpTable};// The `name` naming table. // NameIDs for the name table. var nameTableNames=['copyright',// 0 'fontFamily',// 1 'fontSubfamily',// 2 'uniqueID',// 3 'fullName',// 4 'version',// 5 'postScriptName',// 6 'trademark',// 7 'manufacturer',// 8 'designer',// 9 'description',// 10 'manufacturerURL',// 11 'designerURL',// 12 'license',// 13 'licenseURL',// 14 'reserved',// 15 'preferredFamily',// 16 'preferredSubfamily',// 17 'compatibleFullName',// 18 'sampleText',// 19 'postScriptFindFontName',// 20 'wwsFamily',// 21 'wwsSubfamily'// 22 ];var macLanguages={0:'en',1:'fr',2:'de',3:'it',4:'nl',5:'sv',6:'es',7:'da',8:'pt',9:'no',10:'he',11:'ja',12:'ar',13:'fi',14:'el',15:'is',16:'mt',17:'tr',18:'hr',19:'zh-Hant',20:'ur',21:'hi',22:'th',23:'ko',24:'lt',25:'pl',26:'hu',27:'es',28:'lv',29:'se',30:'fo',31:'fa',32:'ru',33:'zh',34:'nl-BE',35:'ga',36:'sq',37:'ro',38:'cz',39:'sk',40:'si',41:'yi',42:'sr',43:'mk',44:'bg',45:'uk',46:'be',47:'uz',48:'kk',49:'az-Cyrl',50:'az-Arab',51:'hy',52:'ka',53:'mo',54:'ky',55:'tg',56:'tk',57:'mn-CN',58:'mn',59:'ps',60:'ks',61:'ku',62:'sd',63:'bo',64:'ne',65:'sa',66:'mr',67:'bn',68:'as',69:'gu',70:'pa',71:'or',72:'ml',73:'kn',74:'ta',75:'te',76:'si',77:'my',78:'km',79:'lo',80:'vi',81:'id',82:'tl',83:'ms',84:'ms-Arab',85:'am',86:'ti',87:'om',88:'so',89:'sw',90:'rw',91:'rn',92:'ny',93:'mg',94:'eo',128:'cy',129:'eu',130:'ca',131:'la',132:'qu',133:'gn',134:'ay',135:'tt',136:'ug',137:'dz',138:'jv',139:'su',140:'gl',141:'af',142:'br',143:'iu',144:'gd',145:'gv',146:'ga',147:'to',148:'el-polyton',149:'kl',150:'az',151:'nn'};// MacOS language ID → MacOS script ID // // Note that the script ID is not sufficient to determine what encoding // to use in TrueType files. For some languages, MacOS used a modification // of a mainstream script. For example, an Icelandic name would be stored // with smRoman in the TrueType naming table, but the actual encoding // is a special Icelandic version of the normal Macintosh Roman encoding. // As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal // Syllables but MacOS had run out of available script codes, so this was // done as a (pretty radical) "modification" of Ethiopic. // // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt var macLanguageToScript={0:0,// langEnglish → smRoman 1:0,// langFrench → smRoman 2:0,// langGerman → smRoman 3:0,// langItalian → smRoman 4:0,// langDutch → smRoman 5:0,// langSwedish → smRoman 6:0,// langSpanish → smRoman 7:0,// langDanish → smRoman 8:0,// langPortuguese → smRoman 9:0,// langNorwegian → smRoman 10:5,// langHebrew → smHebrew 11:1,// langJapanese → smJapanese 12:4,// langArabic → smArabic 13:0,// langFinnish → smRoman 14:6,// langGreek → smGreek 15:0,// langIcelandic → smRoman (modified) 16:0,// langMaltese → smRoman 17:0,// langTurkish → smRoman (modified) 18:0,// langCroatian → smRoman (modified) 19:2,// langTradChinese → smTradChinese 20:4,// langUrdu → smArabic 21:9,// langHindi → smDevanagari 22:21,// langThai → smThai 23:3,// langKorean → smKorean 24:29,// langLithuanian → smCentralEuroRoman 25:29,// langPolish → smCentralEuroRoman 26:29,// langHungarian → smCentralEuroRoman 27:29,// langEstonian → smCentralEuroRoman 28:29,// langLatvian → smCentralEuroRoman 29:0,// langSami → smRoman 30:0,// langFaroese → smRoman (modified) 31:4,// langFarsi → smArabic (modified) 32:7,// langRussian → smCyrillic 33:25,// langSimpChinese → smSimpChinese 34:0,// langFlemish → smRoman 35:0,// langIrishGaelic → smRoman (modified) 36:0,// langAlbanian → smRoman 37:0,// langRomanian → smRoman (modified) 38:29,// langCzech → smCentralEuroRoman 39:29,// langSlovak → smCentralEuroRoman 40:0,// langSlovenian → smRoman (modified) 41:5,// langYiddish → smHebrew 42:7,// langSerbian → smCyrillic 43:7,// langMacedonian → smCyrillic 44:7,// langBulgarian → smCyrillic 45:7,// langUkrainian → smCyrillic (modified) 46:7,// langByelorussian → smCyrillic 47:7,// langUzbek → smCyrillic 48:7,// langKazakh → smCyrillic 49:7,// langAzerbaijani → smCyrillic 50:4,// langAzerbaijanAr → smArabic 51:24,// langArmenian → smArmenian 52:23,// langGeorgian → smGeorgian 53:7,// langMoldavian → smCyrillic 54:7,// langKirghiz → smCyrillic 55:7,// langTajiki → smCyrillic 56:7,// langTurkmen → smCyrillic 57:27,// langMongolian → smMongolian 58:7,// langMongolianCyr → smCyrillic 59:4,// langPashto → smArabic 60:4,// langKurdish → smArabic 61:4,// langKashmiri → smArabic 62:4,// langSindhi → smArabic 63:26,// langTibetan → smTibetan 64:9,// langNepali → smDevanagari 65:9,// langSanskrit → smDevanagari 66:9,// langMarathi → smDevanagari 67:13,// langBengali → smBengali 68:13,// langAssamese → smBengali 69:11,// langGujarati → smGujarati 70:10,// langPunjabi → smGurmukhi 71:12,// langOriya → smOriya 72:17,// langMalayalam → smMalayalam 73:16,// langKannada → smKannada 74:14,// langTamil → smTamil 75:15,// langTelugu → smTelugu 76:18,// langSinhalese → smSinhalese 77:19,// langBurmese → smBurmese 78:20,// langKhmer → smKhmer 79:22,// langLao → smLao 80:30,// langVietnamese → smVietnamese 81:0,// langIndonesian → smRoman 82:0,// langTagalog → smRoman 83:0,// langMalayRoman → smRoman 84:4,// langMalayArabic → smArabic 85:28,// langAmharic → smEthiopic 86:28,// langTigrinya → smEthiopic 87:28,// langOromo → smEthiopic 88:0,// langSomali → smRoman 89:0,// langSwahili → smRoman 90:0,// langKinyarwanda → smRoman 91:0,// langRundi → smRoman 92:0,// langNyanja → smRoman 93:0,// langMalagasy → smRoman 94:0,// langEsperanto → smRoman 128:0,// langWelsh → smRoman (modified) 129:0,// langBasque → smRoman 130:0,// langCatalan → smRoman 131:0,// langLatin → smRoman 132:0,// langQuechua → smRoman 133:0,// langGuarani → smRoman 134:0,// langAymara → smRoman 135:7,// langTatar → smCyrillic 136:4,// langUighur → smArabic 137:26,// langDzongkha → smTibetan 138:0,// langJavaneseRom → smRoman 139:0,// langSundaneseRom → smRoman 140:0,// langGalician → smRoman 141:0,// langAfrikaans → smRoman 142:0,// langBreton → smRoman (modified) 143:28,// langInuktitut → smEthiopic (modified) 144:0,// langScottishGaelic → smRoman (modified) 145:0,// langManxGaelic → smRoman (modified) 146:0,// langIrishGaelicScript → smRoman (modified) 147:0,// langTongan → smRoman 148:6,// langGreekAncient → smRoman 149:0,// langGreenlandic → smRoman 150:0,// langAzerbaijanRoman → smRoman 151:0// langNynorsk → smRoman };// While Microsoft indicates a region/country for all its language // IDs, we omit the region code if it's equal to the "most likely // region subtag" according to Unicode CLDR. For scripts, we omit // the subtag if it is equal to the Suppress-Script entry in the // IANA language subtag registry for IETF BCP 47. // // For example, Microsoft states that its language code 0x041A is // Croatian in Croatia. We transform this to the BCP 47 language code 'hr' // and not 'hr-HR' because Croatia is the default country for Croatian, // according to Unicode CLDR. As another example, Microsoft states // that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform // this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script // for the Croatian language, according to IANA. // // http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html // http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry var windowsLanguages={0x0436:'af',0x041C:'sq',0x0484:'gsw',0x045E:'am',0x1401:'ar-DZ',0x3C01:'ar-BH',0x0C01:'ar',0x0801:'ar-IQ',0x2C01:'ar-JO',0x3401:'ar-KW',0x3001:'ar-LB',0x1001:'ar-LY',0x1801:'ary',0x2001:'ar-OM',0x4001:'ar-QA',0x0401:'ar-SA',0x2801:'ar-SY',0x1C01:'aeb',0x3801:'ar-AE',0x2401:'ar-YE',0x042B:'hy',0x044D:'as',0x082C:'az-Cyrl',0x042C:'az',0x046D:'ba',0x042D:'eu',0x0423:'be',0x0845:'bn',0x0445:'bn-IN',0x201A:'bs-Cyrl',0x141A:'bs',0x047E:'br',0x0402:'bg',0x0403:'ca',0x0C04:'zh-HK',0x1404:'zh-MO',0x0804:'zh',0x1004:'zh-SG',0x0404:'zh-TW',0x0483:'co',0x041A:'hr',0x101A:'hr-BA',0x0405:'cs',0x0406:'da',0x048C:'prs',0x0465:'dv',0x0813:'nl-BE',0x0413:'nl',0x0C09:'en-AU',0x2809:'en-BZ',0x1009:'en-CA',0x2409:'en-029',0x4009:'en-IN',0x1809:'en-IE',0x2009:'en-JM',0x4409:'en-MY',0x1409:'en-NZ',0x3409:'en-PH',0x4809:'en-SG',0x1C09:'en-ZA',0x2C09:'en-TT',0x0809:'en-GB',0x0409:'en',0x3009:'en-ZW',0x0425:'et',0x0438:'fo',0x0464:'fil',0x040B:'fi',0x080C:'fr-BE',0x0C0C:'fr-CA',0x040C:'fr',0x140C:'fr-LU',0x180C:'fr-MC',0x100C:'fr-CH',0x0462:'fy',0x0456:'gl',0x0437:'ka',0x0C07:'de-AT',0x0407:'de',0x1407:'de-LI',0x1007:'de-LU',0x0807:'de-CH',0x0408:'el',0x046F:'kl',0x0447:'gu',0x0468:'ha',0x040D:'he',0x0439:'hi',0x040E:'hu',0x040F:'is',0x0470:'ig',0x0421:'id',0x045D:'iu',0x085D:'iu-Latn',0x083C:'ga',0x0434:'xh',0x0435:'zu',0x0410:'it',0x0810:'it-CH',0x0411:'ja',0x044B:'kn',0x043F:'kk',0x0453:'km',0x0486:'quc',0x0487:'rw',0x0441:'sw',0x0457:'kok',0x0412:'ko',0x0440:'ky',0x0454:'lo',0x0426:'lv',0x0427:'lt',0x082E:'dsb',0x046E:'lb',0x042F:'mk',0x083E:'ms-BN',0x043E:'ms',0x044C:'ml',0x043A:'mt',0x0481:'mi',0x047A:'arn',0x044E:'mr',0x047C:'moh',0x0450:'mn',0x0850:'mn-CN',0x0461:'ne',0x0414:'nb',0x0814:'nn',0x0482:'oc',0x0448:'or',0x0463:'ps',0x0415:'pl',0x0416:'pt',0x0816:'pt-PT',0x0446:'pa',0x046B:'qu-BO',0x086B:'qu-EC',0x0C6B:'qu',0x0418:'ro',0x0417:'rm',0x0419:'ru',0x243B:'smn',0x103B:'smj-NO',0x143B:'smj',0x0C3B:'se-FI',0x043B:'se',0x083B:'se-SE',0x203B:'sms',0x183B:'sma-NO',0x1C3B:'sms',0x044F:'sa',0x1C1A:'sr-Cyrl-BA',0x0C1A:'sr',0x181A:'sr-Latn-BA',0x081A:'sr-Latn',0x046C:'nso',0x0432:'tn',0x045B:'si',0x041B:'sk',0x0424:'sl',0x2C0A:'es-AR',0x400A:'es-BO',0x340A:'es-CL',0x240A:'es-CO',0x140A:'es-CR',0x1C0A:'es-DO',0x300A:'es-EC',0x440A:'es-SV',0x100A:'es-GT',0x480A:'es-HN',0x080A:'es-MX',0x4C0A:'es-NI',0x180A:'es-PA',0x3C0A:'es-PY',0x280A:'es-PE',0x500A:'es-PR',// Microsoft has defined two different language codes for // “Spanish with modern sorting” and “Spanish with traditional // sorting”. This makes sense for collation APIs, and it would be // possible to express this in BCP 47 language tags via Unicode // extensions (eg., es-u-co-trad is Spanish with traditional // sorting). However, for storing names in fonts, the distinction // does not make sense, so we give “es” in both cases. 0x0C0A:'es',0x040A:'es',0x540A:'es-US',0x380A:'es-UY',0x200A:'es-VE',0x081D:'sv-FI',0x041D:'sv',0x045A:'syr',0x0428:'tg',0x085F:'tzm',0x0449:'ta',0x0444:'tt',0x044A:'te',0x041E:'th',0x0451:'bo',0x041F:'tr',0x0442:'tk',0x0480:'ug',0x0422:'uk',0x042E:'hsb',0x0420:'ur',0x0843:'uz-Cyrl',0x0443:'uz',0x042A:'vi',0x0452:'cy',0x0488:'wo',0x0485:'sah',0x0478:'ii',0x046A:'yo'};// Returns a IETF BCP 47 language code, for example 'zh-Hant' // for 'Chinese in the traditional script'. function getLanguageCode(platformID,languageID,ltag){switch(platformID){case 0:// Unicode if(languageID===0xFFFF){return'und';}else if(ltag){return ltag[languageID];}break;case 1:// Macintosh return macLanguages[languageID];case 3:// Windows return windowsLanguages[languageID];}return undefined;}var utf16='utf-16';// MacOS script ID → encoding. This table stores the default case, // which can be overridden by macLanguageEncodings. var macScriptEncodings={0:'macintosh',// smRoman 1:'x-mac-japanese',// smJapanese 2:'x-mac-chinesetrad',// smTradChinese 3:'x-mac-korean',// smKorean 6:'x-mac-greek',// smGreek 7:'x-mac-cyrillic',// smCyrillic 9:'x-mac-devanagai',// smDevanagari 10:'x-mac-gurmukhi',// smGurmukhi 11:'x-mac-gujarati',// smGujarati 12:'x-mac-oriya',// smOriya 13:'x-mac-bengali',// smBengali 14:'x-mac-tamil',// smTamil 15:'x-mac-telugu',// smTelugu 16:'x-mac-kannada',// smKannada 17:'x-mac-malayalam',// smMalayalam 18:'x-mac-sinhalese',// smSinhalese 19:'x-mac-burmese',// smBurmese 20:'x-mac-khmer',// smKhmer 21:'x-mac-thai',// smThai 22:'x-mac-lao',// smLao 23:'x-mac-georgian',// smGeorgian 24:'x-mac-armenian',// smArmenian 25:'x-mac-chinesesimp',// smSimpChinese 26:'x-mac-tibetan',// smTibetan 27:'x-mac-mongolian',// smMongolian 28:'x-mac-ethiopic',// smEthiopic 29:'x-mac-ce',// smCentralEuroRoman 30:'x-mac-vietnamese',// smVietnamese 31:'x-mac-extarabic'// smExtArabic };// MacOS language ID → encoding. This table stores the exceptional // cases, which override macScriptEncodings. For writing MacOS naming // tables, we need to emit a MacOS script ID. Therefore, we cannot // merge macScriptEncodings into macLanguageEncodings. // // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt var macLanguageEncodings={15:'x-mac-icelandic',// langIcelandic 17:'x-mac-turkish',// langTurkish 18:'x-mac-croatian',// langCroatian 24:'x-mac-ce',// langLithuanian 25:'x-mac-ce',// langPolish 26:'x-mac-ce',// langHungarian 27:'x-mac-ce',// langEstonian 28:'x-mac-ce',// langLatvian 30:'x-mac-icelandic',// langFaroese 37:'x-mac-romanian',// langRomanian 38:'x-mac-ce',// langCzech 39:'x-mac-ce',// langSlovak 40:'x-mac-ce',// langSlovenian 143:'x-mac-inuit',// langInuktitut 146:'x-mac-gaelic'// langIrishGaelicScript };function getEncoding(platformID,encodingID,languageID){switch(platformID){case 0:// Unicode return utf16;case 1:// Apple Macintosh return macLanguageEncodings[languageID]||macScriptEncodings[encodingID];case 3:// Microsoft Windows if(encodingID===1||encodingID===10){return utf16;}break;}return undefined;}// Parse the naming `name` table. // FIXME: Format 1 additional fields are not supported yet. // ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904']. function parseNameTable(data,start,ltag){var name={};var p=new parse.Parser(data,start);var format=p.parseUShort();var count=p.parseUShort();var stringOffset=p.offset+p.parseUShort();for(var i=0;i<count;i++){var platformID=p.parseUShort();var encodingID=p.parseUShort();var languageID=p.parseUShort();var nameID=p.parseUShort();var property=nameTableNames[nameID]||nameID;var byteLength=p.parseUShort();var offset=p.parseUShort();var language=getLanguageCode(platformID,languageID,ltag);var encoding=getEncoding(platformID,encodingID,languageID);if(encoding!==undefined&&language!==undefined){var text=void 0;if(encoding===utf16){text=decode.UTF16(data,stringOffset+offset,byteLength);}else{text=decode.MACSTRING(data,stringOffset+offset,byteLength,encoding);}if(text){var translations=name[property];if(translations===undefined){translations=name[property]={};}translations[language]=text;}}}var langTagCount=0;if(format===1){// FIXME: Also handle Microsoft's 'name' table 1. langTagCount=p.parseUShort();}return name;}// {23: 'foo'} → {'foo': 23} // ['bar', 'baz'] → {'bar': 0, 'baz': 1} function reverseDict(dict){var result={};for(var key in dict){result[dict[key]]=parseInt(key);}return result;}function makeNameRecord(platformID,encodingID,languageID,nameID,length,offset){return new table.Record('NameRecord',[{name:'platformID',type:'USHORT',value:platformID},{name:'encodingID',type:'USHORT',value:encodingID},{name:'languageID',type:'USHORT',value:languageID},{name:'nameID',type:'USHORT',value:nameID},{name:'length',type:'USHORT',value:length},{name:'offset',type:'USHORT',value:offset}]);}// Finds the position of needle in haystack, or -1 if not there. // Like String.indexOf(), but for arrays. function findSubArray(needle,haystack){var needleLength=needle.length;var limit=haystack.length-needleLength+1;loop:for(var pos=0;pos<limit;pos++){for(;pos<limit;pos++){for(var k=0;k<needleLength;k++){if(haystack[pos+k]!==needle[k]){continue loop;}}return pos;}}return-1;}function addStringToPool(s,pool){var offset=findSubArray(s,pool);if(offset<0){offset=pool.length;var i=0;var len=s.length;for(;i<len;++i){pool.push(s[i]);}}return offset;}function makeNameTable(names,ltag){var nameID;var nameIDs=[];var namesWithNumericKeys={};var nameTableIds=reverseDict(nameTableNames);for(var key in names){var id=nameTableIds[key];if(id===undefined){id=key;}nameID=parseInt(id);if(isNaN(nameID)){throw new Error('Name table entry "'+key+'" does not exist, see nameTableNames for complete list.');}namesWithNumericKeys[nameID]=names[key];nameIDs.push(nameID);}var macLanguageIds=reverseDict(macLanguages);var windowsLanguageIds=reverseDict(windowsLanguages);var nameRecords=[];var stringPool=[];for(var i=0;i<nameIDs.length;i++){nameID=nameIDs[i];var translations=namesWithNumericKeys[nameID];for(var lang in translations){var text=translations[lang];// For MacOS, we try to emit the name in the form that was introduced // in the initial version of the TrueType spec (in the late 1980s). // However, this can fail for various reasons: the requested BCP 47 // language code might not have an old-style Mac equivalent; // we might not have a codec for the needed character encoding; // or the name might contain characters that cannot be expressed // in the old-style Macintosh encoding. In case of failure, we emit // the name in a more modern fashion (Unicode encoding with BCP 47 // language tags) that is recognized by MacOS 10.5, released in 2009. // If fonts were only read by operating systems, we could simply // emit all names in the modern form; this would be much easier. // However, there are many applications and libraries that read // 'name' tables directly, and these will usually only recognize // the ancient form (silently skipping the unrecognized names). var macPlatform=1;// Macintosh var macLanguage=macLanguageIds[lang];var macScript=macLanguageToScript[macLanguage];var macEncoding=getEncoding(macPlatform,macScript,macLanguage);var macName=encode.MACSTRING(text,macEncoding);if(macName===undefined){macPlatform=0;// Unicode macLanguage=ltag.indexOf(lang);if(macLanguage<0){macLanguage=ltag.length;ltag.push(lang);}macScript=4;// Unicode 2.0 and later macName=encode.UTF16(text);}var macNameOffset=addStringToPool(macName,stringPool);nameRecords.push(makeNameRecord(macPlatform,macScript,macLanguage,nameID,macName.length,macNameOffset));var winLanguage=windowsLanguageIds[lang];if(winLanguage!==undefined){var winName=encode.UTF16(text);var winNameOffset=addStringToPool(winName,stringPool);nameRecords.push(makeNameRecord(3,1,winLanguage,nameID,winName.length,winNameOffset));}}}nameRecords.sort(function(a,b){return a.platformID-b.platformID||a.encodingID-b.encodingID||a.languageID-b.languageID||a.nameID-b.nameID;});var t=new table.Table('name',[{name:'format',type:'USHORT',value:0},{name:'count',type:'USHORT',value:nameRecords.length},{name:'stringOffset',type:'USHORT',value:6+nameRecords.length*12}]);for(var r=0;r<nameRecords.length;r++){t.fields.push({name:'record_'+r,type:'RECORD',value:nameRecords[r]});}t.fields.push({name:'strings',type:'LITERAL',value:stringPool});return t;}var _name={parse:parseNameTable,make:makeNameTable};// The `OS/2` table contains metrics required in OpenType fonts. var unicodeRanges=[{begin:0x0000,end:0x007F},// Basic Latin {begin:0x0080,end:0x00FF},// Latin-1 Supplement {begin:0x0100,end:0x017F},// Latin Extended-A {begin:0x0180,end:0x024F},// Latin Extended-B {begin:0x0250,end:0x02AF},// IPA Extensions {begin:0x02B0,end:0x02FF},// Spacing Modifier Letters {begin:0x0300,end:0x036F},// Combining Diacritical Marks {begin:0x0370,end:0x03FF},// Greek and Coptic {begin:0x2C80,end:0x2CFF},// Coptic {begin:0x0400,end:0x04FF},// Cyrillic {begin:0x0530,end:0x058F},// Armenian {begin:0x0590,end:0x05FF},// Hebrew {begin:0xA500,end:0xA63F},// Vai {begin:0x0600,end:0x06FF},// Arabic {begin:0x07C0,end:0x07FF},// NKo {begin:0x0900,end:0x097F},// Devanagari {begin:0x0980,end:0x09FF},// Bengali {begin:0x0A00,end:0x0A7F},// Gurmukhi {begin:0x0A80,end:0x0AFF},// Gujarati {begin:0x0B00,end:0x0B7F},// Oriya {begin:0x0B80,end:0x0BFF},// Tamil {begin:0x0C00,end:0x0C7F},// Telugu {begin:0x0C80,end:0x0CFF},// Kannada {begin:0x0D00,end:0x0D7F},// Malayalam {begin:0x0E00,end:0x0E7F},// Thai {begin:0x0E80,end:0x0EFF},// Lao {begin:0x10A0,end:0x10FF},// Georgian {begin:0x1B00,end:0x1B7F},// Balinese {begin:0x1100,end:0x11FF},// Hangul Jamo {begin:0x1E00,end:0x1EFF},// Latin Extended Additional {begin:0x1F00,end:0x1FFF},// Greek Extended {begin:0x2000,end:0x206F},// General Punctuation {begin:0x2070,end:0x209F},// Superscripts And Subscripts {begin:0x20A0,end:0x20CF},// Currency Symbol {begin:0x20D0,end:0x20FF},// Combining Diacritical Marks For Symbols {begin:0x2100,end:0x214F},// Letterlike Symbols {begin:0x2150,end:0x218F},// Number Forms {begin:0x2190,end:0x21FF},// Arrows {begin:0x2200,end:0x22FF},// Mathematical Operators {begin:0x2300,end:0x23FF},// Miscellaneous Technical {begin:0x2400,end:0x243F},// Control Pictures {begin:0x2440,end:0x245F},// Optical Character Recognition {begin:0x2460,end:0x24FF},// Enclosed Alphanumerics {begin:0x2500,end:0x257F},// Box Drawing {begin:0x2580,end:0x259F},// Block Elements {begin:0x25A0,end:0x25FF},// Geometric Shapes {begin:0x2600,end:0x26FF},// Miscellaneous Symbols {begin:0x2700,end:0x27BF},// Dingbats {begin:0x3000,end:0x303F},// CJK Symbols And Punctuation {begin:0x3040,end:0x309F},// Hiragana {begin:0x30A0,end:0x30FF},// Katakana {begin:0x3100,end:0x312F},// Bopomofo {begin:0x3130,end:0x318F},// Hangul Compatibility Jamo {begin:0xA840,end:0xA87F},// Phags-pa {begin:0x3200,end:0x32FF},// Enclosed CJK Letters And Months {begin:0x3300,end:0x33FF},// CJK Compatibility {begin:0xAC00,end:0xD7AF},// Hangul Syllables {begin:0xD800,end:0xDFFF},// Non-Plane 0 * {begin:0x10900,end:0x1091F},// Phoenicia {begin:0x4E00,end:0x9FFF},// CJK Unified Ideographs {begin:0xE000,end:0xF8FF},// Private Use Area (plane 0) {begin:0x31C0,end:0x31EF},// CJK Strokes {begin:0xFB00,end:0xFB4F},// Alphabetic Presentation Forms {begin:0xFB50,end:0xFDFF},// Arabic Presentation Forms-A {begin:0xFE20,end:0xFE2F},// Combining Half Marks {begin:0xFE10,end:0xFE1F},// Vertical Forms {begin:0xFE50,end:0xFE6F},// Small Form Variants {begin:0xFE70,end:0xFEFF},// Arabic Presentation Forms-B {begin:0xFF00,end:0xFFEF},// Halfwidth And Fullwidth Forms {begin:0xFFF0,end:0xFFFF},// Specials {begin:0x0F00,end:0x0FFF},// Tibetan {begin:0x0700,end:0x074F},// Syriac {begin:0x0780,end:0x07BF},// Thaana {begin:0x0D80,end:0x0DFF},// Sinhala {begin:0x1000,end:0x109F},// Myanmar {begin:0x1200,end:0x137F},// Ethiopic {begin:0x13A0,end:0x13FF},// Cherokee {begin:0x1400,end:0x167F},// Unified Canadian Aboriginal Syllabics {begin:0x1680,end:0x169F},// Ogham {begin:0x16A0,end:0x16FF},// Runic {begin:0x1780,end:0x17FF},// Khmer {begin:0x1800,end:0x18AF},// Mongolian {begin:0x2800,end:0x28FF},// Braille Patterns {begin:0xA000,end:0xA48F},// Yi Syllables {begin:0x1700,end:0x171F},// Tagalog {begin:0x10300,end:0x1032F},// Old Italic {begin:0x10330,end:0x1034F},// Gothic {begin:0x10400,end:0x1044F},// Deseret {begin:0x1D000,end:0x1D0FF},// Byzantine Musical Symbols {begin:0x1D400,end:0x1D7FF},// Mathematical Alphanumeric Symbols {begin:0xFF000,end:0xFFFFD},// Private Use (plane 15) {begin:0xFE00,end:0xFE0F},// Variation Selectors {begin:0xE0000,end:0xE007F},// Tags {begin:0x1900,end:0x194F},// Limbu {begin:0x1950,end:0x197F},// Tai Le {begin:0x1980,end:0x19DF},// New Tai Lue {begin:0x1A00,end:0x1A1F},// Buginese {begin:0x2C00,end:0x2C5F},// Glagolitic {begin:0x2D30,end:0x2D7F},// Tifinagh {begin:0x4DC0,end:0x4DFF},// Yijing Hexagram Symbols {begin:0xA800,end:0xA82F},// Syloti Nagri {begin:0x10000,end:0x1007F},// Linear B Syllabary {begin:0x10140,end:0x1018F},// Ancient Greek Numbers {begin:0x10380,end:0x1039F},// Ugaritic {begin:0x103A0,end:0x103DF},// Old Persian {begin:0x10450,end:0x1047F},// Shavian {begin:0x10480,end:0x104AF},// Osmanya {begin:0x10800,end:0x1083F},// Cypriot Syllabary {begin:0x10A00,end:0x10A5F},// Kharoshthi {begin:0x1D300,end:0x1D35F},// Tai Xuan Jing Symbols {begin:0x12000,end:0x123FF},// Cuneiform {begin:0x1D360,end:0x1D37F},// Counting Rod Numerals {begin:0x1B80,end:0x1BBF},// Sundanese {begin:0x1C00,end:0x1C4F},// Lepcha {begin:0x1C50,end:0x1C7F},// Ol Chiki {begin:0xA880,end:0xA8DF},// Saurashtra {begin:0xA900,end:0xA92F},// Kayah Li {begin:0xA930,end:0xA95F},// Rejang {begin:0xAA00,end:0xAA5F},// Cham {begin:0x10190,end:0x101CF},// Ancient Symbols {begin:0x101D0,end:0x101FF},// Phaistos Disc {begin:0x102A0,end:0x102DF},// Carian {begin:0x1F030,end:0x1F09F// Domino Tiles }];function getUnicodeRange(unicode){for(var i=0;i<unicodeRanges.length;i+=1){var range=unicodeRanges[i];if(unicode>=range.begin&&unicode<range.end){return i;}}return-1;}// Parse the OS/2 and Windows metrics `OS/2` table function parseOS2Table(data,start){var os2={};var p=new parse.Parser(data,start);os2.version=p.parseUShort();os2.xAvgCharWidth=p.parseShort();os2.usWeightClass=p.parseUShort();os2.usWidthClass=p.parseUShort();os2.fsType=p.parseUShort();os2.ySubscriptXSize=p.parseShort();os2.ySubscriptYSize=p.parseShort();os2.ySubscriptXOffset=p.parseShort();os2.ySubscriptYOffset=p.parseShort();os2.ySuperscriptXSize=p.parseShort();os2.ySuperscriptYSize=p.parseShort();os2.ySuperscriptXOffset=p.parseShort();os2.ySuperscriptYOffset=p.parseShort();os2.yStrikeoutSize=p.parseShort();os2.yStrikeoutPosition=p.parseShort();os2.sFamilyClass=p.parseShort();os2.panose=[];for(var i=0;i<10;i++){os2.panose[i]=p.parseByte();}os2.ulUnicodeRange1=p.parseULong();os2.ulUnicodeRange2=p.parseULong();os2.ulUnicodeRange3=p.parseULong();os2.ulUnicodeRange4=p.parseULong();os2.achVendID=String.fromCharCode(p.parseByte(),p.parseByte(),p.parseByte(),p.parseByte());os2.fsSelection=p.parseUShort();os2.usFirstCharIndex=p.parseUShort();os2.usLastCharIndex=p.parseUShort();os2.sTypoAscender=p.parseShort();os2.sTypoDescender=p.parseShort();os2.sTypoLineGap=p.parseShort();os2.usWinAscent=p.parseUShort();os2.usWinDescent=p.parseUShort();if(os2.version>=1){os2.ulCodePageRange1=p.parseULong();os2.ulCodePageRange2=p.parseULong();}if(os2.version>=2){os2.sxHeight=p.parseShort();os2.sCapHeight=p.parseShort();os2.usDefaultChar=p.parseUShort();os2.usBreakChar=p.parseUShort();os2.usMaxContent=p.parseUShort();}return os2;}function makeOS2Table(options){return new table.Table('OS/2',[{name:'version',type:'USHORT',value:0x0003},{name:'xAvgCharWidth',type:'SHORT',value:0},{name:'usWeightClass',type:'USHORT',value:0},{name:'usWidthClass',type:'USHORT',value:0},{name:'fsType',type:'USHORT',value:0},{name:'ySubscriptXSize',type:'SHORT',value:650},{name:'ySubscriptYSize',type:'SHORT',value:699},{name:'ySubscriptXOffset',type:'SHORT',value:0},{name:'ySubscriptYOffset',type:'SHORT',value:140},{name:'ySuperscriptXSize',type:'SHORT',value:650},{name:'ySuperscriptYSize',type:'SHORT',value:699},{name:'ySuperscriptXOffset',type:'SHORT',value:0},{name:'ySuperscriptYOffset',type:'SHORT',value:479},{name:'yStrikeoutSize',type:'SHORT',value:49},{name:'yStrikeoutPosition',type:'SHORT',value:258},{name:'sFamilyClass',type:'SHORT',value:0},{name:'bFamilyType',type:'BYTE',value:0},{name:'bSerifStyle',type:'BYTE',value:0},{name:'bWeight',type:'BYTE',value:0},{name:'bProportion',type:'BYTE',value:0},{name:'bContrast',type:'BYTE',value:0},{name:'bStrokeVariation',type:'BYTE',value:0},{name:'bArmStyle',type:'BYTE',value:0},{name:'bLetterform',type:'BYTE',value:0},{name:'bMidline',type:'BYTE',value:0},{name:'bXHeight',type:'BYTE',value:0},{name:'ulUnicodeRange1',type:'ULONG',value:0},{name:'ulUnicodeRange2',type:'ULONG',value:0},{name:'ulUnicodeRange3',type:'ULONG',value:0},{name:'ulUnicodeRange4',type:'ULONG',value:0},{name:'achVendID',type:'CHARARRAY',value:'XXXX'},{name:'fsSelection',type:'USHORT',value:0},{name:'usFirstCharIndex',type:'USHORT',value:0},{name:'usLastCharIndex',type:'USHORT',value:0},{name:'sTypoAscender',type:'SHORT',value:0},{name:'sTypoDescender',type:'SHORT',value:0},{name:'sTypoLineGap',type:'SHORT',value:0},{name:'usWinAscent',type:'USHORT',value:0},{name:'usWinDescent',type:'USHORT',value:0},{name:'ulCodePageRange1',type:'ULONG',value:0},{name:'ulCodePageRange2',type:'ULONG',value:0},{name:'sxHeight',type:'SHORT',value:0},{name:'sCapHeight',type:'SHORT',value:0},{name:'usDefaultChar',type:'USHORT',value:0},{name:'usBreakChar',type:'USHORT',value:0},{name:'usMaxContext',type:'USHORT',value:0}],options);}var os2={parse:parseOS2Table,make:makeOS2Table,unicodeRanges:unicodeRanges,getUnicodeRange:getUnicodeRange};// The `post` table stores additional PostScript information, such as glyph names. // Parse the PostScript `post` table function parsePostTable(data,start){var post={};var p=new parse.Parser(data,start);post.version=p.parseVersion();post.italicAngle=p.parseFixed();post.underlinePosition=p.parseShort();post.underlineThickness=p.parseShort();post.isFixedPitch=p.parseULong();post.minMemType42=p.parseULong();post.maxMemType42=p.parseULong();post.minMemType1=p.parseULong();post.maxMemType1=p.parseULong();switch(post.version){case 1:post.names=standardNames.slice();break;case 2:post.numberOfGlyphs=p.parseUShort();post.glyphNameIndex=new Array(post.numberOfGlyphs);for(var i=0;i<post.numberOfGlyphs;i++){post.glyphNameIndex[i]=p.parseUShort();}post.names=[];for(var i$1=0;i$1<post.numberOfGlyphs;i$1++){if(post.glyphNameIndex[i$1]>=standardNames.length){var nameLength=p.parseChar();post.names.push(p.parseString(nameLength));}}break;case 2.5:post.numberOfGlyphs=p.parseUShort();post.offset=new Array(post.numberOfGlyphs);for(var i$2=0;i$2<post.numberOfGlyphs;i$2++){post.offset[i$2]=p.parseChar();}break;}return post;}function makePostTable(){return new table.Table('post',[{name:'version',type:'FIXED',value:0x00030000},{name:'italicAngle',type:'FIXED',value:0},{name:'underlinePosition',type:'FWORD',value:0},{name:'underlineThickness',type:'FWORD',value:0},{name:'isFixedPitch',type:'ULONG',value:0},{name:'minMemType42',type:'ULONG',value:0},{name:'maxMemType42',type:'ULONG',value:0},{name:'minMemType1',type:'ULONG',value:0},{name:'maxMemType1',type:'ULONG',value:0}]);}var post={parse:parsePostTable,make:makePostTable};// The `GSUB` table contains ligatures, among other things. var subtableParsers=new Array(9);// subtableParsers[0] is unused // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS subtableParsers[1]=function parseLookup1(){var start=this.offset+this.relativeOffset;var substFormat=this.parseUShort();if(substFormat===1){return{substFormat:1,coverage:this.parsePointer(Parser.coverage),deltaGlyphId:this.parseUShort()};}else if(substFormat===2){return{substFormat:2,coverage:this.parsePointer(Parser.coverage),substitute:this.parseOffset16List()};}check.assert(false,'0x'+start.toString(16)+': lookup type 1 format must be 1 or 2.');};// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS subtableParsers[2]=function parseLookup2(){var substFormat=this.parseUShort();check.argument(substFormat===1,'GSUB Multiple Substitution Subtable identifier-format must be 1');return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),sequences:this.parseListOfLists()};};// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS subtableParsers[3]=function parseLookup3(){var substFormat=this.parseUShort();check.argument(substFormat===1,'GSUB Alternate Substitution Subtable identifier-format must be 1');return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),alternateSets:this.parseListOfLists()};};// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS subtableParsers[4]=function parseLookup4(){var substFormat=this.parseUShort();check.argument(substFormat===1,'GSUB ligature table identifier-format must be 1');return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),ligatureSets:this.parseListOfLists(function(){return{ligGlyph:this.parseUShort(),components:this.parseUShortList(this.parseUShort()-1)};})};};var lookupRecordDesc={sequenceIndex:Parser.uShort,lookupListIndex:Parser.uShort};// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF subtableParsers[5]=function parseLookup5(){var start=this.offset+this.relativeOffset;var substFormat=this.parseUShort();if(substFormat===1){return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),ruleSets:this.parseListOfLists(function(){var glyphCount=this.parseUShort();var substCount=this.parseUShort();return{input:this.parseUShortList(glyphCount-1),lookupRecords:this.parseRecordList(substCount,lookupRecordDesc)};})};}else if(substFormat===2){return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),classDef:this.parsePointer(Parser.classDef),classSets:this.parseListOfLists(function(){var glyphCount=this.parseUShort();var substCount=this.parseUShort();return{classes:this.parseUShortList(glyphCount-1),lookupRecords:this.parseRecordList(substCount,lookupRecordDesc)};})};}else if(substFormat===3){var glyphCount=this.parseUShort();var substCount=this.parseUShort();return{substFormat:substFormat,coverages:this.parseList(glyphCount,Parser.pointer(Parser.coverage)),lookupRecords:this.parseRecordList(substCount,lookupRecordDesc)};}check.assert(false,'0x'+start.toString(16)+': lookup type 5 format must be 1, 2 or 3.');};// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC subtableParsers[6]=function parseLookup6(){var start=this.offset+this.relativeOffset;var substFormat=this.parseUShort();if(substFormat===1){return{substFormat:1,coverage:this.parsePointer(Parser.coverage),chainRuleSets:this.parseListOfLists(function(){return{backtrack:this.parseUShortList(),input:this.parseUShortList(this.parseShort()-1),lookahead:this.parseUShortList(),lookupRecords:this.parseRecordList(lookupRecordDesc)};})};}else if(substFormat===2){return{substFormat:2,coverage:this.parsePointer(Parser.coverage),backtrackClassDef:this.parsePointer(Parser.classDef),inputClassDef:this.parsePointer(Parser.classDef),lookaheadClassDef:this.parsePointer(Parser.classDef),chainClassSet:this.parseListOfLists(function(){return{backtrack:this.parseUShortList(),input:this.parseUShortList(this.parseShort()-1),lookahead:this.parseUShortList(),lookupRecords:this.parseRecordList(lookupRecordDesc)};})};}else if(substFormat===3){return{substFormat:3,backtrackCoverage:this.parseList(Parser.pointer(Parser.coverage)),inputCoverage:this.parseList(Parser.pointer(Parser.coverage)),lookaheadCoverage:this.parseList(Parser.pointer(Parser.coverage)),lookupRecords:this.parseRecordList(lookupRecordDesc)};}check.assert(false,'0x'+start.toString(16)+': lookup type 6 format must be 1, 2 or 3.');};// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES subtableParsers[7]=function parseLookup7(){// Extension Substitution subtable var substFormat=this.parseUShort();check.argument(substFormat===1,'GSUB Extension Substitution subtable identifier-format must be 1');var extensionLookupType=this.parseUShort();var extensionParser=new Parser(this.data,this.offset+this.parseULong());return{substFormat:1,lookupType:extensionLookupType,extension:subtableParsers[extensionLookupType].call(extensionParser)};};// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS subtableParsers[8]=function parseLookup8(){var substFormat=this.parseUShort();check.argument(substFormat===1,'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1');return{substFormat:substFormat,coverage:this.parsePointer(Parser.coverage),backtrackCoverage:this.parseList(Parser.pointer(Parser.coverage)),lookaheadCoverage:this.parseList(Parser.pointer(Parser.coverage)),substitutes:this.parseUShortList()};};// https://www.microsoft.com/typography/OTSPEC/gsub.htm function parseGsubTable(data,start){start=start||0;var p=new Parser(data,start);var tableVersion=p.parseVersion(1);check.argument(tableVersion===1||tableVersion===1.1,'Unsupported GSUB table version.');if(tableVersion===1){return{version:tableVersion,scripts:p.parseScriptList(),features:p.parseFeatureList(),lookups:p.parseLookupList(subtableParsers)};}else{return{version:tableVersion,scripts:p.parseScriptList(),features:p.parseFeatureList(),lookups:p.parseLookupList(subtableParsers),variations:p.parseFeatureVariationsList()};}}// GSUB Writing ////////////////////////////////////////////// var subtableMakers=new Array(9);subtableMakers[1]=function makeLookup1(subtable){if(subtable.substFormat===1){return new table.Table('substitutionTable',[{name:'substFormat',type:'USHORT',value:1},{name:'coverage',type:'TABLE',value:new table.Coverage(subtable.coverage)},{name:'deltaGlyphID',type:'USHORT',value:subtable.deltaGlyphId}]);}else{return new table.Table('substitutionTable',[{name:'substFormat',type:'USHORT',value:2},{name:'coverage',type:'TABLE',value:new table.Coverage(subtable.coverage)}].concat(table.ushortList('substitute',subtable.substitute)));}check.fail('Lookup type 1 substFormat must be 1 or 2.');};subtableMakers[3]=function makeLookup3(subtable){check.assert(subtable.substFormat===1,'Lookup type 3 substFormat must be 1.');return new table.Table('substitutionTable',[{name:'substFormat',type:'USHORT',value:1},{name:'coverage',type:'TABLE',value:new table.Coverage(subtable.coverage)}].concat(table.tableList('altSet',subtable.alternateSets,function(alternateSet){return new table.Table('alternateSetTable',table.ushortList('alternate',alternateSet));})));};subtableMakers[4]=function makeLookup4(subtable){check.assert(subtable.substFormat===1,'Lookup type 4 substFormat must be 1.');return new table.Table('substitutionTable',[{name:'substFormat',type:'USHORT',value:1},{name:'coverage',type:'TABLE',value:new table.Coverage(subtable.coverage)}].concat(table.tableList('ligSet',subtable.ligatureSets,function(ligatureSet){return new table.Table('ligatureSetTable',table.tableList('ligature',ligatureSet,function(ligature){return new table.Table('ligatureTable',[{name:'ligGlyph',type:'USHORT',value:ligature.ligGlyph}].concat(table.ushortList('component',ligature.components,ligature.components.length+1)));}));})));};function makeGsubTable(gsub){return new table.Table('GSUB',[{name:'version',type:'ULONG',value:0x10000},{name:'scripts',type:'TABLE',value:new table.ScriptList(gsub.scripts)},{name:'features',type:'TABLE',value:new table.FeatureList(gsub.features)},{name:'lookups',type:'TABLE',value:new table.LookupList(gsub.lookups,subtableMakers)}]);}var gsub={parse:parseGsubTable,make:makeGsubTable};// The `GPOS` table contains kerning pairs, among other things. // Parse the metadata `meta` table. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html function parseMetaTable(data,start){var p=new parse.Parser(data,start);var tableVersion=p.parseULong();check.argument(tableVersion===1,'Unsupported META table version.');p.parseULong();// flags - currently unused and set to 0 p.parseULong();// tableOffset var numDataMaps=p.parseULong();var tags={};for(var i=0;i<numDataMaps;i++){var tag=p.parseTag();var dataOffset=p.parseULong();var dataLength=p.parseULong();var text=decode.UTF8(data,start+dataOffset,dataLength);tags[tag]=text;}return tags;}function makeMetaTable(tags){var numTags=Object.keys(tags).length;var stringPool='';var stringPoolOffset=16+numTags*12;var result=new table.Table('meta',[{name:'version',type:'ULONG',value:1},{name:'flags',type:'ULONG',value:0},{name:'offset',type:'ULONG',value:stringPoolOffset},{name:'numTags',type:'ULONG',value:numTags}]);for(var tag in tags){var pos=stringPool.length;stringPool+=tags[tag];result.fields.push({name:'tag '+tag,type:'TAG',value:tag});result.fields.push({name:'offset '+tag,type:'ULONG',value:stringPoolOffset+pos});result.fields.push({name:'length '+tag,type:'ULONG',value:tags[tag].length});}result.fields.push({name:'stringPool',type:'CHARARRAY',value:stringPool});return result;}var meta={parse:parseMetaTable,make:makeMetaTable};// The `sfnt` wrapper provides organization for the tables in the font. function log2(v){return Math.log(v)/Math.log(2)|0;}function computeCheckSum(bytes){while(bytes.length%4!==0){bytes.push(0);}var sum=0;for(var i=0;i<bytes.length;i+=4){sum+=(bytes[i]<<24)+(bytes[i+1]<<16)+(bytes[i+2]<<8)+bytes[i+3];}sum%=Math.pow(2,32);return sum;}function makeTableRecord(tag,checkSum,offset,length){return new table.Record('Table Record',[{name:'tag',type:'TAG',value:tag!==undefined?tag:''},{name:'checkSum',type:'ULONG',value:checkSum!==undefined?checkSum:0},{name:'offset',type:'ULONG',value:offset!==undefined?offset:0},{name:'length',type:'ULONG',value:length!==undefined?length:0}]);}function makeSfntTable(tables){var sfnt=new table.Table('sfnt',[{name:'version',type:'TAG',value:'OTTO'},{name:'numTables',type:'USHORT',value:0},{name:'searchRange',type:'USHORT',value:0},{name:'entrySelector',type:'USHORT',value:0},{name:'rangeShift',type:'USHORT',value:0}]);sfnt.tables=tables;sfnt.numTables=tables.length;var highestPowerOf2=Math.pow(2,log2(sfnt.numTables));sfnt.searchRange=16*highestPowerOf2;sfnt.entrySelector=log2(highestPowerOf2);sfnt.rangeShift=sfnt.numTables*16-sfnt.searchRange;var recordFields=[];var tableFields=[];var offset=sfnt.sizeOf()+makeTableRecord().sizeOf()*sfnt.numTables;while(offset%4!==0){offset+=1;tableFields.push({name:'padding',type:'BYTE',value:0});}for(var i=0;i<tables.length;i+=1){var t=tables[i];check.argument(t.tableName.length===4,'Table name'+t.tableName+' is invalid.');var tableLength=t.sizeOf();var tableRecord=makeTableRecord(t.tableName,computeCheckSum(t.encode()),offset,tableLength);recordFields.push({name:tableRecord.tag+' Table Record',type:'RECORD',value:tableRecord});tableFields.push({name:t.tableName+' table',type:'RECORD',value:t});offset+=tableLength;check.argument(!isNaN(offset),'Something went wrong calculating the offset.');while(offset%4!==0){offset+=1;tableFields.push({name:'padding',type:'BYTE',value:0});}}// Table records need to be sorted alphabetically. recordFields.sort(function(r1,r2){if(r1.value.tag>r2.value.tag){return 1;}else{return-1;}});sfnt.fields=sfnt.fields.concat(recordFields);sfnt.fields=sfnt.fields.concat(tableFields);return sfnt;}// Get the metrics for a character. If the string has more than one character // this function returns metrics for the first available character. // You can provide optional fallback metrics if no characters are available. function metricsForChar(font,chars,notFoundMetrics){for(var i=0;i<chars.length;i+=1){var glyphIndex=font.charToGlyphIndex(chars[i]);if(glyphIndex>0){var glyph=font.glyphs.get(glyphIndex);return glyph.getMetrics();}}return notFoundMetrics;}function average(vs){var sum=0;for(var i=0;i<vs.length;i+=1){sum+=vs[i];}return sum/vs.length;}// Convert the font object to a SFNT data structure. // This structure contains all the necessary tables and metadata to create a binary OTF file. function fontToSfntTable(font){var xMins=[];var yMins=[];var xMaxs=[];var yMaxs=[];var advanceWidths=[];var leftSideBearings=[];var rightSideBearings=[];var firstCharIndex;var lastCharIndex=0;var ulUnicodeRange1=0;var ulUnicodeRange2=0;var ulUnicodeRange3=0;var ulUnicodeRange4=0;for(var i=0;i<font.glyphs.length;i+=1){var glyph=font.glyphs.get(i);var unicode=glyph.unicode|0;if(isNaN(glyph.advanceWidth)){throw new Error('Glyph '+glyph.name+' ('+i+'): advanceWidth is not a number.');}if(firstCharIndex>unicode||firstCharIndex===undefined){// ignore .notdef char if(unicode>0){firstCharIndex=unicode;}}if(lastCharIndex<unicode){lastCharIndex=unicode;}var position=os2.getUnicodeRange(unicode);if(position<32){ulUnicodeRange1|=1<<position;}else if(position<64){ulUnicodeRange2|=1<<position-32;}else if(position<96){ulUnicodeRange3|=1<<position-64;}else if(position<123){ulUnicodeRange4|=1<<position-96;}else{throw new Error('Unicode ranges bits > 123 are reserved for internal usage');}// Skip non-important characters. if(glyph.name==='.notdef'){continue;}var metrics=glyph.getMetrics();xMins.push(metrics.xMin);yMins.push(metrics.yMin);xMaxs.push(metrics.xMax);yMaxs.push(metrics.yMax);leftSideBearings.push(metrics.leftSideBearing);rightSideBearings.push(metrics.rightSideBearing);advanceWidths.push(glyph.advanceWidth);}var globals={xMin:Math.min.apply(null,xMins),yMin:Math.min.apply(null,yMins),xMax:Math.max.apply(null,xMaxs),yMax:Math.max.apply(null,yMaxs),advanceWidthMax:Math.max.apply(null,advanceWidths),advanceWidthAvg:average(advanceWidths),minLeftSideBearing:Math.min.apply(null,leftSideBearings),maxLeftSideBearing:Math.max.apply(null,leftSideBearings),minRightSideBearing:Math.min.apply(null,rightSideBearings)};globals.ascender=font.ascender;globals.descender=font.descender;var headTable=head.make({flags:3,// 00000011 (baseline for font at y=0; left sidebearing point at x=0) unitsPerEm:font.unitsPerEm,xMin:globals.xMin,yMin:globals.yMin,xMax:globals.xMax,yMax:globals.yMax,lowestRecPPEM:3,createdTimestamp:font.createdTimestamp});var hheaTable=hhea.make({ascender:globals.ascender,descender:globals.descender,advanceWidthMax:globals.advanceWidthMax,minLeftSideBearing:globals.minLeftSideBearing,minRightSideBearing:globals.minRightSideBearing,xMaxExtent:globals.maxLeftSideBearing+(globals.xMax-globals.xMin),numberOfHMetrics:font.glyphs.length});var maxpTable=maxp.make(font.glyphs.length);var os2Table=os2.make({xAvgCharWidth:Math.round(globals.advanceWidthAvg),usWeightClass:font.tables.os2.usWeightClass,usWidthClass:font.tables.os2.usWidthClass,usFirstCharIndex:firstCharIndex,usLastCharIndex:lastCharIndex,ulUnicodeRange1:ulUnicodeRange1,ulUnicodeRange2:ulUnicodeRange2,ulUnicodeRange3:ulUnicodeRange3,ulUnicodeRange4:ulUnicodeRange4,fsSelection:font.tables.os2.fsSelection,// REGULAR // See http://typophile.com/node/13081 for more info on vertical metrics. // We get metrics for typical characters (such as "x" for xHeight). // We provide some fallback characters if characters are unavailable: their // ordering was chosen experimentally. sTypoAscender:globals.ascender,sTypoDescender:globals.descender,sTypoLineGap:0,usWinAscent:globals.yMax,usWinDescent:Math.abs(globals.yMin),ulCodePageRange1:1,// FIXME: hard-code Latin 1 support for now sxHeight:metricsForChar(font,'xyvw',{yMax:Math.round(globals.ascender/2)}).yMax,sCapHeight:metricsForChar(font,'HIKLEFJMNTZBDPRAGOQSUVWXY',globals).yMax,usDefaultChar:font.hasChar(' ')?32:0,// Use space as the default character, if available. usBreakChar:font.hasChar(' ')?32:0// Use space as the break character, if available. });var hmtxTable=hmtx.make(font.glyphs);var cmapTable=cmap.make(font.glyphs);var englishFamilyName=font.getEnglishName('fontFamily');var englishStyleName=font.getEnglishName('fontSubfamily');var englishFullName=englishFamilyName+' '+englishStyleName;var postScriptName=font.getEnglishName('postScriptName');if(!postScriptName){postScriptName=englishFamilyName.replace(/\s/g,'')+'-'+englishStyleName;}var names={};for(var n in font.names){names[n]=font.names[n];}if(!names.uniqueID){names.uniqueID={en:font.getEnglishName('manufacturer')+':'+englishFullName};}if(!names.postScriptName){names.postScriptName={en:postScriptName};}if(!names.preferredFamily){names.preferredFamily=font.names.fontFamily;}if(!names.preferredSubfamily){names.preferredSubfamily=font.names.fontSubfamily;}var languageTags=[];var nameTable=_name.make(names,languageTags);var ltagTable=languageTags.length>0?ltag.make(languageTags):undefined;var postTable=post.make();var cffTable=cff.make(font.glyphs,{version:font.getEnglishName('version'),fullName:englishFullName,familyName:englishFamilyName,weightName:englishStyleName,postScriptName:postScriptName,unitsPerEm:font.unitsPerEm,fontBBox:[0,globals.yMin,globals.ascender,globals.advanceWidthMax]});var metaTable=font.metas&&Object.keys(font.metas).length>0?meta.make(font.metas):undefined;// The order does not matter because makeSfntTable() will sort them. var tables=[headTable,hheaTable,maxpTable,os2Table,nameTable,cmapTable,postTable,cffTable,hmtxTable];if(ltagTable){tables.push(ltagTable);}// Optional tables if(font.tables.gsub){tables.push(gsub.make(font.tables.gsub));}if(metaTable){tables.push(metaTable);}var sfntTable=makeSfntTable(tables);// Compute the font's checkSum and store it in head.checkSumAdjustment. var bytes=sfntTable.encode();var checkSum=computeCheckSum(bytes);var tableFields=sfntTable.fields;var checkSumAdjusted=false;for(var i$1=0;i$1<tableFields.length;i$1+=1){if(tableFields[i$1].name==='head table'){tableFields[i$1].value.checkSumAdjustment=0xB1B0AFBA-checkSum;checkSumAdjusted=true;break;}}if(!checkSumAdjusted){throw new Error('Could not find head table with checkSum to adjust.');}return sfntTable;}var sfnt={make:makeSfntTable,fontToTable:fontToSfntTable,computeCheckSum:computeCheckSum};// The Layout object is the prototype of Substitution objects, and provides function searchTag(arr,tag){/* jshint bitwise: false */var imin=0;var imax=arr.length-1;while(imin<=imax){var imid=imin+imax>>>1;var val=arr[imid].tag;if(val===tag){return imid;}else if(val<tag){imin=imid+1;}else{imax=imid-1;}}// Not found: return -1-insertion point return-imin-1;}function binSearch(arr,value){/* jshint bitwise: false */var imin=0;var imax=arr.length-1;while(imin<=imax){var imid=imin+imax>>>1;var val=arr[imid];if(val===value){return imid;}else if(val<value){imin=imid+1;}else{imax=imid-1;}}// Not found: return -1-insertion point return-imin-1;}// binary search in a list of ranges (coverage, class definition) function searchRange(ranges,value){// jshint bitwise: false var range;var imin=0;var imax=ranges.length-1;while(imin<=imax){var imid=imin+imax>>>1;range=ranges[imid];var start=range.start;if(start===value){return range;}else if(start<value){imin=imid+1;}else{imax=imid-1;}}if(imin>0){range=ranges[imin-1];if(value>range.end){return 0;}return range;}}/** * @exports opentype.Layout * @class */function Layout(font,tableName){this.font=font;this.tableName=tableName;}Layout.prototype={/** * Binary search an object by "tag" property * @instance * @function searchTag * @memberof opentype.Layout * @param {Array} arr * @param {string} tag * @return {number} */searchTag:searchTag,/** * Binary search in a list of numbers * @instance * @function binSearch * @memberof opentype.Layout * @param {Array} arr * @param {number} value * @return {number} */binSearch:binSearch,/** * Get or create the Layout table (GSUB, GPOS etc). * @param {boolean} create - Whether to create a new one. * @return {Object} The GSUB or GPOS table. */getTable:function getTable(create){var layout=this.font.tables[this.tableName];if(!layout&&create){layout=this.font.tables[this.tableName]=this.createDefaultTable();}return layout;},/** * Returns all scripts in the substitution table. * @instance * @return {Array} */getScriptNames:function getScriptNames(){var layout=this.getTable();if(!layout){return[];}return layout.scripts.map(function(script){return script.tag;});},/** * Returns the best bet for a script name. * Returns 'DFLT' if it exists. * If not, returns 'latn' if it exists. * If neither exist, returns undefined. */getDefaultScriptName:function getDefaultScriptName(){var layout=this.getTable();if(!layout){return;}var hasLatn=false;for(var i=0;i<layout.scripts.length;i++){var name=layout.scripts[i].tag;if(name==='DFLT'){return name;}if(name==='latn'){hasLatn=true;}}if(hasLatn){return'latn';}},/** * Returns all LangSysRecords in the given script. * @instance * @param {string} [script='DFLT'] * @param {boolean} create - forces the creation of this script table if it doesn't exist. * @return {Object} An object with tag and script properties. */getScriptTable:function getScriptTable(script,create){var layout=this.getTable(create);if(layout){script=script||'DFLT';var scripts=layout.scripts;var pos=searchTag(layout.scripts,script);if(pos>=0){return scripts[pos].script;}else if(create){var scr={tag:script,script:{defaultLangSys:{reserved:0,reqFeatureIndex:0xffff,featureIndexes:[]},langSysRecords:[]}};scripts.splice(-1-pos,0,scr);return scr.script;}}},/** * Returns a language system table * @instance * @param {string} [script='DFLT'] * @param {string} [language='dlft'] * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist. * @return {Object} */getLangSysTable:function getLangSysTable(script,language,create){var scriptTable=this.getScriptTable(script,create);if(scriptTable){if(!language||language==='dflt'||language==='DFLT'){return scriptTable.defaultLangSys;}var pos=searchTag(scriptTable.langSysRecords,language);if(pos>=0){return scriptTable.langSysRecords[pos].langSys;}else if(create){var langSysRecord={tag:language,langSys:{reserved:0,reqFeatureIndex:0xffff,featureIndexes:[]}};scriptTable.langSysRecords.splice(-1-pos,0,langSysRecord);return langSysRecord.langSys;}}},/** * Get a specific feature table. * @instance * @param {string} [script='DFLT'] * @param {string} [language='dlft'] * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm * @param {boolean} create - forces the creation of the feature table if it doesn't exist. * @return {Object} */getFeatureTable:function getFeatureTable(script,language,feature,create){var langSysTable=this.getLangSysTable(script,language,create);if(langSysTable){var featureRecord;var featIndexes=langSysTable.featureIndexes;var allFeatures=this.font.tables[this.tableName].features;// The FeatureIndex array of indices is in arbitrary order, // even if allFeatures is sorted alphabetically by feature tag. for(var i=0;i<featIndexes.length;i++){featureRecord=allFeatures[featIndexes[i]];if(featureRecord.tag===feature){return featureRecord.feature;}}if(create){var index=allFeatures.length;// Automatic ordering of features would require to shift feature indexes in the script list. check.assert(index===0||feature>=allFeatures[index-1].tag,'Features must be added in alphabetical order.');featureRecord={tag:feature,feature:{params:0,lookupListIndexes:[]}};allFeatures.push(featureRecord);featIndexes.push(index);return featureRecord.feature;}}},/** * Get the lookup tables of a given type for a script/language/feature. * @instance * @param {string} [script='DFLT'] * @param {string} [language='dlft'] * @param {string} feature - 4-letter feature code * @param {number} lookupType - 1 to 9 * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables. * @return {Object[]} */getLookupTables:function getLookupTables(script,language,feature,lookupType,create){var featureTable=this.getFeatureTable(script,language,feature,create);var tables=[];if(featureTable){var lookupTable;var lookupListIndexes=featureTable.lookupListIndexes;var allLookups=this.font.tables[this.tableName].lookups;// lookupListIndexes are in no particular order, so use naive search. for(var i=0;i<lookupListIndexes.length;i++){lookupTable=allLookups[lookupListIndexes[i]];if(lookupTable.lookupType===lookupType){tables.push(lookupTable);}}if(tables.length===0&&create){lookupTable={lookupType:lookupType,lookupFlag:0,subtables:[],markFilteringSet:undefined};var index=allLookups.length;allLookups.push(lookupTable);lookupListIndexes.push(index);return[lookupTable];}}return tables;},/** * Find a glyph in a class definition table * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table * @param {object} classDefTable - an OpenType Layout class definition table * @param {number} glyphIndex - the index of the glyph to find * @returns {number} -1 if not found */getGlyphClass:function getGlyphClass(classDefTable,glyphIndex){switch(classDefTable.format){case 1:if(classDefTable.startGlyph<=glyphIndex&&glyphIndex<classDefTable.startGlyph+classDefTable.classes.length){return classDefTable.classes[glyphIndex-classDefTable.startGlyph];}return 0;case 2:var range=searchRange(classDefTable.ranges,glyphIndex);return range?range.classId:0;}},/** * Find a glyph in a coverage table * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-table * @param {object} coverageTable - an OpenType Layout coverage table * @param {number} glyphIndex - the index of the glyph to find * @returns {number} -1 if not found */getCoverageIndex:function getCoverageIndex(coverageTable,glyphIndex){switch(coverageTable.format){case 1:var index=binSearch(coverageTable.glyphs,glyphIndex);return index>=0?index:-1;case 2:var range=searchRange(coverageTable.ranges,glyphIndex);return range?range.index+glyphIndex-range.start:-1;}},/** * Returns the list of glyph indexes of a coverage table. * Format 1: the list is stored raw * Format 2: compact list as range records. * @instance * @param {Object} coverageTable * @return {Array} */expandCoverage:function expandCoverage(coverageTable){if(coverageTable.format===1){return coverageTable.glyphs;}else{var glyphs=[];var ranges=coverageTable.ranges;for(var i=0;i<ranges.length;i++){var range=ranges[i];var start=range.start;var end=range.end;for(var j=start;j<=end;j++){glyphs.push(j);}}return glyphs;}}};// The Position object provides utility methods to manipulate /** * @exports opentype.Position * @class * @extends opentype.Layout * @param {opentype.Font} * @constructor */function Position(font){Layout.call(this,font,'gpos');}Position.prototype=Layout.prototype;/** * Init some data for faster and easier access later. */Position.prototype.init=function(){var script=this.getDefaultScriptName();this.defaultKerningTables=this.getKerningTables(script);};/** * Find a glyph pair in a list of lookup tables of type 2 and retrieve the xAdvance kerning value. * * @param {integer} leftIndex - left glyph index * @param {integer} rightIndex - right glyph index * @returns {integer} */Position.prototype.getKerningValue=function(kerningLookups,leftIndex,rightIndex){var this$1=this;for(var i=0;i<kerningLookups.length;i++){var subtables=kerningLookups[i].subtables;for(var j=0;j<subtables.length;j++){var subtable=subtables[j];var covIndex=this$1.getCoverageIndex(subtable.coverage,leftIndex);if(covIndex<0){continue;}switch(subtable.posFormat){case 1:// Search Pair Adjustment Positioning Format 1 var pairSet=subtable.pairSets[covIndex];for(var k=0;k<pairSet.length;k++){var pair=pairSet[k];if(pair.secondGlyph===rightIndex){return pair.value1&&pair.value1.xAdvance||0;}}break;// left glyph found, not right glyph - try next subtable case 2:// Search Pair Adjustment Positioning Format 2 var class1=this$1.getGlyphClass(subtable.classDef1,leftIndex);var class2=this$1.getGlyphClass(subtable.classDef2,rightIndex);var pair$1=subtable.classRecords[class1][class2];return pair$1.value1&&pair$1.value1.xAdvance||0;}}}return 0;};/** * List all kerning lookup tables. * * @param {string} [script='DFLT'] - use font.position.getDefaultScriptName() for a better default value * @param {string} [language='dflt'] * @return {object[]} The list of kerning lookup tables (may be empty), or undefined if there is no GPOS table (and we should use the kern table) */Position.prototype.getKerningTables=function(script,language){if(this.font.tables.gpos){return this.getLookupTables(script,language,'kern',2);}};// The Substitution object provides utility methods to manipulate /** * @exports opentype.Substitution * @class * @extends opentype.Layout * @param {opentype.Font} * @constructor */function Substitution(font){Layout.call(this,font,'gsub');}// Check if 2 arrays of primitives are equal. function arraysEqual(ar1,ar2){var n=ar1.length;if(n!==ar2.length){return false;}for(var i=0;i<n;i++){if(ar1[i]!==ar2[i]){return false;}}return true;}// Find the first subtable of a lookup table in a particular format. function getSubstFormat(lookupTable,format,defaultSubtable){var subtables=lookupTable.subtables;for(var i=0;i<subtables.length;i++){var subtable=subtables[i];if(subtable.substFormat===format){return subtable;}}if(defaultSubtable){subtables.push(defaultSubtable);return defaultSubtable;}return undefined;}Substitution.prototype=Layout.prototype;/** * Create a default GSUB table. * @return {Object} gsub - The GSUB table. */Substitution.prototype.createDefaultTable=function(){// Generate a default empty GSUB table with just a DFLT script and dflt lang sys. return{version:1,scripts:[{tag:'DFLT',script:{defaultLangSys:{reserved:0,reqFeatureIndex:0xffff,featureIndexes:[]},langSysRecords:[]}}],features:[],lookups:[]};};/** * List all single substitutions (lookup type 1) for a given script, language, and feature. * @param {string} [script='DFLT'] * @param {string} [language='dflt'] * @param {string} feature - 4-character feature name ('aalt', 'salt', 'ss01'...) * @return {Array} substitutions - The list of substitutions. */Substitution.prototype.getSingle=function(feature,script,language){var this$1=this;var substitutions=[];var lookupTables=this.getLookupTables(script,language,feature,1);for(var idx=0;idx<lookupTables.length;idx++){var subtables=lookupTables[idx].subtables;for(var i=0;i<subtables.length;i++){var subtable=subtables[i];var glyphs=this$1.expandCoverage(subtable.coverage);var j=void 0;if(subtable.substFormat===1){var delta=subtable.deltaGlyphId;for(j=0;j<glyphs.length;j++){var glyph=glyphs[j];substitutions.push({sub:glyph,by:glyph+delta});}}else{var substitute=subtable.substitute;for(j=0;j<glyphs.length;j++){substitutions.push({sub:glyphs[j],by:substitute[j]});}}}}return substitutions;};/** * List all alternates (lookup type 3) for a given script, language, and feature. * @param {string} [script='DFLT'] * @param {string} [language='dflt'] * @param {string} feature - 4-character feature name ('aalt', 'salt'...) * @return {Array} alternates - The list of alternates */Substitution.prototype.getAlternates=function(feature,script,language){var this$1=this;var alternates=[];var lookupTables=this.getLookupTables(script,language,feature,3);for(var idx=0;idx<lookupTables.length;idx++){var subtables=lookupTables[idx].subtables;for(var i=0;i<subtables.length;i++){var subtable=subtables[i];var glyphs=this$1.expandCoverage(subtable.coverage);var alternateSets=subtable.alternateSets;for(var j=0;j<glyphs.length;j++){alternates.push({sub:glyphs[j],by:alternateSets[j]});}}}return alternates;};/** * List all ligatures (lookup type 4) for a given script, language, and feature. * The result is an array of ligature objects like { sub: [ids], by: id } * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {string} [script='DFLT'] * @param {string} [language='dflt'] * @return {Array} ligatures - The list of ligatures. */Substitution.prototype.getLigatures=function(feature,script,language){var this$1=this;var ligatures=[];var lookupTables=this.getLookupTables(script,language,feature,4);for(var idx=0;idx<lookupTables.length;idx++){var subtables=lookupTables[idx].subtables;for(var i=0;i<subtables.length;i++){var subtable=subtables[i];var glyphs=this$1.expandCoverage(subtable.coverage);var ligatureSets=subtable.ligatureSets;for(var j=0;j<glyphs.length;j++){var startGlyph=glyphs[j];var ligSet=ligatureSets[j];for(var k=0;k<ligSet.length;k++){var lig=ligSet[k];ligatures.push({sub:[startGlyph].concat(lig.components),by:lig.ligGlyph});}}}}return ligatures;};/** * Add or modify a single substitution (lookup type 1) * Format 2, more flexible, is always used. * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {Object} substitution - { sub: id, delta: number } for format 1 or { sub: id, by: id } for format 2. * @param {string} [script='DFLT'] * @param {string} [language='dflt'] */Substitution.prototype.addSingle=function(feature,substitution,script,language){var lookupTable=this.getLookupTables(script,language,feature,1,true)[0];var subtable=getSubstFormat(lookupTable,2,{// lookup type 1 subtable, format 2, coverage format 1 substFormat:2,coverage:{format:1,glyphs:[]},substitute:[]});check.assert(subtable.coverage.format===1,'Ligature: unable to modify coverage table format '+subtable.coverage.format);var coverageGlyph=substitution.sub;var pos=this.binSearch(subtable.coverage.glyphs,coverageGlyph);if(pos<0){pos=-1-pos;subtable.coverage.glyphs.splice(pos,0,coverageGlyph);subtable.substitute.splice(pos,0,0);}subtable.substitute[pos]=substitution.by;};/** * Add or modify an alternate substitution (lookup type 1) * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {Object} substitution - { sub: id, by: [ids] } * @param {string} [script='DFLT'] * @param {string} [language='dflt'] */Substitution.prototype.addAlternate=function(feature,substitution,script,language){var lookupTable=this.getLookupTables(script,language,feature,3,true)[0];var subtable=getSubstFormat(lookupTable,1,{// lookup type 3 subtable, format 1, coverage format 1 substFormat:1,coverage:{format:1,glyphs:[]},alternateSets:[]});check.assert(subtable.coverage.format===1,'Ligature: unable to modify coverage table format '+subtable.coverage.format);var coverageGlyph=substitution.sub;var pos=this.binSearch(subtable.coverage.glyphs,coverageGlyph);if(pos<0){pos=-1-pos;subtable.coverage.glyphs.splice(pos,0,coverageGlyph);subtable.alternateSets.splice(pos,0,0);}subtable.alternateSets[pos]=substitution.by;};/** * Add a ligature (lookup type 4) * Ligatures with more components must be stored ahead of those with fewer components in order to be found * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) * @param {Object} ligature - { sub: [ids], by: id } * @param {string} [script='DFLT'] * @param {string} [language='dflt'] */Substitution.prototype.addLigature=function(feature,ligature,script,language){var lookupTable=this.getLookupTables(script,language,feature,4,true)[0];var subtable=lookupTable.subtables[0];if(!subtable){subtable={// lookup type 4 subtable, format 1, coverage format 1 substFormat:1,coverage:{format:1,glyphs:[]},ligatureSets:[]};lookupTable.subtables[0]=subtable;}check.assert(subtable.coverage.format===1,'Ligature: unable to modify coverage table format '+subtable.coverage.format);var coverageGlyph=ligature.sub[0];var ligComponents=ligature.sub.slice(1);var ligatureTable={ligGlyph:ligature.by,components:ligComponents};var pos=this.binSearch(subtable.coverage.glyphs,coverageGlyph);if(pos>=0){// ligatureSet already exists var ligatureSet=subtable.ligatureSets[pos];for(var i=0;i<ligatureSet.length;i++){// If ligature already exists, return. if(arraysEqual(ligatureSet[i].components,ligComponents)){return;}}// ligature does not exist: add it. ligatureSet.push(ligatureTable);}else{// Create a new ligatureSet and add coverage for the first glyph. pos=-1-pos;subtable.coverage.glyphs.splice(pos,0,coverageGlyph);subtable.ligatureSets.splice(pos,0,[ligatureTable]);}};/** * List all feature data for a given script and language. * @param {string} feature - 4-letter feature name * @param {string} [script='DFLT'] * @param {string} [language='dflt'] * @return {Array} substitutions - The list of substitutions. */Substitution.prototype.getFeature=function(feature,script,language){if(/ss\d\d/.test(feature)){// ss01 - ss20 return this.getSingle(feature,script,language);}switch(feature){case'aalt':case'salt':return this.getSingle(feature,script,language).concat(this.getAlternates(feature,script,language));case'dlig':case'liga':case'rlig':return this.getLigatures(feature,script,language);}return undefined;};/** * Add a substitution to a feature for a given script and language. * @param {string} feature - 4-letter feature name * @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] }) * @param {string} [script='DFLT'] * @param {string} [language='dflt'] */Substitution.prototype.add=function(feature,sub,script,language){if(/ss\d\d/.test(feature)){// ss01 - ss20 return this.addSingle(feature,sub,script,language);}switch(feature){case'aalt':case'salt':if(typeof sub.by==='number'){return this.addSingle(feature,sub,script,language);}return this.addAlternate(feature,sub,script,language);case'dlig':case'liga':case'rlig':return this.addLigature(feature,sub,script,language);}return undefined;};function isBrowser(){return typeof window!=='undefined';}function nodeBufferToArrayBuffer(buffer){var ab=new ArrayBuffer(buffer.length);var view=new Uint8Array(ab);for(var i=0;i<buffer.length;++i){view[i]=buffer[i];}return ab;}function arrayBufferToNodeBuffer(ab){var buffer=new Buffer(ab.byteLength);var view=new Uint8Array(ab);for(var i=0;i<buffer.length;++i){buffer[i]=view[i];}return buffer;}function checkArgument(expression,message){if(!expression){throw message;}}// The `glyf` table describes the glyphs in TrueType outline format. // Parse the coordinate data for a glyph. function parseGlyphCoordinate(p,flag,previousValue,shortVectorBitMask,sameBitMask){var v;if((flag&shortVectorBitMask)>0){// The coordinate is 1 byte long. v=p.parseByte();// The `same` bit is re-used for short values to signify the sign of the value. if((flag&sameBitMask)===0){v=-v;}v=previousValue+v;}else{// The coordinate is 2 bytes long. // If the `same` bit is set, the coordinate is the same as the previous coordinate. if((flag&sameBitMask)>0){v=previousValue;}else{// Parse the coordinate as a signed 16-bit delta value. v=previousValue+p.parseShort();}}return v;}// Parse a TrueType glyph. function parseGlyph(glyph,data,start){var p=new parse.Parser(data,start);glyph.numberOfContours=p.parseShort();glyph._xMin=p.parseShort();glyph._yMin=p.parseShort();glyph._xMax=p.parseShort();glyph._yMax=p.parseShort();var flags;var flag;if(glyph.numberOfContours>0){// This glyph is not a composite. var endPointIndices=glyph.endPointIndices=[];for(var i=0;i<glyph.numberOfContours;i+=1){endPointIndices.push(p.parseUShort());}glyph.instructionLength=p.parseUShort();glyph.instructions=[];for(var i$1=0;i$1<glyph.instructionLength;i$1+=1){glyph.instructions.push(p.parseByte());}var numberOfCoordinates=endPointIndices[endPointIndices.length-1]+1;flags=[];for(var i$2=0;i$2<numberOfCoordinates;i$2+=1){flag=p.parseByte();flags.push(flag);// If bit 3 is set, we repeat this flag n times, where n is the next byte. if((flag&8)>0){var repeatCount=p.parseByte();for(var j=0;j<repeatCount;j+=1){flags.push(flag);i$2+=1;}}}check.argument(flags.length===numberOfCoordinates,'Bad flags.');if(endPointIndices.length>0){var points=[];var point;// X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0. if(numberOfCoordinates>0){for(var i$3=0;i$3<numberOfCoordinates;i$3+=1){flag=flags[i$3];point={};point.onCurve=!!(flag&1);point.lastPointOfContour=endPointIndices.indexOf(i$3)>=0;points.push(point);}var px=0;for(var i$4=0;i$4<numberOfCoordinates;i$4+=1){flag=flags[i$4];point=points[i$4];point.x=parseGlyphCoordinate(p,flag,px,2,16);px=point.x;}var py=0;for(var i$5=0;i$5<numberOfCoordinates;i$5+=1){flag=flags[i$5];point=points[i$5];point.y=parseGlyphCoordinate(p,flag,py,4,32);py=point.y;}}glyph.points=points;}else{glyph.points=[];}}else if(glyph.numberOfContours===0){glyph.points=[];}else{glyph.isComposite=true;glyph.points=[];glyph.components=[];var moreComponents=true;while(moreComponents){flags=p.parseUShort();var component={glyphIndex:p.parseUShort(),xScale:1,scale01:0,scale10:0,yScale:1,dx:0,dy:0};if((flags&1)>0){// The arguments are words if((flags&2)>0){// values are offset component.dx=p.parseShort();component.dy=p.parseShort();}else{// values are matched points component.matchedPoints=[p.parseUShort(),p.parseUShort()];}}else{// The arguments are bytes if((flags&2)>0){// values are offset component.dx=p.parseChar();component.dy=p.parseChar();}else{// values are matched points component.matchedPoints=[p.parseByte(),p.parseByte()];}}if((flags&8)>0){// We have a scale component.xScale=component.yScale=p.parseF2Dot14();}else if((flags&64)>0){// We have an X / Y scale component.xScale=p.parseF2Dot14();component.yScale=p.parseF2Dot14();}else if((flags&128)>0){// We have a 2x2 transformation component.xScale=p.parseF2Dot14();component.scale01=p.parseF2Dot14();component.scale10=p.parseF2Dot14();component.yScale=p.parseF2Dot14();}glyph.components.push(component);moreComponents=!!(flags&32);}if(flags&0x100){// We have instructions glyph.instructionLength=p.parseUShort();glyph.instructions=[];for(var i$6=0;i$6<glyph.instructionLength;i$6+=1){glyph.instructions.push(p.parseByte());}}}}// Transform an array of points and return a new array. function transformPoints(points,transform){var newPoints=[];for(var i=0;i<points.length;i+=1){var pt=points[i];var newPt={x:transform.xScale*pt.x+transform.scale01*pt.y+transform.dx,y:transform.scale10*pt.x+transform.yScale*pt.y+transform.dy,onCurve:pt.onCurve,lastPointOfContour:pt.lastPointOfContour};newPoints.push(newPt);}return newPoints;}function getContours(points){var contours=[];var currentContour=[];for(var i=0;i<points.length;i+=1){var pt=points[i];currentContour.push(pt);if(pt.lastPointOfContour){contours.push(currentContour);currentContour=[];}}check.argument(currentContour.length===0,'There are still points left in the current contour.');return contours;}// Convert the TrueType glyph outline to a Path. function getPath(points){var p=new Path();if(!points){return p;}var contours=getContours(points);for(var contourIndex=0;contourIndex<contours.length;++contourIndex){var contour=contours[contourIndex];var prev=null;var curr=contour[contour.length-1];var next=contour[0];if(curr.onCurve){p.moveTo(curr.x,curr.y);}else{if(next.onCurve){p.moveTo(next.x,next.y);}else{// If both first and last points are off-curve, start at their middle. var start={x:(curr.x+next.x)*0.5,y:(curr.y+next.y)*0.5};p.moveTo(start.x,start.y);}}for(var i=0;i<contour.length;++i){prev=curr;curr=next;next=contour[(i+1)%contour.length];if(curr.onCurve){// This is a straight line. p.lineTo(curr.x,curr.y);}else{var prev2=prev;var next2=next;if(!prev.onCurve){prev2={x:(curr.x+prev.x)*0.5,y:(curr.y+prev.y)*0.5};}if(!next.onCurve){next2={x:(curr.x+next.x)*0.5,y:(curr.y+next.y)*0.5};}p.quadraticCurveTo(curr.x,curr.y,next2.x,next2.y);}}p.closePath();}return p;}function buildPath(glyphs,glyph){if(glyph.isComposite){for(var j=0;j<glyph.components.length;j+=1){var component=glyph.components[j];var componentGlyph=glyphs.get(component.glyphIndex);// Force the ttfGlyphLoader to parse the glyph. componentGlyph.getPath();if(componentGlyph.points){var transformedPoints=void 0;if(component.matchedPoints===undefined){// component positioned by offset transformedPoints=transformPoints(componentGlyph.points,component);}else{// component positioned by matched points if(component.matchedPoints[0]>glyph.points.length-1||component.matchedPoints[1]>componentGlyph.points.length-1){throw Error('Matched points out of range in '+glyph.name);}var firstPt=glyph.points[component.matchedPoints[0]];var secondPt=componentGlyph.points[component.matchedPoints[1]];var transform={xScale:component.xScale,scale01:component.scale01,scale10:component.scale10,yScale:component.yScale,dx:0,dy:0};secondPt=transformPoints([secondPt],transform)[0];transform.dx=firstPt.x-secondPt.x;transform.dy=firstPt.y-secondPt.y;transformedPoints=transformPoints(componentGlyph.points,transform);}glyph.points=glyph.points.concat(transformedPoints);}}}return getPath(glyph.points);}// Parse all the glyphs according to the offsets from the `loca` table. function parseGlyfTable(data,start,loca,font){var glyphs=new glyphset.GlyphSet(font);// The last element of the loca table is invalid. for(var i=0;i<loca.length-1;i+=1){var offset=loca[i];var nextOffset=loca[i+1];if(offset!==nextOffset){glyphs.push(i,glyphset.ttfGlyphLoader(font,i,parseGlyph,data,start+offset,buildPath));}else{glyphs.push(i,glyphset.glyphLoader(font,i));}}return glyphs;}var glyf={getPath:getPath,parse:parseGlyfTable};/* A TrueType font hinting interpreter. * * (c) 2017 Axel Kittenberger * * This interpreter has been implemented according to this documentation: * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html * * According to the documentation F24DOT6 values are used for pixels. * That means calculation is 1/64 pixel accurate and uses integer operations. * However, Javascript has floating point operations by default and only * those are available. One could make a case to simulate the 1/64 accuracy * exactly by truncating after every division operation * (for example with << 0) to get pixel exactly results as other TrueType * implementations. It may make sense since some fonts are pixel optimized * by hand using DELTAP instructions. The current implementation doesn't * and rather uses full floating point precision. * * xScale, yScale and rotation is currently ignored. * * A few non-trivial instructions are missing as I didn't encounter yet * a font that used them to test a possible implementation. * * Some fonts seem to use undocumented features regarding the twilight zone. * Only some of them are implemented as they were encountered. * * The exports.DEBUG statements are removed on the minified distribution file. */var instructionTable;var exec;var execGlyph;var execComponent;/* * Creates a hinting object. * * There ought to be exactly one * for each truetype font that is used for hinting. */function Hinting(font){// the font this hinting object is for this.font=font;this.getCommands=function(hPoints){return glyf.getPath(hPoints).commands;};// cached states this._fpgmState=this._prepState=undefined;// errorState // 0 ... all okay // 1 ... had an error in a glyf, // continue working but stop spamming // the console // 2 ... error at prep, stop hinting at this ppem // 3 ... error at fpeg, stop hinting for this font at all this._errorState=0;}/* * Not rounding. */function roundOff(v){return v;}/* * Rounding to grid. */function roundToGrid(v){//Rounding in TT is supposed to "symmetrical around zero" return Math.sign(v)*Math.round(Math.abs(v));}/* * Rounding to double grid. */function roundToDoubleGrid(v){return Math.sign(v)*Math.round(Math.abs(v*2))/2;}/* * Rounding to half grid. */function roundToHalfGrid(v){return Math.sign(v)*(Math.round(Math.abs(v)+0.5)-0.5);}/* * Rounding to up to grid. */function roundUpToGrid(v){return Math.sign(v)*Math.ceil(Math.abs(v));}/* * Rounding to down to grid. */function roundDownToGrid(v){return Math.sign(v)*Math.floor(Math.abs(v));}/* * Super rounding. */var roundSuper=function roundSuper(v){var period=this.srPeriod;var phase=this.srPhase;var threshold=this.srThreshold;var sign=1;if(v<0){v=-v;sign=-1;}v+=threshold-phase;v=Math.trunc(v/period)*period;v+=phase;// according to http://xgridfit.sourceforge.net/round.html if(v<0){return phase*sign;}return v*sign;};/* * Unit vector of x-axis. */var xUnitVector={x:1,y:0,axis:'x',// Gets the projected distance between two points. // o1/o2 ... if true, respective original position is used. distance:function distance(p1,p2,o1,o2){return(o1?p1.xo:p1.x)-(o2?p2.xo:p2.x);},// Moves point p so the moved position has the same relative // position to the moved positions of rp1 and rp2 than the // original positions had. // // See APPENDIX on INTERPOLATE at the bottom of this file. interpolate:function interpolate(p,rp1,rp2,pv){var do1;var do2;var doa1;var doa2;var dm1;var dm2;var dt;if(!pv||pv===this){do1=p.xo-rp1.xo;do2=p.xo-rp2.xo;dm1=rp1.x-rp1.xo;dm2=rp2.x-rp2.xo;doa1=Math.abs(do1);doa2=Math.abs(do2);dt=doa1+doa2;if(dt===0){p.x=p.xo+(dm1+dm2)/2;return;}p.x=p.xo+(dm1*doa2+dm2*doa1)/dt;return;}do1=pv.distance(p,rp1,true,true);do2=pv.distance(p,rp2,true,true);dm1=pv.distance(rp1,rp1,false,true);dm2=pv.distance(rp2,rp2,false,true);doa1=Math.abs(do1);doa2=Math.abs(do2);dt=doa1+doa2;if(dt===0){xUnitVector.setRelative(p,p,(dm1+dm2)/2,pv,true);return;}xUnitVector.setRelative(p,p,(dm1*doa2+dm2*doa1)/dt,pv,true);},// Slope of line normal to this normalSlope:Number.NEGATIVE_INFINITY,// Sets the point 'p' relative to point 'rp' // by the distance 'd'. // // See APPENDIX on SETRELATIVE at the bottom of this file. // // p ... point to set // rp ... reference point // d ... distance on projection vector // pv ... projection vector (undefined = this) // org ... if true, uses the original position of rp as reference. setRelative:function setRelative(p,rp,d,pv,org){if(!pv||pv===this){p.x=(org?rp.xo:rp.x)+d;return;}var rpx=org?rp.xo:rp.x;var rpy=org?rp.yo:rp.y;var rpdx=rpx+d*pv.x;var rpdy=rpy+d*pv.y;p.x=rpdx+(p.y-rpdy)/pv.normalSlope;},// Slope of vector line. slope:0,// Touches the point p. touch:function touch(p){p.xTouched=true;},// Tests if a point p is touched. touched:function touched(p){return p.xTouched;},// Untouches the point p. untouch:function untouch(p){p.xTouched=false;}};/* * Unit vector of y-axis. */var yUnitVector={x:0,y:1,axis:'y',// Gets the projected distance between two points. // o1/o2 ... if true, respective original position is used. distance:function distance(p1,p2,o1,o2){return(o1?p1.yo:p1.y)-(o2?p2.yo:p2.y);},// Moves point p so the moved position has the same relative // position to the moved positions of rp1 and rp2 than the // original positions had. // // See APPENDIX on INTERPOLATE at the bottom of this file. interpolate:function interpolate(p,rp1,rp2,pv){var do1;var do2;var doa1;var doa2;var dm1;var dm2;var dt;if(!pv||pv===this){do1=p.yo-rp1.yo;do2=p.yo-rp2.yo;dm1=rp1.y-rp1.yo;dm2=rp2.y-rp2.yo;doa1=Math.abs(do1);doa2=Math.abs(do2);dt=doa1+doa2;if(dt===0){p.y=p.yo+(dm1+dm2)/2;return;}p.y=p.yo+(dm1*doa2+dm2*doa1)/dt;return;}do1=pv.distance(p,rp1,true,true);do2=pv.distance(p,rp2,true,true);dm1=pv.distance(rp1,rp1,false,true);dm2=pv.distance(rp2,rp2,false,true);doa1=Math.abs(do1);doa2=Math.abs(do2);dt=doa1+doa2;if(dt===0){yUnitVector.setRelative(p,p,(dm1+dm2)/2,pv,true);return;}yUnitVector.setRelative(p,p,(dm1*doa2+dm2*doa1)/dt,pv,true);},// Slope of line normal to this. normalSlope:0,// Sets the point 'p' relative to point 'rp' // by the distance 'd' // // See APPENDIX on SETRELATIVE at the bottom of this file. // // p ... point to set // rp ... reference point // d ... distance on projection vector // pv ... projection vector (undefined = this) // org ... if true, uses the original position of rp as reference. setRelative:function setRelative(p,rp,d,pv,org){if(!pv||pv===this){p.y=(org?rp.yo:rp.y)+d;return;}var rpx=org?rp.xo:rp.x;var rpy=org?rp.yo:rp.y;var rpdx=rpx+d*pv.x;var rpdy=rpy+d*pv.y;p.y=rpdy+pv.normalSlope*(p.x-rpdx);},// Slope of vector line. slope:Number.POSITIVE_INFINITY,// Touches the point p. touch:function touch(p){p.yTouched=true;},// Tests if a point p is touched. touched:function touched(p){return p.yTouched;},// Untouches the point p. untouch:function untouch(p){p.yTouched=false;}};Object.freeze(xUnitVector);Object.freeze(yUnitVector);/* * Creates a unit vector that is not x- or y-axis. */function UnitVector(x,y){this.x=x;this.y=y;this.axis=undefined;this.slope=y/x;this.normalSlope=-x/y;Object.freeze(this);}/* * Gets the projected distance between two points. * o1/o2 ... if true, respective original position is used. */UnitVector.prototype.distance=function(p1,p2,o1,o2){return this.x*xUnitVector.distance(p1,p2,o1,o2)+this.y*yUnitVector.distance(p1,p2,o1,o2);};/* * Moves point p so the moved position has the same relative * position to the moved positions of rp1 and rp2 than the * original positions had. * * See APPENDIX on INTERPOLATE at the bottom of this file. */UnitVector.prototype.interpolate=function(p,rp1,rp2,pv){var dm1;var dm2;var do1;var do2;var doa1;var doa2;var dt;do1=pv.distance(p,rp1,true,true);do2=pv.distance(p,rp2,true,true);dm1=pv.distance(rp1,rp1,false,true);dm2=pv.distance(rp2,rp2,false,true);doa1=Math.abs(do1);doa2=Math.abs(do2);dt=doa1+doa2;if(dt===0){this.setRelative(p,p,(dm1+dm2)/2,pv,true);return;}this.setRelative(p,p,(dm1*doa2+dm2*doa1)/dt,pv,true);};/* * Sets the point 'p' relative to point 'rp' * by the distance 'd' * * See APPENDIX on SETRELATIVE at the bottom of this file. * * p ... point to set * rp ... reference point * d ... distance on projection vector * pv ... projection vector (undefined = this) * org ... if true, uses the original position of rp as reference. */UnitVector.prototype.setRelative=function(p,rp,d,pv,org){pv=pv||this;var rpx=org?rp.xo:rp.x;var rpy=org?rp.yo:rp.y;var rpdx=rpx+d*pv.x;var rpdy=rpy+d*pv.y;var pvns=pv.normalSlope;var fvs=this.slope;var px=p.x;var py=p.y;p.x=(fvs*px-pvns*rpdx+rpdy-py)/(fvs-pvns);p.y=fvs*(p.x-px)+py;};/* * Touches the point p. */UnitVector.prototype.touch=function(p){p.xTouched=true;p.yTouched=true;};/* * Returns a unit vector with x/y coordinates. */function getUnitVector(x,y){var d=Math.sqrt(x*x+y*y);x/=d;y/=d;if(x===1&&y===0){return xUnitVector;}else if(x===0&&y===1){return yUnitVector;}else{return new UnitVector(x,y);}}/* * Creates a point in the hinting engine. */function HPoint(x,y,lastPointOfContour,onCurve){this.x=this.xo=Math.round(x*64)/64;// hinted x value and original x-value this.y=this.yo=Math.round(y*64)/64;// hinted y value and original y-value this.lastPointOfContour=lastPointOfContour;this.onCurve=onCurve;this.prevPointOnContour=undefined;this.nextPointOnContour=undefined;this.xTouched=false;this.yTouched=false;Object.preventExtensions(this);}/* * Returns the next touched point on the contour. * * v ... unit vector to test touch axis. */HPoint.prototype.nextTouched=function(v){var p=this.nextPointOnContour;while(!v.touched(p)&&p!==this){p=p.nextPointOnContour;}return p;};/* * Returns the previous touched point on the contour * * v ... unit vector to test touch axis. */HPoint.prototype.prevTouched=function(v){var p=this.prevPointOnContour;while(!v.touched(p)&&p!==this){p=p.prevPointOnContour;}return p;};/* * The zero point. */var HPZero=Object.freeze(new HPoint(0,0));/* * The default state of the interpreter. * * Note: Freezing the defaultState and then deriving from it * makes the V8 Javascript engine going awkward, * so this is avoided, albeit the defaultState shouldn't * ever change. */var defaultState={cvCutIn:17/16,// control value cut in deltaBase:9,deltaShift:0.125,loop:1,// loops some instructions minDis:1,// minimum distance autoFlip:true};/* * The current state of the interpreter. * * env ... 'fpgm' or 'prep' or 'glyf' * prog ... the program */function State(env,prog){this.env=env;this.stack=[];this.prog=prog;switch(env){case'glyf':this.zp0=this.zp1=this.zp2=1;this.rp0=this.rp1=this.rp2=0;/* fall through */case'prep':this.fv=this.pv=this.dpv=xUnitVector;this.round=roundToGrid;}}/* * Executes a glyph program. * * This does the hinting for each glyph. * * Returns an array of moved points. * * glyph: the glyph to hint * ppem: the size the glyph is rendered for */Hinting.prototype.exec=function(glyph,ppem){if(typeof ppem!=='number'){throw new Error('Point size is not a number!');}// Received a fatal error, don't do any hinting anymore. if(this._errorState>2){return;}var font=this.font;var prepState=this._prepState;if(!prepState||prepState.ppem!==ppem){var fpgmState=this._fpgmState;if(!fpgmState){// Executes the fpgm state. // This is used by fonts to define functions. State.prototype=defaultState;fpgmState=this._fpgmState=new State('fpgm',font.tables.fpgm);fpgmState.funcs=[];fpgmState.font=font;if(exports.DEBUG){console.log('---EXEC FPGM---');fpgmState.step=-1;}try{exec(fpgmState);}catch(e){console.log('Hinting error in FPGM:'+e);this._errorState=3;return;}}// Executes the prep program for this ppem setting. // This is used by fonts to set cvt values // depending on to be rendered font size. State.prototype=fpgmState;prepState=this._prepState=new State('prep',font.tables.prep);prepState.ppem=ppem;// Creates a copy of the cvt table // and scales it to the current ppem setting. var oCvt=font.tables.cvt;if(oCvt){var cvt=prepState.cvt=new Array(oCvt.length);var scale=ppem/font.unitsPerEm;for(var c=0;c<oCvt.length;c++){cvt[c]=oCvt[c]*scale;}}else{prepState.cvt=[];}if(exports.DEBUG){console.log('---EXEC PREP---');prepState.step=-1;}try{exec(prepState);}catch(e){if(this._errorState<2){console.log('Hinting error in PREP:'+e);}this._errorState=2;}}if(this._errorState>1){return;}try{return execGlyph(glyph,prepState);}catch(e){if(this._errorState<1){console.log('Hinting error:'+e);console.log('Note: further hinting errors are silenced');}this._errorState=1;return undefined;}};/* * Executes the hinting program for a glyph. */execGlyph=function execGlyph(glyph,prepState){// original point positions var xScale=prepState.ppem/prepState.font.unitsPerEm;var yScale=xScale;var components=glyph.components;var contours;var gZone;var state;State.prototype=prepState;if(!components){state=new State('glyf',glyph.instructions);if(exports.DEBUG){console.log('---EXEC GLYPH---');state.step=-1;}execComponent(glyph,state,xScale,yScale);gZone=state.gZone;}else{var font=prepState.font;gZone=[];contours=[];for(var i=0;i<components.length;i++){var c=components[i];var cg=font.glyphs.get(c.glyphIndex);state=new State('glyf',cg.instructions);if(exports.DEBUG){console.log('---EXEC COMP '+i+'---');state.step=-1;}execComponent(cg,state,xScale,yScale);// appends the computed points to the result array // post processes the component points var dx=Math.round(c.dx*xScale);var dy=Math.round(c.dy*yScale);var gz=state.gZone;var cc=state.contours;for(var pi=0;pi<gz.length;pi++){var p=gz[pi];p.xTouched=p.yTouched=false;p.xo=p.x=p.x+dx;p.yo=p.y=p.y+dy;}var gLen=gZone.length;gZone.push.apply(gZone,gz);for(var j=0;j<cc.length;j++){contours.push(cc[j]+gLen);}}if(glyph.instructions&&!state.inhibitGridFit){// the composite has instructions on its own state=new State('glyf',glyph.instructions);state.gZone=state.z0=state.z1=state.z2=gZone;state.contours=contours;// note: HPZero cannot be used here, since // the point might be modified gZone.push(new HPoint(0,0),new HPoint(Math.round(glyph.advanceWidth*xScale),0));if(exports.DEBUG){console.log('---EXEC COMPOSITE---');state.step=-1;}exec(state);gZone.length-=2;}}return gZone;};/* * Executes the hinting program for a component of a multi-component glyph * or of the glyph itself for a non-component glyph. */execComponent=function execComponent(glyph,state,xScale,yScale){var points=glyph.points||[];var pLen=points.length;var gZone=state.gZone=state.z0=state.z1=state.z2=[];var contours=state.contours=[];// Scales the original points and // makes copies for the hinted points. var cp;// current point for(var i=0;i<pLen;i++){cp=points[i];gZone[i]=new HPoint(cp.x*xScale,cp.y*yScale,cp.lastPointOfContour,cp.onCurve);}// Chain links the contours. var sp;// start point var np;// next point for(var i$1=0;i$1<pLen;i$1++){cp=gZone[i$1];if(!sp){sp=cp;contours.push(i$1);}if(cp.lastPointOfContour){cp.nextPointOnContour=sp;sp.prevPointOnContour=cp;sp=undefined;}else{np=gZone[i$1+1];cp.nextPointOnContour=np;np.prevPointOnContour=cp;}}if(state.inhibitGridFit){return;}if(exports.DEBUG){console.log('PROCESSING GLYPH',state.stack);for(var i$2=0;i$2<pLen;i$2++){console.log(i$2,gZone[i$2].x,gZone[i$2].y);}}gZone.push(new HPoint(0,0),new HPoint(Math.round(glyph.advanceWidth*xScale),0));exec(state);// Removes the extra points. gZone.length-=2;if(exports.DEBUG){console.log('FINISHED GLYPH',state.stack);for(var i$3=0;i$3<pLen;i$3++){console.log(i$3,gZone[i$3].x,gZone[i$3].y);}}};/* * Executes the program loaded in state. */exec=function exec(state){var prog=state.prog;if(!prog){return;}var pLen=prog.length;var ins;for(state.ip=0;state.ip<pLen;state.ip++){if(exports.DEBUG){state.step++;}ins=instructionTable[prog[state.ip]];if(!ins){throw new Error('unknown instruction: 0x'+Number(prog[state.ip]).toString(16));}ins(state);// very extensive debugging for each step /* if (exports.DEBUG) { var da; if (state.gZone) { da = []; for (let i = 0; i < state.gZone.length; i++) { da.push(i + ' ' + state.gZone[i].x * 64 + ' ' + state.gZone[i].y * 64 + ' ' + (state.gZone[i].xTouched ? 'x' : '') + (state.gZone[i].yTouched ? 'y' : '') ); } console.log('GZ', da); } if (state.tZone) { da = []; for (let i = 0; i < state.tZone.length; i++) { da.push(i + ' ' + state.tZone[i].x * 64 + ' ' + state.tZone[i].y * 64 + ' ' + (state.tZone[i].xTouched ? 'x' : '') + (state.tZone[i].yTouched ? 'y' : '') ); } console.log('TZ', da); } if (state.stack.length > 10) { console.log( state.stack.length, '...', state.stack.slice(state.stack.length - 10) ); } else { console.log(state.stack.length, state.stack); } } */}};/* * Initializes the twilight zone. * * This is only done if a SZPx instruction * refers to the twilight zone. */function initTZone(state){var tZone=state.tZone=new Array(state.gZone.length);// no idea if this is actually correct... for(var i=0;i<tZone.length;i++){tZone[i]=new HPoint(0,0);}}/* * Skips the instruction pointer ahead over an IF/ELSE block. * handleElse .. if true breaks on matching ELSE */function skip(state,handleElse){var prog=state.prog;var ip=state.ip;var nesting=1;var ins;do{ins=prog[++ip];if(ins===0x58)// IF {nesting++;}else if(ins===0x59)// EIF {nesting--;}else if(ins===0x40)// NPUSHB {ip+=prog[ip+1]+1;}else if(ins===0x41)// NPUSHW {ip+=2*prog[ip+1]+1;}else if(ins>=0xB0&&ins<=0xB7)// PUSHB {ip+=ins-0xB0+1;}else if(ins>=0xB8&&ins<=0xBF)// PUSHW {ip+=(ins-0xB8+1)*2;}else if(handleElse&&nesting===1&&ins===0x1B)// ELSE {break;}}while(nesting>0);state.ip=ip;}/*----------------------------------------------------------* * And then a lot of instructions... * *----------------------------------------------------------*/// SVTCA[a] Set freedom and projection Vectors To Coordinate Axis // 0x00-0x01 function SVTCA(v,state){if(exports.DEBUG){console.log(state.step,'SVTCA['+v.axis+']');}state.fv=state.pv=state.dpv=v;}// SPVTCA[a] Set Projection Vector to Coordinate Axis // 0x02-0x03 function SPVTCA(v,state){if(exports.DEBUG){console.log(state.step,'SPVTCA['+v.axis+']');}state.pv=state.dpv=v;}// SFVTCA[a] Set Freedom Vector to Coordinate Axis // 0x04-0x05 function SFVTCA(v,state){if(exports.DEBUG){console.log(state.step,'SFVTCA['+v.axis+']');}state.fv=v;}// SPVTL[a] Set Projection Vector To Line // 0x06-0x07 function SPVTL(a,state){var stack=state.stack;var p2i=stack.pop();var p1i=stack.pop();var p2=state.z2[p2i];var p1=state.z1[p1i];if(exports.DEBUG){console.log('SPVTL['+a+']',p2i,p1i);}var dx;var dy;if(!a){dx=p1.x-p2.x;dy=p1.y-p2.y;}else{dx=p2.y-p1.y;dy=p1.x-p2.x;}state.pv=state.dpv=getUnitVector(dx,dy);}// SFVTL[a] Set Freedom Vector To Line // 0x08-0x09 function SFVTL(a,state){var stack=state.stack;var p2i=stack.pop();var p1i=stack.pop();var p2=state.z2[p2i];var p1=state.z1[p1i];if(exports.DEBUG){console.log('SFVTL['+a+']',p2i,p1i);}var dx;var dy;if(!a){dx=p1.x-p2.x;dy=p1.y-p2.y;}else{dx=p2.y-p1.y;dy=p1.x-p2.x;}state.fv=getUnitVector(dx,dy);}// SPVFS[] Set Projection Vector From Stack // 0x0A function SPVFS(state){var stack=state.stack;var y=stack.pop();var x=stack.pop();if(exports.DEBUG){console.log(state.step,'SPVFS[]',y,x);}state.pv=state.dpv=getUnitVector(x,y);}// SFVFS[] Set Freedom Vector From Stack // 0x0B function SFVFS(state){var stack=state.stack;var y=stack.pop();var x=stack.pop();if(exports.DEBUG){console.log(state.step,'SPVFS[]',y,x);}state.fv=getUnitVector(x,y);}// GPV[] Get Projection Vector // 0x0C function GPV(state){var stack=state.stack;var pv=state.pv;if(exports.DEBUG){console.log(state.step,'GPV[]');}stack.push(pv.x*0x4000);stack.push(pv.y*0x4000);}// GFV[] Get Freedom Vector // 0x0C function GFV(state){var stack=state.stack;var fv=state.fv;if(exports.DEBUG){console.log(state.step,'GFV[]');}stack.push(fv.x*0x4000);stack.push(fv.y*0x4000);}// SFVTPV[] Set Freedom Vector To Projection Vector // 0x0E function SFVTPV(state){state.fv=state.pv;if(exports.DEBUG){console.log(state.step,'SFVTPV[]');}}// ISECT[] moves point p to the InterSECTion of two lines // 0x0F function ISECT(state){var stack=state.stack;var pa0i=stack.pop();var pa1i=stack.pop();var pb0i=stack.pop();var pb1i=stack.pop();var pi=stack.pop();var z0=state.z0;var z1=state.z1;var pa0=z0[pa0i];var pa1=z0[pa1i];var pb0=z1[pb0i];var pb1=z1[pb1i];var p=state.z2[pi];if(exports.DEBUG){console.log('ISECT[], ',pa0i,pa1i,pb0i,pb1i,pi);}// math from // en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line var x1=pa0.x;var y1=pa0.y;var x2=pa1.x;var y2=pa1.y;var x3=pb0.x;var y3=pb0.y;var x4=pb1.x;var y4=pb1.y;var div=(x1-x2)*(y3-y4)-(y1-y2)*(x3-x4);var f1=x1*y2-y1*x2;var f2=x3*y4-y3*x4;p.x=(f1*(x3-x4)-f2*(x1-x2))/div;p.y=(f1*(y3-y4)-f2*(y1-y2))/div;}// SRP0[] Set Reference Point 0 // 0x10 function SRP0(state){state.rp0=state.stack.pop();if(exports.DEBUG){console.log(state.step,'SRP0[]',state.rp0);}}// SRP1[] Set Reference Point 1 // 0x11 function SRP1(state){state.rp1=state.stack.pop();if(exports.DEBUG){console.log(state.step,'SRP1[]',state.rp1);}}// SRP1[] Set Reference Point 2 // 0x12 function SRP2(state){state.rp2=state.stack.pop();if(exports.DEBUG){console.log(state.step,'SRP2[]',state.rp2);}}// SZP0[] Set Zone Pointer 0 // 0x13 function SZP0(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,'SZP0[]',n);}state.zp0=n;switch(n){case 0:if(!state.tZone){initTZone(state);}state.z0=state.tZone;break;case 1:state.z0=state.gZone;break;default:throw new Error('Invalid zone pointer');}}// SZP1[] Set Zone Pointer 1 // 0x14 function SZP1(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,'SZP1[]',n);}state.zp1=n;switch(n){case 0:if(!state.tZone){initTZone(state);}state.z1=state.tZone;break;case 1:state.z1=state.gZone;break;default:throw new Error('Invalid zone pointer');}}// SZP2[] Set Zone Pointer 2 // 0x15 function SZP2(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,'SZP2[]',n);}state.zp2=n;switch(n){case 0:if(!state.tZone){initTZone(state);}state.z2=state.tZone;break;case 1:state.z2=state.gZone;break;default:throw new Error('Invalid zone pointer');}}// SZPS[] Set Zone PointerS // 0x16 function SZPS(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,'SZPS[]',n);}state.zp0=state.zp1=state.zp2=n;switch(n){case 0:if(!state.tZone){initTZone(state);}state.z0=state.z1=state.z2=state.tZone;break;case 1:state.z0=state.z1=state.z2=state.gZone;break;default:throw new Error('Invalid zone pointer');}}// SLOOP[] Set LOOP variable // 0x17 function SLOOP(state){state.loop=state.stack.pop();if(exports.DEBUG){console.log(state.step,'SLOOP[]',state.loop);}}// RTG[] Round To Grid // 0x18 function RTG(state){if(exports.DEBUG){console.log(state.step,'RTG[]');}state.round=roundToGrid;}// RTHG[] Round To Half Grid // 0x19 function RTHG(state){if(exports.DEBUG){console.log(state.step,'RTHG[]');}state.round=roundToHalfGrid;}// SMD[] Set Minimum Distance // 0x1A function SMD(state){var d=state.stack.pop();if(exports.DEBUG){console.log(state.step,'SMD[]',d);}state.minDis=d/0x40;}// ELSE[] ELSE clause // 0x1B function ELSE(state){// This instruction has been reached by executing a then branch // so it just skips ahead until matching EIF. // // In case the IF was negative the IF[] instruction already // skipped forward over the ELSE[] if(exports.DEBUG){console.log(state.step,'ELSE[]');}skip(state,false);}// JMPR[] JuMP Relative // 0x1C function JMPR(state){var o=state.stack.pop();if(exports.DEBUG){console.log(state.step,'JMPR[]',o);}// A jump by 1 would do nothing. state.ip+=o-1;}// SCVTCI[] Set Control Value Table Cut-In // 0x1D function SCVTCI(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,'SCVTCI[]',n);}state.cvCutIn=n/0x40;}// DUP[] DUPlicate top stack element // 0x20 function DUP(state){var stack=state.stack;if(exports.DEBUG){console.log(state.step,'DUP[]');}stack.push(stack[stack.length-1]);}// POP[] POP top stack element // 0x21 function POP(state){if(exports.DEBUG){console.log(state.step,'POP[]');}state.stack.pop();}// CLEAR[] CLEAR the stack // 0x22 function CLEAR(state){if(exports.DEBUG){console.log(state.step,'CLEAR[]');}state.stack.length=0;}// SWAP[] SWAP the top two elements on the stack // 0x23 function SWAP(state){var stack=state.stack;var a=stack.pop();var b=stack.pop();if(exports.DEBUG){console.log(state.step,'SWAP[]');}stack.push(a);stack.push(b);}// DEPTH[] DEPTH of the stack // 0x24 function DEPTH(state){var stack=state.stack;if(exports.DEBUG){console.log(state.step,'DEPTH[]');}stack.push(stack.length);}// LOOPCALL[] LOOPCALL function // 0x2A function LOOPCALL(state){var stack=state.stack;var fn=stack.pop();var c=stack.pop();if(exports.DEBUG){console.log(state.step,'LOOPCALL[]',fn,c);}// saves callers program var cip=state.ip;var cprog=state.prog;state.prog=state.funcs[fn];// executes the function for(var i=0;i<c;i++){exec(state);if(exports.DEBUG){console.log(++state.step,i+1<c?'next loopcall':'done loopcall',i);}}// restores the callers program state.ip=cip;state.prog=cprog;}// CALL[] CALL function // 0x2B function CALL(state){var fn=state.stack.pop();if(exports.DEBUG){console.log(state.step,'CALL[]',fn);}// saves callers program var cip=state.ip;var cprog=state.prog;state.prog=state.funcs[fn];// executes the function exec(state);// restores the callers program state.ip=cip;state.prog=cprog;if(exports.DEBUG){console.log(++state.step,'returning from',fn);}}// CINDEX[] Copy the INDEXed element to the top of the stack // 0x25 function CINDEX(state){var stack=state.stack;var k=stack.pop();if(exports.DEBUG){console.log(state.step,'CINDEX[]',k);}// In case of k == 1, it copies the last element after popping // thus stack.length - k. stack.push(stack[stack.length-k]);}// MINDEX[] Move the INDEXed element to the top of the stack // 0x26 function MINDEX(state){var stack=state.stack;var k=stack.pop();if(exports.DEBUG){console.log(state.step,'MINDEX[]',k);}stack.push(stack.splice(stack.length-k,1)[0]);}// FDEF[] Function DEFinition // 0x2C function FDEF(state){if(state.env!=='fpgm'){throw new Error('FDEF not allowed here');}var stack=state.stack;var prog=state.prog;var ip=state.ip;var fn=stack.pop();var ipBegin=ip;if(exports.DEBUG){console.log(state.step,'FDEF[]',fn);}while(prog[++ip]!==0x2D){}state.ip=ip;state.funcs[fn]=prog.slice(ipBegin+1,ip);}// MDAP[a] Move Direct Absolute Point // 0x2E-0x2F function MDAP(round,state){var pi=state.stack.pop();var p=state.z0[pi];var fv=state.fv;var pv=state.pv;if(exports.DEBUG){console.log(state.step,'MDAP['+round+']',pi);}var d=pv.distance(p,HPZero);if(round){d=state.round(d);}fv.setRelative(p,HPZero,d,pv);fv.touch(p);state.rp0=state.rp1=pi;}// IUP[a] Interpolate Untouched Points through the outline // 0x30 function IUP(v,state){var z2=state.z2;var pLen=z2.length-2;var cp;var pp;var np;if(exports.DEBUG){console.log(state.step,'IUP['+v.axis+']');}for(var i=0;i<pLen;i++){cp=z2[i];// current point // if this point has been touched go on if(v.touched(cp)){continue;}pp=cp.prevTouched(v);// no point on the contour has been touched? if(pp===cp){continue;}np=cp.nextTouched(v);if(pp===np){// only one point on the contour has been touched // so simply moves the point like that v.setRelative(cp,cp,v.distance(pp,pp,false,true),v,true);}v.interpolate(cp,pp,np,v);}}// SHP[] SHift Point using reference point // 0x32-0x33 function SHP(a,state){var stack=state.stack;var rpi=a?state.rp1:state.rp2;var rp=(a?state.z0:state.z1)[rpi];var fv=state.fv;var pv=state.pv;var loop=state.loop;var z2=state.z2;while(loop--){var pi=stack.pop();var p=z2[pi];var d=pv.distance(rp,rp,false,true);fv.setRelative(p,p,d,pv);fv.touch(p);if(exports.DEBUG){console.log(state.step,(state.loop>1?'loop '+(state.loop-loop)+': ':'')+'SHP['+(a?'rp1':'rp2')+']',pi);}}state.loop=1;}// SHC[] SHift Contour using reference point // 0x36-0x37 function SHC(a,state){var stack=state.stack;var rpi=a?state.rp1:state.rp2;var rp=(a?state.z0:state.z1)[rpi];var fv=state.fv;var pv=state.pv;var ci=stack.pop();var sp=state.z2[state.contours[ci]];var p=sp;if(exports.DEBUG){console.log(state.step,'SHC['+a+']',ci);}var d=pv.distance(rp,rp,false,true);do{if(p!==rp){fv.setRelative(p,p,d,pv);}p=p.nextPointOnContour;}while(p!==sp);}// SHZ[] SHift Zone using reference point // 0x36-0x37 function SHZ(a,state){var stack=state.stack;var rpi=a?state.rp1:state.rp2;var rp=(a?state.z0:state.z1)[rpi];var fv=state.fv;var pv=state.pv;var e=stack.pop();if(exports.DEBUG){console.log(state.step,'SHZ['+a+']',e);}var z;switch(e){case 0:z=state.tZone;break;case 1:z=state.gZone;break;default:throw new Error('Invalid zone');}var p;var d=pv.distance(rp,rp,false,true);var pLen=z.length-2;for(var i=0;i<pLen;i++){p=z[i];fv.setRelative(p,p,d,pv);//if (p !== rp) fv.setRelative(p, p, d, pv); }}// SHPIX[] SHift point by a PIXel amount // 0x38 function SHPIX(state){var stack=state.stack;var loop=state.loop;var fv=state.fv;var d=stack.pop()/0x40;var z2=state.z2;while(loop--){var pi=stack.pop();var p=z2[pi];if(exports.DEBUG){console.log(state.step,(state.loop>1?'loop '+(state.loop-loop)+': ':'')+'SHPIX[]',pi,d);}fv.setRelative(p,p,d);fv.touch(p);}state.loop=1;}// IP[] Interpolate Point // 0x39 function IP(state){var stack=state.stack;var rp1i=state.rp1;var rp2i=state.rp2;var loop=state.loop;var rp1=state.z0[rp1i];var rp2=state.z1[rp2i];var fv=state.fv;var pv=state.dpv;var z2=state.z2;while(loop--){var pi=stack.pop();var p=z2[pi];if(exports.DEBUG){console.log(state.step,(state.loop>1?'loop '+(state.loop-loop)+': ':'')+'IP[]',pi,rp1i,'<->',rp2i);}fv.interpolate(p,rp1,rp2,pv);fv.touch(p);}state.loop=1;}// MSIRP[a] Move Stack Indirect Relative Point // 0x3A-0x3B function MSIRP(a,state){var stack=state.stack;var d=stack.pop()/64;var pi=stack.pop();var p=state.z1[pi];var rp0=state.z0[state.rp0];var fv=state.fv;var pv=state.pv;fv.setRelative(p,rp0,d,pv);fv.touch(p);if(exports.DEBUG){console.log(state.step,'MSIRP['+a+']',d,pi);}state.rp1=state.rp0;state.rp2=pi;if(a){state.rp0=pi;}}// ALIGNRP[] Align to reference point. // 0x3C function ALIGNRP(state){var stack=state.stack;var rp0i=state.rp0;var rp0=state.z0[rp0i];var loop=state.loop;var fv=state.fv;var pv=state.pv;var z1=state.z1;while(loop--){var pi=stack.pop();var p=z1[pi];if(exports.DEBUG){console.log(state.step,(state.loop>1?'loop '+(state.loop-loop)+': ':'')+'ALIGNRP[]',pi);}fv.setRelative(p,rp0,0,pv);fv.touch(p);}state.loop=1;}// RTG[] Round To Double Grid // 0x3D function RTDG(state){if(exports.DEBUG){console.log(state.step,'RTDG[]');}state.round=roundToDoubleGrid;}// MIAP[a] Move Indirect Absolute Point // 0x3E-0x3F function MIAP(round,state){var stack=state.stack;var n=stack.pop();var pi=stack.pop();var p=state.z0[pi];var fv=state.fv;var pv=state.pv;var cv=state.cvt[n];if(exports.DEBUG){console.log(state.step,'MIAP['+round+']',n,'(',cv,')',pi);}var d=pv.distance(p,HPZero);if(round){if(Math.abs(d-cv)<state.cvCutIn){d=cv;}d=state.round(d);}fv.setRelative(p,HPZero,d,pv);if(state.zp0===0){p.xo=p.x;p.yo=p.y;}fv.touch(p);state.rp0=state.rp1=pi;}// NPUSB[] PUSH N Bytes // 0x40 function NPUSHB(state){var prog=state.prog;var ip=state.ip;var stack=state.stack;var n=prog[++ip];if(exports.DEBUG){console.log(state.step,'NPUSHB[]',n);}for(var i=0;i<n;i++){stack.push(prog[++ip]);}state.ip=ip;}// NPUSHW[] PUSH N Words // 0x41 function NPUSHW(state){var ip=state.ip;var prog=state.prog;var stack=state.stack;var n=prog[++ip];if(exports.DEBUG){console.log(state.step,'NPUSHW[]',n);}for(var i=0;i<n;i++){var w=prog[++ip]<<8|prog[++ip];if(w&0x8000){w=-((w^0xffff)+1);}stack.push(w);}state.ip=ip;}// WS[] Write Store // 0x42 function WS(state){var stack=state.stack;var store=state.store;if(!store){store=state.store=[];}var v=stack.pop();var l=stack.pop();if(exports.DEBUG){console.log(state.step,'WS',v,l);}store[l]=v;}// RS[] Read Store // 0x43 function RS(state){var stack=state.stack;var store=state.store;var l=stack.pop();if(exports.DEBUG){console.log(state.step,'RS',l);}var v=store&&store[l]||0;stack.push(v);}// WCVTP[] Write Control Value Table in Pixel units // 0x44 function WCVTP(state){var stack=state.stack;var v=stack.pop();var l=stack.pop();if(exports.DEBUG){console.log(state.step,'WCVTP',v,l);}state.cvt[l]=v/0x40;}// RCVT[] Read Control Value Table entry // 0x45 function RCVT(state){var stack=state.stack;var cvte=stack.pop();if(exports.DEBUG){console.log(state.step,'RCVT',cvte);}stack.push(state.cvt[cvte]*0x40);}// GC[] Get Coordinate projected onto the projection vector // 0x46-0x47 function GC(a,state){var stack=state.stack;var pi=stack.pop();var p=state.z2[pi];if(exports.DEBUG){console.log(state.step,'GC['+a+']',pi);}stack.push(state.dpv.distance(p,HPZero,a,false)*0x40);}// MD[a] Measure Distance // 0x49-0x4A function MD(a,state){var stack=state.stack;var pi2=stack.pop();var pi1=stack.pop();var p2=state.z1[pi2];var p1=state.z0[pi1];var d=state.dpv.distance(p1,p2,a,a);if(exports.DEBUG){console.log(state.step,'MD['+a+']',pi2,pi1,'->',d);}state.stack.push(Math.round(d*64));}// MPPEM[] Measure Pixels Per EM // 0x4B function MPPEM(state){if(exports.DEBUG){console.log(state.step,'MPPEM[]');}state.stack.push(state.ppem);}// FLIPON[] set the auto FLIP Boolean to ON // 0x4D function FLIPON(state){if(exports.DEBUG){console.log(state.step,'FLIPON[]');}state.autoFlip=true;}// LT[] Less Than // 0x50 function LT(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,'LT[]',e2,e1);}stack.push(e1<e2?1:0);}// LTEQ[] Less Than or EQual // 0x53 function LTEQ(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,'LTEQ[]',e2,e1);}stack.push(e1<=e2?1:0);}// GTEQ[] Greater Than // 0x52 function GT(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,'GT[]',e2,e1);}stack.push(e1>e2?1:0);}// GTEQ[] Greater Than or EQual // 0x53 function GTEQ(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,'GTEQ[]',e2,e1);}stack.push(e1>=e2?1:0);}// EQ[] EQual // 0x54 function EQ(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,'EQ[]',e2,e1);}stack.push(e2===e1?1:0);}// NEQ[] Not EQual // 0x55 function NEQ(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,'NEQ[]',e2,e1);}stack.push(e2!==e1?1:0);}// ODD[] ODD // 0x56 function ODD(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,'ODD[]',n);}stack.push(Math.trunc(n)%2?1:0);}// EVEN[] EVEN // 0x57 function EVEN(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,'EVEN[]',n);}stack.push(Math.trunc(n)%2?0:1);}// IF[] IF test // 0x58 function IF(state){var test=state.stack.pop();if(exports.DEBUG){console.log(state.step,'IF[]',test);}// if test is true it just continues // if not the ip is skipped until matching ELSE or EIF if(!test){skip(state,true);if(exports.DEBUG){console.log(state.step,'EIF[]');}}}// EIF[] End IF // 0x59 function EIF(state){// this can be reached normally when // executing an else branch. // -> just ignore it if(exports.DEBUG){console.log(state.step,'EIF[]');}}// AND[] logical AND // 0x5A function AND(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,'AND[]',e2,e1);}stack.push(e2&&e1?1:0);}// OR[] logical OR // 0x5B function OR(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,'OR[]',e2,e1);}stack.push(e2||e1?1:0);}// NOT[] logical NOT // 0x5C function NOT(state){var stack=state.stack;var e=stack.pop();if(exports.DEBUG){console.log(state.step,'NOT[]',e);}stack.push(e?0:1);}// DELTAP1[] DELTA exception P1 // DELTAP2[] DELTA exception P2 // DELTAP3[] DELTA exception P3 // 0x5D, 0x71, 0x72 function DELTAP123(b,state){var stack=state.stack;var n=stack.pop();var fv=state.fv;var pv=state.pv;var ppem=state.ppem;var base=state.deltaBase+(b-1)*16;var ds=state.deltaShift;var z0=state.z0;if(exports.DEBUG){console.log(state.step,'DELTAP['+b+']',n,stack);}for(var i=0;i<n;i++){var pi=stack.pop();var arg=stack.pop();var appem=base+((arg&0xF0)>>4);if(appem!==ppem){continue;}var mag=(arg&0x0F)-8;if(mag>=0){mag++;}if(exports.DEBUG){console.log(state.step,'DELTAPFIX',pi,'by',mag*ds);}var p=z0[pi];fv.setRelative(p,p,mag*ds,pv);}}// SDB[] Set Delta Base in the graphics state // 0x5E function SDB(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,'SDB[]',n);}state.deltaBase=n;}// SDS[] Set Delta Shift in the graphics state // 0x5F function SDS(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,'SDS[]',n);}state.deltaShift=Math.pow(0.5,n);}// ADD[] ADD // 0x60 function ADD(state){var stack=state.stack;var n2=stack.pop();var n1=stack.pop();if(exports.DEBUG){console.log(state.step,'ADD[]',n2,n1);}stack.push(n1+n2);}// SUB[] SUB // 0x61 function SUB(state){var stack=state.stack;var n2=stack.pop();var n1=stack.pop();if(exports.DEBUG){console.log(state.step,'SUB[]',n2,n1);}stack.push(n1-n2);}// DIV[] DIV // 0x62 function DIV(state){var stack=state.stack;var n2=stack.pop();var n1=stack.pop();if(exports.DEBUG){console.log(state.step,'DIV[]',n2,n1);}stack.push(n1*64/n2);}// MUL[] MUL // 0x63 function MUL(state){var stack=state.stack;var n2=stack.pop();var n1=stack.pop();if(exports.DEBUG){console.log(state.step,'MUL[]',n2,n1);}stack.push(n1*n2/64);}// ABS[] ABSolute value // 0x64 function ABS(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,'ABS[]',n);}stack.push(Math.abs(n));}// NEG[] NEGate // 0x65 function NEG(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,'NEG[]',n);}stack.push(-n);}// FLOOR[] FLOOR // 0x66 function FLOOR(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,'FLOOR[]',n);}stack.push(Math.floor(n/0x40)*0x40);}// CEILING[] CEILING // 0x67 function CEILING(state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,'CEILING[]',n);}stack.push(Math.ceil(n/0x40)*0x40);}// ROUND[ab] ROUND value // 0x68-0x6B function ROUND(dt,state){var stack=state.stack;var n=stack.pop();if(exports.DEBUG){console.log(state.step,'ROUND[]');}stack.push(state.round(n/0x40)*0x40);}// WCVTF[] Write Control Value Table in Funits // 0x70 function WCVTF(state){var stack=state.stack;var v=stack.pop();var l=stack.pop();if(exports.DEBUG){console.log(state.step,'WCVTF[]',v,l);}state.cvt[l]=v*state.ppem/state.font.unitsPerEm;}// DELTAC1[] DELTA exception C1 // DELTAC2[] DELTA exception C2 // DELTAC3[] DELTA exception C3 // 0x73, 0x74, 0x75 function DELTAC123(b,state){var stack=state.stack;var n=stack.pop();var ppem=state.ppem;var base=state.deltaBase+(b-1)*16;var ds=state.deltaShift;if(exports.DEBUG){console.log(state.step,'DELTAC['+b+']',n,stack);}for(var i=0;i<n;i++){var c=stack.pop();var arg=stack.pop();var appem=base+((arg&0xF0)>>4);if(appem!==ppem){continue;}var mag=(arg&0x0F)-8;if(mag>=0){mag++;}var delta=mag*ds;if(exports.DEBUG){console.log(state.step,'DELTACFIX',c,'by',delta);}state.cvt[c]+=delta;}}// SROUND[] Super ROUND // 0x76 function SROUND(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,'SROUND[]',n);}state.round=roundSuper;var period;switch(n&0xC0){case 0x00:period=0.5;break;case 0x40:period=1;break;case 0x80:period=2;break;default:throw new Error('invalid SROUND value');}state.srPeriod=period;switch(n&0x30){case 0x00:state.srPhase=0;break;case 0x10:state.srPhase=0.25*period;break;case 0x20:state.srPhase=0.5*period;break;case 0x30:state.srPhase=0.75*period;break;default:throw new Error('invalid SROUND value');}n&=0x0F;if(n===0){state.srThreshold=0;}else{state.srThreshold=(n/8-0.5)*period;}}// S45ROUND[] Super ROUND 45 degrees // 0x77 function S45ROUND(state){var n=state.stack.pop();if(exports.DEBUG){console.log(state.step,'S45ROUND[]',n);}state.round=roundSuper;var period;switch(n&0xC0){case 0x00:period=Math.sqrt(2)/2;break;case 0x40:period=Math.sqrt(2);break;case 0x80:period=2*Math.sqrt(2);break;default:throw new Error('invalid S45ROUND value');}state.srPeriod=period;switch(n&0x30){case 0x00:state.srPhase=0;break;case 0x10:state.srPhase=0.25*period;break;case 0x20:state.srPhase=0.5*period;break;case 0x30:state.srPhase=0.75*period;break;default:throw new Error('invalid S45ROUND value');}n&=0x0F;if(n===0){state.srThreshold=0;}else{state.srThreshold=(n/8-0.5)*period;}}// ROFF[] Round Off // 0x7A function ROFF(state){if(exports.DEBUG){console.log(state.step,'ROFF[]');}state.round=roundOff;}// RUTG[] Round Up To Grid // 0x7C function RUTG(state){if(exports.DEBUG){console.log(state.step,'RUTG[]');}state.round=roundUpToGrid;}// RDTG[] Round Down To Grid // 0x7D function RDTG(state){if(exports.DEBUG){console.log(state.step,'RDTG[]');}state.round=roundDownToGrid;}// SCANCTRL[] SCAN conversion ConTRoL // 0x85 function SCANCTRL(state){var n=state.stack.pop();// ignored by opentype.js if(exports.DEBUG){console.log(state.step,'SCANCTRL[]',n);}}// SDPVTL[a] Set Dual Projection Vector To Line // 0x86-0x87 function SDPVTL(a,state){var stack=state.stack;var p2i=stack.pop();var p1i=stack.pop();var p2=state.z2[p2i];var p1=state.z1[p1i];if(exports.DEBUG){console.log(state.step,'SDPVTL['+a+']',p2i,p1i);}var dx;var dy;if(!a){dx=p1.x-p2.x;dy=p1.y-p2.y;}else{dx=p2.y-p1.y;dy=p1.x-p2.x;}state.dpv=getUnitVector(dx,dy);}// GETINFO[] GET INFOrmation // 0x88 function GETINFO(state){var stack=state.stack;var sel=stack.pop();var r=0;if(exports.DEBUG){console.log(state.step,'GETINFO[]',sel);}// v35 as in no subpixel hinting if(sel&0x01){r=35;}// TODO rotation and stretch currently not supported // and thus those GETINFO are always 0. // opentype.js is always gray scaling if(sel&0x20){r|=0x1000;}stack.push(r);}// ROLL[] ROLL the top three stack elements // 0x8A function ROLL(state){var stack=state.stack;var a=stack.pop();var b=stack.pop();var c=stack.pop();if(exports.DEBUG){console.log(state.step,'ROLL[]');}stack.push(b);stack.push(a);stack.push(c);}// MAX[] MAXimum of top two stack elements // 0x8B function MAX(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,'MAX[]',e2,e1);}stack.push(Math.max(e1,e2));}// MIN[] MINimum of top two stack elements // 0x8C function MIN(state){var stack=state.stack;var e2=stack.pop();var e1=stack.pop();if(exports.DEBUG){console.log(state.step,'MIN[]',e2,e1);}stack.push(Math.min(e1,e2));}// SCANTYPE[] SCANTYPE // 0x8D function SCANTYPE(state){var n=state.stack.pop();// ignored by opentype.js if(exports.DEBUG){console.log(state.step,'SCANTYPE[]',n);}}// INSTCTRL[] INSTCTRL // 0x8D function INSTCTRL(state){var s=state.stack.pop();var v=state.stack.pop();if(exports.DEBUG){console.log(state.step,'INSTCTRL[]',s,v);}switch(s){case 1:state.inhibitGridFit=!!v;return;case 2:state.ignoreCvt=!!v;return;default:throw new Error('invalid INSTCTRL[] selector');}}// PUSHB[abc] PUSH Bytes // 0xB0-0xB7 function PUSHB(n,state){var stack=state.stack;var prog=state.prog;var ip=state.ip;if(exports.DEBUG){console.log(state.step,'PUSHB['+n+']');}for(var i=0;i<n;i++){stack.push(prog[++ip]);}state.ip=ip;}// PUSHW[abc] PUSH Words // 0xB8-0xBF function PUSHW(n,state){var ip=state.ip;var prog=state.prog;var stack=state.stack;if(exports.DEBUG){console.log(state.ip,'PUSHW['+n+']');}for(var i=0;i<n;i++){var w=prog[++ip]<<8|prog[++ip];if(w&0x8000){w=-((w^0xffff)+1);}stack.push(w);}state.ip=ip;}// MDRP[abcde] Move Direct Relative Point // 0xD0-0xEF // (if indirect is 0) // // and // // MIRP[abcde] Move Indirect Relative Point // 0xE0-0xFF // (if indirect is 1) function MDRP_MIRP(indirect,setRp0,keepD,ro,dt,state){var stack=state.stack;var cvte=indirect&&stack.pop();var pi=stack.pop();var rp0i=state.rp0;var rp=state.z0[rp0i];var p=state.z1[pi];var md=state.minDis;var fv=state.fv;var pv=state.dpv;var od;// original distance var d;// moving distance var sign;// sign of distance var cv;d=od=pv.distance(p,rp,true,true);sign=d>=0?1:-1;// Math.sign would be 0 in case of 0 // TODO consider autoFlip d=Math.abs(d);if(indirect){cv=state.cvt[cvte];if(ro&&Math.abs(d-cv)<state.cvCutIn){d=cv;}}if(keepD&&d<md){d=md;}if(ro){d=state.round(d);}fv.setRelative(p,rp,sign*d,pv);fv.touch(p);if(exports.DEBUG){console.log(state.step,(indirect?'MIRP[':'MDRP[')+(setRp0?'M':'m')+(keepD?'>':'_')+(ro?'R':'_')+(dt===0?'Gr':dt===1?'Bl':dt===2?'Wh':'')+']',indirect?cvte+'('+state.cvt[cvte]+','+cv+')':'',pi,'(d =',od,'->',sign*d,')');}state.rp1=state.rp0;state.rp2=pi;if(setRp0){state.rp0=pi;}}/* * The instruction table. */instructionTable=[/* 0x00 */SVTCA.bind(undefined,yUnitVector),/* 0x01 */SVTCA.bind(undefined,xUnitVector),/* 0x02 */SPVTCA.bind(undefined,yUnitVector),/* 0x03 */SPVTCA.bind(undefined,xUnitVector),/* 0x04 */SFVTCA.bind(undefined,yUnitVector),/* 0x05 */SFVTCA.bind(undefined,xUnitVector),/* 0x06 */SPVTL.bind(undefined,0),/* 0x07 */SPVTL.bind(undefined,1),/* 0x08 */SFVTL.bind(undefined,0),/* 0x09 */SFVTL.bind(undefined,1),/* 0x0A */SPVFS,/* 0x0B */SFVFS,/* 0x0C */GPV,/* 0x0D */GFV,/* 0x0E */SFVTPV,/* 0x0F */ISECT,/* 0x10 */SRP0,/* 0x11 */SRP1,/* 0x12 */SRP2,/* 0x13 */SZP0,/* 0x14 */SZP1,/* 0x15 */SZP2,/* 0x16 */SZPS,/* 0x17 */SLOOP,/* 0x18 */RTG,/* 0x19 */RTHG,/* 0x1A */SMD,/* 0x1B */ELSE,/* 0x1C */JMPR,/* 0x1D */SCVTCI,/* 0x1E */undefined,// TODO SSWCI /* 0x1F */undefined,// TODO SSW /* 0x20 */DUP,/* 0x21 */POP,/* 0x22 */CLEAR,/* 0x23 */SWAP,/* 0x24 */DEPTH,/* 0x25 */CINDEX,/* 0x26 */MINDEX,/* 0x27 */undefined,// TODO ALIGNPTS /* 0x28 */undefined,/* 0x29 */undefined,// TODO UTP /* 0x2A */LOOPCALL,/* 0x2B */CALL,/* 0x2C */FDEF,/* 0x2D */undefined,// ENDF (eaten by FDEF) /* 0x2E */MDAP.bind(undefined,0),/* 0x2F */MDAP.bind(undefined,1),/* 0x30 */IUP.bind(undefined,yUnitVector),/* 0x31 */IUP.bind(undefined,xUnitVector),/* 0x32 */SHP.bind(undefined,0),/* 0x33 */SHP.bind(undefined,1),/* 0x34 */SHC.bind(undefined,0),/* 0x35 */SHC.bind(undefined,1),/* 0x36 */SHZ.bind(undefined,0),/* 0x37 */SHZ.bind(undefined,1),/* 0x38 */SHPIX,/* 0x39 */IP,/* 0x3A */MSIRP.bind(undefined,0),/* 0x3B */MSIRP.bind(undefined,1),/* 0x3C */ALIGNRP,/* 0x3D */RTDG,/* 0x3E */MIAP.bind(undefined,0),/* 0x3F */MIAP.bind(undefined,1),/* 0x40 */NPUSHB,/* 0x41 */NPUSHW,/* 0x42 */WS,/* 0x43 */RS,/* 0x44 */WCVTP,/* 0x45 */RCVT,/* 0x46 */GC.bind(undefined,0),/* 0x47 */GC.bind(undefined,1),/* 0x48 */undefined,// TODO SCFS /* 0x49 */MD.bind(undefined,0),/* 0x4A */MD.bind(undefined,1),/* 0x4B */MPPEM,/* 0x4C */undefined,// TODO MPS /* 0x4D */FLIPON,/* 0x4E */undefined,// TODO FLIPOFF /* 0x4F */undefined,// TODO DEBUG /* 0x50 */LT,/* 0x51 */LTEQ,/* 0x52 */GT,/* 0x53 */GTEQ,/* 0x54 */EQ,/* 0x55 */NEQ,/* 0x56 */ODD,/* 0x57 */EVEN,/* 0x58 */IF,/* 0x59 */EIF,/* 0x5A */AND,/* 0x5B */OR,/* 0x5C */NOT,/* 0x5D */DELTAP123.bind(undefined,1),/* 0x5E */SDB,/* 0x5F */SDS,/* 0x60 */ADD,/* 0x61 */SUB,/* 0x62 */DIV,/* 0x63 */MUL,/* 0x64 */ABS,/* 0x65 */NEG,/* 0x66 */FLOOR,/* 0x67 */CEILING,/* 0x68 */ROUND.bind(undefined,0),/* 0x69 */ROUND.bind(undefined,1),/* 0x6A */ROUND.bind(undefined,2),/* 0x6B */ROUND.bind(undefined,3),/* 0x6C */undefined,// TODO NROUND[ab] /* 0x6D */undefined,// TODO NROUND[ab] /* 0x6E */undefined,// TODO NROUND[ab] /* 0x6F */undefined,// TODO NROUND[ab] /* 0x70 */WCVTF,/* 0x71 */DELTAP123.bind(undefined,2),/* 0x72 */DELTAP123.bind(undefined,3),/* 0x73 */DELTAC123.bind(undefined,1),/* 0x74 */DELTAC123.bind(undefined,2),/* 0x75 */DELTAC123.bind(undefined,3),/* 0x76 */SROUND,/* 0x77 */S45ROUND,/* 0x78 */undefined,// TODO JROT[] /* 0x79 */undefined,// TODO JROF[] /* 0x7A */ROFF,/* 0x7B */undefined,/* 0x7C */RUTG,/* 0x7D */RDTG,/* 0x7E */POP,// actually SANGW, supposed to do only a pop though /* 0x7F */POP,// actually AA, supposed to do only a pop though /* 0x80 */undefined,// TODO FLIPPT /* 0x81 */undefined,// TODO FLIPRGON /* 0x82 */undefined,// TODO FLIPRGOFF /* 0x83 */undefined,/* 0x84 */undefined,/* 0x85 */SCANCTRL,/* 0x86 */SDPVTL.bind(undefined,0),/* 0x87 */SDPVTL.bind(undefined,1),/* 0x88 */GETINFO,/* 0x89 */undefined,// TODO IDEF /* 0x8A */ROLL,/* 0x8B */MAX,/* 0x8C */MIN,/* 0x8D */SCANTYPE,/* 0x8E */INSTCTRL,/* 0x8F */undefined,/* 0x90 */undefined,/* 0x91 */undefined,/* 0x92 */undefined,/* 0x93 */undefined,/* 0x94 */undefined,/* 0x95 */undefined,/* 0x96 */undefined,/* 0x97 */undefined,/* 0x98 */undefined,/* 0x99 */undefined,/* 0x9A */undefined,/* 0x9B */undefined,/* 0x9C */undefined,/* 0x9D */undefined,/* 0x9E */undefined,/* 0x9F */undefined,/* 0xA0 */undefined,/* 0xA1 */undefined,/* 0xA2 */undefined,/* 0xA3 */undefined,/* 0xA4 */undefined,/* 0xA5 */undefined,/* 0xA6 */undefined,/* 0xA7 */undefined,/* 0xA8 */undefined,/* 0xA9 */undefined,/* 0xAA */undefined,/* 0xAB */undefined,/* 0xAC */undefined,/* 0xAD */undefined,/* 0xAE */undefined,/* 0xAF */undefined,/* 0xB0 */PUSHB.bind(undefined,1),/* 0xB1 */PUSHB.bind(undefined,2),/* 0xB2 */PUSHB.bind(undefined,3),/* 0xB3 */PUSHB.bind(undefined,4),/* 0xB4 */PUSHB.bind(undefined,5),/* 0xB5 */PUSHB.bind(undefined,6),/* 0xB6 */PUSHB.bind(undefined,7),/* 0xB7 */PUSHB.bind(undefined,8),/* 0xB8 */PUSHW.bind(undefined,1),/* 0xB9 */PUSHW.bind(undefined,2),/* 0xBA */PUSHW.bind(undefined,3),/* 0xBB */PUSHW.bind(undefined,4),/* 0xBC */PUSHW.bind(undefined,5),/* 0xBD */PUSHW.bind(undefined,6),/* 0xBE */PUSHW.bind(undefined,7),/* 0xBF */PUSHW.bind(undefined,8),/* 0xC0 */MDRP_MIRP.bind(undefined,0,0,0,0,0),/* 0xC1 */MDRP_MIRP.bind(undefined,0,0,0,0,1),/* 0xC2 */MDRP_MIRP.bind(undefined,0,0,0,0,2),/* 0xC3 */MDRP_MIRP.bind(undefined,0,0,0,0,3),/* 0xC4 */MDRP_MIRP.bind(undefined,0,0,0,1,0),/* 0xC5 */MDRP_MIRP.bind(undefined,0,0,0,1,1),/* 0xC6 */MDRP_MIRP.bind(undefined,0,0,0,1,2),/* 0xC7 */MDRP_MIRP.bind(undefined,0,0,0,1,3),/* 0xC8 */MDRP_MIRP.bind(undefined,0,0,1,0,0),/* 0xC9 */MDRP_MIRP.bind(undefined,0,0,1,0,1),/* 0xCA */MDRP_MIRP.bind(undefined,0,0,1,0,2),/* 0xCB */MDRP_MIRP.bind(undefined,0,0,1,0,3),/* 0xCC */MDRP_MIRP.bind(undefined,0,0,1,1,0),/* 0xCD */MDRP_MIRP.bind(undefined,0,0,1,1,1),/* 0xCE */MDRP_MIRP.bind(undefined,0,0,1,1,2),/* 0xCF */MDRP_MIRP.bind(undefined,0,0,1,1,3),/* 0xD0 */MDRP_MIRP.bind(undefined,0,1,0,0,0),/* 0xD1 */MDRP_MIRP.bind(undefined,0,1,0,0,1),/* 0xD2 */MDRP_MIRP.bind(undefined,0,1,0,0,2),/* 0xD3 */MDRP_MIRP.bind(undefined,0,1,0,0,3),/* 0xD4 */MDRP_MIRP.bind(undefined,0,1,0,1,0),/* 0xD5 */MDRP_MIRP.bind(undefined,0,1,0,1,1),/* 0xD6 */MDRP_MIRP.bind(undefined,0,1,0,1,2),/* 0xD7 */MDRP_MIRP.bind(undefined,0,1,0,1,3),/* 0xD8 */MDRP_MIRP.bind(undefined,0,1,1,0,0),/* 0xD9 */MDRP_MIRP.bind(undefined,0,1,1,0,1),/* 0xDA */MDRP_MIRP.bind(undefined,0,1,1,0,2),/* 0xDB */MDRP_MIRP.bind(undefined,0,1,1,0,3),/* 0xDC */MDRP_MIRP.bind(undefined,0,1,1,1,0),/* 0xDD */MDRP_MIRP.bind(undefined,0,1,1,1,1),/* 0xDE */MDRP_MIRP.bind(undefined,0,1,1,1,2),/* 0xDF */MDRP_MIRP.bind(undefined,0,1,1,1,3),/* 0xE0 */MDRP_MIRP.bind(undefined,1,0,0,0,0),/* 0xE1 */MDRP_MIRP.bind(undefined,1,0,0,0,1),/* 0xE2 */MDRP_MIRP.bind(undefined,1,0,0,0,2),/* 0xE3 */MDRP_MIRP.bind(undefined,1,0,0,0,3),/* 0xE4 */MDRP_MIRP.bind(undefined,1,0,0,1,0),/* 0xE5 */MDRP_MIRP.bind(undefined,1,0,0,1,1),/* 0xE6 */MDRP_MIRP.bind(undefined,1,0,0,1,2),/* 0xE7 */MDRP_MIRP.bind(undefined,1,0,0,1,3),/* 0xE8 */MDRP_MIRP.bind(undefined,1,0,1,0,0),/* 0xE9 */MDRP_MIRP.bind(undefined,1,0,1,0,1),/* 0xEA */MDRP_MIRP.bind(undefined,1,0,1,0,2),/* 0xEB */MDRP_MIRP.bind(undefined,1,0,1,0,3),/* 0xEC */MDRP_MIRP.bind(undefined,1,0,1,1,0),/* 0xED */MDRP_MIRP.bind(undefined,1,0,1,1,1),/* 0xEE */MDRP_MIRP.bind(undefined,1,0,1,1,2),/* 0xEF */MDRP_MIRP.bind(undefined,1,0,1,1,3),/* 0xF0 */MDRP_MIRP.bind(undefined,1,1,0,0,0),/* 0xF1 */MDRP_MIRP.bind(undefined,1,1,0,0,1),/* 0xF2 */MDRP_MIRP.bind(undefined,1,1,0,0,2),/* 0xF3 */MDRP_MIRP.bind(undefined,1,1,0,0,3),/* 0xF4 */MDRP_MIRP.bind(undefined,1,1,0,1,0),/* 0xF5 */MDRP_MIRP.bind(undefined,1,1,0,1,1),/* 0xF6 */MDRP_MIRP.bind(undefined,1,1,0,1,2),/* 0xF7 */MDRP_MIRP.bind(undefined,1,1,0,1,3),/* 0xF8 */MDRP_MIRP.bind(undefined,1,1,1,0,0),/* 0xF9 */MDRP_MIRP.bind(undefined,1,1,1,0,1),/* 0xFA */MDRP_MIRP.bind(undefined,1,1,1,0,2),/* 0xFB */MDRP_MIRP.bind(undefined,1,1,1,0,3),/* 0xFC */MDRP_MIRP.bind(undefined,1,1,1,1,0),/* 0xFD */MDRP_MIRP.bind(undefined,1,1,1,1,1),/* 0xFE */MDRP_MIRP.bind(undefined,1,1,1,1,2),/* 0xFF */MDRP_MIRP.bind(undefined,1,1,1,1,3)];/***************************** Mathematical Considerations ****************************** fv ... refers to freedom vector pv ... refers to projection vector rp ... refers to reference point p ... refers to to point being operated on d ... refers to distance SETRELATIVE: ============ case freedom vector == x-axis: ------------------------------ (pv) .-' rpd .-' .-* d .-'90°' .-' ' .-' ' *-' ' b rp ' ' ' p *----------*-------------- (fv) pm rpdx = rpx + d * pv.x rpdy = rpy + d * pv.y equation of line b y - rpdy = pvns * (x- rpdx) y = p.y x = rpdx + ( p.y - rpdy ) / pvns case freedom vector == y-axis: ------------------------------ * pm |\ | \ | \ | \ | \ | \ | \ | \ | \ | \ b | \ | \ | \ .-' (pv) | 90° \.-' | .-'* rpd | .-' * *-' d p rp rpdx = rpx + d * pv.x rpdy = rpy + d * pv.y equation of line b: pvns ... normal slope to pv y - rpdy = pvns * (x - rpdx) x = p.x y = rpdy + pvns * (p.x - rpdx) generic case: ------------- .'(fv) .' .* pm .' ! .' . .' ! .' . b .' ! * . p ! 90° . ... (pv) ...-*-''' ...---''' rpd ...---''' d *--''' rp rpdx = rpx + d * pv.x rpdy = rpy + d * pv.y equation of line b: pvns... normal slope to pv y - rpdy = pvns * (x - rpdx) equation of freedom vector line: fvs ... slope of freedom vector (=fy/fx) y - py = fvs * (x - px) on pm both equations are true for same x/y y - rpdy = pvns * (x - rpdx) y - py = fvs * (x - px) form to y and set equal: pvns * (x - rpdx) + rpdy = fvs * (x - px) + py expand: pvns * x - pvns * rpdx + rpdy = fvs * x - fvs * px + py switch: fvs * x - fvs * px + py = pvns * x - pvns * rpdx + rpdy solve for x: fvs * x - pvns * x = fvs * px - pvns * rpdx - py + rpdy fvs * px - pvns * rpdx + rpdy - py x = ----------------------------------- fvs - pvns and: y = fvs * (x - px) + py INTERPOLATE: ============ Examples of point interpolation. The weight of the movement of the reference point gets bigger the further the other reference point is away, thus the safest option (that is avoiding 0/0 divisions) is to weight the original distance of the other point by the sum of both distances. If the sum of both distances is 0, then move the point by the arithmetic average of the movement of both reference points. (+6) rp1o *---->*rp1 . . (+12) . . rp2o *---------->* rp2 . . . . . . . . . 10 20 . . |.........|...................| . . . . . . (+8) . po *------>*p . . . . . 12 . 24 . |...........|.......................| 36 ------- (+10) rp1o *-------->*rp1 . . (-10) . . rp2 *<---------* rpo2 . . . . . . . . . 10 . 30 . . |.........|.............................| . . . (+5) . po *--->* p . . . . . . 20 . |....|..............| 5 15 ------- (+10) rp1o *-------->*rp1 . . . . rp2o *-------->*rp2 (+10) po *-------->* p ------- (+10) rp1o *-------->*rp1 . . . .(+30) rp2o *---------------------------->*rp2 (+25) po *----------------------->* p vim: set ts=4 sw=4 expandtab: *****/// The Font object // This code is based on Array.from implementation for strings in https://github.com/mathiasbynens/Array.from var arrayFromString=Array.from||function(s){return s.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]?|[^\uD800-\uDFFF]|./g)||[];};/** * @typedef FontOptions * @type Object * @property {Boolean} empty - whether to create a new empty font * @property {string} familyName * @property {string} styleName * @property {string=} fullName * @property {string=} postScriptName * @property {string=} designer * @property {string=} designerURL * @property {string=} manufacturer * @property {string=} manufacturerURL * @property {string=} license * @property {string=} licenseURL * @property {string=} version * @property {string=} description * @property {string=} copyright * @property {string=} trademark * @property {Number} unitsPerEm * @property {Number} ascender * @property {Number} descender * @property {Number} createdTimestamp * @property {string=} weightClass * @property {string=} widthClass * @property {string=} fsSelection *//** * A Font represents a loaded OpenType font file. * It contains a set of glyphs and methods to draw text on a drawing context, * or to get a path representing the text. * @exports opentype.Font * @class * @param {FontOptions} * @constructor */function Font(options){options=options||{};if(!options.empty){// Check that we've provided the minimum set of names. checkArgument(options.familyName,'When creating a new Font object, familyName is required.');checkArgument(options.styleName,'When creating a new Font object, styleName is required.');checkArgument(options.unitsPerEm,'When creating a new Font object, unitsPerEm is required.');checkArgument(options.ascender,'When creating a new Font object, ascender is required.');checkArgument(options.descender,'When creating a new Font object, descender is required.');checkArgument(options.descender<0,'Descender should be negative (e.g. -512).');// OS X will complain if the names are empty, so we put a single space everywhere by default. this.names={fontFamily:{en:options.familyName||' '},fontSubfamily:{en:options.styleName||' '},fullName:{en:options.fullName||options.familyName+' '+options.styleName},// postScriptName may not contain any whitespace postScriptName:{en:options.postScriptName||(options.familyName+options.styleName).replace(/\s/g,'')},designer:{en:options.designer||' '},designerURL:{en:options.designerURL||' '},manufacturer:{en:options.manufacturer||' '},manufacturerURL:{en:options.manufacturerURL||' '},license:{en:options.license||' '},licenseURL:{en:options.licenseURL||' '},version:{en:options.version||'Version 0.1'},description:{en:options.description||' '},copyright:{en:options.copyright||' '},trademark:{en:options.trademark||' '}};this.unitsPerEm=options.unitsPerEm||1000;this.ascender=options.ascender;this.descender=options.descender;this.createdTimestamp=options.createdTimestamp;this.tables={os2:{usWeightClass:options.weightClass||this.usWeightClasses.MEDIUM,usWidthClass:options.widthClass||this.usWidthClasses.MEDIUM,fsSelection:options.fsSelection||this.fsSelectionValues.REGULAR}};}this.supported=true;// Deprecated: parseBuffer will throw an error if font is not supported. this.glyphs=new glyphset.GlyphSet(this,options.glyphs||[]);this.encoding=new DefaultEncoding(this);this.position=new Position(this);this.substitution=new Substitution(this);this.tables=this.tables||{};Object.defineProperty(this,'hinting',{get:function get(){if(this._hinting){return this._hinting;}if(this.outlinesFormat==='truetype'){return this._hinting=new Hinting(this);}}});}/** * Check if the font has a glyph for the given character. * @param {string} * @return {Boolean} */Font.prototype.hasChar=function(c){return this.encoding.charToGlyphIndex(c)!==null;};/** * Convert the given character to a single glyph index. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {Number} */Font.prototype.charToGlyphIndex=function(s){return this.encoding.charToGlyphIndex(s);};/** * Convert the given character to a single Glyph object. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {opentype.Glyph} */Font.prototype.charToGlyph=function(c){var glyphIndex=this.charToGlyphIndex(c);var glyph=this.glyphs.get(glyphIndex);if(!glyph){// .notdef glyph=this.glyphs.get(0);}return glyph;};/** * Convert the given text to a list of Glyph objects. * Note that there is no strict one-to-one mapping between characters and * glyphs, so the list of returned glyphs can be larger or smaller than the * length of the given string. * @param {string} * @param {GlyphRenderOptions} [options] * @return {opentype.Glyph[]} */Font.prototype.stringToGlyphs=function(s,options){var this$1=this;options=options||this.defaultRenderOptions;// Get glyph indexes var chars=arrayFromString(s);var indexes=[];for(var i=0;i<chars.length;i+=1){var c=chars[i];indexes.push(this$1.charToGlyphIndex(c));}var length=indexes.length;// Apply substitutions on glyph indexes if(options.features){var script=options.script||this.substitution.getDefaultScriptName();var manyToOne=[];if(options.features.liga){manyToOne=manyToOne.concat(this.substitution.getFeature('liga',script,options.language));}if(options.features.rlig){manyToOne=manyToOne.concat(this.substitution.getFeature('rlig',script,options.language));}for(var i$1=0;i$1<length;i$1+=1){for(var j=0;j<manyToOne.length;j++){var ligature=manyToOne[j];var components=ligature.sub;var compCount=components.length;var k=0;while(k<compCount&&components[k]===indexes[i$1+k]){k++;}if(k===compCount){indexes.splice(i$1,compCount,ligature.by);length=length-compCount+1;}}}}// convert glyph indexes to glyph objects var glyphs=new Array(length);var notdef=this.glyphs.get(0);for(var i$2=0;i$2<length;i$2+=1){glyphs[i$2]=this$1.glyphs.get(indexes[i$2])||notdef;}return glyphs;};/** * @param {string} * @return {Number} */Font.prototype.nameToGlyphIndex=function(name){return this.glyphNames.nameToGlyphIndex(name);};/** * @param {string} * @return {opentype.Glyph} */Font.prototype.nameToGlyph=function(name){var glyphIndex=this.nameToGlyphIndex(name);var glyph=this.glyphs.get(glyphIndex);if(!glyph){// .notdef glyph=this.glyphs.get(0);}return glyph;};/** * @param {Number} * @return {String} */Font.prototype.glyphIndexToName=function(gid){if(!this.glyphNames.glyphIndexToName){return'';}return this.glyphNames.glyphIndexToName(gid);};/** * Retrieve the value of the kerning pair between the left glyph (or its index) * and the right glyph (or its index). If no kerning pair is found, return 0. * The kerning value gets added to the advance width when calculating the spacing * between glyphs. * For GPOS kerning, this method uses the default script and language, which covers * most use cases. To have greater control, use font.position.getKerningValue . * @param {opentype.Glyph} leftGlyph * @param {opentype.Glyph} rightGlyph * @return {Number} */Font.prototype.getKerningValue=function(leftGlyph,rightGlyph){leftGlyph=leftGlyph.index||leftGlyph;rightGlyph=rightGlyph.index||rightGlyph;var gposKerning=this.position.defaultKerningTables;if(gposKerning){return this.position.getKerningValue(gposKerning,leftGlyph,rightGlyph);}// "kern" table return this.kerningPairs[leftGlyph+','+rightGlyph]||0;};/** * @typedef GlyphRenderOptions * @type Object * @property {string} [script] - script used to determine which features to apply. By default, 'DFLT' or 'latn' is used. * See https://www.microsoft.com/typography/otspec/scripttags.htm * @property {string} [language='dflt'] - language system used to determine which features to apply. * See https://www.microsoft.com/typography/developers/opentype/languagetags.aspx * @property {boolean} [kerning=true] - whether to include kerning values * @property {object} [features] - OpenType Layout feature tags. Used to enable or disable the features of the given script/language system. * See https://www.microsoft.com/typography/otspec/featuretags.htm */Font.prototype.defaultRenderOptions={kerning:true,features:{liga:true,rlig:true}};/** * Helper function that invokes the given callback for each glyph in the given text. * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text * @param {string} text - The text to apply. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @param {Function} callback */Font.prototype.forEachGlyph=function(text,x,y,fontSize,options,callback){var this$1=this;x=x!==undefined?x:0;y=y!==undefined?y:0;fontSize=fontSize!==undefined?fontSize:72;options=options||this.defaultRenderOptions;var fontScale=1/this.unitsPerEm*fontSize;var glyphs=this.stringToGlyphs(text,options);var kerningLookups;if(options.kerning){var script=options.script||this.position.getDefaultScriptName();kerningLookups=this.position.getKerningTables(script,options.language);}for(var i=0;i<glyphs.length;i+=1){var glyph=glyphs[i];callback.call(this$1,glyph,x,y,fontSize,options);if(glyph.advanceWidth){x+=glyph.advanceWidth*fontScale;}if(options.kerning&&i<glyphs.length-1){// We should apply position adjustment lookups in a more generic way. // Here we only use the xAdvance value. var kerningValue=kerningLookups?this$1.position.getKerningValue(kerningLookups,glyph.index,glyphs[i+1].index):this$1.getKerningValue(glyph,glyphs[i+1]);x+=kerningValue*fontScale;}if(options.letterSpacing){x+=options.letterSpacing*fontSize;}else if(options.tracking){x+=options.tracking/1000*fontSize;}}return x;};/** * Create a Path object that represents the given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path} */Font.prototype.getPath=function(text,x,y,fontSize,options){var fullPath=new Path();this.forEachGlyph(text,x,y,fontSize,options,function(glyph,gX,gY,gFontSize){var glyphPath=glyph.getPath(gX,gY,gFontSize,options,this);fullPath.extend(glyphPath);});return fullPath;};/** * Create an array of Path objects that represent the glyphs of a given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path[]} */Font.prototype.getPaths=function(text,x,y,fontSize,options){var glyphPaths=[];this.forEachGlyph(text,x,y,fontSize,options,function(glyph,gX,gY,gFontSize){var glyphPath=glyph.getPath(gX,gY,gFontSize,options,this);glyphPaths.push(glyphPath);});return glyphPaths;};/** * Returns the advance width of a text. * * This is something different than Path.getBoundingBox() as for example a * suffixed whitespace increases the advanceWidth but not the bounding box * or an overhanging letter like a calligraphic 'f' might have a quite larger * bounding box than its advance width. * * This corresponds to canvas2dContext.measureText(text).width * * @param {string} text - The text to create. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return advance width */Font.prototype.getAdvanceWidth=function(text,fontSize,options){return this.forEachGlyph(text,0,0,fontSize,options,function(){});};/** * Draw the text on the given drawing context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */Font.prototype.draw=function(ctx,text,x,y,fontSize,options){this.getPath(text,x,y,fontSize,options).draw(ctx);};/** * Draw the points of all glyphs in the text. * On-curve points will be drawn in blue, off-curve points will be drawn in red. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */Font.prototype.drawPoints=function(ctx,text,x,y,fontSize,options){this.forEachGlyph(text,x,y,fontSize,options,function(glyph,gX,gY,gFontSize){glyph.drawPoints(ctx,gX,gY,gFontSize);});};/** * Draw lines indicating important font measurements for all glyphs in the text. * Black lines indicate the origin of the coordinate system (point 0,0). * Blue lines indicate the glyph bounding box. * Green line indicates the advance width of the glyph. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */Font.prototype.drawMetrics=function(ctx,text,x,y,fontSize,options){this.forEachGlyph(text,x,y,fontSize,options,function(glyph,gX,gY,gFontSize){glyph.drawMetrics(ctx,gX,gY,gFontSize);});};/** * @param {string} * @return {string} */Font.prototype.getEnglishName=function(name){var translations=this.names[name];if(translations){return translations.en;}};/** * Validate */Font.prototype.validate=function(){var _this=this;function assert(predicate,message){}function assertNamePresent(name){var englishName=_this.getEnglishName(name);assert(englishName&&englishName.trim().length>0,'No English '+name+' specified.');}// Identification information assertNamePresent('fontFamily');assertNamePresent('weightName');assertNamePresent('manufacturer');assertNamePresent('copyright');assertNamePresent('version');// Dimension information assert(this.unitsPerEm>0,'No unitsPerEm specified.');};/** * Convert the font object to a SFNT data structure. * This structure contains all the necessary tables and metadata to create a binary OTF file. * @return {opentype.Table} */Font.prototype.toTables=function(){return sfnt.fontToTable(this);};/** * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead. */Font.prototype.toBuffer=function(){console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.');return this.toArrayBuffer();};/** * Converts a `opentype.Font` into an `ArrayBuffer` * @return {ArrayBuffer} */Font.prototype.toArrayBuffer=function(){var sfntTable=this.toTables();var bytes=sfntTable.encode();var buffer=new ArrayBuffer(bytes.length);var intArray=new Uint8Array(buffer);for(var i=0;i<bytes.length;i++){intArray[i]=bytes[i];}return buffer;};/** * Initiate a download of the OpenType font. */Font.prototype.download=function(fileName){var familyName=this.getEnglishName('fontFamily');var styleName=this.getEnglishName('fontSubfamily');fileName=fileName||familyName.replace(/\s/g,'')+'-'+styleName+'.otf';var arrayBuffer=this.toArrayBuffer();if(isBrowser()){window.requestFileSystem=window.requestFileSystem||window.webkitRequestFileSystem;window.requestFileSystem(window.TEMPORARY,arrayBuffer.byteLength,function(fs){fs.root.getFile(fileName,{create:true},function(fileEntry){fileEntry.createWriter(function(writer){var dataView=new DataView(arrayBuffer);var blob=new Blob([dataView],{type:'font/opentype'});writer.write(blob);writer.addEventListener('writeend',function(){// Navigating to the file will download it. location.href=fileEntry.toURL();},false);});});},function(err){throw new Error(err.name+': '+err.message);});}else{var fs=_dereq_('fs');var buffer=arrayBufferToNodeBuffer(arrayBuffer);fs.writeFileSync(fileName,buffer);}};/** * @private */Font.prototype.fsSelectionValues={ITALIC:0x001,//1 UNDERSCORE:0x002,//2 NEGATIVE:0x004,//4 OUTLINED:0x008,//8 STRIKEOUT:0x010,//16 BOLD:0x020,//32 REGULAR:0x040,//64 USER_TYPO_METRICS:0x080,//128 WWS:0x100,//256 OBLIQUE:0x200//512 };/** * @private */Font.prototype.usWidthClasses={ULTRA_CONDENSED:1,EXTRA_CONDENSED:2,CONDENSED:3,SEMI_CONDENSED:4,MEDIUM:5,SEMI_EXPANDED:6,EXPANDED:7,EXTRA_EXPANDED:8,ULTRA_EXPANDED:9};/** * @private */Font.prototype.usWeightClasses={THIN:100,EXTRA_LIGHT:200,LIGHT:300,NORMAL:400,MEDIUM:500,SEMI_BOLD:600,BOLD:700,EXTRA_BOLD:800,BLACK:900};// The `fvar` table stores font variation axes and instances. function addName(name,names){var nameString=JSON.stringify(name);var nameID=256;for(var nameKey in names){var n=parseInt(nameKey);if(!n||n<256){continue;}if(JSON.stringify(names[nameKey])===nameString){return n;}if(nameID<=n){nameID=n+1;}}names[nameID]=name;return nameID;}function makeFvarAxis(n,axis,names){var nameID=addName(axis.name,names);return[{name:'tag_'+n,type:'TAG',value:axis.tag},{name:'minValue_'+n,type:'FIXED',value:axis.minValue<<16},{name:'defaultValue_'+n,type:'FIXED',value:axis.defaultValue<<16},{name:'maxValue_'+n,type:'FIXED',value:axis.maxValue<<16},{name:'flags_'+n,type:'USHORT',value:0},{name:'nameID_'+n,type:'USHORT',value:nameID}];}function parseFvarAxis(data,start,names){var axis={};var p=new parse.Parser(data,start);axis.tag=p.parseTag();axis.minValue=p.parseFixed();axis.defaultValue=p.parseFixed();axis.maxValue=p.parseFixed();p.skip('uShort',1);// reserved for flags; no values defined axis.name=names[p.parseUShort()]||{};return axis;}function makeFvarInstance(n,inst,axes,names){var nameID=addName(inst.name,names);var fields=[{name:'nameID_'+n,type:'USHORT',value:nameID},{name:'flags_'+n,type:'USHORT',value:0}];for(var i=0;i<axes.length;++i){var axisTag=axes[i].tag;fields.push({name:'axis_'+n+' '+axisTag,type:'FIXED',value:inst.coordinates[axisTag]<<16});}return fields;}function parseFvarInstance(data,start,axes,names){var inst={};var p=new parse.Parser(data,start);inst.name=names[p.parseUShort()]||{};p.skip('uShort',1);// reserved for flags; no values defined inst.coordinates={};for(var i=0;i<axes.length;++i){inst.coordinates[axes[i].tag]=p.parseFixed();}return inst;}function makeFvarTable(fvar,names){var result=new table.Table('fvar',[{name:'version',type:'ULONG',value:0x10000},{name:'offsetToData',type:'USHORT',value:0},{name:'countSizePairs',type:'USHORT',value:2},{name:'axisCount',type:'USHORT',value:fvar.axes.length},{name:'axisSize',type:'USHORT',value:20},{name:'instanceCount',type:'USHORT',value:fvar.instances.length},{name:'instanceSize',type:'USHORT',value:4+fvar.axes.length*4}]);result.offsetToData=result.sizeOf();for(var i=0;i<fvar.axes.length;i++){result.fields=result.fields.concat(makeFvarAxis(i,fvar.axes[i],names));}for(var j=0;j<fvar.instances.length;j++){result.fields=result.fields.concat(makeFvarInstance(j,fvar.instances[j],fvar.axes,names));}return result;}function parseFvarTable(data,start,names){var p=new parse.Parser(data,start);var tableVersion=p.parseULong();check.argument(tableVersion===0x00010000,'Unsupported fvar table version.');var offsetToData=p.parseOffset16();// Skip countSizePairs. p.skip('uShort',1);var axisCount=p.parseUShort();var axisSize=p.parseUShort();var instanceCount=p.parseUShort();var instanceSize=p.parseUShort();var axes=[];for(var i=0;i<axisCount;i++){axes.push(parseFvarAxis(data,start+offsetToData+i*axisSize,names));}var instances=[];var instanceStart=start+offsetToData+axisCount*axisSize;for(var j=0;j<instanceCount;j++){instances.push(parseFvarInstance(data,instanceStart+j*instanceSize,axes,names));}return{axes:axes,instances:instances};}var fvar={make:makeFvarTable,parse:parseFvarTable};// The `GPOS` table contains kerning pairs, among other things. var subtableParsers$1=new Array(10);// subtableParsers[0] is unused // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-1-single-adjustment-positioning-subtable // this = Parser instance subtableParsers$1[1]=function parseLookup1(){var start=this.offset+this.relativeOffset;var posformat=this.parseUShort();if(posformat===1){return{posFormat:1,coverage:this.parsePointer(Parser.coverage),value:this.parseValueRecord()};}else if(posformat===2){return{posFormat:2,coverage:this.parsePointer(Parser.coverage),values:this.parseValueRecordList()};}check.assert(false,'0x'+start.toString(16)+': GPOS lookup type 1 format must be 1 or 2.');};// https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable subtableParsers$1[2]=function parseLookup2(){var start=this.offset+this.relativeOffset;var posFormat=this.parseUShort();check.assert(posFormat===1||posFormat===2,'0x'+start.toString(16)+': GPOS lookup type 2 format must be 1 or 2.');var coverage=this.parsePointer(Parser.coverage);var valueFormat1=this.parseUShort();var valueFormat2=this.parseUShort();if(posFormat===1){// Adjustments for Glyph Pairs return{posFormat:posFormat,coverage:coverage,valueFormat1:valueFormat1,valueFormat2:valueFormat2,pairSets:this.parseList(Parser.pointer(Parser.list(function(){return{// pairValueRecord secondGlyph:this.parseUShort(),value1:this.parseValueRecord(valueFormat1),value2:this.parseValueRecord(valueFormat2)};})))};}else if(posFormat===2){var classDef1=this.parsePointer(Parser.classDef);var classDef2=this.parsePointer(Parser.classDef);var class1Count=this.parseUShort();var class2Count=this.parseUShort();return{// Class Pair Adjustment posFormat:posFormat,coverage:coverage,valueFormat1:valueFormat1,valueFormat2:valueFormat2,classDef1:classDef1,classDef2:classDef2,class1Count:class1Count,class2Count:class2Count,classRecords:this.parseList(class1Count,Parser.list(class2Count,function(){return{value1:this.parseValueRecord(valueFormat1),value2:this.parseValueRecord(valueFormat2)};}))};}};subtableParsers$1[3]=function parseLookup3(){return{error:'GPOS Lookup 3 not supported'};};subtableParsers$1[4]=function parseLookup4(){return{error:'GPOS Lookup 4 not supported'};};subtableParsers$1[5]=function parseLookup5(){return{error:'GPOS Lookup 5 not supported'};};subtableParsers$1[6]=function parseLookup6(){return{error:'GPOS Lookup 6 not supported'};};subtableParsers$1[7]=function parseLookup7(){return{error:'GPOS Lookup 7 not supported'};};subtableParsers$1[8]=function parseLookup8(){return{error:'GPOS Lookup 8 not supported'};};subtableParsers$1[9]=function parseLookup9(){return{error:'GPOS Lookup 9 not supported'};};// https://docs.microsoft.com/en-us/typography/opentype/spec/gpos function parseGposTable(data,start){start=start||0;var p=new Parser(data,start);var tableVersion=p.parseVersion(1);check.argument(tableVersion===1||tableVersion===1.1,'Unsupported GPOS table version '+tableVersion);if(tableVersion===1){return{version:tableVersion,scripts:p.parseScriptList(),features:p.parseFeatureList(),lookups:p.parseLookupList(subtableParsers$1)};}else{return{version:tableVersion,scripts:p.parseScriptList(),features:p.parseFeatureList(),lookups:p.parseLookupList(subtableParsers$1),variations:p.parseFeatureVariationsList()};}}// GPOS Writing ////////////////////////////////////////////// // NOT SUPPORTED var subtableMakers$1=new Array(10);function makeGposTable(gpos){return new table.Table('GPOS',[{name:'version',type:'ULONG',value:0x10000},{name:'scripts',type:'TABLE',value:new table.ScriptList(gpos.scripts)},{name:'features',type:'TABLE',value:new table.FeatureList(gpos.features)},{name:'lookups',type:'TABLE',value:new table.LookupList(gpos.lookups,subtableMakers$1)}]);}var gpos={parse:parseGposTable,make:makeGposTable};// The `kern` table contains kerning pairs. function parseWindowsKernTable(p){var pairs={};// Skip nTables. p.skip('uShort');var subtableVersion=p.parseUShort();check.argument(subtableVersion===0,'Unsupported kern sub-table version.');// Skip subtableLength, subtableCoverage p.skip('uShort',2);var nPairs=p.parseUShort();// Skip searchRange, entrySelector, rangeShift. p.skip('uShort',3);for(var i=0;i<nPairs;i+=1){var leftIndex=p.parseUShort();var rightIndex=p.parseUShort();var value=p.parseShort();pairs[leftIndex+','+rightIndex]=value;}return pairs;}function parseMacKernTable(p){var pairs={};// The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits. // Skip the rest. p.skip('uShort');var nTables=p.parseULong();//check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').'); if(nTables>1){console.warn('Only the first kern subtable is supported.');}p.skip('uLong');var coverage=p.parseUShort();var subtableVersion=coverage&0xFF;p.skip('uShort');if(subtableVersion===0){var nPairs=p.parseUShort();// Skip searchRange, entrySelector, rangeShift. p.skip('uShort',3);for(var i=0;i<nPairs;i+=1){var leftIndex=p.parseUShort();var rightIndex=p.parseUShort();var value=p.parseShort();pairs[leftIndex+','+rightIndex]=value;}}return pairs;}// Parse the `kern` table which contains kerning pairs. function parseKernTable(data,start){var p=new parse.Parser(data,start);var tableVersion=p.parseUShort();if(tableVersion===0){return parseWindowsKernTable(p);}else if(tableVersion===1){return parseMacKernTable(p);}else{throw new Error('Unsupported kern table version ('+tableVersion+').');}}var kern={parse:parseKernTable};// The `loca` table stores the offsets to the locations of the glyphs in the font. // Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font, // relative to the beginning of the glyphData table. // The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs) // The loca table has two versions: a short version where offsets are stored as uShorts, and a long // version where offsets are stored as uLongs. The `head` table specifies which version to use // (under indexToLocFormat). function parseLocaTable(data,start,numGlyphs,shortVersion){var p=new parse.Parser(data,start);var parseFn=shortVersion?p.parseUShort:p.parseULong;// There is an extra entry after the last index element to compute the length of the last glyph. // That's why we use numGlyphs + 1. var glyphOffsets=[];for(var i=0;i<numGlyphs+1;i+=1){var glyphOffset=parseFn.call(p);if(shortVersion){// The short table version stores the actual offset divided by 2. glyphOffset*=2;}glyphOffsets.push(glyphOffset);}return glyphOffsets;}var loca={parse:parseLocaTable};// opentype.js /** * The opentype library. * @namespace opentype */// File loaders ///////////////////////////////////////////////////////// /** * Loads a font from a file. The callback throws an error message as the first parameter if it fails * and the font as an ArrayBuffer in the second parameter if it succeeds. * @param {string} path - The path of the file * @param {Function} callback - The function to call when the font load completes */function loadFromFile(path,callback){var fs=_dereq_('fs');fs.readFile(path,function(err,buffer){if(err){return callback(err.message);}callback(null,nodeBufferToArrayBuffer(buffer));});}/** * Loads a font from a URL. The callback throws an error message as the first parameter if it fails * and the font as an ArrayBuffer in the second parameter if it succeeds. * @param {string} url - The URL of the font file. * @param {Function} callback - The function to call when the font load completes */function loadFromUrl(url,callback){var request=new XMLHttpRequest();request.open('get',url,true);request.responseType='arraybuffer';request.onload=function(){if(request.response){return callback(null,request.response);}else{return callback('Font could not be loaded: '+request.statusText);}};request.onerror=function(){callback('Font could not be loaded');};request.send();}// Table Directory Entries ////////////////////////////////////////////// /** * Parses OpenType table entries. * @param {DataView} * @param {Number} * @return {Object[]} */function parseOpenTypeTableEntries(data,numTables){var tableEntries=[];var p=12;for(var i=0;i<numTables;i+=1){var tag=parse.getTag(data,p);var checksum=parse.getULong(data,p+4);var offset=parse.getULong(data,p+8);var length=parse.getULong(data,p+12);tableEntries.push({tag:tag,checksum:checksum,offset:offset,length:length,compression:false});p+=16;}return tableEntries;}/** * Parses WOFF table entries. * @param {DataView} * @param {Number} * @return {Object[]} */function parseWOFFTableEntries(data,numTables){var tableEntries=[];var p=44;// offset to the first table directory entry. for(var i=0;i<numTables;i+=1){var tag=parse.getTag(data,p);var offset=parse.getULong(data,p+4);var compLength=parse.getULong(data,p+8);var origLength=parse.getULong(data,p+12);var compression=void 0;if(compLength<origLength){compression='WOFF';}else{compression=false;}tableEntries.push({tag:tag,offset:offset,compression:compression,compressedLength:compLength,length:origLength});p+=20;}return tableEntries;}/** * @typedef TableData * @type Object * @property {DataView} data - The DataView * @property {number} offset - The data offset. *//** * @param {DataView} * @param {Object} * @return {TableData} */function uncompressTable(data,tableEntry){if(tableEntry.compression==='WOFF'){var inBuffer=new Uint8Array(data.buffer,tableEntry.offset+2,tableEntry.compressedLength-2);var outBuffer=new Uint8Array(tableEntry.length);tinyInflate(inBuffer,outBuffer);if(outBuffer.byteLength!==tableEntry.length){throw new Error('Decompression error: '+tableEntry.tag+' decompressed length doesn\'t match recorded length');}var view=new DataView(outBuffer.buffer,0);return{data:view,offset:0};}else{return{data:data,offset:tableEntry.offset};}}// Public API /////////////////////////////////////////////////////////// /** * Parse the OpenType file data (as an ArrayBuffer) and return a Font object. * Throws an error if the font could not be parsed. * @param {ArrayBuffer} * @return {opentype.Font} */function parseBuffer(buffer){var indexToLocFormat;var ltagTable;// Since the constructor can also be called to create new fonts from scratch, we indicate this // should be an empty font that we'll fill with our own data. var font=new Font({empty:true});// OpenType fonts use big endian byte ordering. // We can't rely on typed array view types, because they operate with the endianness of the host computer. // Instead we use DataViews where we can specify endianness. var data=new DataView(buffer,0);var numTables;var tableEntries=[];var signature=parse.getTag(data,0);if(signature===String.fromCharCode(0,1,0,0)||signature==='true'||signature==='typ1'){font.outlinesFormat='truetype';numTables=parse.getUShort(data,4);tableEntries=parseOpenTypeTableEntries(data,numTables);}else if(signature==='OTTO'){font.outlinesFormat='cff';numTables=parse.getUShort(data,4);tableEntries=parseOpenTypeTableEntries(data,numTables);}else if(signature==='wOFF'){var flavor=parse.getTag(data,4);if(flavor===String.fromCharCode(0,1,0,0)){font.outlinesFormat='truetype';}else if(flavor==='OTTO'){font.outlinesFormat='cff';}else{throw new Error('Unsupported OpenType flavor '+signature);}numTables=parse.getUShort(data,12);tableEntries=parseWOFFTableEntries(data,numTables);}else{throw new Error('Unsupported OpenType signature '+signature);}var cffTableEntry;var fvarTableEntry;var glyfTableEntry;var gposTableEntry;var gsubTableEntry;var hmtxTableEntry;var kernTableEntry;var locaTableEntry;var nameTableEntry;var metaTableEntry;var p;for(var i=0;i<numTables;i+=1){var tableEntry=tableEntries[i];var table=void 0;switch(tableEntry.tag){case'cmap':table=uncompressTable(data,tableEntry);font.tables.cmap=cmap.parse(table.data,table.offset);font.encoding=new CmapEncoding(font.tables.cmap);break;case'cvt ':table=uncompressTable(data,tableEntry);p=new parse.Parser(table.data,table.offset);font.tables.cvt=p.parseShortList(tableEntry.length/2);break;case'fvar':fvarTableEntry=tableEntry;break;case'fpgm':table=uncompressTable(data,tableEntry);p=new parse.Parser(table.data,table.offset);font.tables.fpgm=p.parseByteList(tableEntry.length);break;case'head':table=uncompressTable(data,tableEntry);font.tables.head=head.parse(table.data,table.offset);font.unitsPerEm=font.tables.head.unitsPerEm;indexToLocFormat=font.tables.head.indexToLocFormat;break;case'hhea':table=uncompressTable(data,tableEntry);font.tables.hhea=hhea.parse(table.data,table.offset);font.ascender=font.tables.hhea.ascender;font.descender=font.tables.hhea.descender;font.numberOfHMetrics=font.tables.hhea.numberOfHMetrics;break;case'hmtx':hmtxTableEntry=tableEntry;break;case'ltag':table=uncompressTable(data,tableEntry);ltagTable=ltag.parse(table.data,table.offset);break;case'maxp':table=uncompressTable(data,tableEntry);font.tables.maxp=maxp.parse(table.data,table.offset);font.numGlyphs=font.tables.maxp.numGlyphs;break;case'name':nameTableEntry=tableEntry;break;case'OS/2':table=uncompressTable(data,tableEntry);font.tables.os2=os2.parse(table.data,table.offset);break;case'post':table=uncompressTable(data,tableEntry);font.tables.post=post.parse(table.data,table.offset);font.glyphNames=new GlyphNames(font.tables.post);break;case'prep':table=uncompressTable(data,tableEntry);p=new parse.Parser(table.data,table.offset);font.tables.prep=p.parseByteList(tableEntry.length);break;case'glyf':glyfTableEntry=tableEntry;break;case'loca':locaTableEntry=tableEntry;break;case'CFF ':cffTableEntry=tableEntry;break;case'kern':kernTableEntry=tableEntry;break;case'GPOS':gposTableEntry=tableEntry;break;case'GSUB':gsubTableEntry=tableEntry;break;case'meta':metaTableEntry=tableEntry;break;}}var nameTable=uncompressTable(data,nameTableEntry);font.tables.name=_name.parse(nameTable.data,nameTable.offset,ltagTable);font.names=font.tables.name;if(glyfTableEntry&&locaTableEntry){var shortVersion=indexToLocFormat===0;var locaTable=uncompressTable(data,locaTableEntry);var locaOffsets=loca.parse(locaTable.data,locaTable.offset,font.numGlyphs,shortVersion);var glyfTable=uncompressTable(data,glyfTableEntry);font.glyphs=glyf.parse(glyfTable.data,glyfTable.offset,locaOffsets,font);}else if(cffTableEntry){var cffTable=uncompressTable(data,cffTableEntry);cff.parse(cffTable.data,cffTable.offset,font);}else{throw new Error('Font doesn\'t contain TrueType or CFF outlines.');}var hmtxTable=uncompressTable(data,hmtxTableEntry);hmtx.parse(hmtxTable.data,hmtxTable.offset,font.numberOfHMetrics,font.numGlyphs,font.glyphs);addGlyphNames(font);if(kernTableEntry){var kernTable=uncompressTable(data,kernTableEntry);font.kerningPairs=kern.parse(kernTable.data,kernTable.offset);}else{font.kerningPairs={};}if(gposTableEntry){var gposTable=uncompressTable(data,gposTableEntry);font.tables.gpos=gpos.parse(gposTable.data,gposTable.offset);font.position.init();}if(gsubTableEntry){var gsubTable=uncompressTable(data,gsubTableEntry);font.tables.gsub=gsub.parse(gsubTable.data,gsubTable.offset);}if(fvarTableEntry){var fvarTable=uncompressTable(data,fvarTableEntry);font.tables.fvar=fvar.parse(fvarTable.data,fvarTable.offset,font.names);}if(metaTableEntry){var metaTable=uncompressTable(data,metaTableEntry);font.tables.meta=meta.parse(metaTable.data,metaTable.offset);font.metas=font.tables.meta;}return font;}/** * Asynchronously load the font from a URL or a filesystem. When done, call the callback * with two arguments `(err, font)`. The `err` will be null on success, * the `font` is a Font object. * We use the node.js callback convention so that * opentype.js can integrate with frameworks like async.js. * @alias opentype.load * @param {string} url - The URL of the font to load. * @param {Function} callback - The callback. */function load(url,callback){var isNode$$1=typeof window==='undefined';var loadFn=isNode$$1?loadFromFile:loadFromUrl;loadFn(url,function(err,arrayBuffer){if(err){return callback(err);}var font;try{font=parseBuffer(arrayBuffer);}catch(e){return callback(e,null);}return callback(null,font);});}/** * Synchronously load the font from a URL or file. * When done, returns the font object or throws an error. * @alias opentype.loadSync * @param {string} url - The URL of the font to load. * @return {opentype.Font} */function loadSync(url){var fs=_dereq_('fs');var buffer=fs.readFileSync(url);return parseBuffer(nodeBufferToArrayBuffer(buffer));}exports.Font=Font;exports.Glyph=Glyph;exports.Path=Path;exports.BoundingBox=BoundingBox;exports._parse=parse;exports.parse=parseBuffer;exports.load=load;exports.loadSync=loadSync;Object.defineProperty(exports,'__esModule',{value:true});});}).call(this,_dereq_("buffer").Buffer);},{"buffer":4,"fs":3}],12:[function(_dereq_,module,exports){// shim for using process in browser var process=module.exports={};// cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error('setTimeout has not been defined');}function defaultClearTimeout(){throw new Error('clearTimeout has not been defined');}(function(){try{if(typeof setTimeout==='function'){cachedSetTimeout=setTimeout;}else{cachedSetTimeout=defaultSetTimout;}}catch(e){cachedSetTimeout=defaultSetTimout;}try{if(typeof clearTimeout==='function'){cachedClearTimeout=clearTimeout;}else{cachedClearTimeout=defaultClearTimeout;}}catch(e){cachedClearTimeout=defaultClearTimeout;}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){//normal enviroments in sane situations return setTimeout(fun,0);}// if setTimeout wasn't available but was latter defined if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0);}try{// when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun,0);}catch(e){try{// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null,fun,0);}catch(e){// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this,fun,0);}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){//normal enviroments in sane situations return clearTimeout(marker);}// if clearTimeout wasn't available but was latter defined if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker);}try{// when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker);}catch(e){try{// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null,marker);}catch(e){// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this,marker);}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return;}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue);}else{queueIndex=-1;}if(queue.length){drainQueue();}}function drainQueue(){if(draining){return;}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){if(currentQueue){currentQueue[queueIndex].run();}}queueIndex=-1;len=queue.length;}currentQueue=null;draining=false;runClearTimeout(timeout);}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i];}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){runTimeout(drainQueue);}};// v8 likes predictible objects function Item(fun,array){this.fun=fun;this.array=array;}Item.prototype.run=function(){this.fun.apply(null,this.array);};process.title='browser';process.browser=true;process.env={};process.argv=[];process.version='';// empty string to avoid regexp issues process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.prependListener=noop;process.prependOnceListener=noop;process.listeners=function(name){return[];};process.binding=function(name){throw new Error('process.binding is not supported');};process.cwd=function(){return'/';};process.chdir=function(dir){throw new Error('process.chdir is not supported');};process.umask=function(){return 0;};},{}],13:[function(_dereq_,module,exports){(function(self){'use strict';if(self.fetch){return;}var support={searchParams:'URLSearchParams'in self,iterable:'Symbol'in self&&'iterator'in Symbol,blob:'FileReader'in self&&'Blob'in self&&function(){try{new Blob();return true;}catch(e){return false;}}(),formData:'FormData'in self,arrayBuffer:'ArrayBuffer'in self};if(support.arrayBuffer){var viewClasses=['[object Int8Array]','[object Uint8Array]','[object Uint8ClampedArray]','[object Int16Array]','[object Uint16Array]','[object Int32Array]','[object Uint32Array]','[object Float32Array]','[object Float64Array]'];var isDataView=function isDataView(obj){return obj&&DataView.prototype.isPrototypeOf(obj);};var isArrayBufferView=ArrayBuffer.isView||function(obj){return obj&&viewClasses.indexOf(Object.prototype.toString.call(obj))>-1;};}function normalizeName(name){if(typeof name!=='string'){name=String(name);}if(/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)){throw new TypeError('Invalid character in header field name');}return name.toLowerCase();}function normalizeValue(value){if(typeof value!=='string'){value=String(value);}return value;}// Build a destructive iterator for the value list function iteratorFor(items){var iterator={next:function next(){var value=items.shift();return{done:value===undefined,value:value};}};if(support.iterable){iterator[Symbol.iterator]=function(){return iterator;};}return iterator;}function Headers(headers){this.map={};if(headers instanceof Headers){headers.forEach(function(value,name){this.append(name,value);},this);}else if(Array.isArray(headers)){headers.forEach(function(header){this.append(header[0],header[1]);},this);}else if(headers){Object.getOwnPropertyNames(headers).forEach(function(name){this.append(name,headers[name]);},this);}}Headers.prototype.append=function(name,value){name=normalizeName(name);value=normalizeValue(value);var oldValue=this.map[name];this.map[name]=oldValue?oldValue+','+value:value;};Headers.prototype['delete']=function(name){delete this.map[normalizeName(name)];};Headers.prototype.get=function(name){name=normalizeName(name);return this.has(name)?this.map[name]:null;};Headers.prototype.has=function(name){return this.map.hasOwnProperty(normalizeName(name));};Headers.prototype.set=function(name,value){this.map[normalizeName(name)]=normalizeValue(value);};Headers.prototype.forEach=function(callback,thisArg){for(var name in this.map){if(this.map.hasOwnProperty(name)){callback.call(thisArg,this.map[name],name,this);}}};Headers.prototype.keys=function(){var items=[];this.forEach(function(value,name){items.push(name);});return iteratorFor(items);};Headers.prototype.values=function(){var items=[];this.forEach(function(value){items.push(value);});return iteratorFor(items);};Headers.prototype.entries=function(){var items=[];this.forEach(function(value,name){items.push([name,value]);});return iteratorFor(items);};if(support.iterable){Headers.prototype[Symbol.iterator]=Headers.prototype.entries;}function consumed(body){if(body.bodyUsed){return Promise.reject(new TypeError('Already read'));}body.bodyUsed=true;}function fileReaderReady(reader){return new Promise(function(resolve,reject){reader.onload=function(){resolve(reader.result);};reader.onerror=function(){reject(reader.error);};});}function readBlobAsArrayBuffer(blob){var reader=new FileReader();var promise=fileReaderReady(reader);reader.readAsArrayBuffer(blob);return promise;}function readBlobAsText(blob){var reader=new FileReader();var promise=fileReaderReady(reader);reader.readAsText(blob);return promise;}function readArrayBufferAsText(buf){var view=new Uint8Array(buf);var chars=new Array(view.length);for(var i=0;i<view.length;i++){chars[i]=String.fromCharCode(view[i]);}return chars.join('');}function bufferClone(buf){if(buf.slice){return buf.slice(0);}else{var view=new Uint8Array(buf.byteLength);view.set(new Uint8Array(buf));return view.buffer;}}function Body(){this.bodyUsed=false;this._initBody=function(body){this._bodyInit=body;if(!body){this._bodyText='';}else if(typeof body==='string'){this._bodyText=body;}else if(support.blob&&Blob.prototype.isPrototypeOf(body)){this._bodyBlob=body;}else if(support.formData&&FormData.prototype.isPrototypeOf(body)){this._bodyFormData=body;}else if(support.searchParams&&URLSearchParams.prototype.isPrototypeOf(body)){this._bodyText=body.toString();}else if(support.arrayBuffer&&support.blob&&isDataView(body)){this._bodyArrayBuffer=bufferClone(body.buffer);// IE 10-11 can't handle a DataView body. this._bodyInit=new Blob([this._bodyArrayBuffer]);}else if(support.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(body)||isArrayBufferView(body))){this._bodyArrayBuffer=bufferClone(body);}else{throw new Error('unsupported BodyInit type');}if(!this.headers.get('content-type')){if(typeof body==='string'){this.headers.set('content-type','text/plain;charset=UTF-8');}else if(this._bodyBlob&&this._bodyBlob.type){this.headers.set('content-type',this._bodyBlob.type);}else if(support.searchParams&&URLSearchParams.prototype.isPrototypeOf(body)){this.headers.set('content-type','application/x-www-form-urlencoded;charset=UTF-8');}}};if(support.blob){this.blob=function(){var rejected=consumed(this);if(rejected){return rejected;}if(this._bodyBlob){return Promise.resolve(this._bodyBlob);}else if(this._bodyArrayBuffer){return Promise.resolve(new Blob([this._bodyArrayBuffer]));}else if(this._bodyFormData){throw new Error('could not read FormData body as blob');}else{return Promise.resolve(new Blob([this._bodyText]));}};this.arrayBuffer=function(){if(this._bodyArrayBuffer){return consumed(this)||Promise.resolve(this._bodyArrayBuffer);}else{return this.blob().then(readBlobAsArrayBuffer);}};}this.text=function(){var rejected=consumed(this);if(rejected){return rejected;}if(this._bodyBlob){return readBlobAsText(this._bodyBlob);}else if(this._bodyArrayBuffer){return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));}else if(this._bodyFormData){throw new Error('could not read FormData body as text');}else{return Promise.resolve(this._bodyText);}};if(support.formData){this.formData=function(){return this.text().then(decode);};}this.json=function(){return this.text().then(JSON.parse);};return this;}// HTTP methods whose capitalization should be normalized var methods=['DELETE','GET','HEAD','OPTIONS','POST','PUT'];function normalizeMethod(method){var upcased=method.toUpperCase();return methods.indexOf(upcased)>-1?upcased:method;}function Request(input,options){options=options||{};var body=options.body;if(input instanceof Request){if(input.bodyUsed){throw new TypeError('Already read');}this.url=input.url;this.credentials=input.credentials;if(!options.headers){this.headers=new Headers(input.headers);}this.method=input.method;this.mode=input.mode;if(!body&&input._bodyInit!=null){body=input._bodyInit;input.bodyUsed=true;}}else{this.url=String(input);}this.credentials=options.credentials||this.credentials||'omit';if(options.headers||!this.headers){this.headers=new Headers(options.headers);}this.method=normalizeMethod(options.method||this.method||'GET');this.mode=options.mode||this.mode||null;this.referrer=null;if((this.method==='GET'||this.method==='HEAD')&&body){throw new TypeError('Body not allowed for GET or HEAD requests');}this._initBody(body);}Request.prototype.clone=function(){return new Request(this,{body:this._bodyInit});};function decode(body){var form=new FormData();body.trim().split('&').forEach(function(bytes){if(bytes){var split=bytes.split('=');var name=split.shift().replace(/\+/g,' ');var value=split.join('=').replace(/\+/g,' ');form.append(decodeURIComponent(name),decodeURIComponent(value));}});return form;}function parseHeaders(rawHeaders){var headers=new Headers();rawHeaders.split(/\r?\n/).forEach(function(line){var parts=line.split(':');var key=parts.shift().trim();if(key){var value=parts.join(':').trim();headers.append(key,value);}});return headers;}Body.call(Request.prototype);function Response(bodyInit,options){if(!options){options={};}this.type='default';this.status='status'in options?options.status:200;this.ok=this.status>=200&&this.status<300;this.statusText='statusText'in options?options.statusText:'OK';this.headers=new Headers(options.headers);this.url=options.url||'';this._initBody(bodyInit);}Body.call(Response.prototype);Response.prototype.clone=function(){return new Response(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Headers(this.headers),url:this.url});};Response.error=function(){var response=new Response(null,{status:0,statusText:''});response.type='error';return response;};var redirectStatuses=[301,302,303,307,308];Response.redirect=function(url,status){if(redirectStatuses.indexOf(status)===-1){throw new RangeError('Invalid status code');}return new Response(null,{status:status,headers:{location:url}});};self.Headers=Headers;self.Request=Request;self.Response=Response;self.fetch=function(input,init){return new Promise(function(resolve,reject){var request=new Request(input,init);var xhr=new XMLHttpRequest();xhr.onload=function(){var options={status:xhr.status,statusText:xhr.statusText,headers:parseHeaders(xhr.getAllResponseHeaders()||'')};options.url='responseURL'in xhr?xhr.responseURL:options.headers.get('X-Request-URL');var body='response'in xhr?xhr.response:xhr.responseText;resolve(new Response(body,options));};xhr.onerror=function(){reject(new TypeError('Network request failed'));};xhr.ontimeout=function(){reject(new TypeError('Network request failed'));};xhr.open(request.method,request.url,true);if(request.credentials==='include'){xhr.withCredentials=true;}if('responseType'in xhr&&support.blob){xhr.responseType='blob';}request.headers.forEach(function(value,name){xhr.setRequestHeader(name,value);});xhr.send(typeof request._bodyInit==='undefined'?null:request._bodyInit);});};self.fetch.polyfill=true;})(typeof self!=='undefined'?self:this);},{}],14:[function(_dereq_,module,exports){'use strict';// core var p5=_dereq_('./core/main');_dereq_('./core/constants');_dereq_('./core/environment');_dereq_('./core/error_helpers');_dereq_('./core/helpers');_dereq_('./core/legacy');_dereq_('./core/p5.Element');_dereq_('./core/p5.Graphics');_dereq_('./core/p5.Renderer');_dereq_('./core/p5.Renderer2D');_dereq_('./core/rendering');_dereq_('./core/shim');_dereq_('./core/structure');_dereq_('./core/transform');_dereq_('./core/shape/2d_primitives');_dereq_('./core/shape/attributes');_dereq_('./core/shape/curves');_dereq_('./core/shape/vertex');// color _dereq_('./color/color_conversion');_dereq_('./color/creating_reading');_dereq_('./color/p5.Color');_dereq_('./color/setting');// data _dereq_('./data/p5.TypedDict');// events _dereq_('./events/acceleration');_dereq_('./events/keyboard');_dereq_('./events/mouse');_dereq_('./events/touch');// image _dereq_('./image/filters');_dereq_('./image/image');_dereq_('./image/loading_displaying');_dereq_('./image/p5.Image');_dereq_('./image/pixels');// io _dereq_('./io/files');_dereq_('./io/p5.Table');_dereq_('./io/p5.TableRow');_dereq_('./io/p5.XML');// math _dereq_('./math/calculation');_dereq_('./math/math');_dereq_('./math/noise');_dereq_('./math/p5.Vector');_dereq_('./math/random');_dereq_('./math/trigonometry');// typography _dereq_('./typography/attributes');_dereq_('./typography/loading_displaying');_dereq_('./typography/p5.Font');// utilities _dereq_('./utilities/array_functions');_dereq_('./utilities/conversion');_dereq_('./utilities/string_functions');_dereq_('./utilities/time_date');// webgl _dereq_('./webgl/3d_primitives');_dereq_('./webgl/interaction');_dereq_('./webgl/light');_dereq_('./webgl/loading');_dereq_('./webgl/material');_dereq_('./webgl/p5.Camera');_dereq_('./webgl/p5.Geometry');_dereq_('./webgl/p5.Matrix');_dereq_('./webgl/p5.RendererGL.Immediate');_dereq_('./webgl/p5.RendererGL');_dereq_('./webgl/p5.RendererGL.Retained');_dereq_('./webgl/p5.Shader');_dereq_('./webgl/p5.Texture');_dereq_('./webgl/text');_dereq_('./core/init');module.exports=p5;},{"./color/color_conversion":15,"./color/creating_reading":16,"./color/p5.Color":17,"./color/setting":18,"./core/constants":19,"./core/environment":20,"./core/error_helpers":21,"./core/helpers":22,"./core/init":23,"./core/legacy":24,"./core/main":25,"./core/p5.Element":26,"./core/p5.Graphics":27,"./core/p5.Renderer":28,"./core/p5.Renderer2D":29,"./core/rendering":30,"./core/shape/2d_primitives":31,"./core/shape/attributes":32,"./core/shape/curves":33,"./core/shape/vertex":34,"./core/shim":35,"./core/structure":36,"./core/transform":37,"./data/p5.TypedDict":38,"./events/acceleration":39,"./events/keyboard":40,"./events/mouse":41,"./events/touch":42,"./image/filters":43,"./image/image":44,"./image/loading_displaying":45,"./image/p5.Image":46,"./image/pixels":47,"./io/files":48,"./io/p5.Table":49,"./io/p5.TableRow":50,"./io/p5.XML":51,"./math/calculation":52,"./math/math":53,"./math/noise":54,"./math/p5.Vector":55,"./math/random":56,"./math/trigonometry":57,"./typography/attributes":58,"./typography/loading_displaying":59,"./typography/p5.Font":60,"./utilities/array_functions":61,"./utilities/conversion":62,"./utilities/string_functions":63,"./utilities/time_date":64,"./webgl/3d_primitives":65,"./webgl/interaction":66,"./webgl/light":67,"./webgl/loading":68,"./webgl/material":69,"./webgl/p5.Camera":70,"./webgl/p5.Geometry":71,"./webgl/p5.Matrix":72,"./webgl/p5.RendererGL":75,"./webgl/p5.RendererGL.Immediate":73,"./webgl/p5.RendererGL.Retained":74,"./webgl/p5.Shader":76,"./webgl/p5.Texture":77,"./webgl/text":78}],15:[function(_dereq_,module,exports){/** * @module Color * @submodule Color Conversion * @for p5 * @requires core */'use strict';/** * Conversions adapted from <http://www.easyrgb.com/en/math.php>. * * In these functions, hue is always in the range [0, 1], just like all other * components are in the range [0, 1]. 'Brightness' and 'value' are used * interchangeably. */var p5=_dereq_('../core/main');p5.ColorConversion={};/** * Convert an HSBA array to HSLA. */p5.ColorConversion._hsbaToHSLA=function(hsba){var hue=hsba[0];var sat=hsba[1];var val=hsba[2];// Calculate lightness. var li=(2-sat)*val/2;// Convert saturation. if(li!==0){if(li===1){sat=0;}else if(li<0.5){sat=sat/(2-sat);}else{sat=sat*val/(2-li*2);}}// Hue and alpha stay the same. return[hue,sat,li,hsba[3]];};/** * Convert an HSBA array to RGBA. */p5.ColorConversion._hsbaToRGBA=function(hsba){var hue=hsba[0]*6;// We will split hue into 6 sectors. var sat=hsba[1];var val=hsba[2];var RGBA=[];if(sat===0){RGBA=[val,val,val,hsba[3]];// Return early if grayscale. }else{var sector=Math.floor(hue);var tint1=val*(1-sat);var tint2=val*(1-sat*(hue-sector));var tint3=val*(1-sat*(1+sector-hue));var red,green,blue;if(sector===1){// Yellow to green. red=tint2;green=val;blue=tint1;}else if(sector===2){// Green to cyan. red=tint1;green=val;blue=tint3;}else if(sector===3){// Cyan to blue. red=tint1;green=tint2;blue=val;}else if(sector===4){// Blue to magenta. red=tint3;green=tint1;blue=val;}else if(sector===5){// Magenta to red. red=val;green=tint1;blue=tint2;}else{// Red to yellow (sector could be 0 or 6). red=val;green=tint3;blue=tint1;}RGBA=[red,green,blue,hsba[3]];}return RGBA;};/** * Convert an HSLA array to HSBA. */p5.ColorConversion._hslaToHSBA=function(hsla){var hue=hsla[0];var sat=hsla[1];var li=hsla[2];// Calculate brightness. var val;if(li<0.5){val=(1+sat)*li;}else{val=li+sat-li*sat;}// Convert saturation. sat=2*(val-li)/val;// Hue and alpha stay the same. return[hue,sat,val,hsla[3]];};/** * Convert an HSLA array to RGBA. * * We need to change basis from HSLA to something that can be more easily be * projected onto RGBA. We will choose hue and brightness as our first two * components, and pick a convenient third one ('zest') so that we don't need * to calculate formal HSBA saturation. */p5.ColorConversion._hslaToRGBA=function(hsla){var hue=hsla[0]*6;// We will split hue into 6 sectors. var sat=hsla[1];var li=hsla[2];var RGBA=[];if(sat===0){RGBA=[li,li,li,hsla[3]];// Return early if grayscale. }else{// Calculate brightness. var val;if(li<0.5){val=(1+sat)*li;}else{val=li+sat-li*sat;}// Define zest. var zest=2*li-val;// Implement projection (project onto green by default). var hzvToRGB=function hzvToRGB(hue,zest,val){if(hue<0){// Hue must wrap to allow projection onto red and blue. hue+=6;}else if(hue>=6){hue-=6;}if(hue<1){// Red to yellow (increasing green). return zest+(val-zest)*hue;}else if(hue<3){// Yellow to cyan (greatest green). return val;}else if(hue<4){// Cyan to blue (decreasing green). return zest+(val-zest)*(4-hue);}else{// Blue to red (least green). return zest;}};// Perform projections, offsetting hue as necessary. RGBA=[hzvToRGB(hue+2,zest,val),hzvToRGB(hue,zest,val),hzvToRGB(hue-2,zest,val),hsla[3]];}return RGBA;};/** * Convert an RGBA array to HSBA. */p5.ColorConversion._rgbaToHSBA=function(rgba){var red=rgba[0];var green=rgba[1];var blue=rgba[2];var val=Math.max(red,green,blue);var chroma=val-Math.min(red,green,blue);var hue,sat;if(chroma===0){// Return early if grayscale. hue=0;sat=0;}else{sat=chroma/val;if(red===val){// Magenta to yellow. hue=(green-blue)/chroma;}else if(green===val){// Yellow to cyan. hue=2+(blue-red)/chroma;}else if(blue===val){// Cyan to magenta. hue=4+(red-green)/chroma;}if(hue<0){// Confine hue to the interval [0, 1). hue+=6;}else if(hue>=6){hue-=6;}}return[hue/6,sat,val,rgba[3]];};/** * Convert an RGBA array to HSLA. */p5.ColorConversion._rgbaToHSLA=function(rgba){var red=rgba[0];var green=rgba[1];var blue=rgba[2];var val=Math.max(red,green,blue);var min=Math.min(red,green,blue);var li=val+min;// We will halve this later. var chroma=val-min;var hue,sat;if(chroma===0){// Return early if grayscale. hue=0;sat=0;}else{if(li<1){sat=chroma/li;}else{sat=chroma/(2-li);}if(red===val){// Magenta to yellow. hue=(green-blue)/chroma;}else if(green===val){// Yellow to cyan. hue=2+(blue-red)/chroma;}else if(blue===val){// Cyan to magenta. hue=4+(red-green)/chroma;}if(hue<0){// Confine hue to the interval [0, 1). hue+=6;}else if(hue>=6){hue-=6;}}return[hue/6,sat,li/2,rgba[3]];};module.exports=p5.ColorConversion;},{"../core/main":25}],16:[function(_dereq_,module,exports){/** * @module Color * @submodule Creating & Reading * @for p5 * @requires core * @requires constants */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');_dereq_('./p5.Color');_dereq_('../core/error_helpers');/** * Extracts the alpha value from a color or pixel array. * * @method alpha * @param {p5.Color|Number[]|String} color <a href="#/p5.Color">p5.Color</a> object, color components, * or CSS color * @return {Number} the alpha value * @example * <div> * <code> * noStroke(); * var c = color(0, 126, 255, 102); * fill(c); * rect(15, 15, 35, 70); * var value = alpha(c); // Sets 'value' to 102 * fill(value); * rect(50, 15, 35, 70); * </code> * </div> * * @alt * Left half of canvas light blue and right half light charcoal grey. * Left half of canvas light purple and right half a royal blue. * Left half of canvas salmon pink and the right half white. * Yellow rect in middle right of canvas, with 55 pixel width and height. * Yellow ellipse in top left canvas, black ellipse in bottom right,both 80x80. * Bright fuschia rect in middle of canvas, 60 pixel width and height. * Two bright green rects on opposite sides of the canvas, both 45x80. * Four blue rects in each corner of the canvas, each are 35x35. * Bright sea green rect on left and darker rect on right of canvas, both 45x80. * Dark green rect on left and light green rect on right of canvas, both 45x80. * Dark blue rect on left and light teal rect on right of canvas, both 45x80. * blue rect on left and green on right, both with black outlines & 35x60. * salmon pink rect on left and black on right, both 35x60. * 4 rects, tan, brown, brownish purple and purple, with white outlines & 20x60. * light pastel green rect on left and dark grey rect on right, both 35x60. * yellow rect on left and red rect on right, both with black outlines & 35x60. * grey canvas * deep pink rect on left and grey rect on right, both 35x60. */p5.prototype.alpha=function(c){p5._validateParameters('alpha',arguments);return this.color(c)._getAlpha();};/** * Extracts the blue value from a color or pixel array. * * @method blue * @param {p5.Color|Number[]|String} color <a href="#/p5.Color">p5.Color</a> object, color components, * or CSS color * @return {Number} the blue value * @example * <div> * <code> * var c = color(175, 100, 220); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * rect(15, 20, 35, 60); // Draw left rectangle * * var blueValue = blue(c); // Get blue in 'c' * print(blueValue); // Prints "220.0" * fill(0, 0, blueValue); // Use 'blueValue' in new fill * rect(50, 20, 35, 60); // Draw right rectangle * </code> * </div> * * @alt * Left half of canvas light purple and right half a royal blue. * */p5.prototype.blue=function(c){p5._validateParameters('blue',arguments);return this.color(c)._getBlue();};/** * Extracts the HSB brightness value from a color or pixel array. * * @method brightness * @param {p5.Color|Number[]|String} color <a href="#/p5.Color">p5.Color</a> object, color components, * or CSS color * @return {Number} the brightness value * @example * <div> * <code> * noStroke(); * colorMode(HSB, 255); * var c = color(0, 126, 255); * fill(c); * rect(15, 20, 35, 60); * var value = brightness(c); // Sets 'value' to 255 * fill(value); * rect(50, 20, 35, 60); * </code> * </div> * * @alt * Left half of canvas salmon pink and the right half white. * */p5.prototype.brightness=function(c){p5._validateParameters('brightness',arguments);return this.color(c)._getBrightness();};/** * Creates colors for storing in variables of the color datatype. The * parameters are interpreted as RGB or HSB values depending on the * current <a href="#/p5/colorMode">colorMode()</a>. The default mode is RGB values from 0 to 255 * and, therefore, the function call color(255, 204, 0) will return a * bright yellow color. * <br><br> * Note that if only one value is provided to <a href="#/p5/color">color()</a>, it will be interpreted * as a grayscale value. Add a second value, and it will be used for alpha * transparency. When three values are specified, they are interpreted as * either RGB or HSB values. Adding a fourth value applies alpha * transparency. * <br><br> * If a single string argument is provided, RGB, RGBA and Hex CSS color * strings and all named color strings are supported. In this case, an alpha * number value as a second argument is not supported, the RGBA form should be * used. * * @method color * @param {Number} gray number specifying value between white * and black. * @param {Number} [alpha] alpha value relative to current color range * (default is 0-255) * @return {p5.Color} resulting color * * @example * <div> * <code> * var c = color(255, 204, 0); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * noStroke(); // Don't draw a stroke around shapes * rect(30, 20, 55, 55); // Draw rectangle * </code> * </div> * * <div> * <code> * var c = color(255, 204, 0); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * noStroke(); // Don't draw a stroke around shapes * ellipse(25, 25, 80, 80); // Draw left circle * * // Using only one value with color() * // generates a grayscale value. * c = color(65); // Update 'c' with grayscale value * fill(c); // Use updated 'c' as fill color * ellipse(75, 75, 80, 80); // Draw right circle * </code> * </div> * * <div> * <code> * // Named SVG & CSS colors may be used, * var c = color('magenta'); * fill(c); // Use 'c' as fill color * noStroke(); // Don't draw a stroke around shapes * rect(20, 20, 60, 60); // Draw rectangle * </code> * </div> * * <div> * <code> * // as can hex color codes: * noStroke(); // Don't draw a stroke around shapes * var c = color('#0f0'); * fill(c); // Use 'c' as fill color * rect(0, 10, 45, 80); // Draw rectangle * * c = color('#00ff00'); * fill(c); // Use updated 'c' as fill color * rect(55, 10, 45, 80); // Draw rectangle * </code> * </div> * * <div> * <code> * // RGB and RGBA color strings are also supported: * // these all set to the same color (solid blue) * var c; * noStroke(); // Don't draw a stroke around shapes * c = color('rgb(0,0,255)'); * fill(c); // Use 'c' as fill color * rect(10, 10, 35, 35); // Draw rectangle * * c = color('rgb(0%, 0%, 100%)'); * fill(c); // Use updated 'c' as fill color * rect(55, 10, 35, 35); // Draw rectangle * * c = color('rgba(0, 0, 255, 1)'); * fill(c); // Use updated 'c' as fill color * rect(10, 55, 35, 35); // Draw rectangle * * c = color('rgba(0%, 0%, 100%, 1)'); * fill(c); // Use updated 'c' as fill color * rect(55, 55, 35, 35); // Draw rectangle * </code> * </div> * * <div> * <code> * // HSL color is also supported and can be specified * // by value * var c; * noStroke(); // Don't draw a stroke around shapes * c = color('hsl(160, 100%, 50%)'); * fill(c); // Use 'c' as fill color * rect(0, 10, 45, 80); // Draw rectangle * * c = color('hsla(160, 100%, 50%, 0.5)'); * fill(c); // Use updated 'c' as fill color * rect(55, 10, 45, 80); // Draw rectangle * </code> * </div> * * <div> * <code> * // HSB color is also supported and can be specified * // by value * var c; * noStroke(); // Don't draw a stroke around shapes * c = color('hsb(160, 100%, 50%)'); * fill(c); // Use 'c' as fill color * rect(0, 10, 45, 80); // Draw rectangle * * c = color('hsba(160, 100%, 50%, 0.5)'); * fill(c); // Use updated 'c' as fill color * rect(55, 10, 45, 80); // Draw rectangle * </code> * </div> * * <div> * <code> * var c; // Declare color 'c' * noStroke(); // Don't draw a stroke around shapes * * // If no colorMode is specified, then the * // default of RGB with scale of 0-255 is used. * c = color(50, 55, 100); // Create a color for 'c' * fill(c); // Use color variable 'c' as fill color * rect(0, 10, 45, 80); // Draw left rect * * colorMode(HSB, 100); // Use HSB with scale of 0-100 * c = color(50, 55, 100); // Update 'c' with new color * fill(c); // Use updated 'c' as fill color * rect(55, 10, 45, 80); // Draw right rect * </code> * </div> * * @alt * Yellow rect in middle right of canvas, with 55 pixel width and height. * Yellow ellipse in top left of canvas, black ellipse in bottom right,both 80x80. * Bright fuschia rect in middle of canvas, 60 pixel width and height. * Two bright green rects on opposite sides of the canvas, both 45x80. * Four blue rects in each corner of the canvas, each are 35x35. * Bright sea green rect on left and darker rect on right of canvas, both 45x80. * Dark green rect on left and lighter green rect on right of canvas, both 45x80. * Dark blue rect on left and light teal rect on right of canvas, both 45x80. * *//** * @method color * @param {Number} v1 red or hue value relative to * the current color range * @param {Number} v2 green or saturation value * relative to the current color range * @param {Number} v3 blue or brightness value * relative to the current color range * @param {Number} [alpha] * @return {p5.Color} *//** * @method color * @param {String} value a color string * @return {p5.Color} *//** * @method color * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color * @return {p5.Color} *//** * @method color * @param {p5.Color} color * @return {p5.Color} */p5.prototype.color=function(){p5._validateParameters('color',arguments);if(arguments[0]instanceof p5.Color){return arguments[0];// Do nothing if argument is already a color object. }var args=arguments[0]instanceof Array?arguments[0]:arguments;return new p5.Color(this,args);};/** * Extracts the green value from a color or pixel array. * * @method green * @param {p5.Color|Number[]|String} color <a href="#/p5.Color">p5.Color</a> object, color components, * or CSS color * @return {Number} the green value * @example * <div> * <code> * var c = color(20, 75, 200); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * rect(15, 20, 35, 60); // Draw left rectangle * * var greenValue = green(c); // Get green in 'c' * print(greenValue); // Print "75.0" * fill(0, greenValue, 0); // Use 'greenValue' in new fill * rect(50, 20, 35, 60); // Draw right rectangle * </code> * </div> * * @alt * blue rect on left and green on right, both with black outlines & 35x60. * */p5.prototype.green=function(c){p5._validateParameters('green',arguments);return this.color(c)._getGreen();};/** * Extracts the hue value from a color or pixel array. * * Hue exists in both HSB and HSL. This function will return the * HSB-normalized hue when supplied with an HSB color object (or when supplied * with a pixel array while the color mode is HSB), but will default to the * HSL-normalized hue otherwise. (The values will only be different if the * maximum hue setting for each system is different.) * * @method hue * @param {p5.Color|Number[]|String} color <a href="#/p5.Color">p5.Color</a> object, color components, * or CSS color * @return {Number} the hue * @example * <div> * <code> * noStroke(); * colorMode(HSB, 255); * var c = color(0, 126, 255); * fill(c); * rect(15, 20, 35, 60); * var value = hue(c); // Sets 'value' to "0" * fill(value); * rect(50, 20, 35, 60); * </code> * </div> * * @alt * salmon pink rect on left and black on right, both 35x60. * */p5.prototype.hue=function(c){p5._validateParameters('hue',arguments);return this.color(c)._getHue();};/** * Blends two colors to find a third color somewhere between them. The amt * parameter is the amount to interpolate between the two values where 0.0 * equal to the first color, 0.1 is very near the first color, 0.5 is halfway * in between, etc. An amount below 0 will be treated as 0. Likewise, amounts * above 1 will be capped at 1. This is different from the behavior of <a href="#/p5/lerp">lerp()</a>, * but necessary because otherwise numbers outside the range will produce * strange and unexpected colors. * <br><br> * The way that colours are interpolated depends on the current color mode. * * @method lerpColor * @param {p5.Color} c1 interpolate from this color * @param {p5.Color} c2 interpolate to this color * @param {Number} amt number between 0 and 1 * @return {p5.Color} interpolated color * @example * <div> * <code> * colorMode(RGB); * stroke(255); * background(51); * var from = color(218, 165, 32); * var to = color(72, 61, 139); * colorMode(RGB); // Try changing to HSB. * var interA = lerpColor(from, to, 0.33); * var interB = lerpColor(from, to, 0.66); * fill(from); * rect(10, 20, 20, 60); * fill(interA); * rect(30, 20, 20, 60); * fill(interB); * rect(50, 20, 20, 60); * fill(to); * rect(70, 20, 20, 60); * </code> * </div> * * @alt * 4 rects one tan, brown, brownish purple, purple, with white outlines & 20x60 * */p5.prototype.lerpColor=function(c1,c2,amt){p5._validateParameters('lerpColor',arguments);var mode=this._colorMode;var maxes=this._colorMaxes;var l0,l1,l2,l3;var fromArray,toArray;if(mode===constants.RGB){fromArray=c1.levels.map(function(level){return level/255;});toArray=c2.levels.map(function(level){return level/255;});}else if(mode===constants.HSB){c1._getBrightness();// Cache hsba so it definitely exists. c2._getBrightness();fromArray=c1.hsba;toArray=c2.hsba;}else if(mode===constants.HSL){c1._getLightness();// Cache hsla so it definitely exists. c2._getLightness();fromArray=c1.hsla;toArray=c2.hsla;}else{throw new Error(mode+'cannot be used for interpolation.');}// Prevent extrapolation. amt=Math.max(Math.min(amt,1),0);// Define lerp here itself if user isn't using math module. // Maintains the definition as found in math/calculation.js if(typeof this.lerp==='undefined'){this.lerp=function(start,stop,amt){return amt*(stop-start)+start;};}// Perform interpolation. l0=this.lerp(fromArray[0],toArray[0],amt);l1=this.lerp(fromArray[1],toArray[1],amt);l2=this.lerp(fromArray[2],toArray[2],amt);l3=this.lerp(fromArray[3],toArray[3],amt);// Scale components. l0*=maxes[mode][0];l1*=maxes[mode][1];l2*=maxes[mode][2];l3*=maxes[mode][3];return this.color(l0,l1,l2,l3);};/** * Extracts the HSL lightness value from a color or pixel array. * * @method lightness * @param {p5.Color|Number[]|String} color <a href="#/p5.Color">p5.Color</a> object, color components, * or CSS color * @return {Number} the lightness * @example * <div> * <code> * noStroke(); * colorMode(HSL); * var c = color(156, 100, 50, 1); * fill(c); * rect(15, 20, 35, 60); * var value = lightness(c); // Sets 'value' to 50 * fill(value); * rect(50, 20, 35, 60); * </code> * </div> * * @alt * light pastel green rect on left and dark grey rect on right, both 35x60. * */p5.prototype.lightness=function(c){p5._validateParameters('lightness',arguments);return this.color(c)._getLightness();};/** * Extracts the red value from a color or pixel array. * * @method red * @param {p5.Color|Number[]|String} color <a href="#/p5.Color">p5.Color</a> object, color components, * or CSS color * @return {Number} the red value * @example * <div> * <code> * var c = color(255, 204, 0); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * rect(15, 20, 35, 60); // Draw left rectangle * * var redValue = red(c); // Get red in 'c' * print(redValue); // Print "255.0" * fill(redValue, 0, 0); // Use 'redValue' in new fill * rect(50, 20, 35, 60); // Draw right rectangle * </code> * </div> * * <div> * <code> * colorMode(RGB, 255); * var c = color(127, 255, 0); * colorMode(RGB, 1); * var myColor = red(c); * print(myColor); * </code> * </div> * * @alt * yellow rect on left and red rect on right, both with black outlines and 35x60. * grey canvas */p5.prototype.red=function(c){p5._validateParameters('red',arguments);return this.color(c)._getRed();};/** * Extracts the saturation value from a color or pixel array. * * Saturation is scaled differently in HSB and HSL. This function will return * the HSB saturation when supplied with an HSB color object (or when supplied * with a pixel array while the color mode is HSB), but will default to the * HSL saturation otherwise. * * @method saturation * @param {p5.Color|Number[]|String} color <a href="#/p5.Color">p5.Color</a> object, color components, * or CSS color * @return {Number} the saturation value * @example * <div> * <code> * noStroke(); * colorMode(HSB, 255); * var c = color(0, 126, 255); * fill(c); * rect(15, 20, 35, 60); * var value = saturation(c); // Sets 'value' to 126 * fill(value); * rect(50, 20, 35, 60); * </code> * </div> * * @alt *deep pink rect on left and grey rect on right, both 35x60. * */p5.prototype.saturation=function(c){p5._validateParameters('saturation',arguments);return this.color(c)._getSaturation();};module.exports=p5;},{"../core/constants":19,"../core/error_helpers":21,"../core/main":25,"./p5.Color":17}],17:[function(_dereq_,module,exports){/** * @module Color * @submodule Creating & Reading * @for p5 * @requires core * @requires constants * @requires color_conversion */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');var color_conversion=_dereq_('./color_conversion');/** * Each color stores the color mode and level maxes that applied at the * time of its construction. These are used to interpret the input arguments * (at construction and later for that instance of color) and to format the * output e.g. when <a href="#/p5/saturation">saturation()</a> is requested. * * Internally we store an array representing the ideal RGBA values in floating * point form, normalized from 0 to 1. From this we calculate the closest * screen color (RGBA levels from 0 to 255) and expose this to the renderer. * * We also cache normalized, floating point components of the color in various * representations as they are calculated. This is done to prevent repeating a * conversion that has already been performed. * * @class p5.Color */p5.Color=function(pInst,vals){// Record color mode and maxes at time of construction. this._storeModeAndMaxes(pInst._colorMode,pInst._colorMaxes);// Calculate normalized RGBA values. if(this.mode!==constants.RGB&&this.mode!==constants.HSL&&this.mode!==constants.HSB){throw new Error(this.mode+' is an invalid colorMode.');}else{this._array=p5.Color._parseInputs.apply(this,vals);}// Expose closest screen color. this._calculateLevels();return this;};/** * This function returns the color formatted as a string. This can be useful * for debugging, or for using p5.js with other libraries. * @method toString * @param {String} [format] How the color string will be formatted. * Leaving this empty formats the string as rgba(r, g, b, a). * '#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes. * 'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode. * 'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels. * 'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages. * @return {String} the formatted string * @example * <div> * <code> * var myColor; * function setup() { * createCanvas(200, 200); * stroke(255); * myColor = color(100, 100, 250); * fill(myColor); * } * * function draw() { * rotate(HALF_PI); * text(myColor.toString(), 0, -5); * text(myColor.toString('#rrggbb'), 0, -30); * text(myColor.toString('rgba%'), 0, -55); * } * </code> * </div> * * @alt * canvas with text representation of color */p5.Color.prototype.toString=function(format){if(!this.hsba)this.hsba=color_conversion._rgbaToHSBA(this._array);if(!this.hsla)this.hsla=color_conversion._rgbaToHSLA(this._array);var a=this.levels;var f=this._array;var alpha=f[3];// String representation uses normalized alpha switch(format){case'#rrggbb':return'#'.concat(a[0]<16?'0'.concat(a[0].toString(16)):a[0].toString(16),a[1]<16?'0'.concat(a[1].toString(16)):a[1].toString(16),a[2]<16?'0'.concat(a[2].toString(16)):a[2].toString(16));case'#rrggbbaa':return'#'.concat(a[0]<16?'0'.concat(a[0].toString(16)):a[0].toString(16),a[1]<16?'0'.concat(a[1].toString(16)):a[1].toString(16),a[2]<16?'0'.concat(a[2].toString(16)):a[2].toString(16),a[3]<16?'0'.concat(a[2].toString(16)):a[3].toString(16));case'#rgb':return'#'.concat(Math.round(f[0]*15).toString(16),Math.round(f[1]*15).toString(16),Math.round(f[2]*15).toString(16));case'#rgba':return'#'.concat(Math.round(f[0]*15).toString(16),Math.round(f[1]*15).toString(16),Math.round(f[2]*15).toString(16),Math.round(f[3]*15).toString(16));case'rgb':return'rgb('.concat(a[0],', ',a[1],', ',a[2],')');case'rgb%':return'rgb('.concat((100*f[0]).toPrecision(3),'%, ',(100*f[1]).toPrecision(3),'%, ',(100*f[2]).toPrecision(3),'%)');case'rgba%':return'rgba('.concat((100*f[0]).toPrecision(3),'%, ',(100*f[1]).toPrecision(3),'%, ',(100*f[2]).toPrecision(3),'%, ',(100*f[3]).toPrecision(3),'%)');case'hsb':case'hsv':return'hsb('.concat(this.hsba[0]*this.maxes[constants.HSB][0],', ',this.hsba[1]*this.maxes[constants.HSB][1],', ',this.hsba[2]*this.maxes[constants.HSB][2],')');case'hsb%':case'hsv%':return'hsb('.concat((100*this.hsba[0]).toPrecision(3),'%, ',(100*this.hsba[1]).toPrecision(3),'%, ',(100*this.hsba[2]).toPrecision(3),'%)');case'hsba':case'hsva':return'hsba('.concat(this.hsba[0]*this.maxes[constants.HSB][0],', ',this.hsba[1]*this.maxes[constants.HSB][1],', ',this.hsba[2]*this.maxes[constants.HSB][2],', ',alpha,')');case'hsba%':case'hsva%':return'hsba('.concat((100*this.hsba[0]).toPrecision(3),'%, ',(100*this.hsba[1]).toPrecision(3),'%, ',(100*this.hsba[2]).toPrecision(3),'%, ',(100*alpha).toPrecision(3),'%)');case'hsl':return'hsl('.concat(this.hsla[0]*this.maxes[constants.HSL][0],', ',this.hsla[1]*this.maxes[constants.HSL][1],', ',this.hsla[2]*this.maxes[constants.HSL][2],')');case'hsl%':return'hsl('.concat((100*this.hsla[0]).toPrecision(3),'%, ',(100*this.hsla[1]).toPrecision(3),'%, ',(100*this.hsla[2]).toPrecision(3),'%)');case'hsla':return'hsla('.concat(this.hsla[0]*this.maxes[constants.HSL][0],', ',this.hsla[1]*this.maxes[constants.HSL][1],', ',this.hsla[2]*this.maxes[constants.HSL][2],', ',alpha,')');case'hsla%':return'hsl('.concat((100*this.hsla[0]).toPrecision(3),'%, ',(100*this.hsla[1]).toPrecision(3),'%, ',(100*this.hsla[2]).toPrecision(3),'%, ',(100*alpha).toPrecision(3),'%)');case'rgba':default:return'rgba('+a[0]+','+a[1]+','+a[2]+','+alpha+')';}};/** * @method setRed * @param {Number} red the new red value * @example * <div> * <code> * var backgroundColor; * * function setup() { * backgroundColor = color(100, 50, 150); * } * * function draw() { * backgroundColor.setRed(128 + 128 * sin(millis() / 1000)); * background(backgroundColor); * } * </code> * </div> * * @alt * canvas with gradually changing background color */p5.Color.prototype.setRed=function(new_red){this._array[0]=new_red/this.maxes[constants.RGB][0];this._calculateLevels();};/** * @method setGreen * @param {Number} green the new green value * @example * <div> * <code> * var backgroundColor; * * function setup() { * backgroundColor = color(100, 50, 150); * } * * function draw() { * backgroundColor.setGreen(128 + 128 * sin(millis() / 1000)); * background(backgroundColor); * } * </code> * </div> * * @alt * canvas with gradually changing background color **/p5.Color.prototype.setGreen=function(new_green){this._array[1]=new_green/this.maxes[constants.RGB][1];this._calculateLevels();};/** * @method setBlue * @param {Number} blue the new blue value * @example * <div> * <code> * var backgroundColor; * * function setup() { * backgroundColor = color(100, 50, 150); * } * * function draw() { * backgroundColor.setBlue(128 + 128 * sin(millis() / 1000)); * background(backgroundColor); * } * </code> * </div> * * @alt * canvas with gradually changing background color **/p5.Color.prototype.setBlue=function(new_blue){this._array[2]=new_blue/this.maxes[constants.RGB][2];this._calculateLevels();};/** * @method setAlpha * @param {Number} alpha the new alpha value * @example * <div> * <code> * var squareColor; * * function setup() { * ellipseMode(CORNERS); * strokeWeight(4); * squareColor = color(100, 50, 150); * } * * function draw() { * background(255); * * noFill(); * stroke(0); * ellipse(10, 10, width - 10, height - 10); * * squareColor.setAlpha(128 + 128 * sin(millis() / 1000)); * fill(squareColor); * noStroke(); * rect(13, 13, width - 26, height - 26); * } * </code> * </div> * * @alt * circle behind a square with gradually changing opacity **/p5.Color.prototype.setAlpha=function(new_alpha){this._array[3]=new_alpha/this.maxes[this.mode][3];this._calculateLevels();};// calculates and stores the closest screen levels p5.Color.prototype._calculateLevels=function(){var array=this._array;// (loop backwards for performance) var levels=this.levels=new Array(array.length);for(var i=array.length-1;i>=0;--i){levels[i]=Math.round(array[i]*255);}};p5.Color.prototype._getAlpha=function(){return this._array[3]*this.maxes[this.mode][3];};// stores the color mode and maxes in this instance of Color // for later use (by _parseInputs()) p5.Color.prototype._storeModeAndMaxes=function(new_mode,new_maxes){this.mode=new_mode;this.maxes=new_maxes;};p5.Color.prototype._getMode=function(){return this.mode;};p5.Color.prototype._getMaxes=function(){return this.maxes;};p5.Color.prototype._getBlue=function(){return this._array[2]*this.maxes[constants.RGB][2];};p5.Color.prototype._getBrightness=function(){if(!this.hsba){this.hsba=color_conversion._rgbaToHSBA(this._array);}return this.hsba[2]*this.maxes[constants.HSB][2];};p5.Color.prototype._getGreen=function(){return this._array[1]*this.maxes[constants.RGB][1];};/** * Hue is the same in HSB and HSL, but the maximum value may be different. * This function will return the HSB-normalized saturation when supplied with * an HSB color object, but will default to the HSL-normalized saturation * otherwise. */p5.Color.prototype._getHue=function(){if(this.mode===constants.HSB){if(!this.hsba){this.hsba=color_conversion._rgbaToHSBA(this._array);}return this.hsba[0]*this.maxes[constants.HSB][0];}else{if(!this.hsla){this.hsla=color_conversion._rgbaToHSLA(this._array);}return this.hsla[0]*this.maxes[constants.HSL][0];}};p5.Color.prototype._getLightness=function(){if(!this.hsla){this.hsla=color_conversion._rgbaToHSLA(this._array);}return this.hsla[2]*this.maxes[constants.HSL][2];};p5.Color.prototype._getRed=function(){return this._array[0]*this.maxes[constants.RGB][0];};/** * Saturation is scaled differently in HSB and HSL. This function will return * the HSB saturation when supplied with an HSB color object, but will default * to the HSL saturation otherwise. */p5.Color.prototype._getSaturation=function(){if(this.mode===constants.HSB){if(!this.hsba){this.hsba=color_conversion._rgbaToHSBA(this._array);}return this.hsba[1]*this.maxes[constants.HSB][1];}else{if(!this.hsla){this.hsla=color_conversion._rgbaToHSLA(this._array);}return this.hsla[1]*this.maxes[constants.HSL][1];}};/** * CSS named colors. */var namedColors={aliceblue:'#f0f8ff',antiquewhite:'#faebd7',aqua:'#00ffff',aquamarine:'#7fffd4',azure:'#f0ffff',beige:'#f5f5dc',bisque:'#ffe4c4',black:'#000000',blanchedalmond:'#ffebcd',blue:'#0000ff',blueviolet:'#8a2be2',brown:'#a52a2a',burlywood:'#deb887',cadetblue:'#5f9ea0',chartreuse:'#7fff00',chocolate:'#d2691e',coral:'#ff7f50',cornflowerblue:'#6495ed',cornsilk:'#fff8dc',crimson:'#dc143c',cyan:'#00ffff',darkblue:'#00008b',darkcyan:'#008b8b',darkgoldenrod:'#b8860b',darkgray:'#a9a9a9',darkgreen:'#006400',darkgrey:'#a9a9a9',darkkhaki:'#bdb76b',darkmagenta:'#8b008b',darkolivegreen:'#556b2f',darkorange:'#ff8c00',darkorchid:'#9932cc',darkred:'#8b0000',darksalmon:'#e9967a',darkseagreen:'#8fbc8f',darkslateblue:'#483d8b',darkslategray:'#2f4f4f',darkslategrey:'#2f4f4f',darkturquoise:'#00ced1',darkviolet:'#9400d3',deeppink:'#ff1493',deepskyblue:'#00bfff',dimgray:'#696969',dimgrey:'#696969',dodgerblue:'#1e90ff',firebrick:'#b22222',floralwhite:'#fffaf0',forestgreen:'#228b22',fuchsia:'#ff00ff',gainsboro:'#dcdcdc',ghostwhite:'#f8f8ff',gold:'#ffd700',goldenrod:'#daa520',gray:'#808080',green:'#008000',greenyellow:'#adff2f',grey:'#808080',honeydew:'#f0fff0',hotpink:'#ff69b4',indianred:'#cd5c5c',indigo:'#4b0082',ivory:'#fffff0',khaki:'#f0e68c',lavender:'#e6e6fa',lavenderblush:'#fff0f5',lawngreen:'#7cfc00',lemonchiffon:'#fffacd',lightblue:'#add8e6',lightcoral:'#f08080',lightcyan:'#e0ffff',lightgoldenrodyellow:'#fafad2',lightgray:'#d3d3d3',lightgreen:'#90ee90',lightgrey:'#d3d3d3',lightpink:'#ffb6c1',lightsalmon:'#ffa07a',lightseagreen:'#20b2aa',lightskyblue:'#87cefa',lightslategray:'#778899',lightslategrey:'#778899',lightsteelblue:'#b0c4de',lightyellow:'#ffffe0',lime:'#00ff00',limegreen:'#32cd32',linen:'#faf0e6',magenta:'#ff00ff',maroon:'#800000',mediumaquamarine:'#66cdaa',mediumblue:'#0000cd',mediumorchid:'#ba55d3',mediumpurple:'#9370db',mediumseagreen:'#3cb371',mediumslateblue:'#7b68ee',mediumspringgreen:'#00fa9a',mediumturquoise:'#48d1cc',mediumvioletred:'#c71585',midnightblue:'#191970',mintcream:'#f5fffa',mistyrose:'#ffe4e1',moccasin:'#ffe4b5',navajowhite:'#ffdead',navy:'#000080',oldlace:'#fdf5e6',olive:'#808000',olivedrab:'#6b8e23',orange:'#ffa500',orangered:'#ff4500',orchid:'#da70d6',palegoldenrod:'#eee8aa',palegreen:'#98fb98',paleturquoise:'#afeeee',palevioletred:'#db7093',papayawhip:'#ffefd5',peachpuff:'#ffdab9',peru:'#cd853f',pink:'#ffc0cb',plum:'#dda0dd',powderblue:'#b0e0e6',purple:'#800080',red:'#ff0000',rosybrown:'#bc8f8f',royalblue:'#4169e1',saddlebrown:'#8b4513',salmon:'#fa8072',sandybrown:'#f4a460',seagreen:'#2e8b57',seashell:'#fff5ee',sienna:'#a0522d',silver:'#c0c0c0',skyblue:'#87ceeb',slateblue:'#6a5acd',slategray:'#708090',slategrey:'#708090',snow:'#fffafa',springgreen:'#00ff7f',steelblue:'#4682b4',tan:'#d2b48c',teal:'#008080',thistle:'#d8bfd8',tomato:'#ff6347',turquoise:'#40e0d0',violet:'#ee82ee',wheat:'#f5deb3',white:'#ffffff',whitesmoke:'#f5f5f5',yellow:'#ffff00',yellowgreen:'#9acd32'};/** * These regular expressions are used to build up the patterns for matching * viable CSS color strings: fragmenting the regexes in this way increases the * legibility and comprehensibility of the code. * * Note that RGB values of .9 are not parsed by IE, but are supported here for * color string consistency. */var WHITESPACE=/\s*/;// Match zero or more whitespace characters. var INTEGER=/(\d{1,3})/;// Match integers: 79, 255, etc. var DECIMAL=/((?:\d+(?:\.\d+)?)|(?:\.\d+))/;// Match 129.6, 79, .9, etc. var PERCENT=new RegExp(DECIMAL.source+'%');// Match 12.9%, 79%, .9%, etc. /** * Full color string patterns. The capture groups are necessary. */var colorPatterns={// Match colors in format #XXX, e.g. #416. HEX3:/^#([a-f0-9])([a-f0-9])([a-f0-9])$/i,// Match colors in format #XXXX, e.g. #5123. HEX4:/^#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])$/i,// Match colors in format #XXXXXX, e.g. #b4d455. HEX6:/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i,// Match colors in format #XXXXXXXX, e.g. #b4d45535. HEX8:/^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i,// Match colors in format rgb(R, G, B), e.g. rgb(255, 0, 128). RGB:new RegExp(['^rgb\\(',INTEGER.source,',',INTEGER.source,',',INTEGER.source,'\\)$'].join(WHITESPACE.source),'i'),// Match colors in format rgb(R%, G%, B%), e.g. rgb(100%, 0%, 28.9%). RGB_PERCENT:new RegExp(['^rgb\\(',PERCENT.source,',',PERCENT.source,',',PERCENT.source,'\\)$'].join(WHITESPACE.source),'i'),// Match colors in format rgb(R, G, B, A), e.g. rgb(255, 0, 128, 0.25). RGBA:new RegExp(['^rgba\\(',INTEGER.source,',',INTEGER.source,',',INTEGER.source,',',DECIMAL.source,'\\)$'].join(WHITESPACE.source),'i'),// Match colors in format rgb(R%, G%, B%, A), e.g. rgb(100%, 0%, 28.9%, 0.5). RGBA_PERCENT:new RegExp(['^rgba\\(',PERCENT.source,',',PERCENT.source,',',PERCENT.source,',',DECIMAL.source,'\\)$'].join(WHITESPACE.source),'i'),// Match colors in format hsla(H, S%, L%), e.g. hsl(100, 40%, 28.9%). HSL:new RegExp(['^hsl\\(',INTEGER.source,',',PERCENT.source,',',PERCENT.source,'\\)$'].join(WHITESPACE.source),'i'),// Match colors in format hsla(H, S%, L%, A), e.g. hsla(100, 40%, 28.9%, 0.5). HSLA:new RegExp(['^hsla\\(',INTEGER.source,',',PERCENT.source,',',PERCENT.source,',',DECIMAL.source,'\\)$'].join(WHITESPACE.source),'i'),// Match colors in format hsb(H, S%, B%), e.g. hsb(100, 40%, 28.9%). HSB:new RegExp(['^hsb\\(',INTEGER.source,',',PERCENT.source,',',PERCENT.source,'\\)$'].join(WHITESPACE.source),'i'),// Match colors in format hsba(H, S%, B%, A), e.g. hsba(100, 40%, 28.9%, 0.5). HSBA:new RegExp(['^hsba\\(',INTEGER.source,',',PERCENT.source,',',PERCENT.source,',',DECIMAL.source,'\\)$'].join(WHITESPACE.source),'i')};/** * For a number of different inputs, returns a color formatted as [r, g, b, a] * arrays, with each component normalized between 0 and 1. * * @private * @param {Array} [...args] An 'array-like' object that represents a list of * arguments * @return {Number[]} a color formatted as [r, g, b, a] * Example: * input ==> output * g ==> [g, g, g, 255] * g,a ==> [g, g, g, a] * r, g, b ==> [r, g, b, 255] * r, g, b, a ==> [r, g, b, a] * [g] ==> [g, g, g, 255] * [g, a] ==> [g, g, g, a] * [r, g, b] ==> [r, g, b, 255] * [r, g, b, a] ==> [r, g, b, a] * @example * <div> * <code> * // todo * </code> * </div> * * @alt * //todo * */p5.Color._parseInputs=function(r,g,b,a){var numArgs=arguments.length;var mode=this.mode;var maxes=this.maxes[mode];var results=[];var i;if(numArgs>=3){// Argument is a list of component values. results[0]=r/maxes[0];results[1]=g/maxes[1];results[2]=b/maxes[2];// Alpha may be undefined, so default it to 100%. if(typeof a==='number'){results[3]=a/maxes[3];}else{results[3]=1;}// Constrain components to the range [0,1]. // (loop backwards for performance) for(i=results.length-1;i>=0;--i){var result=results[i];if(result<0){results[i]=0;}else if(result>1){results[i]=1;}}// Convert to RGBA and return. if(mode===constants.HSL){return color_conversion._hslaToRGBA(results);}else if(mode===constants.HSB){return color_conversion._hsbaToRGBA(results);}else{return results;}}else if(numArgs===1&&typeof r==='string'){var str=r.trim().toLowerCase();// Return if string is a named colour. if(namedColors[str]){return p5.Color._parseInputs.call(this,namedColors[str]);}// Try RGBA pattern matching. if(colorPatterns.HEX3.test(str)){// #rgb results=colorPatterns.HEX3.exec(str).slice(1).map(function(color){return parseInt(color+color,16)/255;});results[3]=1;return results;}else if(colorPatterns.HEX6.test(str)){// #rrggbb results=colorPatterns.HEX6.exec(str).slice(1).map(function(color){return parseInt(color,16)/255;});results[3]=1;return results;}else if(colorPatterns.HEX4.test(str)){// #rgba results=colorPatterns.HEX4.exec(str).slice(1).map(function(color){return parseInt(color+color,16)/255;});return results;}else if(colorPatterns.HEX8.test(str)){// #rrggbbaa results=colorPatterns.HEX8.exec(str).slice(1).map(function(color){return parseInt(color,16)/255;});return results;}else if(colorPatterns.RGB.test(str)){// rgb(R,G,B) results=colorPatterns.RGB.exec(str).slice(1).map(function(color){return color/255;});results[3]=1;return results;}else if(colorPatterns.RGB_PERCENT.test(str)){// rgb(R%,G%,B%) results=colorPatterns.RGB_PERCENT.exec(str).slice(1).map(function(color){return parseFloat(color)/100;});results[3]=1;return results;}else if(colorPatterns.RGBA.test(str)){// rgba(R,G,B,A) results=colorPatterns.RGBA.exec(str).slice(1).map(function(color,idx){if(idx===3){return parseFloat(color);}return color/255;});return results;}else if(colorPatterns.RGBA_PERCENT.test(str)){// rgba(R%,G%,B%,A%) results=colorPatterns.RGBA_PERCENT.exec(str).slice(1).map(function(color,idx){if(idx===3){return parseFloat(color);}return parseFloat(color)/100;});return results;}// Try HSLA pattern matching. if(colorPatterns.HSL.test(str)){// hsl(H,S,L) results=colorPatterns.HSL.exec(str).slice(1).map(function(color,idx){if(idx===0){return parseInt(color,10)/360;}return parseInt(color,10)/100;});results[3]=1;}else if(colorPatterns.HSLA.test(str)){// hsla(H,S,L,A) results=colorPatterns.HSLA.exec(str).slice(1).map(function(color,idx){if(idx===0){return parseInt(color,10)/360;}else if(idx===3){return parseFloat(color);}return parseInt(color,10)/100;});}results=results.map(function(value){return Math.max(Math.min(value,1),0);});if(results.length){return color_conversion._hslaToRGBA(results);}// Try HSBA pattern matching. if(colorPatterns.HSB.test(str)){// hsb(H,S,B) results=colorPatterns.HSB.exec(str).slice(1).map(function(color,idx){if(idx===0){return parseInt(color,10)/360;}return parseInt(color,10)/100;});results[3]=1;}else if(colorPatterns.HSBA.test(str)){// hsba(H,S,B,A) results=colorPatterns.HSBA.exec(str).slice(1).map(function(color,idx){if(idx===0){return parseInt(color,10)/360;}else if(idx===3){return parseFloat(color);}return parseInt(color,10)/100;});}if(results.length){// (loop backwards for performance) for(i=results.length-1;i>=0;--i){results[i]=Math.max(Math.min(results[i],1),0);}return color_conversion._hsbaToRGBA(results);}// Input did not match any CSS color pattern: default to white. results=[1,1,1,1];}else if((numArgs===1||numArgs===2)&&typeof r==='number'){// 'Grayscale' mode. /** * For HSB and HSL, interpret the gray level as a brightness/lightness * value (they are equivalent when chroma is zero). For RGB, normalize the * gray level according to the blue maximum. */results[0]=r/maxes[2];results[1]=r/maxes[2];results[2]=r/maxes[2];// Alpha may be undefined, so default it to 100%. if(typeof g==='number'){results[3]=g/maxes[3];}else{results[3]=1;}// Constrain components to the range [0,1]. results=results.map(function(value){return Math.max(Math.min(value,1),0);});}else{throw new Error(arguments+'is not a valid color representation.');}return results;};module.exports=p5.Color;},{"../core/constants":19,"../core/main":25,"./color_conversion":15}],18:[function(_dereq_,module,exports){/** * @module Color * @submodule Setting * @for p5 * @requires core * @requires constants */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');_dereq_('./p5.Color');/** * The <a href="#/p5/background">background()</a> function sets the color used for the background of the * p5.js canvas. The default background is light gray. This function is * typically used within <a href="#/p5/draw">draw()</a> to clear the display window at the beginning * of each frame, but it can be used inside <a href="#/p5/setup">setup()</a> to set the background on * the first frame of animation or if the background need only be set once. * <br><br> * The color is either specified in terms of the RGB, HSB, or HSL color * depending on the current <a href="#/p5/colorMode">colorMode</a>. (The default color space is RGB, with * each value in the range from 0 to 255). The alpha range by default is also 0 to 255. * <br><br> * If a single string argument is provided, RGB, RGBA and Hex CSS color strings * and all named color strings are supported. In this case, an alpha number * value as a second argument is not supported, the RGBA form should be used. * <br><br> * A <a href="#/p5.Color">p5.Color</a> object can also be provided to set the background color. * <br><br> * A <a href="#/p5.Image">p5.Image</a> can also be provided to set the background image. * * @method background * @param {p5.Color} color any value created by the <a href="#/p5/color">color()</a> function * @chainable * * @example * <div> * <code> * // Grayscale integer value * background(51); * </code> * </div> * * <div> * <code> * // R, G & B integer values * background(255, 204, 0); * </code> * </div> * * <div> * <code> * // H, S & B integer values * colorMode(HSB); * background(255, 204, 100); * </code> * </div> * * <div> * <code> * // Named SVG/CSS color string * background('red'); * </code> * </div> * * <div> * <code> * // three-digit hexadecimal RGB notation * background('#fae'); * </code> * </div> * * <div> * <code> * // six-digit hexadecimal RGB notation * background('#222222'); * </code> * </div> * * <div> * <code> * // integer RGB notation * background('rgb(0,255,0)'); * </code> * </div> * * <div> * <code> * // integer RGBA notation * background('rgba(0,255,0, 0.25)'); * </code> * </div> * * <div> * <code> * // percentage RGB notation * background('rgb(100%,0%,10%)'); * </code> * </div> * * <div> * <code> * // percentage RGBA notation * background('rgba(100%,0%,100%,0.5)'); * </code> * </div> * * <div> * <code> * // p5 Color object * background(color(0, 0, 255)); * </code> * </div> * * @alt * canvas with darkest charcoal grey background. * canvas with yellow background. * canvas with royal blue background. * canvas with red background. * canvas with pink background. * canvas with black background. * canvas with bright green background. * canvas with soft green background. * canvas with red background. * canvas with light purple background. * canvas with blue background. *//** * @method background * @param {String} colorstring color string, possible formats include: integer * rgb() or rgba(), percentage rgb() or rgba(), * 3-digit hex, 6-digit hex * @param {Number} [a] opacity of the background relative to current * color range (default is 0-255) * @chainable *//** * @method background * @param {Number} gray specifies a value between white and black * @param {Number} [a] * @chainable *//** * @method background * @param {Number} v1 red or hue value (depending on the current color * mode) * @param {Number} v2 green or saturation value (depending on the current * color mode) * @param {Number} v3 blue or brightness value (depending on the current * color mode) * @param {Number} [a] * @chainable *//** * @method background * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color * @chainable *//** * @method background * @param {p5.Image} image image created with <a href="#/p5/loadImage">loadImage()</a> or <a href="#/p5/createImage">createImage()</a>, * to set as background * (must be same size as the sketch window) * @param {Number} [a] * @chainable */p5.prototype.background=function(){if(arguments[0]instanceof p5.Image){this.image(arguments[0],0,0,this.width,this.height);}else{this._renderer.background.apply(this._renderer,arguments);}return this;};/** * Clears the pixels within a buffer. This function only works on p5.Canvas * objects created with the <a href="#/p5/createCanvas">createCanvas()</a> function; it won't work with the * main display window. Unlike the main graphics context, pixels in * additional graphics areas created with <a href="#/p5/createGraphics">createGraphics()</a> can be entirely * or partially transparent. This function clears everything to make all of * the pixels 100% transparent. * * @method clear * @chainable * @example * <div> * <code> * // Clear the screen on mouse press. * function setup() { * createCanvas(100, 100); * } * * function draw() { * ellipse(mouseX, mouseY, 20, 20); * } * * function mousePressed() { * clear(); * } * </code> * </div> * * @alt * 20x20 white ellipses are continually drawn at mouse x and y coordinates. * */p5.prototype.clear=function(){this._renderer.clear();return this;};/** * <a href="#/p5/colorMode">colorMode()</a> changes the way p5.js interprets color data. By default, the * parameters for <a href="#/p5/fill">fill()</a>, <a href="#/p5/stroke">stroke()</a>, <a href="#/p5/background">background()</a>, and <a href="#/p5/color">color()</a> are defined by * values between 0 and 255 using the RGB color model. This is equivalent to * setting colorMode(RGB, 255). Setting colorMode(HSB) lets you use the HSB * system instead. By default, this is colorMode(HSB, 360, 100, 100, 1). You * can also use HSL. * <br><br> * Note: existing color objects remember the mode that they were created in, * so you can change modes as you like without affecting their appearance. * * * @method colorMode * @param {Constant} mode either RGB, HSB or HSL, corresponding to * Red/Green/Blue and Hue/Saturation/Brightness * (or Lightness) * @param {Number} [max] range for all values * @chainable * * @example * <div> * <code> * noStroke(); * colorMode(RGB, 100); * for (var i = 0; i < 100; i++) { * for (var j = 0; j < 100; j++) { * stroke(i, j, 0); * point(i, j); * } * } * </code> * </div> * * <div> * <code> * noStroke(); * colorMode(HSB, 100); * for (var i = 0; i < 100; i++) { * for (var j = 0; j < 100; j++) { * stroke(i, j, 100); * point(i, j); * } * } * </code> * </div> * * <div> * <code> * colorMode(RGB, 255); * var c = color(127, 255, 0); * * colorMode(RGB, 1); * var myColor = c._getRed(); * text(myColor, 10, 10, 80, 80); * </code> * </div> * * <div> * <code> * noFill(); * colorMode(RGB, 255, 255, 255, 1); * background(255); * * strokeWeight(4); * stroke(255, 0, 10, 0.3); * ellipse(40, 40, 50, 50); * ellipse(50, 50, 40, 40); * </code> * </div> * * @alt *Green to red gradient from bottom L to top R. shading originates from top left. *Rainbow gradient from left to right. Brightness increasing to white at top. *unknown image. *50x50 ellipse at middle L & 40x40 ellipse at center. Transluscent pink outlines. * *//** * @method colorMode * @param {Constant} mode * @param {Number} max1 range for the red or hue depending on the * current color mode * @param {Number} max2 range for the green or saturation depending * on the current color mode * @param {Number} max3 range for the blue or brightness/lighntess * depending on the current color mode * @param {Number} [maxA] range for the alpha * @chainable */p5.prototype.colorMode=function(mode,max1,max2,max3,maxA){p5._validateParameters('colorMode',arguments);if(mode===constants.RGB||mode===constants.HSB||mode===constants.HSL){// Set color mode. this._colorMode=mode;// Set color maxes. var maxes=this._colorMaxes[mode];if(arguments.length===2){maxes[0]=max1;// Red maxes[1]=max1;// Green maxes[2]=max1;// Blue maxes[3]=max1;// Alpha }else if(arguments.length===4){maxes[0]=max1;// Red maxes[1]=max2;// Green maxes[2]=max3;// Blue }else if(arguments.length===5){maxes[0]=max1;// Red maxes[1]=max2;// Green maxes[2]=max3;// Blue maxes[3]=maxA;// Alpha }}return this;};/** * Sets the color used to fill shapes. For example, if you run * fill(204, 102, 0), all subsequent shapes will be filled with orange. This * color is either specified in terms of the RGB or HSB color depending on * the current <a href="#/p5/colorMode">colorMode()</a>. (The default color space is RGB, with each value * in the range from 0 to 255). The alpha range by default is also 0 to 255. * <br><br> * If a single string argument is provided, RGB, RGBA and Hex CSS color strings * and all named color strings are supported. In this case, an alpha number * value as a second argument is not supported, the RGBA form should be used. * <br><br> * A p5 <a href="#/p5.Color">Color</a> object can also be provided to set the fill color. * * @method fill * @param {Number} v1 red or hue value relative to * the current color range * @param {Number} v2 green or saturation value * relative to the current color range * @param {Number} v3 blue or brightness value * relative to the current color range * @param {Number} [alpha] * @chainable * @example * <div> * <code> * // Grayscale integer value * fill(51); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // R, G & B integer values * fill(255, 204, 0); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // H, S & B integer values * colorMode(HSB); * fill(255, 204, 100); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // Named SVG/CSS color string * fill('red'); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // three-digit hexadecimal RGB notation * fill('#fae'); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // six-digit hexadecimal RGB notation * fill('#222222'); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // integer RGB notation * fill('rgb(0,255,0)'); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // integer RGBA notation * fill('rgba(0,255,0, 0.25)'); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // percentage RGB notation * fill('rgb(100%,0%,10%)'); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // percentage RGBA notation * fill('rgba(100%,0%,100%,0.5)'); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // p5 Color object * fill(color(0, 0, 255)); * rect(20, 20, 60, 60); * </code> * </div> * @alt * 60x60 dark charcoal grey rect with black outline in center of canvas. * 60x60 yellow rect with black outline in center of canvas. * 60x60 royal blue rect with black outline in center of canvas. * 60x60 red rect with black outline in center of canvas. * 60x60 pink rect with black outline in center of canvas. * 60x60 black rect with black outline in center of canvas. * 60x60 light green rect with black outline in center of canvas. * 60x60 soft green rect with black outline in center of canvas. * 60x60 red rect with black outline in center of canvas. * 60x60 dark fushcia rect with black outline in center of canvas. * 60x60 blue rect with black outline in center of canvas. *//** * @method fill * @param {String} value a color string * @chainable *//** * @method fill * @param {Number} gray a gray value * @param {Number} [alpha] * @chainable *//** * @method fill * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color * @chainable *//** * @method fill * @param {p5.Color} color the fill color * @chainable */p5.prototype.fill=function(){this._renderer._setProperty('_fillSet',true);this._renderer._setProperty('_doFill',true);this._renderer.fill.apply(this._renderer,arguments);return this;};/** * Disables filling geometry. If both <a href="#/p5/noStroke">noStroke()</a> and <a href="#/p5/noFill">noFill()</a> are called, * nothing will be drawn to the screen. * * @method noFill * @chainable * @example * <div> * <code> * rect(15, 10, 55, 55); * noFill(); * rect(20, 20, 60, 60); * </code> * </div> * * <div modernizr='webgl'> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(0); * noFill(); * stroke(100, 100, 240); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(45, 45, 45); * } * </code> * </div> * * @alt * white rect top middle and noFill rect center. Both 60x60 with black outlines. * black canvas with purple cube wireframe spinning */p5.prototype.noFill=function(){this._renderer._setProperty('_doFill',false);return this;};/** * Disables drawing the stroke (outline). If both <a href="#/p5/noStroke">noStroke()</a> and <a href="#/p5/noFill">noFill()</a> * are called, nothing will be drawn to the screen. * * @method noStroke * @chainable * @example * <div> * <code> * noStroke(); * rect(20, 20, 60, 60); * </code> * </div> * * <div modernizr='webgl'> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(0); * noStroke(); * fill(240, 150, 150); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(45, 45, 45); * } * </code> * </div> * * @alt * 60x60 white rect at center. no outline. * black canvas with pink cube spinning */p5.prototype.noStroke=function(){this._renderer._setProperty('_doStroke',false);return this;};/** * Sets the color used to draw lines and borders around shapes. This color * is either specified in terms of the RGB or HSB color depending on the * current <a href="#/p5/colorMode">colorMode()</a> (the default color space is RGB, with each value in * the range from 0 to 255). The alpha range by default is also 0 to 255. * <br><br> * If a single string argument is provided, RGB, RGBA and Hex CSS color * strings and all named color strings are supported. In this case, an alpha * number value as a second argument is not supported, the RGBA form should be * used. * <br><br> * A p5 <a href="#/p5.Color">Color</a> object can also be provided to set the stroke color. * * * @method stroke * @param {Number} v1 red or hue value relative to * the current color range * @param {Number} v2 green or saturation value * relative to the current color range * @param {Number} v3 blue or brightness value * relative to the current color range * @param {Number} [alpha] * @chainable * * @example * <div> * <code> * // Grayscale integer value * strokeWeight(4); * stroke(51); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // R, G & B integer values * stroke(255, 204, 0); * strokeWeight(4); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // H, S & B integer values * colorMode(HSB); * strokeWeight(4); * stroke(255, 204, 100); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // Named SVG/CSS color string * stroke('red'); * strokeWeight(4); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // three-digit hexadecimal RGB notation * stroke('#fae'); * strokeWeight(4); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // six-digit hexadecimal RGB notation * stroke('#222222'); * strokeWeight(4); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // integer RGB notation * stroke('rgb(0,255,0)'); * strokeWeight(4); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // integer RGBA notation * stroke('rgba(0,255,0,0.25)'); * strokeWeight(4); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // percentage RGB notation * stroke('rgb(100%,0%,10%)'); * strokeWeight(4); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // percentage RGBA notation * stroke('rgba(100%,0%,100%,0.5)'); * strokeWeight(4); * rect(20, 20, 60, 60); * </code> * </div> * * <div> * <code> * // p5 Color object * stroke(color(0, 0, 255)); * strokeWeight(4); * rect(20, 20, 60, 60); * </code> * </div> * * @alt * 60x60 white rect at center. Dark charcoal grey outline. * 60x60 white rect at center. Yellow outline. * 60x60 white rect at center. Royal blue outline. * 60x60 white rect at center. Red outline. * 60x60 white rect at center. Pink outline. * 60x60 white rect at center. Black outline. * 60x60 white rect at center. Bright green outline. * 60x60 white rect at center. Soft green outline. * 60x60 white rect at center. Red outline. * 60x60 white rect at center. Dark fushcia outline. * 60x60 white rect at center. Blue outline. *//** * @method stroke * @param {String} value a color string * @chainable *//** * @method stroke * @param {Number} gray a gray value * @param {Number} [alpha] * @chainable *//** * @method stroke * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color * @chainable *//** * @method stroke * @param {p5.Color} color the stroke color * @chainable */p5.prototype.stroke=function(){this._renderer._setProperty('_strokeSet',true);this._renderer._setProperty('_doStroke',true);this._renderer.stroke.apply(this._renderer,arguments);return this;};module.exports=p5;},{"../core/constants":19,"../core/main":25,"./p5.Color":17}],19:[function(_dereq_,module,exports){/** * @module Constants * @submodule Constants * @for p5 */'use strict';var PI=Math.PI;module.exports={// GRAPHICS RENDERER /** * @property {String} P2D * @final */P2D:'p2d',/** * @property {String} WEBGL * @final */WEBGL:'webgl',// ENVIRONMENT /** * @property {String} ARROW * @final */ARROW:'default',/** * @property {String} CROSS * @final */CROSS:'crosshair',/** * @property {String} HAND * @final */HAND:'pointer',/** * @property {String} MOVE * @final */MOVE:'move',/** * @property {String} TEXT * @final */TEXT:'text',/** * @property {String} WAIT * @final */WAIT:'wait',// TRIGONOMETRY /** * HALF_PI is a mathematical constant with the value * 1.57079632679489661923. It is half the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>. * * @property {Number} HALF_PI * @final * * @example * <div><code> * arc(50, 50, 80, 80, 0, HALF_PI); * </code></div> * * @alt * 80x80 white quarter-circle with curve toward bottom right of canvas. * */HALF_PI:PI/2,/** * PI is a mathematical constant with the value * 3.14159265358979323846. It is the ratio of the circumference * of a circle to its diameter. It is useful in combination with * the trigonometric functions <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>. * * @property {Number} PI * @final * * @example * <div><code> * arc(50, 50, 80, 80, 0, PI); * </code></div> * * @alt * white half-circle with curve toward bottom of canvas. * */PI:PI,/** * QUARTER_PI is a mathematical constant with the value 0.7853982. * It is one quarter the ratio of the circumference of a circle to * its diameter. It is useful in combination with the trigonometric * functions <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>. * * @property {Number} QUARTER_PI * @final * * @example * <div><code> * arc(50, 50, 80, 80, 0, QUARTER_PI); * </code></div> * * @alt * white eighth-circle rotated about 40 degrees with curve bottom right canvas. * */QUARTER_PI:PI/4,/** * TAU is an alias for TWO_PI, a mathematical constant with the * value 6.28318530717958647693. It is twice the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>. * * @property {Number} TAU * @final * * @example * <div><code> * arc(50, 50, 80, 80, 0, TAU); * </code></div> * * @alt * 80x80 white ellipse shape in center of canvas. * */TAU:PI*2,/** * TWO_PI is a mathematical constant with the value * 6.28318530717958647693. It is twice the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>. * * @property {Number} TWO_PI * @final * * @example * <div><code> * arc(50, 50, 80, 80, 0, TWO_PI); * </code></div> * * @alt * 80x80 white ellipse shape in center of canvas. * */TWO_PI:PI*2,/** * Constant to be used with <a href="#/p5/angleMode">angleMode()</a> function, to set the mode which * p5.js interprates and calculates angles (either DEGREES or RADIANS). * @property {String} DEGREES * @final * * @example * <div class='norender'><code> * function setup() { * angleMode(DEGREES); * } * </code></div> */DEGREES:'degrees',/** * Constant to be used with <a href="#/p5/angleMode">angleMode()</a> function, to set the mode which * p5.js interprates and calculates angles (either RADIANS or DEGREES). * @property {String} RADIANS * @final * * @example * <div class='norender'><code> * function setup() { * angleMode(RADIANS); * } * </code></div> */RADIANS:'radians',DEG_TO_RAD:PI/180.0,RAD_TO_DEG:180.0/PI,// SHAPE /** * @property {String} CORNER * @final */CORNER:'corner',/** * @property {String} CORNERS * @final */CORNERS:'corners',/** * @property {String} RADIUS * @final */RADIUS:'radius',/** * @property {String} RIGHT * @final */RIGHT:'right',/** * @property {String} LEFT * @final */LEFT:'left',/** * @property {String} CENTER * @final */CENTER:'center',/** * @property {String} TOP * @final */TOP:'top',/** * @property {String} BOTTOM * @final */BOTTOM:'bottom',/** * @property {String} BASELINE * @final * @default alphabetic */BASELINE:'alphabetic',/** * @property {Number} POINTS * @final * @default 0x0000 */POINTS:0x0000,/** * @property {Number} LINES * @final * @default 0x0001 */LINES:0x0001,/** * @property {Number} LINE_STRIP * @final * @default 0x0003 */LINE_STRIP:0x0003,/** * @property {Number} LINE_LOOP * @final * @default 0x0002 */LINE_LOOP:0x0002,/** * @property {Number} TRIANGLES * @final * @default 0x0004 */TRIANGLES:0x0004,/** * @property {Number} TRIANGLE_FAN * @final * @default 0x0006 */TRIANGLE_FAN:0x0006,/** * @property {Number} TRIANGLE_STRIP * @final * @default 0x0005 */TRIANGLE_STRIP:0x0005,/** * @property {String} QUADS * @final */QUADS:'quads',/** * @property {String} QUAD_STRIP * @final * @default quad_strip */QUAD_STRIP:'quad_strip',/** * @property {String} CLOSE * @final */CLOSE:'close',/** * @property {String} OPEN * @final */OPEN:'open',/** * @property {String} CHORD * @final */CHORD:'chord',/** * @property {String} PIE * @final */PIE:'pie',/** * @property {String} PROJECT * @final * @default square */PROJECT:'square',// PEND: careful this is counterintuitive /** * @property {String} SQUARE * @final * @default butt */SQUARE:'butt',/** * @property {String} ROUND * @final */ROUND:'round',/** * @property {String} BEVEL * @final */BEVEL:'bevel',/** * @property {String} MITER * @final */MITER:'miter',// COLOR /** * @property {String} RGB * @final */RGB:'rgb',/** * @property {String} HSB * @final */HSB:'hsb',/** * @property {String} HSL * @final */HSL:'hsl',// DOM EXTENSION /** * @property {String} AUTO * @final */AUTO:'auto',// INPUT ALT:18,BACKSPACE:8,CONTROL:17,DELETE:46,DOWN_ARROW:40,ENTER:13,ESCAPE:27,LEFT_ARROW:37,OPTION:18,RETURN:13,RIGHT_ARROW:39,SHIFT:16,TAB:9,UP_ARROW:38,// RENDERING /** * @property {String} BLEND * @final * @default source-over */BLEND:'source-over',/** * @property {String} ADD * @final * @default lighter */ADD:'lighter',//ADD: 'add', // //SUBTRACT: 'subtract', // /** * @property {String} DARKEST * @final */DARKEST:'darken',/** * @property {String} LIGHTEST * @final * @default lighten */LIGHTEST:'lighten',/** * @property {String} DIFFERENCE * @final */DIFFERENCE:'difference',/** * @property {String} EXCLUSION * @final */EXCLUSION:'exclusion',/** * @property {String} MULTIPLY * @final */MULTIPLY:'multiply',/** * @property {String} SCREEN * @final */SCREEN:'screen',/** * @property {String} REPLACE * @final * @default copy */REPLACE:'copy',/** * @property {String} OVERLAY * @final */OVERLAY:'overlay',/** * @property {String} HARD_LIGHT * @final */HARD_LIGHT:'hard-light',/** * @property {String} SOFT_LIGHT * @final */SOFT_LIGHT:'soft-light',/** * @property {String} DODGE * @final * @default color-dodge */DODGE:'color-dodge',/** * @property {String} BURN * @final * @default color-burn */BURN:'color-burn',// FILTERS /** * @property {String} THRESHOLD * @final */THRESHOLD:'threshold',/** * @property {String} GRAY * @final */GRAY:'gray',/** * @property {String} OPAQUE * @final */OPAQUE:'opaque',/** * @property {String} INVERT * @final */INVERT:'invert',/** * @property {String} POSTERIZE * @final */POSTERIZE:'posterize',/** * @property {String} DILATE * @final */DILATE:'dilate',/** * @property {String} ERODE * @final */ERODE:'erode',/** * @property {String} BLUR * @final */BLUR:'blur',// TYPOGRAPHY /** * @property {String} NORMAL * @final */NORMAL:'normal',/** * @property {String} ITALIC * @final */ITALIC:'italic',/** * @property {String} BOLD * @final */BOLD:'bold',// TYPOGRAPHY-INTERNAL _DEFAULT_TEXT_FILL:'#000000',_DEFAULT_LEADMULT:1.25,_CTX_MIDDLE:'middle',// VERTICES LINEAR:'linear',QUADRATIC:'quadratic',BEZIER:'bezier',CURVE:'curve',// WEBGL DRAWMODES STROKE:'stroke',FILL:'fill',TEXTURE:'texture',IMMEDIATE:'immediate',//WEBGL TEXTURE WRAP AND FILTERING // LINEAR already exists above NEAREST:'nearest',REPEAT:'repeat',CLAMP:'clamp',MIRROR:'mirror',// DEVICE-ORIENTATION /** * @property {String} LANDSCAPE * @final */LANDSCAPE:'landscape',/** * @property {String} PORTRAIT * @final */PORTRAIT:'portrait',// DEFAULTS _DEFAULT_STROKE:'#000000',_DEFAULT_FILL:'#FFFFFF',/** * @property {String} GRID * @final */GRID:'grid',/** * @property {String} AXES * @final */AXES:'axes'};},{}],20:[function(_dereq_,module,exports){/** * @module Environment * @submodule Environment * @for p5 * @requires core * @requires constants */'use strict';var p5=_dereq_('./main');var C=_dereq_('./constants');var standardCursors=[C.ARROW,C.CROSS,C.HAND,C.MOVE,C.TEXT,C.WAIT];p5.prototype._frameRate=0;p5.prototype._lastFrameTime=window.performance.now();p5.prototype._targetFrameRate=60;var _windowPrint=window.print;/** * The <a href="#/p5/print">print()</a> function writes to the console area of your browser. * This function is often helpful for looking at the data a program is * producing. This function creates a new line of text for each call to * the function. Individual elements can be * separated with quotes ("") and joined with the addition operator (+). * * @method print * @param {Any} contents any combination of Number, String, Object, Boolean, * Array to print * @example * <div><code class='norender'> * var x = 10; * print('The value of x is ' + x); * // prints "The value of x is 10" * </code></div> * @alt * default grey canvas */p5.prototype.print=function(){if(!arguments.length){_windowPrint();}else{console.log.apply(console,arguments);}};/** * The system variable <a href="#/p5/frameCount">frameCount</a> contains the number of frames that have * been displayed since the program started. Inside <a href="#/p5/setup">setup()</a> the value is 0, * after the first iteration of draw it is 1, etc. * * @property {Integer} frameCount * @readOnly * @example * <div><code> * function setup() { * frameRate(30); * textSize(30); * textAlign(CENTER); * } * * function draw() { * background(200); * text(frameCount, width / 2, height / 2); * } </code></div> * * @alt * numbers rapidly counting upward with frame count set to 30. * */p5.prototype.frameCount=0;/** * Confirms if the window a p5.js program is in is "focused," meaning that * the sketch will accept mouse or keyboard input. This variable is * "true" if the window is focused and "false" if not. * * @property {Boolean} focused * @readOnly * @example * <div><code> * // To demonstrate, put two windows side by side. * // Click on the window that the p5 sketch isn't in! * function draw() { * background(200); * noStroke(); * fill(0, 200, 0); * ellipse(25, 25, 50, 50); * * if (!focused) { // or "if (focused === false)" * stroke(200, 0, 0); * line(0, 0, 100, 100); * line(100, 0, 0, 100); * } * } * </code></div> * * @alt * green 50x50 ellipse at top left. Red X covers canvas when page focus changes * */p5.prototype.focused=document.hasFocus();/** * Sets the cursor to a predefined symbol or an image, or makes it visible * if already hidden. If you are trying to set an image as the cursor, the * recommended size is 16x16 or 32x32 pixels. The values for parameters x and y * must be less than the dimensions of the image. * * @method cursor * @param {String|Constant} type either ARROW, CROSS, HAND, MOVE, TEXT, or * WAIT, or path for image * @param {Number} [x] the horizontal active spot of the cursor * @param {Number} [y] the vertical active spot of the cursor * @example * <div><code> * // Move the mouse left and right across the image * // to see the cursor change from a cross to a hand * function draw() { * line(width / 2, 0, width / 2, height); * if (mouseX < 50) { * cursor(CROSS); * } else { * cursor(HAND); * } * } * </code></div> * * @alt * horizontal line divides canvas. cursor on left is a cross, right is hand. * */p5.prototype.cursor=function(type,x,y){var cursor='auto';var canvas=this._curElement.elt;if(standardCursors.indexOf(type)>-1){// Standard css cursor cursor=type;}else if(typeof type==='string'){var coords='';if(x&&y&&typeof x==='number'&&typeof y==='number'){// Note that x and y values must be unit-less positive integers < 32 // https://developer.mozilla.org/en-US/docs/Web/CSS/cursor coords=x+' '+y;}if(type.substring(0,7)==='http://'||type.substring(0,8)==='https://'){// Image (absolute url) cursor='url('+type+') '+coords+', auto';}else if(/\.(cur|jpg|jpeg|gif|png|CUR|JPG|JPEG|GIF|PNG)$/.test(type)){// Image file (relative path) - Separated for performance reasons cursor='url('+type+') '+coords+', auto';}else{// Any valid string for the css cursor property cursor=type;}}canvas.style.cursor=cursor;};/** * Specifies the number of frames to be displayed every second. For example, * the function call frameRate(30) will attempt to refresh 30 times a second. * If the processor is not fast enough to maintain the specified rate, the * frame rate will not be achieved. Setting the frame rate within <a href="#/p5/setup">setup()</a> is * recommended. The default frame rate is based on the frame rate of the display * (here also called "refresh rate"), which is set to 60 frames per second on most * computers. A frame rate of 24 frames per second (usual for movies) or above * will be enough for smooth animations * This is the same as setFrameRate(val). * <br><br> * Calling <a href="#/p5/frameRate">frameRate()</a> with no arguments returns the current framerate. The * draw function must run at least once before it will return a value. This * is the same as <a href="#/p5/getFrameRate">getFrameRate()</a>. * <br><br> * Calling <a href="#/p5/frameRate">frameRate()</a> with arguments that are not of the type numbers * or are non positive also returns current framerate. * * @method frameRate * @param {Number} fps number of frames to be displayed every second * @chainable * * @example * * <div><code> * var rectX = 0; * var fr = 30; //starting FPS * var clr; * * function setup() { * background(200); * frameRate(fr); // Attempt to refresh at starting FPS * clr = color(255, 0, 0); * } * * function draw() { * background(200); * rectX = rectX += 1; // Move Rectangle * * if (rectX >= width) { // If you go off screen. * if (fr === 30) { * clr = color(0, 0, 255); * fr = 10; * frameRate(fr); // make frameRate 10 FPS * } else { * clr = color(255, 0, 0); * fr = 30; * frameRate(fr); // make frameRate 30 FPS * } * rectX = 0; * } * fill(clr); * rect(rectX, 40, 20, 20); * } * </code></div> * * @alt * blue rect moves left to right, followed by red rect moving faster. Loops. * *//** * @method frameRate * @return {Number} current frameRate */p5.prototype.frameRate=function(fps){p5._validateParameters('frameRate',arguments);if(typeof fps!=='number'||fps<0){return this._frameRate;}else{this._setProperty('_targetFrameRate',fps);this._runFrames();return this;}};/** * Returns the current framerate. * * @private * @return {Number} current frameRate */p5.prototype.getFrameRate=function(){return this.frameRate();};/** * Specifies the number of frames to be displayed every second. For example, * the function call frameRate(30) will attempt to refresh 30 times a second. * If the processor is not fast enough to maintain the specified rate, the * frame rate will not be achieved. Setting the frame rate within <a href="#/p5/setup">setup()</a> is * recommended. The default rate is 60 frames per second. * * Calling <a href="#/p5/frameRate">frameRate()</a> with no arguments returns the current framerate. * * @private * @param {Number} [fps] number of frames to be displayed every second */p5.prototype.setFrameRate=function(fps){return this.frameRate(fps);};/** * Hides the cursor from view. * * @method noCursor * @example * <div><code> * function setup() { * noCursor(); * } * * function draw() { * background(200); * ellipse(mouseX, mouseY, 10, 10); * } * </code></div> * * * @alt * cursor becomes 10x 10 white ellipse the moves with mouse x and y. * */p5.prototype.noCursor=function(){this._curElement.elt.style.cursor='none';};/** * System variable that stores the width of the screen display according to The * default <a href="#/p5/pixelDensity">pixelDensity</a>. This is used to run a * full-screen program on any display size. To return actual screen size, * multiply this by pixelDensity. * * @property {Number} displayWidth * @readOnly * @example * <div class="norender"><code> * createCanvas(displayWidth, displayHeight); * </code></div> * * @alt * cursor becomes 10x 10 white ellipse the moves with mouse x and y. * */p5.prototype.displayWidth=screen.width;/** * System variable that stores the height of the screen display according to The * default <a href="#/p5/pixelDensity">pixelDensity</a>. This is used to run a * full-screen program on any display size. To return actual screen size, * multiply this by pixelDensity. * * @property {Number} displayHeight * @readOnly * @example * <div class="norender"><code> * createCanvas(displayWidth, displayHeight); * </code></div> * * @alt * no display. * */p5.prototype.displayHeight=screen.height;/** * System variable that stores the width of the inner window, it maps to * window.innerWidth. * * @property {Number} windowWidth * @readOnly * @example * <div class="norender"><code> * createCanvas(windowWidth, windowHeight); * </code></div> * * @alt * no display. * */p5.prototype.windowWidth=getWindowWidth();/** * System variable that stores the height of the inner window, it maps to * window.innerHeight. * * @property {Number} windowHeight * @readOnly * @example * <div class="norender"><code> * createCanvas(windowWidth, windowHeight); * </code></div> *@alt * no display. * */p5.prototype.windowHeight=getWindowHeight();/** * The <a href="#/p5/windowResized">windowResized()</a> function is called once every time the browser window * is resized. This is a good place to resize the canvas or do any other * adjustments to accommodate the new window size. * * @method windowResized * @example * <div class="norender"><code> * function setup() { * createCanvas(windowWidth, windowHeight); * } * * function draw() { * background(0, 100, 200); * } * * function windowResized() { * resizeCanvas(windowWidth, windowHeight); * } * </code></div> * @alt * no display. */p5.prototype._onresize=function(e){this._setProperty('windowWidth',getWindowWidth());this._setProperty('windowHeight',getWindowHeight());var context=this._isGlobal?window:this;var executeDefault;if(typeof context.windowResized==='function'){executeDefault=context.windowResized(e);if(executeDefault!==undefined&&!executeDefault){e.preventDefault();}}};function getWindowWidth(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth||0;}function getWindowHeight(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight||0;}/** * System variable that stores the width of the drawing canvas. This value * is set by the first parameter of the <a href="#/p5/createCanvas">createCanvas()</a> function. * For example, the function call createCanvas(320, 240) sets the width * variable to the value 320. The value of width defaults to 100 if * <a href="#/p5/createCanvas">createCanvas()</a> is not used in a program. * * @property {Number} width * @readOnly */p5.prototype.width=0;/** * System variable that stores the height of the drawing canvas. This value * is set by the second parameter of the <a href="#/p5/createCanvas">createCanvas()</a> function. For * example, the function call createCanvas(320, 240) sets the height * variable to the value 240. The value of height defaults to 100 if * <a href="#/p5/createCanvas">createCanvas()</a> is not used in a program. * * @property {Number} height * @readOnly */p5.prototype.height=0;/** * If argument is given, sets the sketch to fullscreen or not based on the * value of the argument. If no argument is given, returns the current * fullscreen state. Note that due to browser restrictions this can only * be called on user input, for example, on mouse press like the example * below. * * @method fullscreen * @param {Boolean} [val] whether the sketch should be in fullscreen mode * or not * @return {Boolean} current fullscreen state * @example * <div> * <code> * // Clicking in the box toggles fullscreen on and off. * function setup() { * background(200); * } * function mousePressed() { * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { * var fs = fullscreen(); * fullscreen(!fs); * } * } * </code> * </div> * * @alt * no display. * */p5.prototype.fullscreen=function(val){p5._validateParameters('fullscreen',arguments);// no arguments, return fullscreen or not if(typeof val==='undefined'){return document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement;}else{// otherwise set to fullscreen or not if(val){launchFullscreen(document.documentElement);}else{exitFullscreen();}}};/** * Sets the pixel scaling for high pixel density displays. By default * pixel density is set to match display density, call pixelDensity(1) * to turn this off. Calling <a href="#/p5/pixelDensity">pixelDensity()</a> with no arguments returns * the current pixel density of the sketch. * * @method pixelDensity * @param {Number} val whether or how much the sketch should scale * @chainable * @example * <div> * <code> * function setup() { * pixelDensity(1); * createCanvas(100, 100); * background(200); * ellipse(width / 2, height / 2, 50, 50); * } * </code> * </div> * <div> * <code> * function setup() { * pixelDensity(3.0); * createCanvas(100, 100); * background(200); * ellipse(width / 2, height / 2, 50, 50); * } * </code> * </div> * * @alt * fuzzy 50x50 white ellipse with black outline in center of canvas. * sharp 50x50 white ellipse with black outline in center of canvas. *//** * @method pixelDensity * @returns {Number} current pixel density of the sketch */p5.prototype.pixelDensity=function(val){p5._validateParameters('pixelDensity',arguments);var returnValue;if(typeof val==='number'){if(val!==this._pixelDensity){this._pixelDensity=val;this._pixelsDirty=true;}returnValue=this;this.resizeCanvas(this.width,this.height,true);// as a side effect, it will clear the canvas }else{returnValue=this._pixelDensity;}return returnValue;};/** * Returns the pixel density of the current display the sketch is running on. * * @method displayDensity * @returns {Number} current pixel density of the display * @example * <div> * <code> * function setup() { * var density = displayDensity(); * pixelDensity(density); * createCanvas(100, 100); * background(200); * ellipse(width / 2, height / 2, 50, 50); * } * </code> * </div> * * @alt * 50x50 white ellipse with black outline in center of canvas. */p5.prototype.displayDensity=function(){return window.devicePixelRatio;};function launchFullscreen(element){var enabled=document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled;if(!enabled){throw new Error('Fullscreen not enabled in this browser.');}if(element.requestFullscreen){element.requestFullscreen();}else if(element.mozRequestFullScreen){element.mozRequestFullScreen();}else if(element.webkitRequestFullscreen){element.webkitRequestFullscreen();}else if(element.msRequestFullscreen){element.msRequestFullscreen();}}function exitFullscreen(){if(document.exitFullscreen){document.exitFullscreen();}else if(document.mozCancelFullScreen){document.mozCancelFullScreen();}else if(document.webkitExitFullscreen){document.webkitExitFullscreen();}else if(document.msExitFullscreen){document.msExitFullscreen();}}/** * Gets the current URL. * @method getURL * @return {String} url * @example * <div> * <code> * var url; * var x = 100; * * function setup() { * fill(0); * noStroke(); * url = getURL(); * } * * function draw() { * background(200); * text(url, x, height / 2); * x--; * } * </code> * </div> * * @alt * current url (http://p5js.org/reference/#/p5/getURL) moves right to left. * */p5.prototype.getURL=function(){return location.href;};/** * Gets the current URL path as an array. * @method getURLPath * @return {String[]} path components * @example * <div class='norender'><code> * function setup() { * var urlPath = getURLPath(); * for (var i = 0; i < urlPath.length; i++) { * text(urlPath[i], 10, i * 20 + 20); * } * } * </code></div> * * @alt *no display * */p5.prototype.getURLPath=function(){return location.pathname.split('/').filter(function(v){return v!=='';});};/** * Gets the current URL params as an Object. * @method getURLParams * @return {Object} URL params * @example * <div class='norender notest'> * <code> * // Example: http://p5js.org?year=2014&month=May&day=15 * * function setup() { * var params = getURLParams(); * text(params.day, 10, 20); * text(params.month, 10, 40); * text(params.year, 10, 60); * } * </code> * </div> * @alt * no display. * */p5.prototype.getURLParams=function(){var re=/[?&]([^&=]+)(?:[&=])([^&=]+)/gim;var m;var v={};while((m=re.exec(location.search))!=null){if(m.index===re.lastIndex){re.lastIndex++;}v[m[1]]=m[2];}return v;};module.exports=p5;},{"./constants":19,"./main":25}],21:[function(_dereq_,module,exports){/** * @for p5 * @requires core */'use strict';var p5=_dereq_('./main');var constants=_dereq_('./constants');if(typeof IS_MINIFIED!=='undefined'){p5._validateParameters=p5._friendlyFileLoadError=function(){};}else{var doFriendlyWelcome=false;// TEMP until we get it all working LM // for parameter validation var dataDoc=_dereq_('../../docs/reference/data.json');var arrDoc=JSON.parse(JSON.stringify(dataDoc));// -- Borrowed from jQuery 1.11.3 -- var class2type={};var toString=class2type.toString;var names=['Boolean','Number','String','Function','Array','Date','RegExp','Object','Error'];for(var n=0;n<names.length;n++){class2type['[object '+names[n]+']']=names[n].toLowerCase();}var getType=function getType(obj){if(obj==null){return obj+'';}return(typeof obj==="undefined"?"undefined":_typeof(obj))==='object'||typeof obj==='function'?class2type[toString.call(obj)]||'object':typeof obj==="undefined"?"undefined":_typeof(obj);};// -- End borrow -- var friendlyWelcome=function friendlyWelcome(){// p5.js brand - magenta: #ED225D //var astrixBgColor = 'transparent'; //var astrixTxtColor = '#ED225D'; //var welcomeBgColor = '#ED225D'; //var welcomeTextColor = 'white'; console.log(' _ \n'+' /\\| |/\\ \n'+" \\ ` ' / \n"+' / , . \\ \n'+' \\/|_|\\/ '+'\n\n> p5.js says: Welcome! '+'This is your friendly debugger. '+'To turn me off switch to using “p5.min.js”.');};/** * Prints out a fancy, colorful message to the console log * * @private * @param {String} message the words to be said * @param {String} func the name of the function to link * @param {Number|String} color CSS color string or error type * * @return console logs */// Wrong number of params, undefined param, wrong type var FILE_LOAD=3;var ERR_PARAMS=3;// p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta // See testColors below for all the color codes and names var typeColors=['#2D7BB6','#EE9900','#4DB200','#C83C00'];var report=function report(message,func,color){if(doFriendlyWelcome){friendlyWelcome();doFriendlyWelcome=false;}if('undefined'===getType(color)){color='#B40033';// dark magenta }else if(getType(color)==='number'){// Type to color color=typeColors[color];}if(func==='loadX'){console.log('> p5.js says: '+message);}else if(func.substring(0,4)==='load'){console.log('> p5.js says: '+message+'[https://github.com/processing/p5.js/wiki/Local-server]');}else{console.log('> p5.js says: '+message+' [http://p5js.org/reference/#p5/'+func+']');}};var errorCases={'0':{fileType:'image',method:'loadImage',message:' hosting the image online,'},'1':{fileType:'XML file',method:'loadXML'},'2':{fileType:'table file',method:'loadTable'},'3':{fileType:'text file',method:'loadStrings'},'4':{fileType:'font',method:'loadFont',message:' hosting the font online,'},'5':{fileType:'json',method:'loadJSON'},'6':{fileType:'file',method:'loadBytes'},'7':{method:'loadX',message:"In case your large file isn't fetched successfully,"+'we recommend splitting the file into smaller segments and fetching those.'}};p5._friendlyFileLoadError=function(errorType,filePath){var errorInfo=errorCases[errorType];var message;if(errorType===7){message=errorInfo.message;}else{message='It looks like there was a problem'+' loading your '+errorInfo.fileType+'.'+' Try checking if the file path ['+filePath+'] is correct,'+(errorInfo.message||'')+' or running a local server.';}report(message,errorInfo.method,FILE_LOAD);};var docCache={};var builtinTypes=['null','number','string','boolean','constant','function','any','integer'];// validateParameters() helper functions: // lookupParamDoc() for querying data.json var lookupParamDoc=function lookupParamDoc(func){// look for the docs in the `data.json` datastructure var ichDot=func.lastIndexOf('.');var funcName=func.substr(ichDot+1);var funcClass=func.substr(0,ichDot)||'p5';var queryResult;var classitems=arrDoc.classitems;for(var ici=0;ici<classitems.length;ici++){var x=classitems[ici];if(x.name===funcName&&x.class===funcClass){queryResult=x;break;}}// different JSON structure for funct with multi-format var overloads=[];if(queryResult.hasOwnProperty('overloads')){// add all the overloads for(var i=0;i<queryResult.overloads.length;i++){overloads.push({formats:queryResult.overloads[i].params});}}else{// no overloads, just add the main method definition overloads.push({formats:queryResult.params||[]});}// parse the parameter types for each overload var mapConstants={};var maxParams=0;overloads.forEach(function(overload){var formats=overload.formats;// keep a record of the maximum number of arguments // this method requires. if(maxParams<formats.length){maxParams=formats.length;}// calculate the minimum number of arguments // this overload requires. var minParams=formats.length;while(minParams>0&&formats[minParams-1].optional){minParams--;}overload.minParams=minParams;// loop through each parameter position, and parse its types formats.forEach(function(format){// split this parameter's types format.types=format.type.split('|').map(function ct(type){// array if(type.substr(type.length-2,2)==='[]'){return{name:type,array:ct(type.substr(0,type.length-2))};}var lowerType=type.toLowerCase();// contant if(lowerType==='constant'){var constant;if(mapConstants.hasOwnProperty(format.name)){constant=mapConstants[format.name];}else{// parse possible constant values from description var myRe=/either\s+(?:[A-Z0-9_]+\s*,?\s*(?:or)?\s*)+/g;var values={};var names=[];constant=mapConstants[format.name]={values:values,names:names};var myArray=myRe.exec(format.description);if(func==='endShape'&&format.name==='mode'){values[constants.CLOSE]=true;names.push('CLOSE');}else{var match=myArray[0];var reConst=/[A-Z0-9_]+/g;var matchConst;while((matchConst=reConst.exec(match))!==null){var name=matchConst[0];if(constants.hasOwnProperty(name)){values[constants[name]]=true;names.push(name);}}}}return{name:type,builtin:lowerType,names:constant.names,values:constant.values};}// function if(lowerType.substr(0,'function'.length)==='function'){lowerType='function';}// builtin if(builtinTypes.indexOf(lowerType)>=0){return{name:type,builtin:lowerType};}// find type's prototype var t=window;var typeParts=type.split('.');// special-case 'p5' since it may be non-global if(typeParts[0]==='p5'){t=p5;typeParts.shift();}typeParts.forEach(function(p){t=t&&t[p];});if(t){return{name:type,prototype:t};}return{name:type,type:lowerType};});});});return{overloads:overloads,maxParams:maxParams};};var isNumber=function isNumber(param){switch(typeof param==="undefined"?"undefined":_typeof(param)){case'number':return true;case'string':return!isNaN(param);default:return false;}};var testParamType=function testParamType(param,type){var isArray=param instanceof Array;var matches=true;if(type.array&&isArray){for(var i=0;i<param.length;i++){var error=testParamType(param[i],type.array);if(error)return error/2;// half error for elements }}else if(type.prototype){matches=param instanceof type.prototype;}else if(type.builtin){switch(type.builtin){case'number':matches=isNumber(param);break;case'integer':matches=isNumber(param)&&Number(param)===Math.floor(param);break;case'boolean':case'any':matches=true;break;case'array':matches=isArray;break;case'string':matches=/*typeof param === 'number' ||*/typeof param==='string';break;case'constant':matches=type.values.hasOwnProperty(param);break;case'function':matches=param instanceof Function;break;case'null':matches=param===null;break;}}else{matches=(typeof param==="undefined"?"undefined":_typeof(param))===type.t;}return matches?0:1;};// testType() for non-object type parameter validation var testParamTypes=function testParamTypes(param,types){var minScore=9999;for(var i=0;minScore>0&&i<types.length;i++){var score=testParamType(param,types[i]);if(minScore>score)minScore=score;}return minScore;};// generate a score (higher is worse) for applying these args to // this overload. var scoreOverload=function scoreOverload(args,argCount,overload,minScore){var score=0;var formats=overload.formats;var minParams=overload.minParams;// check for too few/many args // the score is double number of extra/missing args if(argCount<minParams){score=(minParams-argCount)*2;}else if(argCount>formats.length){score=(argCount-formats.length)*2;}// loop through the formats, adding up the error score for each arg. // quit early if the score gets higher than the previous best overload. for(var p=0;score<=minScore&&p<formats.length;p++){var arg=args[p];var format=formats[p];// '== null' checks for 'null' and typeof 'undefined' if(arg==null){// handle non-optional and non-trailing undefined args if(!format.optional||p<minParams||p<argCount){score+=1;}}else{score+=testParamTypes(arg,format.types);}}return score;};// gets a list of errors for this overload var getOverloadErrors=function getOverloadErrors(args,argCount,overload){var formats=overload.formats;var minParams=overload.minParams;// check for too few/many args if(argCount<minParams){return[{type:'TOO_FEW_ARGUMENTS',argCount:argCount,minParams:minParams}];}else if(argCount>formats.length){return[{type:'TOO_MANY_ARGUMENTS',argCount:argCount,maxParams:formats.length}];}var errorArray=[];for(var p=0;p<formats.length;p++){var arg=args[p];var format=formats[p];// '== null' checks for 'null' and typeof 'undefined' if(arg==null){// handle non-optional and non-trailing undefined args if(!format.optional||p<minParams||p<argCount){errorArray.push({type:'EMPTY_VAR',position:p,format:format});}}else if(testParamTypes(arg,format.types)>0){errorArray.push({type:'WRONG_TYPE',position:p,format:format,arg:arg});}}return errorArray;};// a custom error type, used by the mocha // tests when expecting validation errors p5.ValidationError=function(name){var err=function err(message,func){this.message=message;this.func=func;if('captureStackTrace'in Error)Error.captureStackTrace(this,err);else this.stack=new Error().stack;};err.prototype=Object.create(Error.prototype);err.prototype.name=name;err.prototype.constructor=err;return err;}('ValidationError');// function for generating console.log() msg p5._friendlyParamError=function(errorObj,func){var message;function formatType(){var format=errorObj.format;return format.types.map(function(type){return type.names?type.names.join('|'):type.name;}).join('|');}switch(errorObj.type){case'EMPTY_VAR':message=func+'() was expecting '+formatType()+' for parameter #'+errorObj.position+' (zero-based index), received an empty variable instead.'+' If not intentional, this is often a problem with scope:'+' [https://p5js.org/examples/data-variable-scope.html]';break;case'WRONG_TYPE':var arg=errorObj.arg;var argType=arg instanceof Array?'array':arg===null?'null':arg.name||(typeof arg==="undefined"?"undefined":_typeof(arg));message=func+'() was expecting '+formatType()+' for parameter #'+errorObj.position+' (zero-based index), received '+argType+' instead';break;case'TOO_FEW_ARGUMENTS':message=func+'() was expecting at least '+errorObj.minParams+' arguments, but received only '+errorObj.argCount;break;case'TOO_MANY_ARGUMENTS':message=func+'() was expecting no more than '+errorObj.maxParams+' arguments, but received '+errorObj.argCount;break;}if(message){if(p5._throwValidationErrors){throw new p5.ValidationError(message);}try{var re=/Function\.validateParameters.*[\r\n].*[\r\n].*\(([^)]*)/;var location=re.exec(new Error().stack)[1];if(location){message+=' at '+location;}}catch(err){}report(message+'.',func,ERR_PARAMS);}};/** * Validates parameters * param {String} func the name of the function * param {Array} args user input arguments * * example: * var a; * ellipse(10,10,a,5); * console ouput: * "It looks like ellipse received an empty variable in spot #2." * * example: * ellipse(10,"foo",5,5); * console output: * "ellipse was expecting a number for parameter #1, * received "foo" instead." */p5._validateParameters=function validateParameters(func,args){if(p5.disableFriendlyErrors){return;// skip FES }// lookup the docs in the 'data.json' file var docs=docCache[func]||(docCache[func]=lookupParamDoc(func));var overloads=docs.overloads;// ignore any trailing `undefined` arguments var argCount=args.length;// '== null' checks for 'null' and typeof 'undefined' while(argCount>0&&args[argCount-1]==null){argCount--;}// find the overload with the best score var minScore=99999;var minOverload;for(var i=0;i<overloads.length;i++){var score=scoreOverload(args,argCount,overloads[i],minScore);if(score===0){return;// done! }else if(minScore>score){// this score is better that what we have so far... minScore=score;minOverload=i;}}// this should _always_ be true here... if(minScore>0){// get the errors for the best overload var errorArray=getOverloadErrors(args,argCount,overloads[minOverload]);// generate err msg for(var n=0;n<errorArray.length;n++){p5._friendlyParamError(errorArray[n],func);}}};/** * Prints out all the colors in the color pallete with white text. * For color blindness testing. *//* function testColors() { var str = 'A box of biscuits, a box of mixed biscuits and a biscuit mixer'; report(str, 'print', '#ED225D'); // p5.js magenta report(str, 'print', '#2D7BB6'); // p5.js blue report(str, 'print', '#EE9900'); // p5.js orange report(str, 'print', '#A67F59'); // p5.js light brown report(str, 'print', '#704F21'); // p5.js gold report(str, 'print', '#1CC581'); // auto cyan report(str, 'print', '#FF6625'); // auto orange report(str, 'print', '#79EB22'); // auto green report(str, 'print', '#B40033'); // p5.js darkened magenta report(str, 'print', '#084B7F'); // p5.js darkened blue report(str, 'print', '#945F00'); // p5.js darkened orange report(str, 'print', '#6B441D'); // p5.js darkened brown report(str, 'print', '#2E1B00'); // p5.js darkened gold report(str, 'print', '#008851'); // auto dark cyan report(str, 'print', '#C83C00'); // auto dark orange report(str, 'print', '#4DB200'); // auto dark green } */p5.prototype._validateParameters=p5.validateParameters;}// This is a lazily-defined list of p5 symbols that may be // misused by beginners at top-level code, outside of setup/draw. We'd like // to detect these errors and help the user by suggesting they move them // into setup/draw. // // For more details, see https://github.com/processing/p5.js/issues/1121. var misusedAtTopLevelCode=null;var FAQ_URL='https://github.com/processing/p5.js/wiki/p5.js-overview'+'#why-cant-i-assign-variables-using-p5-functions-and-'+'variables-before-setup';var defineMisusedAtTopLevelCode=function defineMisusedAtTopLevelCode(){var uniqueNamesFound={};var getSymbols=function getSymbols(obj){return Object.getOwnPropertyNames(obj).filter(function(name){if(name[0]==='_'){return false;}if(name in uniqueNamesFound){return false;}uniqueNamesFound[name]=true;return true;}).map(function(name){var type;if(typeof obj[name]==='function'){type='function';}else if(name===name.toUpperCase()){type='constant';}else{type='variable';}return{name:name,type:type};});};misusedAtTopLevelCode=[].concat(getSymbols(p5.prototype),// At present, p5 only adds its constants to p5.prototype during // construction, which may not have happened at the time a // ReferenceError is thrown, so we'll manually add them to our list. getSymbols(_dereq_('./constants')));// This will ultimately ensure that we report the most specific error // possible to the user, e.g. advising them about HALF_PI instead of PI // when their code misuses the former. misusedAtTopLevelCode.sort(function(a,b){return b.name.length-a.name.length;});};var helpForMisusedAtTopLevelCode=function helpForMisusedAtTopLevelCode(e,log){if(!log){log=console.log.bind(console);}if(!misusedAtTopLevelCode){defineMisusedAtTopLevelCode();}// If we find that we're logging lots of false positives, we can // uncomment the following code to avoid displaying anything if the // user's code isn't likely to be using p5's global mode. (Note that // setup/draw are more likely to be defined due to JS function hoisting.) // //if (!('setup' in window || 'draw' in window)) { // return; //} misusedAtTopLevelCode.some(function(symbol){// Note that while just checking for the occurrence of the // symbol name in the error message could result in false positives, // a more rigorous test is difficult because different browsers // log different messages, and the format of those messages may // change over time. // // For example, if the user uses 'PI' in their code, it may result // in any one of the following messages: // // * 'PI' is undefined (Microsoft Edge) // * ReferenceError: PI is undefined (Firefox) // * Uncaught ReferenceError: PI is not defined (Chrome) if(e.message&&e.message.match('\\W?'+symbol.name+'\\W')!==null){log("Did you just try to use p5.js's "+symbol.name+(symbol.type==='function'?'() ':' ')+symbol.type+'? If so, you may want to '+"move it into your sketch's setup() function.\n\n"+'For more details, see: '+FAQ_URL);return true;}});};// Exposing this primarily for unit testing. p5.prototype._helpForMisusedAtTopLevelCode=helpForMisusedAtTopLevelCode;if(document.readyState!=='complete'){window.addEventListener('error',helpForMisusedAtTopLevelCode,false);// Our job is only to catch ReferenceErrors that are thrown when // global (non-instance mode) p5 APIs are used at the top-level // scope of a file, so we'll unbind our error listener now to make // sure we don't log false positives later. window.addEventListener('load',function(){window.removeEventListener('error',helpForMisusedAtTopLevelCode,false);});}module.exports=p5;},{"../../docs/reference/data.json":1,"./constants":19,"./main":25}],22:[function(_dereq_,module,exports){/** * @requires constants */'use strict';var constants=_dereq_('./constants');module.exports={modeAdjust:function modeAdjust(a,b,c,d,mode){if(mode===constants.CORNER){return{x:a,y:b,w:c,h:d};}else if(mode===constants.CORNERS){return{x:a,y:b,w:c-a,h:d-b};}else if(mode===constants.RADIUS){return{x:a-c,y:b-d,w:2*c,h:2*d};}else if(mode===constants.CENTER){return{x:a-c*0.5,y:b-d*0.5,w:c,h:d};}}};},{"./constants":19}],23:[function(_dereq_,module,exports){'use strict';var p5=_dereq_('../core/main');/** * _globalInit * * TODO: ??? * if sketch is on window * assume "global" mode * and instantiate p5 automatically * otherwise do nothing * * @private * @return {Undefined} */var _globalInit=function _globalInit(){if(!window.mocha){// If there is a setup or draw function on the window // then instantiate p5 in "global" mode if((window.setup&&typeof window.setup==='function'||window.draw&&typeof window.draw==='function')&&!p5.instance){new p5();}}};// TODO: ??? // if the page is ready, initialize p5 immediately if(document.readyState==='complete'){_globalInit();// if the page is still loading, add an event listener // and initialize p5 as soon as it finishes loading }else{window.addEventListener('load',_globalInit,false);}},{"../core/main":25}],24:[function(_dereq_,module,exports){/** * @for p5 * @requires core * These are functions that are part of the Processing API but are not part of * the p5.js API. In some cases they have a new name, in others, they are * removed completely. Not all unsupported Processing functions are listed here * but we try to include ones that a user coming from Processing might likely * call. */'use strict';var p5=_dereq_('./main');p5.prototype.exit=function(){throw new Error('exit() not implemented, see remove()');};p5.prototype.pushStyle=function(){throw new Error('pushStyle() not used, see push()');};p5.prototype.popStyle=function(){throw new Error('popStyle() not used, see pop()');};p5.prototype.size=function(){var s='size() is not a valid p5 function, to set the size of the ';s+='drawing canvas, please use createCanvas() instead';throw new Error(s);};module.exports=p5;},{"./main":25}],25:[function(_dereq_,module,exports){/** * @module Structure * @submodule Structure * @for p5 * @requires constants */'use strict';_dereq_('./shim');// Core needs the PVariables object var constants=_dereq_('./constants');/** * This is the p5 instance constructor. * * A p5 instance holds all the properties and methods related to * a p5 sketch. It expects an incoming sketch closure and it can also * take an optional node parameter for attaching the generated p5 canvas * to a node. The sketch closure takes the newly created p5 instance as * its sole argument and may optionally set <a href="#/p5/preload">preload()</a>, <a href="#/p5/setup">setup()</a>, and/or * <a href="#/p5/draw">draw()</a> properties on it for running a sketch. * * A p5 sketch can run in "global" or "instance" mode: * "global" - all properties and methods are attached to the window * "instance" - all properties and methods are bound to this p5 object * * @class p5 * @constructor * @param {function} sketch a closure that can set optional <a href="#/p5/preload">preload()</a>, * <a href="#/p5/setup">setup()</a>, and/or <a href="#/p5/draw">draw()</a> properties on the * given p5 instance * @param {HTMLElement|Boolean} [node] element to attach canvas to, if a * boolean is passed in use it as sync * @param {Boolean} [sync] start synchronously (optional) * @return {p5} a p5 instance */var p5=function p5(sketch,node,sync){if(typeof node==='boolean'&&typeof sync==='undefined'){sync=node;node=undefined;}////////////////////////////////////////////// // PUBLIC p5 PROPERTIES AND METHODS ////////////////////////////////////////////// /** * Called directly before <a href="#/p5/setup">setup()</a>, the <a href="#/p5/preload">preload()</a> function is used to handle * asynchronous loading of external files in a blocking way. If a preload * function is defined, <a href="#/p5/setup">setup()</a> will wait until any load calls within have * finished. Nothing besides load calls (<a href="#/p5/loadImage">loadImage</a>, <a href="#/p5/loadJSON">loadJSON</a>, <a href="#/p5/loadFont">loadFont</a>, * <a href="#/p5/loadStrings">loadStrings</a>, etc.) should be inside the preload function. If asynchronous * loading is preferred, the load methods can instead be called in <a href="#/p5/setup">setup()</a> * or anywhere else with the use of a callback parameter. * <br><br> * By default the text "loading..." will be displayed. To make your own * loading page, include an HTML element with id "p5_loading" in your * page. More information <a href="http://bit.ly/2kQ6Nio">here</a>. * * @method preload * @example * <div><code> * var img; * var c; * function preload() { // preload() runs once * img = loadImage('assets/laDefense.jpg'); * } * * function setup() { // setup() waits until preload() is done * img.loadPixels(); * // get color of middle pixel * c = img.get(img.width / 2, img.height / 2); * } * * function draw() { * background(c); * image(img, 25, 25, 50, 50); * } * </code></div> * * @alt * nothing displayed * *//** * The <a href="#/p5/setup">setup()</a> function is called once when the program starts. It's used to * define initial environment properties such as screen size and background * color and to load media such as images and fonts as the program starts. * There can only be one <a href="#/p5/setup">setup()</a> function for each program and it shouldn't * be called again after its initial execution. * <br><br> * Note: Variables declared within <a href="#/p5/setup">setup()</a> are not accessible within other * functions, including <a href="#/p5/draw">draw()</a>. * * @method setup * @example * <div><code> * var a = 0; * * function setup() { * background(0); * noStroke(); * fill(102); * } * * function draw() { * rect(a++ % width, 10, 2, 80); * } * </code></div> * * @alt * nothing displayed * *//** * Called directly after <a href="#/p5/setup">setup()</a>, the <a href="#/p5/draw">draw()</a> function continuously executes * the lines of code contained inside its block until the program is stopped * or <a href="#/p5/noLoop">noLoop()</a> is called. Note if <a href="#/p5/noLoop">noLoop()</a> is called in <a href="#/p5/setup">setup()</a>, <a href="#/p5/draw">draw()</a> will * still be executed once before stopping. <a href="#/p5/draw">draw()</a> is called automatically and * should never be called explicitly. * <br><br> * It should always be controlled with <a href="#/p5/noLoop">noLoop()</a>, <a href="#/p5/redraw">redraw()</a> and <a href="#/p5/loop">loop()</a>. After * <a href="#/p5/noLoop">noLoop()</a> stops the code in <a href="#/p5/draw">draw()</a> from executing, <a href="#/p5/redraw">redraw()</a> causes the * code inside <a href="#/p5/draw">draw()</a> to execute once, and <a href="#/p5/loop">loop()</a> will cause the code * inside <a href="#/p5/draw">draw()</a> to resume executing continuously. * <br><br> * The number of times <a href="#/p5/draw">draw()</a> executes in each second may be controlled with * the <a href="#/p5/frameRate">frameRate()</a> function. * <br><br> * There can only be one <a href="#/p5/draw">draw()</a> function for each sketch, and <a href="#/p5/draw">draw()</a> must * exist if you want the code to run continuously, or to process events such * as <a href="#/p5/mousePressed">mousePressed()</a>. Sometimes, you might have an empty call to <a href="#/p5/draw">draw()</a> in * your program, as shown in the above example. * <br><br> * It is important to note that the drawing coordinate system will be reset * at the beginning of each <a href="#/p5/draw">draw()</a> call. If any transformations are performed * within <a href="#/p5/draw">draw()</a> (ex: scale, rotate, translate), their effects will be * undone at the beginning of <a href="#/p5/draw">draw()</a>, so transformations will not accumulate * over time. On the other hand, styling applied (ex: fill, stroke, etc) will * remain in effect. * * @method draw * @example * <div><code> * var yPos = 0; * function setup() { // setup() runs once * frameRate(30); * } * function draw() { // draw() loops forever, until stopped * background(204); * yPos = yPos - 1; * if (yPos < 0) { * yPos = height; * } * line(0, yPos, width, yPos); * } * </code></div> * * @alt * nothing displayed * */////////////////////////////////////////////// // PRIVATE p5 PROPERTIES AND METHODS ////////////////////////////////////////////// this._setupDone=false;// for handling hidpi this._pixelDensity=Math.ceil(window.devicePixelRatio)||1;this._userNode=node;this._curElement=null;this._elements=[];this._requestAnimId=0;this._preloadCount=0;this._isGlobal=false;this._loop=true;this._initializeInstanceVariables();this._defaultCanvasSize={width:100,height:100};this._events={// keep track of user-events for unregistering later mousemove:null,mousedown:null,mouseup:null,dragend:null,dragover:null,click:null,dblclick:null,mouseover:null,mouseout:null,keydown:null,keyup:null,keypress:null,touchstart:null,touchmove:null,touchend:null,resize:null,blur:null};this._events.wheel=null;this._loadingScreenId='p5_loading';// Allows methods to be registered on an instance that // are instance-specific. this._registeredMethods={};var methods=Object.getOwnPropertyNames(p5.prototype._registeredMethods);for(var i=0;i<methods.length;i++){var prop=methods[i];this._registeredMethods[prop]=p5.prototype._registeredMethods[prop].slice();}if(window.DeviceOrientationEvent){this._events.deviceorientation=null;}if(window.DeviceMotionEvent&&!window._isNodeWebkit){this._events.devicemotion=null;}this._start=function(){// Find node if id given if(this._userNode){if(typeof this._userNode==='string'){this._userNode=document.getElementById(this._userNode);}}var context=this._isGlobal?window:this;var userPreload=context.preload;if(userPreload){// Setup loading screen // Set loading screen into dom if not present // Otherwise displays and removes user provided loading screen var loadingScreen=document.getElementById(this._loadingScreenId);if(!loadingScreen){loadingScreen=document.createElement('div');loadingScreen.innerHTML='Loading...';loadingScreen.style.position='absolute';loadingScreen.id=this._loadingScreenId;var node=this._userNode||document.body;node.appendChild(loadingScreen);}var methods=this._preloadMethods;for(var method in methods){// default to p5 if no object defined methods[method]=methods[method]||p5;var obj=methods[method];//it's p5, check if it's global or instance if(obj===p5.prototype||obj===p5){if(this._isGlobal){window[method]=this._wrapPreload(this,method);}obj=this;}this._registeredPreloadMethods[method]=obj[method];obj[method]=this._wrapPreload(obj,method);}userPreload();this._runIfPreloadsAreDone();}else{this._setup();this._runFrames();this._draw();}}.bind(this);this._runIfPreloadsAreDone=function(){var context=this._isGlobal?window:this;if(context._preloadCount===0){var loadingScreen=document.getElementById(context._loadingScreenId);if(loadingScreen){loadingScreen.parentNode.removeChild(loadingScreen);}context._setup();context._runFrames();context._draw();}};this._decrementPreload=function(){var context=this._isGlobal?window:this;if(typeof context.preload==='function'){context._setProperty('_preloadCount',context._preloadCount-1);context._runIfPreloadsAreDone();}};this._wrapPreload=function(obj,fnName){return function(){//increment counter this._incrementPreload();//call original function return this._registeredPreloadMethods[fnName].apply(obj,arguments);}.bind(this);};this._incrementPreload=function(){var context=this._isGlobal?window:this;context._setProperty('_preloadCount',context._preloadCount+1);};this._setup=function(){// Always create a default canvas. // Later on if the user calls createCanvas, this default one // will be replaced this.createCanvas(this._defaultCanvasSize.width,this._defaultCanvasSize.height,'p2d');// return preload functions to their normal vals if switched by preload var context=this._isGlobal?window:this;if(typeof context.preload==='function'){for(var f in this._preloadMethods){context[f]=this._preloadMethods[f][f];if(context[f]&&this){context[f]=context[f].bind(this);}}}// Short-circuit on this, in case someone used the library in "global" // mode earlier if(typeof context.setup==='function'){context.setup();}// unhide any hidden canvases that were created var canvases=document.getElementsByTagName('canvas');for(var i=0;i<canvases.length;i++){var k=canvases[i];if(k.dataset.hidden==='true'){k.style.visibility='';delete k.dataset.hidden;}}this._setupDone=true;}.bind(this);this._draw=function(){var now=window.performance.now();var time_since_last=now-this._lastFrameTime;var target_time_between_frames=1000/this._targetFrameRate;// only draw if we really need to; don't overextend the browser. // draw if we're within 5ms of when our next frame should paint // (this will prevent us from giving up opportunities to draw // again when it's really about time for us to do so). fixes an // issue where the frameRate is too low if our refresh loop isn't // in sync with the browser. note that we have to draw once even // if looping is off, so we bypass the time delay if that // is the case. var epsilon=5;if(!this._loop||time_since_last>=target_time_between_frames-epsilon){//mandatory update values(matrixs and stack) this.redraw();this._frameRate=1000.0/(now-this._lastFrameTime);this._lastFrameTime=now;// If the user is actually using mouse module, then update // coordinates, otherwise skip. We can test this by simply // checking if any of the mouse functions are available or not. // NOTE : This reflects only in complete build or modular build. if(typeof this._updateMouseCoords!=='undefined'){this._updateMouseCoords();}}// get notified the next time the browser gives us // an opportunity to draw. if(this._loop){this._requestAnimId=window.requestAnimationFrame(this._draw);}}.bind(this);this._runFrames=function(){if(this._updateInterval){clearInterval(this._updateInterval);}}.bind(this);this._setProperty=function(prop,value){this[prop]=value;if(this._isGlobal){window[prop]=value;}}.bind(this);/** * Removes the entire p5 sketch. This will remove the canvas and any * elements created by p5.js. It will also stop the draw loop and unbind * any properties or methods from the window global scope. It will * leave a variable p5 in case you wanted to create a new p5 sketch. * If you like, you can set p5 = null to erase it. While all functions and * variables and objects created by the p5 library will be removed, any * other global variables created by your code will remain. * * @method remove * @example * <div class='norender'><code> * function draw() { * ellipse(50, 50, 10, 10); * } * * function mousePressed() { * remove(); // remove whole sketch on mouse press * } * </code></div> * * @alt * nothing displayed * */this.remove=function(){var loadingScreen=document.getElementById(this._loadingScreenId);if(loadingScreen){loadingScreen.parentNode.removeChild(loadingScreen);// Add 1 to preload counter to prevent the sketch ever executing setup() this._incrementPreload();}if(this._curElement){// stop draw this._loop=false;if(this._requestAnimId){window.cancelAnimationFrame(this._requestAnimId);}// unregister events sketch-wide for(var ev in this._events){window.removeEventListener(ev,this._events[ev]);}// remove DOM elements created by p5, and listeners for(var i=0;i<this._elements.length;i++){var e=this._elements[i];if(e.elt.parentNode){e.elt.parentNode.removeChild(e.elt);}for(var elt_ev in e._events){e.elt.removeEventListener(elt_ev,e._events[elt_ev]);}}// call any registered remove functions var self=this;this._registeredMethods.remove.forEach(function(f){if(typeof f!=='undefined'){f.call(self);}});}// remove window bound properties and methods if(this._isGlobal){for(var p in p5.prototype){try{delete window[p];}catch(x){window[p]=undefined;}}for(var p2 in this){if(this.hasOwnProperty(p2)){try{delete window[p2];}catch(x){window[p2]=undefined;}}}p5.instance=null;}}.bind(this);// call any registered init functions this._registeredMethods.init.forEach(function(f){if(typeof f!=='undefined'){f.call(this);}},this);var friendlyBindGlobal=this._createFriendlyGlobalFunctionBinder();// If the user has created a global setup or draw function, // assume "global" mode and make everything global (i.e. on the window) if(!sketch){this._isGlobal=true;p5.instance=this;// Loop through methods on the prototype and attach them to the window for(var p in p5.prototype){if(typeof p5.prototype[p]==='function'){var ev=p.substring(2);if(!this._events.hasOwnProperty(ev)){if(Math.hasOwnProperty(p)&&Math[p]===p5.prototype[p]){// Multiple p5 methods are just native Math functions. These can be // called without any binding. friendlyBindGlobal(p,p5.prototype[p]);}else{friendlyBindGlobal(p,p5.prototype[p].bind(this));}}}else{friendlyBindGlobal(p,p5.prototype[p]);}}// Attach its properties to the window for(var p2 in this){if(this.hasOwnProperty(p2)){friendlyBindGlobal(p2,this[p2]);}}}else{// Else, the user has passed in a sketch closure that may set // user-provided 'setup', 'draw', etc. properties on this instance of p5 sketch(this);}// Bind events to window (not using container div bc key events don't work) for(var e in this._events){var f=this['_on'+e];if(f){var m=f.bind(this);window.addEventListener(e,m,{passive:false});this._events[e]=m;}}var focusHandler=function(){this._setProperty('focused',true);}.bind(this);var blurHandler=function(){this._setProperty('focused',false);}.bind(this);window.addEventListener('focus',focusHandler);window.addEventListener('blur',blurHandler);this.registerMethod('remove',function(){window.removeEventListener('focus',focusHandler);window.removeEventListener('blur',blurHandler);});if(sync){this._start();}else{if(document.readyState==='complete'){this._start();}else{window.addEventListener('load',this._start.bind(this),false);}}};p5.prototype._initializeInstanceVariables=function(){this._styles=[];this._bezierDetail=20;this._curveDetail=20;this._colorMode=constants.RGB;this._colorMaxes={rgb:[255,255,255,255],hsb:[360,100,100,1],hsl:[360,100,100,1]};this._pixelsDirty=true;};// This is a pointer to our global mode p5 instance, if we're in // global mode. p5.instance=null;// Allows for the friendly error system to be turned off when creating a sketch, // which can give a significant boost to performance when needed. p5.disableFriendlyErrors=false;// attach constants to p5 prototype for(var k in constants){p5.prototype[k]=constants[k];}// functions that cause preload to wait // more can be added by using registerPreloadMethod(func) p5.prototype._preloadMethods={loadJSON:p5.prototype,loadImage:p5.prototype,loadStrings:p5.prototype,loadXML:p5.prototype,loadBytes:p5.prototype,loadTable:p5.prototype,loadFont:p5.prototype,loadModel:p5.prototype,loadShader:p5.prototype};p5.prototype._registeredMethods={init:[],pre:[],post:[],remove:[]};p5.prototype._registeredPreloadMethods={};p5.prototype.registerPreloadMethod=function(fnString,obj){// obj = obj || p5.prototype; if(!p5.prototype._preloadMethods.hasOwnProperty(fnString)){p5.prototype._preloadMethods[fnString]=obj;}};p5.prototype.registerMethod=function(name,m){var target=this||p5.prototype;if(!target._registeredMethods.hasOwnProperty(name)){target._registeredMethods[name]=[];}target._registeredMethods[name].push(m);};// create a function which provides a standardized process for binding // globals; this is implemented as a factory primarily so that there's a // way to redefine what "global" means for the binding function so it // can be used in scenarios like unit testing where the window object // might not exist p5.prototype._createFriendlyGlobalFunctionBinder=function(options){options=options||{};var globalObject=options.globalObject||window;var log=options.log||console.log.bind(console);var propsToForciblyOverwrite={// p5.print actually always overwrites an existing global function, // albeit one that is very unlikely to be used: // // https://developer.mozilla.org/en-US/docs/Web/API/Window/print print:true};return function(prop,value){if(!p5.disableFriendlyErrors&&typeof IS_MINIFIED==='undefined'&&typeof value==='function'&&!(prop in p5.prototype._preloadMethods)){try{// Because p5 has so many common function names, it's likely // that users may accidentally overwrite global p5 functions with // their own variables. Let's allow this but log a warning to // help users who may be doing this unintentionally. // // For more information, see: // // https://github.com/processing/p5.js/issues/1317 if(prop in globalObject&&!(prop in propsToForciblyOverwrite)){throw new Error('global "'+prop+'" already exists');}// It's possible that this might throw an error because there // are a lot of edge-cases in which `Object.defineProperty` might // not succeed; since this functionality is only intended to // help beginners anyways, we'll just catch such an exception // if it occurs, and fall back to legacy behavior. Object.defineProperty(globalObject,prop,{configurable:true,enumerable:true,get:function get(){return value;},set:function set(newValue){Object.defineProperty(globalObject,prop,{configurable:true,enumerable:true,value:newValue,writable:true});log('You just changed the value of "'+prop+'", which was '+"a p5 function. This could cause problems later if you're "+'not careful.');}});}catch(e){log('p5 had problems creating the global function "'+prop+'", '+'possibly because your code is already using that name as '+'a variable. You may want to rename your variable to something '+'else.');globalObject[prop]=value;}}else{globalObject[prop]=value;}};};module.exports=p5;},{"./constants":19,"./shim":35}],26:[function(_dereq_,module,exports){/** * @module DOM * @submodule DOM * @for p5.Element */'use strict';var p5=_dereq_('./main');/** * Base class for all elements added to a sketch, including canvas, * graphics buffers, and other HTML elements. Methods in blue are * included in the core functionality, methods in brown are added * with the <a href="http://p5js.org/reference/#/libraries/p5.dom">p5.dom * library</a>. * It is not called directly, but <a href="#/p5.Element">p5.Element</a> * objects are created by calling <a href="#/p5/createCanvas">createCanvas</a>, <a href="#/p5/createGraphics">createGraphics</a>, * or in the p5.dom library, <a href="#/p5/createDiv">createDiv</a>, <a href="#/p5/createImg">createImg</a>, <a href="#/p5/createInput">createInput</a>, etc. * * @class p5.Element * @param {String} elt DOM node that is wrapped * @param {p5} [pInst] pointer to p5 instance */p5.Element=function(elt,pInst){/** * Underlying HTML element. All normal HTML methods can be called on this. * @example * <div> * <code> * createCanvas(300, 500); * background(0, 0, 0, 0); * var input = createInput(); * input.position(20, 225); * var inputElem = new p5.Element(input.elt); * inputElem.style('width:450px;'); * inputElem.value('some string'); * </code> * </div> * * @property elt * @readOnly */this.elt=elt;this._pInst=pInst;this._events={};this.width=this.elt.offsetWidth;this.height=this.elt.offsetHeight;};/** * * Attaches the element to the parent specified. A way of setting * the container for the element. Accepts either a string ID, DOM * node, or <a href="#/p5.Element">p5.Element</a>. If no arguments given, parent node is returned. * For more ways to position the canvas, see the * <a href='https://github.com/processing/p5.js/wiki/Positioning-your-canvas'> * positioning the canvas</a> wiki page. * * @method parent * @param {String|p5.Element|Object} parent the ID, DOM node, or <a href="#/p5.Element">p5.Element</a> * of desired parent element * @chainable * * @example * <div class="norender notest"><code> * // in the html file: * // &lt;div id="myContainer">&lt;/div> * * // in the js file: * var cnv = createCanvas(100, 100); * cnv.parent('myContainer'); * </code></div> * <div class='norender'><code> * var div0 = createDiv('this is the parent'); * var div1 = createDiv('this is the child'); * div1.parent(div0); // use p5.Element * </code></div> * <div class='norender'><code> * var div0 = createDiv('this is the parent'); * div0.id('apples'); * var div1 = createDiv('this is the child'); * div1.parent('apples'); // use id * </code></div> * <div class='norender notest'><code> * var elt = document.getElementById('myParentDiv'); * var div1 = createDiv('this is the child'); * div1.parent(elt); // use element from page * </code></div> * * @alt * no display. *//** * @method parent * @return {p5.Element} * */p5.Element.prototype.parent=function(p){if(typeof p==='undefined'){return this.elt.parentNode;}if(typeof p==='string'){if(p[0]==='#'){p=p.substring(1);}p=document.getElementById(p);}else if(p instanceof p5.Element){p=p.elt;}p.appendChild(this.elt);return this;};/** * * Sets the ID of the element. If no ID argument is passed in, it instead * returns the current ID of the element. * * @method id * @param {String} id ID of the element * @chainable * * @example * <div class='norender'><code> * function setup() { * var cnv = createCanvas(100, 100); * // Assigns a CSS selector ID to * // the canvas element. * cnv.id('mycanvas'); * } * </code></div> * * @alt * no display. *//** * @method id * @return {String} the id of the element */p5.Element.prototype.id=function(id){if(typeof id==='undefined'){return this.elt.id;}this.elt.id=id;this.width=this.elt.offsetWidth;this.height=this.elt.offsetHeight;return this;};/** * * Adds given class to the element. If no class argument is passed in, it * instead returns a string containing the current class(es) of the element. * * @method class * @param {String} class class to add * @chainable * * @example * <div class='norender'><code> * function setup() { * var cnv = createCanvas(100, 100); * // Assigns a CSS selector class 'small' * // to the canvas element. * cnv.class('small'); * } * </code></div> * * @alt * no display. *//** * @method class * @return {String} the class of the element */p5.Element.prototype.class=function(c){if(typeof c==='undefined'){return this.elt.className;}this.elt.className=c;return this;};/** * The .<a href="#/p5.Element/mousePressed">mousePressed()</a> function is called once after every time a * mouse button is pressed over the element. * Some mobile browsers may also trigger this event on a touch screen, * if the user performs a quick tap. * This can be used to attach element specific event listeners. * * @method mousePressed * @param {Function|Boolean} fxn function to be fired when mouse is * pressed over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class='norender'><code> * var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mousePressed(changeGray); // attach listener for * // canvas click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires with any click anywhere * function mousePressed() { * d = d + 10; * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } * </code></div> * * @alt * no display. * */p5.Element.prototype.mousePressed=function(fxn){// Prepend the mouse property setters to the event-listener. // This is required so that mouseButton is set correctly prior to calling the callback (fxn). // For details, see https://github.com/processing/p5.js/issues/3087. var eventPrependedFxn=function eventPrependedFxn(event){this._pInst._setProperty('mouseIsPressed',true);this._pInst._setMouseButton(event);// Pass along the return-value of the callback: return fxn();};// Pass along the event-prepended form of the callback. adjustListener('mousedown',eventPrependedFxn,this);return this;};/** * The .<a href="#/p5.Element/doubleClicked">doubleClicked()</a> function is called once after every time a * mouse button is pressed twice over the element. This can be used to * attach element and action specific event listeners. * * @method doubleClicked * @param {Function|Boolean} fxn function to be fired when mouse is * double clicked over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @return {p5.Element} * @example * <div class='norender'><code> * var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.doubleClicked(changeGray); // attach listener for * // canvas double click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires with any double click anywhere * function doubleClicked() { * d = d + 10; * } * * // this function fires only when cnv is double clicked * function changeGray() { * g = random(0, 255); * } * </code></div> * * @alt * no display. * */p5.Element.prototype.doubleClicked=function(fxn){adjustListener('dblclick',fxn,this);return this;};/** * The .<a href="#/p5.Element/mouseWheel">mouseWheel()</a> function is called once after every time a * mouse wheel is scrolled over the element. This can be used to * attach element specific event listeners. * <br><br> * The function accepts a callback function as argument which will be executed * when the `wheel` event is triggered on the element, the callback function is * passed one argument `event`. The `event.deltaY` property returns negative * values if the mouse wheel is rotated up or away from the user and positive * in the other direction. The `event.deltaX` does the same as `event.deltaY` * except it reads the horizontal wheel scroll of the mouse wheel. * <br><br> * On OS X with "natural" scrolling enabled, the `event.deltaY` values are * reversed. * * @method mouseWheel * @param {Function|Boolean} fxn function to be fired when mouse is * scrolled over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class='norender'><code> * var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseWheel(changeSize); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires with mousewheel movement * // anywhere on screen * function mouseWheel() { * g = g + 10; * } * * // this function fires with mousewheel movement * // over canvas only * function changeSize(event) { * if (event.deltaY > 0) { * d = d + 10; * } else { * d = d - 10; * } * } * </code></div> * * * @alt * no display. * */p5.Element.prototype.mouseWheel=function(fxn){adjustListener('wheel',fxn,this);return this;};/** * The .<a href="#/p5.Element/mouseReleased">mouseReleased()</a> function is called once after every time a * mouse button is released over the element. * Some mobile browsers may also trigger this event on a touch screen, * if the user performs a quick tap. * This can be used to attach element specific event listeners. * * @method mouseReleased * @param {Function|Boolean} fxn function to be fired when mouse is * released over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class='norender'><code> * var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseReleased(changeGray); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires after the mouse has been * // released * function mouseReleased() { * d = d + 10; * } * * // this function fires after the mouse has been * // released while on canvas * function changeGray() { * g = random(0, 255); * } * </code></div> * * * @alt * no display. * */p5.Element.prototype.mouseReleased=function(fxn){adjustListener('mouseup',fxn,this);return this;};/** * The .<a href="#/p5.Element/mouseClicked">mouseClicked()</a> function is called once after a mouse button is * pressed and released over the element. * Some mobile browsers may also trigger this event on a touch screen, * if the user performs a quick tap. * This can be used to attach element specific event listeners. * * @method mouseClicked * @param {Function|Boolean} fxn function to be fired when mouse is * clicked over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class="norender"> * <code> * var cnv; * var d; * var g; * * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseClicked(changeGray); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires after the mouse has been * // clicked anywhere * function mouseClicked() { * d = d + 10; * } * * // this function fires after the mouse has been * // clicked on canvas * function changeGray() { * g = random(0, 255); * } * </code> * </div> * * @alt * no display. * */p5.Element.prototype.mouseClicked=function(fxn){adjustListener('click',fxn,this);return this;};/** * The .<a href="#/p5.Element/mouseMoved">mouseMoved()</a> function is called once every time a * mouse moves over the element. This can be used to attach an * element specific event listener. * * @method mouseMoved * @param {Function|Boolean} fxn function to be fired when a mouse moves * over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class='norender'><code> * var cnv; * var d = 30; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseMoved(changeSize); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * fill(200); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires when mouse moves anywhere on * // page * function mouseMoved() { * g = g + 5; * if (g > 255) { * g = 0; * } * } * * // this function fires when mouse moves over canvas * function changeSize() { * d = d + 2; * if (d > 100) { * d = 0; * } * } * </code></div> * * * @alt * no display. * */p5.Element.prototype.mouseMoved=function(fxn){adjustListener('mousemove',fxn,this);return this;};/** * The .<a href="#/p5.Element/mouseOver">mouseOver()</a> function is called once after every time a * mouse moves onto the element. This can be used to attach an * element specific event listener. * * @method mouseOver * @param {Function|Boolean} fxn function to be fired when a mouse moves * onto the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class='norender'><code> * var cnv; * var d; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseOver(changeGray); * d = 10; * } * * function draw() { * ellipse(width / 2, height / 2, d, d); * } * * function changeGray() { * d = d + 10; * if (d > 100) { * d = 0; * } * } * </code></div> * * * @alt * no display. * */p5.Element.prototype.mouseOver=function(fxn){adjustListener('mouseover',fxn,this);return this;};/** * The .<a href="#/p5.Element/changed">changed()</a> function is called when the value of an * element changes. * This can be used to attach an element specific event listener. * * @method changed * @param {Function|Boolean} fxn function to be fired when the value of * an element changes. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div><code> * var sel; * * function setup() { * textAlign(CENTER); * background(200); * sel = createSelect(); * sel.position(10, 10); * sel.option('pear'); * sel.option('kiwi'); * sel.option('grape'); * sel.changed(mySelectEvent); * } * * function mySelectEvent() { * var item = sel.value(); * background(200); * text("it's a " + item + '!', 50, 50); * } * </code></div> * <div><code> * var checkbox; * var cnv; * * function setup() { * checkbox = createCheckbox(' fill'); * checkbox.changed(changeFill); * cnv = createCanvas(100, 100); * cnv.position(0, 30); * noFill(); * } * * function draw() { * background(200); * ellipse(50, 50, 50, 50); * } * * function changeFill() { * if (checkbox.checked()) { * fill(0); * } else { * noFill(); * } * } * </code></div> * * @alt * dropdown: pear, kiwi, grape. When selected text "its a" + selection shown. * */p5.Element.prototype.changed=function(fxn){adjustListener('change',fxn,this);return this;};/** * The .<a href="#/p5.Element/input">input()</a> function is called when any user input is * detected with an element. The input event is often used * to detect keystrokes in a input element, or changes on a * slider element. This can be used to attach an element specific * event listener. * * @method input * @param {Function|Boolean} fxn function to be fired when any user input is * detected within the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class='norender'><code> * // Open your console to see the output * function setup() { * var inp = createInput(''); * inp.input(myInputEvent); * } * * function myInputEvent() { * console.log('you are typing: ', this.value()); * } * </code></div> * * @alt * no display. * */p5.Element.prototype.input=function(fxn){adjustListener('input',fxn,this);return this;};/** * The .<a href="#/p5.Element/mouseOut">mouseOut()</a> function is called once after every time a * mouse moves off the element. This can be used to attach an * element specific event listener. * * @method mouseOut * @param {Function|Boolean} fxn function to be fired when a mouse * moves off of an element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class='norender'><code> * var cnv; * var d; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseOut(changeGray); * d = 10; * } * * function draw() { * ellipse(width / 2, height / 2, d, d); * } * * function changeGray() { * d = d + 10; * if (d > 100) { * d = 0; * } * } * </code></div> * * @alt * no display. * */p5.Element.prototype.mouseOut=function(fxn){adjustListener('mouseout',fxn,this);return this;};/** * The .<a href="#/p5.Element/touchStarted">touchStarted()</a> function is called once after every time a touch is * registered. This can be used to attach element specific event listeners. * * @method touchStarted * @param {Function|Boolean} fxn function to be fired when a touch * starts over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class='norender'><code> * var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchStarted(changeGray); // attach listener for * // canvas click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires with any touch anywhere * function touchStarted() { * d = d + 10; * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } * </code></div> * * @alt * no display. * */p5.Element.prototype.touchStarted=function(fxn){adjustListener('touchstart',fxn,this);return this;};/** * The .<a href="#/p5.Element/touchMoved">touchMoved()</a> function is called once after every time a touch move is * registered. This can be used to attach element specific event listeners. * * @method touchMoved * @param {Function|Boolean} fxn function to be fired when a touch moves over * the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class='norender'><code> * var cnv; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchMoved(changeGray); // attach listener for * // canvas click only * g = 100; * } * * function draw() { * background(g); * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } * </code></div> * * @alt * no display. * */p5.Element.prototype.touchMoved=function(fxn){adjustListener('touchmove',fxn,this);return this;};/** * The .<a href="#/p5.Element/touchEnded">touchEnded()</a> function is called once after every time a touch is * registered. This can be used to attach element specific event listeners. * * @method touchEnded * @param {Function|Boolean} fxn function to be fired when a touch ends * over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class='norender'><code> * var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchEnded(changeGray); // attach listener for * // canvas click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires with any touch anywhere * function touchEnded() { * d = d + 10; * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } * </code></div> * * * @alt * no display. * */p5.Element.prototype.touchEnded=function(fxn){adjustListener('touchend',fxn,this);return this;};/** * The .<a href="#/p5.Element/dragOver">dragOver()</a> function is called once after every time a * file is dragged over the element. This can be used to attach an * element specific event listener. * * @method dragOver * @param {Function|Boolean} fxn function to be fired when a file is * dragged over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div><code> * // To test this sketch, simply drag a * // file over the canvas * function setup() { * var c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('Drag file', width / 2, height / 2); * c.dragOver(dragOverCallback); * } * * // This function will be called whenever * // a file is dragged over the canvas * function dragOverCallback() { * background(240); * text('Dragged over', width / 2, height / 2); * } * </code></div> * @alt * nothing displayed */p5.Element.prototype.dragOver=function(fxn){adjustListener('dragover',fxn,this);return this;};/** * The .dragLeave() function is called once after every time a * dragged file leaves the element area. This can be used to attach an * element specific event listener. * * @method dragLeave * @param {Function|Boolean} fxn function to be fired when a file is * dragged off the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div><code> * // To test this sketch, simply drag a file * // over and then out of the canvas area * function setup() { * var c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('Drag file', width / 2, height / 2); * c.dragLeave(dragLeaveCallback); * } * * // This function will be called whenever * // a file is dragged out of the canvas * function dragLeaveCallback() { * background(240); * text('Dragged off', width / 2, height / 2); * } * </code></div> * @alt * nothing displayed */p5.Element.prototype.dragLeave=function(fxn){adjustListener('dragleave',fxn,this);return this;};/** * The .<a href="#/p5.Element/drop">drop()</a> function is called for each file dropped on the element. * It requires a callback that is passed a p5.File object. You can * optionally pass two callbacks, the first one (required) is triggered * for each file dropped when the file is loaded. The second (optional) * is triggered just once when a file (or files) are dropped. * * @method drop * @param {Function} callback callback triggered when files are dropped. * @param {Function} [fxn] callback to receive loaded file. * @chainable * @example * <div><code> * function setup() { * var c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('drop file', width / 2, height / 2); * c.drop(gotFile); * } * * function gotFile(file) { * background(200); * text('received file:', width / 2, height / 2); * text(file.name, width / 2, height / 2 + 50); * } * </code></div> * * <div><code> * var img; * * function setup() { * var c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('drop image', width / 2, height / 2); * c.drop(gotFile); * } * * function draw() { * if (img) { * image(img, 0, 0, width, height); * } * } * * function gotFile(file) { * img = createImg(file.data).hide(); * } * </code></div> * * @alt * Canvas turns into whatever image is dragged/dropped onto it. */p5.Element.prototype.drop=function(callback,fxn){// Make a file loader callback and trigger user's callback function makeLoader(theFile){// Making a p5.File object var p5file=new p5.File(theFile);return function(e){p5file.data=e.target.result;callback(p5file);};}// Is the file stuff supported? if(window.File&&window.FileReader&&window.FileList&&window.Blob){// If you want to be able to drop you've got to turn off // a lot of default behavior attachListener('dragover',function(evt){evt.stopPropagation();evt.preventDefault();},this);// If this is a drag area we need to turn off the default behavior attachListener('dragleave',function(evt){evt.stopPropagation();evt.preventDefault();},this);// If just one argument it's the callback for the files if(typeof fxn!=='undefined'){attachListener('drop',fxn,this);}// Deal with the files attachListener('drop',function(evt){evt.stopPropagation();evt.preventDefault();// A FileList var files=evt.dataTransfer.files;// Load each one and trigger the callback for(var i=0;i<files.length;i++){var f=files[i];var reader=new FileReader();reader.onload=makeLoader(f);// Text or data? // This should likely be improved if(f.type.indexOf('text')>-1){reader.readAsText(f);}else{reader.readAsDataURL(f);}}},this);}else{console.log('The File APIs are not fully supported in this browser.');}return this;};// General handler for event attaching and detaching function adjustListener(ev,fxn,ctx){if(fxn===false){detachListener(ev,ctx);}else{attachListener(ev,fxn,ctx);}return this;}function attachListener(ev,fxn,ctx){// LM removing, not sure why we had this? // var _this = ctx; // var f = function (e) { fxn(e, _this); }; // detach the old listener if there was one if(ctx._events[ev]){detachListener(ev,ctx);}var f=fxn.bind(ctx);ctx.elt.addEventListener(ev,f,false);ctx._events[ev]=f;}function detachListener(ev,ctx){var f=ctx._events[ev];ctx.elt.removeEventListener(ev,f,false);ctx._events[ev]=null;}/** * Helper fxn for sharing pixel methods * */p5.Element.prototype._setProperty=function(prop,value){this[prop]=value;};module.exports=p5.Element;},{"./main":25}],27:[function(_dereq_,module,exports){/** * @module Rendering * @submodule Rendering * @for p5 */'use strict';var p5=_dereq_('./main');var constants=_dereq_('./constants');/** * Thin wrapper around a renderer, to be used for creating a * graphics buffer object. Use this class if you need * to draw into an off-screen graphics buffer. The two parameters define the * width and height in pixels. The fields and methods for this class are * extensive, but mirror the normal drawing API for p5. * * @class p5.Graphics * @extends p5.Element * @param {Number} w width * @param {Number} h height * @param {Constant} renderer the renderer to use, either P2D or WEBGL * @param {p5} [pInst] pointer to p5 instance */p5.Graphics=function(w,h,renderer,pInst){var r=renderer||constants.P2D;this.canvas=document.createElement('canvas');var node=pInst._userNode||document.body;node.appendChild(this.canvas);p5.Element.call(this,this.canvas,pInst,false);// bind methods and props of p5 to the new object for(var p in p5.prototype){if(!this[p]){if(typeof p5.prototype[p]==='function'){this[p]=p5.prototype[p].bind(this);}else{this[p]=p5.prototype[p];}}}p5.prototype._initializeInstanceVariables.apply(this);this.width=w;this.height=h;this._pixelDensity=pInst._pixelDensity;if(r===constants.WEBGL){this._renderer=new p5.RendererGL(this.canvas,this,false);}else{this._renderer=new p5.Renderer2D(this.canvas,this,false);}pInst._elements.push(this);this._renderer.resize(w,h);this._renderer._applyDefaults();return this;};p5.Graphics.prototype=Object.create(p5.Element.prototype);/** * Removes a Graphics object from the page and frees any resources * associated with it. * * @method remove * * @example * <div class='norender'><code> * var bg; * function setup() { * bg = createCanvas(100, 100); * bg.background(0); * image(bg, 0, 0); * bg.remove(); * } * </code></div> * * <div><code> * var bg; * function setup() { * pixelDensity(1); * createCanvas(100, 100); * stroke(255); * fill(0); * * // create and draw the background image * bg = createGraphics(100, 100); * bg.background(200); * bg.ellipse(50, 50, 80, 80); * } * function draw() { * var t = millis() / 1000; * // draw the background * if (bg) { * image(bg, frameCount % 100, 0); * image(bg, frameCount % 100 - 100, 0); * } * // draw the foreground * var p = p5.Vector.fromAngle(t, 35).add(50, 50); * ellipse(p.x, p.y, 30); * } * function mouseClicked() { * // remove the background * if (bg) { * bg.remove(); * bg = null; * } * } * </code></div> * * @alt * no image * a multi-colored circle moving back and forth over a scrolling background. * */p5.Graphics.prototype.remove=function(){if(this.elt.parentNode){this.elt.parentNode.removeChild(this.elt);}var idx=this._pInst._elements.indexOf(this);if(idx!==-1){this._pInst._elements.splice(idx,1);}for(var elt_ev in this._events){this.elt.removeEventListener(elt_ev,this._events[elt_ev]);}};module.exports=p5.Graphics;},{"./constants":19,"./main":25}],28:[function(_dereq_,module,exports){/** * @module Rendering * @submodule Rendering * @for p5 */'use strict';var p5=_dereq_('./main');var constants=_dereq_('../core/constants');/** * Main graphics and rendering context, as well as the base API * implementation for p5.js "core". To be used as the superclass for * Renderer2D and Renderer3D classes, respecitvely. * * @class p5.Renderer * @constructor * @extends p5.Element * @param {String} elt DOM node that is wrapped * @param {p5} [pInst] pointer to p5 instance * @param {Boolean} [isMainCanvas] whether we're using it as main canvas */p5.Renderer=function(elt,pInst,isMainCanvas){p5.Element.call(this,elt,pInst);this.canvas=elt;if(isMainCanvas){this._isMainCanvas=true;// for pixel method sharing with pimage this._pInst._setProperty('_curElement',this);this._pInst._setProperty('canvas',this.canvas);this._pInst._setProperty('width',this.width);this._pInst._setProperty('height',this.height);}else{// hide if offscreen buffer by default this.canvas.style.display='none';this._styles=[];// non-main elt styles stored in p5.Renderer }this._textSize=12;this._textLeading=15;this._textFont='sans-serif';this._textStyle=constants.NORMAL;this._textAscent=null;this._textDescent=null;this._textAlign=constants.LEFT;this._textBaseline=constants.BASELINE;this._rectMode=constants.CORNER;this._ellipseMode=constants.CENTER;this._curveTightness=0;this._imageMode=constants.CORNER;this._tint=null;this._doStroke=true;this._doFill=true;this._strokeSet=false;this._fillSet=false;};p5.Renderer.prototype=Object.create(p5.Element.prototype);// the renderer should return a 'style' object that it wishes to // store on the push stack. p5.Renderer.prototype.push=function(){return{properties:{_doStroke:this._doStroke,_strokeSet:this._strokeSet,_doFill:this._doFill,_fillSet:this._fillSet,_tint:this._tint,_imageMode:this._imageMode,_rectMode:this._rectMode,_ellipseMode:this._ellipseMode,_textFont:this._textFont,_textLeading:this._textLeading,_textSize:this._textSize,_textAlign:this._textAlign,_textBaseline:this._textBaseline,_textStyle:this._textStyle}};};// a pop() operation is in progress // the renderer is passed the 'style' object that it returned // from its push() method. p5.Renderer.prototype.pop=function(style){if(style.properties){// copy the style properties back into the renderer Object.assign(this,style.properties);}};/** * Resize our canvas element. */p5.Renderer.prototype.resize=function(w,h){this.width=w;this.height=h;this.elt.width=w*this._pInst._pixelDensity;this.elt.height=h*this._pInst._pixelDensity;this.elt.style.width=w+'px';this.elt.style.height=h+'px';if(this._isMainCanvas){this._pInst._setProperty('width',this.width);this._pInst._setProperty('height',this.height);}};p5.Renderer.prototype.textLeading=function(l){if(typeof l==='number'){this._setProperty('_textLeading',l);return this._pInst;}return this._textLeading;};p5.Renderer.prototype.textSize=function(s){if(typeof s==='number'){this._setProperty('_textSize',s);this._setProperty('_textLeading',s*constants._DEFAULT_LEADMULT);return this._applyTextProperties();}return this._textSize;};p5.Renderer.prototype.textStyle=function(s){if(s){if(s===constants.NORMAL||s===constants.ITALIC||s===constants.BOLD){this._setProperty('_textStyle',s);}return this._applyTextProperties();}return this._textStyle;};p5.Renderer.prototype.textAscent=function(){if(this._textAscent===null){this._updateTextMetrics();}return this._textAscent;};p5.Renderer.prototype.textDescent=function(){if(this._textDescent===null){this._updateTextMetrics();}return this._textDescent;};p5.Renderer.prototype.textAlign=function(h,v){if(typeof h!=='undefined'){this._setProperty('_textAlign',h);if(typeof v!=='undefined'){this._setProperty('_textBaseline',v);}return this._applyTextProperties();}else{return{horizontal:this._textAlign,vertical:this._textBaseline};}};p5.Renderer.prototype.text=function(str,x,y,maxWidth,maxHeight){var p=this._pInst,cars,n,ii,jj,line,testLine,testWidth,words,totalHeight,finalMaxHeight=Number.MAX_VALUE;if(!(this._doFill||this._doStroke)){return;}if(typeof str==='undefined'){return;}else if(typeof str!=='string'){str=str.toString();}str=str.replace(/(\t)/g,' ');cars=str.split('\n');if(typeof maxWidth!=='undefined'){totalHeight=0;for(ii=0;ii<cars.length;ii++){line='';words=cars[ii].split(' ');for(n=0;n<words.length;n++){testLine=line+words[n]+' ';testWidth=this.textWidth(testLine);if(testWidth>maxWidth){line=words[n]+' ';totalHeight+=p.textLeading();}else{line=testLine;}}}if(this._rectMode===constants.CENTER){x-=maxWidth/2;y-=maxHeight/2;}switch(this._textAlign){case constants.CENTER:x+=maxWidth/2;break;case constants.RIGHT:x+=maxWidth;break;}var baselineHacked=false;if(typeof maxHeight!=='undefined'){switch(this._textBaseline){case constants.BOTTOM:y+=maxHeight-totalHeight;break;case constants.CENTER:y+=(maxHeight-totalHeight)/2;break;case constants.BASELINE:baselineHacked=true;this._textBaseline=constants.TOP;break;}// remember the max-allowed y-position for any line (fix to #928) finalMaxHeight=y+maxHeight-p.textAscent();}for(ii=0;ii<cars.length;ii++){line='';words=cars[ii].split(' ');for(n=0;n<words.length;n++){testLine=line+words[n]+' ';testWidth=this.textWidth(testLine);if(testWidth>maxWidth&&line.length>0){this._renderText(p,line,x,y,finalMaxHeight);line=words[n]+' ';y+=p.textLeading();}else{line=testLine;}}this._renderText(p,line,x,y,finalMaxHeight);y+=p.textLeading();if(baselineHacked){this._textBaseline=constants.BASELINE;}}}else{// Offset to account for vertically centering multiple lines of text - no // need to adjust anything for vertical align top or baseline var offset=0,vAlign=p.textAlign().vertical;if(vAlign===constants.CENTER){offset=(cars.length-1)*p.textLeading()/2;}else if(vAlign===constants.BOTTOM){offset=(cars.length-1)*p.textLeading();}for(jj=0;jj<cars.length;jj++){this._renderText(p,cars[jj],x,y-offset,finalMaxHeight);y+=p.textLeading();}}return p;};p5.Renderer.prototype._applyDefaults=function(){return this;};/** * Helper fxn to check font type (system or otf) */p5.Renderer.prototype._isOpenType=function(f){f=f||this._textFont;return(typeof f==="undefined"?"undefined":_typeof(f))==='object'&&f.font&&f.font.supported;};p5.Renderer.prototype._updateTextMetrics=function(){if(this._isOpenType()){this._setProperty('_textAscent',this._textFont._textAscent());this._setProperty('_textDescent',this._textFont._textDescent());return this;}// Adapted from http://stackoverflow.com/a/25355178 var text=document.createElement('span');text.style.fontFamily=this._textFont;text.style.fontSize=this._textSize+'px';text.innerHTML='ABCjgq|';var block=document.createElement('div');block.style.display='inline-block';block.style.width='1px';block.style.height='0px';var container=document.createElement('div');container.appendChild(text);container.appendChild(block);container.style.height='0px';container.style.overflow='hidden';document.body.appendChild(container);block.style.verticalAlign='baseline';var blockOffset=calculateOffset(block);var textOffset=calculateOffset(text);var ascent=blockOffset[1]-textOffset[1];block.style.verticalAlign='bottom';blockOffset=calculateOffset(block);textOffset=calculateOffset(text);var height=blockOffset[1]-textOffset[1];var descent=height-ascent;document.body.removeChild(container);this._setProperty('_textAscent',ascent);this._setProperty('_textDescent',descent);return this;};/** * Helper fxn to measure ascent and descent. * Adapted from http://stackoverflow.com/a/25355178 */function calculateOffset(object){var currentLeft=0,currentTop=0;if(object.offsetParent){do{currentLeft+=object.offsetLeft;currentTop+=object.offsetTop;}while(object=object.offsetParent);}else{currentLeft+=object.offsetLeft;currentTop+=object.offsetTop;}return[currentLeft,currentTop];}module.exports=p5.Renderer;},{"../core/constants":19,"./main":25}],29:[function(_dereq_,module,exports){'use strict';var p5=_dereq_('./main');var constants=_dereq_('./constants');var filters=_dereq_('../image/filters');_dereq_('./p5.Renderer');/** * p5.Renderer2D * The 2D graphics canvas renderer class. * extends p5.Renderer */var styleEmpty='rgba(0,0,0,0)';// var alphaThreshold = 0.00125; // minimum visible p5.Renderer2D=function(elt,pInst,isMainCanvas){p5.Renderer.call(this,elt,pInst,isMainCanvas);this.drawingContext=this.canvas.getContext('2d');this._pInst._setProperty('drawingContext',this.drawingContext);return this;};p5.Renderer2D.prototype=Object.create(p5.Renderer.prototype);p5.Renderer2D.prototype._applyDefaults=function(){this._cachedFillStyle=this._cachedStrokeStyle=undefined;this._setFill(constants._DEFAULT_FILL);this._setStroke(constants._DEFAULT_STROKE);this.drawingContext.lineCap=constants.ROUND;this.drawingContext.font='normal 12px sans-serif';};p5.Renderer2D.prototype.resize=function(w,h){p5.Renderer.prototype.resize.call(this,w,h);this.drawingContext.scale(this._pInst._pixelDensity,this._pInst._pixelDensity);};////////////////////////////////////////////// // COLOR | Setting ////////////////////////////////////////////// p5.Renderer2D.prototype.background=function(){this.drawingContext.save();this.resetMatrix();if(arguments[0]instanceof p5.Image){this._pInst.image(arguments[0],0,0,this.width,this.height);}else{var curFill=this._getFill();// create background rect var color=this._pInst.color.apply(this._pInst,arguments);var newFill=color.toString();this._setFill(newFill);this.drawingContext.fillRect(0,0,this.width,this.height);// reset fill this._setFill(curFill);}this.drawingContext.restore();this._pInst._pixelsDirty=true;};p5.Renderer2D.prototype.clear=function(){this.drawingContext.save();this.resetMatrix();this.drawingContext.clearRect(0,0,this.width,this.height);this.drawingContext.restore();this._pInst._pixelsDirty=true;};p5.Renderer2D.prototype.fill=function(){var color=this._pInst.color.apply(this._pInst,arguments);this._setFill(color.toString());};p5.Renderer2D.prototype.stroke=function(){var color=this._pInst.color.apply(this._pInst,arguments);this._setStroke(color.toString());};////////////////////////////////////////////// // IMAGE | Loading & Displaying ////////////////////////////////////////////// p5.Renderer2D.prototype.image=function(img,sx,sy,sWidth,sHeight,dx,dy,dWidth,dHeight){var cnv;try{if(this._tint){if(p5.MediaElement&&img instanceof p5.MediaElement){img.loadPixels();}if(img.canvas){cnv=this._getTintedImageCanvas(img);}}if(!cnv){cnv=img.canvas||img.elt;}var s=1;if(img.width&&img.width>0){s=cnv.width/img.width;}this.drawingContext.drawImage(cnv,s*sx,s*sy,s*sWidth,s*sHeight,dx,dy,dWidth,dHeight);}catch(e){if(e.name!=='NS_ERROR_NOT_AVAILABLE'){throw e;}}this._pInst._pixelsDirty=true;};p5.Renderer2D.prototype._getTintedImageCanvas=function(img){if(!img.canvas){return img;}var pixels=filters._toPixels(img.canvas);var tmpCanvas=document.createElement('canvas');tmpCanvas.width=img.canvas.width;tmpCanvas.height=img.canvas.height;var tmpCtx=tmpCanvas.getContext('2d');var id=tmpCtx.createImageData(img.canvas.width,img.canvas.height);var newPixels=id.data;for(var i=0;i<pixels.length;i+=4){var r=pixels[i];var g=pixels[i+1];var b=pixels[i+2];var a=pixels[i+3];newPixels[i]=r*this._tint[0]/255;newPixels[i+1]=g*this._tint[1]/255;newPixels[i+2]=b*this._tint[2]/255;newPixels[i+3]=a*this._tint[3]/255;}tmpCtx.putImageData(id,0,0);return tmpCanvas;};////////////////////////////////////////////// // IMAGE | Pixels ////////////////////////////////////////////// p5.Renderer2D.prototype.blendMode=function(mode){this.drawingContext.globalCompositeOperation=mode;};p5.Renderer2D.prototype.blend=function(){var currBlend=this.drawingContext.globalCompositeOperation;var blendMode=arguments[arguments.length-1];var copyArgs=Array.prototype.slice.call(arguments,0,arguments.length-1);this.drawingContext.globalCompositeOperation=blendMode;if(this._pInst){this._pInst.copy.apply(this._pInst,copyArgs);}else{this.copy.apply(this,copyArgs);}this.drawingContext.globalCompositeOperation=currBlend;};p5.Renderer2D.prototype.copy=function(){var srcImage,sx,sy,sw,sh,dx,dy,dw,dh;if(arguments.length===9){srcImage=arguments[0];sx=arguments[1];sy=arguments[2];sw=arguments[3];sh=arguments[4];dx=arguments[5];dy=arguments[6];dw=arguments[7];dh=arguments[8];}else if(arguments.length===8){srcImage=this._pInst;sx=arguments[0];sy=arguments[1];sw=arguments[2];sh=arguments[3];dx=arguments[4];dy=arguments[5];dw=arguments[6];dh=arguments[7];}else{throw new Error('Signature not supported');}p5.Renderer2D._copyHelper(this,srcImage,sx,sy,sw,sh,dx,dy,dw,dh);this._pInst._pixelsDirty=true;};p5.Renderer2D._copyHelper=function(dstImage,srcImage,sx,sy,sw,sh,dx,dy,dw,dh){srcImage.loadPixels();var s=srcImage.canvas.width/srcImage.width;dstImage.drawingContext.drawImage(srcImage.canvas,s*sx,s*sy,s*sw,s*sh,dx,dy,dw,dh);};p5.Renderer2D.prototype.get=function(x,y,w,h){if(typeof w==='undefined'&&typeof h==='undefined'){if(typeof x==='undefined'&&typeof y==='undefined'){x=y=0;w=this.width;h=this.height;}else{w=h=1;}}// if the section does not overlap the canvas if(x+w<0||y+h<0||x>=this.width||y>=this.height){// TODO: is this valid for w,h > 1 ? return[0,0,0,255];}var ctx=this._pInst||this;var pd=ctx._pixelDensity;// round down to get integer numbers x=Math.floor(x);y=Math.floor(y);w=Math.floor(w);h=Math.floor(h);var sx=x*pd;var sy=y*pd;if(w===1&&h===1&&!(this instanceof p5.RendererGL)){var imageData,index;if(ctx._pixelsDirty){imageData=this.drawingContext.getImageData(sx,sy,1,1).data;index=0;}else{imageData=ctx.pixels;index=(sx+sy*this.width*pd)*4;}return[imageData[index+0],imageData[index+1],imageData[index+2],imageData[index+3]];}else{//auto constrain the width and height to //dimensions of the source image var dw=Math.min(w,ctx.width);var dh=Math.min(h,ctx.height);var sw=dw*pd;var sh=dh*pd;var region=new p5.Image(dw,dh);region.canvas.getContext('2d').drawImage(this.canvas,sx,sy,sw,sh,0,0,dw,dh);return region;}};p5.Renderer2D.prototype.loadPixels=function(){var ctx=this._pInst||this;// if called by p5.Image if(!ctx._pixelsDirty)return;ctx._pixelsDirty=false;var pd=ctx._pixelDensity;var w=this.width*pd;var h=this.height*pd;var imageData=this.drawingContext.getImageData(0,0,w,h);// @todo this should actually set pixels per object, so diff buffers can // have diff pixel arrays. ctx._setProperty('imageData',imageData);ctx._setProperty('pixels',imageData.data);};p5.Renderer2D.prototype.set=function(x,y,imgOrCol){// round down to get integer numbers x=Math.floor(x);y=Math.floor(y);var ctx=this._pInst||this;if(imgOrCol instanceof p5.Image){this.drawingContext.save();this.drawingContext.setTransform(1,0,0,1,0,0);this.drawingContext.scale(ctx._pixelDensity,ctx._pixelDensity);this.drawingContext.drawImage(imgOrCol.canvas,x,y);this.drawingContext.restore();ctx._pixelsDirty=true;}else{var r=0,g=0,b=0,a=0;var idx=4*(y*ctx._pixelDensity*(this.width*ctx._pixelDensity)+x*ctx._pixelDensity);if(!ctx.imageData||ctx._pixelsDirty){ctx.loadPixels.call(ctx);}if(typeof imgOrCol==='number'){if(idx<ctx.pixels.length){r=imgOrCol;g=imgOrCol;b=imgOrCol;a=255;//this.updatePixels.call(this); }}else if(imgOrCol instanceof Array){if(imgOrCol.length<4){throw new Error('pixel array must be of the form [R, G, B, A]');}if(idx<ctx.pixels.length){r=imgOrCol[0];g=imgOrCol[1];b=imgOrCol[2];a=imgOrCol[3];//this.updatePixels.call(this); }}else if(imgOrCol instanceof p5.Color){if(idx<ctx.pixels.length){r=imgOrCol.levels[0];g=imgOrCol.levels[1];b=imgOrCol.levels[2];a=imgOrCol.levels[3];//this.updatePixels.call(this); }}// loop over pixelDensity * pixelDensity for(var i=0;i<ctx._pixelDensity;i++){for(var j=0;j<ctx._pixelDensity;j++){// loop over idx=4*((y*ctx._pixelDensity+j)*this.width*ctx._pixelDensity+(x*ctx._pixelDensity+i));ctx.pixels[idx]=r;ctx.pixels[idx+1]=g;ctx.pixels[idx+2]=b;ctx.pixels[idx+3]=a;}}}};p5.Renderer2D.prototype.updatePixels=function(x,y,w,h){var ctx=this._pInst||this;var pd=ctx._pixelDensity;if(x===undefined&&y===undefined&&w===undefined&&h===undefined){x=0;y=0;w=this.width;h=this.height;}w*=pd;h*=pd;this.drawingContext.putImageData(ctx.imageData,x,y,0,0,w,h);if(x!==0||y!==0||w!==this.width||h!==this.height){ctx._pixelsDirty=true;}};////////////////////////////////////////////// // SHAPE | 2D Primitives ////////////////////////////////////////////// /** * Generate a cubic Bezier representing an arc on the unit circle of total * angle `size` radians, beginning `start` radians above the x-axis. Up to * four of these curves are combined to make a full arc. * * See www.joecridge.me/bezier.pdf for an explanation of the method. */p5.Renderer2D.prototype._acuteArcToBezier=function _acuteArcToBezier(start,size){// Evauate constants. var alpha=size/2.0,cos_alpha=Math.cos(alpha),sin_alpha=Math.sin(alpha),cot_alpha=1.0/Math.tan(alpha),phi=start+alpha,// This is how far the arc needs to be rotated. cos_phi=Math.cos(phi),sin_phi=Math.sin(phi),lambda=(4.0-cos_alpha)/3.0,mu=sin_alpha+(cos_alpha-lambda)*cot_alpha;// Return rotated waypoints. return{ax:Math.cos(start),ay:Math.sin(start),bx:lambda*cos_phi+mu*sin_phi,by:lambda*sin_phi-mu*cos_phi,cx:lambda*cos_phi-mu*sin_phi,cy:lambda*sin_phi+mu*cos_phi,dx:Math.cos(start+size),dy:Math.sin(start+size)};};p5.Renderer2D.prototype.arc=function(x,y,w,h,start,stop,mode){var ctx=this.drawingContext;var rx=w/2.0;var ry=h/2.0;var epsilon=0.00001;// Smallest visible angle on displays up to 4K. var arcToDraw=0;var curves=[];x+=rx;y+=ry;// Create curves while(stop-start>epsilon){arcToDraw=Math.min(stop-start,constants.HALF_PI);curves.push(this._acuteArcToBezier(start,arcToDraw));start+=arcToDraw;}// Fill curves if(this._doFill){ctx.beginPath();curves.forEach(function(curve,index){if(index===0){ctx.moveTo(x+curve.ax*rx,y+curve.ay*ry);}// prettier-ignore ctx.bezierCurveTo(x+curve.bx*rx,y+curve.by*ry,x+curve.cx*rx,y+curve.cy*ry,x+curve.dx*rx,y+curve.dy*ry);});if(mode===constants.PIE||mode==null){ctx.lineTo(x,y);}ctx.closePath();ctx.fill();}// Stroke curves if(this._doStroke){ctx.beginPath();curves.forEach(function(curve,index){if(index===0){ctx.moveTo(x+curve.ax*rx,y+curve.ay*ry);}// prettier-ignore ctx.bezierCurveTo(x+curve.bx*rx,y+curve.by*ry,x+curve.cx*rx,y+curve.cy*ry,x+curve.dx*rx,y+curve.dy*ry);});if(mode===constants.PIE){ctx.lineTo(x,y);ctx.closePath();}else if(mode===constants.CHORD){ctx.closePath();}ctx.stroke();}return this;};p5.Renderer2D.prototype.ellipse=function(args){var ctx=this.drawingContext;var doFill=this._doFill,doStroke=this._doStroke;var x=args[0],y=args[1],w=args[2],h=args[3];if(doFill&&!doStroke){if(this._getFill()===styleEmpty){return this;}}else if(!doFill&&doStroke){if(this._getStroke()===styleEmpty){return this;}}var kappa=0.5522847498,ox=w/2*kappa,// control point offset horizontal oy=h/2*kappa,// control point offset vertical xe=x+w,// x-end ye=y+h,// y-end xm=x+w/2,// x-middle ym=y+h/2;// y-middle ctx.beginPath();ctx.moveTo(x,ym);ctx.bezierCurveTo(x,ym-oy,xm-ox,y,xm,y);ctx.bezierCurveTo(xm+ox,y,xe,ym-oy,xe,ym);ctx.bezierCurveTo(xe,ym+oy,xm+ox,ye,xm,ye);ctx.bezierCurveTo(xm-ox,ye,x,ym+oy,x,ym);ctx.closePath();if(doFill){ctx.fill();}if(doStroke){ctx.stroke();}};p5.Renderer2D.prototype.line=function(x1,y1,x2,y2){var ctx=this.drawingContext;if(!this._doStroke){return this;}else if(this._getStroke()===styleEmpty){return this;}// Translate the line by (0.5, 0.5) to draw it crisp if(ctx.lineWidth%2===1){ctx.translate(0.5,0.5);}ctx.beginPath();ctx.moveTo(x1,y1);ctx.lineTo(x2,y2);ctx.stroke();if(ctx.lineWidth%2===1){ctx.translate(-0.5,-0.5);}return this;};p5.Renderer2D.prototype.point=function(x,y){var ctx=this.drawingContext;if(!this._doStroke){return this;}else if(this._getStroke()===styleEmpty){return this;}var s=this._getStroke();var f=this._getFill();x=Math.round(x);y=Math.round(y);// swapping fill color to stroke and back after for correct point rendering this._setFill(s);if(ctx.lineWidth>1){ctx.beginPath();ctx.arc(x,y,ctx.lineWidth/2,0,constants.TWO_PI,false);ctx.fill();}else{ctx.fillRect(x,y,1,1);}this._setFill(f);};p5.Renderer2D.prototype.quad=function(x1,y1,x2,y2,x3,y3,x4,y4){var ctx=this.drawingContext;var doFill=this._doFill,doStroke=this._doStroke;if(doFill&&!doStroke){if(this._getFill()===styleEmpty){return this;}}else if(!doFill&&doStroke){if(this._getStroke()===styleEmpty){return this;}}ctx.beginPath();ctx.moveTo(x1,y1);ctx.lineTo(x2,y2);ctx.lineTo(x3,y3);ctx.lineTo(x4,y4);ctx.closePath();if(doFill){ctx.fill();}if(doStroke){ctx.stroke();}return this;};p5.Renderer2D.prototype.rect=function(args){var x=args[0],y=args[1],w=args[2],h=args[3],tl=args[4],tr=args[5],br=args[6],bl=args[7];var ctx=this.drawingContext;var doFill=this._doFill,doStroke=this._doStroke;if(doFill&&!doStroke){if(this._getFill()===styleEmpty){return this;}}else if(!doFill&&doStroke){if(this._getStroke()===styleEmpty){return this;}}// Translate the line by (0.5, 0.5) to draw a crisp rectangle border if(this._doStroke&&ctx.lineWidth%2===1){ctx.translate(0.5,0.5);}ctx.beginPath();if(typeof tl==='undefined'){// No rounded corners ctx.rect(x,y,w,h);}else{// At least one rounded corner // Set defaults when not specified if(typeof tr==='undefined'){tr=tl;}if(typeof br==='undefined'){br=tr;}if(typeof bl==='undefined'){bl=br;}var hw=w/2;var hh=h/2;// Clip radii if(w<2*tl){tl=hw;}if(h<2*tl){tl=hh;}if(w<2*tr){tr=hw;}if(h<2*tr){tr=hh;}if(w<2*br){br=hw;}if(h<2*br){br=hh;}if(w<2*bl){bl=hw;}if(h<2*bl){bl=hh;}// Draw shape ctx.beginPath();ctx.moveTo(x+tl,y);ctx.arcTo(x+w,y,x+w,y+h,tr);ctx.arcTo(x+w,y+h,x,y+h,br);ctx.arcTo(x,y+h,x,y,bl);ctx.arcTo(x,y,x+w,y,tl);ctx.closePath();}if(this._doFill){ctx.fill();}if(this._doStroke){ctx.stroke();}if(this._doStroke&&ctx.lineWidth%2===1){ctx.translate(-0.5,-0.5);}return this;};p5.Renderer2D.prototype.triangle=function(args){var ctx=this.drawingContext;var doFill=this._doFill,doStroke=this._doStroke;var x1=args[0],y1=args[1];var x2=args[2],y2=args[3];var x3=args[4],y3=args[5];if(doFill&&!doStroke){if(this._getFill()===styleEmpty){return this;}}else if(!doFill&&doStroke){if(this._getStroke()===styleEmpty){return this;}}ctx.beginPath();ctx.moveTo(x1,y1);ctx.lineTo(x2,y2);ctx.lineTo(x3,y3);ctx.closePath();if(doFill){ctx.fill();}if(doStroke){ctx.stroke();}};p5.Renderer2D.prototype.endShape=function(mode,vertices,isCurve,isBezier,isQuadratic,isContour,shapeKind){if(vertices.length===0){return this;}if(!this._doStroke&&!this._doFill){return this;}var closeShape=mode===constants.CLOSE;var v;if(closeShape&&!isContour){vertices.push(vertices[0]);}var i,j;var numVerts=vertices.length;if(isCurve&&(shapeKind===constants.POLYGON||shapeKind===null)){if(numVerts>3){var b=[],s=1-this._curveTightness;this.drawingContext.beginPath();this.drawingContext.moveTo(vertices[1][0],vertices[1][1]);for(i=1;i+2<numVerts;i++){v=vertices[i];b[0]=[v[0],v[1]];b[1]=[v[0]+(s*vertices[i+1][0]-s*vertices[i-1][0])/6,v[1]+(s*vertices[i+1][1]-s*vertices[i-1][1])/6];b[2]=[vertices[i+1][0]+(s*vertices[i][0]-s*vertices[i+2][0])/6,vertices[i+1][1]+(s*vertices[i][1]-s*vertices[i+2][1])/6];b[3]=[vertices[i+1][0],vertices[i+1][1]];this.drawingContext.bezierCurveTo(b[1][0],b[1][1],b[2][0],b[2][1],b[3][0],b[3][1]);}if(closeShape){this.drawingContext.lineTo(vertices[i+1][0],vertices[i+1][1]);}this._doFillStrokeClose();}}else if(isBezier&&(shapeKind===constants.POLYGON||shapeKind===null)){this.drawingContext.beginPath();for(i=0;i<numVerts;i++){if(vertices[i].isVert){if(vertices[i].moveTo){this.drawingContext.moveTo(vertices[i][0],vertices[i][1]);}else{this.drawingContext.lineTo(vertices[i][0],vertices[i][1]);}}else{this.drawingContext.bezierCurveTo(vertices[i][0],vertices[i][1],vertices[i][2],vertices[i][3],vertices[i][4],vertices[i][5]);}}this._doFillStrokeClose();}else if(isQuadratic&&(shapeKind===constants.POLYGON||shapeKind===null)){this.drawingContext.beginPath();for(i=0;i<numVerts;i++){if(vertices[i].isVert){if(vertices[i].moveTo){this.drawingContext.moveTo([0],vertices[i][1]);}else{this.drawingContext.lineTo(vertices[i][0],vertices[i][1]);}}else{this.drawingContext.quadraticCurveTo(vertices[i][0],vertices[i][1],vertices[i][2],vertices[i][3]);}}this._doFillStrokeClose();}else{if(shapeKind===constants.POINTS){for(i=0;i<numVerts;i++){v=vertices[i];if(this._doStroke){this._pInst.stroke(v[6]);}this._pInst.point(v[0],v[1]);}}else if(shapeKind===constants.LINES){for(i=0;i+1<numVerts;i+=2){v=vertices[i];if(this._doStroke){this._pInst.stroke(vertices[i+1][6]);}this._pInst.line(v[0],v[1],vertices[i+1][0],vertices[i+1][1]);}}else if(shapeKind===constants.TRIANGLES){for(i=0;i+2<numVerts;i+=3){v=vertices[i];this.drawingContext.beginPath();this.drawingContext.moveTo(v[0],v[1]);this.drawingContext.lineTo(vertices[i+1][0],vertices[i+1][1]);this.drawingContext.lineTo(vertices[i+2][0],vertices[i+2][1]);this.drawingContext.closePath();if(this._doFill){this._pInst.fill(vertices[i+2][5]);this.drawingContext.fill();}if(this._doStroke){this._pInst.stroke(vertices[i+2][6]);this.drawingContext.stroke();}}}else if(shapeKind===constants.TRIANGLE_STRIP){for(i=0;i+1<numVerts;i++){v=vertices[i];this.drawingContext.beginPath();this.drawingContext.moveTo(vertices[i+1][0],vertices[i+1][1]);this.drawingContext.lineTo(v[0],v[1]);if(this._doStroke){this._pInst.stroke(vertices[i+1][6]);}if(this._doFill){this._pInst.fill(vertices[i+1][5]);}if(i+2<numVerts){this.drawingContext.lineTo(vertices[i+2][0],vertices[i+2][1]);if(this._doStroke){this._pInst.stroke(vertices[i+2][6]);}if(this._doFill){this._pInst.fill(vertices[i+2][5]);}}this._doFillStrokeClose();}}else if(shapeKind===constants.TRIANGLE_FAN){if(numVerts>2){// For performance reasons, try to batch as many of the // fill and stroke calls as possible. this.drawingContext.beginPath();for(i=2;i<numVerts;i++){v=vertices[i];this.drawingContext.moveTo(vertices[0][0],vertices[0][1]);this.drawingContext.lineTo(vertices[i-1][0],vertices[i-1][1]);this.drawingContext.lineTo(v[0],v[1]);this.drawingContext.lineTo(vertices[0][0],vertices[0][1]);// If the next colour is going to be different, stroke / fill now if(i<numVerts-1){if(this._doFill&&v[5]!==vertices[i+1][5]||this._doStroke&&v[6]!==vertices[i+1][6]){if(this._doFill){this._pInst.fill(v[5]);this.drawingContext.fill();this._pInst.fill(vertices[i+1][5]);}if(this._doStroke){this._pInst.stroke(v[6]);this.drawingContext.stroke();this._pInst.stroke(vertices[i+1][6]);}this.drawingContext.closePath();this.drawingContext.beginPath();// Begin the next one }}}this._doFillStrokeClose();}}else if(shapeKind===constants.QUADS){for(i=0;i+3<numVerts;i+=4){v=vertices[i];this.drawingContext.beginPath();this.drawingContext.moveTo(v[0],v[1]);for(j=1;j<4;j++){this.drawingContext.lineTo(vertices[i+j][0],vertices[i+j][1]);}this.drawingContext.lineTo(v[0],v[1]);if(this._doFill){this._pInst.fill(vertices[i+3][5]);}if(this._doStroke){this._pInst.stroke(vertices[i+3][6]);}this._doFillStrokeClose();}}else if(shapeKind===constants.QUAD_STRIP){if(numVerts>3){for(i=0;i+1<numVerts;i+=2){v=vertices[i];this.drawingContext.beginPath();if(i+3<numVerts){this.drawingContext.moveTo(vertices[i+2][0],vertices[i+2][1]);this.drawingContext.lineTo(v[0],v[1]);this.drawingContext.lineTo(vertices[i+1][0],vertices[i+1][1]);this.drawingContext.lineTo(vertices[i+3][0],vertices[i+3][1]);if(this._doFill){this._pInst.fill(vertices[i+3][5]);}if(this._doStroke){this._pInst.stroke(vertices[i+3][6]);}}else{this.drawingContext.moveTo(v[0],v[1]);this.drawingContext.lineTo(vertices[i+1][0],vertices[i+1][1]);}this._doFillStrokeClose();}}}else{this.drawingContext.beginPath();this.drawingContext.moveTo(vertices[0][0],vertices[0][1]);for(i=1;i<numVerts;i++){v=vertices[i];if(v.isVert){if(v.moveTo){this.drawingContext.moveTo(v[0],v[1]);}else{this.drawingContext.lineTo(v[0],v[1]);}}}this._doFillStrokeClose();}}isCurve=false;isBezier=false;isQuadratic=false;isContour=false;if(closeShape){vertices.pop();}this._pInst._pixelsDirty=true;return this;};////////////////////////////////////////////// // SHAPE | Attributes ////////////////////////////////////////////// p5.Renderer2D.prototype.noSmooth=function(){if('imageSmoothingEnabled'in this.drawingContext){this.drawingContext.imageSmoothingEnabled=false;}return this;};p5.Renderer2D.prototype.smooth=function(){if('imageSmoothingEnabled'in this.drawingContext){this.drawingContext.imageSmoothingEnabled=true;}return this;};p5.Renderer2D.prototype.strokeCap=function(cap){if(cap===constants.ROUND||cap===constants.SQUARE||cap===constants.PROJECT){this.drawingContext.lineCap=cap;}return this;};p5.Renderer2D.prototype.strokeJoin=function(join){if(join===constants.ROUND||join===constants.BEVEL||join===constants.MITER){this.drawingContext.lineJoin=join;}return this;};p5.Renderer2D.prototype.strokeWeight=function(w){if(typeof w==='undefined'||w===0){// hack because lineWidth 0 doesn't work this.drawingContext.lineWidth=0.0001;}else{this.drawingContext.lineWidth=w;}return this;};p5.Renderer2D.prototype._getFill=function(){if(!this._cachedFillStyle){this._cachedFillStyle=this.drawingContext.fillStyle;}return this._cachedFillStyle;};p5.Renderer2D.prototype._setFill=function(fillStyle){if(fillStyle!==this._cachedFillStyle){this.drawingContext.fillStyle=fillStyle;this._cachedFillStyle=fillStyle;}};p5.Renderer2D.prototype._getStroke=function(){if(!this._cachedStrokeStyle){this._cachedStrokeStyle=this.drawingContext.strokeStyle;}return this._cachedStrokeStyle;};p5.Renderer2D.prototype._setStroke=function(strokeStyle){if(strokeStyle!==this._cachedStrokeStyle){this.drawingContext.strokeStyle=strokeStyle;this._cachedStrokeStyle=strokeStyle;}};////////////////////////////////////////////// // SHAPE | Curves ////////////////////////////////////////////// p5.Renderer2D.prototype.bezier=function(x1,y1,x2,y2,x3,y3,x4,y4){this._pInst.beginShape();this._pInst.vertex(x1,y1);this._pInst.bezierVertex(x2,y2,x3,y3,x4,y4);this._pInst.endShape();return this;};p5.Renderer2D.prototype.curve=function(x1,y1,x2,y2,x3,y3,x4,y4){this._pInst.beginShape();this._pInst.curveVertex(x1,y1);this._pInst.curveVertex(x2,y2);this._pInst.curveVertex(x3,y3);this._pInst.curveVertex(x4,y4);this._pInst.endShape();return this;};////////////////////////////////////////////// // SHAPE | Vertex ////////////////////////////////////////////// p5.Renderer2D.prototype._doFillStrokeClose=function(){if(this._doFill){this.drawingContext.fill();}if(this._doStroke){this.drawingContext.stroke();}this.drawingContext.closePath();this._pInst._pixelsDirty=true;};////////////////////////////////////////////// // TRANSFORM ////////////////////////////////////////////// p5.Renderer2D.prototype.applyMatrix=function(a,b,c,d,e,f){this.drawingContext.transform(a,b,c,d,e,f);};p5.Renderer2D.prototype.resetMatrix=function(){this.drawingContext.setTransform(1,0,0,1,0,0);this.drawingContext.scale(this._pInst._pixelDensity,this._pInst._pixelDensity);return this;};p5.Renderer2D.prototype.rotate=function(rad){this.drawingContext.rotate(rad);};p5.Renderer2D.prototype.scale=function(x,y){this.drawingContext.scale(x,y);return this;};p5.Renderer2D.prototype.shearX=function(rad){this.drawingContext.transform(1,0,Math.tan(rad),1,0,0);return this;};p5.Renderer2D.prototype.shearY=function(rad){this.drawingContext.transform(1,Math.tan(rad),0,1,0,0);return this;};p5.Renderer2D.prototype.translate=function(x,y){// support passing a vector as the 1st parameter if(x instanceof p5.Vector){y=x.y;x=x.x;}this.drawingContext.translate(x,y);return this;};////////////////////////////////////////////// // TYPOGRAPHY // ////////////////////////////////////////////// p5.Renderer2D.prototype.text=function(str,x,y,maxWidth,maxHeight){var baselineHacked;// baselineHacked: (HACK) // A temporary fix to conform to Processing's implementation // of BASELINE vertical alignment in a bounding box if(typeof maxWidth!=='undefined'&&typeof maxHeight!=='undefined'){if(this.drawingContext.textBaseline===constants.BASELINE){baselineHacked=true;this.drawingContext.textBaseline=constants.TOP;}}var p=p5.Renderer.prototype.text.apply(this,arguments);if(baselineHacked){this.drawingContext.textBaseline=constants.BASELINE;}return p;};p5.Renderer2D.prototype._renderText=function(p,line,x,y,maxY){if(y>=maxY){return;// don't render lines beyond our maxY position }p.push();// fix to #803 if(!this._isOpenType()){// a system/browser font // no stroke unless specified by user if(this._doStroke&&this._strokeSet){this.drawingContext.strokeText(line,x,y);}if(this._doFill){// if fill hasn't been set by user, use default text fill if(!this._fillSet){this._setFill(constants._DEFAULT_TEXT_FILL);}this.drawingContext.fillText(line,x,y);}}else{// an opentype font, let it handle the rendering this._textFont._renderPath(line,x,y,{renderer:this});}p.pop();this._pInst._pixelsDirty=true;return p;};p5.Renderer2D.prototype.textWidth=function(s){if(this._isOpenType()){return this._textFont._textWidth(s,this._textSize);}return this.drawingContext.measureText(s).width;};p5.Renderer2D.prototype._applyTextProperties=function(){var font,p=this._pInst;this._setProperty('_textAscent',null);this._setProperty('_textDescent',null);font=this._textFont;if(this._isOpenType()){font=this._textFont.font.familyName;this._setProperty('_textStyle',this._textFont.font.styleName);}this.drawingContext.font=(this._textStyle||'normal')+' '+(this._textSize||12)+'px '+(font||'sans-serif');this.drawingContext.textAlign=this._textAlign;if(this._textBaseline===constants.CENTER){this.drawingContext.textBaseline=constants._CTX_MIDDLE;}else{this.drawingContext.textBaseline=this._textBaseline;}return p;};////////////////////////////////////////////// // STRUCTURE ////////////////////////////////////////////// // a push() operation is in progress. // the renderer should return a 'style' object that it wishes to // store on the push stack. // derived renderers should call the base class' push() method // to fetch the base style object. p5.Renderer2D.prototype.push=function(){this.drawingContext.save();// get the base renderer style return p5.Renderer.prototype.push.apply(this);};// a pop() operation is in progress // the renderer is passed the 'style' object that it returned // from its push() method. // derived renderers should pass this object to their base // class' pop method p5.Renderer2D.prototype.pop=function(style){this.drawingContext.restore();// Re-cache the fill / stroke state this._cachedFillStyle=this.drawingContext.fillStyle;this._cachedStrokeStyle=this.drawingContext.strokeStyle;p5.Renderer.prototype.pop.call(this,style);};module.exports=p5.Renderer2D;},{"../image/filters":43,"./constants":19,"./main":25,"./p5.Renderer":28}],30:[function(_dereq_,module,exports){/** * @module Rendering * @submodule Rendering * @for p5 */'use strict';var p5=_dereq_('./main');var constants=_dereq_('./constants');_dereq_('./p5.Graphics');_dereq_('./p5.Renderer2D');_dereq_('../webgl/p5.RendererGL');var defaultId='defaultCanvas0';// this gets set again in createCanvas var defaultClass='p5Canvas';/** * Creates a canvas element in the document, and sets the dimensions of it * in pixels. This method should be called only once at the start of setup. * Calling <a href="#/p5/createCanvas">createCanvas</a> more than once in a sketch will result in very * unpredictable behavior. If you want more than one drawing canvas * you could use <a href="#/p5/createGraphics">createGraphics</a> (hidden by default but it can be shown). * <br><br> * The system variables width and height are set by the parameters passed * to this function. If <a href="#/p5/createCanvas">createCanvas()</a> is not used, the window will be * given a default size of 100x100 pixels. * <br><br> * For more ways to position the canvas, see the * <a href='https://github.com/processing/p5.js/wiki/Positioning-your-canvas'> * positioning the canvas</a> wiki page. * * @method createCanvas * @param {Number} w width of the canvas * @param {Number} h height of the canvas * @param {Constant} [renderer] either P2D or WEBGL * @return {p5.Renderer} * @example * <div> * <code> * function setup() { * createCanvas(100, 50); * background(153); * line(0, 0, width, height); * } * </code> * </div> * * @alt * Black line extending from top-left of canvas to bottom right. * */p5.prototype.createCanvas=function(w,h,renderer){p5._validateParameters('createCanvas',arguments);//optional: renderer, otherwise defaults to p2d var r=renderer||constants.P2D;var c;if(r===constants.WEBGL){c=document.getElementById(defaultId);if(c){//if defaultCanvas already exists c.parentNode.removeChild(c);//replace the existing defaultCanvas var thisRenderer=this._renderer;this._elements=this._elements.filter(function(e){return e!==thisRenderer;});}c=document.createElement('canvas');c.id=defaultId;c.classList.add(defaultClass);}else{if(!this._defaultGraphicsCreated){c=document.createElement('canvas');var i=0;while(document.getElementById('defaultCanvas'+i)){i++;}defaultId='defaultCanvas'+i;c.id=defaultId;c.classList.add(defaultClass);}else{// resize the default canvas if new one is created c=this.canvas;}}// set to invisible if still in setup (to prevent flashing with manipulate) if(!this._setupDone){c.dataset.hidden=true;// tag to show later c.style.visibility='hidden';}if(this._userNode){// user input node case this._userNode.appendChild(c);}else{document.body.appendChild(c);}// Init our graphics renderer //webgl mode if(r===constants.WEBGL){this._setProperty('_renderer',new p5.RendererGL(c,this,true));this._elements.push(this._renderer);}else{//P2D mode if(!this._defaultGraphicsCreated){this._setProperty('_renderer',new p5.Renderer2D(c,this,true));this._defaultGraphicsCreated=true;this._elements.push(this._renderer);}}this._renderer.resize(w,h);this._renderer._applyDefaults();return this._renderer;};/** * Resizes the canvas to given width and height. The canvas will be cleared * and draw will be called immediately, allowing the sketch to re-render itself * in the resized canvas. * @method resizeCanvas * @param {Number} w width of the canvas * @param {Number} h height of the canvas * @param {Boolean} [noRedraw] don't redraw the canvas immediately * @example * <div class="norender"><code> * function setup() { * createCanvas(windowWidth, windowHeight); * } * * function draw() { * background(0, 100, 200); * } * * function windowResized() { * resizeCanvas(windowWidth, windowHeight); * } * </code></div> * * @alt * No image displayed. * */p5.prototype.resizeCanvas=function(w,h,noRedraw){p5._validateParameters('resizeCanvas',arguments);if(this._renderer){// save canvas properties var props={};for(var key in this.drawingContext){var val=this.drawingContext[key];if((typeof val==="undefined"?"undefined":_typeof(val))!=='object'&&typeof val!=='function'){props[key]=val;}}this._renderer.resize(w,h);this.width=w;this.height=h;// reset canvas properties for(var savedKey in props){try{this.drawingContext[savedKey]=props[savedKey];}catch(err){// ignore read-only property errors }}if(!noRedraw){this.redraw();}}};/** * Removes the default canvas for a p5 sketch that doesn't * require a canvas * @method noCanvas * @example * <div> * <code> * function setup() { * noCanvas(); * } * </code> * </div> * * @alt * no image displayed * */p5.prototype.noCanvas=function(){if(this.canvas){this.canvas.parentNode.removeChild(this.canvas);}};/** * Creates and returns a new p5.Renderer object. Use this class if you need * to draw into an off-screen graphics buffer. The two parameters define the * width and height in pixels. * * @method createGraphics * @param {Number} w width of the offscreen graphics buffer * @param {Number} h height of the offscreen graphics buffer * @param {Constant} [renderer] either P2D or WEBGL * undefined defaults to p2d * @return {p5.Graphics} offscreen graphics buffer * @example * <div> * <code> * var pg; * function setup() { * createCanvas(100, 100); * pg = createGraphics(100, 100); * } * function draw() { * background(200); * pg.background(100); * pg.noStroke(); * pg.ellipse(pg.width / 2, pg.height / 2, 50, 50); * image(pg, 50, 50); * image(pg, 0, 0, 50, 50); * } * </code> * </div> * * @alt * 4 grey squares alternating light and dark grey. White quarter circle mid-left. * */p5.prototype.createGraphics=function(w,h,renderer){p5._validateParameters('createGraphics',arguments);return new p5.Graphics(w,h,renderer,this);};/** * Blends the pixels in the display window according to the defined mode. * There is a choice of the following modes to blend the source pixels (A) * with the ones of pixels already in the display window (B): * <ul> * <li><code>BLEND</code> - linear interpolation of colours: C = * A\*factor + B. This is the default blending mode.</li> * <li><code>ADD</code> - sum of A and B</li> * <li><code>DARKEST</code> - only the darkest colour succeeds: C = * min(A\*factor, B).</li> * <li><code>LIGHTEST</code> - only the lightest colour succeeds: C = * max(A\*factor, B).</li> * <li><code>DIFFERENCE</code> - subtract colors from underlying image.</li> * <li><code>EXCLUSION</code> - similar to <code>DIFFERENCE</code>, but less * extreme.</li> * <li><code>MULTIPLY</code> - multiply the colors, result will always be * darker.</li> * <li><code>SCREEN</code> - opposite multiply, uses inverse values of the * colors.</li> * <li><code>REPLACE</code> - the pixels entirely replace the others and * don't utilize alpha (transparency) values.</li> * <li><code>OVERLAY</code> - mix of <code>MULTIPLY</code> and <code>SCREEN * </code>. Multiplies dark values, and screens light values.</li> * <li><code>HARD_LIGHT</code> - <code>SCREEN</code> when greater than 50% * gray, <code>MULTIPLY</code> when lower.</li> * <li><code>SOFT_LIGHT</code> - mix of <code>DARKEST</code> and * <code>LIGHTEST</code>. Works like <code>OVERLAY</code>, but not as harsh. * </li> * <li><code>DODGE</code> - lightens light tones and increases contrast, * ignores darks.</li> * <li><code>BURN</code> - darker areas are applied, increasing contrast, * ignores lights.</li> * </ul> * * @method blendMode * @param {Constant} mode blend mode to set for canvas. * either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY, * EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL * @example * <div> * <code> * blendMode(LIGHTEST); * strokeWeight(30); * stroke(80, 150, 255); * line(25, 25, 75, 75); * stroke(255, 50, 50); * line(75, 25, 25, 75); * </code> * </div> * <div> * <code> * blendMode(MULTIPLY); * strokeWeight(30); * stroke(80, 150, 255); * line(25, 25, 75, 75); * stroke(255, 50, 50); * line(75, 25, 25, 75); * </code> * </div> * @alt * translucent image thick red & blue diagonal rounded lines intersecting center * Thick red & blue diagonal rounded lines intersecting center. dark at overlap * */p5.prototype.blendMode=function(mode){p5._validateParameters('blendMode',arguments);if(mode===constants.BLEND||mode===constants.DARKEST||mode===constants.LIGHTEST||mode===constants.DIFFERENCE||mode===constants.MULTIPLY||mode===constants.EXCLUSION||mode===constants.SCREEN||mode===constants.REPLACE||mode===constants.OVERLAY||mode===constants.HARD_LIGHT||mode===constants.SOFT_LIGHT||mode===constants.DODGE||mode===constants.BURN||mode===constants.ADD||mode===constants.NORMAL){this._renderer.blendMode(mode);}else{throw new Error('Mode '+mode+' not recognized.');}};module.exports=p5;},{"../webgl/p5.RendererGL":75,"./constants":19,"./main":25,"./p5.Graphics":27,"./p5.Renderer2D":29}],31:[function(_dereq_,module,exports){/** * @module Shape * @submodule 2D Primitives * @for p5 * @requires core * @requires constants */'use strict';var p5=_dereq_('../main');var constants=_dereq_('../constants');var canvas=_dereq_('../helpers');_dereq_('../error_helpers');/** * Draw an arc to the screen. If called with only x, y, w, h, start, and * stop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc * will be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The * origin may be changed with the <a href="#/p5/ellipseMode">ellipseMode()</a> function.<br><br> * Note that drawing a full circle (ex: 0 to TWO_PI) will appear blank * because 0 and TWO_PI are the same position on the unit circle. The * best way to handle this is by using the <a href="#/p5/ellipse">ellipse()</a> function instead * to create a closed ellipse, and to use the <a href="#/p5/arc">arc()</a> function * only to draw parts of an ellipse. * * @method arc * @param {Number} x x-coordinate of the arc's ellipse * @param {Number} y y-coordinate of the arc's ellipse * @param {Number} w width of the arc's ellipse by default * @param {Number} h height of the arc's ellipse by default * @param {Number} start angle to start the arc, specified in radians * @param {Number} stop angle to stop the arc, specified in radians * @param {Constant} [mode] optional parameter to determine the way of drawing * the arc. either CHORD, PIE or OPEN * @param {Number} [detail] optional parameter for WebGL mode only. This is to * specify the number of vertices that makes up the * perimeter of the arc. Default value is 25. * * @chainable * @example * <div> * <code> * arc(50, 55, 50, 50, 0, HALF_PI); * noFill(); * arc(50, 55, 60, 60, HALF_PI, PI); * arc(50, 55, 70, 70, PI, PI + QUARTER_PI); * arc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI); * </code> * </div> * * <div> * <code> * arc(50, 50, 80, 80, 0, PI + QUARTER_PI); * </code> * </div> * * <div> * <code> * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN); * </code> * </div> * * <div> * <code> * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD); * </code> * </div> * * <div> * <code> * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE); * </code> * </div> * * @alt *shattered outline of an ellipse with a quarter of a white circle bottom-right. *white ellipse with top right quarter missing. *white ellipse with black outline with top right missing. *white ellipse with top right missing with black outline around shape. *white ellipse with top right quarter missing with black outline around the shape. * */p5.prototype.arc=function(x,y,w,h,start,stop,mode,detail){p5._validateParameters('arc',arguments);// if the current stroke and fill settings wouldn't result in something // visible, exit immediately if(!this._renderer._doStroke&&!this._renderer._doFill){return this;}start=this._toRadians(start);stop=this._toRadians(stop);// Make all angles positive... while(start<0){start+=constants.TWO_PI;}while(stop<0){stop+=constants.TWO_PI;}if(typeof start!=='undefined'&&typeof stop!=='undefined'){// don't display anything if the angles are same or they have a difference of 0 - TWO_PI if(stop.toFixed(10)===start.toFixed(10)||Math.abs(stop-start)===constants.TWO_PI){start%=constants.TWO_PI;stop%=constants.TWO_PI;start+=constants.TWO_PI;}else if(Math.abs(stop-start)>constants.TWO_PI){// display a full circle if the difference between them is greater than 0 - TWO_PI start%=constants.TWO_PI;stop%=constants.TWO_PI;stop+=constants.TWO_PI;}}//Adjust angles to counter linear scaling. if(start<=constants.HALF_PI){start=Math.atan(w/h*Math.tan(start));}else if(start>constants.HALF_PI&&start<=3*constants.HALF_PI){start=Math.atan(w/h*Math.tan(start))+constants.PI;}if(stop<=constants.HALF_PI){stop=Math.atan(w/h*Math.tan(stop));}else if(stop>constants.HALF_PI&&stop<=3*constants.HALF_PI){stop=Math.atan(w/h*Math.tan(stop))+constants.PI;}// Exceed the interval if necessary in order to preserve the size and // orientation of the arc. if(start>stop){stop+=constants.TWO_PI;}// p5 supports negative width and heights for ellipses w=Math.abs(w);h=Math.abs(h);var vals=canvas.modeAdjust(x,y,w,h,this._renderer._ellipseMode);this._renderer.arc(vals.x,vals.y,vals.w,vals.h,start,stop,mode,detail);return this;};/** * Draws an ellipse (oval) to the screen. An ellipse with equal width and * height is a circle. By default, the first two parameters set the location, * and the third and fourth parameters set the shape's width and height. If * no height is specified, the value of width is used for both the width and * height. If a negative height or width is specified, the absolute value is taken. * The origin may be changed with the <a href="#/p5/ellipseMode">ellipseMode()</a> function. * * @method ellipse * @param {Number} x x-coordinate of the ellipse. * @param {Number} y y-coordinate of the ellipse. * @param {Number} w width of the ellipse. * @param {Number} [h] height of the ellipse. * @chainable * @example * <div> * <code> * ellipse(56, 46, 55, 55); * </code> * </div> * * @alt *white ellipse with black outline in middle-right of canvas that is 55x55. * *//** * @method ellipse * @param {Number} x * @param {Number} y * @param {Number} w * @param {Number} h * @param {Integer} detail number of radial sectors to draw */p5.prototype.ellipse=function(x,y,w,h,detailX){p5._validateParameters('ellipse',arguments);// if the current stroke and fill settings wouldn't result in something // visible, exit immediately if(!this._renderer._doStroke&&!this._renderer._doFill){return this;}// p5 supports negative width and heights for rects if(w<0){w=Math.abs(w);}if(typeof h==='undefined'){// Duplicate 3rd argument if only 3 given. h=w;}else if(h<0){h=Math.abs(h);}var vals=canvas.modeAdjust(x,y,w,h,this._renderer._ellipseMode);this._renderer.ellipse([vals.x,vals.y,vals.w,vals.h,detailX]);return this;};/** * Draws a line (a direct path between two points) to the screen. The version * of <a href="#/p5/line">line()</a> with four parameters draws the line in 2D. To color a line, use * the <a href="#/p5/stroke">stroke()</a> function. A line cannot be filled, therefore the <a href="#/p5/fill">fill()</a> * function will not affect the color of a line. 2D lines are drawn with a * width of one pixel by default, but this can be changed with the * <a href="#/p5/strokeWeight">strokeWeight()</a> function. * * @method line * @param {Number} x1 the x-coordinate of the first point * @param {Number} y1 the y-coordinate of the first point * @param {Number} x2 the x-coordinate of the second point * @param {Number} y2 the y-coordinate of the second point * @chainable * @example * <div> * <code> * line(30, 20, 85, 75); * </code> * </div> * * <div> * <code> * line(30, 20, 85, 20); * stroke(126); * line(85, 20, 85, 75); * stroke(255); * line(85, 75, 30, 75); * </code> * </div> * * @alt *line 78 pixels long running from mid-top to bottom-right of canvas. *3 lines of various stroke sizes. Form top, bottom and right sides of a square. * *//** * @method line * @param {Number} x1 * @param {Number} y1 * @param {Number} z1 the z-coordinate of the first point * @param {Number} x2 * @param {Number} y2 * @param {Number} z2 the z-coordinate of the second point * @chainable */p5.prototype.line=function(){p5._validateParameters('line',arguments);if(this._renderer._doStroke){this._renderer.line.apply(this._renderer,arguments);}return this;};/** * Draws a point, a coordinate in space at the dimension of one pixel. * The first parameter is the horizontal value for the point, the second * value is the vertical value for the point. The color of the point is * determined by the current stroke. * * @method point * @param {Number} x the x-coordinate * @param {Number} y the y-coordinate * @param {Number} [z] the z-coordinate (for WEBGL mode) * @chainable * @example * <div> * <code> * point(30, 20); * point(85, 20); * point(85, 75); * point(30, 75); * </code> * </div> * * @alt *4 points centered in the middle-right of the canvas. * */p5.prototype.point=function(){p5._validateParameters('point',arguments);if(this._renderer._doStroke){this._renderer.point.apply(this._renderer,arguments);}return this;};/** * Draw a quad. A quad is a quadrilateral, a four sided polygon. It is * similar to a rectangle, but the angles between its edges are not * constrained to ninety degrees. The first pair of parameters (x1,y1) * sets the first vertex and the subsequent pairs should proceed * clockwise or counter-clockwise around the defined shape. * * @method quad * @param {Number} x1 the x-coordinate of the first point * @param {Number} y1 the y-coordinate of the first point * @param {Number} x2 the x-coordinate of the second point * @param {Number} y2 the y-coordinate of the second point * @param {Number} x3 the x-coordinate of the third point * @param {Number} y3 the y-coordinate of the third point * @param {Number} x4 the x-coordinate of the fourth point * @param {Number} y4 the y-coordinate of the fourth point * @chainable * @example * <div> * <code> * quad(38, 31, 86, 20, 69, 63, 30, 76); * </code> * </div> * * @alt *irregular white quadrilateral shape with black outline mid-right of canvas. * *//** * @method quad * @param {Number} x1 * @param {Number} y1 * @param {Number} z1 the z-coordinate of the first point * @param {Number} x2 * @param {Number} y2 * @param {Number} z2 the z-coordinate of the second point * @param {Number} x3 * @param {Number} y3 * @param {Number} z3 the z-coordinate of the third point * @param {Number} x4 * @param {Number} y4 * @param {Number} z4 the z-coordinate of the fourth point * @chainable */p5.prototype.quad=function(){p5._validateParameters('quad',arguments);if(this._renderer._doStroke||this._renderer._doFill){this._renderer.quad.apply(this._renderer,arguments);}return this;};/** * Draws a rectangle to the screen. A rectangle is a four-sided shape with * every angle at ninety degrees. By default, the first two parameters set * the location of the upper-left corner, the third sets the width, and the * fourth sets the height. The way these parameters are interpreted, however, * may be changed with the <a href="#/p5/rectMode">rectMode()</a> function. * <br><br> * The fifth, sixth, seventh and eighth parameters, if specified, * determine corner radius for the top-left, top-right, lower-right and * lower-left corners, respectively. An omitted corner radius parameter is set * to the value of the previously specified radius value in the parameter list. * * @method rect * @param {Number} x x-coordinate of the rectangle. * @param {Number} y y-coordinate of the rectangle. * @param {Number} w width of the rectangle. * @param {Number} h height of the rectangle. * @param {Number} [tl] optional radius of top-left corner. * @param {Number} [tr] optional radius of top-right corner. * @param {Number} [br] optional radius of bottom-right corner. * @param {Number} [bl] optional radius of bottom-left corner. * @chainable * @example * <div> * <code> * // Draw a rectangle at location (30, 20) with a width and height of 55. * rect(30, 20, 55, 55); * </code> * </div> * * <div> * <code> * // Draw a rectangle with rounded corners, each having a radius of 20. * rect(30, 20, 55, 55, 20); * </code> * </div> * * <div> * <code> * // Draw a rectangle with rounded corners having the following radii: * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5. * rect(30, 20, 55, 55, 20, 15, 10, 5); * </code> * </div> * * @alt * 55x55 white rect with black outline in mid-right of canvas. * 55x55 white rect with black outline and rounded edges in mid-right of canvas. * 55x55 white rect with black outline and rounded edges of different radii. *//** * @method rect * @param {Number} x * @param {Number} y * @param {Number} w * @param {Number} h * @param {Integer} [detailX] number of segments in the x-direction * @param {Integer} [detailY] number of segments in the y-direction * @chainable */p5.prototype.rect=function(){p5._validateParameters('rect',arguments);if(this._renderer._doStroke||this._renderer._doFill){var vals=canvas.modeAdjust(arguments[0],arguments[1],arguments[2],arguments[3],this._renderer._rectMode);var args=[vals.x,vals.y,vals.w,vals.h];// append the additional arguments (either cornder radii, or // segment details) to the argument list for(var i=4;i<arguments.length;i++){args[i]=arguments[i];}this._renderer.rect(args);}return this;};/** * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the * second point, and the last two arguments specify the third point. * * @method triangle * @param {Number} x1 x-coordinate of the first point * @param {Number} y1 y-coordinate of the first point * @param {Number} x2 x-coordinate of the second point * @param {Number} y2 y-coordinate of the second point * @param {Number} x3 x-coordinate of the third point * @param {Number} y3 y-coordinate of the third point * @chainable * @example * <div> * <code> * triangle(30, 75, 58, 20, 86, 75); * </code> * </div> * *@alt * white triangle with black outline in mid-right of canvas. * */p5.prototype.triangle=function(){p5._validateParameters('triangle',arguments);if(this._renderer._doStroke||this._renderer._doFill){this._renderer.triangle(arguments);}return this;};module.exports=p5;},{"../constants":19,"../error_helpers":21,"../helpers":22,"../main":25}],32:[function(_dereq_,module,exports){/** * @module Shape * @submodule Attributes * @for p5 * @requires core * @requires constants */'use strict';var p5=_dereq_('../main');var constants=_dereq_('../constants');/** * Modifies the location from which ellipses are drawn by changing the way * in which parameters given to <a href="#/p5/ellipse">ellipse()</a> are interpreted. * <br><br> * The default mode is ellipseMode(CENTER), which interprets the first two * parameters of <a href="#/p5/ellipse">ellipse()</a> as the shape's center point, while the third and * fourth parameters are its width and height. * <br><br> * ellipseMode(RADIUS) also uses the first two parameters of <a href="#/p5/ellipse">ellipse()</a> as * the shape's center point, but uses the third and fourth parameters to * specify half of the shapes's width and height. * <br><br> * ellipseMode(CORNER) interprets the first two parameters of <a href="#/p5/ellipse">ellipse()</a> as * the upper-left corner of the shape, while the third and fourth parameters * are its width and height. * <br><br> * ellipseMode(CORNERS) interprets the first two parameters of <a href="#/p5/ellipse">ellipse()</a> as * the location of one corner of the ellipse's bounding box, and the third * and fourth parameters as the location of the opposite corner. * <br><br> * The parameter must be written in ALL CAPS because Javascript is a * case-sensitive language. * * @method ellipseMode * @param {Constant} mode either CENTER, RADIUS, CORNER, or CORNERS * @chainable * @example * <div> * <code> * ellipseMode(RADIUS); // Set ellipseMode to RADIUS * fill(255); // Set fill to white * ellipse(50, 50, 30, 30); // Draw white ellipse using RADIUS mode * * ellipseMode(CENTER); // Set ellipseMode to CENTER * fill(100); // Set fill to gray * ellipse(50, 50, 30, 30); // Draw gray ellipse using CENTER mode * </code> * </div> * * <div> * <code> * ellipseMode(CORNER); // Set ellipseMode is CORNER * fill(255); // Set fill to white * ellipse(25, 25, 50, 50); // Draw white ellipse using CORNER mode * * ellipseMode(CORNERS); // Set ellipseMode to CORNERS * fill(100); // Set fill to gray * ellipse(25, 25, 50, 50); // Draw gray ellipse using CORNERS mode * </code> * </div> * * @alt * 60x60 white ellipse and 30x30 grey ellipse with black outlines at center. * 60x60 white ellipse @center and 30x30 grey ellipse top-right, black outlines. * */p5.prototype.ellipseMode=function(m){p5._validateParameters('ellipseMode',arguments);if(m===constants.CORNER||m===constants.CORNERS||m===constants.RADIUS||m===constants.CENTER){this._renderer._ellipseMode=m;}return this;};/** * Draws all geometry with jagged (aliased) edges. Note that <a href="#/p5/smooth">smooth()</a> is * active by default in 2D mode, so it is necessary to call <a href="#/p5/noSmooth">noSmooth()</a> to disable * smoothing of geometry, images, and fonts. In 3D mode, <a href="#/p5/noSmooth">noSmooth()</a> is enabled * by default, so it is necessary to call <a href="#/p5/smooth">smooth()</a> if you would like * smooth (antialiased) edges on your geometry. * * @method noSmooth * @chainable * @example * <div> * <code> * background(0); * noStroke(); * smooth(); * ellipse(30, 48, 36, 36); * noSmooth(); * ellipse(70, 48, 36, 36); * </code> * </div> * * @alt * 2 pixelated 36x36 white ellipses to left & right of center, black background * */p5.prototype.noSmooth=function(){this._renderer.noSmooth();return this;};/** * Modifies the location from which rectangles are drawn by changing the way * in which parameters given to <a href="#/p5/rect">rect()</a> are interpreted. * <br><br> * The default mode is rectMode(CORNER), which interprets the first two * parameters of <a href="#/p5/rect">rect()</a> as the upper-left corner of the shape, while the * third and fourth parameters are its width and height. * <br><br> * rectMode(CORNERS) interprets the first two parameters of <a href="#/p5/rect">rect()</a> as the * location of one corner, and the third and fourth parameters as the * location of the opposite corner. * <br><br> * rectMode(CENTER) interprets the first two parameters of <a href="#/p5/rect">rect()</a> as the * shape's center point, while the third and fourth parameters are its * width and height. * <br><br> * rectMode(RADIUS) also uses the first two parameters of <a href="#/p5/rect">rect()</a> as the * shape's center point, but uses the third and fourth parameters to specify * half of the shapes's width and height. * <br><br> * The parameter must be written in ALL CAPS because Javascript is a * case-sensitive language. * * @method rectMode * @param {Constant} mode either CORNER, CORNERS, CENTER, or RADIUS * @chainable * @example * <div> * <code> * rectMode(CORNER); // Default rectMode is CORNER * fill(255); // Set fill to white * rect(25, 25, 50, 50); // Draw white rect using CORNER mode * * rectMode(CORNERS); // Set rectMode to CORNERS * fill(100); // Set fill to gray * rect(25, 25, 50, 50); // Draw gray rect using CORNERS mode * </code> * </div> * * <div> * <code> * rectMode(RADIUS); // Set rectMode to RADIUS * fill(255); // Set fill to white * rect(50, 50, 30, 30); // Draw white rect using RADIUS mode * * rectMode(CENTER); // Set rectMode to CENTER * fill(100); // Set fill to gray * rect(50, 50, 30, 30); // Draw gray rect using CENTER mode * </code> * </div> * * @alt * 50x50 white rect at center and 25x25 grey rect in the top left of the other. * 50x50 white rect at center and 25x25 grey rect in the center of the other. * */p5.prototype.rectMode=function(m){p5._validateParameters('rectMode',arguments);if(m===constants.CORNER||m===constants.CORNERS||m===constants.RADIUS||m===constants.CENTER){this._renderer._rectMode=m;}return this;};/** * Draws all geometry with smooth (anti-aliased) edges. <a href="#/p5/smooth">smooth()</a> will also * improve image quality of resized images. Note that <a href="#/p5/smooth">smooth()</a> is active by * default in 2D mode; <a href="#/p5/noSmooth">noSmooth()</a> can be used to disable smoothing of geometry, * images, and fonts. In 3D mode, <a href="#/p5/noSmooth">noSmooth()</a> is enabled * by default, so it is necessary to call <a href="#/p5/smooth">smooth()</a> if you would like * smooth (antialiased) edges on your geometry. * * @method smooth * @chainable * @example * <div> * <code> * background(0); * noStroke(); * smooth(); * ellipse(30, 48, 36, 36); * noSmooth(); * ellipse(70, 48, 36, 36); * </code> * </div> * * @alt * 2 pixelated 36x36 white ellipses one left one right of center. On black. * */p5.prototype.smooth=function(){this._renderer.smooth();return this;};/** * Sets the style for rendering line endings. These ends are either squared, * extended, or rounded, each of which specified with the corresponding * parameters: SQUARE, PROJECT, and ROUND. The default cap is ROUND. * * @method strokeCap * @param {Constant} cap either SQUARE, PROJECT, or ROUND * @chainable * @example * <div> * <code> * strokeWeight(12.0); * strokeCap(ROUND); * line(20, 30, 80, 30); * strokeCap(SQUARE); * line(20, 50, 80, 50); * strokeCap(PROJECT); * line(20, 70, 80, 70); * </code> * </div> * * @alt * 3 lines. Top line: rounded ends, mid: squared, bottom:longer squared ends. * */p5.prototype.strokeCap=function(cap){p5._validateParameters('strokeCap',arguments);if(cap===constants.ROUND||cap===constants.SQUARE||cap===constants.PROJECT){this._renderer.strokeCap(cap);}return this;};/** * Sets the style of the joints which connect line segments. These joints * are either mitered, beveled, or rounded and specified with the * corresponding parameters MITER, BEVEL, and ROUND. The default joint is * MITER. * * @method strokeJoin * @param {Constant} join either MITER, BEVEL, ROUND * @chainable * @example * <div> * <code> * noFill(); * strokeWeight(10.0); * strokeJoin(MITER); * beginShape(); * vertex(35, 20); * vertex(65, 50); * vertex(35, 80); * endShape(); * </code> * </div> * * <div> * <code> * noFill(); * strokeWeight(10.0); * strokeJoin(BEVEL); * beginShape(); * vertex(35, 20); * vertex(65, 50); * vertex(35, 80); * endShape(); * </code> * </div> * * <div> * <code> * noFill(); * strokeWeight(10.0); * strokeJoin(ROUND); * beginShape(); * vertex(35, 20); * vertex(65, 50); * vertex(35, 80); * endShape(); * </code> * </div> * * @alt * Right-facing arrowhead shape with pointed tip in center of canvas. * Right-facing arrowhead shape with flat tip in center of canvas. * Right-facing arrowhead shape with rounded tip in center of canvas. * */p5.prototype.strokeJoin=function(join){p5._validateParameters('strokeJoin',arguments);if(join===constants.ROUND||join===constants.BEVEL||join===constants.MITER){this._renderer.strokeJoin(join);}return this;};/** * Sets the width of the stroke used for lines, points, and the border * around shapes. All widths are set in units of pixels. * * @method strokeWeight * @param {Number} weight the weight (in pixels) of the stroke * @chainable * @example * <div> * <code> * strokeWeight(1); // Default * line(20, 20, 80, 20); * strokeWeight(4); // Thicker * line(20, 40, 80, 40); * strokeWeight(10); // Beastly * line(20, 70, 80, 70); * </code> * </div> * * @alt * 3 horizontal black lines. Top line: thin, mid: medium, bottom:thick. * */p5.prototype.strokeWeight=function(w){p5._validateParameters('strokeWeight',arguments);this._renderer.strokeWeight(w);return this;};module.exports=p5;},{"../constants":19,"../main":25}],33:[function(_dereq_,module,exports){/** * @module Shape * @submodule Curves * @for p5 * @requires core */'use strict';var p5=_dereq_('../main');_dereq_('../error_helpers');/** * Draws a cubic Bezier curve on the screen. These curves are defined by a * series of anchor and control points. The first two parameters specify * the first anchor point and the last two parameters specify the other * anchor point, which become the first and last points on the curve. The * middle parameters specify the two control points which define the shape * of the curve. Approximately speaking, control points "pull" the curve * towards them.<br /><br />Bezier curves were developed by French * automotive engineer Pierre Bezier, and are commonly used in computer * graphics to define gently sloping curves. See also <a href="#/p5/curve">curve()</a>. * * @method bezier * @param {Number} x1 x-coordinate for the first anchor point * @param {Number} y1 y-coordinate for the first anchor point * @param {Number} x2 x-coordinate for the first control point * @param {Number} y2 y-coordinate for the first control point * @param {Number} x3 x-coordinate for the second control point * @param {Number} y3 y-coordinate for the second control point * @param {Number} x4 x-coordinate for the second anchor point * @param {Number} y4 y-coordinate for the second anchor point * @chainable * @example * <div> * <code> * noFill(); * stroke(255, 102, 0); * line(85, 20, 10, 10); * line(90, 90, 15, 80); * stroke(0, 0, 0); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * </code> * </div> * * <div> * <code> * background(0, 0, 0); * noFill(); * stroke(255); * bezier(250, 250, 0, 100, 100, 0, 100, 0, 0, 0, 100, 0); * </code> * </div> * * @alt * stretched black s-shape in center with orange lines extending from end points. * stretched black s-shape with 10 5x5 white ellipses along the shape. * stretched black s-shape with 7 5x5 ellipses and orange lines along the shape. * stretched black s-shape with 17 small orange lines extending from under shape. * horseshoe shape with orange ends facing left and black curved center. * horseshoe shape with orange ends facing left and black curved center. * Line shaped like right-facing arrow,points move with mouse-x and warp shape. * horizontal line that hooks downward on the right and 13 5x5 ellipses along it. * right curving line mid-right of canvas with 7 short lines radiating from it. *//** * @method bezier * @param {Number} x1 * @param {Number} y1 * @param {Number} z1 z-coordinate for the first anchor point * @param {Number} x2 * @param {Number} y2 * @param {Number} z2 z-coordinate for the first control point * @param {Number} x3 * @param {Number} y3 * @param {Number} z3 z-coordinate for the second control point * @param {Number} x4 * @param {Number} y4 * @param {Number} z4 z-coordinate for the second anchor point * @chainable */p5.prototype.bezier=function(){p5._validateParameters('bezier',arguments);// if the current stroke and fill settings wouldn't result in something // visible, exit immediately if(!this._renderer._doStroke&&!this._renderer._doFill){return this;}this._renderer.bezier.apply(this._renderer,arguments);return this;};/** * Sets the resolution at which Beziers display. * * The default value is 20. * * This function is only useful when using the WEBGL renderer * as the default canvas renderer does not use this information. * * @method bezierDetail * @param {Number} detail resolution of the curves * @chainable * @example * <div modernizr='webgl'> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * noFill(); * * bezierDetail(5); * } * * function draw() { * background(200); * * // prettier-ignore * bezier(-40, -40, 0, * 90, -40, 0, * -90, 40, 0, * 40, 40, 0); * } * </code> * </div> * * @alt * stretched black s-shape with a low level of bezier detail * */p5.prototype.bezierDetail=function(d){p5._validateParameters('bezierDetail',arguments);this._bezierDetail=d;return this;};/** * Evaluates the Bezier at position t for points a, b, c, d. * The parameters a and d are the first and last points * on the curve, and b and c are the control points. * The final parameter t varies between 0 and 1. * This can be done once with the x coordinates and a second time * with the y coordinates to get the location of a bezier curve at t. * * @method bezierPoint * @param {Number} a coordinate of first point on the curve * @param {Number} b coordinate of first control point * @param {Number} c coordinate of second control point * @param {Number} d coordinate of second point on the curve * @param {Number} t value between 0 and 1 * @return {Number} the value of the Bezier at position t * @example * <div> * <code> * noFill(); * var x1 = 85, x2 = 10, x3 = 90, x4 = 15; * var y1 = 20, y2 = 10, y3 = 90, y4 = 80; * bezier(x1, y1, x2, y2, x3, y3, x4, y4); * fill(255); * var steps = 10; * for (var i = 0; i <= steps; i++) { * var t = i / steps; * var x = bezierPoint(x1, x2, x3, x4, t); * var y = bezierPoint(y1, y2, y3, y4, t); * ellipse(x, y, 5, 5); * } * </code> * </div> * * @alt * stretched black s-shape with 17 small orange lines extending from under shape. * */p5.prototype.bezierPoint=function(a,b,c,d,t){p5._validateParameters('bezierPoint',arguments);var adjustedT=1-t;return Math.pow(adjustedT,3)*a+3*Math.pow(adjustedT,2)*t*b+3*adjustedT*Math.pow(t,2)*c+Math.pow(t,3)*d;};/** * Evaluates the tangent to the Bezier at position t for points a, b, c, d. * The parameters a and d are the first and last points * on the curve, and b and c are the control points. * The final parameter t varies between 0 and 1. * * @method bezierTangent * @param {Number} a coordinate of first point on the curve * @param {Number} b coordinate of first control point * @param {Number} c coordinate of second control point * @param {Number} d coordinate of second point on the curve * @param {Number} t value between 0 and 1 * @return {Number} the tangent at position t * @example * <div> * <code> * noFill(); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * var steps = 6; * fill(255); * for (var i = 0; i <= steps; i++) { * var t = i / steps; * // Get the location of the point * var x = bezierPoint(85, 10, 90, 15, t); * var y = bezierPoint(20, 10, 90, 80, t); * // Get the tangent points * var tx = bezierTangent(85, 10, 90, 15, t); * var ty = bezierTangent(20, 10, 90, 80, t); * // Calculate an angle from the tangent points * var a = atan2(ty, tx); * a += PI; * stroke(255, 102, 0); * line(x, y, cos(a) * 30 + x, sin(a) * 30 + y); * // The following line of code makes a line * // inverse of the above line * //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y); * stroke(0); * ellipse(x, y, 5, 5); * } * </code> * </div> * * <div> * <code> * noFill(); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * stroke(255, 102, 0); * var steps = 16; * for (var i = 0; i <= steps; i++) { * var t = i / steps; * var x = bezierPoint(85, 10, 90, 15, t); * var y = bezierPoint(20, 10, 90, 80, t); * var tx = bezierTangent(85, 10, 90, 15, t); * var ty = bezierTangent(20, 10, 90, 80, t); * var a = atan2(ty, tx); * a -= HALF_PI; * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y); * } * </code> * </div> * * @alt * s-shaped line with 17 short orange lines extending from underside of shape * */p5.prototype.bezierTangent=function(a,b,c,d,t){p5._validateParameters('bezierTangent',arguments);var adjustedT=1-t;return 3*d*Math.pow(t,2)-3*c*Math.pow(t,2)+6*c*adjustedT*t-6*b*adjustedT*t+3*b*Math.pow(adjustedT,2)-3*a*Math.pow(adjustedT,2);};/** * Draws a curved line on the screen between two points, given as the * middle four parameters. The first two parameters are a control point, as * if the curve came from this point even though it's not drawn. The last * two parameters similarly describe the other control point. <br /><br /> * Longer curves can be created by putting a series of <a href="#/p5/curve">curve()</a> functions * together or using <a href="#/p5/curveVertex">curveVertex()</a>. An additional function called * <a href="#/p5/curveTightness">curveTightness()</a> provides control for the visual quality of the curve. * The <a href="#/p5/curve">curve()</a> function is an implementation of Catmull-Rom splines. * * @method curve * @param {Number} x1 x-coordinate for the beginning control point * @param {Number} y1 y-coordinate for the beginning control point * @param {Number} x2 x-coordinate for the first point * @param {Number} y2 y-coordinate for the first point * @param {Number} x3 x-coordinate for the second point * @param {Number} y3 y-coordinate for the second point * @param {Number} x4 x-coordinate for the ending control point * @param {Number} y4 y-coordinate for the ending control point * @chainable * @example * <div> * <code> * noFill(); * stroke(255, 102, 0); * curve(5, 26, 5, 26, 73, 24, 73, 61); * stroke(0); * curve(5, 26, 73, 24, 73, 61, 15, 65); * stroke(255, 102, 0); * curve(73, 24, 73, 61, 15, 65, 15, 65); * </code> * </div> * <div> * <code> * // Define the curve points as JavaScript objects * var p1 = { x: 5, y: 26 }, p2 = { x: 73, y: 24 }; * var p3 = { x: 73, y: 61 }, p4 = { x: 15, y: 65 }; * noFill(); * stroke(255, 102, 0); * curve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y); * stroke(0); * curve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y); * stroke(255, 102, 0); * curve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y); * </code> * </div> * <div> * <code> * noFill(); * stroke(255, 102, 0); * curve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0); * stroke(0); * curve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0); * stroke(255, 102, 0); * curve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0); * </code> * </div> * * @alt * horseshoe shape with orange ends facing left and black curved center. * horseshoe shape with orange ends facing left and black curved center. * curving black and orange lines. *//** * @method curve * @param {Number} x1 * @param {Number} y1 * @param {Number} z1 z-coordinate for the beginning control point * @param {Number} x2 * @param {Number} y2 * @param {Number} z2 z-coordinate for the first point * @param {Number} x3 * @param {Number} y3 * @param {Number} z3 z-coordinate for the second point * @param {Number} x4 * @param {Number} y4 * @param {Number} z4 z-coordinate for the ending control point * @chainable */p5.prototype.curve=function(){p5._validateParameters('curve',arguments);if(this._renderer._doStroke){this._renderer.curve.apply(this._renderer,arguments);}return this;};/** * Sets the resolution at which curves display. * * The default value is 20 while the minimum value is 3. * * This function is only useful when using the WEBGL renderer * as the default canvas renderer does not use this * information. * * @method curveDetail * @param {Number} resolution of the curves * @chainable * @example * <div modernizr='webgl'> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * * curveDetail(5); * } * function draw() { * background(200); * * curve(250, 600, 0, -30, 40, 0, 30, 30, 0, -250, 600, 0); * } * </code> * </div> * * @alt * white arch shape with a low level of curve detail. * */p5.prototype.curveDetail=function(d){p5._validateParameters('curveDetail',arguments);if(d<3){this._curveDetail=3;}else{this._curveDetail=d;}return this;};/** * Modifies the quality of forms created with <a href="#/p5/curve">curve()</a> and <a href="#/p5/curveVertex">curveVertex()</a>. * The parameter tightness determines how the curve fits to the vertex * points. The value 0.0 is the default value for tightness (this value * defines the curves to be Catmull-Rom splines) and the value 1.0 connects * all the points with straight lines. Values within the range -5.0 and 5.0 * will deform the curves but will leave them recognizable and as values * increase in magnitude, they will continue to deform. * * @method curveTightness * @param {Number} amount of deformation from the original vertices * @chainable * @example * <div> * <code> * // Move the mouse left and right to see the curve change * * function setup() { * createCanvas(100, 100); * noFill(); * } * * function draw() { * background(204); * var t = map(mouseX, 0, width, -5, 5); * curveTightness(t); * beginShape(); * curveVertex(10, 26); * curveVertex(10, 26); * curveVertex(83, 24); * curveVertex(83, 61); * curveVertex(25, 65); * curveVertex(25, 65); * endShape(); * } * </code> * </div> * * @alt * Line shaped like right-facing arrow,points move with mouse-x and warp shape. */p5.prototype.curveTightness=function(t){p5._validateParameters('curveTightness',arguments);this._renderer._curveTightness=t;return this;};/** * Evaluates the curve at position t for points a, b, c, d. * The parameter t varies between 0 and 1, a and d are control points * of the curve, and b and c are the start and end points of the curve. * This can be done once with the x coordinates and a second time * with the y coordinates to get the location of a curve at t. * * @method curvePoint * @param {Number} a coordinate of first control point of the curve * @param {Number} b coordinate of first point * @param {Number} c coordinate of second point * @param {Number} d coordinate of second control point * @param {Number} t value between 0 and 1 * @return {Number} bezier value at position t * @example * <div> * <code> * noFill(); * curve(5, 26, 5, 26, 73, 24, 73, 61); * curve(5, 26, 73, 24, 73, 61, 15, 65); * fill(255); * ellipseMode(CENTER); * var steps = 6; * for (var i = 0; i <= steps; i++) { * var t = i / steps; * var x = curvePoint(5, 5, 73, 73, t); * var y = curvePoint(26, 26, 24, 61, t); * ellipse(x, y, 5, 5); * x = curvePoint(5, 73, 73, 15, t); * y = curvePoint(26, 24, 61, 65, t); * ellipse(x, y, 5, 5); * } * </code> * </div> * *line hooking down to right-bottom with 13 5x5 white ellipse points */p5.prototype.curvePoint=function(a,b,c,d,t){p5._validateParameters('curvePoint',arguments);var t3=t*t*t,t2=t*t,f1=-0.5*t3+t2-0.5*t,f2=1.5*t3-2.5*t2+1.0,f3=-1.5*t3+2.0*t2+0.5*t,f4=0.5*t3-0.5*t2;return a*f1+b*f2+c*f3+d*f4;};/** * Evaluates the tangent to the curve at position t for points a, b, c, d. * The parameter t varies between 0 and 1, a and d are points on the curve, * and b and c are the control points. * * @method curveTangent * @param {Number} a coordinate of first point on the curve * @param {Number} b coordinate of first control point * @param {Number} c coordinate of second control point * @param {Number} d coordinate of second point on the curve * @param {Number} t value between 0 and 1 * @return {Number} the tangent at position t * @example * <div> * <code> * noFill(); * curve(5, 26, 73, 24, 73, 61, 15, 65); * var steps = 6; * for (var i = 0; i <= steps; i++) { * var t = i / steps; * var x = curvePoint(5, 73, 73, 15, t); * var y = curvePoint(26, 24, 61, 65, t); * //ellipse(x, y, 5, 5); * var tx = curveTangent(5, 73, 73, 15, t); * var ty = curveTangent(26, 24, 61, 65, t); * var a = atan2(ty, tx); * a -= PI / 2.0; * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y); * } * </code> * </div> * * @alt *right curving line mid-right of canvas with 7 short lines radiating from it. */p5.prototype.curveTangent=function(a,b,c,d,t){p5._validateParameters('curveTangent',arguments);var t2=t*t,f1=-3*t2/2+2*t-0.5,f2=9*t2/2-5*t,f3=-9*t2/2+4*t+0.5,f4=3*t2/2-t;return a*f1+b*f2+c*f3+d*f4;};module.exports=p5;},{"../error_helpers":21,"../main":25}],34:[function(_dereq_,module,exports){/** * @module Shape * @submodule Vertex * @for p5 * @requires core * @requires constants */'use strict';var p5=_dereq_('../main');var constants=_dereq_('../constants');var shapeKind=null;var vertices=[];var contourVertices=[];var isBezier=false;var isCurve=false;var isQuadratic=false;var isContour=false;var isFirstContour=true;/** * Use the <a href="#/p5/beginContour">beginContour()</a> and <a href="#/p5/endContour">endContour()</a> functions to create negative * shapes within shapes such as the center of the letter 'O'. <a href="#/p5/beginContour">beginContour()</a> * begins recording vertices for the shape and <a href="#/p5/endContour">endContour()</a> stops recording. * The vertices that define a negative shape must "wind" in the opposite * direction from the exterior shape. First draw vertices for the exterior * clockwise order, then for internal shapes, draw vertices * shape in counter-clockwise. * <br><br> * These functions can only be used within a <a href="#/p5/beginShape">beginShape()</a>/<a href="#/p5/endShape">endShape()</a> pair and * transformations such as <a href="#/p5/translate">translate()</a>, <a href="#/p5/rotate">rotate()</a>, and <a href="#/p5/scale">scale()</a> do not work * within a <a href="#/p5/beginContour">beginContour()</a>/<a href="#/p5/endContour">endContour()</a> pair. It is also not possible to use * other shapes, such as <a href="#/p5/ellipse">ellipse()</a> or <a href="#/p5/rect">rect()</a> within. * * @method beginContour * @chainable * @example * <div> * <code> * translate(50, 50); * stroke(255, 0, 0); * beginShape(); * // Exterior part of shape, clockwise winding * vertex(-40, -40); * vertex(40, -40); * vertex(40, 40); * vertex(-40, 40); * // Interior part of shape, counter-clockwise winding * beginContour(); * vertex(-20, -20); * vertex(-20, 20); * vertex(20, 20); * vertex(20, -20); * endContour(); * endShape(CLOSE); * </code> * </div> * * @alt * white rect and smaller grey rect with red outlines in center of canvas. * */p5.prototype.beginContour=function(){contourVertices=[];isContour=true;return this;};/** * Using the <a href="#/p5/beginShape">beginShape()</a> and <a href="#/p5/endShape">endShape()</a> functions allow creating more * complex forms. <a href="#/p5/beginShape">beginShape()</a> begins recording vertices for a shape and * <a href="#/p5/endShape">endShape()</a> stops recording. The value of the kind parameter tells it which * types of shapes to create from the provided vertices. With no mode * specified, the shape can be any irregular polygon. * <br><br> * The parameters available for <a href="#/p5/beginShape">beginShape()</a> are POINTS, LINES, TRIANGLES, * TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. After calling the * <a href="#/p5/beginShape">beginShape()</a> function, a series of <a href="#/p5/vertex">vertex()</a> commands must follow. To stop * drawing the shape, call <a href="#/p5/endShape">endShape()</a>. Each shape will be outlined with the * current stroke color and filled with the fill color. * <br><br> * Transformations such as <a href="#/p5/translate">translate()</a>, <a href="#/p5/rotate">rotate()</a>, and <a href="#/p5/scale">scale()</a> do not work * within <a href="#/p5/beginShape">beginShape()</a>. It is also not possible to use other shapes, such as * <a href="#/p5/ellipse">ellipse()</a> or <a href="#/p5/rect">rect()</a> within <a href="#/p5/beginShape">beginShape()</a>. * * @method beginShape * @param {Constant} [kind] either POINTS, LINES, TRIANGLES, TRIANGLE_FAN * TRIANGLE_STRIP, QUADS, or QUAD_STRIP * @chainable * @example * <div> * <code> * beginShape(); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(CLOSE); * </code> * </div> * * <div> * <code> * beginShape(POINTS); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * </code> * </div> * * <div> * <code> * beginShape(LINES); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * </code> * </div> * * <div> * <code> * noFill(); * beginShape(); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * </code> * </div> * * <div> * <code> * noFill(); * beginShape(); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(CLOSE); * </code> * </div> * * <div> * <code> * beginShape(TRIANGLES); * vertex(30, 75); * vertex(40, 20); * vertex(50, 75); * vertex(60, 20); * vertex(70, 75); * vertex(80, 20); * endShape(); * </code> * </div> * * <div> * <code> * beginShape(TRIANGLE_STRIP); * vertex(30, 75); * vertex(40, 20); * vertex(50, 75); * vertex(60, 20); * vertex(70, 75); * vertex(80, 20); * vertex(90, 75); * endShape(); * </code> * </div> * * <div> * <code> * beginShape(TRIANGLE_FAN); * vertex(57.5, 50); * vertex(57.5, 15); * vertex(92, 50); * vertex(57.5, 85); * vertex(22, 50); * vertex(57.5, 15); * endShape(); * </code> * </div> * * <div> * <code> * beginShape(QUADS); * vertex(30, 20); * vertex(30, 75); * vertex(50, 75); * vertex(50, 20); * vertex(65, 20); * vertex(65, 75); * vertex(85, 75); * vertex(85, 20); * endShape(); * </code> * </div> * * <div> * <code> * beginShape(QUAD_STRIP); * vertex(30, 20); * vertex(30, 75); * vertex(50, 20); * vertex(50, 75); * vertex(65, 20); * vertex(65, 75); * vertex(85, 20); * vertex(85, 75); * endShape(); * </code> * </div> * * <div> * <code> * beginShape(); * vertex(20, 20); * vertex(40, 20); * vertex(40, 40); * vertex(60, 40); * vertex(60, 60); * vertex(20, 60); * endShape(CLOSE); * </code> * </div> * @alt * white square-shape with black outline in middle-right of canvas. * 4 black points in a square shape in middle-right of canvas. * 2 horizontal black lines. In the top-right and bottom-right of canvas. * 3 line shape with horizontal on top, vertical in middle and horizontal bottom. * square line shape in middle-right of canvas. * 2 white triangle shapes mid-right canvas. left one pointing up and right down. * 5 horizontal interlocking and alternating white triangles in mid-right canvas. * 4 interlocking white triangles in 45 degree rotated square-shape. * 2 white rectangle shapes in mid-right canvas. Both 20x55. * 3 side-by-side white rectangles center rect is smaller in mid-right canvas. * Thick white l-shape with black outline mid-top-left of canvas. * */p5.prototype.beginShape=function(kind){p5._validateParameters('beginShape',arguments);if(this._renderer.isP3D){this._renderer.beginShape.apply(this._renderer,arguments);}else{if(kind===constants.POINTS||kind===constants.LINES||kind===constants.TRIANGLES||kind===constants.TRIANGLE_FAN||kind===constants.TRIANGLE_STRIP||kind===constants.QUADS||kind===constants.QUAD_STRIP){shapeKind=kind;}else{shapeKind=null;}vertices=[];contourVertices=[];}return this;};/** * Specifies vertex coordinates for Bezier curves. Each call to * bezierVertex() defines the position of two control points and * one anchor point of a Bezier curve, adding a new segment to a * line or shape. For WebGL mode bezierVertex() can be used in 2D * as well as 3D mode. 2D mode expects 6 parameters, while 3D mode * expects 9 parameters (including z coordinates). * <br><br> * The first time bezierVertex() is used within a <a href="#/p5/beginShape">beginShape()</a> * call, it must be prefaced with a call to <a href="#/p5/vertex">vertex()</a> to set the first anchor * point. This function must be used between <a href="#/p5/beginShape">beginShape()</a> and <a href="#/p5/endShape">endShape()</a> * and only when there is no MODE or POINTS parameter specified to * <a href="#/p5/beginShape">beginShape()</a>. * * @method bezierVertex * @param {Number} x2 x-coordinate for the first control point * @param {Number} y2 y-coordinate for the first control point * @param {Number} x3 x-coordinate for the second control point * @param {Number} y3 y-coordinate for the second control point * @param {Number} x4 x-coordinate for the anchor point * @param {Number} y4 y-coordinate for the anchor point * @chainable * @example * <div> * <code> * noFill(); * beginShape(); * vertex(30, 20); * bezierVertex(80, 0, 80, 75, 30, 75); * endShape(); * </code> * </div> * * <div> * <code> * beginShape(); * vertex(30, 20); * bezierVertex(80, 0, 80, 75, 30, 75); * bezierVertex(50, 80, 60, 25, 30, 20); * endShape(); * </code> * </div> * * @alt * crescent-shaped line in middle of canvas. Points facing left. * white crescent shape in middle of canvas. Points facing left. *//** * @method bezierVertex * @param {Number} x2 * @param {Number} y2 * @param {Number} [z2] z-coordinate for the first control point (for WebGL mode) * @param {Number} x3 * @param {Number} y3 * @param {Number} [z3] z-coordinate for the second control point (for WebGL mode) * @param {Number} x4 * @param {Number} y4 * @param {Number} [z4] z-coordinate for the anchor point (for WebGL mode) * @chainable * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * setAttributes('antialias', true); * } * function draw() { * orbitControl(); * background(50); * strokeWeight(4); * stroke(255); * point(-25, 30); * point(25, 30); * point(25, -30); * point(-25, -30); * * strokeWeight(1); * noFill(); * * beginShape(); * vertex(-25, 30); * bezierVertex(25, 30, 25, -30, -25, -30); * endShape(); * * beginShape(); * vertex(-25, 30, 20); * bezierVertex(25, 30, 20, 25, -30, 20, -25, -30, 20); * endShape(); * } * </code> * </div> * * @alt * crescent shape in middle of canvas with another crescent shape on positive z-axis. */p5.prototype.bezierVertex=function(){p5._validateParameters('bezierVertex',arguments);if(this._renderer.isP3D){this._renderer.bezierVertex.apply(this._renderer,arguments);}else{if(vertices.length===0){throw'vertex() must be used once before calling bezierVertex()';}else{isBezier=true;var vert=[];for(var i=0;i<arguments.length;i++){vert[i]=arguments[i];}vert.isVert=false;if(isContour){contourVertices.push(vert);}else{vertices.push(vert);}}}return this;};/** * Specifies vertex coordinates for curves. This function may only * be used between <a href="#/p5/beginShape">beginShape()</a> and <a href="#/p5/endShape">endShape()</a> and only when there * is no MODE parameter specified to <a href="#/p5/beginShape">beginShape()</a>. * For WebGL mode curveVertex() can be used in 2D as well as 3D mode. * 2D mode expects 2 parameters, while 3D mode expects 3 parameters. * <br><br> * The first and last points in a series of curveVertex() lines will be used to * guide the beginning and end of a the curve. A minimum of four * points is required to draw a tiny curve between the second and * third points. Adding a fifth point with curveVertex() will draw * the curve between the second, third, and fourth points. The * curveVertex() function is an implementation of Catmull-Rom * splines. * * @method curveVertex * @param {Number} x x-coordinate of the vertex * @param {Number} y y-coordinate of the vertex * @chainable * @example * <div> * <code> * strokeWeight(5); * point(84, 91); * point(68, 19); * point(21, 17); * point(32, 91); * strokeWeight(1); * * noFill(); * beginShape(); * curveVertex(84, 91); * curveVertex(84, 91); * curveVertex(68, 19); * curveVertex(21, 17); * curveVertex(32, 91); * curveVertex(32, 91); * endShape(); * </code> * </div> * * * @alt * Upside-down u-shape line, mid canvas. left point extends beyond canvas view. *//** * @method curveVertex * @param {Number} x * @param {Number} y * @param {Number} [z] z-coordinate of the vertex (for WebGL mode) * @chainable * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * setAttributes('antialias', true); * } * function draw() { * orbitControl(); * background(50); * strokeWeight(4); * stroke(255); * * point(-25, 25); * point(-25, 25); * point(-25, -25); * point(25, -25); * point(25, 25); * point(25, 25); * * strokeWeight(1); * noFill(); * * beginShape(); * curveVertex(-25, 25); * curveVertex(-25, 25); * curveVertex(-25, -25); * curveVertex(25, -25); * curveVertex(25, 25); * curveVertex(25, 25); * endShape(); * * beginShape(); * curveVertex(-25, 25, 20); * curveVertex(-25, 25, 20); * curveVertex(-25, -25, 20); * curveVertex(25, -25, 20); * curveVertex(25, 25, 20); * curveVertex(25, 25, 20); * endShape(); * } * </code> * </div> * * @alt * Upside-down u-shape line, mid canvas with the same shape in positive z-axis. * */p5.prototype.curveVertex=function(){p5._validateParameters('curveVertex',arguments);if(this._renderer.isP3D){this._renderer.curveVertex.apply(this._renderer,arguments);}else{isCurve=true;this.vertex(arguments[0],arguments[1]);}return this;};/** * Use the <a href="#/p5/beginContour">beginContour()</a> and <a href="#/p5/endContour">endContour()</a> functions to create negative * shapes within shapes such as the center of the letter 'O'. <a href="#/p5/beginContour">beginContour()</a> * begins recording vertices for the shape and <a href="#/p5/endContour">endContour()</a> stops recording. * The vertices that define a negative shape must "wind" in the opposite * direction from the exterior shape. First draw vertices for the exterior * clockwise order, then for internal shapes, draw vertices * shape in counter-clockwise. * <br><br> * These functions can only be used within a <a href="#/p5/beginShape">beginShape()</a>/<a href="#/p5/endShape">endShape()</a> pair and * transformations such as <a href="#/p5/translate">translate()</a>, <a href="#/p5/rotate">rotate()</a>, and <a href="#/p5/scale">scale()</a> do not work * within a <a href="#/p5/beginContour">beginContour()</a>/<a href="#/p5/endContour">endContour()</a> pair. It is also not possible to use * other shapes, such as <a href="#/p5/ellipse">ellipse()</a> or <a href="#/p5/rect">rect()</a> within. * * @method endContour * @chainable * @example * <div> * <code> * translate(50, 50); * stroke(255, 0, 0); * beginShape(); * // Exterior part of shape, clockwise winding * vertex(-40, -40); * vertex(40, -40); * vertex(40, 40); * vertex(-40, 40); * // Interior part of shape, counter-clockwise winding * beginContour(); * vertex(-20, -20); * vertex(-20, 20); * vertex(20, 20); * vertex(20, -20); * endContour(); * endShape(CLOSE); * </code> * </div> * * @alt * white rect and smaller grey rect with red outlines in center of canvas. * */p5.prototype.endContour=function(){var vert=contourVertices[0].slice();// copy all data vert.isVert=contourVertices[0].isVert;vert.moveTo=false;contourVertices.push(vert);// prevent stray lines with multiple contours if(isFirstContour){vertices.push(vertices[0]);isFirstContour=false;}for(var i=0;i<contourVertices.length;i++){vertices.push(contourVertices[i]);}return this;};/** * The <a href="#/p5/endShape">endShape()</a> function is the companion to <a href="#/p5/beginShape">beginShape()</a> and may only be * called after <a href="#/p5/beginShape">beginShape()</a>. When <a href="#/p5/endshape">endshape()</a> is called, all of image data * defined since the previous call to <a href="#/p5/beginShape">beginShape()</a> is written into the image * buffer. The constant CLOSE as the value for the MODE parameter to close * the shape (to connect the beginning and the end). * * @method endShape * @param {Constant} [mode] use CLOSE to close the shape * @chainable * @example * <div> * <code> * noFill(); * * beginShape(); * vertex(20, 20); * vertex(45, 20); * vertex(45, 80); * endShape(CLOSE); * * beginShape(); * vertex(50, 20); * vertex(75, 20); * vertex(75, 80); * endShape(); * </code> * </div> * * @alt * Triangle line shape with smallest interior angle on bottom and upside-down L. * */p5.prototype.endShape=function(mode){p5._validateParameters('endShape',arguments);if(this._renderer.isP3D){this._renderer.endShape(mode,isCurve,isBezier,isQuadratic,isContour,shapeKind);}else{if(vertices.length===0){return this;}if(!this._renderer._doStroke&&!this._renderer._doFill){return this;}var closeShape=mode===constants.CLOSE;// if the shape is closed, the first element is also the last element if(closeShape&&!isContour){vertices.push(vertices[0]);}this._renderer.endShape(mode,vertices,isCurve,isBezier,isQuadratic,isContour,shapeKind);// Reset some settings isCurve=false;isBezier=false;isQuadratic=false;isContour=false;isFirstContour=true;// If the shape is closed, the first element was added as last element. // We must remove it again to prevent the list of vertices from growing // over successive calls to endShape(CLOSE) if(closeShape){vertices.pop();}}return this;};/** * Specifies vertex coordinates for quadratic Bezier curves. Each call to * quadraticVertex() defines the position of one control points and one * anchor point of a Bezier curve, adding a new segment to a line or shape. * The first time quadraticVertex() is used within a <a href="#/p5/beginShape">beginShape()</a> call, it * must be prefaced with a call to <a href="#/p5/vertex">vertex()</a> to set the first anchor point. * For WebGL mode quadraticVertex() can be used in 2D as well as 3D mode. * 2D mode expects 4 parameters, while 3D mode expects 6 parameters * (including z coordinates). * <br><br> * This function must be used between <a href="#/p5/beginShape">beginShape()</a> and <a href="#/p5/endShape">endShape()</a> * and only when there is no MODE or POINTS parameter specified to * <a href="#/p5/beginShape">beginShape()</a>. * * @method quadraticVertex * @param {Number} cx x-coordinate for the control point * @param {Number} cy y-coordinate for the control point * @param {Number} x3 x-coordinate for the anchor point * @param {Number} y3 y-coordinate for the anchor point * @chainable * @example * <div> * <code> * strokeWeight(5); * point(20, 20); * point(80, 20); * point(50, 50); * * noFill(); * strokeWeight(1); * beginShape(); * vertex(20, 20); * quadraticVertex(80, 20, 50, 50); * endShape(); * </code> * </div> * * <div> * <code> * strokeWeight(5); * point(20, 20); * point(80, 20); * point(50, 50); * * point(20, 80); * point(80, 80); * point(80, 60); * * noFill(); * strokeWeight(1); * beginShape(); * vertex(20, 20); * quadraticVertex(80, 20, 50, 50); * quadraticVertex(20, 80, 80, 80); * vertex(80, 60); * endShape(); * </code> * </div> * * @alt * arched-shaped black line with 4 pixel thick stroke weight. * backwards s-shaped black line with 4 pixel thick stroke weight. *//** * @method quadraticVertex * @param {Number} cx * @param {Number} cy * @param {Number} [cz] z-coordinate for the control point (for WebGL mode) * @param {Number} x3 * @param {Number} y3 * @param {Number} [z3] z-coordinate for the anchor point (for WebGL mode) * @chainable * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * setAttributes('antialias', true); * } * function draw() { * orbitControl(); * background(50); * strokeWeight(4); * stroke(255); * * point(-35, -35); * point(35, -35); * point(0, 0); * point(-35, 35); * point(35, 35); * point(35, 10); * * strokeWeight(1); * noFill(); * * beginShape(); * vertex(-35, -35); * quadraticVertex(35, -35, 0, 0); * quadraticVertex(-35, 35, 35, 35); * vertex(35, 10); * endShape(); * * beginShape(); * vertex(-35, -35, 20); * quadraticVertex(35, -35, 20, 0, 0, 20); * quadraticVertex(-35, 35, 20, 35, 35, 20); * vertex(35, 10, 20); * endShape(); * } * </code> * </div> * * @alt * backwards s-shaped black line with the same s-shaped line in postive z-axis. */p5.prototype.quadraticVertex=function(){p5._validateParameters('quadraticVertex',arguments);if(this._renderer.isP3D){this._renderer.quadraticVertex.apply(this._renderer,arguments);}else{//if we're drawing a contour, put the points into an // array for inside drawing if(this._contourInited){var pt={};pt.x=arguments[0];pt.y=arguments[1];pt.x3=arguments[2];pt.y3=arguments[3];pt.type=constants.QUADRATIC;this._contourVertices.push(pt);return this;}if(vertices.length>0){isQuadratic=true;var vert=[];for(var i=0;i<arguments.length;i++){vert[i]=arguments[i];}vert.isVert=false;if(isContour){contourVertices.push(vert);}else{vertices.push(vert);}}else{throw new Error('vertex() must be used once before calling quadraticVertex()');}}return this;};/** * All shapes are constructed by connecting a series of vertices. <a href="#/p5/vertex">vertex()</a> * is used to specify the vertex coordinates for points, lines, triangles, * quads, and polygons. It is used exclusively within the <a href="#/p5/beginShape">beginShape()</a> and * <a href="#/p5/endShape">endShape()</a> functions. * * @method vertex * @param {Number} x x-coordinate of the vertex * @param {Number} y y-coordinate of the vertex * @chainable * @example * <div> * <code> * strokeWeight(3); * beginShape(POINTS); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * </code> * </div> * * @alt * 4 black points in a square shape in middle-right of canvas. * * <div> * <code> * createCanvas(100, 100, WEBGL); * background(240, 240, 240); * fill(237, 34, 93); * noStroke(); * beginShape(); * vertex(0, 35); * vertex(35, 0); * vertex(0, -35); * vertex(-35, 0); * endShape(); * </code> * </div> * * @alt * 4 points making a diamond shape * * <div> * <code> * createCanvas(100, 100, WEBGL); * background(240, 240, 240); * fill(237, 34, 93); * noStroke(); * beginShape(); * vertex(-10, 10); * vertex(0, 35); * vertex(10, 10); * vertex(35, 0); * vertex(10, -8); * vertex(0, -35); * vertex(-10, -8); * vertex(-35, 0); * endShape(); * </code> * </div> * * @alt * 8 points making a star * * <div> * <code> * strokeWeight(3); * stroke(237, 34, 93); * beginShape(LINES); * vertex(10, 35); * vertex(90, 35); * vertex(10, 65); * vertex(90, 65); * vertex(35, 10); * vertex(35, 90); * vertex(65, 10); * vertex(65, 90); * endShape(); * </code> * </div> * * @alt * 8 points making 4 lines * *//** * @method vertex * @param {Number} x * @param {Number} y * @param {Number} z z-coordinate of the vertex * @param {Number} [u] the vertex's texture u-coordinate * @param {Number} [v] the vertex's texture v-coordinate * @chainable */p5.prototype.vertex=function(x,y,moveTo,u,v){if(this._renderer.isP3D){this._renderer.vertex.apply(this._renderer,arguments);}else{var vert=[];vert.isVert=true;vert[0]=x;vert[1]=y;vert[2]=0;vert[3]=0;vert[4]=0;vert[5]=this._renderer._getFill();vert[6]=this._renderer._getStroke();if(moveTo){vert.moveTo=moveTo;}if(isContour){if(contourVertices.length===0){vert.moveTo=true;}contourVertices.push(vert);}else{vertices.push(vert);}}return this;};module.exports=p5;},{"../constants":19,"../main":25}],35:[function(_dereq_,module,exports){'use strict';// requestAnim shim layer by Paul Irish // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/ // requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller // fixes from Paul Irish and Tino Zijdel window.requestAnimationFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback,element){// should '60' here be framerate? window.setTimeout(callback,1000/60);};}();/** * shim for Uint8ClampedArray.slice * (allows arrayCopy to work with pixels[]) * with thanks to http://halfpapstudios.com/blog/tag/html5-canvas/ * Enumerable set to false to protect for...in from * Uint8ClampedArray.prototype pollution. */(function(){'use strict';if(typeof Uint8ClampedArray!=='undefined'&&!Uint8ClampedArray.prototype.slice){Object.defineProperty(Uint8ClampedArray.prototype,'slice',{value:Array.prototype.slice,writable:true,configurable:true,enumerable:false});}})();/** * this is implementation of Object.assign() which is unavailable in * IE11 and (non-Chrome) Android browsers. * The assign() method is used to copy the values of all enumerable * own properties from one or more source objects to a target object. * It will return the target object. * Modified from https://github.com/ljharb/object.assign */(function(){'use strict';if(!Object.assign){var keys=Object.keys;var defineProperty=Object.defineProperty;var canBeObject=function canBeObject(obj){return typeof obj!=='undefined'&&obj!==null;};var hasSymbols=typeof Symbol==='function'&&_typeof(Symbol())==='symbol';var propIsEnumerable=Object.prototype.propertyIsEnumerable;var isEnumerableOn=function isEnumerableOn(obj){return function isEnumerable(prop){return propIsEnumerable.call(obj,prop);};};// per ES6 spec, this function has to have a length of 2 var assignShim=function assign(target,source1){if(!canBeObject(target)){throw new TypeError('target must be an object');}var objTarget=Object(target);var s,source,i,props;for(s=1;s<arguments.length;++s){source=Object(arguments[s]);props=keys(source);if(hasSymbols&&Object.getOwnPropertySymbols){props.push.apply(props,Object.getOwnPropertySymbols(source).filter(isEnumerableOn(source)));}for(i=0;i<props.length;++i){objTarget[props[i]]=source[props[i]];}}return objTarget;};defineProperty(Object,'assign',{value:assignShim,configurable:true,enumerable:false,writable:true});}})();},{}],36:[function(_dereq_,module,exports){/** * @module Structure * @submodule Structure * @for p5 * @requires core */'use strict';var p5=_dereq_('./main');/** * Stops p5.js from continuously executing the code within <a href="#/p5/draw">draw()</a>. * If <a href="#/p5/loop">loop()</a> is called, the code in <a href="#/p5/draw">draw()</a> begins to run continuously again. * If using <a href="#/p5/noLoop">noLoop()</a> in <a href="#/p5/setup">setup()</a>, it should be the last line inside the block. * <br><br> * When <a href="#/p5/noLoop">noLoop()</a> is used, it's not possible to manipulate or access the * screen inside event handling functions such as <a href="#/p5/mousePressed">mousePressed()</a> or * <a href="#/p5/keyPressed">keyPressed()</a>. Instead, use those functions to call <a href="#/p5/redraw">redraw()</a> or <a href="#/p5/loop">loop()</a>, * which will run <a href="#/p5/draw">draw()</a>, which can update the screen properly. This means * that when <a href="#/p5/noLoop">noLoop()</a> has been called, no drawing can happen, and functions * like <a href="#/p5/saveFrame">saveFrame()</a> or <a href="#/p5/loadPixels">loadPixels()</a> may not be used. * <br><br> * Note that if the sketch is resized, <a href="#/p5/redraw">redraw()</a> will be called to update * the sketch, even after <a href="#/p5/noLoop">noLoop()</a> has been specified. Otherwise, the sketch * would enter an odd state until <a href="#/p5/loop">loop()</a> was called. * * @method noLoop * @example * <div><code> * function setup() { * createCanvas(100, 100); * background(200); * noLoop(); * } * function draw() { * line(10, 10, 90, 90); * } * </code></div> * * <div><code> * var x = 0; * function setup() { * createCanvas(100, 100); * } * * function draw() { * background(204); * x = x + 0.1; * if (x > width) { * x = 0; * } * line(x, 0, x, height); * } * * function mousePressed() { * noLoop(); * } * * function mouseReleased() { * loop(); * } * </code></div> * * @alt * 113 pixel long line extending from top-left to bottom right of canvas. * horizontal line moves slowly from left. Loops but stops on mouse press. * */p5.prototype.noLoop=function(){this._loop=false;};/** * By default, p5.js loops through draw() continuously, executing the code * within it. However, the <a href="#/p5/draw">draw()</a> loop may be stopped by calling <a href="#/p5/noLoop">noLoop()</a>. * In that case, the <a href="#/p5/draw">draw()</a> loop can be resumed with loop(). * * @method loop * @example * <div><code> * var x = 0; * function setup() { * createCanvas(100, 100); * noLoop(); * } * * function draw() { * background(204); * x = x + 0.1; * if (x > width) { * x = 0; * } * line(x, 0, x, height); * } * * function mousePressed() { * loop(); * } * * function mouseReleased() { * noLoop(); * } * </code></div> * * @alt * horizontal line moves slowly from left. Loops but stops on mouse press. * */p5.prototype.loop=function(){this._loop=true;this._draw();};/** * The <a href="#/p5/push">push()</a> function saves the current drawing style settings and * transformations, while <a href="#/p5/pop">pop()</a> restores these settings. Note that these * functions are always used together. They allow you to change the style * and transformation settings and later return to what you had. When a new * state is started with <a href="#/p5/push">push()</a>, it builds on the current style and transform * information. The <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a> functions can be embedded to provide * more control. (See the second example for a demonstration.) * <br><br> * <a href="#/p5/push">push()</a> stores information related to the current transformation state * and style settings controlled by the following functions: <a href="#/p5/fill">fill()</a>, * <a href="#/p5/stroke">stroke()</a>, <a href="#/p5/tint">tint()</a>, <a href="#/p5/strokeWeight">strokeWeight()</a>, <a href="#/p5/strokeCap">strokeCap()</a>, <a href="#/p5/strokeJoin">strokeJoin()</a>, * <a href="#/p5/imageMode">imageMode()</a>, <a href="#/p5/rectMode">rectMode()</a>, <a href="#/p5/ellipseMode">ellipseMode()</a>, <a href="#/p5/colorMode">colorMode()</a>, <a href="#/p5/textAlign">textAlign()</a>, * <a href="#/p5/textFont">textFont()</a>, <a href="#/p5/textMode">textMode()</a>, <a href="#/p5/textSize">textSize()</a>, <a href="#/p5/textLeading">textLeading()</a>. * * @method push * @example * <div> * <code> * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * strokeWeight(10); * fill(204, 153, 0); * translate(50, 0); * ellipse(0, 50, 33, 33); // Middle circle * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * </code> * </div> * <div> * <code> * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * strokeWeight(10); * fill(204, 153, 0); * ellipse(33, 50, 33, 33); // Left-middle circle * * push(); // Start another new drawing state * stroke(0, 102, 153); * ellipse(66, 50, 33, 33); // Right-middle circle * pop(); // Restore previous state * * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * </code> * </div> * * @alt * Gold ellipse + thick black outline @center 2 white ellipses on left and right. * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right. * */p5.prototype.push=function(){this._styles.push({props:{_colorMode:this._colorMode},renderer:this._renderer.push()});};/** * The <a href="#/p5/push">push()</a> function saves the current drawing style settings and * transformations, while <a href="#/p5/pop">pop()</a> restores these settings. Note that these * functions are always used together. They allow you to change the style * and transformation settings and later return to what you had. When a new * state is started with <a href="#/p5/push">push()</a>, it builds on the current style and transform * information. The <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a> functions can be embedded to provide * more control. (See the second example for a demonstration.) * <br><br> * <a href="#/p5/push">push()</a> stores information related to the current transformation state * and style settings controlled by the following functions: <a href="#/p5/fill">fill()</a>, * <a href="#/p5/stroke">stroke()</a>, <a href="#/p5/tint">tint()</a>, <a href="#/p5/strokeWeight">strokeWeight()</a>, <a href="#/p5/strokeCap">strokeCap()</a>, <a href="#/p5/strokeJoin">strokeJoin()</a>, * <a href="#/p5/imageMode">imageMode()</a>, <a href="#/p5/rectMode">rectMode()</a>, <a href="#/p5/ellipseMode">ellipseMode()</a>, <a href="#/p5/colorMode">colorMode()</a>, <a href="#/p5/textAlign">textAlign()</a>, * <a href="#/p5/textFont">textFont()</a>, <a href="#/p5/textMode">textMode()</a>, <a href="#/p5/textSize">textSize()</a>, <a href="#/p5/textLeading">textLeading()</a>. * * @method pop * @example * <div> * <code> * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * translate(50, 0); * strokeWeight(10); * fill(204, 153, 0); * ellipse(0, 50, 33, 33); // Middle circle * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * </code> * </div> * <div> * <code> * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * strokeWeight(10); * fill(204, 153, 0); * ellipse(33, 50, 33, 33); // Left-middle circle * * push(); // Start another new drawing state * stroke(0, 102, 153); * ellipse(66, 50, 33, 33); // Right-middle circle * pop(); // Restore previous state * * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * </code> * </div> * * @alt * Gold ellipse + thick black outline @center 2 white ellipses on left and right. * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right. * */p5.prototype.pop=function(){var style=this._styles.pop();if(style){this._renderer.pop(style.renderer);Object.assign(this,style.props);}else{console.warn('pop() was called without matching push()');}};/** * * Executes the code within <a href="#/p5/draw">draw()</a> one time. This functions allows the * program to update the display window only when necessary, for example * when an event registered by <a href="#/p5/mousePressed">mousePressed()</a> or <a href="#/p5/keyPressed">keyPressed()</a> occurs. * <br><br> * In structuring a program, it only makes sense to call <a href="#/p5/redraw">redraw()</a> within * events such as <a href="#/p5/mousePressed">mousePressed()</a>. This is because <a href="#/p5/redraw">redraw()</a> does not run * <a href="#/p5/draw">draw()</a> immediately (it only sets a flag that indicates an update is * needed). * <br><br> * The <a href="#/p5/redraw">redraw()</a> function does not work properly when called inside <a href="#/p5/draw">draw()</a>. * To enable/disable animations, use <a href="#/p5/loop">loop()</a> and <a href="#/p5/noLoop">noLoop()</a>. * <br><br> * In addition you can set the number of redraws per method call. Just * add an integer as single parameter for the number of redraws. * * @method redraw * @param {Integer} [n] Redraw for n-times. The default value is 1. * @example * <div><code> * var x = 0; * * function setup() { * createCanvas(100, 100); * noLoop(); * } * * function draw() { * background(204); * line(x, 0, x, height); * } * * function mousePressed() { * x += 1; * redraw(); * } * </code></div> * * <div class='norender'><code> * var x = 0; * * function setup() { * createCanvas(100, 100); * noLoop(); * } * * function draw() { * background(204); * x += 1; * line(x, 0, x, height); * } * * function mousePressed() { * redraw(5); * } * </code></div> * * @alt * black line on far left of canvas * black line on far left of canvas * */p5.prototype.redraw=function(n){var numberOfRedraws=parseInt(n);if(isNaN(numberOfRedraws)||numberOfRedraws<1){numberOfRedraws=1;}var context=this._isGlobal?window:this;var userSetup=context.setup;var userDraw=context.draw;if(typeof userDraw==='function'){if(typeof userSetup==='undefined'){context.scale(context._pixelDensity,context._pixelDensity);}var callMethod=function callMethod(f){f.call(context);};for(var idxRedraw=0;idxRedraw<numberOfRedraws;idxRedraw++){context.resetMatrix();if(context._renderer.isP3D){context._renderer._update();}context._setProperty('frameCount',context.frameCount+1);context._registeredMethods.pre.forEach(callMethod);userDraw();context._registeredMethods.post.forEach(callMethod);}}};module.exports=p5;},{"./main":25}],37:[function(_dereq_,module,exports){/** * @module Transform * @submodule Transform * @for p5 * @requires core * @requires constants */'use strict';var p5=_dereq_('./main');/** * Multiplies the current matrix by the one specified through the parameters. * This is a powerful operation that can perform the equivalent of translate, * scale, shear and rotate all at once. You can learn more about transformation * matrices on <a href="https://en.wikipedia.org/wiki/Transformation_matrix"> * Wikipedia</a>. * * The naming of the arguments here follows the naming of the <a href= * "https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-transform"> * WHATWG specification</a> and corresponds to a * transformation matrix of the * form: * * > <img style="max-width: 150px" src="assets/transformation-matrix.png" * alt="The transformation matrix used when applyMatrix is called"/> * * @method applyMatrix * @param {Number} a numbers which define the 2x3 matrix to be multiplied * @param {Number} b numbers which define the 2x3 matrix to be multiplied * @param {Number} c numbers which define the 2x3 matrix to be multiplied * @param {Number} d numbers which define the 2x3 matrix to be multiplied * @param {Number} e numbers which define the 2x3 matrix to be multiplied * @param {Number} f numbers which define the 2x3 matrix to be multiplied * @chainable * @example * <div> * <code> * function setup() { * frameRate(10); * rectMode(CENTER); * } * * function draw() { * var step = frameCount % 20; * background(200); * // Equivalent to translate(x, y); * applyMatrix(1, 0, 0, 1, 40 + step, 50); * rect(0, 0, 50, 50); * } * </code> * </div> * <div> * <code> * function setup() { * frameRate(10); * rectMode(CENTER); * } * * function draw() { * var step = frameCount % 20; * background(200); * translate(50, 50); * // Equivalent to scale(x, y); * applyMatrix(1 / step, 0, 0, 1 / step, 0, 0); * rect(0, 0, 50, 50); * } * </code> * </div> * <div> * <code> * function setup() { * frameRate(10); * rectMode(CENTER); * } * * function draw() { * var step = frameCount % 20; * var angle = map(step, 0, 20, 0, TWO_PI); * var cos_a = cos(angle); * var sin_a = sin(angle); * background(200); * translate(50, 50); * // Equivalent to rotate(angle); * applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0); * rect(0, 0, 50, 50); * } * </code> * </div> * <div> * <code> * function setup() { * frameRate(10); * rectMode(CENTER); * } * * function draw() { * var step = frameCount % 20; * var angle = map(step, 0, 20, -PI / 4, PI / 4); * background(200); * translate(50, 50); * // equivalent to shearX(angle); * var shear_factor = 1 / tan(PI / 2 - angle); * applyMatrix(1, 0, shear_factor, 1, 0, 0); * rect(0, 0, 50, 50); * } * </code> * </div> * * @alt * A rectangle translating to the right * A rectangle shrinking to the center * A rectangle rotating clockwise about the center * A rectangle shearing * */p5.prototype.applyMatrix=function(a,b,c,d,e,f){this._renderer.applyMatrix(a,b,c,d,e,f);return this;};p5.prototype.popMatrix=function(){throw new Error('popMatrix() not used, see pop()');};p5.prototype.printMatrix=function(){throw new Error('printMatrix() not implemented');};p5.prototype.pushMatrix=function(){throw new Error('pushMatrix() not used, see push()');};/** * Replaces the current matrix with the identity matrix. * * @method resetMatrix * @chainable * @example * <div> * <code> * translate(50, 50); * applyMatrix(0.5, 0.5, -0.5, 0.5, 0, 0); * rect(0, 0, 20, 20); * // Note that the translate is also reset. * resetMatrix(); * rect(0, 0, 20, 20); * </code> * </div> * * @alt * A rotated retangle in the center with another at the top left corner * */p5.prototype.resetMatrix=function(){this._renderer.resetMatrix();return this;};/** * Rotates a shape the amount specified by the angle parameter. This * function accounts for <a href="#/p5/angleMode">angleMode</a>, so angles can be entered in either * RADIANS or DEGREES. * <br><br> * Objects are always rotated around their relative position to the * origin and positive numbers rotate objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * rotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI). * All tranformations are reset when <a href="#/p5/draw">draw()</a> begins again. * <br><br> * Technically, <a href="#/p5/rotate">rotate()</a> multiplies the current transformation matrix * by a rotation matrix. This function can be further controlled by * the <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a>. * * @method rotate * @param {Number} angle the angle of rotation, specified in radians * or degrees, depending on current angleMode * @param {p5.Vector|Number[]} [axis] (in 3d) the axis to rotate around * @chainable * @example * <div> * <code> * translate(width / 2, height / 2); * rotate(PI / 3.0); * rect(-26, -26, 52, 52); * </code> * </div> * * @alt * white 52x52 rect with black outline at center rotated counter 45 degrees * */p5.prototype.rotate=function(angle,axis){p5._validateParameters('rotate',arguments);this._renderer.rotate(this._toRadians(angle),axis);return this;};/** * Rotates around X axis. * @method rotateX * @param {Number} angle the angle of rotation, specified in radians * or degrees, depending on current angleMode * @chainable * @example * <div modernizr='webgl'> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(255); * rotateX(millis() / 1000); * box(); * } * </code> * </div> * * @alt * 3d box rotating around the x axis. */p5.prototype.rotateX=function(angle){this._assert3d('rotateX');p5._validateParameters('rotateX',arguments);this._renderer.rotateX(this._toRadians(angle));return this;};/** * Rotates around Y axis. * @method rotateY * @param {Number} angle the angle of rotation, specified in radians * or degrees, depending on current angleMode * @chainable * @example * <div modernizr='webgl'> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(255); * rotateY(millis() / 1000); * box(); * } * </code> * </div> * * @alt * 3d box rotating around the y axis. */p5.prototype.rotateY=function(angle){this._assert3d('rotateY');p5._validateParameters('rotateY',arguments);this._renderer.rotateY(this._toRadians(angle));return this;};/** * Rotates around Z axis. Webgl mode only. * @method rotateZ * @param {Number} angle the angle of rotation, specified in radians * or degrees, depending on current angleMode * @chainable * @example * <div modernizr='webgl'> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(255); * rotateZ(millis() / 1000); * box(); * } * </code> * </div> * * @alt * 3d box rotating around the z axis. */p5.prototype.rotateZ=function(angle){this._assert3d('rotateZ');p5._validateParameters('rotateZ',arguments);this._renderer.rotateZ(this._toRadians(angle));return this;};/** * Increases or decreases the size of a shape by expanding and contracting * vertices. Objects always scale from their relative origin to the * coordinate system. Scale values are specified as decimal percentages. * For example, the function call scale(2.0) increases the dimension of a * shape by 200%. * <br><br> * Transformations apply to everything that happens after and subsequent * calls to the function multiply the effect. For example, calling scale(2.0) * and then scale(1.5) is the same as scale(3.0). If <a href="#/p5/scale">scale()</a> is called * within <a href="#/p5/draw">draw()</a>, the transformation is reset when the loop begins again. * <br><br> * Using this function with the z parameter is only available in WEBGL mode. * This function can be further controlled with <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a>. * * @method scale * @param {Number|p5.Vector|Number[]} s * percent to scale the object, or percentage to * scale the object in the x-axis if multiple arguments * are given * @param {Number} [y] percent to scale the object in the y-axis * @param {Number} [z] percent to scale the object in the z-axis (webgl only) * @chainable * @example * <div> * <code> * rect(30, 20, 50, 50); * scale(0.5); * rect(30, 20, 50, 50); * </code> * </div> * * <div> * <code> * rect(30, 20, 50, 50); * scale(0.5, 1.3); * rect(30, 20, 50, 50); * </code> * </div> * * @alt * white 52x52 rect with black outline at center rotated counter 45 degrees * 2 white rects with black outline- 1 50x50 at center. other 25x65 bottom left * *//** * @method scale * @param {p5.Vector|Number[]} scales per-axis percents to scale the object * @chainable */p5.prototype.scale=function(x,y,z){p5._validateParameters('scale',arguments);// Only check for Vector argument type if Vector is available if(x instanceof p5.Vector){var v=x;x=v.x;y=v.y;z=v.z;}else if(x instanceof Array){var rg=x;x=rg[0];y=rg[1];z=rg[2]||1;}if(isNaN(y)){y=z=x;}else if(isNaN(z)){z=1;}this._renderer.scale.call(this._renderer,x,y,z);return this;};/** * Shears a shape around the x-axis the amount specified by the angle * parameter. Angles should be specified in the current angleMode. * Objects are always sheared around their relative position to the origin * and positive numbers shear objects in a clockwise direction. * <br><br> * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * shearX(PI/2) and then shearX(PI/2) is the same as shearX(PI). * If <a href="#/p5/shearX">shearX()</a> is called within the <a href="#/p5/draw">draw()</a>, the transformation is reset when * the loop begins again. * <br><br> * Technically, <a href="#/p5/shearX">shearX()</a> multiplies the current transformation matrix by a * rotation matrix. This function can be further controlled by the * <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a> functions. * * @method shearX * @param {Number} angle angle of shear specified in radians or degrees, * depending on current angleMode * @chainable * @example * <div> * <code> * translate(width / 4, height / 4); * shearX(PI / 4.0); * rect(0, 0, 30, 30); * </code> * </div> * * @alt * white irregular quadrilateral with black outline at top middle. * */p5.prototype.shearX=function(angle){p5._validateParameters('shearX',arguments);this._renderer.shearX(this._toRadians(angle));return this;};/** * Shears a shape around the y-axis the amount specified by the angle * parameter. Angles should be specified in the current angleMode. Objects * are always sheared around their relative position to the origin and * positive numbers shear objects in a clockwise direction. * <br><br> * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * shearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If * <a href="#/p5/shearY">shearY()</a> is called within the <a href="#/p5/draw">draw()</a>, the transformation is reset when * the loop begins again. * <br><br> * Technically, <a href="#/p5/shearY">shearY()</a> multiplies the current transformation matrix by a * rotation matrix. This function can be further controlled by the * <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a> functions. * * @method shearY * @param {Number} angle angle of shear specified in radians or degrees, * depending on current angleMode * @chainable * @example * <div> * <code> * translate(width / 4, height / 4); * shearY(PI / 4.0); * rect(0, 0, 30, 30); * </code> * </div> * * @alt * white irregular quadrilateral with black outline at middle bottom. * */p5.prototype.shearY=function(angle){p5._validateParameters('shearY',arguments);this._renderer.shearY(this._toRadians(angle));return this;};/** * Specifies an amount to displace objects within the display window. * The x parameter specifies left/right translation, the y parameter * specifies up/down translation. * <br><br> * Transformations are cumulative and apply to everything that happens after * and subsequent calls to the function accumulates the effect. For example, * calling translate(50, 0) and then translate(20, 0) is the same as * translate(70, 0). If <a href="#/p5/translate">translate()</a> is called within <a href="#/p5/draw">draw()</a>, the * transformation is reset when the loop begins again. This function can be * further controlled by using <a href="#/p5/push">push()</a> and <a href="#/p5/pop">pop()</a>. * * @method translate * @param {Number} x left/right translation * @param {Number} y up/down translation * @param {Number} [z] forward/backward translation (webgl only) * @chainable * @example * <div> * <code> * translate(30, 20); * rect(0, 0, 55, 55); * </code> * </div> * * <div> * <code> * rect(0, 0, 55, 55); // Draw rect at original 0,0 * translate(30, 20); * rect(0, 0, 55, 55); // Draw rect at new 0,0 * translate(14, 14); * rect(0, 0, 55, 55); // Draw rect at new 0,0 * </code> * </div> * * <div> * <code> * function draw() { * background(200); * rectMode(CENTER); * translate(width / 2, height / 2); * translate(p5.Vector.fromAngle(millis() / 1000, 40)); * rect(0, 0, 20, 20); * } * </code> * </div> * * @alt * white 55x55 rect with black outline at center right. * 3 white 55x55 rects with black outlines at top-l, center-r and bottom-r. * a 20x20 white rect moving in a circle around the canvas * *//** * @method translate * @param {p5.Vector} vector the vector to translate by * @chainable */p5.prototype.translate=function(x,y,z){p5._validateParameters('translate',arguments);if(this._renderer.isP3D){this._renderer.translate(x,y,z);}else{this._renderer.translate(x,y);}return this;};module.exports=p5;},{"./main":25}],38:[function(_dereq_,module,exports){/** * @module Data * @submodule Dictionary * @for p5.TypedDict * @requires core * * This module defines the p5 methods for the p5 Dictionary classes. * The classes StringDict and NumberDict are for storing and working * with key-value pairs. */'use strict';var p5=_dereq_('../core/main');/** * * Creates a new instance of p5.StringDict using the key-value pair * or the object you provide. * * @method createStringDict * @for p5 * @param {String} key * @param {String} value * @return {p5.StringDict} * * @example * <div class="norender"> * <code> * function setup() { * var myDictionary = createStringDict('p5', 'js'); * print(myDictionary.hasKey('p5')); // logs true to console * * var anotherDictionary = createStringDict({ happy: 'coding' }); * print(anotherDictionary.hasKey('happy')); // logs true to console * } * </code></div> *//** * @method createStringDict * @param {Object} object object * @return {p5.StringDict} */p5.prototype.createStringDict=function(key,value){p5._validateParameters('createStringDict',arguments);return new p5.StringDict(key,value);};/** * * Creates a new instance of <a href="#/p5.NumberDict">p5.NumberDict</a> using the key-value pair * or object you provide. * * @method createNumberDict * @for p5 * @param {Number} key * @param {Number} value * @return {p5.NumberDict} * * @example * <div class="norender"> * <code> * function setup() { * var myDictionary = createNumberDict(100, 42); * print(myDictionary.hasKey(100)); // logs true to console * * var anotherDictionary = createNumberDict({ 200: 84 }); * print(anotherDictionary.hasKey(200)); // logs true to console * } * </code></div> *//** * @method createNumberDict * @param {Object} object object * @return {p5.NumberDict} */p5.prototype.createNumberDict=function(key,value){p5._validateParameters('createNumberDict',arguments);return new p5.NumberDict(key,value);};/** * * Base class for all p5.Dictionary types. Specifically * typed Dictionary classes inherit from this class. * * @class p5.TypedDict * */p5.TypedDict=function(key,value){if(key instanceof Object){this.data=key;}else{this.data={};this.data[key]=value;}return this;};/** * Returns the number of key-value pairs currently stored in the Dictionary. * * @method size * @return {Integer} the number of key-value pairs in the Dictionary * * @example * <div class="norender"> * <code> * function setup() { * var myDictionary = createNumberDict(1, 10); * myDictionary.create(2, 20); * myDictionary.create(3, 30); * print(myDictionary.size()); // logs 3 to the console * } * </code></div> * */p5.TypedDict.prototype.size=function(){return Object.keys(this.data).length;};/** * Returns true if the given key exists in the Dictionary, * otherwise returns false. * * @method hasKey * @param {Number|String} key that you want to look up * @return {Boolean} whether that key exists in Dictionary * * @example * <div class="norender"> * <code> * function setup() { * var myDictionary = createStringDict('p5', 'js'); * print(myDictionary.hasKey('p5')); // logs true to console * } * </code></div> * */p5.TypedDict.prototype.hasKey=function(key){return this.data.hasOwnProperty(key);};/** * Returns the value stored at the given key. * * @method get * @param {Number|String} the key you want to access * @return {Number|String} the value stored at that key * * @example * <div class="norender"> * <code> * function setup() { * var myDictionary = createStringDict('p5', 'js'); * var myValue = myDictionary.get('p5'); * print(myValue === 'js'); // logs true to console * } * </code></div> * */p5.TypedDict.prototype.get=function(key){if(this.data.hasOwnProperty(key)){return this.data[key];}else{console.log(key+' does not exist in this Dictionary');}};/** * Updates the value associated with the given key in case it already exists * in the Dictionary. Otherwise a new key-value pair is added. * * @method set * @param {Number|String} key * @param {Number|String} value * * @example * <div class="norender"> * <code> * function setup() { * var myDictionary = createStringDict('p5', 'js'); * myDictionary.set('p5', 'JS'); * myDictionary.print(); // logs "key: p5 - value: JS" to console * } * </code></div> * */p5.TypedDict.prototype.set=function(key,value){if(this._validate(value)){this.data[key]=value;}else{console.log('Those values dont work for this dictionary type.');}};/** * private helper function to handle the user passing in objects * during construction or calls to create() */p5.TypedDict.prototype._addObj=function(obj){for(var key in obj){this.set(key,obj[key]);}};/** * Creates a new key-value pair in the Dictionary. * * @method create * @param {Number|String} key * @param {Number|String} value * * @example * <div class="norender"> * <code> * function setup() { * var myDictionary = createStringDict('p5', 'js'); * myDictionary.create('happy', 'coding'); * myDictionary.print(); * // above logs "key: p5 - value: js, key: happy - value: coding" to console * } * </code></div> *//** * @method create * @param {Object} obj key/value pair */p5.TypedDict.prototype.create=function(key,value){if(key instanceof Object&&typeof value==='undefined'){this._addObj(key);}else if(typeof key!=='undefined'){this.set(key,value);}else{console.log('In order to create a new Dictionary entry you must pass '+'an object or a key, value pair');}};/** * Removes all previously stored key-value pairs from the Dictionary. * * @method clear * @example * <div class="norender"> * <code> * function setup() { * var myDictionary = createStringDict('p5', 'js'); * print(myDictionary.hasKey('p5')); // prints 'true' * myDictionary.clear(); * print(myDictionary.hasKey('p5')); // prints 'false' * } * </code> * </div> */p5.TypedDict.prototype.clear=function(){this.data={};};/** * Removes the key-value pair stored at the given key from the Dictionary. * * @method remove * @param {Number|String} key for the pair to remove * * @example * <div class="norender"> * <code> * function setup() { * var myDictionary = createStringDict('p5', 'js'); * myDictionary.create('happy', 'coding'); * myDictionary.print(); * // above logs "key: p5 - value: js, key: happy - value: coding" to console * myDictionary.remove('p5'); * myDictionary.print(); * // above logs "key: happy value: coding" to console * } * </code></div> * */p5.TypedDict.prototype.remove=function(key){if(this.data.hasOwnProperty(key)){delete this.data[key];}else{throw new Error(key+' does not exist in this Dictionary');}};/** * Logs the set of items currently stored in the Dictionary to the console. * * @method print * * @example * <div class="norender"> * <code> * function setup() { * var myDictionary = createStringDict('p5', 'js'); * myDictionary.create('happy', 'coding'); * myDictionary.print(); * // above logs "key: p5 - value: js, key: happy - value: coding" to console * } * </code> * </div> */p5.TypedDict.prototype.print=function(){for(var item in this.data){console.log('key:'+item+' value:'+this.data[item]);}};/** * Converts the Dictionary into a CSV file for local download. * * @method saveTable * @example * <div> * <code> * createButton('save') * .position(10, 10) * .mousePressed(function() { * createStringDict({ * john: 1940, * paul: 1942, * george: 1943, * ringo: 1940 * }).saveTable('beatles'); * }); * </code> * </div> */p5.TypedDict.prototype.saveTable=function(filename){var output='';for(var key in this.data){output+=key+','+this.data[key]+'\n';}var blob=new Blob([output],{type:'text/csv'});p5.prototype.downloadFile(blob,filename||'mycsv','csv');};/** * Converts the Dictionary into a JSON file for local download. * * @method saveJSON * @example * <div> * <code> * createButton('save') * .position(10, 10) * .mousePressed(function() { * createStringDict({ * john: 1940, * paul: 1942, * george: 1943, * ringo: 1940 * }).saveJSON('beatles'); * }); * </code> * </div> */p5.TypedDict.prototype.saveJSON=function(filename,opt){p5.prototype.saveJSON(this.data,filename,opt);};/** * private helper function to ensure that the user passed in valid * values for the Dictionary type */p5.TypedDict.prototype._validate=function(value){return true;};/** * * A simple Dictionary class for Strings. * * @class p5.StringDict * @extends p5.TypedDict * */p5.StringDict=function(){p5.TypedDict.apply(this,arguments);};p5.StringDict.prototype=Object.create(p5.TypedDict.prototype);p5.StringDict.prototype._validate=function(value){return typeof value==='string';};/** * * A simple Dictionary class for Numbers. * * @class p5.NumberDict * @extends p5.TypedDict * */p5.NumberDict=function(){p5.TypedDict.apply(this,arguments);};p5.NumberDict.prototype=Object.create(p5.TypedDict.prototype);/** * private helper function to ensure that the user passed in valid * values for the Dictionary type */p5.NumberDict.prototype._validate=function(value){return typeof value==='number';};/** * Add the given number to the value currently stored at the given key. * The sum then replaces the value previously stored in the Dictionary. * * @method add * @param {Number} Key for the value you wish to add to * @param {Number} Number to add to the value * @example * <div class='norender'> * <code> * function setup() { * var myDictionary = createNumberDict(2, 5); * myDictionary.add(2, 2); * print(myDictionary.get(2)); // logs 7 to console. * } * </code></div> * * */p5.NumberDict.prototype.add=function(key,amount){if(this.data.hasOwnProperty(key)){this.data[key]+=amount;}else{console.log('The key - '+key+' does not exist in this dictionary.');}};/** * Subtract the given number from the value currently stored at the given key. * The difference then replaces the value previously stored in the Dictionary. * * @method sub * @param {Number} Key for the value you wish to subtract from * @param {Number} Number to subtract from the value * @example * <div class='norender'> * <code> * function setup() { * var myDictionary = createNumberDict(2, 5); * myDictionary.sub(2, 2); * print(myDictionary.get(2)); // logs 3 to console. * } * </code></div> * * */p5.NumberDict.prototype.sub=function(key,amount){this.add(key,-amount);};/** * Multiply the given number with the value currently stored at the given key. * The product then replaces the value previously stored in the Dictionary. * * @method mult * @param {Number} Key for value you wish to multiply * @param {Number} Amount to multiply the value by * @example * <div class='norender'> * <code> * function setup() { * var myDictionary = createNumberDict(2, 4); * myDictionary.mult(2, 2); * print(myDictionary.get(2)); // logs 8 to console. * } * </code></div> * * */p5.NumberDict.prototype.mult=function(key,amount){if(this.data.hasOwnProperty(key)){this.data[key]*=amount;}else{console.log('The key - '+key+' does not exist in this dictionary.');}};/** * Divide the given number with the value currently stored at the given key. * The quotient then replaces the value previously stored in the Dictionary. * * @method div * @param {Number} Key for value you wish to divide * @param {Number} Amount to divide the value by * @example * <div class='norender'> * <code> * function setup() { * var myDictionary = createNumberDict(2, 8); * myDictionary.div(2, 2); * print(myDictionary.get(2)); // logs 4 to console. * } * </code></div> * * */p5.NumberDict.prototype.div=function(key,amount){if(this.data.hasOwnProperty(key)){this.data[key]/=amount;}else{console.log('The key - '+key+' does not exist in this dictionary.');}};/** * private helper function for finding lowest or highest value * the argument 'flip' is used to flip the comparison arrow * from 'less than' to 'greater than' * */p5.NumberDict.prototype._valueTest=function(flip){if(Object.keys(this.data).length===0){throw new Error('Unable to search for a minimum or maximum value on an empty NumberDict');}else if(Object.keys(this.data).length===1){return this.data[Object.keys(this.data)[0]];}else{var result=this.data[Object.keys(this.data)[0]];for(var key in this.data){if(this.data[key]*flip<result*flip){result=this.data[key];}}return result;}};/** * Return the lowest number currently stored in the Dictionary. * * @method minValue * @return {Number} * @example * <div class='norender'> * <code> * function setup() { * var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); * var lowestValue = myDictionary.minValue(); // value is -10 * print(lowestValue); * } * </code></div> * */p5.NumberDict.prototype.minValue=function(){return this._valueTest(1);};/** * Return the highest number currently stored in the Dictionary. * * @method maxValue * @return {Number} * @example * <div class='norender'> * <code> * function setup() { * var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); * var highestValue = myDictionary.maxValue(); // value is 3 * print(highestValue); * } * </code></div> * */p5.NumberDict.prototype.maxValue=function(){return this._valueTest(-1);};/** * private helper function for finding lowest or highest key * the argument 'flip' is used to flip the comparison arrow * from 'less than' to 'greater than' * */p5.NumberDict.prototype._keyTest=function(flip){if(Object.keys(this.data).length===0){throw new Error('Unable to use minValue on an empty NumberDict');}else if(Object.keys(this.data).length===1){return Object.keys(this.data)[0];}else{var result=Object.keys(this.data)[0];for(var i=1;i<Object.keys(this.data).length;i++){if(Object.keys(this.data)[i]*flip<result*flip){result=Object.keys(this.data)[i];}}return result;}};/** * Return the lowest key currently used in the Dictionary. * * @method minKey * @return {Number} * @example * <div class='norender'> * <code> * function setup() { * var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); * var lowestKey = myDictionary.minKey(); // value is 1.2 * print(lowestKey); * } * </code></div> * */p5.NumberDict.prototype.minKey=function(){return this._keyTest(1);};/** * Return the highest key currently used in the Dictionary. * * @method maxKey * @return {Number} * @example * <div class='norender'> * <code> * function setup() { * var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); * var highestKey = myDictionary.maxKey(); // value is 4 * print(highestKey); * } * </code></div> * */p5.NumberDict.prototype.maxKey=function(){return this._keyTest(-1);};module.exports=p5.TypedDict;},{"../core/main":25}],39:[function(_dereq_,module,exports){/** * @module Events * @submodule Acceleration * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');/** * The system variable deviceOrientation always contains the orientation of * the device. The value of this variable will either be set 'landscape' * or 'portrait'. If no data is available it will be set to 'undefined'. * either LANDSCAPE or PORTRAIT. * * @property {Constant} deviceOrientation * @readOnly */p5.prototype.deviceOrientation=undefined;/** * The system variable accelerationX always contains the acceleration of the * device along the x axis. Value is represented as meters per second squared. * * @property {Number} accelerationX * @readOnly */p5.prototype.accelerationX=0;/** * The system variable accelerationY always contains the acceleration of the * device along the y axis. Value is represented as meters per second squared. * * @property {Number} accelerationY * @readOnly */p5.prototype.accelerationY=0;/** * The system variable accelerationZ always contains the acceleration of the * device along the z axis. Value is represented as meters per second squared. * * @property {Number} accelerationZ * @readOnly */p5.prototype.accelerationZ=0;/** * The system variable pAccelerationX always contains the acceleration of the * device along the x axis in the frame previous to the current frame. Value * is represented as meters per second squared. * * @property {Number} pAccelerationX * @readOnly */p5.prototype.pAccelerationX=0;/** * The system variable pAccelerationY always contains the acceleration of the * device along the y axis in the frame previous to the current frame. Value * is represented as meters per second squared. * * @property {Number} pAccelerationY * @readOnly */p5.prototype.pAccelerationY=0;/** * The system variable pAccelerationZ always contains the acceleration of the * device along the z axis in the frame previous to the current frame. Value * is represented as meters per second squared. * * @property {Number} pAccelerationZ * @readOnly */p5.prototype.pAccelerationZ=0;/** * _updatePAccelerations updates the pAcceleration values * * @private */p5.prototype._updatePAccelerations=function(){this._setProperty('pAccelerationX',this.accelerationX);this._setProperty('pAccelerationY',this.accelerationY);this._setProperty('pAccelerationZ',this.accelerationZ);};/** * The system variable rotationX always contains the rotation of the * device along the x axis. Value is represented as 0 to +/-180 degrees. * <br><br> * Note: The order the rotations are called is important, ie. if used * together, it must be called in the order Z-X-Y or there might be * unexpected behaviour. * * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * //rotateZ(radians(rotationZ)); * rotateX(radians(rotationX)); * //rotateY(radians(rotationY)); * box(200, 200, 200); * } * </code> * </div> * * @property {Number} rotationX * @readOnly * * @alt * red horizontal line right, green vertical line bottom. black background. * */p5.prototype.rotationX=0;/** * The system variable rotationY always contains the rotation of the * device along the y axis. Value is represented as 0 to +/-90 degrees. * <br><br> * Note: The order the rotations are called is important, ie. if used * together, it must be called in the order Z-X-Y or there might be * unexpected behaviour. * * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * //rotateZ(radians(rotationZ)); * //rotateX(radians(rotationX)); * rotateY(radians(rotationY)); * box(200, 200, 200); * } * </code> * </div> * * @property {Number} rotationY * @readOnly * * @alt * red horizontal line right, green vertical line bottom. black background. */p5.prototype.rotationY=0;/** * The system variable rotationZ always contains the rotation of the * device along the z axis. Value is represented as 0 to 359 degrees. * <br><br> * Unlike rotationX and rotationY, this variable is available for devices * with a built-in compass only. * <br><br> * Note: The order the rotations are called is important, ie. if used * together, it must be called in the order Z-X-Y or there might be * unexpected behaviour. * * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateZ(radians(rotationZ)); * //rotateX(radians(rotationX)); * //rotateY(radians(rotationY)); * box(200, 200, 200); * } * </code> * </div> * * @property {Number} rotationZ * @readOnly * * @alt * red horizontal line right, green vertical line bottom. black background. */p5.prototype.rotationZ=0;/** * The system variable pRotationX always contains the rotation of the * device along the x axis in the frame previous to the current frame. Value * is represented as 0 to +/-180 degrees. * <br><br> * pRotationX can also be used with rotationX to determine the rotate * direction of the device along the X-axis. * @example * <div class='norender'> * <code> * // A simple if statement looking at whether * // rotationX - pRotationX < 0 is true or not will be * // sufficient for determining the rotate direction * // in most cases. * * // Some extra logic is needed to account for cases where * // the angles wrap around. * var rotateDirection = 'clockwise'; * * // Simple range conversion to make things simpler. * // This is not absolutely necessary but the logic * // will be different in that case. * * var rX = rotationX + 180; * var pRX = pRotationX + 180; * * if ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) { * rotateDirection = 'clockwise'; * } else if (rX - pRX < 0 || rX - pRX > 270) { * rotateDirection = 'counter-clockwise'; * } * * print(rotateDirection); * </code> * </div> * * @alt * no image to display. * * * @property {Number} pRotationX * @readOnly */p5.prototype.pRotationX=0;/** * The system variable pRotationY always contains the rotation of the * device along the y axis in the frame previous to the current frame. Value * is represented as 0 to +/-90 degrees. * <br><br> * pRotationY can also be used with rotationY to determine the rotate * direction of the device along the Y-axis. * @example * <div class='norender'> * <code> * // A simple if statement looking at whether * // rotationY - pRotationY < 0 is true or not will be * // sufficient for determining the rotate direction * // in most cases. * * // Some extra logic is needed to account for cases where * // the angles wrap around. * var rotateDirection = 'clockwise'; * * // Simple range conversion to make things simpler. * // This is not absolutely necessary but the logic * // will be different in that case. * * var rY = rotationY + 180; * var pRY = pRotationY + 180; * * if ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) { * rotateDirection = 'clockwise'; * } else if (rY - pRY < 0 || rY - pRY > 270) { * rotateDirection = 'counter-clockwise'; * } * print(rotateDirection); * </code> * </div> * * @alt * no image to display. * * * @property {Number} pRotationY * @readOnly */p5.prototype.pRotationY=0;/** * The system variable pRotationZ always contains the rotation of the * device along the z axis in the frame previous to the current frame. Value * is represented as 0 to 359 degrees. * <br><br> * pRotationZ can also be used with rotationZ to determine the rotate * direction of the device along the Z-axis. * @example * <div class='norender'> * <code> * // A simple if statement looking at whether * // rotationZ - pRotationZ < 0 is true or not will be * // sufficient for determining the rotate direction * // in most cases. * * // Some extra logic is needed to account for cases where * // the angles wrap around. * var rotateDirection = 'clockwise'; * * if ( * (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) || * rotationZ - pRotationZ < -270 * ) { * rotateDirection = 'clockwise'; * } else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) { * rotateDirection = 'counter-clockwise'; * } * print(rotateDirection); * </code> * </div> * * @alt * no image to display. * * * @property {Number} pRotationZ * @readOnly */p5.prototype.pRotationZ=0;var startAngleX=0;var startAngleY=0;var startAngleZ=0;var rotateDirectionX='clockwise';var rotateDirectionY='clockwise';var rotateDirectionZ='clockwise';var pRotateDirectionX;var pRotateDirectionY;var pRotateDirectionZ;p5.prototype._updatePRotations=function(){this._setProperty('pRotationX',this.rotationX);this._setProperty('pRotationY',this.rotationY);this._setProperty('pRotationZ',this.rotationZ);};/** * @property {String} turnAxis * @readOnly */p5.prototype.turnAxis=undefined;var move_threshold=0.5;var shake_threshold=30;/** * The <a href="#/p5/setMoveThreshold">setMoveThreshold()</a> function is used to set the movement threshold for * the <a href="#/p5/deviceMoved">deviceMoved()</a> function. The default threshold is set to 0.5. * * @method setMoveThreshold * @param {number} value The threshold value * @example * <div class="norender"> * <code> * // Run this example on a mobile device * // You will need to move the device incrementally further * // the closer the square's color gets to white in order to change the value. * * var value = 0; * var threshold = 0.5; * function setup() { * setMoveThreshold(threshold); * } * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function deviceMoved() { * value = value + 5; * threshold = threshold + 0.1; * if (value > 255) { * value = 0; * threshold = 30; * } * setMoveThreshold(threshold); * } * </code> * </div> * * @alt * 50x50 black rect in center of canvas. turns white on mobile when device moves */p5.prototype.setMoveThreshold=function(val){p5._validateParameters('setMoveThreshold',arguments);move_threshold=val;};/** * The <a href="#/p5/setShakeThreshold">setShakeThreshold()</a> function is used to set the movement threshold for * the <a href="#/p5/deviceShaken">deviceShaken()</a> function. The default threshold is set to 30. * * @method setShakeThreshold * @param {number} value The threshold value * @example * <div class="norender"> * <code> * // Run this example on a mobile device * // You will need to shake the device more firmly * // the closer the box's fill gets to white in order to change the value. * * var value = 0; * var threshold = 30; * function setup() { * setShakeThreshold(threshold); * } * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function deviceMoved() { * value = value + 5; * threshold = threshold + 5; * if (value > 255) { * value = 0; * threshold = 30; * } * setShakeThreshold(threshold); * } * </code> * </div> * * @alt * 50x50 black rect in center of canvas. turns white on mobile when device * is being shaked */p5.prototype.setShakeThreshold=function(val){p5._validateParameters('setShakeThreshold',arguments);shake_threshold=val;};/** * The <a href="#/p5/deviceMoved">deviceMoved()</a> function is called when the device is moved by more than * the threshold value along X, Y or Z axis. The default threshold is set to * 0.5. * @method deviceMoved * @example * <div class="norender"> * <code> * // Run this example on a mobile device * // Move the device around * // to change the value. * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function deviceMoved() { * value = value + 5; * if (value > 255) { * value = 0; * } * } * </code> * </div> * * @alt * 50x50 black rect in center of canvas. turns white on mobile when device moves * *//** * The <a href="#/p5/deviceTurned">deviceTurned()</a> function is called when the device rotates by * more than 90 degrees continuously. * <br><br> * The axis that triggers the <a href="#/p5/deviceTurned">deviceTurned()</a> method is stored in the turnAxis * variable. The <a href="#/p5/deviceTurned">deviceTurned()</a> method can be locked to trigger on any axis: * X, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'. * * @method deviceTurned * @example * <div class="norender"> * <code> * // Run this example on a mobile device * // Rotate the device by 90 degrees * // to change the value. * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function deviceTurned() { * if (value === 0) { * value = 255; * } else if (value === 255) { * value = 0; * } * } * </code> * </div> * <div> * <code> * // Run this example on a mobile device * // Rotate the device by 90 degrees in the * // X-axis to change the value. * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function deviceTurned() { * if (turnAxis === 'X') { * if (value === 0) { * value = 255; * } else if (value === 255) { * value = 0; * } * } * } * </code> * </div> * * @alt * 50x50 black rect in center of canvas. turns white on mobile when device turns * 50x50 black rect in center of canvas. turns white on mobile when x-axis turns * *//** * The <a href="#/p5/deviceShaken">deviceShaken()</a> function is called when the device total acceleration * changes of accelerationX and accelerationY values is more than * the threshold value. The default threshold is set to 30. * @method deviceShaken * @example * <div class="norender"> * <code> * // Run this example on a mobile device * // Shake the device to change the value. * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function deviceShaken() { * value = value + 5; * if (value > 255) { * value = 0; * } * } * </code> * </div> * * @alt * 50x50 black rect in center of canvas. turns white on mobile when device shakes * */p5.prototype._ondeviceorientation=function(e){this._updatePRotations();this._setProperty('rotationX',e.beta);this._setProperty('rotationY',e.gamma);this._setProperty('rotationZ',e.alpha);this._handleMotion();};p5.prototype._ondevicemotion=function(e){this._updatePAccelerations();this._setProperty('accelerationX',e.acceleration.x*2);this._setProperty('accelerationY',e.acceleration.y*2);this._setProperty('accelerationZ',e.acceleration.z*2);this._handleMotion();};p5.prototype._handleMotion=function(){if(window.orientation===90||window.orientation===-90){this._setProperty('deviceOrientation','landscape');}else if(window.orientation===0){this._setProperty('deviceOrientation','portrait');}else if(window.orientation===undefined){this._setProperty('deviceOrientation','undefined');}var deviceMoved=this.deviceMoved||window.deviceMoved;if(typeof deviceMoved==='function'){if(Math.abs(this.accelerationX-this.pAccelerationX)>move_threshold||Math.abs(this.accelerationY-this.pAccelerationY)>move_threshold||Math.abs(this.accelerationZ-this.pAccelerationZ)>move_threshold){deviceMoved();}}var deviceTurned=this.deviceTurned||window.deviceTurned;if(typeof deviceTurned==='function'){// The angles given by rotationX etc is from range -180 to 180. // The following will convert them to 0 to 360 for ease of calculation // of cases when the angles wrapped around. // _startAngleX will be converted back at the end and updated. var wRX=this.rotationX+180;var wPRX=this.pRotationX+180;var wSAX=startAngleX+180;if(wRX-wPRX>0&&wRX-wPRX<270||wRX-wPRX<-270){rotateDirectionX='clockwise';}else if(wRX-wPRX<0||wRX-wPRX>270){rotateDirectionX='counter-clockwise';}if(rotateDirectionX!==pRotateDirectionX){wSAX=wRX;}if(Math.abs(wRX-wSAX)>90&&Math.abs(wRX-wSAX)<270){wSAX=wRX;this._setProperty('turnAxis','X');deviceTurned();}pRotateDirectionX=rotateDirectionX;startAngleX=wSAX-180;// Y-axis is identical to X-axis except for changing some names. var wRY=this.rotationY+180;var wPRY=this.pRotationY+180;var wSAY=startAngleY+180;if(wRY-wPRY>0&&wRY-wPRY<270||wRY-wPRY<-270){rotateDirectionY='clockwise';}else if(wRY-wPRY<0||wRY-this.pRotationY>270){rotateDirectionY='counter-clockwise';}if(rotateDirectionY!==pRotateDirectionY){wSAY=wRY;}if(Math.abs(wRY-wSAY)>90&&Math.abs(wRY-wSAY)<270){wSAY=wRY;this._setProperty('turnAxis','Y');deviceTurned();}pRotateDirectionY=rotateDirectionY;startAngleY=wSAY-180;// Z-axis is already in the range 0 to 360 // so no conversion is needed. if(this.rotationZ-this.pRotationZ>0&&this.rotationZ-this.pRotationZ<270||this.rotationZ-this.pRotationZ<-270){rotateDirectionZ='clockwise';}else if(this.rotationZ-this.pRotationZ<0||this.rotationZ-this.pRotationZ>270){rotateDirectionZ='counter-clockwise';}if(rotateDirectionZ!==pRotateDirectionZ){startAngleZ=this.rotationZ;}if(Math.abs(this.rotationZ-startAngleZ)>90&&Math.abs(this.rotationZ-startAngleZ)<270){startAngleZ=this.rotationZ;this._setProperty('turnAxis','Z');deviceTurned();}pRotateDirectionZ=rotateDirectionZ;this._setProperty('turnAxis',undefined);}var deviceShaken=this.deviceShaken||window.deviceShaken;if(typeof deviceShaken==='function'){var accelerationChangeX;var accelerationChangeY;// Add accelerationChangeZ if acceleration change on Z is needed if(this.pAccelerationX!==null){accelerationChangeX=Math.abs(this.accelerationX-this.pAccelerationX);accelerationChangeY=Math.abs(this.accelerationY-this.pAccelerationY);}if(accelerationChangeX+accelerationChangeY>shake_threshold){deviceShaken();}}};module.exports=p5;},{"../core/main":25}],40:[function(_dereq_,module,exports){/** * @module Events * @submodule Keyboard * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');/** * Holds the key codes of currently pressed keys. * @private */var downKeys={};/** * The boolean system variable <a href="#/p5/keyIsPressed">keyIsPressed</a> is true if any key is pressed * and false if no keys are pressed. * * @property {Boolean} keyIsPressed * @readOnly * @example * <div> * <code> * function draw() { * if (keyIsPressed === true) { * fill(0); * } else { * fill(255); * } * rect(25, 25, 50, 50); * } * </code> * </div> * * @alt * 50x50 white rect that turns black on keypress. * */p5.prototype.isKeyPressed=false;p5.prototype.keyIsPressed=false;// khan /** * The system variable key always contains the value of the most recent * key on the keyboard that was typed. To get the proper capitalization, it * is best to use it within <a href="#/p5/keyTyped">keyTyped()</a>. For non-ASCII keys, use the <a href="#/p5/keyCode">keyCode</a> * variable. * * @property {String} key * @readOnly * @example * <div><code> * // Click any key to display it! * // (Not Guaranteed to be Case Sensitive) * function setup() { * fill(245, 123, 158); * textSize(50); * } * * function draw() { * background(200); * text(key, 33, 65); // Display last key pressed. * } * </code></div> * * @alt * canvas displays any key value that is pressed in pink font. * */p5.prototype.key='';/** * The variable keyCode is used to detect special keys such as BACKSPACE, * DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW, * DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW. * You can also check for custom keys by looking up the keyCode of any key * on a site like this: <a href="http://keycode.info/">keycode.info</a>. * * @property {Integer} keyCode * @readOnly * @example * <div><code> * var fillVal = 126; * function draw() { * fill(fillVal); * rect(25, 25, 50, 50); * } * * function keyPressed() { * if (keyCode === UP_ARROW) { * fillVal = 255; * } else if (keyCode === DOWN_ARROW) { * fillVal = 0; * } * return false; // prevent default * } * </code></div> * * @alt * Grey rect center. turns white when up arrow pressed and black when down * */p5.prototype.keyCode=0;/** * The <a href="#/p5/keyPressed">keyPressed()</a> function is called once every time a key is pressed. The * keyCode for the key that was pressed is stored in the <a href="#/p5/keyCode">keyCode</a> variable. * <br><br> * For non-ASCII keys, use the keyCode variable. You can check if the keyCode * equals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, * OPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW. * <br><br> * For ASCII keys that was pressed is stored in the key variable. However, it * does not distinguish between uppercase and lowercase. For this reason, it * is recommended to use <a href="#/p5/keyTyped">keyTyped()</a> to read the key variable, in which the * case of the variable will be distinguished. * <br><br> * Because of how operating systems handle key repeats, holding down a key * may cause multiple calls to <a href="#/p5/keyTyped">keyTyped()</a> (and <a href="#/p5/keyReleased">keyReleased()</a> as well). The * rate of repeat is set by the operating system and how each computer is * configured.<br><br> * Browsers may have different default * behaviors attached to various key events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method keyPressed * @example * <div> * <code> * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function keyPressed() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * </code> * </div> * <div> * <code> * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function keyPressed() { * if (keyCode === LEFT_ARROW) { * value = 255; * } else if (keyCode === RIGHT_ARROW) { * value = 0; * } * } * </code> * </div> * <div class="norender"> * <code> * function keyPressed() { * // Do something * return false; // prevent any default behaviour * } * </code> * </div> * * @alt * black rect center. turns white when key pressed and black when released * black rect center. turns white when left arrow pressed and black when right. * */p5.prototype._onkeydown=function(e){if(downKeys[e.which]){// prevent multiple firings return;}this._setProperty('isKeyPressed',true);this._setProperty('keyIsPressed',true);this._setProperty('keyCode',e.which);downKeys[e.which]=true;this._setProperty('key',e.key||String.fromCharCode(e.which)||e.which);var keyPressed=this.keyPressed||window.keyPressed;if(typeof keyPressed==='function'&&!e.charCode){var executeDefault=keyPressed(e);if(executeDefault===false){e.preventDefault();}}};/** * The <a href="#/p5/keyReleased">keyReleased()</a> function is called once every time a key is released. * See <a href="#/p5/key">key</a> and <a href="#/p5/keyCode">keyCode</a> for more information.<br><br> * Browsers may have different default * behaviors attached to various key events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method keyReleased * @example * <div> * <code> * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function keyReleased() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * return false; // prevent any default behavior * } * </code> * </div> * * @alt * black rect center. turns white when key pressed and black when pressed again * */p5.prototype._onkeyup=function(e){var keyReleased=this.keyReleased||window.keyReleased;downKeys[e.which]=false;if(!areDownKeys()){this._setProperty('isKeyPressed',false);this._setProperty('keyIsPressed',false);}this._setProperty('_lastKeyCodeTyped',null);this._setProperty('key',e.key||String.fromCharCode(e.which)||e.which);this._setProperty('keyCode',e.which);if(typeof keyReleased==='function'){var executeDefault=keyReleased(e);if(executeDefault===false){e.preventDefault();}}};/** * The <a href="#/p5/keyTyped">keyTyped()</a> function is called once every time a key is pressed, but * action keys such as Ctrl, Shift, and Alt are ignored. The most recent * key pressed will be stored in the key variable. * <br><br> * Because of how operating systems handle key repeats, holding down a key * will cause multiple calls to <a href="#/p5/keyTyped">keyTyped()</a> (and <a href="#/p5/keyReleased">keyReleased()</a> as well). The * rate of repeat is set by the operating system and how each computer is * configured.<br><br> * Browsers may have different default behaviors attached to various key * events. To prevent any default behavior for this event, add "return false" * to the end of the method. * * @method keyTyped * @example * <div> * <code> * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function keyTyped() { * if (key === 'a') { * value = 255; * } else if (key === 'b') { * value = 0; * } * // uncomment to prevent any default behavior * // return false; * } * </code> * </div> * * @alt * black rect center. turns white when 'a' key typed and black when 'b' pressed * */p5.prototype._onkeypress=function(e){if(e.which===this._lastKeyCodeTyped){// prevent multiple firings return;}this._setProperty('keyCode',e.which);this._setProperty('_lastKeyCodeTyped',e.which);// track last keyCode this._setProperty('key',String.fromCharCode(e.which));var keyTyped=this.keyTyped||window.keyTyped;if(typeof keyTyped==='function'){var executeDefault=keyTyped(e);if(executeDefault===false){e.preventDefault();}}};/** * The onblur function is called when the user is no longer focused * on the p5 element. Because the keyup events will not fire if the user is * not focused on the element we must assume all keys currently down have * been released. */p5.prototype._onblur=function(e){downKeys={};};/** * The <a href="#/p5/keyIsDown">keyIsDown()</a> function checks if the key is currently down, i.e. pressed. * It can be used if you have an object that moves, and you want several keys * to be able to affect its behaviour simultaneously, such as moving a * sprite diagonally. You can put in any number representing the keyCode of * the key, or use any of the variable <a href="#/p5/keyCode">keyCode</a> names listed * <a href="http://p5js.org/reference/#p5/keyCode">here</a>. * * @method keyIsDown * @param {Number} code The key to check for. * @return {Boolean} whether key is down or not * @example * <div><code> * var x = 100; * var y = 100; * * function setup() { * createCanvas(512, 512); * } * * function draw() { * if (keyIsDown(LEFT_ARROW)) { * x -= 5; * } * * if (keyIsDown(RIGHT_ARROW)) { * x += 5; * } * * if (keyIsDown(UP_ARROW)) { * y -= 5; * } * * if (keyIsDown(DOWN_ARROW)) { * y += 5; * } * * clear(); * fill(255, 0, 0); * ellipse(x, y, 50, 50); * } * </code></div> * * <div><code> * var diameter = 50; * * function setup() { * createCanvas(512, 512); * } * * function draw() { * // 107 and 187 are keyCodes for "+" * if (keyIsDown(107) || keyIsDown(187)) { * diameter += 1; * } * * // 109 and 189 are keyCodes for "-" * if (keyIsDown(109) || keyIsDown(189)) { * diameter -= 1; * } * * clear(); * fill(255, 0, 0); * ellipse(50, 50, diameter, diameter); * } * </code></div> * * @alt * 50x50 red ellipse moves left, right, up and down with arrow presses. * 50x50 red ellipse gets bigger or smaller when + or - are pressed. * */p5.prototype.keyIsDown=function(code){p5._validateParameters('keyIsDown',arguments);return downKeys[code];};/** * The checkDownKeys function returns a boolean true if any keys pressed * and a false if no keys are currently pressed. * Helps avoid instances where a multiple keys are pressed simultaneously and * releasing a single key will then switch the * keyIsPressed property to true. * @private **/function areDownKeys(){for(var key in downKeys){if(downKeys.hasOwnProperty(key)&&downKeys[key]===true){return true;}}return false;}module.exports=p5;},{"../core/main":25}],41:[function(_dereq_,module,exports){/** * @module Events * @submodule Mouse * @for p5 * @requires core * @requires constants */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');/* * This is a flag which is false until the first time * we receive a mouse event. The pmouseX and pmouseY * values will match the mouseX and mouseY values until * this interaction takes place. */p5.prototype._hasMouseInteracted=false;/** * The system variable mouseX always contains the current horizontal * position of the mouse, relative to (0, 0) of the canvas. If touch is * used instead of mouse input, mouseX will hold the x value of the most * recent touch point. * * @property {Number} mouseX * @readOnly * * @example * <div> * <code> * // Move the mouse across the canvas * function draw() { * background(244, 248, 252); * line(mouseX, 0, mouseX, 100); * } * </code> * </div> * * @alt * horizontal black line moves left and right with mouse x-position * */p5.prototype.mouseX=0;/** * The system variable mouseY always contains the current vertical position * of the mouse, relative to (0, 0) of the canvas. If touch is * used instead of mouse input, mouseY will hold the y value of the most * recent touch point. * * @property {Number} mouseY * @readOnly * * @example * <div> * <code> * // Move the mouse across the canvas * function draw() { * background(244, 248, 252); * line(0, mouseY, 100, mouseY); * } * </code> * </div> * * @alt * vertical black line moves up and down with mouse y-position * */p5.prototype.mouseY=0;/** * The system variable pmouseX always contains the horizontal position of * the mouse or finger in the frame previous to the current frame, relative to * (0, 0) of the canvas. Note: pmouseX will be reset to the current mouseX * value at the start of each touch event. * * @property {Number} pmouseX * @readOnly * * @example * <div> * <code> * // Move the mouse across the canvas to leave a trail * function setup() { * //slow down the frameRate to make it more visible * frameRate(10); * } * * function draw() { * background(244, 248, 252); * line(mouseX, mouseY, pmouseX, pmouseY); * print(pmouseX + ' -> ' + mouseX); * } * </code> * </div> * * @alt * line trail is created from cursor movements. faster movement make longer line. * */p5.prototype.pmouseX=0;/** * The system variable pmouseY always contains the vertical position of the * mouse or finger in the frame previous to the current frame, relative to * (0, 0) of the canvas. Note: pmouseY will be reset to the current mouseY * value at the start of each touch event. * * @property {Number} pmouseY * @readOnly * * @example * <div> * <code> * function draw() { * background(237, 34, 93); * fill(0); * //draw a square only if the mouse is not moving * if (mouseY === pmouseY && mouseX === pmouseX) { * rect(20, 20, 60, 60); * } * * print(pmouseY + ' -> ' + mouseY); * } * </code> * </div> * * @alt * 60x60 black rect center, fuschia background. rect flickers on mouse movement * */p5.prototype.pmouseY=0;/** * The system variable winMouseX always contains the current horizontal * position of the mouse, relative to (0, 0) of the window. * * @property {Number} winMouseX * @readOnly * * @example * <div> * <code> * var myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas * myCanvas = createCanvas(100, 100); * } * * function draw() { * background(237, 34, 93); * fill(0); * * //move the canvas to the horizontal mouse position * //rela tive to the window * myCanvas.position(winMouseX + 1, windowHeight / 2); * * //the y of the square is relative to the canvas * rect(20, mouseY, 60, 60); * } * </code> * </div> * * @alt * 60x60 black rect y moves with mouse y and fuschia canvas moves with mouse x * */p5.prototype.winMouseX=0;/** * The system variable winMouseY always contains the current vertical * position of the mouse, relative to (0, 0) of the window. * * @property {Number} winMouseY * @readOnly * * @example * <div> * <code> * var myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas * myCanvas = createCanvas(100, 100); * } * * function draw() { * background(237, 34, 93); * fill(0); * * //move the canvas to the vertical mouse position * //rel ative to the window * myCanvas.position(windowWidth / 2, winMouseY + 1); * * //the x of the square is relative to the canvas * rect(mouseX, 20, 60, 60); * } * </code> * </div> * * @alt * 60x60 black rect x moves with mouse x and fuschia canvas y moves with mouse y * */p5.prototype.winMouseY=0;/** * The system variable pwinMouseX always contains the horizontal position * of the mouse in the frame previous to the current frame, relative to * (0, 0) of the window. Note: pwinMouseX will be reset to the current winMouseX * value at the start of each touch event. * * @property {Number} pwinMouseX * @readOnly * * @example * <div> * <code> * var myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas * myCanvas = createCanvas(100, 100); * noStroke(); * fill(237, 34, 93); * } * * function draw() { * clear(); * //the difference between previous and * //current x position is the horizontal mouse speed * var speed = abs(winMouseX - pwinMouseX); * //change the size of the circle * //according to the horizontal speed * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5); * //move the canvas to the mouse position * myCanvas.position(winMouseX + 1, winMouseY + 1); * } * </code> * </div> * * @alt * fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed * */p5.prototype.pwinMouseX=0;/** * The system variable pwinMouseY always contains the vertical position of * the mouse in the frame previous to the current frame, relative to (0, 0) * of the window. Note: pwinMouseY will be reset to the current winMouseY * value at the start of each touch event. * * @property {Number} pwinMouseY * @readOnly * * * @example * <div> * <code> * var myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas * myCanvas = createCanvas(100, 100); * noStroke(); * fill(237, 34, 93); * } * * function draw() { * clear(); * //the difference between previous and * //current y position is the vertical mouse speed * var speed = abs(winMouseY - pwinMouseY); * //change the size of the circle * //according to the vertical speed * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5); * //move the canvas to the mouse position * myCanvas.position(winMouseX + 1, winMouseY + 1); * } * </code> * </div> * * @alt * fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed * */p5.prototype.pwinMouseY=0;/** * Processing automatically tracks if the mouse button is pressed and which * button is pressed. The value of the system variable mouseButton is either * LEFT, RIGHT, or CENTER depending on which button was pressed last. * Warning: different browsers may track mouseButton differently. * * @property {Constant} mouseButton * @readOnly * * @example * <div> * <code> * function draw() { * background(237, 34, 93); * fill(0); * * if (mouseIsPressed) { * if (mouseButton === LEFT) { * ellipse(50, 50, 50, 50); * } * if (mouseButton === RIGHT) { * rect(25, 25, 50, 50); * } * if (mouseButton === CENTER) { * triangle(23, 75, 50, 20, 78, 75); * } * } * * print(mouseButton); * } * </code> * </div> * * @alt * 50x50 black ellipse appears on center of fuschia canvas on mouse click/press. * */p5.prototype.mouseButton=0;/** * The boolean system variable mouseIsPressed is true if the mouse is pressed * and false if not. * * @property {Boolean} mouseIsPressed * @readOnly * * @example * <div> * <code> * function draw() { * background(237, 34, 93); * fill(0); * * if (mouseIsPressed) { * ellipse(50, 50, 50, 50); * } else { * rect(25, 25, 50, 50); * } * * print(mouseIsPressed); * } * </code> * </div> * * @alt * black 50x50 rect becomes ellipse with mouse click/press. fuschia background. * */p5.prototype.mouseIsPressed=false;p5.prototype._updateNextMouseCoords=function(e){if(this._curElement!==null&&(!e.touches||e.touches.length>0)){var mousePos=getMousePos(this._curElement.elt,this.width,this.height,e);this._setProperty('mouseX',mousePos.x);this._setProperty('mouseY',mousePos.y);this._setProperty('winMouseX',mousePos.winX);this._setProperty('winMouseY',mousePos.winY);}if(!this._hasMouseInteracted){// For first draw, make previous and next equal this._updateMouseCoords();this._setProperty('_hasMouseInteracted',true);}};p5.prototype._updateMouseCoords=function(){this._setProperty('pmouseX',this.mouseX);this._setProperty('pmouseY',this.mouseY);this._setProperty('pwinMouseX',this.winMouseX);this._setProperty('pwinMouseY',this.winMouseY);this._setProperty('_pmouseWheelDeltaY',this._mouseWheelDeltaY);};function getMousePos(canvas,w,h,evt){if(evt&&!evt.clientX){// use touches if touch and not mouse if(evt.touches){evt=evt.touches[0];}else if(evt.changedTouches){evt=evt.changedTouches[0];}}var rect=canvas.getBoundingClientRect();var sx=canvas.scrollWidth/w;var sy=canvas.scrollHeight/h;return{x:(evt.clientX-rect.left)/sx,y:(evt.clientY-rect.top)/sy,winX:evt.clientX,winY:evt.clientY,id:evt.identifier};}p5.prototype._setMouseButton=function(e){if(e.button===1){this._setProperty('mouseButton',constants.CENTER);}else if(e.button===2){this._setProperty('mouseButton',constants.RIGHT);}else{this._setProperty('mouseButton',constants.LEFT);}};/** * The <a href="#/p5/mouseMoved">mouseMoved()</a> function is called every time the mouse moves and a mouse * button is not pressed.<br><br> * Browsers may have different default * behaviors attached to various mouse events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method mouseMoved * @example * <div> * <code> * // Move the mouse across the page * // to change its value * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function mouseMoved() { * value = value + 5; * if (value > 255) { * value = 0; * } * } * </code> * </div> * * <div class="norender"> * <code> * function mouseMoved() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * </code> * </div> * * @alt * black 50x50 rect becomes lighter with mouse movements until white then resets * no image displayed * *//** * The <a href="#/p5/mouseDragged">mouseDragged()</a> function is called once every time the mouse moves and * a mouse button is pressed. If no <a href="#/p5/mouseDragged">mouseDragged()</a> function is defined, the * <a href="#/p5/touchMoved">touchMoved()</a> function will be called instead if it is defined.<br><br> * Browsers may have different default * behaviors attached to various mouse events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method mouseDragged * @example * <div> * <code> * // Drag the mouse across the page * // to change its value * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function mouseDragged() { * value = value + 5; * if (value > 255) { * value = 0; * } * } * </code> * </div> * * <div class="norender"> * <code> * function mouseDragged() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * </code> * </div> * * @alt * black 50x50 rect turns lighter with mouse click and drag until white, resets * no image displayed * */p5.prototype._onmousemove=function(e){var context=this._isGlobal?window:this;var executeDefault;this._updateNextMouseCoords(e);if(!this.mouseIsPressed){if(typeof context.mouseMoved==='function'){executeDefault=context.mouseMoved(e);if(executeDefault===false){e.preventDefault();}}}else{if(typeof context.mouseDragged==='function'){executeDefault=context.mouseDragged(e);if(executeDefault===false){e.preventDefault();}}else if(typeof context.touchMoved==='function'){executeDefault=context.touchMoved(e);if(executeDefault===false){e.preventDefault();}}}};/** * The <a href="#/p5/mousePressed">mousePressed()</a> function is called once after every time a mouse button * is pressed. The mouseButton variable (see the related reference entry) * can be used to determine which button has been pressed. If no * <a href="#/p5/mousePressed">mousePressed()</a> function is defined, the <a href="#/p5/touchStarted">touchStarted()</a> function will be * called instead if it is defined.<br><br> * Browsers may have different default * behaviors attached to various mouse events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method mousePressed * @example * <div> * <code> * // Click within the image to change * // the value of the rectangle * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function mousePressed() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * </code> * </div> * * <div class="norender"> * <code> * function mousePressed() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * </code> * </div> * * @alt * black 50x50 rect turns white with mouse click/press. * no image displayed * */p5.prototype._onmousedown=function(e){var context=this._isGlobal?window:this;var executeDefault;this._setProperty('mouseIsPressed',true);this._setMouseButton(e);this._updateNextMouseCoords(e);if(typeof context.mousePressed==='function'){executeDefault=context.mousePressed(e);if(executeDefault===false){e.preventDefault();}}else if(typeof context.touchStarted==='function'){executeDefault=context.touchStarted(e);if(executeDefault===false){e.preventDefault();}}};/** * The <a href="#/p5/mouseReleased">mouseReleased()</a> function is called every time a mouse button is * released. If no <a href="#/p5/mouseReleased">mouseReleased()</a> function is defined, the <a href="#/p5/touchEnded">touchEnded()</a> * function will be called instead if it is defined.<br><br> * Browsers may have different default * behaviors attached to various mouse events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * * @method mouseReleased * @example * <div> * <code> * // Click within the image to change * // the value of the rectangle * // after the mouse has been clicked * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function mouseReleased() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * </code> * </div> * * <div class="norender"> * <code> * function mouseReleased() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * </code> * </div> * * @alt * black 50x50 rect turns white with mouse click/press. * no image displayed * */p5.prototype._onmouseup=function(e){var context=this._isGlobal?window:this;var executeDefault;this._setProperty('mouseIsPressed',false);if(typeof context.mouseReleased==='function'){executeDefault=context.mouseReleased(e);if(executeDefault===false){e.preventDefault();}}else if(typeof context.touchEnded==='function'){executeDefault=context.touchEnded(e);if(executeDefault===false){e.preventDefault();}}};p5.prototype._ondragend=p5.prototype._onmouseup;p5.prototype._ondragover=p5.prototype._onmousemove;/** * The <a href="#/p5/mouseClicked">mouseClicked()</a> function is called once after a mouse button has been * pressed and then released.<br><br> * Browsers handle clicks differently, so this function is only guaranteed to be * run when the left mouse button is clicked. To handle other mouse buttons * being pressed or released, see <a href="#/p5/mousePressed">mousePressed()</a> or <a href="#/p5/mouseReleased">mouseReleased()</a>.<br><br> * Browsers may have different default * behaviors attached to various mouse events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method mouseClicked * @example * <div> * <code> * // Click within the image to change * // the value of the rectangle * // after the mouse has been clicked * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * * function mouseClicked() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * </code> * </div> * * <div class="norender"> * <code> * function mouseClicked() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * </code> * </div> * * @alt * black 50x50 rect turns white with mouse click/press. * no image displayed * */p5.prototype._onclick=function(e){var context=this._isGlobal?window:this;if(typeof context.mouseClicked==='function'){var executeDefault=context.mouseClicked(e);if(executeDefault===false){e.preventDefault();}}};/** * The <a href="#/p5/doubleClicked">doubleClicked()</a> function is executed every time a event * listener has detected a dblclick event which is a part of the * DOM L3 specification. The doubleClicked event is fired when a * pointing device button (usually a mouse's primary button) * is clicked twice on a single element. For more info on the * dblclick event refer to mozilla's documentation here: * https://developer.mozilla.org/en-US/docs/Web/Events/dblclick * * @method doubleClicked * @example * <div> * <code> * // Click within the image to change * // the value of the rectangle * // after the mouse has been double clicked * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * * function doubleClicked() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * </code> * </div> * * <div class="norender"> * <code> * function doubleClicked() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * </code> * </div> * * @alt * black 50x50 rect turns white with mouse doubleClick/press. * no image displayed */p5.prototype._ondblclick=function(e){var context=this._isGlobal?window:this;if(typeof context.doubleClicked==='function'){var executeDefault=context.doubleClicked(e);if(executeDefault===false){e.preventDefault();}}};/** * For use with WebGL orbitControl. * @property {Number} _mouseWheelDeltaY * @readOnly * @private */p5.prototype._mouseWheelDeltaY=0;/** * For use with WebGL orbitControl. * @property {Number} _pmouseWheelDeltaY * @readOnly * @private */p5.prototype._pmouseWheelDeltaY=0;/** * The function <a href="#/p5/mouseWheel">mouseWheel()</a> is executed every time a vertical mouse wheel * event is detected either triggered by an actual mouse wheel or by a * touchpad.<br><br> * The event.delta property returns the amount the mouse wheel * have scrolled. The values can be positive or negative depending on the * scroll direction (on OS X with "natural" scrolling enabled, the signs * are inverted).<br><br> * Browsers may have different default behaviors attached to various * mouse events. To prevent any default behavior for this event, add * "return false" to the end of the method.<br><br> * Due to the current support of the "wheel" event on Safari, the function * may only work as expected if "return false" is included while using Safari. * * @method mouseWheel * * @example * <div> * <code> * var pos = 25; * * function draw() { * background(237, 34, 93); * fill(0); * rect(25, pos, 50, 50); * } * * function mouseWheel(event) { * print(event.delta); * //move the square according to the vertical scroll amount * pos += event.delta; * //uncomment to block page scrolling * //return false; * } * </code> * </div> * * @alt * black 50x50 rect moves up and down with vertical scroll. fuschia background * */p5.prototype._onwheel=function(e){var context=this._isGlobal?window:this;this._setProperty('_mouseWheelDeltaY',e.deltaY);if(typeof context.mouseWheel==='function'){e.delta=e.deltaY;var executeDefault=context.mouseWheel(e);if(executeDefault===false){e.preventDefault();}}};module.exports=p5;},{"../core/constants":19,"../core/main":25}],42:[function(_dereq_,module,exports){/** * @module Events * @submodule Touch * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');/** * The system variable touches[] contains an array of the positions of all * current touch points, relative to (0, 0) of the canvas, and IDs identifying a * unique touch as it moves. Each element in the array is an object with x, y, * and id properties. * * The touches[] array is not supported on Safari and IE on touch-based * desktops (laptops). * * @property {Object[]} touches * @readOnly * * @example * <div> * <code> * // On a touchscreen device, touch * // the canvas using one or more fingers * // at the same time * function draw() { * clear(); * var display = touches.length + ' touches'; * text(display, 5, 10); * } * </code> * </div> * * @alt * Number of touches currently registered are displayed on the canvas */p5.prototype.touches=[];p5.prototype._updateTouchCoords=function(e){if(this._curElement!==null){var touches=[];for(var i=0;i<e.touches.length;i++){touches[i]=getTouchInfo(this._curElement.elt,this.width,this.height,e,i);}this._setProperty('touches',touches);}};function getTouchInfo(canvas,w,h,e,i){i=i||0;var rect=canvas.getBoundingClientRect();var sx=canvas.scrollWidth/w;var sy=canvas.scrollHeight/h;var touch=e.touches[i]||e.changedTouches[i];return{x:(touch.clientX-rect.left)/sx,y:(touch.clientY-rect.top)/sy,winX:touch.clientX,winY:touch.clientY,id:touch.identifier};}/** * The touchStarted() function is called once after every time a touch is * registered. If no <a href="#/p5/touchStarted">touchStarted()</a> function is defined, the <a href="#/p5/mousePressed">mousePressed()</a> * function will be called instead if it is defined.<br><br> * Browsers may have different default behaviors attached to various touch * events. To prevent any default behavior for this event, add "return false" * to the end of the method. * * @method touchStarted * @example * <div> * <code> * // Touch within the image to change * // the value of the rectangle * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function touchStarted() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * </code> * </div> * * <div class="norender"> * <code> * function touchStarted() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * </code> * </div> * * @alt * 50x50 black rect turns white with touch event. * no image displayed */p5.prototype._ontouchstart=function(e){var context=this._isGlobal?window:this;var executeDefault;this._setProperty('mouseIsPressed',true);this._updateTouchCoords(e);this._updateNextMouseCoords(e);this._updateMouseCoords();// reset pmouseXY at the start of each touch event if(typeof context.touchStarted==='function'){executeDefault=context.touchStarted(e);if(executeDefault===false){e.preventDefault();}}else if(typeof context.mousePressed==='function'){executeDefault=context.mousePressed(e);if(executeDefault===false){e.preventDefault();}}};/** * The <a href="#/p5/touchMoved">touchMoved()</a> function is called every time a touch move is registered. * If no <a href="#/p5/touchMoved">touchMoved()</a> function is defined, the <a href="#/p5/mouseDragged">mouseDragged()</a> function will * be called instead if it is defined.<br><br> * Browsers may have different default behaviors attached to various touch * events. To prevent any default behavior for this event, add "return false" * to the end of the method. * * @method touchMoved * @example * <div> * <code> * // Move your finger across the page * // to change its value * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function touchMoved() { * value = value + 5; * if (value > 255) { * value = 0; * } * } * </code> * </div> * * <div class="norender"> * <code> * function touchMoved() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * </code> * </div> * * @alt * 50x50 black rect turns lighter with touch until white. resets * no image displayed * */p5.prototype._ontouchmove=function(e){var context=this._isGlobal?window:this;var executeDefault;this._updateTouchCoords(e);this._updateNextMouseCoords(e);if(typeof context.touchMoved==='function'){executeDefault=context.touchMoved(e);if(executeDefault===false){e.preventDefault();}}else if(typeof context.mouseDragged==='function'){executeDefault=context.mouseDragged(e);if(executeDefault===false){e.preventDefault();}}};/** * The <a href="#/p5/touchEnded">touchEnded()</a> function is called every time a touch ends. If no * <a href="#/p5/touchEnded">touchEnded()</a> function is defined, the <a href="#/p5/mouseReleased">mouseReleased()</a> function will be * called instead if it is defined.<br><br> * Browsers may have different default behaviors attached to various touch * events. To prevent any default behavior for this event, add "return false" * to the end of the method. * * @method touchEnded * @example * <div> * <code> * // Release touch within the image to * // change the value of the rectangle * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function touchEnded() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * </code> * </div> * * <div class="norender"> * <code> * function touchEnded() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * </code> * </div> * * @alt * 50x50 black rect turns white with touch. * no image displayed * */p5.prototype._ontouchend=function(e){this._setProperty('mouseIsPressed',false);this._updateTouchCoords(e);this._updateNextMouseCoords(e);var context=this._isGlobal?window:this;var executeDefault;if(typeof context.touchEnded==='function'){executeDefault=context.touchEnded(e);if(executeDefault===false){e.preventDefault();}}else if(typeof context.mouseReleased==='function'){executeDefault=context.mouseReleased(e);if(executeDefault===false){e.preventDefault();}}};module.exports=p5;},{"../core/main":25}],43:[function(_dereq_,module,exports){/*global ImageData:false *//** * This module defines the filters for use with image buffers. * * This module is basically a collection of functions stored in an object * as opposed to modules. The functions are destructive, modifying * the passed in canvas rather than creating a copy. * * Generally speaking users of this module will use the Filters.apply method * on a canvas to create an effect. * * A number of functions are borrowed/adapted from * http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ * or the java processing implementation. */'use strict';var Filters={};/* * Helper functions *//** * Returns the pixel buffer for a canvas * * @private * * @param {Canvas|ImageData} canvas the canvas to get pixels from * @return {Uint8ClampedArray} a one-dimensional array containing * the data in thc RGBA order, with integer * values between 0 and 255 */Filters._toPixels=function(canvas){if(canvas instanceof ImageData){return canvas.data;}else{return canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height).data;}};/** * Returns a 32 bit number containing ARGB data at ith pixel in the * 1D array containing pixels data. * * @private * * @param {Uint8ClampedArray} data array returned by _toPixels() * @param {Integer} i index of a 1D Image Array * @return {Integer} 32 bit integer value representing * ARGB value. */Filters._getARGB=function(data,i){var offset=i*4;return data[offset+3]<<24&0xff000000|data[offset]<<16&0x00ff0000|data[offset+1]<<8&0x0000ff00|data[offset+2]&0x000000ff;};/** * Modifies pixels RGBA values to values contained in the data object. * * @private * * @param {Uint8ClampedArray} pixels array returned by _toPixels() * @param {Int32Array} data source 1D array where each value * represents ARGB values */Filters._setPixels=function(pixels,data){var offset=0;for(var i=0,al=pixels.length;i<al;i++){offset=i*4;pixels[offset+0]=(data[i]&0x00ff0000)>>>16;pixels[offset+1]=(data[i]&0x0000ff00)>>>8;pixels[offset+2]=data[i]&0x000000ff;pixels[offset+3]=(data[i]&0xff000000)>>>24;}};/** * Returns the ImageData object for a canvas * https://developer.mozilla.org/en-US/docs/Web/API/ImageData * * @private * * @param {Canvas|ImageData} canvas canvas to get image data from * @return {ImageData} Holder of pixel data (and width and * height) for a canvas */Filters._toImageData=function(canvas){if(canvas instanceof ImageData){return canvas;}else{return canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height);}};/** * Returns a blank ImageData object. * * @private * * @param {Integer} width * @param {Integer} height * @return {ImageData} */Filters._createImageData=function(width,height){Filters._tmpCanvas=document.createElement('canvas');Filters._tmpCtx=Filters._tmpCanvas.getContext('2d');return this._tmpCtx.createImageData(width,height);};/** * Applys a filter function to a canvas. * * The difference between this and the actual filter functions defined below * is that the filter functions generally modify the pixel buffer but do * not actually put that data back to the canvas (where it would actually * update what is visible). By contrast this method does make the changes * actually visible in the canvas. * * The apply method is the method that callers of this module would generally * use. It has been separated from the actual filters to support an advanced * use case of creating a filter chain that executes without actually updating * the canvas in between everystep. * * @private * @param {HTMLCanvasElement} canvas [description] * @param {function(ImageData,Object)} func [description] * @param {Object} filterParam [description] */Filters.apply=function(canvas,func,filterParam){var ctx=canvas.getContext('2d');var imageData=ctx.getImageData(0,0,canvas.width,canvas.height);//Filters can either return a new ImageData object, or just modify //the one they received. var newImageData=func(imageData,filterParam);if(newImageData instanceof ImageData){ctx.putImageData(newImageData,0,0,0,0,canvas.width,canvas.height);}else{ctx.putImageData(imageData,0,0,0,0,canvas.width,canvas.height);}};/* * Filters *//** * Converts the image to black and white pixels depending if they are above or * below the threshold defined by the level parameter. The parameter must be * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. * * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ * * @private * @param {Canvas} canvas * @param {Float} level */Filters.threshold=function(canvas,level){var pixels=Filters._toPixels(canvas);if(level===undefined){level=0.5;}var thresh=Math.floor(level*255);for(var i=0;i<pixels.length;i+=4){var r=pixels[i];var g=pixels[i+1];var b=pixels[i+2];var gray=0.2126*r+0.7152*g+0.0722*b;var val;if(gray>=thresh){val=255;}else{val=0;}pixels[i]=pixels[i+1]=pixels[i+2]=val;}};/** * Converts any colors in the image to grayscale equivalents. * No parameter is used. * * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ * * @private * @param {Canvas} canvas */Filters.gray=function(canvas){var pixels=Filters._toPixels(canvas);for(var i=0;i<pixels.length;i+=4){var r=pixels[i];var g=pixels[i+1];var b=pixels[i+2];// CIE luminance for RGB var gray=0.2126*r+0.7152*g+0.0722*b;pixels[i]=pixels[i+1]=pixels[i+2]=gray;}};/** * Sets the alpha channel to entirely opaque. No parameter is used. * * @private * @param {Canvas} canvas */Filters.opaque=function(canvas){var pixels=Filters._toPixels(canvas);for(var i=0;i<pixels.length;i+=4){pixels[i+3]=255;}return pixels;};/** * Sets each pixel to its inverse value. No parameter is used. * @private * @param {Canvas} canvas */Filters.invert=function(canvas){var pixels=Filters._toPixels(canvas);for(var i=0;i<pixels.length;i+=4){pixels[i]=255-pixels[i];pixels[i+1]=255-pixels[i+1];pixels[i+2]=255-pixels[i+2];}};/** * Limits each channel of the image to the number of colors specified as * the parameter. The parameter can be set to values between 2 and 255, but * results are most noticeable in the lower ranges. * * Adapted from java based processing implementation * * @private * @param {Canvas} canvas * @param {Integer} level */Filters.posterize=function(canvas,level){var pixels=Filters._toPixels(canvas);if(level<2||level>255){throw new Error('Level must be greater than 2 and less than 255 for posterize');}var levels1=level-1;for(var i=0;i<pixels.length;i+=4){var rlevel=pixels[i];var glevel=pixels[i+1];var blevel=pixels[i+2];pixels[i]=(rlevel*level>>8)*255/levels1;pixels[i+1]=(glevel*level>>8)*255/levels1;pixels[i+2]=(blevel*level>>8)*255/levels1;}};/** * reduces the bright areas in an image * @private * @param {Canvas} canvas * */Filters.dilate=function(canvas){var pixels=Filters._toPixels(canvas);var currIdx=0;var maxIdx=pixels.length?pixels.length/4:0;var out=new Int32Array(maxIdx);var currRowIdx,maxRowIdx,colOrig,colOut,currLum;var idxRight,idxLeft,idxUp,idxDown;var colRight,colLeft,colUp,colDown;var lumRight,lumLeft,lumUp,lumDown;while(currIdx<maxIdx){currRowIdx=currIdx;maxRowIdx=currIdx+canvas.width;while(currIdx<maxRowIdx){colOrig=colOut=Filters._getARGB(pixels,currIdx);idxLeft=currIdx-1;idxRight=currIdx+1;idxUp=currIdx-canvas.width;idxDown=currIdx+canvas.width;if(idxLeft<currRowIdx){idxLeft=currIdx;}if(idxRight>=maxRowIdx){idxRight=currIdx;}if(idxUp<0){idxUp=0;}if(idxDown>=maxIdx){idxDown=currIdx;}colUp=Filters._getARGB(pixels,idxUp);colLeft=Filters._getARGB(pixels,idxLeft);colDown=Filters._getARGB(pixels,idxDown);colRight=Filters._getARGB(pixels,idxRight);//compute luminance currLum=77*(colOrig>>16&0xff)+151*(colOrig>>8&0xff)+28*(colOrig&0xff);lumLeft=77*(colLeft>>16&0xff)+151*(colLeft>>8&0xff)+28*(colLeft&0xff);lumRight=77*(colRight>>16&0xff)+151*(colRight>>8&0xff)+28*(colRight&0xff);lumUp=77*(colUp>>16&0xff)+151*(colUp>>8&0xff)+28*(colUp&0xff);lumDown=77*(colDown>>16&0xff)+151*(colDown>>8&0xff)+28*(colDown&0xff);if(lumLeft>currLum){colOut=colLeft;currLum=lumLeft;}if(lumRight>currLum){colOut=colRight;currLum=lumRight;}if(lumUp>currLum){colOut=colUp;currLum=lumUp;}if(lumDown>currLum){colOut=colDown;currLum=lumDown;}out[currIdx++]=colOut;}}Filters._setPixels(pixels,out);};/** * increases the bright areas in an image * @private * @param {Canvas} canvas * */Filters.erode=function(canvas){var pixels=Filters._toPixels(canvas);var currIdx=0;var maxIdx=pixels.length?pixels.length/4:0;var out=new Int32Array(maxIdx);var currRowIdx,maxRowIdx,colOrig,colOut,currLum;var idxRight,idxLeft,idxUp,idxDown;var colRight,colLeft,colUp,colDown;var lumRight,lumLeft,lumUp,lumDown;while(currIdx<maxIdx){currRowIdx=currIdx;maxRowIdx=currIdx+canvas.width;while(currIdx<maxRowIdx){colOrig=colOut=Filters._getARGB(pixels,currIdx);idxLeft=currIdx-1;idxRight=currIdx+1;idxUp=currIdx-canvas.width;idxDown=currIdx+canvas.width;if(idxLeft<currRowIdx){idxLeft=currIdx;}if(idxRight>=maxRowIdx){idxRight=currIdx;}if(idxUp<0){idxUp=0;}if(idxDown>=maxIdx){idxDown=currIdx;}colUp=Filters._getARGB(pixels,idxUp);colLeft=Filters._getARGB(pixels,idxLeft);colDown=Filters._getARGB(pixels,idxDown);colRight=Filters._getARGB(pixels,idxRight);//compute luminance currLum=77*(colOrig>>16&0xff)+151*(colOrig>>8&0xff)+28*(colOrig&0xff);lumLeft=77*(colLeft>>16&0xff)+151*(colLeft>>8&0xff)+28*(colLeft&0xff);lumRight=77*(colRight>>16&0xff)+151*(colRight>>8&0xff)+28*(colRight&0xff);lumUp=77*(colUp>>16&0xff)+151*(colUp>>8&0xff)+28*(colUp&0xff);lumDown=77*(colDown>>16&0xff)+151*(colDown>>8&0xff)+28*(colDown&0xff);if(lumLeft<currLum){colOut=colLeft;currLum=lumLeft;}if(lumRight<currLum){colOut=colRight;currLum=lumRight;}if(lumUp<currLum){colOut=colUp;currLum=lumUp;}if(lumDown<currLum){colOut=colDown;currLum=lumDown;}out[currIdx++]=colOut;}}Filters._setPixels(pixels,out);};// BLUR // internal kernel stuff for the gaussian blur filter var blurRadius;var blurKernelSize;var blurKernel;var blurMult;/* * Port of https://github.com/processing/processing/blob/ * master/core/src/processing/core/PImage.java#L1250 * * Optimized code for building the blur kernel. * further optimized blur code (approx. 15% for radius=20) * bigger speed gains for larger radii (~30%) * added support for various image types (ALPHA, RGB, ARGB) * [toxi 050728] */function buildBlurKernel(r){var radius=r*3.5|0;radius=radius<1?1:radius<248?radius:248;if(blurRadius!==radius){blurRadius=radius;blurKernelSize=1+blurRadius<<1;blurKernel=new Int32Array(blurKernelSize);blurMult=new Array(blurKernelSize);for(var l=0;l<blurKernelSize;l++){blurMult[l]=new Int32Array(256);}var bk,bki;var bm,bmi;for(var i=1,radiusi=radius-1;i<radius;i++){blurKernel[radius+i]=blurKernel[radiusi]=bki=radiusi*radiusi;bm=blurMult[radius+i];bmi=blurMult[radiusi--];for(var j=0;j<256;j++){bm[j]=bmi[j]=bki*j;}}bk=blurKernel[radius]=radius*radius;bm=blurMult[radius];for(var k=0;k<256;k++){bm[k]=bk*k;}}}// Port of https://github.com/processing/processing/blob/ // master/core/src/processing/core/PImage.java#L1433 function blurARGB(canvas,radius){var pixels=Filters._toPixels(canvas);var width=canvas.width;var height=canvas.height;var numPackedPixels=width*height;var argb=new Int32Array(numPackedPixels);for(var j=0;j<numPackedPixels;j++){argb[j]=Filters._getARGB(pixels,j);}var sum,cr,cg,cb,ca;var read,ri,ym,ymi,bk0;var a2=new Int32Array(numPackedPixels);var r2=new Int32Array(numPackedPixels);var g2=new Int32Array(numPackedPixels);var b2=new Int32Array(numPackedPixels);var yi=0;buildBlurKernel(radius);var x,y,i;var bm;for(y=0;y<height;y++){for(x=0;x<width;x++){cb=cg=cr=ca=sum=0;read=x-blurRadius;if(read<0){bk0=-read;read=0;}else{if(read>=width){break;}bk0=0;}for(i=bk0;i<blurKernelSize;i++){if(read>=width){break;}var c=argb[read+yi];bm=blurMult[i];ca+=bm[(c&-16777216)>>>24];cr+=bm[(c&16711680)>>16];cg+=bm[(c&65280)>>8];cb+=bm[c&255];sum+=blurKernel[i];read++;}ri=yi+x;a2[ri]=ca/sum;r2[ri]=cr/sum;g2[ri]=cg/sum;b2[ri]=cb/sum;}yi+=width;}yi=0;ym=-blurRadius;ymi=ym*width;for(y=0;y<height;y++){for(x=0;x<width;x++){cb=cg=cr=ca=sum=0;if(ym<0){bk0=ri=-ym;read=x;}else{if(ym>=height){break;}bk0=0;ri=ym;read=x+ymi;}for(i=bk0;i<blurKernelSize;i++){if(ri>=height){break;}bm=blurMult[i];ca+=bm[a2[read]];cr+=bm[r2[read]];cg+=bm[g2[read]];cb+=bm[b2[read]];sum+=blurKernel[i];ri++;read+=width;}argb[x+yi]=ca/sum<<24|cr/sum<<16|cg/sum<<8|cb/sum;}yi+=width;ymi+=width;ym++;}Filters._setPixels(pixels,argb);}Filters.blur=function(canvas,radius){blurARGB(canvas,radius);};module.exports=Filters;},{}],44:[function(_dereq_,module,exports){/** * @module Image * @submodule Image * @for p5 * @requires core *//** * This module defines the p5 methods for the <a href="#/p5.Image">p5.Image</a> class * for drawing images to the main display canvas. */'use strict';var p5=_dereq_('../core/main');// This is not global, but ESLint is not aware that // this module is implicitly enclosed with Browserify: this overrides the // redefined-global error and permits using the name "frames" for the array // of saved animation frames. /* global frames:true */var frames=[];/** * Creates a new <a href="#/p5.Image">p5.Image</a> (the datatype for storing images). This provides a * fresh buffer of pixels to play with. Set the size of the buffer with the * width and height parameters. * <br><br> * .<a href="#/p5.Image/pixels">pixels</a> gives access to an array containing the values for all the pixels * in the display window. * These values are numbers. This array is the size (including an appropriate * factor for the <a href="#/p5/pixelDensity">pixelDensity</a>) of the display window x4, * representing the R, G, B, A values in order for each pixel, moving from * left to right across each row, then down each column. See .<a href="#/p5.Image/pixels">pixels</a> for * more info. It may also be simpler to use <a href="#/p5.Image/set">set()</a> or <a href="#/p5.Image/get">get()</a>. * <br><br> * Before accessing the pixels of an image, the data must loaded with the * <a href="#/p5.Image/loadPixels">loadPixels()</a> function. After the array data has been modified, the * <a href="#/p5.Image/updatePixels">updatePixels()</a> function must be run to update the changes. * * @method createImage * @param {Integer} width width in pixels * @param {Integer} height height in pixels * @return {p5.Image} the <a href="#/p5.Image">p5.Image</a> object * @example * <div> * <code> * var img = createImage(66, 66); * img.loadPixels(); * for (var i = 0; i < img.width; i++) { * for (var j = 0; j < img.height; j++) { * img.set(i, j, color(0, 90, 102)); * } * } * img.updatePixels(); * image(img, 17, 17); * </code> * </div> * * <div> * <code> * var img = createImage(66, 66); * img.loadPixels(); * for (var i = 0; i < img.width; i++) { * for (var j = 0; j < img.height; j++) { * img.set(i, j, color(0, 90, 102, (i % img.width) * 2)); * } * } * img.updatePixels(); * image(img, 17, 17); * image(img, 34, 34); * </code> * </div> * * <div> * <code> * var pink = color(255, 102, 204); * var img = createImage(66, 66); * img.loadPixels(); * var d = pixelDensity(); * var halfImage = 4 * (img.width * d) * (img.height / 2 * d); * for (var i = 0; i < halfImage; i += 4) { * img.pixels[i] = red(pink); * img.pixels[i + 1] = green(pink); * img.pixels[i + 2] = blue(pink); * img.pixels[i + 3] = alpha(pink); * } * img.updatePixels(); * image(img, 17, 17); * </code> * </div> * * @alt * 66x66 dark turquoise rect in center of canvas. * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas * no image displayed * */p5.prototype.createImage=function(width,height){p5._validateParameters('createImage',arguments);return new p5.Image(width,height);};/** * Save the current canvas as an image. The browser will either save the * file immediately, or prompt the user with a dialogue window. * * @method saveCanvas * @param {p5.Element|HTMLCanvasElement} selectedCanvas a variable * representing a specific html5 canvas (optional) * @param {String} [filename] * @param {String} [extension] 'jpg' or 'png' * * @example * <div class='norender notest'><code> * function setup() { * var c = createCanvas(100, 100); * background(255, 0, 0); * saveCanvas(c, 'myCanvas', 'jpg'); * } * </code></div> * <div class='norender notest'><code> * // note that this example has the same result as above * // if no canvas is specified, defaults to main canvas * function setup() { * var c = createCanvas(100, 100); * background(255, 0, 0); * saveCanvas('myCanvas', 'jpg'); * * // all of the following are valid * saveCanvas(c, 'myCanvas', 'jpg'); * saveCanvas(c, 'myCanvas.jpg'); * saveCanvas(c, 'myCanvas'); * saveCanvas(c); * saveCanvas('myCanvas', 'png'); * saveCanvas('myCanvas'); * saveCanvas(); * } * </code></div> * * @alt * no image displayed * no image displayed * no image displayed *//** * @method saveCanvas * @param {String} [filename] * @param {String} [extension] */p5.prototype.saveCanvas=function(){p5._validateParameters('saveCanvas',arguments);// copy arguments to array var args=[].slice.call(arguments);var htmlCanvas,filename,extension;if(arguments[0]instanceof HTMLCanvasElement){htmlCanvas=arguments[0];args.shift();}else if(arguments[0]instanceof p5.Element){htmlCanvas=arguments[0].elt;args.shift();}else{htmlCanvas=this._curElement&&this._curElement.elt;}if(args.length>=1){filename=args[0];}if(args.length>=2){extension=args[1];}extension=extension||p5.prototype._checkFileExtension(filename,extension)[1]||'png';var mimeType;switch(extension){default://case 'png': mimeType='image/png';break;case'jpeg':case'jpg':mimeType='image/jpeg';break;}htmlCanvas.toBlob(function(blob){p5.prototype.downloadFile(blob,filename,extension);},mimeType);};/** * Capture a sequence of frames that can be used to create a movie. * Accepts a callback. For example, you may wish to send the frames * to a server where they can be stored or converted into a movie. * If no callback is provided, the browser will pop up save dialogues in an * attempt to download all of the images that have just been created. With the * callback provided the image data isn't saved by default but instead passed * as an argument to the callback function as an array of objects, with the * size of array equal to the total number of frames. * * Note that <a href="#/p5.Image/saveFrames">saveFrames()</a> will only save the first 15 frames of an animation. * To export longer animations, you might look into a library like * <a href="https://github.com/spite/ccapture.js/">ccapture.js</a>. * * @method saveFrames * @param {String} filename * @param {String} extension 'jpg' or 'png' * @param {Number} duration Duration in seconds to save the frames for. * @param {Number} framerate Framerate to save the frames in. * @param {function(Array)} [callback] A callback function that will be executed to handle the image data. This function should accept an array as argument. The array will contain the specified number of frames of objects. Each object has three properties: imageData - an image/octet-stream, filename and extension. * @example * <div><code> * function draw() { * background(mouseX); * } * * function mousePressed() { * saveFrames('out', 'png', 1, 25, function(data) { * print(data); * }); * } </code></div> * * @alt * canvas background goes from light to dark with mouse x. * */p5.prototype.saveFrames=function(fName,ext,_duration,_fps,callback){p5._validateParameters('saveFrames',arguments);var duration=_duration||3;duration=p5.prototype.constrain(duration,0,15);duration=duration*1000;var fps=_fps||15;fps=p5.prototype.constrain(fps,0,22);var count=0;var makeFrame=p5.prototype._makeFrame;var cnv=this._curElement.elt;var frameFactory=setInterval(function(){makeFrame(fName+count,ext,cnv);count++;},1000/fps);setTimeout(function(){clearInterval(frameFactory);if(callback){callback(frames);}else{for(var i=0;i<frames.length;i++){var f=frames[i];p5.prototype.downloadFile(f.imageData,f.filename,f.ext);}}frames=[];// clear frames },duration+0.01);};p5.prototype._makeFrame=function(filename,extension,_cnv){var cnv;if(this){cnv=this._curElement.elt;}else{cnv=_cnv;}var mimeType;if(!extension){extension='png';mimeType='image/png';}else{switch(extension.toLowerCase()){case'png':mimeType='image/png';break;case'jpeg':mimeType='image/jpeg';break;case'jpg':mimeType='image/jpeg';break;default:mimeType='image/png';break;}}var downloadMime='image/octet-stream';var imageData=cnv.toDataURL(mimeType);imageData=imageData.replace(mimeType,downloadMime);var thisFrame={};thisFrame.imageData=imageData;thisFrame.filename=filename;thisFrame.ext=extension;frames.push(thisFrame);};module.exports=p5;},{"../core/main":25}],45:[function(_dereq_,module,exports){/** * @module Image * @submodule Loading & Displaying * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');var Filters=_dereq_('./filters');var canvas=_dereq_('../core/helpers');var constants=_dereq_('../core/constants');_dereq_('../core/error_helpers');/** * Loads an image from a path and creates a <a href="#/p5.Image">p5.Image</a> from it. * <br><br> * The image may not be immediately available for rendering * If you want to ensure that the image is ready before doing * anything with it, place the <a href="#/p5/loadImage">loadImage()</a> call in <a href="#/p5/preload">preload()</a>. * You may also supply a callback function to handle the image when it's ready. * <br><br> * The path to the image should be relative to the HTML file * that links in your sketch. Loading an image from a URL or other * remote location may be blocked due to your browser's built-in * security. * * @method loadImage * @param {String} path Path of the image to be loaded * @param {function(p5.Image)} [successCallback] Function to be called once * the image is loaded. Will be passed the * <a href="#/p5.Image">p5.Image</a>. * @param {function(Event)} [failureCallback] called with event error if * the image fails to load. * @return {p5.Image} the <a href="#/p5.Image">p5.Image</a> object * @example * <div> * <code> * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * image(img, 0, 0); * } * </code> * </div> * <div> * <code> * function setup() { * // here we use a callback to display the image after loading * loadImage('assets/laDefense.jpg', function(img) { * image(img, 0, 0); * }); * } * </code> * </div> * * @alt * image of the underside of a white umbrella and grided ceililng above * image of the underside of a white umbrella and grided ceililng above * */p5.prototype.loadImage=function(path,successCallback,failureCallback){p5._validateParameters('loadImage',arguments);var img=new Image();var pImg=new p5.Image(1,1,this);var self=this;img.onload=function(){pImg.width=pImg.canvas.width=img.width;pImg.height=pImg.canvas.height=img.height;// Draw the image into the backing canvas of the p5.Image pImg.drawingContext.drawImage(img,0,0);pImg.modified=true;if(typeof successCallback==='function'){successCallback(pImg);}self._decrementPreload();};img.onerror=function(e){p5._friendlyFileLoadError(0,img.src);if(typeof failureCallback==='function'){failureCallback(e);}};// Set crossOrigin in case image is served with CORS headers. // This will let us draw to the canvas without tainting it. // See https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image // When using data-uris the file will be loaded locally // so we don't need to worry about crossOrigin with base64 file types. if(path.indexOf('data:image/')!==0){img.crossOrigin='Anonymous';}// start loading the image img.src=path;return pImg;};/** * Validates clipping params. Per drawImage spec sWidth and sHight cannot be * negative or greater than image intrinsic width and height * @private * @param {Number} sVal * @param {Number} iVal * @returns {Number} * @private */function _sAssign(sVal,iVal){if(sVal>0&&sVal<iVal){return sVal;}else{return iVal;}}/** * Draw an image to the p5.js canvas. * * This function can be used with different numbers of parameters. The * simplest use requires only three parameters: img, x, and y—where (x, y) is * the position of the image. Two more parameters can optionally be added to * specify the width and height of the image. * * This function can also be used with all eight Number parameters. To * differentiate between all these parameters, p5.js uses the language of * "destination rectangle" (which corresponds to "dx", "dy", etc.) and "source * image" (which corresponds to "sx", "sy", etc.) below. Specifying the * "source image" dimensions can be useful when you want to display a * subsection of the source image instead of the whole thing. Here's a diagram * to explain further: * <img src="assets/drawImage.png"></img> * * @method image * @param {p5.Image|p5.Element} img the image to display * @param {Number} x the x-coordinate of the top-left corner of the image * @param {Number} y the y-coordinate of the top-left corner of the image * @param {Number} [width] the width to draw the image * @param {Number} [height] the height to draw the image * @example * <div> * <code> * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * // Top-left corner of the img is at (0, 0) * // Width and height are the img's original width and height * image(img, 0, 0); * } * </code> * </div> * <div> * <code> * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * background(50); * // Top-left corner of the img is at (10, 10) * // Width and height are 50 x 50 * image(img, 10, 10, 50, 50); * } * </code> * </div> * <div> * <code> * function setup() { * // Here, we use a callback to display the image after loading * loadImage('assets/laDefense.jpg', function(img) { * image(img, 0, 0); * }); * } * </code> * </div> * <div> * <code> * var img; * function preload() { * img = loadImage('assets/gradient.png'); * } * function setup() { * // 1. Background image * // Top-left corner of the img is at (0, 0) * // Width and height are the img's original width and height, 100 x 100 * image(img, 0, 0); * // 2. Top right image * // Top-left corner of destination rectangle is at (50, 0) * // Destination rectangle width and height are 40 x 20 * // The next parameters are relative to the source image: * // - Starting at position (50, 50) on the source image, capture a 50 x 50 * // subsection * // - Draw this subsection to fill the dimensions of the destination rectangle * image(img, 50, 0, 40, 20, 50, 50, 50, 50); * } * </code> * </div> * @alt * image of the underside of a white umbrella and gridded ceiling above * image of the underside of a white umbrella and gridded ceiling above * *//** * @method image * @param {p5.Image|p5.Element} img * @param {Number} dx the x-coordinate of the destination * rectangle in which to draw the source image * @param {Number} dy the y-coordinate of the destination * rectangle in which to draw the source image * @param {Number} dWidth the width of the destination rectangle * @param {Number} dHeight the height of the destination rectangle * @param {Number} sx the x-coordinate of the subsection of the source * image to draw into the destination rectangle * @param {Number} sy the y-coordinate of the subsection of the source * image to draw into the destination rectangle * @param {Number} [sWidth] the width of the subsection of the * source image to draw into the destination * rectangle * @param {Number} [sHeight] the height of the subsection of the * source image to draw into the destination rectangle */p5.prototype.image=function(img,dx,dy,dWidth,dHeight,sx,sy,sWidth,sHeight){// set defaults per spec: https://goo.gl/3ykfOq p5._validateParameters('image',arguments);var defW=img.width;var defH=img.height;if(img.elt&&img.elt.videoWidth&&!img.canvas){// video no canvas defW=img.elt.videoWidth;defH=img.elt.videoHeight;}var _dx=dx;var _dy=dy;var _dw=dWidth||defW;var _dh=dHeight||defH;var _sx=sx||0;var _sy=sy||0;var _sw=sWidth||defW;var _sh=sHeight||defH;_sw=_sAssign(_sw,defW);_sh=_sAssign(_sh,defH);// This part needs cleanup and unit tests // see issues https://github.com/processing/p5.js/issues/1741 // and https://github.com/processing/p5.js/issues/1673 var pd=1;if(img.elt&&!img.canvas&&img.elt.style.width){//if img is video and img.elt.size() has been used and //no width passed to image() if(img.elt.videoWidth&&!dWidth){pd=img.elt.videoWidth;}else{//all other cases pd=img.elt.width;}pd/=parseInt(img.elt.style.width,10);}_sx*=pd;_sy*=pd;_sh*=pd;_sw*=pd;var vals=canvas.modeAdjust(_dx,_dy,_dw,_dh,this._renderer._imageMode);// tint the image if there is a tint this._renderer.image(img,_sx,_sy,_sw,_sh,vals.x,vals.y,vals.w,vals.h);};/** * Sets the fill value for displaying images. Images can be tinted to * specified colors or made transparent by including an alpha value. * <br><br> * To apply transparency to an image without affecting its color, use * white as the tint color and specify an alpha value. For instance, * tint(255, 128) will make an image 50% transparent (assuming the default * alpha range of 0-255, which can be changed with <a href="#/p5/colorMode">colorMode()</a>). * <br><br> * The value for the gray parameter must be less than or equal to the current * maximum value as specified by <a href="#/p5/colorMode">colorMode()</a>. The default maximum value is * 255. * * * @method tint * @param {Number} v1 red or hue value relative to * the current color range * @param {Number} v2 green or saturation value * relative to the current color range * @param {Number} v3 blue or brightness value * relative to the current color range * @param {Number} [alpha] * * @example * <div> * <code> * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * image(img, 0, 0); * tint(0, 153, 204); // Tint blue * image(img, 50, 0); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * image(img, 0, 0); * tint(0, 153, 204, 126); // Tint blue and set transparency * image(img, 50, 0); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * image(img, 0, 0); * tint(255, 126); // Apply transparency without changing color * image(img, 50, 0); * } * </code> * </div> * * @alt * 2 side by side images of umbrella and ceiling, one image with blue tint * Images of umbrella and ceiling, one half of image with blue tint * 2 side by side images of umbrella and ceiling, one image translucent * *//** * @method tint * @param {String} value a color string *//** * @method tint * @param {Number} gray a gray value * @param {Number} [alpha] *//** * @method tint * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color *//** * @method tint * @param {p5.Color} color the tint color */p5.prototype.tint=function(){p5._validateParameters('tint',arguments);var c=this.color.apply(this,arguments);this._renderer._tint=c.levels;};/** * Removes the current fill value for displaying images and reverts to * displaying images with their original hues. * * @method noTint * @example * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * tint(0, 153, 204); // Tint blue * image(img, 0, 0); * noTint(); // Disable tint * image(img, 50, 0); * } * </code> * </div> * * @alt * 2 side by side images of bricks, left image with blue tint * */p5.prototype.noTint=function(){this._renderer._tint=null;};/** * Apply the current tint color to the input image, return the resulting * canvas. * * @private * @param {p5.Image} The image to be tinted * @return {canvas} The resulting tinted canvas * */p5.prototype._getTintedImageCanvas=function(img){if(!img.canvas){return img;}var pixels=Filters._toPixels(img.canvas);var tmpCanvas=document.createElement('canvas');tmpCanvas.width=img.canvas.width;tmpCanvas.height=img.canvas.height;var tmpCtx=tmpCanvas.getContext('2d');var id=tmpCtx.createImageData(img.canvas.width,img.canvas.height);var newPixels=id.data;for(var i=0;i<pixels.length;i+=4){var r=pixels[i];var g=pixels[i+1];var b=pixels[i+2];var a=pixels[i+3];newPixels[i]=r*this._renderer._tint[0]/255;newPixels[i+1]=g*this._renderer._tint[1]/255;newPixels[i+2]=b*this._renderer._tint[2]/255;newPixels[i+3]=a*this._renderer._tint[3]/255;}tmpCtx.putImageData(id,0,0);return tmpCanvas;};/** * Set image mode. Modifies the location from which images are drawn by * changing the way in which parameters given to <a href="#/p5/image">image()</a> are interpreted. * The default mode is imageMode(CORNER), which interprets the second and * third parameters of <a href="#/p5/image">image()</a> as the upper-left corner of the image. If * two additional parameters are specified, they are used to set the image's * width and height. * <br><br> * imageMode(CORNERS) interprets the second and third parameters of <a href="#/p5/image">image()</a> * as the location of one corner, and the fourth and fifth parameters as the * opposite corner. * <br><br> * imageMode(CENTER) interprets the second and third parameters of <a href="#/p5/image">image()</a> * as the image's center point. If two additional parameters are specified, * they are used to set the image's width and height. * * @method imageMode * @param {Constant} mode either CORNER, CORNERS, or CENTER * @example * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * imageMode(CORNER); * image(img, 10, 10, 50, 50); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * imageMode(CORNERS); * image(img, 10, 10, 90, 40); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * imageMode(CENTER); * image(img, 50, 50, 80, 80); * } * </code> * </div> * * @alt * small square image of bricks * horizontal rectangle image of bricks * large square image of bricks * */p5.prototype.imageMode=function(m){p5._validateParameters('imageMode',arguments);if(m===constants.CORNER||m===constants.CORNERS||m===constants.CENTER){this._renderer._imageMode=m;}};module.exports=p5;},{"../core/constants":19,"../core/error_helpers":21,"../core/helpers":22,"../core/main":25,"./filters":43}],46:[function(_dereq_,module,exports){/** * @module Image * @submodule Image * @requires core * @requires constants * @requires filters *//** * This module defines the <a href="#/p5.Image">p5.Image</a> class and P5 methods for * drawing images to the main display canvas. */'use strict';var p5=_dereq_('../core/main');var Filters=_dereq_('./filters');/* * Class methods *//** * Creates a new <a href="#/p5.Image">p5.Image</a>. A <a href="#/p5.Image">p5.Image</a> is a canvas backed representation of an * image. * <br><br> * p5 can display .gif, .jpg and .png images. Images may be displayed * in 2D and 3D space. Before an image is used, it must be loaded with the * <a href="#/p5/loadImage">loadImage()</a> function. The <a href="#/p5.Image">p5.Image</a> class contains fields for the width and * height of the image, as well as an array called <a href="#/p5.Image/pixels">pixels[]</a> that contains the * values for every pixel in the image. * <br><br> * The methods described below allow easy access to the image's pixels and * alpha channel and simplify the process of compositing. * <br><br> * Before using the <a href="#/p5.Image/pixels">pixels[]</a> array, be sure to use the <a href="#/p5.Image/loadPixels">loadPixels()</a> method on * the image to make sure that the pixel data is properly loaded. * @example * <div><code> * function setup() { * var img = createImage(100, 100); // same as new p5.Image(100, 100); * img.loadPixels(); * createCanvas(100, 100); * background(0); * * // helper for writing color to array * function writeColor(image, x, y, red, green, blue, alpha) { * var index = (x + y * width) * 4; * image.pixels[index] = red; * image.pixels[index + 1] = green; * image.pixels[index + 2] = blue; * image.pixels[index + 3] = alpha; * } * * var x, y; * // fill with random colors * for (y = 0; y < img.height; y++) { * for (x = 0; x < img.width; x++) { * var red = random(255); * var green = random(255); * var blue = random(255); * var alpha = 255; * writeColor(img, x, y, red, green, blue, alpha); * } * } * * // draw a red line * y = 0; * for (x = 0; x < img.width; x++) { * writeColor(img, x, y, 255, 0, 0, 255); * } * * // draw a green line * y = img.height - 1; * for (x = 0; x < img.width; x++) { * writeColor(img, x, y, 0, 255, 0, 255); * } * * img.updatePixels(); * image(img, 0, 0); * } * </code></div> * * * @class p5.Image * @param {Number} width * @param {Number} height */p5.Image=function(width,height){/** * Image width. * @property {Number} width * @readOnly * @example * <div><code> * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * createCanvas(100, 100); * image(img, 0, 0); * for (var i = 0; i < img.width; i++) { * var c = img.get(i, img.height / 2); * stroke(c); * line(i, height / 2, i, height); * } * } * </code></div> * * @alt * rocky mountains in top and horizontal lines in corresponding colors in bottom. * */this.width=width;/** * Image height. * @property {Number} height * @readOnly * @example * <div><code> * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * createCanvas(100, 100); * image(img, 0, 0); * for (var i = 0; i < img.height; i++) { * var c = img.get(img.width / 2, i); * stroke(c); * line(0, i, width / 2, i); * } * } * </code></div> * * @alt * rocky mountains on right and vertical lines in corresponding colors on left. * */this.height=height;this.canvas=document.createElement('canvas');this.canvas.width=this.width;this.canvas.height=this.height;this.drawingContext=this.canvas.getContext('2d');this._pixelDensity=1;//used for webgl texturing only this._modified=false;this._pixelsDirty=true;/** * Array containing the values for all the pixels in the display window. * These values are numbers. This array is the size (include an appropriate * factor for pixelDensity) of the display window x4, * representing the R, G, B, A values in order for each pixel, moving from * left to right across each row, then down each column. Retina and other * high denisty displays may have more pixels (by a factor of * pixelDensity^2). * For example, if the image is 100x100 pixels, there will be 40,000. With * pixelDensity = 2, there will be 160,000. The first four values * (indices 0-3) in the array will be the R, G, B, A values of the pixel at * (0, 0). The second four values (indices 4-7) will contain the R, G, B, A * values of the pixel at (1, 0). More generally, to set values for a pixel * at (x, y): * ```javascript * var d = pixelDensity(); * for (var i = 0; i < d; i++) { * for (var j = 0; j < d; j++) { * // loop over * idx = 4 * ((y * d + j) * width * d + (x * d + i)); * pixels[idx] = r; * pixels[idx+1] = g; * pixels[idx+2] = b; * pixels[idx+3] = a; * } * } * ``` * <br><br> * Before accessing this array, the data must loaded with the <a href="#/p5.Image/loadPixels">loadPixels()</a> * function. After the array data has been modified, the <a href="#/p5.Image/updatePixels">updatePixels()</a> * function must be run to update the changes. * @property {Number[]} pixels * @example * <div> * <code> * var img = createImage(66, 66); * img.loadPixels(); * for (var i = 0; i < img.width; i++) { * for (var j = 0; j < img.height; j++) { * img.set(i, j, color(0, 90, 102)); * } * } * img.updatePixels(); * image(img, 17, 17); * </code> * </div> * <div> * <code> * var pink = color(255, 102, 204); * var img = createImage(66, 66); * img.loadPixels(); * for (var i = 0; i < 4 * (width * height / 2); i += 4) { * img.pixels[i] = red(pink); * img.pixels[i + 1] = green(pink); * img.pixels[i + 2] = blue(pink); * img.pixels[i + 3] = alpha(pink); * } * img.updatePixels(); * image(img, 17, 17); * </code> * </div> * * @alt * 66x66 turquoise rect in center of canvas * 66x66 pink rect in center of canvas * */this.pixels=[];};/** * Helper fxn for sharing pixel methods * */p5.Image.prototype._setProperty=function(prop,value){this[prop]=value;this.setModified(true);};/** * Loads the pixels data for this image into the [pixels] attribute. * * @method loadPixels * @example * <div><code> * var myImage; * var halfImage; * * function preload() { * myImage = loadImage('assets/rockies.jpg'); * } * * function setup() { * myImage.loadPixels(); * halfImage = 4 * width * height / 2; * for (var i = 0; i < halfImage; i++) { * myImage.pixels[i + halfImage] = myImage.pixels[i]; * } * myImage.updatePixels(); * } * * function draw() { * image(myImage, 0, 0); * } * </code></div> * * @alt * 2 images of rocky mountains vertically stacked * */p5.Image.prototype.loadPixels=function(){p5.Renderer2D.prototype.loadPixels.call(this);this.setModified(true);};/** * Updates the backing canvas for this image with the contents of * the [pixels] array. * * @method updatePixels * @param {Integer} x x-offset of the target update area for the * underlying canvas * @param {Integer} y y-offset of the target update area for the * underlying canvas * @param {Integer} w height of the target update area for the * underlying canvas * @param {Integer} h height of the target update area for the * underlying canvas * @example * <div><code> * var myImage; * var halfImage; * * function preload() { * myImage = loadImage('assets/rockies.jpg'); * } * * function setup() { * myImage.loadPixels(); * halfImage = 4 * width * height / 2; * for (var i = 0; i < halfImage; i++) { * myImage.pixels[i + halfImage] = myImage.pixels[i]; * } * myImage.updatePixels(); * } * * function draw() { * image(myImage, 0, 0); * } * </code></div> * * @alt * 2 images of rocky mountains vertically stacked * *//** * @method updatePixels */p5.Image.prototype.updatePixels=function(x,y,w,h){p5.Renderer2D.prototype.updatePixels.call(this,x,y,w,h);this.setModified(true);};/** * Get a region of pixels from an image. * * If no params are passed, those whole image is returned, * if x and y are the only params passed a single pixel is extracted * if all params are passed a rectangle region is extracted and a <a href="#/p5.Image">p5.Image</a> * is returned. * * Returns undefined if the region is outside the bounds of the image * * @method get * @param {Number} [x] x-coordinate of the pixel * @param {Number} [y] y-coordinate of the pixel * @param {Number} [w] width * @param {Number} [h] height * @return {Number[]|Color|p5.Image} color of pixel at x,y in array format * [R, G, B, A] or <a href="#/p5.Image">p5.Image</a> * @example * <div><code> * var myImage; * var c; * * function preload() { * myImage = loadImage('assets/rockies.jpg'); * } * * function setup() { * background(myImage); * noStroke(); * c = myImage.get(60, 90); * fill(c); * rect(25, 25, 50, 50); * } * * //get() returns color here * </code></div> * * @alt * image of rocky mountains with 50x50 green rect in front * */p5.Image.prototype.get=function(x,y,w,h){return p5.Renderer2D.prototype.get.call(this,x,y,w,h);};/** * Set the color of a single pixel or write an image into * this <a href="#/p5.Image">p5.Image</a>. * * Note that for a large number of pixels this will * be slower than directly manipulating the pixels array * and then calling <a href="#/p5.Image/updatePixels">updatePixels()</a>. * * @method set * @param {Number} x x-coordinate of the pixel * @param {Number} y y-coordinate of the pixel * @param {Number|Number[]|Object} a grayscale value | pixel array | * a <a href="#/p5.Color">p5.Color</a> | image to copy * @example * <div> * <code> * var img = createImage(66, 66); * img.loadPixels(); * for (var i = 0; i < img.width; i++) { * for (var j = 0; j < img.height; j++) { * img.set(i, j, color(0, 90, 102, (i % img.width) * 2)); * } * } * img.updatePixels(); * image(img, 17, 17); * image(img, 34, 34); * </code> * </div> * * @alt * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas * */p5.Image.prototype.set=function(x,y,imgOrCol){p5.Renderer2D.prototype.set.call(this,x,y,imgOrCol);this.setModified(true);};/** * Resize the image to a new width and height. To make the image scale * proportionally, use 0 as the value for the wide or high parameter. * For instance, to make the width of an image 150 pixels, and change * the height using the same proportion, use resize(150, 0). * * @method resize * @param {Number} width the resized image width * @param {Number} height the resized image height * @example * <div><code> * var img; * * function preload() { * img = loadImage('assets/rockies.jpg'); * } * function draw() { * image(img, 0, 0); * } * * function mousePressed() { * img.resize(50, 100); * } * </code></div> * * @alt * image of rocky mountains. zoomed in * */p5.Image.prototype.resize=function(width,height){// Copy contents to a temporary canvas, resize the original // and then copy back. // // There is a faster approach that involves just one copy and swapping the // this.canvas reference. We could switch to that approach if (as i think // is the case) there an expectation that the user would not hold a // reference to the backing canvas of a p5.Image. But since we do not // enforce that at the moment, I am leaving in the slower, but safer // implementation. // auto-resize if(width===0&&height===0){width=this.canvas.width;height=this.canvas.height;}else if(width===0){width=this.canvas.width*height/this.canvas.height;}else if(height===0){height=this.canvas.height*width/this.canvas.width;}width=Math.floor(width);height=Math.floor(height);var tempCanvas=document.createElement('canvas');tempCanvas.width=width;tempCanvas.height=height;// prettier-ignore tempCanvas.getContext('2d').drawImage(this.canvas,0,0,this.canvas.width,this.canvas.height,0,0,tempCanvas.width,tempCanvas.height);// Resize the original canvas, which will clear its contents this.canvas.width=this.width=width;this.canvas.height=this.height=height;//Copy the image back // prettier-ignore this.drawingContext.drawImage(tempCanvas,0,0,width,height,0,0,width,height);if(this.pixels.length>0){this.loadPixels();}this.setModified(true);this._pixelsDirty=true;};/** * Copies a region of pixels from one image to another. If no * srcImage is specified this is used as the source. If the source * and destination regions aren't the same size, it will * automatically resize source pixels to fit the specified * target region. * * @method copy * @param {p5.Image|p5.Element} srcImage source image * @param {Integer} sx X coordinate of the source's upper left corner * @param {Integer} sy Y coordinate of the source's upper left corner * @param {Integer} sw source image width * @param {Integer} sh source image height * @param {Integer} dx X coordinate of the destination's upper left corner * @param {Integer} dy Y coordinate of the destination's upper left corner * @param {Integer} dw destination image width * @param {Integer} dh destination image height * @example * <div><code> * var photo; * var bricks; * var x; * var y; * * function preload() { * photo = loadImage('assets/rockies.jpg'); * bricks = loadImage('assets/bricks.jpg'); * } * * function setup() { * x = bricks.width / 2; * y = bricks.height / 2; * photo.copy(bricks, 0, 0, x, y, 0, 0, x, y); * image(photo, 0, 0); * } * </code></div> * * @alt * image of rocky mountains and smaller image on top of bricks at top left * *//** * @method copy * @param {Integer} sx * @param {Integer} sy * @param {Integer} sw * @param {Integer} sh * @param {Integer} dx * @param {Integer} dy * @param {Integer} dw * @param {Integer} dh */p5.Image.prototype.copy=function(){var srcImage,sx,sy,sw,sh,dx,dy,dw,dh;if(arguments.length===9){srcImage=arguments[0];sx=arguments[1];sy=arguments[2];sw=arguments[3];sh=arguments[4];dx=arguments[5];dy=arguments[6];dw=arguments[7];dh=arguments[8];}else if(arguments.length===8){srcImage=this;sx=arguments[0];sy=arguments[1];sw=arguments[2];sh=arguments[3];dx=arguments[4];dy=arguments[5];dw=arguments[6];dh=arguments[7];}else{throw new Error('Signature not supported');}p5.Renderer2D._copyHelper(this,srcImage,sx,sy,sw,sh,dx,dy,dw,dh);this._pixelsDirty=true;};/** * Masks part of an image from displaying by loading another * image and using it's alpha channel as an alpha channel for * this image. * * @method mask * @param {p5.Image} srcImage source image * @example * <div><code> * var photo, maskImage; * function preload() { * photo = loadImage('assets/rockies.jpg'); * maskImage = loadImage('assets/mask2.png'); * } * * function setup() { * createCanvas(100, 100); * photo.mask(maskImage); * image(photo, 0, 0); * } * </code></div> * * @alt * image of rocky mountains with white at right * * * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/ * */// TODO: - Accept an array of alpha values. // - Use other channels of an image. p5 uses the // blue channel (which feels kind of arbitrary). Note: at the // moment this method does not match native processings original // functionality exactly. p5.Image.prototype.mask=function(p5Image){if(p5Image===undefined){p5Image=this;}var currBlend=this.drawingContext.globalCompositeOperation;var scaleFactor=1;if(p5Image instanceof p5.Renderer){scaleFactor=p5Image._pInst._pixelDensity;}var copyArgs=[p5Image,0,0,scaleFactor*p5Image.width,scaleFactor*p5Image.height,0,0,this.width,this.height];this.drawingContext.globalCompositeOperation='destination-in';p5.Image.prototype.copy.apply(this,copyArgs);this.drawingContext.globalCompositeOperation=currBlend;this.setModified(true);};/** * Applies an image filter to a <a href="#/p5.Image">p5.Image</a> * * @method filter * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT, * POSTERIZE, BLUR, ERODE, DILATE or BLUR. * See Filters.js for docs on * each available filter * @param {Number} [filterParam] an optional parameter unique * to each filter, see above * @example * <div><code> * var photo1; * var photo2; * * function preload() { * photo1 = loadImage('assets/rockies.jpg'); * photo2 = loadImage('assets/rockies.jpg'); * } * * function setup() { * photo2.filter('gray'); * image(photo1, 0, 0); * image(photo2, width / 2, 0); * } * </code></div> * * @alt * 2 images of rocky mountains left one in color, right in black and white * */p5.Image.prototype.filter=function(operation,value){Filters.apply(this.canvas,Filters[operation.toLowerCase()],value);this.setModified(true);};/** * Copies a region of pixels from one image to another, using a specified * blend mode to do the operation. * * @method blend * @param {p5.Image} srcImage source image * @param {Integer} sx X coordinate of the source's upper left corner * @param {Integer} sy Y coordinate of the source's upper left corner * @param {Integer} sw source image width * @param {Integer} sh source image height * @param {Integer} dx X coordinate of the destination's upper left corner * @param {Integer} dy Y coordinate of the destination's upper left corner * @param {Integer} dw destination image width * @param {Integer} dh destination image height * @param {Constant} blendMode the blend mode. either * BLEND, DARKEST, LIGHTEST, DIFFERENCE, * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. * * Available blend modes are: normal | multiply | screen | overlay | * darken | lighten | color-dodge | color-burn | hard-light | * soft-light | difference | exclusion | hue | saturation | * color | luminosity * * * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/ * @example * <div><code> * var mountains; * var bricks; * * function preload() { * mountains = loadImage('assets/rockies.jpg'); * bricks = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD); * image(mountains, 0, 0); * image(bricks, 0, 0); * } * </code></div> * <div><code> * var mountains; * var bricks; * * function preload() { * mountains = loadImage('assets/rockies.jpg'); * bricks = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST); * image(mountains, 0, 0); * image(bricks, 0, 0); * } * </code></div> * <div><code> * var mountains; * var bricks; * * function preload() { * mountains = loadImage('assets/rockies.jpg'); * bricks = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST); * image(mountains, 0, 0); * image(bricks, 0, 0); * } * </code></div> * * @alt * image of rocky mountains. Brick images on left and right. Right overexposed * image of rockies. Brickwall images on left and right. Right mortar transparent * image of rockies. Brickwall images on left and right. Right translucent * *//** * @method blend * @param {Integer} sx * @param {Integer} sy * @param {Integer} sw * @param {Integer} sh * @param {Integer} dx * @param {Integer} dy * @param {Integer} dw * @param {Integer} dh * @param {Constant} blendMode */p5.Image.prototype.blend=function(){p5.prototype.blend.apply(this,arguments);this.setModified(true);};/** * helper method for web GL mode to indicate that an image has been * changed or unchanged since last upload. gl texture upload will * set this value to false after uploading the texture. * @method setModified * @param {boolean} val sets whether or not the image has been * modified. * @private */p5.Image.prototype.setModified=function(val){this._modified=val;//enforce boolean? };/** * helper method for web GL mode to figure out if the image * has been modified and might need to be re-uploaded to texture * memory between frames. * @method isModified * @private * @return {boolean} a boolean indicating whether or not the * image has been updated or modified since last texture upload. */p5.Image.prototype.isModified=function(){return this._modified;};/** * Saves the image to a file and force the browser to download it. * Accepts two strings for filename and file extension * Supports png (default) and jpg. * * @method save * @param {String} filename give your file a name * @param {String} extension 'png' or 'jpg' * @example * <div><code> * var photo; * * function preload() { * photo = loadImage('assets/rockies.jpg'); * } * * function draw() { * image(photo, 0, 0); * } * * function keyTyped() { * if (key === 's') { * photo.save('photo', 'png'); * } * } * </code></div> * * @alt * image of rocky mountains. * */p5.Image.prototype.save=function(filename,extension){p5.prototype.saveCanvas(this.canvas,filename,extension);};module.exports=p5.Image;},{"../core/main":25,"./filters":43}],47:[function(_dereq_,module,exports){/** * @module Image * @submodule Pixels * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');var Filters=_dereq_('./filters');_dereq_('../color/p5.Color');/** * <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference * /Global_Objects/Uint8ClampedArray' target='_blank'>Uint8ClampedArray</a> * containing the values for all the pixels in the display window. * These values are numbers. This array is the size (include an appropriate * factor for <a href="#/p5/pixelDensity">pixelDensity</a>) of the display window x4, * representing the R, G, B, A values in order for each pixel, moving from * left to right across each row, then down each column. Retina and other * high density displays will have more pixels[] (by a factor of * pixelDensity^2). * For example, if the image is 100x100 pixels, there will be 40,000. On a * retina display, there will be 160,000. * <br><br> * The first four values (indices 0-3) in the array will be the R, G, B, A * values of the pixel at (0, 0). The second four values (indices 4-7) will * contain the R, G, B, A values of the pixel at (1, 0). More generally, to * set values for a pixel at (x, y): * ```javascript * var d = pixelDensity(); * for (var i = 0; i < d; i++) { * for (var j = 0; j < d; j++) { * // loop over * idx = 4 * ((y * d + j) * width * d + (x * d + i)); * pixels[idx] = r; * pixels[idx+1] = g; * pixels[idx+2] = b; * pixels[idx+3] = a; * } * } * ``` * <p>While the above method is complex, it is flexible enough to work with * any pixelDensity. Note that <a href="#/p5/set">set()</a> will automatically take care of * setting all the appropriate values in <a href="#/p5/pixels">pixels[]</a> for a given (x, y) at * any pixelDensity, but the performance may not be as fast when lots of * modifications are made to the pixel array. * <br><br> * Before accessing this array, the data must loaded with the <a href="#/p5/loadPixels">loadPixels()</a> * function. After the array data has been modified, the <a href="#/p5/updatePixels">updatePixels()</a> * function must be run to update the changes. * <br><br> * Note that this is not a standard javascript array. This means that * standard javascript functions such as <a href="#/p5/slice">slice()</a> or * <a href="#/p5/arrayCopy">arrayCopy()</a> do not * work.</p> * * @property {Number[]} pixels * @example * <div> * <code> * var pink = color(255, 102, 204); * loadPixels(); * var d = pixelDensity(); * var halfImage = 4 * (width * d) * (height / 2 * d); * for (var i = 0; i < halfImage; i += 4) { * pixels[i] = red(pink); * pixels[i + 1] = green(pink); * pixels[i + 2] = blue(pink); * pixels[i + 3] = alpha(pink); * } * updatePixels(); * </code> * </div> * * @alt * top half of canvas pink, bottom grey * */p5.prototype.pixels=[];/** * Copies a region of pixels from one image to another, using a specified * blend mode to do the operation. * * @method blend * @param {p5.Image} srcImage source image * @param {Integer} sx X coordinate of the source's upper left corner * @param {Integer} sy Y coordinate of the source's upper left corner * @param {Integer} sw source image width * @param {Integer} sh source image height * @param {Integer} dx X coordinate of the destination's upper left corner * @param {Integer} dy Y coordinate of the destination's upper left corner * @param {Integer} dw destination image width * @param {Integer} dh destination image height * @param {Constant} blendMode the blend mode. either * BLEND, DARKEST, LIGHTEST, DIFFERENCE, * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. * * @example * <div><code> * var img0; * var img1; * * function preload() { * img0 = loadImage('assets/rockies.jpg'); * img1 = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * background(img0); * image(img1, 0, 0); * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST); * } * </code></div> * <div><code> * var img0; * var img1; * * function preload() { * img0 = loadImage('assets/rockies.jpg'); * img1 = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * background(img0); * image(img1, 0, 0); * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST); * } * </code></div> * <div><code> * var img0; * var img1; * * function preload() { * img0 = loadImage('assets/rockies.jpg'); * img1 = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * background(img0); * image(img1, 0, 0); * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD); * } * </code></div> * * @alt * image of rocky mountains. Brick images on left and right. Right overexposed * image of rockies. Brickwall images on left and right. Right mortar transparent * image of rockies. Brickwall images on left and right. Right translucent * * *//** * @method blend * @param {Integer} sx * @param {Integer} sy * @param {Integer} sw * @param {Integer} sh * @param {Integer} dx * @param {Integer} dy * @param {Integer} dw * @param {Integer} dh * @param {Constant} blendMode */p5.prototype.blend=function(){p5._validateParameters('blend',arguments);if(this._renderer){this._renderer.blend.apply(this._renderer,arguments);}else{p5.Renderer2D.prototype.blend.apply(this,arguments);}};/** * Copies a region of the canvas to another region of the canvas * and copies a region of pixels from an image used as the srcImg parameter * into the canvas srcImage is specified this is used as the source. If * the source and destination regions aren't the same size, it will * automatically resize source pixels to fit the specified * target region. * * @method copy * @param {p5.Image|p5.Element} srcImage source image * @param {Integer} sx X coordinate of the source's upper left corner * @param {Integer} sy Y coordinate of the source's upper left corner * @param {Integer} sw source image width * @param {Integer} sh source image height * @param {Integer} dx X coordinate of the destination's upper left corner * @param {Integer} dy Y coordinate of the destination's upper left corner * @param {Integer} dw destination image width * @param {Integer} dh destination image height * * @example * <div><code> * var img; * * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * background(img); * copy(img, 7, 22, 10, 10, 35, 25, 50, 50); * stroke(255); * noFill(); * // Rectangle shows area being copied * rect(7, 22, 10, 10); * } * </code></div> * * @alt * image of rocky mountains. Brick images on left and right. Right overexposed * image of rockies. Brickwall images on left and right. Right mortar transparent * image of rockies. Brickwall images on left and right. Right translucent * *//** * @method copy * @param {Integer} sx * @param {Integer} sy * @param {Integer} sw * @param {Integer} sh * @param {Integer} dx * @param {Integer} dy * @param {Integer} dw * @param {Integer} dh */p5.prototype.copy=function(){p5._validateParameters('copy',arguments);p5.Renderer2D.prototype.copy.apply(this._renderer,arguments);};/** * Applies a filter to the canvas. * <br><br> * * The presets options are: * <br><br> * * THRESHOLD * Converts the image to black and white pixels depending if they are above or * below the threshold defined by the level parameter. The parameter must be * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. * <br><br> * * GRAY * Converts any colors in the image to grayscale equivalents. No parameter * is used. * <br><br> * * OPAQUE * Sets the alpha channel to entirely opaque. No parameter is used. * <br><br> * * INVERT * Sets each pixel to its inverse value. No parameter is used. * <br><br> * * POSTERIZE * Limits each channel of the image to the number of colors specified as the * parameter. The parameter can be set to values between 2 and 255, but * results are most noticeable in the lower ranges. * <br><br> * * BLUR * Executes a Gaussian blur with the level parameter specifying the extent * of the blurring. If no parameter is used, the blur is equivalent to * Gaussian blur of radius 1. Larger values increase the blur. * <br><br> * * ERODE * Reduces the light areas. No parameter is used. * <br><br> * * DILATE * Increases the light areas. No parameter is used. * * @method filter * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT, * POSTERIZE, BLUR, ERODE, DILATE or BLUR. * See Filters.js for docs on * each available filter * @param {Number} [filterParam] an optional parameter unique * to each filter, see above * * @example * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(THRESHOLD); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(GRAY); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(OPAQUE); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(INVERT); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(POSTERIZE, 3); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(DILATE); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(BLUR, 3); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(ERODE); * } * </code> * </div> * * @alt * black and white image of a brick wall. * greyscale image of a brickwall * image of a brickwall * jade colored image of a brickwall * red and pink image of a brickwall * image of a brickwall * blurry image of a brickwall * image of a brickwall * image of a brickwall with less detail * */p5.prototype.filter=function(operation,value){p5._validateParameters('filter',arguments);if(this.canvas!==undefined){Filters.apply(this.canvas,Filters[operation.toLowerCase()],value);}else{Filters.apply(this.elt,Filters[operation.toLowerCase()],value);}};/** * Returns an array of [R,G,B,A] values for any pixel or grabs a section of * an image. If no parameters are specified, the entire image is returned. * Use the x and y parameters to get the value of one pixel. Get a section of * the display window by specifying additional w and h parameters. When * getting an image, the x and y parameters define the coordinates for the * upper-left corner of the image, regardless of the current <a href="#/p5/imageMode">imageMode()</a>. * <br><br> * If the pixel requested is outside of the image window, [0,0,0,255] is * returned. To get the numbers scaled according to the current color ranges * and taking into account <a href="#/p5/colorMode">colorMode</a>, use <a href="#/p5/getColor">getColor</a> instead of get. * <br><br> * Getting the color of a single pixel with get(x, y) is easy, but not as fast * as grabbing the data directly from <a href="#/p5/pixels">pixels[]</a>. The equivalent statement to * get(x, y) using <a href="#/p5/pixels">pixels[]</a> with pixel density d is * <code> * var x, y, d; // set these to the coordinates * var off = (y * width + x) * d * 4; * var components = [ * pixels[off], * pixels[off + 1], * pixels[off + 2], * pixels[off + 3] * ]; * print(components); * </code> * <br><br> * See the reference for <a href="#/p5/pixels">pixels[]</a> for more information. * * If you want to extract an array of colors or a subimage from an p5.Image object, * take a look at <a href="#/p5.Image/get">p5.Image.get()</a> * * @method get * @param {Number} [x] x-coordinate of the pixel * @param {Number} [y] y-coordinate of the pixel * @param {Number} [w] width * @param {Number} [h] height * @return {Number[]|p5.Image} values of pixel at x,y in array format * [R, G, B, A] or <a href="#/p5.Image">p5.Image</a> * @example * <div> * <code> * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * function setup() { * image(img, 0, 0); * var c = get(); * image(c, width / 2, 0); * } * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * function setup() { * image(img, 0, 0); * var c = get(50, 90); * fill(c); * noStroke(); * rect(25, 25, 50, 50); * } * </code> * </div> * * @alt * 2 images of the rocky mountains, side-by-side * Image of the rocky mountains with 50x50 green rect in center of canvas * */p5.prototype.get=function(x,y,w,h){return this._renderer.get(x,y,w,h);};/** * Loads the pixel data for the display window into the <a href="#/p5/pixels">pixels[]</a> array. This * function must always be called before reading from or writing to <a href="#/p5/pixels">pixels[]</a>. * Note that only changes made with <a href="#/p5/set">set()</a> or direct manipulation of <a href="#/p5/pixels">pixels[]</a> * will occur. * * @method loadPixels * @example * <div> * <code> * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * image(img, 0, 0); * var d = pixelDensity(); * var halfImage = 4 * (img.width * d) * (img.height * d / 2); * loadPixels(); * for (var i = 0; i < halfImage; i++) { * pixels[i + halfImage] = pixels[i]; * } * updatePixels(); * } * </code> * </div> * * @alt * two images of the rocky mountains. one on top, one on bottom of canvas. * */p5.prototype.loadPixels=function(){p5._validateParameters('loadPixels',arguments);this._renderer.loadPixels();};/** * <p>Changes the color of any pixel, or writes an image directly to the * display window.</p> * <p>The x and y parameters specify the pixel to change and the c parameter * specifies the color value. This can be a <a href="#/p5.Color">p5.Color</a> object, or [R, G, B, A] * pixel array. It can also be a single grayscale value. * When setting an image, the x and y parameters define the coordinates for * the upper-left corner of the image, regardless of the current <a href="#/p5/imageMode">imageMode()</a>. * </p> * <p> * After using <a href="#/p5/set">set()</a>, you must call <a href="#/p5/updatePixels">updatePixels()</a> for your changes to appear. * This should be called once all pixels have been set, and must be called before * calling .<a href="#/p5/get">get()</a> or drawing the image. * </p> * <p>Setting the color of a single pixel with set(x, y) is easy, but not as * fast as putting the data directly into <a href="#/p5/pixels">pixels[]</a>. Setting the <a href="#/p5/pixels">pixels[]</a> * values directly may be complicated when working with a retina display, * but will perform better when lots of pixels need to be set directly on * every loop.</p> * <p>See the reference for <a href="#/p5/pixels">pixels[]</a> for more information.</p> * * @method set * @param {Number} x x-coordinate of the pixel * @param {Number} y y-coordinate of the pixel * @param {Number|Number[]|Object} c insert a grayscale value | a pixel array | * a <a href="#/p5.Color">p5.Color</a> object | a <a href="#/p5.Image">p5.Image</a> to copy * @example * <div> * <code> * var black = color(0); * set(30, 20, black); * set(85, 20, black); * set(85, 75, black); * set(30, 75, black); * updatePixels(); * </code> * </div> * * <div> * <code> * for (var i = 30; i < width - 15; i++) { * for (var j = 20; j < height - 25; j++) { * var c = color(204 - j, 153 - i, 0); * set(i, j, c); * } * } * updatePixels(); * </code> * </div> * * <div> * <code> * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * set(0, 0, img); * updatePixels(); * line(0, 0, width, height); * line(0, height, width, 0); * } * </code> * </div> * * @alt * 4 black points in the shape of a square middle-right of canvas. * square with orangey-brown gradient lightening at bottom right. * image of the rocky mountains. with lines like an 'x' through the center. */p5.prototype.set=function(x,y,imgOrCol){this._renderer.set(x,y,imgOrCol);};/** * Updates the display window with the data in the <a href="#/p5/pixels">pixels[]</a> array. * Use in conjunction with <a href="#/p5/loadPixels">loadPixels()</a>. If you're only reading pixels from * the array, there's no need to call <a href="#/p5/updatePixels">updatePixels()</a> — updating is only * necessary to apply changes. <a href="#/p5/updatePixels">updatePixels()</a> should be called anytime the * pixels array is manipulated or <a href="#/p5/set">set()</a> is called, and only changes made with * <a href="#/p5/set">set()</a> or direct changes to <a href="#/p5/pixels">pixels[]</a> will occur. * * @method updatePixels * @param {Number} [x] x-coordinate of the upper-left corner of region * to update * @param {Number} [y] y-coordinate of the upper-left corner of region * to update * @param {Number} [w] width of region to update * @param {Number} [h] height of region to update * @example * <div> * <code> * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * image(img, 0, 0); * var d = pixelDensity(); * var halfImage = 4 * (img.width * d) * (img.height * d / 2); * loadPixels(); * for (var i = 0; i < halfImage; i++) { * pixels[i + halfImage] = pixels[i]; * } * updatePixels(); * } * </code> * </div> * @alt * two images of the rocky mountains. one on top, one on bottom of canvas. */p5.prototype.updatePixels=function(x,y,w,h){p5._validateParameters('updatePixels',arguments);// graceful fail - if loadPixels() or set() has not been called, pixel // array will be empty, ignore call to updatePixels() if(this.pixels.length===0){return;}this._renderer.updatePixels(x,y,w,h);};module.exports=p5;},{"../color/p5.Color":17,"../core/main":25,"./filters":43}],48:[function(_dereq_,module,exports){/** * @module IO * @submodule Input * @for p5 * @requires core *//* globals Request: false *//* globals Headers: false */'use strict';var p5=_dereq_('../core/main');_dereq_('whatwg-fetch');_dereq_('es6-promise').polyfill();var fetchJsonp=_dereq_('fetch-jsonp');_dereq_('../core/error_helpers');/** * Loads a JSON file from a file or a URL, and returns an Object. * Note that even if the JSON file contains an Array, an Object will be * returned with index numbers as keys. * * This method is asynchronous, meaning it may not finish before the next * line in your sketch is executed. JSONP is supported via a polyfill and you * can pass in as the second argument an object with definitions of the json * callback following the syntax specified <a href="https://github.com/camsong/ * fetch-jsonp">here</a>. * * This method is suitable for fetching files up to size of 64MB. * @method loadJSON * @param {String} path name of the file or url to load * @param {Object} [jsonpOptions] options object for jsonp related settings * @param {String} [datatype] "json" or "jsonp" * @param {function} [callback] function to be executed after * <a href="#/p5/loadJSON">loadJSON()</a> completes, data is passed * in as first argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @return {Object|Array} JSON data * @example * * <p>Calling <a href="#/p5/loadJSON">loadJSON()</a> inside <a href="#/p5/preload">preload()</a> guarantees to complete the * operation before <a href="#/p5/setup">setup()</a> and <a href="#/p5/draw">draw()</a> are called.</p> * * <div><code> * // Examples use USGS Earthquake API: * // https://earthquake.usgs.gov/fdsnws/event/1/#methods * var earthquakes; * function preload() { * // Get the most recent earthquake in the database * var url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' + * 'summary/all_day.geojson'; * earthquakes = loadJSON(url); * } * * function setup() { * noLoop(); * } * * function draw() { * background(200); * // Get the magnitude and name of the earthquake out of the loaded JSON * var earthquakeMag = earthquakes.features[0].properties.mag; * var earthquakeName = earthquakes.features[0].properties.place; * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10); * textAlign(CENTER); * text(earthquakeName, 0, height - 30, width, 30); * } * </code></div> * * * <p>Outside of preload(), you may supply a callback function to handle the * object:</p> * <div><code> * function setup() { * noLoop(); * var url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' + * 'summary/all_day.geojson'; * loadJSON(url, drawEarthquake); * } * * function draw() { * background(200); * } * * function drawEarthquake(earthquakes) { * // Get the magnitude and name of the earthquake out of the loaded JSON * var earthquakeMag = earthquakes.features[0].properties.mag; * var earthquakeName = earthquakes.features[0].properties.place; * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10); * textAlign(CENTER); * text(earthquakeName, 0, height - 30, width, 30); * } * </code></div> * * @alt * 50x50 ellipse that changes from black to white depending on the current humidity * 50x50 ellipse that changes from black to white depending on the current humidity * *//** * @method loadJSON * @param {String} path * @param {String} datatype * @param {function} [callback] * @param {function} [errorCallback] * @return {Object|Array} *//** * @method loadJSON * @param {String} path * @param {function} callback * @param {function} [errorCallback] * @return {Object|Array} */p5.prototype.loadJSON=function(){p5._validateParameters('loadJSON',arguments);var path=arguments[0];var callback;var errorCallback;var options;var ret={};// object needed for preload var t='json';// check for explicit data type argument for(var i=1;i<arguments.length;i++){var arg=arguments[i];if(typeof arg==='string'){if(arg==='jsonp'||arg==='json'){t=arg;}}else if(typeof arg==='function'){if(!callback){callback=arg;}else{errorCallback=arg;}}else if((typeof arg==="undefined"?"undefined":_typeof(arg))==='object'&&arg.hasOwnProperty('jsonpCallback')){t='jsonp';options=arg;}}var self=this;this.httpDo(path,'GET',options,t,function(resp){for(var k in resp){ret[k]=resp[k];}if(typeof callback!=='undefined'){callback(resp);}self._decrementPreload();},function(err){// Error handling p5._friendlyFileLoadError(5,path);if(errorCallback){errorCallback(err);}else{throw err;}});return ret;};/** * Reads the contents of a file and creates a String array of its individual * lines. If the name of the file is used as the parameter, as in the above * example, the file must be located in the sketch directory/folder. * <br><br> * Alternatively, the file maybe be loaded from anywhere on the local * computer using an absolute path (something that starts with / on Unix and * Linux, or a drive letter on Windows), or the filename parameter can be a * URL for a file found on a network. * <br><br> * This method is asynchronous, meaning it may not finish before the next * line in your sketch is executed. * * This method is suitable for fetching files up to size of 64MB. * @method loadStrings * @param {String} filename name of the file or url to load * @param {function} [callback] function to be executed after <a href="#/p5/loadStrings">loadStrings()</a> * completes, Array is passed in as first * argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @return {String[]} Array of Strings * @example * * <p>Calling loadStrings() inside <a href="#/p5/preload">preload()</a> guarantees to complete the * operation before <a href="#/p5/setup">setup()</a> and <a href="#/p5/draw">draw()</a> are called.</p> * * <div><code> * var result; * function preload() { * result = loadStrings('assets/test.txt'); * } * function setup() { * background(200); * var ind = floor(random(result.length)); * text(result[ind], 10, 10, 80, 80); * } * </code></div> * * <p>Outside of preload(), you may supply a callback function to handle the * object:</p> * * <div><code> * function setup() { * loadStrings('assets/test.txt', pickString); * } * * function pickString(result) { * background(200); * var ind = floor(random(result.length)); * text(result[ind], 10, 10, 80, 80); * } * </code></div> * * @alt * randomly generated text from a file, for example "i smell like butter" * randomly generated text from a file, for example "i have three feet" * */p5.prototype.loadStrings=function(){p5._validateParameters('loadStrings',arguments);var ret=[];var callback,errorCallback;for(var i=1;i<arguments.length;i++){var arg=arguments[i];if(typeof arg==='function'){if(typeof callback==='undefined'){callback=arg;}else if(typeof errorCallback==='undefined'){errorCallback=arg;}}}var self=this;p5.prototype.httpDo.call(this,arguments[0],'GET','text',function(data){// split lines handling mac/windows/linux endings var lines=data.replace(/\r\n/g,'\r').replace(/\n/g,'\r').split(/\r/);Array.prototype.push.apply(ret,lines);if(typeof callback!=='undefined'){callback(ret);}self._decrementPreload();},function(err){// Error handling p5._friendlyFileLoadError(3,arguments[0]);if(errorCallback){errorCallback(err);}else{throw err;}});return ret;};/** * <p>Reads the contents of a file or URL and creates a <a href="#/p5.Table">p5.Table</a> object with * its values. If a file is specified, it must be located in the sketch's * "data" folder. The filename parameter can also be a URL to a file found * online. By default, the file is assumed to be comma-separated (in CSV * format). Table only looks for a header row if the 'header' option is * included.</p> * * <p>Possible options include: * <ul> * <li>csv - parse the table as comma-separated values</li> * <li>tsv - parse the table as tab-separated values</li> * <li>header - this table has a header (title) row</li> * </ul> * </p> * * <p>When passing in multiple options, pass them in as separate parameters, * seperated by commas. For example: * <br><br> * <code> * loadTable('my_csv_file.csv', 'csv', 'header'); * </code> * </p> * * <p> All files loaded and saved use UTF-8 encoding.</p> * * <p>This method is asynchronous, meaning it may not finish before the next * line in your sketch is executed. Calling <a href="#/p5/loadTable">loadTable()</a> inside <a href="#/p5/preload">preload()</a> * guarantees to complete the operation before <a href="#/p5/setup">setup()</a> and <a href="#/p5/draw">draw()</a> are called. * <p>Outside of <a href="#/p5/preload">preload()</a>, you may supply a callback function to handle the * object:</p> * </p> * * This method is suitable for fetching files up to size of 64MB. * @method loadTable * @param {String} filename name of the file or URL to load * @param {String} options "header" "csv" "tsv" * @param {function} [callback] function to be executed after * <a href="#/p5/loadTable">loadTable()</a> completes. On success, the * <a href="#/p5.Table">Table</a> object is passed in as the * first argument. * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @return {Object} <a href="#/p5.Table">Table</a> object containing data * * @example * <div class='norender'> * <code> * // Given the following CSV file called "mammals.csv" * // located in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * //the file can be remote * //table = loadTable("http://p5js.org/reference/assets/mammals.csv", * // "csv", "header"); * } * * function setup() { * //count the columns * print(table.getRowCount() + ' total rows in table'); * print(table.getColumnCount() + ' total columns in table'); * * print(table.getColumn('name')); * //["Goat", "Leopard", "Zebra"] * * //cycle through the table * for (var r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) { * print(table.getString(r, c)); * } * } * </code> * </div> * * @alt * randomly generated text from a file, for example "i smell like butter" * randomly generated text from a file, for example "i have three feet" * *//** * @method loadTable * @param {String} filename * @param {function} [callback] * @param {function} [errorCallback] * @return {Object} */p5.prototype.loadTable=function(path){var callback;var errorCallback;var options=[];var header=false;var ext=path.substring(path.lastIndexOf('.')+1,path.length);var sep=',';var separatorSet=false;if(ext==='tsv'){//Only need to check extension is tsv because csv is default sep='\t';}for(var i=1;i<arguments.length;i++){if(typeof arguments[i]==='function'){if(typeof callback==='undefined'){callback=arguments[i];}else if(typeof errorCallback==='undefined'){errorCallback=arguments[i];}}else if(typeof arguments[i]==='string'){options.push(arguments[i]);if(arguments[i]==='header'){header=true;}if(arguments[i]==='csv'){if(separatorSet){throw new Error('Cannot set multiple separator types.');}else{sep=',';separatorSet=true;}}else if(arguments[i]==='tsv'){if(separatorSet){throw new Error('Cannot set multiple separator types.');}else{sep='\t';separatorSet=true;}}}}var t=new p5.Table();var self=this;this.httpDo(path,'GET','table',function(resp){var state={};// define constants var PRE_TOKEN=0,MID_TOKEN=1,POST_TOKEN=2,POST_RECORD=4;var QUOTE='"',CR='\r',LF='\n';var records=[];var offset=0;var currentRecord=null;var currentChar;var tokenBegin=function tokenBegin(){state.currentState=PRE_TOKEN;state.token='';};var tokenEnd=function tokenEnd(){currentRecord.push(state.token);tokenBegin();};var recordBegin=function recordBegin(){state.escaped=false;currentRecord=[];tokenBegin();};var recordEnd=function recordEnd(){state.currentState=POST_RECORD;records.push(currentRecord);currentRecord=null;};for(;;){currentChar=resp[offset++];// EOF if(currentChar==null){if(state.escaped){throw new Error('Unclosed quote in file.');}if(currentRecord){tokenEnd();recordEnd();break;}}if(currentRecord===null){recordBegin();}// Handle opening quote if(state.currentState===PRE_TOKEN){if(currentChar===QUOTE){state.escaped=true;state.currentState=MID_TOKEN;continue;}state.currentState=MID_TOKEN;}// mid-token and escaped, look for sequences and end quote if(state.currentState===MID_TOKEN&&state.escaped){if(currentChar===QUOTE){if(resp[offset]===QUOTE){state.token+=QUOTE;offset++;}else{state.escaped=false;state.currentState=POST_TOKEN;}}else if(currentChar===CR){continue;}else{state.token+=currentChar;}continue;}// fall-through: mid-token or post-token, not escaped if(currentChar===CR){if(resp[offset]===LF){offset++;}tokenEnd();recordEnd();}else if(currentChar===LF){tokenEnd();recordEnd();}else if(currentChar===sep){tokenEnd();}else if(state.currentState===MID_TOKEN){state.token+=currentChar;}}// set up column names if(header){t.columns=records.shift();}else{for(i=0;i<records[0].length;i++){t.columns[i]='null';}}var row;for(i=0;i<records.length;i++){//Handles row of 'undefined' at end of some CSVs if(records[i].length===1){if(records[i][0]==='undefined'||records[i][0]===''){continue;}}row=new p5.TableRow();row.arr=records[i];row.obj=makeObject(records[i],t.columns);t.addRow(row);}if(typeof callback==='function'){callback(t);}self._decrementPreload();},function(err){// Error handling p5._friendlyFileLoadError(2,path);if(errorCallback){errorCallback(err);}else{throw err;}});return t;};// helper function to turn a row into a JSON object function makeObject(row,headers){var ret={};headers=headers||[];if(typeof headers==='undefined'){for(var j=0;j<row.length;j++){headers[j.toString()]=j;}}for(var i=0;i<headers.length;i++){var key=headers[i];var val=row[i];ret[key]=val;}return ret;}function parseXML(two){var one=new p5.XML();var children=two.childNodes;if(children&&children.length){for(var i=0;i<children.length;i++){var node=parseXML(children[i]);one.addChild(node);}one.setName(two.nodeName);one._setCont(two.textContent);one._setAttributes(two);for(var j=0;j<one.children.length;j++){one.children[j].parent=one;}return one;}else{one.setName(two.nodeName);one._setCont(two.textContent);one._setAttributes(two);return one;}}/** * Reads the contents of a file and creates an XML object with its values. * If the name of the file is used as the parameter, as in the above example, * the file must be located in the sketch directory/folder. * * Alternatively, the file maybe be loaded from anywhere on the local * computer using an absolute path (something that starts with / on Unix and * Linux, or a drive letter on Windows), or the filename parameter can be a * URL for a file found on a network. * * This method is asynchronous, meaning it may not finish before the next * line in your sketch is executed. Calling <a href="#/p5/loadXML">loadXML()</a> inside <a href="#/p5/preload">preload()</a> * guarantees to complete the operation before <a href="#/p5/setup">setup()</a> and <a href="#/p5/draw">draw()</a> are called. * * Outside of <a href="#/p5/preload">preload()</a>, you may supply a callback function to handle the * object. * * This method is suitable for fetching files up to size of 64MB. * @method loadXML * @param {String} filename name of the file or URL to load * @param {function} [callback] function to be executed after <a href="#/p5/loadXML">loadXML()</a> * completes, XML object is passed in as * first argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @return {Object} XML object containing data * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var children = xml.getChildren('animal'); * * for (var i = 0; i < children.length; i++) { * var id = children[i].getNum('id'); * var coloring = children[i].getString('species'); * var name = children[i].getContent(); * print(id + ', ' + coloring + ', ' + name); * } * } * * // Sketch prints: * // 0, Capra hircus, Goat * // 1, Panthera pardus, Leopard * // 2, Equus zebra, Zebra * </code></div> * * @alt * no image displayed * */p5.prototype.loadXML=function(){var ret={};var callback,errorCallback;for(var i=1;i<arguments.length;i++){var arg=arguments[i];if(typeof arg==='function'){if(typeof callback==='undefined'){callback=arg;}else if(typeof errorCallback==='undefined'){errorCallback=arg;}}}var self=this;this.httpDo(arguments[0],'GET','xml',function(xml){for(var key in xml){ret[key]=xml[key];}if(typeof callback!=='undefined'){callback(ret);}self._decrementPreload();},function(err){// Error handling p5._friendlyFileLoadError(1,arguments[0]);if(errorCallback){errorCallback(err);}else{throw err;}});return ret;};/** * This method is suitable for fetching files up to size of 64MB. * @method loadBytes * @param {string} file name of the file or URL to load * @param {function} [callback] function to be executed after <a href="#/p5/loadBytes">loadBytes()</a> * completes * @param {function} [errorCallback] function to be executed if there * is an error * @returns {Object} an object whose 'bytes' property will be the loaded buffer * * @example * <div class='norender'><code> * var data; * * function preload() { * data = loadBytes('assets/mammals.xml'); * } * * function setup() { * for (var i = 0; i < 5; i++) { * console.log(data.bytes[i].toString(16)); * } * } * </code></div> * * @alt * no image displayed * */p5.prototype.loadBytes=function(file,callback,errorCallback){var ret={};var self=this;this.httpDo(file,'GET','arrayBuffer',function(arrayBuffer){ret.bytes=new Uint8Array(arrayBuffer);if(typeof callback==='function'){callback(ret);}self._decrementPreload();},function(err){// Error handling p5._friendlyFileLoadError(6,file);if(errorCallback){errorCallback(err);}else{throw err;}});return ret;};/** * Method for executing an HTTP GET request. If data type is not specified, * p5 will try to guess based on the URL, defaulting to text. This is equivalent to * calling <code>httpDo(path, 'GET')</code>. The 'binary' datatype will return * a Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer * which can be used to initialize typed arrays (such as Uint8Array). * * @method httpGet * @param {String} path name of the file or url to load * @param {String} [datatype] "json", "jsonp", "binary", "arrayBuffer", * "xml", or "text" * @param {Object|Boolean} [data] param data passed sent with request * @param {function} [callback] function to be executed after * <a href="#/p5/httpGet">httpGet()</a> completes, data is passed in * as first argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @return {Promise} A promise that resolves with the data when the operation * completes successfully or rejects with the error after * one occurs. * @example * <div class='norender'><code> * // Examples use USGS Earthquake API: * // https://earthquake.usgs.gov/fdsnws/event/1/#methods * var earthquakes; * function preload() { * // Get the most recent earthquake in the database * var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?' + * 'format=geojson&limit=1&orderby=time'; * httpGet(url, 'jsonp', false, function(response) { * // when the HTTP request completes, populate the variable that holds the * // earthquake data used in the visualization. * earthquakes = response; * }); * } * * function draw() { * if (!earthquakes) { * // Wait until the earthquake data has loaded before drawing. * return; * } * background(200); * // Get the magnitude and name of the earthquake out of the loaded JSON * var earthquakeMag = earthquakes.features[0].properties.mag; * var earthquakeName = earthquakes.features[0].properties.place; * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10); * textAlign(CENTER); * text(earthquakeName, 0, height - 30, width, 30); * noLoop(); * } * </code></div> *//** * @method httpGet * @param {String} path * @param {Object|Boolean} data * @param {function} [callback] * @param {function} [errorCallback] * @return {Promise} *//** * @method httpGet * @param {String} path * @param {function} callback * @param {function} [errorCallback] * @return {Promise} */p5.prototype.httpGet=function(){p5._validateParameters('httpGet',arguments);var args=Array.prototype.slice.call(arguments);args.splice(1,0,'GET');return p5.prototype.httpDo.apply(this,args);};/** * Method for executing an HTTP POST request. If data type is not specified, * p5 will try to guess based on the URL, defaulting to text. This is equivalent to * calling <code>httpDo(path, 'POST')</code>. * * @method httpPost * @param {String} path name of the file or url to load * @param {String} [datatype] "json", "jsonp", "xml", or "text". * If omitted, <a href="#/p5/httpPost">httpPost()</a> will guess. * @param {Object|Boolean} [data] param data passed sent with request * @param {function} [callback] function to be executed after * <a href="#/p5/httpPost">httpPost()</a> completes, data is passed in * as first argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @return {Promise} A promise that resolves with the data when the operation * completes successfully or rejects with the error after * one occurs. * * @example * <div> * <code> * // Examples use jsonplaceholder.typicode.com for a Mock Data API * * var url = 'https://jsonplaceholder.typicode.com/posts'; * var postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' }; * * function setup() { * createCanvas(800, 800); * } * * function mousePressed() { * // Pick new random color values * var r = random(255); * var g = random(255); * var b = random(255); * * httpPost(url, 'json', postData, function(result) { * strokeWeight(2); * stroke(r, g, b); * fill(r, g, b, 127); * ellipse(mouseX, mouseY, 200, 200); * text(result.body, mouseX, mouseY); * }); * } * </code> * </div> * * * <div><code> * var url = 'https://invalidURL'; // A bad URL that will cause errors * var postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' }; * * function setup() { * createCanvas(800, 800); * } * * function mousePressed() { * // Pick new random color values * var r = random(255); * var g = random(255); * var b = random(255); * * httpPost( * url, * 'json', * postData, * function(result) { * // ... won't be called * }, * function(error) { * strokeWeight(2); * stroke(r, g, b); * fill(r, g, b, 127); * text(error.toString(), mouseX, mouseY); * } * ); * } * </code></div> * *//** * @method httpPost * @param {String} path * @param {Object|Boolean} data * @param {function} [callback] * @param {function} [errorCallback] * @return {Promise} *//** * @method httpPost * @param {String} path * @param {function} callback * @param {function} [errorCallback] * @return {Promise} */p5.prototype.httpPost=function(){p5._validateParameters('httpPost',arguments);var args=Array.prototype.slice.call(arguments);args.splice(1,0,'POST');return p5.prototype.httpDo.apply(this,args);};/** * Method for executing an HTTP request. If data type is not specified, * p5 will try to guess based on the URL, defaulting to text.<br><br> * For more advanced use, you may also pass in the path as the first argument * and a object as the second argument, the signature follows the one specified * in the Fetch API specification. * This method is suitable for fetching files up to size of 64MB when "GET" is used. * * @method httpDo * @param {String} path name of the file or url to load * @param {String} [method] either "GET", "POST", or "PUT", * defaults to "GET" * @param {String} [datatype] "json", "jsonp", "xml", or "text" * @param {Object} [data] param data passed sent with request * @param {function} [callback] function to be executed after * <a href="#/p5/httpGet">httpGet()</a> completes, data is passed in * as first argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @return {Promise} A promise that resolves with the data when the operation * completes successfully or rejects with the error after * one occurs. * * @example * <div> * <code> * // Examples use USGS Earthquake API: * // https://earthquake.usgs.gov/fdsnws/event/1/#methods * * // displays an animation of all USGS earthquakes * var earthquakes; * var eqFeatureIndex = 0; * * function preload() { * var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson'; * httpDo( * url, * { * method: 'GET', * // Other Request options, like special headers for apis * headers: { authorization: 'Bearer secretKey' } * }, * function(res) { * earthquakes = res; * } * ); * } * * function draw() { * // wait until the data is loaded * if (!earthquakes || !earthquakes.features[eqFeatureIndex]) { * return; * } * clear(); * * var feature = earthquakes.features[eqFeatureIndex]; * var mag = feature.properties.mag; * var rad = mag / 11 * ((width + height) / 2); * fill(255, 0, 0, 100); * ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad); * * if (eqFeatureIndex >= earthquakes.features.length) { * eqFeatureIndex = 0; * } else { * eqFeatureIndex += 1; * } * } * </code> * </div> *//** * @method httpDo * @param {String} path * @param {Object} options Request object options as documented in the * "fetch" API * <a href="https://developer.mozilla.org/en/docs/Web/API/Fetch_API">reference</a> * @param {function} [callback] * @param {function} [errorCallback] * @return {Promise} */p5.prototype.httpDo=function(){var type;var callback;var errorCallback;var request;var promise;var jsonpOptions={};var cbCount=0;var contentType='text/plain';// Trim the callbacks off the end to get an idea of how many arguments are passed for(var i=arguments.length-1;i>0;i--){if(typeof arguments[i]==='function'){cbCount++;}else{break;}}// The number of arguments minus callbacks var argsCount=arguments.length-cbCount;var path=arguments[0];if(argsCount===2&&typeof path==='string'&&_typeof(arguments[1])==='object'){// Intended for more advanced use, pass in Request parameters directly request=new Request(path,arguments[1]);callback=arguments[2];errorCallback=arguments[3];}else{// Provided with arguments var method='GET';var data;for(var j=1;j<arguments.length;j++){var a=arguments[j];if(typeof a==='string'){if(a==='GET'||a==='POST'||a==='PUT'||a==='DELETE'){method=a;}else if(a==='json'||a==='jsonp'||a==='binary'||a==='arrayBuffer'||a==='xml'||a==='text'||a==='table'){type=a;}else{data=a;}}else if(typeof a==='number'){data=a.toString();}else if((typeof a==="undefined"?"undefined":_typeof(a))==='object'){if(a.hasOwnProperty('jsonpCallback')){for(var attr in a){jsonpOptions[attr]=a[attr];}}else{data=JSON.stringify(a);contentType='application/json';}}else if(typeof a==='function'){if(!callback){callback=a;}else{errorCallback=a;}}}request=new Request(path,{method:method,mode:'cors',body:data,headers:new Headers({'Content-Type':contentType})});}// do some sort of smart type checking if(!type){if(path.indexOf('json')!==-1){type='json';}else if(path.indexOf('xml')!==-1){type='xml';}else{type='text';}}if(type==='jsonp'){promise=fetchJsonp(path,jsonpOptions);}else{promise=fetch(request);}promise=promise.then(function(res){if(!res.ok){var err=new Error(res.body);err.status=res.status;err.ok=false;throw err;}else{var fileSize=res.headers.get('content-length');if(fileSize&&fileSize>64000000){p5._friendlyFileLoadError(7,path);}switch(type){case'json':case'jsonp':return res.json();case'binary':return res.blob();case'arrayBuffer':return res.arrayBuffer();case'xml':return res.text().then(function(text){var parser=new DOMParser();var xml=parser.parseFromString(text,'text/xml');return parseXML(xml.documentElement);});default:return res.text();}}});promise.then(callback||function(){});promise.catch(errorCallback||console.error);return promise;};/** * @module IO * @submodule Output * @for p5 */window.URL=window.URL||window.webkitURL;// private array of p5.PrintWriter objects p5.prototype._pWriters=[];/** * @method createWriter * @param {String} name name of the file to be created * @param {String} [extension] * @return {p5.PrintWriter} * @example * <div> * <code> * createButton('save') * .position(10, 10) * .mousePressed(function() { * var writer = createWriter('squares.txt'); * for (var i = 0; i < 10; i++) { * writer.print(i * i); * } * writer.close(); * writer.clear(); * }); * </code> * </div> */p5.prototype.createWriter=function(name,extension){var newPW;// check that it doesn't already exist for(var i in p5.prototype._pWriters){if(p5.prototype._pWriters[i].name===name){// if a p5.PrintWriter w/ this name already exists... // return p5.prototype._pWriters[i]; // return it w/ contents intact. // or, could return a new, empty one with a unique name: newPW=new p5.PrintWriter(name+this.millis(),extension);p5.prototype._pWriters.push(newPW);return newPW;}}newPW=new p5.PrintWriter(name,extension);p5.prototype._pWriters.push(newPW);return newPW;};/** * @class p5.PrintWriter * @param {String} filename * @param {String} [extension] */p5.PrintWriter=function(filename,extension){var self=this;this.name=filename;this.content='';//Changed to write because it was being overloaded by function below. /** * Writes data to the PrintWriter stream * @method write * @param {Array} data all data to be written by the PrintWriter * @example * <div class="norender notest"> * <code> * // creates a file called 'newFile.txt' * var writer = createWriter('newFile.txt'); * // write 'Hello world!'' to the file * writer.write(['Hello world!']); * // close the PrintWriter and save the file * writer.close(); * </code> * </div> * <div class='norender notest'> * <code> * // creates a file called 'newFile2.txt' * var writer = createWriter('newFile2.txt'); * // write 'apples,bananas,123' to the file * writer.write(['apples', 'bananas', 123]); * // close the PrintWriter and save the file * writer.close(); * </code> * </div> * <div class='norender notest'> * <code> * // creates a file called 'newFile3.txt' * var writer = createWriter('newFile3.txt'); * // write 'My name is: Teddy' to the file * writer.write('My name is:'); * writer.write(' Teddy'); * // close the PrintWriter and save the file * writer.close(); * </code> * </div> */this.write=function(data){this.content+=data;};/** * Writes data to the PrintWriter stream, and adds a new line at the end * @method print * @param {Array} data all data to be printed by the PrintWriter * @example * <div class='norender notest'> * <code> * // creates a file called 'newFile.txt' * var writer = createWriter('newFile.txt'); * // creates a file containing * // My name is: * // Teddy * writer.print('My name is:'); * writer.print('Teddy'); * // close the PrintWriter and save the file * writer.close(); * </code> * </div> * <div class='norender notest'> * <code> * var writer; * * function setup() { * createCanvas(400, 400); * // create a PrintWriter * writer = createWriter('newFile.txt'); * } * * function draw() { * // print all mouseX and mouseY coordinates to the stream * writer.print([mouseX, mouseY]); * } * * function mouseClicked() { * // close the PrintWriter and save the file * writer.close(); * } * </code> * </div> */this.print=function(data){this.content+=data+'\n';};/** * Clears the data already written to the PrintWriter object * @method clear * @example * <div class ="norender notest"><code> * // create writer object * var writer = createWriter('newFile.txt'); * writer.write(['clear me']); * // clear writer object here * writer.clear(); * // close writer * writer.close(); * </code></div> * */this.clear=function(){this.content='';};/** * Closes the PrintWriter * @method close * @example * <div class="norender notest"> * <code> * // create a file called 'newFile.txt' * var writer = createWriter('newFile.txt'); * // close the PrintWriter and save the file * writer.close(); * </code> * </div> * <div class='norender notest'> * <code> * // create a file called 'newFile2.txt' * var writer = createWriter('newFile2.txt'); * // write some data to the file * writer.write([100, 101, 102]); * // close the PrintWriter and save the file * writer.close(); * </code> * </div> */this.close=function(){// convert String to Array for the writeFile Blob var arr=[];arr.push(this.content);p5.prototype.writeFile(arr,filename,extension);// remove from _pWriters array and delete self for(var i in p5.prototype._pWriters){if(p5.prototype._pWriters[i].name===this.name){// remove from _pWriters array p5.prototype._pWriters.splice(i,1);}}self.clear();self={};};};/** * @module IO * @submodule Output * @for p5 */// object, filename, options --> saveJSON, saveStrings, // filename, [extension] [canvas] --> saveImage /** * <p>Save an image, text, json, csv, wav, or html. Prompts download to * the client's computer. <b>Note that it is not recommended to call <a href="#/p5/save">save()</a> * within draw if it's looping, as the <a href="#/p5/save">save()</a> function will open a new save * dialog every frame.</b></p> * <p>The default behavior is to save the canvas as an image. You can * optionally specify a filename. * For example:</p> * <pre class='language-javascript'><code> * save(); * save('myCanvas.jpg'); // save a specific canvas with a filename * </code></pre> * * <p>Alternately, the first parameter can be a pointer to a canvas * <a href="#/p5.Element">p5.Element</a>, an Array of Strings, * an Array of JSON, a JSON object, a <a href="#/p5.Table">p5.Table</a>, a <a href="#/p5.Image">p5.Image</a>, or a * p5.SoundFile (requires p5.sound). The second parameter is a filename * (including extension). The third parameter is for options specific * to this type of object. This method will save a file that fits the * given paramaters. For example:</p> * * <pre class='language-javascript'><code> * // Saves canvas as an image * save('myCanvas.jpg'); * * // Saves pImage as a png image * var img = createImage(10, 10); * save(img, 'my.png'); * * // Saves canvas as an image * var cnv = createCanvas(100, 100); * save(cnv, 'myCanvas.jpg'); * * // Saves p5.Renderer object as an image * var gb = createGraphics(100, 100); * save(gb, 'myGraphics.jpg'); * * var myTable = new p5.Table(); * * // Saves table as html file * save(myTable, 'myTable.html'); * * // Comma Separated Values * save(myTable, 'myTable.csv'); * * // Tab Separated Values * save(myTable, 'myTable.tsv'); * * var myJSON = { a: 1, b: true }; * * // Saves pretty JSON * save(myJSON, 'my.json'); * * // Optimizes JSON filesize * save(myJSON, 'my.json', true); * * // Saves array of strings to a text file with line breaks after each item * var arrayOfStrings = ['a', 'b']; * save(arrayOfStrings, 'my.txt'); * </code></pre> * * @method save * @param {Object|String} [objectOrFilename] If filename is provided, will * save canvas as an image with * either png or jpg extension * depending on the filename. * If object is provided, will * save depending on the object * and filename (see examples * above). * @param {String} [filename] If an object is provided as the first * parameter, then the second parameter * indicates the filename, * and should include an appropriate * file extension (see examples above). * @param {Boolean|String} [options] Additional options depend on * filetype. For example, when saving JSON, * <code>true</code> indicates that the * output will be optimized for filesize, * rather than readability. */p5.prototype.save=function(object,_filename,_options){// parse the arguments and figure out which things we are saving var args=arguments;// ================================================= // OPTION 1: saveCanvas... // if no arguments are provided, save canvas var cnv=this._curElement.elt;if(args.length===0){p5.prototype.saveCanvas(cnv);return;}else if(args[0]instanceof p5.Renderer||args[0]instanceof p5.Graphics){// otherwise, parse the arguments // if first param is a p5Graphics, then saveCanvas p5.prototype.saveCanvas(args[0].elt,args[1],args[2]);return;}else if(args.length===1&&typeof args[0]==='string'){// if 1st param is String and only one arg, assume it is canvas filename p5.prototype.saveCanvas(cnv,args[0]);}else{// ================================================= // OPTION 2: extension clarifies saveStrings vs. saveJSON var extension=_checkFileExtension(args[1],args[2])[1];switch(extension){case'json':p5.prototype.saveJSON(args[0],args[1],args[2]);return;case'txt':p5.prototype.saveStrings(args[0],args[1],args[2]);return;// ================================================= // OPTION 3: decide based on object... default:if(args[0]instanceof Array){p5.prototype.saveStrings(args[0],args[1],args[2]);}else if(args[0]instanceof p5.Table){p5.prototype.saveTable(args[0],args[1],args[2]);}else if(args[0]instanceof p5.Image){p5.prototype.saveCanvas(args[0].canvas,args[1]);}else if(args[0]instanceof p5.SoundFile){p5.prototype.saveSound(args[0],args[1],args[2],args[3]);}}}};/** * Writes the contents of an Array or a JSON object to a .json file. * The file saving process and location of the saved file will * vary between web browsers. * * @method saveJSON * @param {Array|Object} json * @param {String} filename * @param {Boolean} [optimize] If true, removes line breaks * and spaces from the output * file to optimize filesize * (but not readability). * @example * <div><code> * var json = {}; // new JSON Object * * json.id = 0; * json.species = 'Panthera leo'; * json.name = 'Lion'; * * createButton('save') * .position(10, 10) * .mousePressed(function() { * saveJSON(json, 'lion.json'); * }); * * // saves the following to a file called "lion.json": * // { * // "id": 0, * // "species": "Panthera leo", * // "name": "Lion" * // } * </code></div> * * @alt * no image displayed * */p5.prototype.saveJSON=function(json,filename,opt){p5._validateParameters('saveJSON',arguments);var stringify;if(opt){stringify=JSON.stringify(json);}else{stringify=JSON.stringify(json,undefined,2);}this.saveStrings(stringify.split('\n'),filename,'json');};p5.prototype.saveJSONObject=p5.prototype.saveJSON;p5.prototype.saveJSONArray=p5.prototype.saveJSON;/** * Writes an array of Strings to a text file, one line per String. * The file saving process and location of the saved file will * vary between web browsers. * * @method saveStrings * @param {String[]} list string array to be written * @param {String} filename filename for output * @param {String} [extension] the filename's extension * @example * <div><code> * var words = 'apple bear cat dog'; * * // .split() outputs an Array * var list = split(words, ' '); * * createButton('save') * .position(10, 10) * .mousePressed(function() { * saveStrings(list, 'nouns.txt'); * }); * * // Saves the following to a file called 'nouns.txt': * // * // apple * // bear * // cat * // dog * </code></div> * * @alt * no image displayed * */p5.prototype.saveStrings=function(list,filename,extension){p5._validateParameters('saveStrings',arguments);var ext=extension||'txt';var pWriter=this.createWriter(filename,ext);for(var i=0;i<list.length;i++){if(i<list.length-1){pWriter.print(list[i]);}else{pWriter.print(list[i]);}}pWriter.close();pWriter.clear();};// ======= // HELPERS // ======= function escapeHelper(content){return content.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#039;');}/** * Writes the contents of a <a href="#/p5.Table">Table</a> object to a file. Defaults to a * text file with comma-separated-values ('csv') but can also * use tab separation ('tsv'), or generate an HTML table ('html'). * The file saving process and location of the saved file will * vary between web browsers. * * @method saveTable * @param {p5.Table} Table the <a href="#/p5.Table">Table</a> object to save to a file * @param {String} filename the filename to which the Table should be saved * @param {String} [options] can be one of "tsv", "csv", or "html" * @example * <div><code> * var table; * * function setup() { * table = new p5.Table(); * * table.addColumn('id'); * table.addColumn('species'); * table.addColumn('name'); * * var newRow = table.addRow(); * newRow.setNum('id', table.getRowCount() - 1); * newRow.setString('species', 'Panthera leo'); * newRow.setString('name', 'Lion'); * * // To save, un-comment next line then click 'run' * // saveTable(table, 'new.csv'); * } * * // Saves the following to a file called 'new.csv': * // id,species,name * // 0,Panthera leo,Lion * </code></div> * * @alt * no image displayed * */p5.prototype.saveTable=function(table,filename,options){p5._validateParameters('saveTable',arguments);var ext;if(options===undefined){ext=filename.substring(filename.lastIndexOf('.')+1,filename.length);}else{ext=options;}var pWriter=this.createWriter(filename,ext);var header=table.columns;var sep=',';// default to CSV if(ext==='tsv'){sep='\t';}if(ext!=='html'){// make header if it has values if(header[0]!=='0'){for(var h=0;h<header.length;h++){if(h<header.length-1){pWriter.write(header[h]+sep);}else{pWriter.write(header[h]);}}pWriter.write('\n');}// make rows for(var i=0;i<table.rows.length;i++){var j;for(j=0;j<table.rows[i].arr.length;j++){if(j<table.rows[i].arr.length-1){pWriter.write(table.rows[i].arr[j]+sep);}else if(i<table.rows.length-1){pWriter.write(table.rows[i].arr[j]);}else{pWriter.write(table.rows[i].arr[j]);}}pWriter.write('\n');}}else{// otherwise, make HTML pWriter.print('<html>');pWriter.print('<head>');var str=' <meta http-equiv="content-type" content';str+='="text/html;charset=utf-8" />';pWriter.print(str);pWriter.print('</head>');pWriter.print('<body>');pWriter.print(' <table>');// make header if it has values if(header[0]!=='0'){pWriter.print(' <tr>');for(var k=0;k<header.length;k++){var e=escapeHelper(header[k]);pWriter.print(' <td>'+e);pWriter.print(' </td>');}pWriter.print(' </tr>');}// make rows for(var row=0;row<table.rows.length;row++){pWriter.print(' <tr>');for(var col=0;col<table.columns.length;col++){var entry=table.rows[row].getString(col);var htmlEntry=escapeHelper(entry);pWriter.print(' <td>'+htmlEntry);pWriter.print(' </td>');}pWriter.print(' </tr>');}pWriter.print(' </table>');pWriter.print('</body>');pWriter.print('</html>');}// close and clear the pWriter pWriter.close();pWriter.clear();};// end saveTable() /** * Generate a blob of file data as a url to prepare for download. * Accepts an array of data, a filename, and an extension (optional). * This is a private function because it does not do any formatting, * but it is used by <a href="#/p5/saveStrings">saveStrings</a>, <a href="#/p5/saveJSON">saveJSON</a>, <a href="#/p5/saveTable">saveTable</a> etc. * * @param {Array} dataToDownload * @param {String} filename * @param {String} [extension] * @private */p5.prototype.writeFile=function(dataToDownload,filename,extension){var type='application/octet-stream';if(p5.prototype._isSafari()){type='text/plain';}var blob=new Blob(dataToDownload,{type:type});p5.prototype.downloadFile(blob,filename,extension);};/** * Forces download. Accepts a url to filedata/blob, a filename, * and an extension (optional). * This is a private function because it does not do any formatting, * but it is used by <a href="#/p5/saveStrings">saveStrings</a>, <a href="#/p5/saveJSON">saveJSON</a>, <a href="#/p5/saveTable">saveTable</a> etc. * * @method downloadFile * @private * @param {String|Blob} data either an href generated by createObjectURL, * or a Blob object containing the data * @param {String} [filename] * @param {String} [extension] */p5.prototype.downloadFile=function(data,fName,extension){var fx=_checkFileExtension(fName,extension);var filename=fx[0];if(data instanceof Blob){var fileSaver=_dereq_('file-saver');fileSaver.saveAs(data,filename);return;}var a=document.createElement('a');a.href=data;a.download=filename;// Firefox requires the link to be added to the DOM before click() a.onclick=function(e){destroyClickedElement(e);e.stopPropagation();};a.style.display='none';document.body.appendChild(a);// Safari will open this file in the same page as a confusing Blob. if(p5.prototype._isSafari()){var aText='Hello, Safari user! To download this file...\n';aText+='1. Go to File --> Save As.\n';aText+='2. Choose "Page Source" as the Format.\n';aText+='3. Name it with this extension: ."'+fx[1]+'"';alert(aText);}a.click();};/** * Returns a file extension, or another string * if the provided parameter has no extension. * * @param {String} filename * @param {String} [extension] * @return {String[]} [fileName, fileExtension] * * @private */function _checkFileExtension(filename,extension){if(!extension||extension===true||extension==='true'){extension='';}if(!filename){filename='untitled';}var ext='';// make sure the file will have a name, see if filename needs extension if(filename&&filename.indexOf('.')>-1){ext=filename.split('.').pop();}// append extension if it doesn't exist if(extension){if(ext!==extension){ext=extension;filename=filename+'.'+ext;}}return[filename,ext];}p5.prototype._checkFileExtension=_checkFileExtension;/** * Returns true if the browser is Safari, false if not. * Safari makes trouble for downloading files. * * @return {Boolean} [description] * @private */p5.prototype._isSafari=function(){var x=Object.prototype.toString.call(window.HTMLElement);return x.indexOf('Constructor')>0;};/** * Helper function, a callback for download that deletes * an invisible anchor element from the DOM once the file * has been automatically downloaded. * * @private */function destroyClickedElement(event){document.body.removeChild(event.target);}module.exports=p5;},{"../core/error_helpers":21,"../core/main":25,"es6-promise":5,"fetch-jsonp":6,"file-saver":7,"whatwg-fetch":13}],49:[function(_dereq_,module,exports){/** * @module IO * @submodule Table * @requires core */'use strict';var p5=_dereq_('../core/main');/** * Table Options * <p>Generic class for handling tabular data, typically from a * CSV, TSV, or other sort of spreadsheet file.</p> * <p>CSV files are * <a href="http://en.wikipedia.org/wiki/Comma-separated_values"> * comma separated values</a>, often with the data in quotes. TSV * files use tabs as separators, and usually don't bother with the * quotes.</p> * <p>File names should end with .csv if they're comma separated.</p> * <p>A rough "spec" for CSV can be found * <a href="http://tools.ietf.org/html/rfc4180">here</a>.</p> * <p>To load files, use the <a href="#/p5/loadTable">loadTable</a> method.</p> * <p>To save tables to your computer, use the <a href="#/p5/save">save</a> method * or the <a href="#/p5/saveTable">saveTable</a> method.</p> * * Possible options include: * <ul> * <li>csv - parse the table as comma-separated values * <li>tsv - parse the table as tab-separated values * <li>header - this table has a header (title) row * </ul> *//** * <a href="#/p5.Table">Table</a> objects store data with multiple rows and columns, much * like in a traditional spreadsheet. Tables can be generated from * scratch, dynamically, or using data from an existing file. * * @class p5.Table * @constructor * @param {p5.TableRow[]} [rows] An array of p5.TableRow objects */p5.Table=function(rows){/** * @property columns {String[]} */this.columns=[];/** * @property rows {p5.TableRow[]} */this.rows=[];};/** * Use <a href="#/p5/addRow">addRow()</a> to add a new row of data to a <a href="#/p5.Table">p5.Table</a> object. By default, * an empty row is created. Typically, you would store a reference to * the new row in a TableRow object (see newRow in the example above), * and then set individual values using <a href="#/p5/set">set()</a>. * * If a <a href="#/p5.TableRow">p5.TableRow</a> object is included as a parameter, then that row is * duplicated and added to the table. * * @method addRow * @param {p5.TableRow} [row] row to be added to the table * @return {p5.TableRow} the row that was added * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //add a row * var newRow = table.addRow(); * newRow.setString('id', table.getRowCount() - 1); * newRow.setString('species', 'Canis Lupus'); * newRow.setString('name', 'Wolf'); * * //print the results * for (var r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * </code> * </div> * * @alt * no image displayed * */p5.Table.prototype.addRow=function(row){// make sure it is a valid TableRow var r=row||new p5.TableRow();if(typeof r.arr==='undefined'||typeof r.obj==='undefined'){//r = new p5.prototype.TableRow(r); throw new Error('invalid TableRow: '+r);}r.table=this;this.rows.push(r);return r;};/** * Removes a row from the table object. * * @method removeRow * @param {Integer} id ID number of the row to remove * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //remove the first row * table.removeRow(0); * * //print the results * for (var r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * </code> * </div> * * @alt * no image displayed * */p5.Table.prototype.removeRow=function(id){this.rows[id].table=null;// remove reference to table var chunk=this.rows.splice(id+1,this.rows.length);this.rows.pop();this.rows=this.rows.concat(chunk);};/** * Returns a reference to the specified <a href="#/p5.TableRow">p5.TableRow</a>. The reference * can then be used to get and set values of the selected row. * * @method getRow * @param {Integer} rowID ID number of the row to get * @return {p5.TableRow} <a href="#/p5.TableRow">p5.TableRow</a> object * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var row = table.getRow(1); * //print it column by column * //note: a row is an object, not an array * for (var c = 0; c < table.getColumnCount(); c++) { * print(row.getString(c)); * } * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.getRow=function(r){return this.rows[r];};/** * Gets all rows from the table. Returns an array of <a href="#/p5.TableRow">p5.TableRow</a>s. * * @method getRows * @return {p5.TableRow[]} Array of <a href="#/p5.TableRow">p5.TableRow</a>s * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * * //warning: rows is an array of objects * for (var r = 0; r < rows.length; r++) { * rows[r].set('name', 'Unicorn'); * } * * //print the results * for (r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * </code> * </div> * * @alt * no image displayed * */p5.Table.prototype.getRows=function(){return this.rows;};/** * Finds the first row in the Table that contains the value * provided, and returns a reference to that row. Even if * multiple rows are possible matches, only the first matching * row is returned. The column to search may be specified by * either its ID or title. * * @method findRow * @param {String} value The value to match * @param {Integer|String} column ID number or title of the * column to search * @return {p5.TableRow} * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //find the animal named zebra * var row = table.findRow('Zebra', 'name'); * //find the corresponding species * print(row.getString('species')); * } * </code> * </div> * * @alt * no image displayed * */p5.Table.prototype.findRow=function(value,column){// try the Object if(typeof column==='string'){for(var i=0;i<this.rows.length;i++){if(this.rows[i].obj[column]===value){return this.rows[i];}}}else{// try the Array for(var j=0;j<this.rows.length;j++){if(this.rows[j].arr[column]===value){return this.rows[j];}}}// otherwise... return null;};/** * Finds the rows in the Table that contain the value * provided, and returns references to those rows. Returns an * Array, so for must be used to iterate through all the rows, * as shown in the example above. The column to search may be * specified by either its ID or title. * * @method findRows * @param {String} value The value to match * @param {Integer|String} column ID number or title of the * column to search * @return {p5.TableRow[]} An Array of TableRow objects * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //add another goat * var newRow = table.addRow(); * newRow.setString('id', table.getRowCount() - 1); * newRow.setString('species', 'Scape Goat'); * newRow.setString('name', 'Goat'); * * //find the rows containing animals named Goat * var rows = table.findRows('Goat', 'name'); * print(rows.length + ' Goats found'); * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.findRows=function(value,column){var ret=[];if(typeof column==='string'){for(var i=0;i<this.rows.length;i++){if(this.rows[i].obj[column]===value){ret.push(this.rows[i]);}}}else{// try the Array for(var j=0;j<this.rows.length;j++){if(this.rows[j].arr[column]===value){ret.push(this.rows[j]);}}}return ret;};/** * Finds the first row in the Table that matches the regular * expression provided, and returns a reference to that row. * Even if multiple rows are possible matches, only the first * matching row is returned. The column to search may be * specified by either its ID or title. * * @method matchRow * @param {String|RegExp} regexp The regular expression to match * @param {String|Integer} column The column ID (number) or * title (string) * @return {p5.TableRow} TableRow object * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //Search using specified regex on a given column, return TableRow object * var mammal = table.matchRow(new RegExp('ant'), 1); * print(mammal.getString(1)); * //Output "Panthera pardus" * } * </code> * </div> * */p5.Table.prototype.matchRow=function(regexp,column){if(typeof column==='number'){for(var j=0;j<this.rows.length;j++){if(this.rows[j].arr[column].match(regexp)){return this.rows[j];}}}else{for(var i=0;i<this.rows.length;i++){if(this.rows[i].obj[column].match(regexp)){return this.rows[i];}}}return null;};/** * Finds the rows in the Table that match the regular expression provided, * and returns references to those rows. Returns an array, so for must be * used to iterate through all the rows, as shown in the example. The * column to search may be specified by either its ID or title. * * @method matchRows * @param {String} regexp The regular expression to match * @param {String|Integer} [column] The column ID (number) or * title (string) * @return {p5.TableRow[]} An Array of TableRow objects * @example * <div class="norender"> * <code> * var table; * * function setup() { * table = new p5.Table(); * * table.addColumn('name'); * table.addColumn('type'); * * var newRow = table.addRow(); * newRow.setString('name', 'Lion'); * newRow.setString('type', 'Mammal'); * * newRow = table.addRow(); * newRow.setString('name', 'Snake'); * newRow.setString('type', 'Reptile'); * * newRow = table.addRow(); * newRow.setString('name', 'Mosquito'); * newRow.setString('type', 'Insect'); * * newRow = table.addRow(); * newRow.setString('name', 'Lizard'); * newRow.setString('type', 'Reptile'); * * var rows = table.matchRows('R.*', 'type'); * for (var i = 0; i < rows.length; i++) { * print(rows[i].getString('name') + ': ' + rows[i].getString('type')); * } * } * // Sketch prints: * // Snake: Reptile * // Lizard: Reptile * </code> * </div> */p5.Table.prototype.matchRows=function(regexp,column){var ret=[];if(typeof column==='number'){for(var j=0;j<this.rows.length;j++){if(this.rows[j].arr[column].match(regexp)){ret.push(this.rows[j]);}}}else{for(var i=0;i<this.rows.length;i++){if(this.rows[i].obj[column].match(regexp)){ret.push(this.rows[i]);}}}return ret;};/** * Retrieves all values in the specified column, and returns them * as an array. The column may be specified by either its ID or title. * * @method getColumn * @param {String|Number} column String or Number of the column to return * @return {Array} Array of column values * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //getColumn returns an array that can be printed directly * print(table.getColumn('species')); * //outputs ["Capra hircus", "Panthera pardus", "Equus zebra"] * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.getColumn=function(value){var ret=[];if(typeof value==='string'){for(var i=0;i<this.rows.length;i++){ret.push(this.rows[i].obj[value]);}}else{for(var j=0;j<this.rows.length;j++){ret.push(this.rows[j].arr[value]);}}return ret;};/** * Removes all rows from a Table. While all rows are removed, * columns and column titles are maintained. * * @method clearRows * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * table.clearRows(); * print(table.getRowCount() + ' total rows in table'); * print(table.getColumnCount() + ' total columns in table'); * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.clearRows=function(){delete this.rows;this.rows=[];};/** * Use <a href="#/p5/addColumn">addColumn()</a> to add a new column to a <a href="#/p5.Table">Table</a> object. * Typically, you will want to specify a title, so the column * may be easily referenced later by name. (If no title is * specified, the new column's title will be null.) * * @method addColumn * @param {String} [title] title of the given column * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * table.addColumn('carnivore'); * table.set(0, 'carnivore', 'no'); * table.set(1, 'carnivore', 'yes'); * table.set(2, 'carnivore', 'no'); * * //print the results * for (var r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.addColumn=function(title){var t=title||null;this.columns.push(t);};/** * Returns the total number of columns in a Table. * * @method getColumnCount * @return {Integer} Number of columns in this table * @example * <div> * <code> * // given the cvs file "blobs.csv" in /assets directory * // ID, Name, Flavor, Shape, Color * // Blob1, Blobby, Sweet, Blob, Pink * // Blob2, Saddy, Savory, Blob, Blue * * var table; * * function preload() { * table = loadTable('assets/blobs.csv'); * } * * function setup() { * createCanvas(200, 100); * textAlign(CENTER); * background(255); * } * * function draw() { * var numOfColumn = table.getColumnCount(); * text('There are ' + numOfColumn + ' columns in the table.', 100, 50); * } * </code> * </div> */p5.Table.prototype.getColumnCount=function(){return this.columns.length;};/** * Returns the total number of rows in a Table. * * @method getRowCount * @return {Integer} Number of rows in this table * @example * <div> * <code> * // given the cvs file "blobs.csv" in /assets directory * // * // ID, Name, Flavor, Shape, Color * // Blob1, Blobby, Sweet, Blob, Pink * // Blob2, Saddy, Savory, Blob, Blue * * var table; * * function preload() { * table = loadTable('assets/blobs.csv'); * } * * function setup() { * createCanvas(200, 100); * textAlign(CENTER); * background(255); * } * * function draw() { * text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50); * } * </code> * </div> */p5.Table.prototype.getRowCount=function(){return this.rows.length;};/** * <p>Removes any of the specified characters (or "tokens").</p> * * <p>If no column is specified, then the values in all columns and * rows are processed. A specific column may be referenced by * either its ID or title.</p> * * @method removeTokens * @param {String} chars String listing characters to be removed * @param {String|Integer} [column] Column ID (number) * or name (string) * * @example * <div class="norender"><code> * function setup() { * var table = new p5.Table(); * * table.addColumn('name'); * table.addColumn('type'); * * var newRow = table.addRow(); * newRow.setString('name', ' $Lion ,'); * newRow.setString('type', ',,,Mammal'); * * newRow = table.addRow(); * newRow.setString('name', '$Snake '); * newRow.setString('type', ',,,Reptile'); * * table.removeTokens(',$ '); * print(table.getArray()); * } * * // prints: * // 0 "Lion" "Mamal" * // 1 "Snake" "Reptile" * </code></div> */p5.Table.prototype.removeTokens=function(chars,column){var escape=function escape(s){return s.replace(/[-/\\^$*+?.()|[\]{}]/g,'\\$&');};var charArray=[];for(var i=0;i<chars.length;i++){charArray.push(escape(chars.charAt(i)));}var regex=new RegExp(charArray.join('|'),'g');if(typeof column==='undefined'){for(var c=0;c<this.columns.length;c++){for(var d=0;d<this.rows.length;d++){var s=this.rows[d].arr[c];s=s.replace(regex,'');this.rows[d].arr[c]=s;this.rows[d].obj[this.columns[c]]=s;}}}else if(typeof column==='string'){for(var j=0;j<this.rows.length;j++){var val=this.rows[j].obj[column];val=val.replace(regex,'');this.rows[j].obj[column]=val;var pos=this.columns.indexOf(column);this.rows[j].arr[pos]=val;}}else{for(var k=0;k<this.rows.length;k++){var str=this.rows[k].arr[column];str=str.replace(regex,'');this.rows[k].arr[column]=str;this.rows[k].obj[this.columns[column]]=str;}}};/** * Trims leading and trailing whitespace, such as spaces and tabs, * from String table values. If no column is specified, then the * values in all columns and rows are trimmed. A specific column * may be referenced by either its ID or title. * * @method trim * @param {String|Integer} [column] Column ID (number) * or name (string) * @example * <div class="norender"><code> * function setup() { * var table = new p5.Table(); * * table.addColumn('name'); * table.addColumn('type'); * * var newRow = table.addRow(); * newRow.setString('name', ' Lion ,'); * newRow.setString('type', ' Mammal '); * * newRow = table.addRow(); * newRow.setString('name', ' Snake '); * newRow.setString('type', ' Reptile '); * * table.trim(); * print(table.getArray()); * } * * // prints: * // 0 "Lion" "Mamal" * // 1 "Snake" "Reptile" * </code></div> */p5.Table.prototype.trim=function(column){var regex=new RegExp(' ','g');if(typeof column==='undefined'){for(var c=0;c<this.columns.length;c++){for(var d=0;d<this.rows.length;d++){var s=this.rows[d].arr[c];s=s.replace(regex,'');this.rows[d].arr[c]=s;this.rows[d].obj[this.columns[c]]=s;}}}else if(typeof column==='string'){for(var j=0;j<this.rows.length;j++){var val=this.rows[j].obj[column];val=val.replace(regex,'');this.rows[j].obj[column]=val;var pos=this.columns.indexOf(column);this.rows[j].arr[pos]=val;}}else{for(var k=0;k<this.rows.length;k++){var str=this.rows[k].arr[column];str=str.replace(regex,'');this.rows[k].arr[column]=str;this.rows[k].obj[this.columns[column]]=str;}}};/** * Use <a href="#/p5/removeColumn">removeColumn()</a> to remove an existing column from a Table * object. The column to be removed may be identified by either * its title (a String) or its index value (an int). * removeColumn(0) would remove the first column, removeColumn(1) * would remove the second column, and so on. * * @method removeColumn * @param {String|Integer} column columnName (string) or ID (number) * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * table.removeColumn('id'); * print(table.getColumnCount()); * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.removeColumn=function(c){var cString;var cNumber;if(typeof c==='string'){// find the position of c in the columns cString=c;cNumber=this.columns.indexOf(c);}else{cNumber=c;cString=this.columns[c];}var chunk=this.columns.splice(cNumber+1,this.columns.length);this.columns.pop();this.columns=this.columns.concat(chunk);for(var i=0;i<this.rows.length;i++){var tempR=this.rows[i].arr;var chip=tempR.splice(cNumber+1,tempR.length);tempR.pop();this.rows[i].arr=tempR.concat(chip);delete this.rows[i].obj[cString];}};/** * Stores a value in the Table's specified row and column. * The row is specified by its ID, while the column may be specified * by either its ID or title. * * @method set * @param {Integer} row row ID * @param {String|Integer} column column ID (Number) * or title (String) * @param {String|Number} value value to assign * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * table.set(0, 'species', 'Canis Lupus'); * table.set(0, 'name', 'Wolf'); * * //print the results * for (var r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.set=function(row,column,value){this.rows[row].set(column,value);};/** * Stores a Float value in the Table's specified row and column. * The row is specified by its ID, while the column may be specified * by either its ID or title. * * @method setNum * @param {Integer} row row ID * @param {String|Integer} column column ID (Number) * or title (String) * @param {Number} value value to assign * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * table.setNum(1, 'id', 1); * * print(table.getColumn(0)); * //["0", 1, "2"] * } * </code> * </div> * *@alt * no image displayed */p5.Table.prototype.setNum=function(row,column,value){this.rows[row].setNum(column,value);};/** * Stores a String value in the Table's specified row and column. * The row is specified by its ID, while the column may be specified * by either its ID or title. * * @method setString * @param {Integer} row row ID * @param {String|Integer} column column ID (Number) * or title (String) * @param {String} value value to assign * @example * <div class="norender"><code> * // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //add a row * var newRow = table.addRow(); * newRow.setString('id', table.getRowCount() - 1); * newRow.setString('species', 'Canis Lupus'); * newRow.setString('name', 'Wolf'); * * print(table.getArray()); * } * </code></div> * * @alt * no image displayed */p5.Table.prototype.setString=function(row,column,value){this.rows[row].setString(column,value);};/** * Retrieves a value from the Table's specified row and column. * The row is specified by its ID, while the column may be specified by * either its ID or title. * * @method get * @param {Integer} row row ID * @param {String|Integer} column columnName (string) or * ID (number) * @return {String|Number} * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * print(table.get(0, 1)); * //Capra hircus * print(table.get(0, 'species')); * //Capra hircus * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.get=function(row,column){return this.rows[row].get(column);};/** * Retrieves a Float value from the Table's specified row and column. * The row is specified by its ID, while the column may be specified by * either its ID or title. * * @method getNum * @param {Integer} row row ID * @param {String|Integer} column columnName (string) or * ID (number) * @return {Number} * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * print(table.getNum(1, 0) + 100); * //id 1 + 100 = 101 * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.getNum=function(row,column){return this.rows[row].getNum(column);};/** * Retrieves a String value from the Table's specified row and column. * The row is specified by its ID, while the column may be specified by * either its ID or title. * * @method getString * @param {Integer} row row ID * @param {String|Integer} column columnName (string) or * ID (number) * @return {String} * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * // table is comma separated value "CSV" * // and has specifiying header for column labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * print(table.getString(0, 0)); // 0 * print(table.getString(0, 1)); // Capra hircus * print(table.getString(0, 2)); // Goat * print(table.getString(1, 0)); // 1 * print(table.getString(1, 1)); // Panthera pardus * print(table.getString(1, 2)); // Leopard * print(table.getString(2, 0)); // 2 * print(table.getString(2, 1)); // Equus zebra * print(table.getString(2, 2)); // Zebra * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.getString=function(row,column){return this.rows[row].getString(column);};/** * Retrieves all table data and returns as an object. If a column name is * passed in, each row object will be stored with that attribute as its * title. * * @method getObject * @param {String} [headerColumn] Name of the column which should be used to * title each row object (optional) * @return {Object} * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var tableObject = table.getObject(); * * print(tableObject); * //outputs an object * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.getObject=function(headerColumn){var tableObject={};var obj,cPos,index;for(var i=0;i<this.rows.length;i++){obj=this.rows[i].obj;if(typeof headerColumn==='string'){cPos=this.columns.indexOf(headerColumn);// index of columnID if(cPos>=0){index=obj[headerColumn];tableObject[index]=obj;}else{throw new Error('This table has no column named "'+headerColumn+'"');}}else{tableObject[i]=this.rows[i].obj;}}return tableObject;};/** * Retrieves all table data and returns it as a multidimensional array. * * @method getArray * @return {Array} * * @example * <div class="norender"> * <code> * // Given the CSV file "mammals.csv" * // in the project's "assets" folder * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leoperd * // 2,Equus zebra,Zebra * * var table; * * function preload() { * // table is comma separated value "CSV" * // and has specifiying header for column labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var tableArray = table.getArray(); * for (var i = 0; i < tableArray.length; i++) { * print(tableArray[i]); * } * } * </code> * </div> * *@alt * no image displayed * */p5.Table.prototype.getArray=function(){var tableArray=[];for(var i=0;i<this.rows.length;i++){tableArray.push(this.rows[i].arr);}return tableArray;};module.exports=p5;},{"../core/main":25}],50:[function(_dereq_,module,exports){/** * @module IO * @submodule Table * @requires core */'use strict';var p5=_dereq_('../core/main');/** * A TableRow object represents a single row of data values, * stored in columns, from a table. * * A Table Row contains both an ordered array, and an unordered * JSON object. * * @class p5.TableRow * @constructor * @param {String} [str] optional: populate the row with a * string of values, separated by the * separator * @param {String} [separator] comma separated values (csv) by default */p5.TableRow=function(str,separator){var arr=[];var obj={};if(str){separator=separator||',';arr=str.split(separator);}for(var i=0;i<arr.length;i++){var key=i;var val=arr[i];obj[key]=val;}this.arr=arr;this.obj=obj;this.table=null;};/** * Stores a value in the TableRow's specified column. * The column may be specified by either its ID or title. * * @method set * @param {String|Integer} column Column ID (Number) * or Title (String) * @param {String|Number} value The value to be stored * * @example * <div class="norender"><code> * // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * for (var r = 0; r < rows.length; r++) { * rows[r].set('name', 'Unicorn'); * } * * //print the results * print(table.getArray()); * } * </code></div> * * @alt * no image displayed */p5.TableRow.prototype.set=function(column,value){// if typeof column is string, use .obj if(typeof column==='string'){var cPos=this.table.columns.indexOf(column);// index of columnID if(cPos>=0){this.obj[column]=value;this.arr[cPos]=value;}else{throw new Error('This table has no column named "'+column+'"');}}else{// if typeof column is number, use .arr if(column<this.table.columns.length){this.arr[column]=value;var cTitle=this.table.columns[column];this.obj[cTitle]=value;}else{throw new Error('Column #'+column+' is out of the range of this table');}}};/** * Stores a Float value in the TableRow's specified column. * The column may be specified by either its ID or title. * * @method setNum * @param {String|Integer} column Column ID (Number) * or Title (String) * @param {Number|String} value The value to be stored * as a Float * @example * <div class="norender"><code> * // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * for (var r = 0; r < rows.length; r++) { * rows[r].setNum('id', r + 10); * } * * print(table.getArray()); * } * </code></div> * * @alt * no image displayed */p5.TableRow.prototype.setNum=function(column,value){var floatVal=parseFloat(value);this.set(column,floatVal);};/** * Stores a String value in the TableRow's specified column. * The column may be specified by either its ID or title. * * @method setString * @param {String|Integer} column Column ID (Number) * or Title (String) * @param {String|Number|Boolean|Object} value The value to be stored * as a String * @example * <div class="norender"><code> * // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * for (var r = 0; r < rows.length; r++) { * var name = rows[r].getString('name'); * rows[r].setString('name', 'A ' + name + ' named George'); * } * * print(table.getArray()); * } * </code></div> * * @alt * no image displayed */p5.TableRow.prototype.setString=function(column,value){var stringVal=value.toString();this.set(column,stringVal);};/** * Retrieves a value from the TableRow's specified column. * The column may be specified by either its ID or title. * * @method get * @param {String|Integer} column columnName (string) or * ID (number) * @return {String|Number} * * @example * <div class="norender"><code> * // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var names = []; * var rows = table.getRows(); * for (var r = 0; r < rows.length; r++) { * names.push(rows[r].get('name')); * } * * print(names); * } * </code></div> * * @alt * no image displayed */p5.TableRow.prototype.get=function(column){if(typeof column==='string'){return this.obj[column];}else{return this.arr[column];}};/** * Retrieves a Float value from the TableRow's specified * column. The column may be specified by either its ID or * title. * * @method getNum * @param {String|Integer} column columnName (string) or * ID (number) * @return {Number} Float Floating point number * @example * <div class="norender"><code> * // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * var minId = Infinity; * var maxId = -Infinity; * for (var r = 0; r < rows.length; r++) { * var id = rows[r].getNum('id'); * minId = min(minId, id); * maxId = min(maxId, id); * } * print('minimum id = ' + minId + ', maximum id = ' + maxId); * } * </code></div> * * @alt * no image displayed */p5.TableRow.prototype.getNum=function(column){var ret;if(typeof column==='string'){ret=parseFloat(this.obj[column]);}else{ret=parseFloat(this.arr[column]);}if(ret.toString()==='NaN'){throw'Error: '+this.obj[column]+' is NaN (Not a Number)';}return ret;};/** * Retrieves an String value from the TableRow's specified * column. The column may be specified by either its ID or * title. * * @method getString * @param {String|Integer} column columnName (string) or * ID (number) * @return {String} String * @example * <div class="norender"><code> * // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * var longest = ''; * for (var r = 0; r < rows.length; r++) { * var species = rows[r].getString('species'); * if (longest.length < species.length) { * longest = species; * } * } * * print('longest: ' + longest); * } * </code></div> * * @alt * no image displayed */p5.TableRow.prototype.getString=function(column){if(typeof column==='string'){return this.obj[column].toString();}else{return this.arr[column].toString();}};module.exports=p5;},{"../core/main":25}],51:[function(_dereq_,module,exports){/** * @module IO * @submodule XML * @requires core */'use strict';var p5=_dereq_('../core/main');/** * XML is a representation of an XML object, able to parse XML code. Use * <a href="#/p5/loadXML">loadXML()</a> to load external XML files and create XML objects. * * @class p5.XML * @constructor * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var children = xml.getChildren('animal'); * * for (var i = 0; i < children.length; i++) { * var id = children[i].getNum('id'); * var coloring = children[i].getString('species'); * var name = children[i].getContent(); * print(id + ', ' + coloring + ', ' + name); * } * } * * // Sketch prints: * // 0, Capra hircus, Goat * // 1, Panthera pardus, Leopard * // 2, Equus zebra, Zebra * </code></div> * * @alt * no image displayed * */p5.XML=function(){this.name=null;//done this.attributes={};//done this.children=[];this.parent=null;this.content=null;//done };/** * Gets a copy of the element's parent. Returns the parent as another * <a href="#/p5.XML">p5.XML</a> object. * * @method getParent * @return {p5.XML} element parent * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var children = xml.getChildren('animal'); * var parent = children[1].getParent(); * print(parent.getName()); * } * * // Sketch prints: * // mammals * </code></div> */p5.XML.prototype.getParent=function(){return this.parent;};/** * Gets the element's full name, which is returned as a String. * * @method getName * @return {String} the name of the node * @example&lt;animal * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * print(xml.getName()); * } * * // Sketch prints: * // mammals * </code></div> */p5.XML.prototype.getName=function(){return this.name;};/** * Sets the element's name, which is specified as a String. * * @method setName * @param {String} the new name of the node * @example&lt;animal * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * print(xml.getName()); * xml.setName('fish'); * print(xml.getName()); * } * * // Sketch prints: * // mammals * // fish * </code></div> */p5.XML.prototype.setName=function(name){this.name=name;};/** * Checks whether or not the element has any children, and returns the result * as a boolean. * * @method hasChildren * @return {boolean} * @example&lt;animal * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * print(xml.hasChildren()); * } * * // Sketch prints: * // true * </code></div> */p5.XML.prototype.hasChildren=function(){return this.children.length>0;};/** * Get the names of all of the element's children, and returns the names as an * array of Strings. This is the same as looping through and calling <a href="#/p5.XML/getName">getName()</a> * on each child element individually. * * @method listChildren * @return {String[]} names of the children of the element * @example&lt;animal * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * print(xml.listChildren()); * } * * // Sketch prints: * // ["animal", "animal", "animal"] * </code></div> */p5.XML.prototype.listChildren=function(){return this.children.map(function(c){return c.name;});};/** * Returns all of the element's children as an array of <a href="#/p5.XML">p5.XML</a> objects. When * the name parameter is specified, then it will return all children that match * that name. * * @method getChildren * @param {String} [name] element name * @return {p5.XML[]} children of the element * @example&lt;animal * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var animals = xml.getChildren('animal'); * * for (var i = 0; i < animals.length; i++) { * print(animals[i].getContent()); * } * } * * // Sketch prints: * // "Goat" * // "Leopard" * // "Zebra" * </code></div> */p5.XML.prototype.getChildren=function(param){if(param){return this.children.filter(function(c){return c.name===param;});}else{return this.children;}};/** * Returns the first of the element's children that matches the name parameter * or the child of the given index.It returns undefined if no matching * child is found. * * @method getChild * @param {String|Integer} name element name or index * @return {p5.XML} * @example&lt;animal * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getContent()); * } * * // Sketch prints: * // "Goat" * </code></div> * <div class='norender'><code> * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var secondChild = xml.getChild(1); * print(secondChild.getContent()); * } * * // Sketch prints: * // "Leopard" * </code></div> */p5.XML.prototype.getChild=function(param){if(typeof param==='string'){for(var i=0;i<this.children.length;i++){var child=this.children[i];if(child.name===param)return child;}}else{return this.children[param];}};/** * Appends a new child to the element. The child can be specified with * either a String, which will be used as the new tag's name, or as a * reference to an existing <a href="#/p5.XML">p5.XML</a> object. * A reference to the newly created child is returned as an <a href="#/p5.XML">p5.XML</a> object. * * @method addChild * @param {p5.XML} node a <a href="#/p5.XML">p5.XML</a> Object which will be the child to be added * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var child = new p5.XML(); * child.setAttribute('id', '3'); * child.setAttribute('species', 'Ornithorhynchus anatinus'); * child.setContent('Platypus'); * xml.addChild(child); * * var animals = xml.getChildren('animal'); * print(animals[animals.length - 1].getContent()); * } * * // Sketch prints: * // "Goat" * // "Leopard" * // "Zebra" * </code></div> */p5.XML.prototype.addChild=function(node){if(node instanceof p5.XML){this.children.push(node);}else{// PEND }};/** * Removes the element specified by name or index. * * @method removeChild * @param {String|Integer} name element name or index * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * xml.removeChild('animal'); * var children = xml.getChildren(); * for (var i = 0; i < children.length; i++) { * print(children[i].getContent()); * } * } * * // Sketch prints: * // "Leopard" * // "Zebra" * </code></div> * <div class='norender'><code> * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * xml.removeChild(1); * var children = xml.getChildren(); * for (var i = 0; i < children.length; i++) { * print(children[i].getContent()); * } * } * * // Sketch prints: * // "Goat" * // "Zebra" * </code></div> */p5.XML.prototype.removeChild=function(param){var ind=-1;if(typeof param==='string'){for(var i=0;i<this.children.length;i++){if(this.children[i].name===param){ind=i;break;}}}else{ind=param;}if(ind!==-1){this.children.splice(ind,1);}};/** * Counts the specified element's number of attributes, returned as an Number. * * @method getAttributeCount * @return {Integer} * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getAttributeCount()); * } * * // Sketch prints: * // 2 * </code></div> */p5.XML.prototype.getAttributeCount=function(){return Object.keys(this.attributes).length;};/** * Gets all of the specified element's attributes, and returns them as an * array of Strings. * * @method listAttributes * @return {String[]} an array of strings containing the names of attributes * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.listAttributes()); * } * * // Sketch prints: * // ["id", "species"] * </code></div> */p5.XML.prototype.listAttributes=function(){return Object.keys(this.attributes);};/** * Checks whether or not an element has the specified attribute. * * @method hasAttribute * @param {String} the attribute to be checked * @return {boolean} true if attribute found else false * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.hasAttribute('species')); * print(firstChild.hasAttribute('color')); * } * * // Sketch prints: * // true * // false * </code></div> */p5.XML.prototype.hasAttribute=function(name){return this.attributes[name]?true:false;};/** * Returns an attribute value of the element as an Number. If the defaultValue * parameter is specified and the attribute doesn't exist, then defaultValue * is returned. If no defaultValue is specified and the attribute doesn't * exist, the value 0 is returned. * * @method getNum * @param {String} name the non-null full name of the attribute * @param {Number} [defaultValue] the default value of the attribute * @return {Number} * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getNum('id')); * } * * // Sketch prints: * // 0 * </code></div> */p5.XML.prototype.getNum=function(name,defaultValue){return Number(this.attributes[name])||defaultValue||0;};/** * Returns an attribute value of the element as an String. If the defaultValue * parameter is specified and the attribute doesn't exist, then defaultValue * is returned. If no defaultValue is specified and the attribute doesn't * exist, null is returned. * * @method getString * @param {String} name the non-null full name of the attribute * @param {Number} [defaultValue] the default value of the attribute * @return {String} * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getString('species')); * } * * // Sketch prints: * // "Capra hircus" * </code></div> */p5.XML.prototype.getString=function(name,defaultValue){return String(this.attributes[name])||defaultValue||null;};/** * Sets the content of an element's attribute. The first parameter specifies * the attribute name, while the second specifies the new content. * * @method setAttribute * @param {String} name the full name of the attribute * @param {Number|String|Boolean} value the value of the attribute * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getString('species')); * firstChild.setAttribute('species', 'Jamides zebra'); * print(firstChild.getString('species')); * } * * // Sketch prints: * // "Capra hircus" * // "Jamides zebra" * </code></div> */p5.XML.prototype.setAttribute=function(name,value){if(this.attributes[name]){this.attributes[name]=value;}};/** * Returns the content of an element. If there is no such content, * defaultValue is returned if specified, otherwise null is returned. * * @method getContent * @param {String} [defaultValue] value returned if no content is found * @return {String} * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getContent()); * } * * // Sketch prints: * // "Goat" * </code></div> */p5.XML.prototype.getContent=function(defaultValue){return this.content||defaultValue||null;};/** * Sets the element's content. * * @method setContent * @param {String} text the new content * @example * <div class='norender'><code> * // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // <?xml version="1.0"?> * // &lt;mammals&gt; * // &lt;animal id="0" species="Capra hircus">Goat&lt;/animal&gt; * // &lt;animal id="1" species="Panthera pardus">Leopard&lt;/animal&gt; * // &lt;animal id="2" species="Equus zebra">Zebra&lt;/animal&gt; * // &lt;/mammals&gt; * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getContent()); * firstChild.setContent('Mountain Goat'); * print(firstChild.getContent()); * } * * // Sketch prints: * // "Goat" * // "Mountain Goat" * </code></div> */p5.XML.prototype.setContent=function(content){if(!this.children.length){this.content=content;}};/* HELPERS *//** * This method is called while the parsing of XML (when loadXML() is * called). The difference between this method and the setContent() * method defined later is that this one is used to set the content * when the node in question has more nodes under it and so on and * not directly text content. While in the other one is used when * the node in question directly has text inside it. * */p5.XML.prototype._setCont=function(content){var str;str=content;str=str.replace(/\s\s+/g,',');//str = str.split(','); this.content=str;};/** * This method is called while the parsing of XML (when loadXML() is * called). The XML node is passed and its attributes are stored in the * <a href="#/p5.XML">p5.XML</a>'s attribute Object. * */p5.XML.prototype._setAttributes=function(node){var att={};var attributes=node.attributes;if(attributes){for(var i=0;i<attributes.length;i++){var attribute=attributes[i];att[attribute.nodeName]=attribute.nodeValue;}}this.attributes=att;};module.exports=p5;},{"../core/main":25}],52:[function(_dereq_,module,exports){/** * @module Math * @submodule Calculation * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');/** * Calculates the absolute value (magnitude) of a number. Maps to Math.abs(). * The absolute value of a number is always positive. * * @method abs * @param {Number} n number to compute * @return {Number} absolute value of given number * @example * <div class = "norender"><code> * function setup() { * var x = -3; * var y = abs(x); * * print(x); // -3 * print(y); // 3 * } * </code></div> * * @alt * no image displayed * */p5.prototype.abs=Math.abs;/** * Calculates the closest int value that is greater than or equal to the * value of the parameter. Maps to Math.ceil(). For example, ceil(9.03) * returns the value 10. * * @method ceil * @param {Number} n number to round up * @return {Integer} rounded up number * @example * <div><code> * function draw() { * background(200); * // map, mouseX between 0 and 5. * var ax = map(mouseX, 0, 100, 0, 5); * var ay = 66; * * //Get the ceiling of the mapped number. * var bx = ceil(map(mouseX, 0, 100, 0, 5)); * var by = 33; * * // Multiply the mapped numbers by 20 to more easily * // see the changes. * stroke(0); * fill(0); * line(0, ay, ax * 20, ay); * line(0, by, bx * 20, by); * * // Reformat the float returned by map and draw it. * noStroke(); * text(nfc(ax, 2), ax, ay - 5); * text(nfc(bx, 1), bx, by - 5); * } * </code></div> * * @alt * 2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals * */p5.prototype.ceil=Math.ceil;/** * Constrains a value between a minimum and maximum value. * * @method constrain * @param {Number} n number to constrain * @param {Number} low minimum limit * @param {Number} high maximum limit * @return {Number} constrained number * @example * <div><code> * function draw() { * background(200); * * var leftWall = 25; * var rightWall = 75; * * // xm is just the mouseX, while * // xc is the mouseX, but constrained * // between the leftWall and rightWall! * var xm = mouseX; * var xc = constrain(mouseX, leftWall, rightWall); * * // Draw the walls. * stroke(150); * line(leftWall, 0, leftWall, height); * line(rightWall, 0, rightWall, height); * * // Draw xm and xc as circles. * noStroke(); * fill(150); * ellipse(xm, 33, 9, 9); // Not Constrained * fill(0); * ellipse(xc, 66, 9, 9); // Constrained * } * </code></div> * * @alt * 2 vertical lines. 2 ellipses move with mouse X 1 does not move passed lines * */p5.prototype.constrain=function(n,low,high){p5._validateParameters('constrain',arguments);return Math.max(Math.min(n,high),low);};/** * Calculates the distance between two points. * * @method dist * @param {Number} x1 x-coordinate of the first point * @param {Number} y1 y-coordinate of the first point * @param {Number} x2 x-coordinate of the second point * @param {Number} y2 y-coordinate of the second point * @return {Number} distance between the two points * * @example * <div><code> * // Move your mouse inside the canvas to see the * // change in distance between two points! * function draw() { * background(200); * fill(0); * * var x1 = 10; * var y1 = 90; * var x2 = mouseX; * var y2 = mouseY; * * line(x1, y1, x2, y2); * ellipse(x1, y1, 7, 7); * ellipse(x2, y2, 7, 7); * * // d is the length of the line * // the distance from point 1 to point 2. * var d = int(dist(x1, y1, x2, y2)); * * // Let's write d along the line we are drawing! * push(); * translate((x1 + x2) / 2, (y1 + y2) / 2); * rotate(atan2(y2 - y1, x2 - x1)); * text(nfc(d, 1), 0, -5); * pop(); * // Fancy! * } * </code></div> * * @alt * 2 ellipses joined by line. 1 ellipse moves with mouse X&Y. Distance displayed. *//** * @method dist * @param {Number} x1 * @param {Number} y1 * @param {Number} z1 z-coordinate of the first point * @param {Number} x2 * @param {Number} y2 * @param {Number} z2 z-coordinate of the second point * @return {Number} distance between the two points */p5.prototype.dist=function(){p5._validateParameters('dist',arguments);if(arguments.length===4){//2D return hypot(arguments[2]-arguments[0],arguments[3]-arguments[1]);}else if(arguments.length===6){//3D return hypot(arguments[3]-arguments[0],arguments[4]-arguments[1],arguments[5]-arguments[2]);}};/** * Returns Euler's number e (2.71828...) raised to the power of the n * parameter. Maps to Math.exp(). * * @method exp * @param {Number} n exponent to raise * @return {Number} e^n * @example * <div><code> * function draw() { * background(200); * * // Compute the exp() function with a value between 0 and 2 * var xValue = map(mouseX, 0, width, 0, 2); * var yValue = exp(xValue); * * var y = map(yValue, 0, 8, height, 0); * * var legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4); * stroke(150); * line(mouseX, y, mouseX, height); * fill(0); * text(legend, 5, 15); * noStroke(); * ellipse(mouseX, y, 7, 7); * * // Draw the exp(x) curve, * // over the domain of x from 0 to 2 * noFill(); * stroke(0); * beginShape(); * for (var x = 0; x < width; x++) { * xValue = map(x, 0, width, 0, 2); * yValue = exp(xValue); * y = map(yValue, 0, 8, height, 0); * vertex(x, y); * } * * endShape(); * line(0, 0, 0, height); * line(0, height - 1, width, height - 1); * } * </code></div> * * @alt * ellipse moves along a curve with mouse x. e^n displayed. * */p5.prototype.exp=Math.exp;/** * Calculates the closest int value that is less than or equal to the * value of the parameter. Maps to Math.floor(). * * @method floor * @param {Number} n number to round down * @return {Integer} rounded down number * @example * <div><code> * function draw() { * background(200); * //map, mouseX between 0 and 5. * var ax = map(mouseX, 0, 100, 0, 5); * var ay = 66; * * //Get the floor of the mapped number. * var bx = floor(map(mouseX, 0, 100, 0, 5)); * var by = 33; * * // Multiply the mapped numbers by 20 to more easily * // see the changes. * stroke(0); * fill(0); * line(0, ay, ax * 20, ay); * line(0, by, bx * 20, by); * * // Reformat the float returned by map and draw it. * noStroke(); * text(nfc(ax, 2), ax, ay - 5); * text(nfc(bx, 1), bx, by - 5); * } * </code></div> * * @alt * 2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals * */p5.prototype.floor=Math.floor;/** * Calculates a number between two numbers at a specific increment. The amt * parameter is the amount to interpolate between the two values where 0.0 * equal to the first point, 0.1 is very near the first point, 0.5 is * half-way in between, etc. The lerp function is convenient for creating * motion along a straight path and for drawing dotted lines. * * @method lerp * @param {Number} start first value * @param {Number} stop second value * @param {Number} amt number between 0.0 and 1.0 * @return {Number} lerped value * @example * <div><code> * function setup() { * background(200); * var a = 20; * var b = 80; * var c = lerp(a, b, 0.2); * var d = lerp(a, b, 0.5); * var e = lerp(a, b, 0.8); * * var y = 50; * * strokeWeight(5); * stroke(0); // Draw the original points in black * point(a, y); * point(b, y); * * stroke(100); // Draw the lerp points in gray * point(c, y); * point(d, y); * point(e, y); * } * </code></div> * * @alt * 5 points horizontally staggered mid-canvas. mid 3 are grey, outer black * */p5.prototype.lerp=function(start,stop,amt){p5._validateParameters('lerp',arguments);return amt*(stop-start)+start;};/** * Calculates the natural logarithm (the base-e logarithm) of a number. This * function expects the n parameter to be a value greater than 0.0. Maps to * Math.log(). * * @method log * @param {Number} n number greater than 0 * @return {Number} natural logarithm of n * @example * <div><code> * function draw() { * background(200); * var maxX = 2.8; * var maxY = 1.5; * * // Compute the natural log of a value between 0 and maxX * var xValue = map(mouseX, 0, width, 0, maxX); * if (xValue > 0) { // Cannot take the log of a negative number. * var yValue = log(xValue); * var y = map(yValue, -maxY, maxY, height, 0); * * // Display the calculation occurring. * var legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3); * stroke(150); * line(mouseX, y, mouseX, height); * fill(0); * text(legend, 5, 15); * noStroke(); * ellipse(mouseX, y, 7, 7); * } * * // Draw the log(x) curve, * // over the domain of x from 0 to maxX * noFill(); * stroke(0); * beginShape(); * for (var x = 0; x < width; x++) { * xValue = map(x, 0, width, 0, maxX); * yValue = log(xValue); * y = map(yValue, -maxY, maxY, height, 0); * vertex(x, y); * } * endShape(); * line(0, 0, 0, height); * line(0, height / 2, width, height / 2); * } * </code></div> * * @alt * ellipse moves along a curve with mouse x. natural logarithm of n displayed. * */p5.prototype.log=Math.log;/** * Calculates the magnitude (or length) of a vector. A vector is a direction * in space commonly used in computer graphics and linear algebra. Because it * has no "start" position, the magnitude of a vector can be thought of as * the distance from the coordinate 0,0 to its x,y value. Therefore, <a href="#/p5/mag">mag()</a> is * a shortcut for writing dist(0, 0, x, y). * * @method mag * @param {Number} a first value * @param {Number} b second value * @return {Number} magnitude of vector from (0,0) to (a,b) * @example * <div><code> * function setup() { * var x1 = 20; * var x2 = 80; * var y1 = 30; * var y2 = 70; * * line(0, 0, x1, y1); * print(mag(x1, y1)); // Prints "36.05551275463989" * line(0, 0, x2, y1); * print(mag(x2, y1)); // Prints "85.44003745317531" * line(0, 0, x1, y2); * print(mag(x1, y2)); // Prints "72.80109889280519" * line(0, 0, x2, y2); * print(mag(x2, y2)); // Prints "106.3014581273465" * } * </code></div> * * @alt * 4 lines of different length radiate from top left of canvas. * */p5.prototype.mag=function(x,y){p5._validateParameters('mag',arguments);return hypot(x,y);};/** * Re-maps a number from one range to another. * <br><br> * In the first example above, the number 25 is converted from a value in the * range of 0 to 100 into a value that ranges from the left edge of the * window (0) to the right edge (width). * * @method map * @param {Number} value the incoming value to be converted * @param {Number} start1 lower bound of the value's current range * @param {Number} stop1 upper bound of the value's current range * @param {Number} start2 lower bound of the value's target range * @param {Number} stop2 upper bound of the value's target range * @param {Boolean} [withinBounds] constrain the value to the newly mapped range * @return {Number} remapped number * @example * <div><code> * var value = 25; * var m = map(value, 0, 100, 0, width); * ellipse(m, 50, 10, 10); </code></div> * * <div><code> * function setup() { * noStroke(); * } * * function draw() { * background(204); * var x1 = map(mouseX, 0, width, 25, 75); * ellipse(x1, 25, 25, 25); * //This ellipse is constrained to the 0-100 range * //after setting withinBounds to true * var x2 = map(mouseX, 0, width, 0, 100, true); * ellipse(x2, 75, 25, 25); * } </code></div> * * @alt * 10 by 10 white ellipse with in mid left canvas * 2 25 by 25 white ellipses move with mouse x. Bottom has more range from X * */p5.prototype.map=function(n,start1,stop1,start2,stop2,withinBounds){p5._validateParameters('map',arguments);var newval=(n-start1)/(stop1-start1)*(stop2-start2)+start2;if(!withinBounds){return newval;}if(start2<stop2){return this.constrain(newval,start2,stop2);}else{return this.constrain(newval,stop2,start2);}};/** * Determines the largest value in a sequence of numbers, and then returns * that value. <a href="#/p5/max">max()</a> accepts any number of Number parameters, or an Array * of any length. * * @method max * @param {Number} n0 Number to compare * @param {Number} n1 Number to compare * @return {Number} maximum Number * @example * <div><code> * function setup() { * // Change the elements in the array and run the sketch * // to show how max() works! * var numArray = [2, 1, 5, 4, 8, 9]; * fill(0); * noStroke(); * text('Array Elements', 0, 10); * // Draw all numbers in the array * var spacing = 15; * var elemsY = 25; * for (var i = 0; i < numArray.length; i++) { * text(numArray[i], i * spacing, elemsY); * } * var maxX = 33; * var maxY = 80; * // Draw the Maximum value in the array. * textSize(32); * text(max(numArray), maxX, maxY); * } * </code></div> * * @alt * Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 9 * *//** * @method max * @param {Number[]} nums Numbers to compare * @return {Number} */p5.prototype.max=function(){p5._validateParameters('max',arguments);if(arguments[0]instanceof Array){return Math.max.apply(null,arguments[0]);}else{return Math.max.apply(null,arguments);}};/** * Determines the smallest value in a sequence of numbers, and then returns * that value. <a href="#/p5/min">min()</a> accepts any number of Number parameters, or an Array * of any length. * * @method min * @param {Number} n0 Number to compare * @param {Number} n1 Number to compare * @return {Number} minimum Number * @example * <div><code> * function setup() { * // Change the elements in the array and run the sketch * // to show how min() works! * var numArray = [2, 1, 5, 4, 8, 9]; * fill(0); * noStroke(); * text('Array Elements', 0, 10); * // Draw all numbers in the array * var spacing = 15; * var elemsY = 25; * for (var i = 0; i < numArray.length; i++) { * text(numArray[i], i * spacing, elemsY); * } * var maxX = 33; * var maxY = 80; * // Draw the Minimum value in the array. * textSize(32); * text(min(numArray), maxX, maxY); * } * </code></div> * * @alt * Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 1 * *//** * @method min * @param {Number[]} nums Numbers to compare * @return {Number} */p5.prototype.min=function(){p5._validateParameters('min',arguments);if(arguments[0]instanceof Array){return Math.min.apply(null,arguments[0]);}else{return Math.min.apply(null,arguments);}};/** * Normalizes a number from another range into a value between 0 and 1. * Identical to map(value, low, high, 0, 1). * Numbers outside of the range are not clamped to 0 and 1, because * out-of-range values are often intentional and useful. (See the second * example above.) * * @method norm * @param {Number} value incoming value to be normalized * @param {Number} start lower bound of the value's current range * @param {Number} stop upper bound of the value's current range * @return {Number} normalized number * @example * <div><code> * function draw() { * background(200); * var currentNum = mouseX; * var lowerBound = 0; * var upperBound = width; //100; * var normalized = norm(currentNum, lowerBound, upperBound); * var lineY = 70; * line(0, lineY, width, lineY); * //Draw an ellipse mapped to the non-normalized value. * noStroke(); * fill(50); * var s = 7; // ellipse size * ellipse(currentNum, lineY, s, s); * * // Draw the guide * var guideY = lineY + 15; * text('0', 0, guideY); * textAlign(RIGHT); * text('100', width, guideY); * * // Draw the normalized value * textAlign(LEFT); * fill(0); * textSize(32); * var normalY = 40; * var normalX = 20; * text(normalized, normalX, normalY); * } * </code></div> * * @alt * ellipse moves with mouse. 0 shown left & 100 right and updating values center * */p5.prototype.norm=function(n,start,stop){p5._validateParameters('norm',arguments);return this.map(n,start,stop,0,1);};/** * Facilitates exponential expressions. The <a href="#/p5/pow">pow()</a> function is an efficient * way of multiplying numbers by themselves (or their reciprocals) in large * quantities. For example, pow(3, 5) is equivalent to the expression * 3*3*3*3*3 and pow(3, -5) is equivalent to 1 / 3*3*3*3*3. Maps to * Math.pow(). * * @method pow * @param {Number} n base of the exponential expression * @param {Number} e power by which to raise the base * @return {Number} n^e * @example * <div><code> * function setup() { * //Exponentially increase the size of an ellipse. * var eSize = 3; // Original Size * var eLoc = 10; // Original Location * * ellipse(eLoc, eLoc, eSize, eSize); * * ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2)); * * ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3)); * * ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4)); * } * </code></div> * * @alt * small to large ellipses radiating from top left of canvas * */p5.prototype.pow=Math.pow;/** * Calculates the integer closest to the n parameter. For example, * round(133.8) returns the value 134. Maps to Math.round(). * * @method round * @param {Number} n number to round * @return {Integer} rounded number * @example * <div><code> * function draw() { * background(200); * //map, mouseX between 0 and 5. * var ax = map(mouseX, 0, 100, 0, 5); * var ay = 66; * * // Round the mapped number. * var bx = round(map(mouseX, 0, 100, 0, 5)); * var by = 33; * * // Multiply the mapped numbers by 20 to more easily * // see the changes. * stroke(0); * fill(0); * line(0, ay, ax * 20, ay); * line(0, by, bx * 20, by); * * // Reformat the float returned by map and draw it. * noStroke(); * text(nfc(ax, 2), ax, ay - 5); * text(nfc(bx, 1), bx, by - 5); * } * </code></div> * * @alt * horizontal center line squared values displayed on top and regular on bottom. * */p5.prototype.round=Math.round;/** * Squares a number (multiplies a number by itself). The result is always a * positive number, as multiplying two negative numbers always yields a * positive result. For example, -1 * -1 = 1. * * @method sq * @param {Number} n number to square * @return {Number} squared number * @example * <div><code> * function draw() { * background(200); * var eSize = 7; * var x1 = map(mouseX, 0, width, 0, 10); * var y1 = 80; * var x2 = sq(x1); * var y2 = 20; * * // Draw the non-squared. * line(0, y1, width, y1); * ellipse(x1, y1, eSize, eSize); * * // Draw the squared. * line(0, y2, width, y2); * ellipse(x2, y2, eSize, eSize); * * // Draw dividing line. * stroke(100); * line(0, height / 2, width, height / 2); * * // Draw text. * var spacing = 15; * noStroke(); * fill(0); * text('x = ' + x1, 0, y1 + spacing); * text('sq(x) = ' + x2, 0, y2 + spacing); * } * </code></div> * * @alt * horizontal center line squared values displayed on top and regular on bottom. * */p5.prototype.sq=function(n){return n*n;};/** * Calculates the square root of a number. The square root of a number is * always positive, even though there may be a valid negative root. The * square root s of number a is such that s*s = a. It is the opposite of * squaring. Maps to Math.sqrt(). * * @method sqrt * @param {Number} n non-negative number to square root * @return {Number} square root of number * @example * <div><code> * function draw() { * background(200); * var eSize = 7; * var x1 = mouseX; * var y1 = 80; * var x2 = sqrt(x1); * var y2 = 20; * * // Draw the non-squared. * line(0, y1, width, y1); * ellipse(x1, y1, eSize, eSize); * * // Draw the squared. * line(0, y2, width, y2); * ellipse(x2, y2, eSize, eSize); * * // Draw dividing line. * stroke(100); * line(0, height / 2, width, height / 2); * * // Draw text. * noStroke(); * fill(0); * var spacing = 15; * text('x = ' + x1, 0, y1 + spacing); * text('sqrt(x) = ' + x2, 0, y2 + spacing); * } * </code></div> * * @alt * horizontal center line squareroot values displayed on top and regular on bottom. * */p5.prototype.sqrt=Math.sqrt;// Calculate the length of the hypotenuse of a right triangle // This won't under- or overflow in intermediate steps // https://en.wikipedia.org/wiki/Hypot function hypot(x,y,z){// Use the native implementation if it's available if(typeof Math.hypot==='function'){return Math.hypot.apply(null,arguments);}// Otherwise use the V8 implementation // https://github.com/v8/v8/blob/8cd3cf297287e581a49e487067f5cbd991b27123/src/js/math.js#L217 var length=arguments.length;var args=[];var max=0;for(var i=0;i<length;i++){var n=arguments[i];n=+n;if(n===Infinity||n===-Infinity){return Infinity;}n=Math.abs(n);if(n>max){max=n;}args[i]=n;}if(max===0){max=1;}var sum=0;var compensation=0;for(var j=0;j<length;j++){var m=args[j]/max;var summand=m*m-compensation;var preliminary=sum+summand;compensation=preliminary-sum-summand;sum=preliminary;}return Math.sqrt(sum)*max;}module.exports=p5;},{"../core/main":25}],53:[function(_dereq_,module,exports){/** * @module Math * @submodule Math * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');/** * Creates a new <a href="#/p5.Vector">p5.Vector</a> (the datatype for storing vectors). This provides a * two or three dimensional vector, specifically a Euclidean (also known as * geometric) vector. A vector is an entity that has both magnitude and * direction. * * @method createVector * @param {Number} [x] x component of the vector * @param {Number} [y] y component of the vector * @param {Number} [z] z component of the vector * @return {p5.Vector} * @example * <div modernizr='webgl'><code> * function setup() { * createCanvas(100, 100, WEBGL); * noStroke(); * fill(255, 102, 204); * } * * function draw() { * background(255); * pointLight(color(255), createVector(sin(millis() / 1000) * 20, -40, -10)); * scale(0.75); * sphere(); * } * </code></div> * * @alt * a purple sphere lit by a point light oscillating horizontally */p5.prototype.createVector=function(x,y,z){if(this instanceof p5){return new p5.Vector(this,arguments);}else{return new p5.Vector(x,y,z);}};module.exports=p5;},{"../core/main":25}],54:[function(_dereq_,module,exports){////////////////////////////////////////////////////////////// // http://mrl.nyu.edu/~perlin/noise/ // Adapting from PApplet.java // which was adapted from toxi // which was adapted from the german demo group farbrausch // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip // someday we might consider using "improved noise" // http://mrl.nyu.edu/~perlin/paper445.pdf // See: https://github.com/shiffman/The-Nature-of-Code-Examples-p5.js/ // blob/master/introduction/Noise1D/noise.js /** * @module Math * @submodule Noise * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');var PERLIN_YWRAPB=4;var PERLIN_YWRAP=1<<PERLIN_YWRAPB;var PERLIN_ZWRAPB=8;var PERLIN_ZWRAP=1<<PERLIN_ZWRAPB;var PERLIN_SIZE=4095;var perlin_octaves=4;// default to medium smooth var perlin_amp_falloff=0.5;// 50% reduction/octave var scaled_cosine=function scaled_cosine(i){return 0.5*(1.0-Math.cos(i*Math.PI));};var perlin;// will be initialized lazily by noise() or noiseSeed() /** * Returns the Perlin noise value at specified coordinates. Perlin noise is * a random sequence generator producing a more natural ordered, harmonic * succession of numbers compared to the standard <b>random()</b> function. * It was invented by Ken Perlin in the 1980s and been used since in * graphical applications to produce procedural textures, natural motion, * shapes, terrains etc.<br /><br /> The main difference to the * <b>random()</b> function is that Perlin noise is defined in an infinite * n-dimensional space where each pair of coordinates corresponds to a * fixed semi-random value (fixed only for the lifespan of the program; see * the <a href="#/p5/noiseSeed">noiseSeed()</a> function). p5.js can compute 1D, 2D and 3D noise, * depending on the number of coordinates given. The resulting value will * always be between 0.0 and 1.0. The noise value can be animated by moving * through the noise space as demonstrated in the example above. The 2nd * and 3rd dimension can also be interpreted as time.<br /><br />The actual * noise is structured similar to an audio signal, in respect to the * function's use of frequencies. Similar to the concept of harmonics in * physics, perlin noise is computed over several octaves which are added * together for the final result. <br /><br />Another way to adjust the * character of the resulting sequence is the scale of the input * coordinates. As the function works within an infinite space the value of * the coordinates doesn't matter as such, only the distance between * successive coordinates does (eg. when using <b>noise()</b> within a * loop). As a general rule the smaller the difference between coordinates, * the smoother the resulting noise sequence will be. Steps of 0.005-0.03 * work best for most applications, but this will differ depending on use. * * * @method noise * @param {Number} x x-coordinate in noise space * @param {Number} [y] y-coordinate in noise space * @param {Number} [z] z-coordinate in noise space * @return {Number} Perlin noise value (between 0 and 1) at specified * coordinates * @example * <div> * <code> * var xoff = 0.0; * * function draw() { * background(204); * xoff = xoff + 0.01; * var n = noise(xoff) * width; * line(n, 0, n, height); * } * </code> * </div> * <div> * <code>var noiseScale=0.02; * * function draw() { * background(0); * for (var x=0; x < width; x++) { * var noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale); * stroke(noiseVal*255); * line(x, mouseY+noiseVal*80, x, height); * } * } * </code> * </div> * * @alt * vertical line moves left to right with updating noise values. * horizontal wave pattern effected by mouse x-position & updating noise values. * */p5.prototype.noise=function(x,y,z){y=y||0;z=z||0;if(perlin==null){perlin=new Array(PERLIN_SIZE+1);for(var i=0;i<PERLIN_SIZE+1;i++){perlin[i]=Math.random();}}if(x<0){x=-x;}if(y<0){y=-y;}if(z<0){z=-z;}var xi=Math.floor(x),yi=Math.floor(y),zi=Math.floor(z);var xf=x-xi;var yf=y-yi;var zf=z-zi;var rxf,ryf;var r=0;var ampl=0.5;var n1,n2,n3;for(var o=0;o<perlin_octaves;o++){var of=xi+(yi<<PERLIN_YWRAPB)+(zi<<PERLIN_ZWRAPB);rxf=scaled_cosine(xf);ryf=scaled_cosine(yf);n1=perlin[of&PERLIN_SIZE];n1+=rxf*(perlin[of+1&PERLIN_SIZE]-n1);n2=perlin[of+PERLIN_YWRAP&PERLIN_SIZE];n2+=rxf*(perlin[of+PERLIN_YWRAP+1&PERLIN_SIZE]-n2);n1+=ryf*(n2-n1);of+=PERLIN_ZWRAP;n2=perlin[of&PERLIN_SIZE];n2+=rxf*(perlin[of+1&PERLIN_SIZE]-n2);n3=perlin[of+PERLIN_YWRAP&PERLIN_SIZE];n3+=rxf*(perlin[of+PERLIN_YWRAP+1&PERLIN_SIZE]-n3);n2+=ryf*(n3-n2);n1+=scaled_cosine(zf)*(n2-n1);r+=n1*ampl;ampl*=perlin_amp_falloff;xi<<=1;xf*=2;yi<<=1;yf*=2;zi<<=1;zf*=2;if(xf>=1.0){xi++;xf--;}if(yf>=1.0){yi++;yf--;}if(zf>=1.0){zi++;zf--;}}return r;};/** * * Adjusts the character and level of detail produced by the Perlin noise * function. Similar to harmonics in physics, noise is computed over * several octaves. Lower octaves contribute more to the output signal and * as such define the overall intensity of the noise, whereas higher octaves * create finer grained details in the noise sequence. * <br><br> * By default, noise is computed over 4 octaves with each octave contributing * exactly half than its predecessor, starting at 50% strength for the 1st * octave. This falloff amount can be changed by adding an additional function * parameter. Eg. a falloff factor of 0.75 means each octave will now have * 75% impact (25% less) of the previous lower octave. Any value between * 0.0 and 1.0 is valid, however note that values greater than 0.5 might * result in greater than 1.0 values returned by <b>noise()</b>. * <br><br> * By changing these parameters, the signal created by the <b>noise()</b> * function can be adapted to fit very specific needs and characteristics. * * @method noiseDetail * @param {Number} lod number of octaves to be used by the noise * @param {Number} falloff falloff factor for each octave * @example * <div> * <code> * var noiseVal; * var noiseScale = 0.02; * * function setup() { * createCanvas(100, 100); * } * * function draw() { * background(0); * for (var y = 0; y < height; y++) { * for (var x = 0; x < width / 2; x++) { * noiseDetail(2, 0.2); * noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale); * stroke(noiseVal * 255); * point(x, y); * noiseDetail(8, 0.65); * noiseVal = noise( * (mouseX + x + width / 2) * noiseScale, * (mouseY + y) * noiseScale * ); * stroke(noiseVal * 255); * point(x + width / 2, y); * } * } * } * </code> * </div> * * @alt * 2 vertical grey smokey patterns affected my mouse x-position and noise. * */p5.prototype.noiseDetail=function(lod,falloff){if(lod>0){perlin_octaves=lod;}if(falloff>0){perlin_amp_falloff=falloff;}};/** * Sets the seed value for <b>noise()</b>. By default, <b>noise()</b> * produces different results each time the program is run. Set the * <b>value</b> parameter to a constant to return the same pseudo-random * numbers each time the software is run. * * @method noiseSeed * @param {Number} seed the seed value * @example * <div> * <code>var xoff = 0.0; * * function setup() { * noiseSeed(99); * stroke(0, 10); * } * * function draw() { * xoff = xoff + .01; * var n = noise(xoff) * width; * line(n, 0, n, height); * } * </code> * </div> * * @alt * vertical grey lines drawing in pattern affected by noise. * */p5.prototype.noiseSeed=function(seed){// Linear Congruential Generator // Variant of a Lehman Generator var lcg=function(){// Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes // m is basically chosen to be large (as it is the max period) // and for its relationships to a and c var m=4294967296;// a - 1 should be divisible by m's prime factors var a=1664525;// c and m should be co-prime var c=1013904223;var seed,z;return{setSeed:function setSeed(val){// pick a random seed if val is undefined or null // the >>> 0 casts the seed to an unsigned 32-bit integer z=seed=(val==null?Math.random()*m:val)>>>0;},getSeed:function getSeed(){return seed;},rand:function rand(){// define the recurrence relationship z=(a*z+c)%m;// return a float in [0, 1) // if z = m then z / m = 0 therefore (z % m) / m < 1 always return z/m;}};}();lcg.setSeed(seed);perlin=new Array(PERLIN_SIZE+1);for(var i=0;i<PERLIN_SIZE+1;i++){perlin[i]=lcg.rand();}};module.exports=p5;},{"../core/main":25}],55:[function(_dereq_,module,exports){/** * @module Math * @submodule Math * @requires constants */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');/** * A class to describe a two or three dimensional vector, specifically * a Euclidean (also known as geometric) vector. A vector is an entity * that has both magnitude and direction. The datatype, however, stores * the components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude * and direction can be accessed via the methods <a href="#/p5/mag">mag()</a> and <a href="#/p5/heading">heading()</a>. * <br><br> * In many of the p5.js examples, you will see <a href="#/p5.Vector">p5.Vector</a> used to describe a * position, velocity, or acceleration. For example, if you consider a rectangle * moving across the screen, at any given instant it has a position (a vector * that points from the origin to its location), a velocity (the rate at which * the object's position changes per time unit, expressed as a vector), and * acceleration (the rate at which the object's velocity changes per time * unit, expressed as a vector). * <br><br> * Since vectors represent groupings of values, we cannot simply use * traditional addition/multiplication/etc. Instead, we'll need to do some * "vector" math, which is made easy by the methods inside the <a href="#/p5.Vector">p5.Vector</a> class. * * @class p5.Vector * @param {Number} [x] x component of the vector * @param {Number} [y] y component of the vector * @param {Number} [z] z component of the vector * @example * <div> * <code> * var v1 = createVector(40, 50); * var v2 = createVector(40, 50); * * ellipse(v1.x, v1.y, 50, 50); * ellipse(v2.x, v2.y, 50, 50); * v1.add(v2); * ellipse(v1.x, v1.y, 50, 50); * </code> * </div> * * @alt * 2 white ellipses. One center-left the other bottom right and off canvas * */p5.Vector=function Vector(){var x,y,z;// This is how it comes in with createVector() if(arguments[0]instanceof p5){// save reference to p5 if passed in this.p5=arguments[0];x=arguments[1][0]||0;y=arguments[1][1]||0;z=arguments[1][2]||0;// This is what we'll get with new p5.Vector() }else{x=arguments[0]||0;y=arguments[1]||0;z=arguments[2]||0;}/** * The x component of the vector * @property x {Number} */this.x=x;/** * The y component of the vector * @property y {Number} */this.y=y;/** * The z component of the vector * @property z {Number} */this.z=z;};/** * Returns a string representation of a vector v by calling String(v) * or v.toString(). This method is useful for logging vectors in the * console. * @method toString * @return {String} * @example * <div class = "norender"> * <code> * function setup() { * var v = createVector(20, 30); * print(String(v)); // prints "p5.Vector Object : [20, 30, 0]" * } * </code> * </div> * * <div> * <code> * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'black'); * * noStroke(); * text(v1.toString(), 10, 25, 90, 75); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.prototype.toString=function p5VectorToString(){return'p5.Vector Object : ['+this.x+', '+this.y+', '+this.z+']';};/** * Sets the x, y, and z component of the vector using two or three separate * variables, the data from a <a href="#/p5.Vector">p5.Vector</a>, or the values from a float array. * @method set * @param {Number} [x] the x component of the vector * @param {Number} [y] the y component of the vector * @param {Number} [z] the z component of the vector * @chainable * @example * <div class="norender"> * <code> * function setup() { * var v = createVector(1, 2, 3); * v.set(4, 5, 6); // Sets vector to [4, 5, 6] * * var v1 = createVector(0, 0, 0); * var arr = [1, 2, 3]; * v1.set(arr); // Sets vector to [1, 2, 3] * } * </code> * </div> * * <div> * <code> * var v0, v1; * function setup() { * createCanvas(100, 100); * * v0 = createVector(0, 0); * v1 = createVector(50, 50); * } * * function draw() { * background(240); * * drawArrow(v0, v1, 'black'); * v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1)); * * noStroke(); * text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> *//** * @method set * @param {p5.Vector|Number[]} value the vector to set * @chainable */p5.Vector.prototype.set=function set(x,y,z){if(x instanceof p5.Vector){this.x=x.x||0;this.y=x.y||0;this.z=x.z||0;return this;}if(x instanceof Array){this.x=x[0]||0;this.y=x[1]||0;this.z=x[2]||0;return this;}this.x=x||0;this.y=y||0;this.z=z||0;return this;};/** * Gets a copy of the vector, returns a <a href="#/p5.Vector">p5.Vector</a> object. * * @method copy * @return {p5.Vector} the copy of the <a href="#/p5.Vector">p5.Vector</a> object * @example * <div class="norender"> * <code> * var v1 = createVector(1, 2, 3); * var v2 = v1.copy(); * print(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z); * // Prints "true" * </code> * </div> */p5.Vector.prototype.copy=function copy(){if(this.p5){return new p5.Vector(this.p5,[this.x,this.y,this.z]);}else{return new p5.Vector(this.x,this.y,this.z);}};/** * Adds x, y, and z components to a vector, adds one vector to another, or * adds two independent vectors together. The version of the method that adds * two vectors together is a static method and returns a <a href="#/p5.Vector">p5.Vector</a>, the others * acts directly on the vector. See the examples for more context. * * @method add * @param {Number} x the x component of the vector to be added * @param {Number} [y] the y component of the vector to be added * @param {Number} [z] the z component of the vector to be added * @chainable * @example * <div class="norender"> * <code> * var v = createVector(1, 2, 3); * v.add(4, 5, 6); * // v's components are set to [5, 7, 9] * </code> * </div> * * <div class="norender"> * <code> * // Static method * var v1 = createVector(1, 2, 3); * var v2 = createVector(2, 3, 4); * * var v3 = p5.Vector.add(v1, v2); * // v3 has components [3, 5, 7] * print(v3); * </code> * </div> * * <div> * <code> * // red vector + blue vector = purple vector * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'red'); * * var v2 = createVector(-30, 20); * drawArrow(v1, v2, 'blue'); * * var v3 = p5.Vector.add(v1, v2); * drawArrow(v0, v3, 'purple'); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> *//** * @method add * @param {p5.Vector|Number[]} value the vector to add * @chainable */p5.Vector.prototype.add=function add(x,y,z){if(x instanceof p5.Vector){this.x+=x.x||0;this.y+=x.y||0;this.z+=x.z||0;return this;}if(x instanceof Array){this.x+=x[0]||0;this.y+=x[1]||0;this.z+=x[2]||0;return this;}this.x+=x||0;this.y+=y||0;this.z+=z||0;return this;};/** * Subtracts x, y, and z components from a vector, subtracts one vector from * another, or subtracts two independent vectors. The version of the method * that subtracts two vectors is a static method and returns a <a href="#/p5.Vector">p5.Vector</a>, the * other acts directly on the vector. See the examples for more context. * * @method sub * @param {Number} x the x component of the vector to subtract * @param {Number} [y] the y component of the vector to subtract * @param {Number} [z] the z component of the vector to subtract * @chainable * @example * <div class="norender"> * <code> * var v = createVector(4, 5, 6); * v.sub(1, 1, 1); * // v's components are set to [3, 4, 5] * </code> * </div> * * <div class="norender"> * <code> * // Static method * var v1 = createVector(2, 3, 4); * var v2 = createVector(1, 2, 3); * * var v3 = p5.Vector.sub(v1, v2); * // v3 has components [1, 1, 1] * print(v3); * </code> * </div> * * <div> * <code> * // red vector - blue vector = purple vector * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(70, 50); * drawArrow(v0, v1, 'red'); * * var v2 = createVector(mouseX, mouseY); * drawArrow(v0, v2, 'blue'); * * var v3 = p5.Vector.sub(v1, v2); * drawArrow(v2, v3, 'purple'); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> *//** * @method sub * @param {p5.Vector|Number[]} value the vector to subtract * @chainable */p5.Vector.prototype.sub=function sub(x,y,z){if(x instanceof p5.Vector){this.x-=x.x||0;this.y-=x.y||0;this.z-=x.z||0;return this;}if(x instanceof Array){this.x-=x[0]||0;this.y-=x[1]||0;this.z-=x[2]||0;return this;}this.x-=x||0;this.y-=y||0;this.z-=z||0;return this;};/** * Multiply the vector by a scalar. The static version of this method * creates a new <a href="#/p5.Vector">p5.Vector</a> while the non static version acts on the vector * directly. See the examples for more context. * * @method mult * @param {Number} n the number to multiply with the vector * @chainable * @example * <div class="norender"> * <code> * var v = createVector(1, 2, 3); * v.mult(2); * // v's components are set to [2, 4, 6] * </code> * </div> * * <div class="norender"> * <code> * // Static method * var v1 = createVector(1, 2, 3); * var v2 = p5.Vector.mult(v1, 2); * // v2 has components [2, 4, 6] * print(v2); * </code> * </div> * * <div> * <code> * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = createVector(25, -25); * drawArrow(v0, v1, 'red'); * * var num = map(mouseX, 0, width, -2, 2, true); * var v2 = p5.Vector.mult(v1, num); * drawArrow(v0, v2, 'blue'); * * noStroke(); * text('multiplied by ' + num.toFixed(2), 5, 90); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.prototype.mult=function mult(n){if(!(typeof n==='number'&&isFinite(n))){console.warn('p5.Vector.prototype.mult:','n is undefined or not a finite number');return this;}this.x*=n;this.y*=n;this.z*=n;return this;};/** * Divide the vector by a scalar. The static version of this method creates a * new <a href="#/p5.Vector">p5.Vector</a> while the non static version acts on the vector directly. * See the examples for more context. * * @method div * @param {number} n the number to divide the vector by * @chainable * @example * <div class="norender"> * <code> * var v = createVector(6, 4, 2); * v.div(2); //v's components are set to [3, 2, 1] * </code> * </div> * * <div class="norender"> * <code> * // Static method * var v1 = createVector(6, 4, 2); * var v2 = p5.Vector.div(v1, 2); * // v2 has components [3, 2, 1] * print(v2); * </code> * </div> * * <div> * <code> * function draw() { * background(240); * * var v0 = createVector(0, 100); * var v1 = createVector(50, -50); * drawArrow(v0, v1, 'red'); * * var num = map(mouseX, 0, width, 10, 0.5, true); * var v2 = p5.Vector.div(v1, num); * drawArrow(v0, v2, 'blue'); * * noStroke(); * text('divided by ' + num.toFixed(2), 10, 90); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.prototype.div=function div(n){if(!(typeof n==='number'&&isFinite(n))){console.warn('p5.Vector.prototype.div:','n is undefined or not a finite number');return this;}if(n===0){console.warn('p5.Vector.prototype.div:','divide by 0');return this;}this.x/=n;this.y/=n;this.z/=n;return this;};/** * Calculates the magnitude (length) of the vector and returns the result as * a float (this is simply the equation sqrt(x*x + y*y + z*z).) * * @method mag * @return {Number} magnitude of the vector * @example * <div> * <code> * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'black'); * * noStroke(); * text('vector length: ' + v1.mag().toFixed(2), 10, 70, 90, 30); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> * <div class="norender"> * <code> * var v = createVector(20.0, 30.0, 40.0); * var m = v.mag(); * print(m); // Prints "53.85164807134504" * </code> * </div> */p5.Vector.prototype.mag=function mag(){return Math.sqrt(this.magSq());};/** * Calculates the squared magnitude of the vector and returns the result * as a float (this is simply the equation <em>(x*x + y*y + z*z)</em>.) * Faster if the real length is not required in the * case of comparing vectors, etc. * * @method magSq * @return {number} squared magnitude of the vector * @example * <div class="norender"> * <code> * // Static method * var v1 = createVector(6, 4, 2); * print(v1.magSq()); // Prints "56" * </code> * </div> * * <div> * <code> * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'black'); * * noStroke(); * text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.prototype.magSq=function magSq(){var x=this.x;var y=this.y;var z=this.z;return x*x+y*y+z*z;};/** * Calculates the dot product of two vectors. The version of the method * that computes the dot product of two independent vectors is a static * method. See the examples for more context. * * * @method dot * @param {Number} x x component of the vector * @param {Number} [y] y component of the vector * @param {Number} [z] z component of the vector * @return {Number} the dot product * * @example * <div class="norender"> * <code> * var v1 = createVector(1, 2, 3); * var v2 = createVector(2, 3, 4); * * print(v1.dot(v2)); // Prints "20" * </code> * </div> * * <div class="norender"> * <code> * //Static method * var v1 = createVector(1, 2, 3); * var v2 = createVector(3, 2, 1); * print(p5.Vector.dot(v1, v2)); // Prints "10" * </code> * </div> *//** * @method dot * @param {p5.Vector} value value component of the vector or a <a href="#/p5.Vector">p5.Vector</a> * @return {Number} */p5.Vector.prototype.dot=function dot(x,y,z){if(x instanceof p5.Vector){return this.dot(x.x,x.y,x.z);}return this.x*(x||0)+this.y*(y||0)+this.z*(z||0);};/** * Calculates and returns a vector composed of the cross product between * two vectors. Both the static and non static methods return a new <a href="#/p5.Vector">p5.Vector</a>. * See the examples for more context. * * @method cross * @param {p5.Vector} v <a href="#/p5.Vector">p5.Vector</a> to be crossed * @return {p5.Vector} <a href="#/p5.Vector">p5.Vector</a> composed of cross product * @example * <div class="norender"> * <code> * var v1 = createVector(1, 2, 3); * var v2 = createVector(1, 2, 3); * * v1.cross(v2); // v's components are [0, 0, 0] * </code> * </div> * * <div class="norender"> * <code> * // Static method * var v1 = createVector(1, 0, 0); * var v2 = createVector(0, 1, 0); * * var crossProduct = p5.Vector.cross(v1, v2); * // crossProduct has components [0, 0, 1] * print(crossProduct); * </code> * </div> */p5.Vector.prototype.cross=function cross(v){var x=this.y*v.z-this.z*v.y;var y=this.z*v.x-this.x*v.z;var z=this.x*v.y-this.y*v.x;if(this.p5){return new p5.Vector(this.p5,[x,y,z]);}else{return new p5.Vector(x,y,z);}};/** * Calculates the Euclidean distance between two points (considering a * point as a vector object). * * @method dist * @param {p5.Vector} v the x, y, and z coordinates of a <a href="#/p5.Vector">p5.Vector</a> * @return {Number} the distance * @example * <div class="norender"> * <code> * var v1 = createVector(1, 0, 0); * var v2 = createVector(0, 1, 0); * * var distance = v1.dist(v2); // distance is 1.4142... * print(distance); * </code> * </div> * * <div class="norender"> * <code> * // Static method * var v1 = createVector(1, 0, 0); * var v2 = createVector(0, 1, 0); * * var distance = p5.Vector.dist(v1, v2); * // distance is 1.4142... * print(distance); * </code> * </div> * * <div> * <code> * function draw() { * background(240); * * var v0 = createVector(0, 0); * * var v1 = createVector(70, 50); * drawArrow(v0, v1, 'red'); * * var v2 = createVector(mouseX, mouseY); * drawArrow(v0, v2, 'blue'); * * noStroke(); * text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.prototype.dist=function dist(v){return v.copy().sub(this).mag();};/** * Normalize the vector to length 1 (make it a unit vector). * * @method normalize * @return {p5.Vector} normalized <a href="#/p5.Vector">p5.Vector</a> * @example * <div class="norender"> * <code> * var v = createVector(10, 20, 2); * // v has components [10.0, 20.0, 2.0] * v.normalize(); * // v's components are set to * // [0.4454354, 0.8908708, 0.089087084] * </code> * </div> * <div> * <code> * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = createVector(mouseX - 50, mouseY - 50); * * drawArrow(v0, v1, 'red'); * v1.normalize(); * drawArrow(v0, v1.mult(35), 'blue'); * * noFill(); * ellipse(50, 50, 35 * 2); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.prototype.normalize=function normalize(){var len=this.mag();// here we multiply by the reciprocal instead of calling 'div()' // since div duplicates this zero check. if(len!==0)this.mult(1/len);return this;};/** * Limit the magnitude of this vector to the value used for the <b>max</b> * parameter. * * @method limit * @param {Number} max the maximum magnitude for the vector * @chainable * @example * <div class="norender"> * <code> * var v = createVector(10, 20, 2); * // v has components [10.0, 20.0, 2.0] * v.limit(5); * // v's components are set to * // [2.2271771, 4.4543543, 0.4454354] * </code> * </div> * <div> * <code> * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = createVector(mouseX - 50, mouseY - 50); * * drawArrow(v0, v1, 'red'); * drawArrow(v0, v1.limit(35), 'blue'); * * noFill(); * ellipse(50, 50, 35 * 2); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.prototype.limit=function limit(max){var mSq=this.magSq();if(mSq>max*max){this.div(Math.sqrt(mSq))//normalize it .mult(max);}return this;};/** * Set the magnitude of this vector to the value used for the <b>len</b> * parameter. * * @method setMag * @param {number} len the new length for this vector * @chainable * @example * <div class="norender"> * <code> * var v = createVector(10, 20, 2); * // v has components [10.0, 20.0, 2.0] * v.setMag(10); * // v's components are set to [6.0, 8.0, 0.0] * </code> * </div> * * <div> * <code> * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(50, 50); * * drawArrow(v0, v1, 'red'); * * var length = map(mouseX, 0, width, 0, 141, true); * v1.setMag(length); * drawArrow(v0, v1, 'blue'); * * noStroke(); * text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.prototype.setMag=function setMag(n){return this.normalize().mult(n);};/** * Calculate the angle of rotation for this vector (only 2D vectors) * * @method heading * @return {Number} the angle of rotation * @example * <div class = "norender"> * <code> * function setup() { * var v1 = createVector(30, 50); * print(v1.heading()); // 1.0303768265243125 * * v1 = createVector(40, 50); * print(v1.heading()); // 0.8960553845713439 * * v1 = createVector(30, 70); * print(v1.heading()); // 1.1659045405098132 * } * </code> * </div> * * <div> * <code> * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = createVector(mouseX - 50, mouseY - 50); * * drawArrow(v0, v1, 'black'); * * var myHeading = v1.heading(); * noStroke(); * text( * 'vector heading: ' + * myHeading.toFixed(2) + * ' radians or ' + * degrees(myHeading).toFixed(2) + * ' degrees', * 10, * 50, * 90, * 50 * ); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.prototype.heading=function heading(){var h=Math.atan2(this.y,this.x);if(this.p5)return this.p5._fromRadians(h);return h;};/** * Rotate the vector by an angle (only 2D vectors), magnitude remains the * same * * @method rotate * @param {number} angle the angle of rotation * @chainable * @example * <div class="norender"> * <code> * var v = createVector(10.0, 20.0); * // v has components [10.0, 20.0, 0.0] * v.rotate(HALF_PI); * // v's components are set to [-20.0, 9.999999, 0.0] * </code> * </div> * * <div> * <code> * var angle = 0; * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = createVector(50, 0); * * drawArrow(v0, v1.rotate(angle), 'black'); * angle += 0.01; * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.prototype.rotate=function rotate(a){var newHeading=this.heading()+a;if(this.p5)newHeading=this.p5._toRadians(newHeading);var mag=this.mag();this.x=Math.cos(newHeading)*mag;this.y=Math.sin(newHeading)*mag;return this;};/** * Calculates and returns the angle (in radians) between two vectors. * @method angleBetween * @param {p5.Vector} the x, y, and z components of a <a href="#/p5.Vector">p5.Vector</a> * @return {Number} the angle between (in radians) * @example * <div class="norender"> * <code> * var v1 = createVector(1, 0, 0); * var v2 = createVector(0, 1, 0); * * var angle = v1.angleBetween(v2); * // angle is PI/2 * print(angle); * </code> * </div> * * <div> * <code> * function draw() { * background(240); * var v0 = createVector(50, 50); * * var v1 = createVector(50, 0); * drawArrow(v0, v1, 'red'); * * var v2 = createVector(mouseX - 50, mouseY - 50); * drawArrow(v0, v2, 'blue'); * * var angleBetween = v1.angleBetween(v2); * noStroke(); * text( * 'angle between: ' + * angleBetween.toFixed(2) + * ' radians or ' + * degrees(angleBetween).toFixed(2) + * ' degrees', * 10, * 50, * 90, * 50 * ); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.prototype.angleBetween=function angleBetween(v){var dotmagmag=this.dot(v)/(this.mag()*v.mag());// Mathematically speaking: the dotmagmag variable will be between -1 and 1 // inclusive. Practically though it could be slightly outside this range due // to floating-point rounding issues. This can make Math.acos return NaN. // // Solution: we'll clamp the value to the -1,1 range var angle=Math.acos(Math.min(1,Math.max(-1,dotmagmag)));if(this.p5)return this.p5._fromRadians(angle);return angle;};/** * Linear interpolate the vector to another vector * * @method lerp * @param {Number} x the x component * @param {Number} y the y component * @param {Number} z the z component * @param {Number} amt the amount of interpolation; some value between 0.0 * (old vector) and 1.0 (new vector). 0.9 is very near * the new vector. 0.5 is halfway in between. * @chainable * * @example * <div class="norender"> * <code> * var v = createVector(1, 1, 0); * * v.lerp(3, 3, 0, 0.5); // v now has components [2,2,0] * </code> * </div> * * <div class="norender"> * <code> * var v1 = createVector(0, 0, 0); * var v2 = createVector(100, 100, 0); * * var v3 = p5.Vector.lerp(v1, v2, 0.5); * // v3 has components [50,50,0] * print(v3); * </code> * </div> * * <div> * <code> * var step = 0.01; * var amount = 0; * * function draw() { * background(240); * var v0 = createVector(0, 0); * * var v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'red'); * * var v2 = createVector(90, 90); * drawArrow(v0, v2, 'blue'); * * if (amount > 1 || amount < 0) { * step *= -1; * } * amount += step; * var v3 = p5.Vector.lerp(v1, v2, amount); * * drawArrow(v0, v3, 'purple'); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> *//** * @method lerp * @param {p5.Vector} v the <a href="#/p5.Vector">p5.Vector</a> to lerp to * @param {Number} amt * @chainable */p5.Vector.prototype.lerp=function lerp(x,y,z,amt){if(x instanceof p5.Vector){return this.lerp(x.x,x.y,x.z,y);}this.x+=(x-this.x)*amt||0;this.y+=(y-this.y)*amt||0;this.z+=(z-this.z)*amt||0;return this;};/** * Return a representation of this vector as a float array. This is only * for temporary use. If used in any other fashion, the contents should be * copied by using the <b>p5.Vector.<a href="#/p5.Vector/copy">copy()</a></b> method to copy into your own * array. * * @method array * @return {Number[]} an Array with the 3 values * @example * <div class = "norender"> * <code> * function setup() { * var v = createVector(20, 30); * print(v.array()); // Prints : Array [20, 30, 0] * } * </code> * </div> * * <div class="norender"> * <code> * var v = createVector(10.0, 20.0, 30.0); * var f = v.array(); * print(f[0]); // Prints "10.0" * print(f[1]); // Prints "20.0" * print(f[2]); // Prints "30.0" * </code> * </div> */p5.Vector.prototype.array=function array(){return[this.x||0,this.y||0,this.z||0];};/** * Equality check against a <a href="#/p5.Vector">p5.Vector</a> * * @method equals * @param {Number} [x] the x component of the vector * @param {Number} [y] the y component of the vector * @param {Number} [z] the z component of the vector * @return {Boolean} whether the vectors are equals * @example * <div class = "norender"> * <code> * var v1 = createVector(5, 10, 20); * var v2 = createVector(5, 10, 20); * var v3 = createVector(13, 10, 19); * * print(v1.equals(v2.x, v2.y, v2.z)); // true * print(v1.equals(v3.x, v3.y, v3.z)); // false * </code> * </div> * * <div class="norender"> * <code> * var v1 = createVector(10.0, 20.0, 30.0); * var v2 = createVector(10.0, 20.0, 30.0); * var v3 = createVector(0.0, 0.0, 0.0); * print(v1.equals(v2)); // true * print(v1.equals(v3)); // false * </code> * </div> *//** * @method equals * @param {p5.Vector|Array} value the vector to compare * @return {Boolean} */p5.Vector.prototype.equals=function equals(x,y,z){var a,b,c;if(x instanceof p5.Vector){a=x.x||0;b=x.y||0;c=x.z||0;}else if(x instanceof Array){a=x[0]||0;b=x[1]||0;c=x[2]||0;}else{a=x||0;b=y||0;c=z||0;}return this.x===a&&this.y===b&&this.z===c;};// Static Methods /** * Make a new 2D vector from an angle * * @method fromAngle * @static * @param {Number} angle the desired angle, in radians * @param {Number} [length] the length of the new vector (defaults to 1) * @return {p5.Vector} the new <a href="#/p5.Vector">p5.Vector</a> object * @example * <div> * <code> * function draw() { * background(200); * * // Create a variable, proportional to the mouseX, * // varying from 0-360, to represent an angle in degrees. * angleMode(DEGREES); * var myDegrees = map(mouseX, 0, width, 0, 360); * * // Display that variable in an onscreen text. * // (Note the nfc() function to truncate additional decimal places, * // and the "\xB0" character for the degree symbol.) * var readout = 'angle = ' + nfc(myDegrees, 1) + '\xB0'; * noStroke(); * fill(0); * text(readout, 5, 15); * * // Create a p5.Vector using the fromAngle function, * // and extract its x and y components. * var v = p5.Vector.fromAngle(radians(myDegrees), 30); * var vx = v.x; * var vy = v.y; * * push(); * translate(width / 2, height / 2); * noFill(); * stroke(150); * line(0, 0, 30, 0); * stroke(0); * line(0, 0, vx, vy); * pop(); * } * </code> * </div> */p5.Vector.fromAngle=function fromAngle(angle,length){if(typeof length==='undefined'){length=1;}return new p5.Vector(length*Math.cos(angle),length*Math.sin(angle),0);};/** * Make a new 3D vector from a pair of ISO spherical angles * * @method fromAngles * @static * @param {Number} theta the polar angle, in radians (zero is up) * @param {Number} phi the azimuthal angle, in radians * (zero is out of the screen) * @param {Number} [length] the length of the new vector (defaults to 1) * @return {p5.Vector} the new <a href="#/p5.Vector">p5.Vector</a> object * @example * <div modernizr='webgl'> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * fill(255); * noStroke(); * } * function draw() { * background(255); * * var t = millis() / 1000; * * // add three point lights * pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100)); * pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100)); * pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100)); * * sphere(35); * } * </code> * </div> */p5.Vector.fromAngles=function(theta,phi,length){if(typeof length==='undefined'){length=1;}var cosPhi=Math.cos(phi);var sinPhi=Math.sin(phi);var cosTheta=Math.cos(theta);var sinTheta=Math.sin(theta);return new p5.Vector(length*sinTheta*sinPhi,-length*cosTheta,length*sinTheta*cosPhi);};/** * Make a new 2D unit vector from a random angle * * @method random2D * @static * @return {p5.Vector} the new <a href="#/p5.Vector">p5.Vector</a> object * @example * <div class="norender"> * <code> * var v = p5.Vector.random2D(); * // May make v's attributes something like: * // [0.61554617, -0.51195765, 0.0] or * // [-0.4695841, -0.14366731, 0.0] or * // [0.6091097, -0.22805278, 0.0] * print(v); * </code> * </div> * * <div> * <code> * function setup() { * frameRate(1); * } * * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = p5.Vector.random2D(); * drawArrow(v0, v1.mult(50), 'black'); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * </code> * </div> */p5.Vector.random2D=function random2D(){return this.fromAngle(Math.random()*constants.TWO_PI);};/** * Make a new random 3D unit vector. * * @method random3D * @static * @return {p5.Vector} the new <a href="#/p5.Vector">p5.Vector</a> object * @example * <div class="norender"> * <code> * var v = p5.Vector.random3D(); * // May make v's attributes something like: * // [0.61554617, -0.51195765, 0.599168] or * // [-0.4695841, -0.14366731, -0.8711202] or * // [0.6091097, -0.22805278, -0.7595902] * print(v); * </code> * </div> */p5.Vector.random3D=function random3D(){var angle=Math.random()*constants.TWO_PI;var vz=Math.random()*2-1;var vzBase=Math.sqrt(1-vz*vz);var vx=vzBase*Math.cos(angle);var vy=vzBase*Math.sin(angle);return new p5.Vector(vx,vy,vz);};// Adds two vectors together and returns a new one. /** * @method add * @static * @param {p5.Vector} v1 a <a href="#/p5.Vector">p5.Vector</a> to add * @param {p5.Vector} v2 a <a href="#/p5.Vector">p5.Vector</a> to add * @param {p5.Vector} target the vector to receive the result *//** * @method add * @static * @param {p5.Vector} v1 * @param {p5.Vector} v2 * @return {p5.Vector} the resulting <a href="#/p5.Vector">p5.Vector</a> * */p5.Vector.add=function add(v1,v2,target){if(!target){target=v1.copy();}else{target.set(v1);}target.add(v2);return target;};/* * Subtracts one <a href="#/p5.Vector">p5.Vector</a> from another and returns a new one. The second * vector (v2) is subtracted from the first (v1), resulting in v1-v2. *//** * @method sub * @static * @param {p5.Vector} v1 a <a href="#/p5.Vector">p5.Vector</a> to subtract from * @param {p5.Vector} v2 a <a href="#/p5.Vector">p5.Vector</a> to subtract * @param {p5.Vector} target if undefined a new vector will be created *//** * @method sub * @static * @param {p5.Vector} v1 * @param {p5.Vector} v2 * @return {p5.Vector} the resulting <a href="#/p5.Vector">p5.Vector</a> */p5.Vector.sub=function sub(v1,v2,target){if(!target){target=v1.copy();}else{target.set(v1);}target.sub(v2);return target;};/** * Multiplies a vector by a scalar and returns a new vector. *//** * @method mult * @static * @param {p5.Vector} v the vector to multiply * @param {Number} n * @param {p5.Vector} target if undefined a new vector will be created *//** * @method mult * @static * @param {p5.Vector} v * @param {Number} n * @return {p5.Vector} the resulting new <a href="#/p5.Vector">p5.Vector</a> */p5.Vector.mult=function mult(v,n,target){if(!target){target=v.copy();}else{target.set(v);}target.mult(n);return target;};/** * Divides a vector by a scalar and returns a new vector. *//** * @method div * @static * @param {p5.Vector} v the vector to divide * @param {Number} n * @param {p5.Vector} target if undefined a new vector will be created *//** * @method div * @static * @param {p5.Vector} v * @param {Number} n * @return {p5.Vector} the resulting new <a href="#/p5.Vector">p5.Vector</a> */p5.Vector.div=function div(v,n,target){if(!target){target=v.copy();}else{target.set(v);}target.div(n);return target;};/** * Calculates the dot product of two vectors. *//** * @method dot * @static * @param {p5.Vector} v1 the first <a href="#/p5.Vector">p5.Vector</a> * @param {p5.Vector} v2 the second <a href="#/p5.Vector">p5.Vector</a> * @return {Number} the dot product */p5.Vector.dot=function dot(v1,v2){return v1.dot(v2);};/** * Calculates the cross product of two vectors. *//** * @method cross * @static * @param {p5.Vector} v1 the first <a href="#/p5.Vector">p5.Vector</a> * @param {p5.Vector} v2 the second <a href="#/p5.Vector">p5.Vector</a> * @return {Number} the cross product */p5.Vector.cross=function cross(v1,v2){return v1.cross(v2);};/** * Calculates the Euclidean distance between two points (considering a * point as a vector object). *//** * @method dist * @static * @param {p5.Vector} v1 the first <a href="#/p5.Vector">p5.Vector</a> * @param {p5.Vector} v2 the second <a href="#/p5.Vector">p5.Vector</a> * @return {Number} the distance */p5.Vector.dist=function dist(v1,v2){return v1.dist(v2);};/** * Linear interpolate a vector to another vector and return the result as a * new vector. *//** * @method lerp * @static * @param {p5.Vector} v1 * @param {p5.Vector} v2 * @param {Number} amt * @param {p5.Vector} target if undefined a new vector will be created *//** * @method lerp * @static * @param {p5.Vector} v1 * @param {p5.Vector} v2 * @param {Number} amt * @return {Number} the lerped value */p5.Vector.lerp=function lerp(v1,v2,amt,target){if(!target){target=v1.copy();}else{target.set(v1);}target.lerp(v2,amt);return target;};/** * @method mag * @param {p5.Vector} vecT the vector to return the magnitude of * @return {Number} the magnitude of vecT * @static */p5.Vector.mag=function mag(vecT){var x=vecT.x,y=vecT.y,z=vecT.z;var magSq=x*x+y*y+z*z;return Math.sqrt(magSq);};module.exports=p5.Vector;},{"../core/constants":19,"../core/main":25}],56:[function(_dereq_,module,exports){/** * @module Math * @submodule Random * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');var seeded=false;var previous=false;var y2=0;// Linear Congruential Generator // Variant of a Lehman Generator var lcg=function(){// Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes // m is basically chosen to be large (as it is the max period) // and for its relationships to a and c var m=4294967296,// a - 1 should be divisible by m's prime factors a=1664525,// c and m should be co-prime c=1013904223,seed,z;return{setSeed:function setSeed(val){// pick a random seed if val is undefined or null // the >>> 0 casts the seed to an unsigned 32-bit integer z=seed=(val==null?Math.random()*m:val)>>>0;},getSeed:function getSeed(){return seed;},rand:function rand(){// define the recurrence relationship z=(a*z+c)%m;// return a float in [0, 1) // if z = m then z / m = 0 therefore (z % m) / m < 1 always return z/m;}};}();/** * Sets the seed value for <a href="#/p5/random">random()</a>. * * By default, <a href="#/p5/random">random()</a> produces different results each time the program * is run. Set the seed parameter to a constant to return the same * pseudo-random numbers each time the software is run. * * @method randomSeed * @param {Number} seed the seed value * @example * <div> * <code> * randomSeed(99); * for (var i = 0; i < 100; i++) { * var r = random(0, 255); * stroke(r); * line(i, 0, i, 100); * } * </code> * </div> * * @alt * many vertical lines drawn in white, black or grey. * */p5.prototype.randomSeed=function(seed){lcg.setSeed(seed);seeded=true;previous=false;};/** * Return a random floating-point number. * * Takes either 0, 1 or 2 arguments. * * If no argument is given, returns a random number from 0 * up to (but not including) 1. * * If one argument is given and it is a number, returns a random number from 0 * up to (but not including) the number. * * If one argument is given and it is an array, returns a random element from * that array. * * If two arguments are given, returns a random number from the * first argument up to (but not including) the second argument. * * @method random * @param {Number} [min] the lower bound (inclusive) * @param {Number} [max] the upper bound (exclusive) * @return {Number} the random number * @example * <div> * <code> * for (var i = 0; i < 100; i++) { * var r = random(50); * stroke(r * 5); * line(50, i, 50 + r, i); * } * </code> * </div> * <div> * <code> * for (var i = 0; i < 100; i++) { * var r = random(-50, 50); * line(50, i, 50 + r, i); * } * </code> * </div> * <div> * <code> * // Get a random element from an array using the random(Array) syntax * var words = ['apple', 'bear', 'cat', 'dog']; * var word = random(words); // select random word * text(word, 10, 50); // draw the word * </code> * </div> * * @alt * 100 horizontal lines from center canvas to right. size+fill change each time * 100 horizontal lines from center of canvas. height & side change each render * word displayed at random. Either apple, bear, cat, or dog * *//** * @method random * @param {Array} choices the array to choose from * @return {*} the random element from the array * @example */p5.prototype.random=function(min,max){var rand;if(seeded){rand=lcg.rand();}else{rand=Math.random();}if(typeof min==='undefined'){return rand;}else if(typeof max==='undefined'){if(min instanceof Array){return min[Math.floor(rand*min.length)];}else{return rand*min;}}else{if(min>max){var tmp=min;min=max;max=tmp;}return rand*(max-min)+min;}};/** * * Returns a random number fitting a Gaussian, or * normal, distribution. There is theoretically no minimum or maximum * value that <a href="#/p5/randomGaussian">randomGaussian()</a> might return. Rather, there is * just a very low probability that values far from the mean will be * returned; and a higher probability that numbers near the mean will * be returned. * <br><br> * Takes either 0, 1 or 2 arguments.<br> * If no args, returns a mean of 0 and standard deviation of 1.<br> * If one arg, that arg is the mean (standard deviation is 1).<br> * If two args, first is mean, second is standard deviation. * * @method randomGaussian * @param {Number} mean the mean * @param {Number} sd the standard deviation * @return {Number} the random number * @example * <div> * <code> * for (var y = 0; y < 100; y++) { * var x = randomGaussian(50, 15); * line(50, y, x, y); * } * </code> * </div> * <div> * <code> * var distribution = new Array(360); * * function setup() { * createCanvas(100, 100); * for (var i = 0; i < distribution.length; i++) { * distribution[i] = floor(randomGaussian(0, 15)); * } * } * * function draw() { * background(204); * * translate(width / 2, width / 2); * * for (var i = 0; i < distribution.length; i++) { * rotate(TWO_PI / distribution.length); * stroke(0); * var dist = abs(distribution[i]); * line(0, 0, dist, 0); * } * } * </code> * </div> * @alt * 100 horizontal lines from center of canvas. height & side change each render * black lines radiate from center of canvas. size determined each render */p5.prototype.randomGaussian=function(mean,sd){var y1,x1,x2,w;if(previous){y1=y2;previous=false;}else{do{x1=this.random(2)-1;x2=this.random(2)-1;w=x1*x1+x2*x2;}while(w>=1);w=Math.sqrt(-2*Math.log(w)/w);y1=x1*w;y2=x2*w;previous=true;}var m=mean||0;var s=sd||1;return y1*s+m;};module.exports=p5;},{"../core/main":25}],57:[function(_dereq_,module,exports){/** * @module Math * @submodule Trigonometry * @for p5 * @requires core * @requires constants */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');/* * all DEGREES/RADIANS conversion should be done in the p5 instance * if possible, using the p5._toRadians(), p5._fromRadians() methods. */p5.prototype._angleMode=constants.RADIANS;/** * The inverse of <a href="#/p5/cos">cos()</a>, returns the arc cosine of a value. This function * expects the values in the range of -1 to 1 and values are returned in * the range 0 to PI (3.1415927). * * @method acos * @param {Number} value the value whose arc cosine is to be returned * @return {Number} the arc cosine of the given value * * @example * <div class= “norender"> * <code> * var a = PI; * var c = cos(a); * var ac = acos(c); * // Prints: "3.1415927 : -1.0 : 3.1415927" * print(a + ' : ' + c + ' : ' + ac); * </code> * </div> * * <div class= “norender"> * <code> * var a = PI + PI / 4.0; * var c = cos(a); * var ac = acos(c); * // Prints: "3.926991 : -0.70710665 : 2.3561943" * print(a + ' : ' + c + ' : ' + ac); * </code> * </div> */p5.prototype.acos=function(ratio){return this._fromRadians(Math.acos(ratio));};/** * The inverse of <a href="#/p5/sin">sin()</a>, returns the arc sine of a value. This function * expects the values in the range of -1 to 1 and values are returned * in the range -PI/2 to PI/2. * * @method asin * @param {Number} value the value whose arc sine is to be returned * @return {Number} the arc sine of the given value * * @example * <div class= “norender"> * <code> * var a = PI + PI / 3; * var s = sin(a); * var as = asin(s); * // Prints: "1.0471976 : 0.86602545 : 1.0471976" * print(a + ' : ' + s + ' : ' + as); * </code> * </div> * * <div class= “norender"> * <code> * var a = PI + PI / 3.0; * var s = sin(a); * var as = asin(s); * // Prints: "4.1887903 : -0.86602545 : -1.0471976" * print(a + ' : ' + s + ' : ' + as); * </code> * </div> * */p5.prototype.asin=function(ratio){return this._fromRadians(Math.asin(ratio));};/** * The inverse of <a href="#/p5/tan">tan()</a>, returns the arc tangent of a value. This function * expects the values in the range of -Infinity to Infinity (exclusive) and * values are returned in the range -PI/2 to PI/2. * * @method atan * @param {Number} value the value whose arc tangent is to be returned * @return {Number} the arc tangent of the given value * * @example * <div class= “norender"> * <code> * var a = PI + PI / 3; * var t = tan(a); * var at = atan(t); * // Prints: "1.0471976 : 1.7320509 : 1.0471976" * print(a + ' : ' + t + ' : ' + at); * </code> * </div> * * <div class= “norender"> * <code> * var a = PI + PI / 3.0; * var t = tan(a); * var at = atan(t); * // Prints: "4.1887903 : 1.7320513 : 1.0471977" * print(a + ' : ' + t + ' : ' + at); * </code> * </div> * */p5.prototype.atan=function(ratio){return this._fromRadians(Math.atan(ratio));};/** * Calculates the angle (in radians) from a specified point to the coordinate * origin as measured from the positive x-axis. Values are returned as a * float in the range from PI to -PI. The atan2<a href="#/p5/">()</a> function is most often used * for orienting geometry to the position of the cursor. * <br><br> * Note: The y-coordinate of the point is the first parameter, and the * x-coordinate is the second parameter, due the the structure of calculating * the tangent. * * @method atan2 * @param {Number} y y-coordinate of the point * @param {Number} x x-coordinate of the point * @return {Number} the arc tangent of the given point * * @example * <div> * <code> * function draw() { * background(204); * translate(width / 2, height / 2); * var a = atan2(mouseY - height / 2, mouseX - width / 2); * rotate(a); * rect(-30, -5, 60, 10); * } * </code> * </div> * * @alt * 60 by 10 rect at center of canvas rotates with mouse movements * */p5.prototype.atan2=function(y,x){return this._fromRadians(Math.atan2(y,x));};/** * Calculates the cosine of an angle. This function takes into account the * current <a href="#/p5/angleMode">angleMode</a>. Values are returned in the range -1 to 1. * * @method cos * @param {Number} angle the angle * @return {Number} the cosine of the angle * * @example * <div> * <code> * var a = 0.0; * var inc = TWO_PI / 25.0; * for (var i = 0; i < 25; i++) { * line(i * 4, 50, i * 4, 50 + cos(a) * 40.0); * a = a + inc; * } * </code> * </div> * * @alt * vertical black lines form wave patterns, extend-down on left and right side * */p5.prototype.cos=function(angle){return Math.cos(this._toRadians(angle));};/** * Calculates the sine of an angle. This function takes into account the * current <a href="#/p5/angleMode">angleMode</a>. Values are returned in the range -1 to 1. * * @method sin * @param {Number} angle the angle * @return {Number} the sine of the angle * * @example * <div> * <code> * var a = 0.0; * var inc = TWO_PI / 25.0; * for (var i = 0; i < 25; i++) { * line(i * 4, 50, i * 4, 50 + sin(a) * 40.0); * a = a + inc; * } * </code> * </div> * * @alt * vertical black lines extend down and up from center to form wave pattern * */p5.prototype.sin=function(angle){return Math.sin(this._toRadians(angle));};/** * Calculates the tangent of an angle. This function takes into account * the current <a href="#/p5/angleMode">angleMode</a>. Values are returned in the range -1 to 1. * * @method tan * @param {Number} angle the angle * @return {Number} the tangent of the angle * * @example * <div> * <code> * var a = 0.0; * var inc = TWO_PI / 50.0; * for (var i = 0; i < 100; i = i + 2) { * line(i, 50, i, 50 + tan(a) * 2.0); * a = a + inc; * } * </code> * * * @alt * vertical black lines end down and up from center to form spike pattern * */p5.prototype.tan=function(angle){return Math.tan(this._toRadians(angle));};/** * Converts a radian measurement to its corresponding value in degrees. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90° = PI/2 = 1.5707964. This function does not take into account the * current <a href="#/p5/angleMode">angleMode</a>. * * @method degrees * @param {Number} radians the radians value to convert to degrees * @return {Number} the converted angle * * * @example * <div class= “norender"> * <code> * var rad = PI / 4; * var deg = degrees(rad); * print(rad + ' radians is ' + deg + ' degrees'); * // Prints: 0.7853981633974483 radians is 45 degrees * </code> * </div> * */p5.prototype.degrees=function(angle){return angle*constants.RAD_TO_DEG;};/** * Converts a degree measurement to its corresponding value in radians. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90° = PI/2 = 1.5707964. This function does not take into account the * current <a href="#/p5/angleMode">angleMode</a>. * * @method radians * @param {Number} degrees the degree value to convert to radians * @return {Number} the converted angle * * @example * <div class= “norender"> * <code> * var deg = 45.0; * var rad = radians(deg); * print(deg + ' degrees is ' + rad + ' radians'); * // Prints: 45 degrees is 0.7853981633974483 radians * </code> * </div> */p5.prototype.radians=function(angle){return angle*constants.DEG_TO_RAD;};/** * Sets the current mode of p5 to given mode. Default mode is RADIANS. * * @method angleMode * @param {Constant} mode either RADIANS or DEGREES * * @example * <div> * <code> * function draw() { * background(204); * angleMode(DEGREES); // Change the mode to DEGREES * var a = atan2(mouseY - height / 2, mouseX - width / 2); * translate(width / 2, height / 2); * push(); * rotate(a); * rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees * pop(); * angleMode(RADIANS); // Change the mode to RADIANS * rotate(a); // var a stays the same * rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians * } * </code> * </div> * * @alt * 40 by 10 rect in center rotates with mouse moves. 20 by 10 rect moves faster. * * */p5.prototype.angleMode=function(mode){if(mode===constants.DEGREES||mode===constants.RADIANS){this._angleMode=mode;}};/** * converts angles from the current angleMode to RADIANS * * @method _toRadians * @private * @param {Number} angle * @returns {Number} */p5.prototype._toRadians=function(angle){if(this._angleMode===constants.DEGREES){return angle*constants.DEG_TO_RAD;}return angle;};/** * converts angles from the current angleMode to DEGREES * * @method _toDegrees * @private * @param {Number} angle * @returns {Number} */p5.prototype._toDegrees=function(angle){if(this._angleMode===constants.RADIANS){return angle*constants.RAD_TO_DEG;}return angle;};/** * converts angles from RADIANS into the current angleMode * * @method _fromRadians * @private * @param {Number} angle * @returns {Number} */p5.prototype._fromRadians=function(angle){if(this._angleMode===constants.DEGREES){return angle*constants.RAD_TO_DEG;}return angle;};module.exports=p5;},{"../core/constants":19,"../core/main":25}],58:[function(_dereq_,module,exports){/** * @module Typography * @submodule Attributes * @for p5 * @requires core * @requires constants */'use strict';var p5=_dereq_('../core/main');/** * Sets the current alignment for drawing text. Accepts two * arguments: horizAlign (LEFT, CENTER, or RIGHT) and * vertAlign (TOP, BOTTOM, CENTER, or BASELINE). * * The horizAlign parameter is in reference to the x value * of the <a href="#/p5/text">text()</a> function, while the vertAlign parameter is * in reference to the y value. * * So if you write textAlign(LEFT), you are aligning the left * edge of your text to the x value you give in <a href="#/p5/text">text()</a>. If you * write textAlign(RIGHT, TOP), you are aligning the right edge * of your text to the x value and the top of edge of the text * to the y value. * * @method textAlign * @param {Constant} horizAlign horizontal alignment, either LEFT, * CENTER, or RIGHT * @param {Constant} [vertAlign] vertical alignment, either TOP, * BOTTOM, CENTER, or BASELINE * @chainable * @example * <div> * <code> * textSize(16); * textAlign(RIGHT); * text('ABCD', 50, 30); * textAlign(CENTER); * text('EFGH', 50, 50); * textAlign(LEFT); * text('IJKL', 50, 70); * </code> * </div> * * <div> * <code> * textSize(16); * strokeWeight(0.5); * * line(0, 12, width, 12); * textAlign(CENTER, TOP); * text('TOP', 0, 12, width); * * line(0, 37, width, 37); * textAlign(CENTER, CENTER); * text('CENTER', 0, 37, width); * * line(0, 62, width, 62); * textAlign(CENTER, BASELINE); * text('BASELINE', 0, 62, width); * * line(0, 87, width, 87); * textAlign(CENTER, BOTTOM); * text('BOTTOM', 0, 87, width); * </code> * </div> * * @alt *Letters ABCD displayed at top right, EFGH at center and IJKL at bottom left. * The names of the four vertical alignments rendered each showing that alignment's placement relative to a horizontal line. * *//** * @method textAlign * @return {Object} */p5.prototype.textAlign=function(horizAlign,vertAlign){p5._validateParameters('textAlign',arguments);return this._renderer.textAlign.apply(this._renderer,arguments);};/** * Sets/gets the spacing, in pixels, between lines of text. This * setting will be used in all subsequent calls to the <a href="#/p5/text">text()</a> function. * * @method textLeading * @param {Number} leading the size in pixels for spacing between lines * @chainable * * @example * <div> * <code> * // Text to display. The "\n" is a "new line" character * var lines = 'L1\nL2\nL3'; * textSize(12); * * textLeading(10); // Set leading to 10 * text(lines, 10, 25); * * textLeading(20); // Set leading to 20 * text(lines, 40, 25); * * textLeading(30); // Set leading to 30 * text(lines, 70, 25); * </code> * </div> * * @alt *set L1 L2 & L3 displayed vertically 3 times. spacing increases for each set *//** * @method textLeading * @return {Number} */p5.prototype.textLeading=function(theLeading){p5._validateParameters('textLeading',arguments);return this._renderer.textLeading.apply(this._renderer,arguments);};/** * Sets/gets the current font size. This size will be used in all subsequent * calls to the <a href="#/p5/text">text()</a> function. Font size is measured in pixels. * * @method textSize * @param {Number} theSize the size of the letters in units of pixels * @chainable * * @example * <div> * <code> * textSize(12); * text('Font Size 12', 10, 30); * textSize(14); * text('Font Size 14', 10, 60); * textSize(16); * text('Font Size 16', 10, 90); * </code> * </div> * * @alt *Font Size 12 displayed small, Font Size 14 medium & Font Size 16 large *//** * @method textSize * @return {Number} */p5.prototype.textSize=function(theSize){p5._validateParameters('textSize',arguments);return this._renderer.textSize.apply(this._renderer,arguments);};/** * Sets/gets the style of the text for system fonts to NORMAL, ITALIC, or BOLD. * Note: this may be is overridden by CSS styling. For non-system fonts * (opentype, truetype, etc.) please load styled fonts instead. * * @method textStyle * @param {Constant} theStyle styling for text, either NORMAL, * ITALIC, or BOLD * @chainable * @example * <div> * <code> * strokeWeight(0); * textSize(12); * textStyle(NORMAL); * text('Font Style Normal', 10, 30); * textStyle(ITALIC); * text('Font Style Italic', 10, 60); * textStyle(BOLD); * text('Font Style Bold', 10, 90); * </code> * </div> * * @alt *words Font Style Normal displayed normally, Italic in italic and bold in bold *//** * @method textStyle * @return {String} */p5.prototype.textStyle=function(theStyle){p5._validateParameters('textStyle',arguments);return this._renderer.textStyle.apply(this._renderer,arguments);};/** * Calculates and returns the width of any character or text string. * * @method textWidth * @param {String} theText the String of characters to measure * @return {Number} * @example * <div> * <code> * textSize(28); * * var aChar = 'P'; * var cWidth = textWidth(aChar); * text(aChar, 0, 40); * line(cWidth, 0, cWidth, 50); * * var aString = 'p5.js'; * var sWidth = textWidth(aString); * text(aString, 0, 85); * line(sWidth, 50, sWidth, 100); * </code> * </div> * * @alt *Letter P and p5.js are displayed with vertical lines at end. P is wide * */p5.prototype.textWidth=function(theText){p5._validateParameters('textWidth',arguments);if(theText.length===0){return 0;}return this._renderer.textWidth.apply(this._renderer,arguments);};/** * Returns the ascent of the current font at its current size. The ascent * represents the distance, in pixels, of the tallest character above * the baseline. * @method textAscent * @return {Number} * @example * <div> * <code> * var base = height * 0.75; * var scalar = 0.8; // Different for each font * * textSize(32); // Set initial text size * var asc = textAscent() * scalar; // Calc ascent * line(0, base - asc, width, base - asc); * text('dp', 0, base); // Draw text on baseline * * textSize(64); // Increase text size * asc = textAscent() * scalar; // Recalc ascent * line(40, base - asc, width, base - asc); * text('dp', 40, base); // Draw text on baseline * </code> * </div> */p5.prototype.textAscent=function(){p5._validateParameters('textAscent',arguments);return this._renderer.textAscent();};/** * Returns the descent of the current font at its current size. The descent * represents the distance, in pixels, of the character with the longest * descender below the baseline. * @method textDescent * @return {Number} * @example * <div> * <code> * var base = height * 0.75; * var scalar = 0.8; // Different for each font * * textSize(32); // Set initial text size * var desc = textDescent() * scalar; // Calc ascent * line(0, base + desc, width, base + desc); * text('dp', 0, base); // Draw text on baseline * * textSize(64); // Increase text size * desc = textDescent() * scalar; // Recalc ascent * line(40, base + desc, width, base + desc); * text('dp', 40, base); // Draw text on baseline * </code> * </div> */p5.prototype.textDescent=function(){p5._validateParameters('textDescent',arguments);return this._renderer.textDescent();};/** * Helper function to measure ascent and descent. */p5.prototype._updateTextMetrics=function(){return this._renderer._updateTextMetrics();};module.exports=p5;},{"../core/main":25}],59:[function(_dereq_,module,exports){/** * @module Typography * @submodule Loading & Displaying * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');var opentype=_dereq_('opentype.js');_dereq_('../core/error_helpers');/** * Loads an opentype font file (.otf, .ttf) from a file or a URL, * and returns a PFont Object. This method is asynchronous, * meaning it may not finish before the next line in your sketch * is executed. * <br><br> * The path to the font should be relative to the HTML file * that links in your sketch. Loading an from a URL or other * remote location may be blocked due to your browser's built-in * security. * * @method loadFont * @param {String} path name of the file or url to load * @param {Function} [callback] function to be executed after * <a href="#/p5/loadFont">loadFont()</a> completes * @param {Function} [onError] function to be executed if * an error occurs * @return {p5.Font} <a href="#/p5.Font">p5.Font</a> object * @example * * <p>Calling loadFont() inside <a href="#/p5/preload">preload()</a> guarantees that the load * operation will have completed before <a href="#/p5/setup">setup()</a> and <a href="#/p5/draw">draw()</a> are called.</p> * * <div><code> * var myFont; * function preload() { * myFont = loadFont('assets/AvenirNextLTPro-Demi.otf'); * } * * function setup() { * fill('#ED225D'); * textFont(myFont); * textSize(36); * text('p5*js', 10, 50); * } * </code></div> * * Outside of <a href="#/p5/preload">preload()</a>, you may supply a callback function to handle the * object: * * <div><code> * function setup() { * loadFont('assets/AvenirNextLTPro-Demi.otf', drawText); * } * * function drawText(font) { * fill('#ED225D'); * textFont(font, 36); * text('p5*js', 10, 50); * } * </code></div> * * <p>You can also use the string name of the font to style other HTML * elements.</p> * * <div><code> * function preload() { * loadFont('assets/Avenir.otf'); * } * * function setup() { * var myDiv = createDiv('hello there'); * myDiv.style('font-family', 'Avenir'); * } * </code></div> * * @alt * p5*js in p5's theme dark pink * p5*js in p5's theme dark pink * */p5.prototype.loadFont=function(path,onSuccess,onError){p5._validateParameters('loadFont',arguments);var p5Font=new p5.Font(this);var self=this;opentype.load(path,function(err,font){if(err){if(typeof onError!=='undefined'){return onError(err);}p5._friendlyFileLoadError(4,path);console.error(err,path);return;}p5Font.font=font;if(typeof onSuccess!=='undefined'){onSuccess(p5Font);}self._decrementPreload();// check that we have an acceptable font type var validFontTypes=['ttf','otf','woff','woff2'],fileNoPath=path.split('\\').pop().split('/').pop(),lastDotIdx=fileNoPath.lastIndexOf('.'),fontFamily,newStyle,fileExt=lastDotIdx<1?null:fileNoPath.substr(lastDotIdx+1);// if so, add it to the DOM (name-only) for use with p5.dom if(validFontTypes.indexOf(fileExt)>-1){fontFamily=fileNoPath.substr(0,lastDotIdx);newStyle=document.createElement('style');newStyle.appendChild(document.createTextNode('\n@font-face {'+'\nfont-family: '+fontFamily+';\nsrc: url('+path+');\n}\n'));document.head.appendChild(newStyle);}});return p5Font;};/** * Draws text to the screen. Displays the information specified in the first * parameter on the screen in the position specified by the additional * parameters. A default font will be used unless a font is set with the * <a href="#/p5/textFont">textFont()</a> function and a default size will be used unless a font is set * with <a href="#/p5/textSize">textSize()</a>. Change the color of the text with the <a href="#/p5/fill">fill()</a> function. * Change the outline of the text with the <a href="#/p5/stroke">stroke()</a> and <a href="#/p5/strokeWeight">strokeWeight()</a> * functions. * <br><br> * The text displays in relation to the <a href="#/p5/textAlign">textAlign()</a> function, which gives the * option to draw to the left, right, and center of the coordinates. * <br><br> * The x2 and y2 parameters define a rectangular area to display within and * may only be used with string data. When these parameters are specified, * they are interpreted based on the current <a href="#/p5/rectMode">rectMode()</a> setting. Text that * does not fit completely within the rectangle specified will not be drawn * to the screen. If x2 and y2 are not specified, the baseline alignment is the * default, which means that the text will be drawn upwards from x and y. * <br><br> * <b>WEBGL</b>: Only opentype/truetype fonts are supported. You must load a font using the * <a href="#/p5/loadFont">loadFont()</a> method (see the example above). * <a href="#/p5/stroke">stroke()</a> currently has no effect in webgl mode. * * @method text * @param {String|Object|Array|Number|Boolean} str the alphanumeric * symbols to be displayed * @param {Number} x x-coordinate of text * @param {Number} y y-coordinate of text * @param {Number} [x2] by default, the width of the text box, * see <a href="#/p5/rectMode">rectMode()</a> for more info * @param {Number} [y2] by default, the height of the text box, * see <a href="#/p5/rectMode">rectMode()</a> for more info * @chainable * @example * <div> * <code> * textSize(32); * text('word', 10, 30); * fill(0, 102, 153); * text('word', 10, 60); * fill(0, 102, 153, 51); * text('word', 10, 90); * </code> * </div> * <div> * <code> * var s = 'The quick brown fox jumped over the lazy dog.'; * fill(50); * text(s, 10, 10, 70, 80); // Text wraps within text box * </code> * </div> * * <div modernizr='webgl'> * <code> * var avenir; * function preload() { * avenir = loadFont('assets/Avenir.otf'); * } * function setup() { * createCanvas(100, 100, WEBGL); * textFont(avenir); * textSize(width / 3); * textAlign(CENTER, CENTER); * } * function draw() { * background(0); * var time = millis(); * rotateX(time / 1000); * rotateZ(time / 1234); * text('p5.js', 0, 0); * } * </code> * </div> * * @alt *'word' displayed 3 times going from black, blue to translucent blue * The quick brown fox jumped over the lazy dog. * the text 'p5.js' spinning in 3d * */p5.prototype.text=function(str,x,y,maxWidth,maxHeight){p5._validateParameters('text',arguments);return!(this._renderer._doFill||this._renderer._doStroke)?this:this._renderer.text.apply(this._renderer,arguments);};/** * Sets the current font that will be drawn with the <a href="#/p5/text">text()</a> function. * <br><br> * <b>WEBGL</b>: Only fonts loaded via <a href="#/p5/loadFont">loadFont()</a> are supported. * * @method textFont * @return {Object} the current font * * @example * <div> * <code> * fill(0); * textSize(12); * textFont('Georgia'); * text('Georgia', 12, 30); * textFont('Helvetica'); * text('Helvetica', 12, 60); * </code> * </div> * <div> * <code> * var fontRegular, fontItalic, fontBold; * function preload() { * fontRegular = loadFont('assets/Regular.otf'); * fontItalic = loadFont('assets/Italic.ttf'); * fontBold = loadFont('assets/Bold.ttf'); * } * function setup() { * background(210); * fill(0) .strokeWeight(0) .textSize(10); * textFont(fontRegular); * text('Font Style Normal', 10, 30); * textFont(fontItalic); * text('Font Style Italic', 10, 50); * textFont(fontBold); * text('Font Style Bold', 10, 70); * } * </code> * </div> * * @alt *words Font Style Normal displayed normally, Italic in italic and bold in bold *//** * @method textFont * @param {Object|String} font a font loaded via <a href="#/p5/loadFont">loadFont()</a>, or a String * representing a <a href="https://mzl.la/2dOw8WD">web safe font</a> (a font * that is generally available across all systems) * @param {Number} [size] the font size to use * @chainable */p5.prototype.textFont=function(theFont,theSize){p5._validateParameters('textFont',arguments);if(arguments.length){if(!theFont){throw new Error('null font passed to textFont');}this._renderer._setProperty('_textFont',theFont);if(theSize){this._renderer._setProperty('_textSize',theSize);this._renderer._setProperty('_textLeading',theSize*constants._DEFAULT_LEADMULT);}return this._renderer._applyTextProperties();}return this._renderer._textFont;};module.exports=p5;},{"../core/constants":19,"../core/error_helpers":21,"../core/main":25,"opentype.js":11}],60:[function(_dereq_,module,exports){/** * This module defines the <a href="#/p5.Font">p5.Font</a> class and functions for * drawing text to the display canvas. * @module Typography * @submodule Font * @requires core * @requires constants */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');/* * TODO: * -- kerning * -- alignment: justified? *//** * Base class for font handling * @class p5.Font * @param {p5} [pInst] pointer to p5 instance */p5.Font=function(p){this.parent=p;this.cache={};/** * Underlying opentype font implementation * @property font */this.font=undefined;};p5.Font.prototype.list=function(){// TODO throw new Error('not yet implemented');};/** * Returns a tight bounding box for the given text string using this * font (currently only supports single lines) * * @method textBounds * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Number} [fontSize] font size to use (optional) * @param {Object} [options] opentype options (optional) * * @return {Object} a rectangle object with properties: x, y, w, h * * @example * <div> * <code> * var font; * var textString = 'Lorem ipsum dolor sit amet.'; * function preload() { * font = loadFont('./assets/Regular.otf'); * } * function setup() { * background(210); * * var bbox = font.textBounds(textString, 10, 30, 12); * fill(255); * stroke(0); * rect(bbox.x, bbox.y, bbox.w, bbox.h); * fill(0); * noStroke(); * * textFont(font); * textSize(12); * text(textString, 10, 30); * } * </code> * </div> * * @alt *words Lorem ipsum dol go off canvas and contained by white bounding box * */p5.Font.prototype.textBounds=function(str,x,y,fontSize,options){x=x!==undefined?x:0;y=y!==undefined?y:0;fontSize=fontSize||this.parent._renderer._textSize;// Check cache for existing bounds. Take into consideration the text alignment // settings. Default alignment should match opentype's origin: left-aligned & // alphabetic baseline. var p=options&&options.renderer&&options.renderer._pInst||this.parent,renderer=p._renderer,alignment=renderer._textAlign||constants.LEFT,baseline=renderer._textBaseline||constants.BASELINE,key=cacheKey('textBounds',str,x,y,fontSize,alignment,baseline),result=this.cache[key];if(!result){var minX,minY,maxX,maxY,pos,xCoords=[],yCoords=[],scale=this._scale(fontSize);this.font.forEachGlyph(str,x,y,fontSize,options,function(glyph,gX,gY,gFontSize){var gm=glyph.getMetrics();xCoords.push(gX+gm.xMin*scale);xCoords.push(gX+gm.xMax*scale);yCoords.push(gY+-gm.yMin*scale);yCoords.push(gY+-gm.yMax*scale);});minX=Math.min.apply(null,xCoords);minY=Math.min.apply(null,yCoords);maxX=Math.max.apply(null,xCoords);maxY=Math.max.apply(null,yCoords);result={x:minX,y:minY,h:maxY-minY,w:maxX-minX,advance:minX-x};// Bounds are now calculated, so shift the x & y to match alignment settings pos=this._handleAlignment(renderer,str,result.x,result.y,result.w+result.advance);result.x=pos.x;result.y=pos.y;this.cache[cacheKey('textBounds',str,x,y,fontSize,alignment,baseline)]=result;}return result;};/** * Computes an array of points following the path for specified text * * @method textToPoints * @param {String} txt a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Number} fontSize font size to use (optional) * @param {Object} [options] an (optional) object that can contain: * * <br>sampleFactor - the ratio of path-length to number of samples * (default=.25); higher values yield more points and are therefore * more precise * * <br>simplifyThreshold - if set to a non-zero value, collinear points will be * be removed from the polygon; the value represents the threshold angle to use * when determining whether two edges are collinear * * @return {Array} an array of points, each with x, y, alpha (the path angle) * @example * <div> * <code> * var font; * function preload() { * font = loadFont('./assets/Avenir.otf'); * } * * var points; * var bounds; * function setup() { * createCanvas(100, 100); * stroke(0); * fill(255, 104, 204); * * points = font.textToPoints('p5', 0, 0, 10, { * sampleFactor: 5, * simplifyThreshold: 0 * }); * bounds = font.textBounds(' p5 ', 0, 0, 10); * } * * function draw() { * background(255); * beginShape(); * translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h); * for (var i = 0; i < points.length; i++) { * var p = points[i]; * vertex( * p.x * width / bounds.w + * sin(20 * p.y / bounds.h + millis() / 1000) * width / 30, * p.y * height / bounds.h * ); * } * endShape(CLOSE); * } * </code> * </div> * */p5.Font.prototype.textToPoints=function(txt,x,y,fontSize,options){var xoff=0,result=[],glyphs=this._getGlyphs(txt);function isSpace(i){return glyphs[i].name&&glyphs[i].name==='space'||txt.length===glyphs.length&&txt[i]===' '||glyphs[i].index&&glyphs[i].index===3;}fontSize=fontSize||this.parent._renderer._textSize;for(var i=0;i<glyphs.length;i++){if(!isSpace(i)){// fix to #1817, #2069 var gpath=glyphs[i].getPath(x,y,fontSize),paths=splitPaths(gpath.commands);for(var j=0;j<paths.length;j++){var pts=pathToPoints(paths[j],options);for(var k=0;k<pts.length;k++){pts[k].x+=xoff;result.push(pts[k]);}}}xoff+=glyphs[i].advanceWidth*this._scale(fontSize);}return result;};// ----------------------------- End API ------------------------------ /** * Returns the set of opentype glyphs for the supplied string. * * Note that there is not a strict one-to-one mapping between characters * and glyphs, so the list of returned glyphs can be larger or smaller * than the length of the given string. * * @private * @param {String} str the string to be converted * @return {Array} the opentype glyphs */p5.Font.prototype._getGlyphs=function(str){return this.font.stringToGlyphs(str);};/** * Returns an opentype path for the supplied string and position. * * @private * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional) * @return {Object} the opentype path */p5.Font.prototype._getPath=function(line,x,y,options){var p=options&&options.renderer&&options.renderer._pInst||this.parent,renderer=p._renderer,pos=this._handleAlignment(renderer,line,x,y);return this.font.getPath(line,pos.x,pos.y,renderer._textSize,options);};/* * Creates an SVG-formatted path-data string * (See http://www.w3.org/TR/SVG/paths.html#PathData) * from the given opentype path or string/position * * @param {Object} path an opentype path, OR the following: * * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional), set options.decimals * to set the decimal precision of the path-data * * @return {Object} this p5.Font object */p5.Font.prototype._getPathData=function(line,x,y,options){var decimals=3;// create path from string/position if(typeof line==='string'&&arguments.length>2){line=this._getPath(line,x,y,options);}else if((typeof x==="undefined"?"undefined":_typeof(x))==='object'){// handle options specified in 2nd arg options=x;}// handle svg arguments if(options&&typeof options.decimals==='number'){decimals=options.decimals;}return line.toPathData(decimals);};/* * Creates an SVG <path> element, as a string, * from the given opentype path or string/position * * @param {Object} path an opentype path, OR the following: * * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional), set options.decimals * to set the decimal precision of the path-data in the <path> element, * options.fill to set the fill color for the <path> element, * options.stroke to set the stroke color for the <path> element, * options.strokeWidth to set the strokeWidth for the <path> element. * * @return {Object} this p5.Font object */p5.Font.prototype._getSVG=function(line,x,y,options){var decimals=3;// create path from string/position if(typeof line==='string'&&arguments.length>2){line=this._getPath(line,x,y,options);}else if((typeof x==="undefined"?"undefined":_typeof(x))==='object'){// handle options specified in 2nd arg options=x;}// handle svg arguments if(options){if(typeof options.decimals==='number'){decimals=options.decimals;}if(typeof options.strokeWidth==='number'){line.strokeWidth=options.strokeWidth;}if(typeof options.fill!=='undefined'){line.fill=options.fill;}if(typeof options.stroke!=='undefined'){line.stroke=options.stroke;}}return line.toSVG(decimals);};/* * Renders an opentype path or string/position * to the current graphics context * * @param {Object} path an opentype path, OR the following: * * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional) * * @return {p5.Font} this p5.Font object */p5.Font.prototype._renderPath=function(line,x,y,options){var pdata,pg=options&&options.renderer||this.parent._renderer,ctx=pg.drawingContext;if((typeof line==="undefined"?"undefined":_typeof(line))==='object'&&line.commands){pdata=line.commands;}else{//pos = handleAlignment(p, ctx, line, x, y); pdata=this._getPath(line,x,y,options).commands;}ctx.beginPath();for(var i=0;i<pdata.length;i+=1){var cmd=pdata[i];if(cmd.type==='M'){ctx.moveTo(cmd.x,cmd.y);}else if(cmd.type==='L'){ctx.lineTo(cmd.x,cmd.y);}else if(cmd.type==='C'){ctx.bezierCurveTo(cmd.x1,cmd.y1,cmd.x2,cmd.y2,cmd.x,cmd.y);}else if(cmd.type==='Q'){ctx.quadraticCurveTo(cmd.x1,cmd.y1,cmd.x,cmd.y);}else if(cmd.type==='Z'){ctx.closePath();}}// only draw stroke if manually set by user if(pg._doStroke&&pg._strokeSet){ctx.stroke();}if(pg._doFill){// if fill hasn't been set by user, use default-text-fill if(!pg._fillSet){pg._setFill(constants._DEFAULT_TEXT_FILL);}ctx.fill();}return this;};p5.Font.prototype._textWidth=function(str,fontSize){return this.font.getAdvanceWidth(str,fontSize);};p5.Font.prototype._textAscent=function(fontSize){return this.font.ascender*this._scale(fontSize);};p5.Font.prototype._textDescent=function(fontSize){return-this.font.descender*this._scale(fontSize);};p5.Font.prototype._scale=function(fontSize){return 1/this.font.unitsPerEm*(fontSize||this.parent._renderer._textSize);};p5.Font.prototype._handleAlignment=function(renderer,line,x,y,textWidth){var fontSize=renderer._textSize;if(typeof textWidth==='undefined'){textWidth=this._textWidth(line,fontSize);}switch(renderer._textAlign){case constants.CENTER:x-=textWidth/2;break;case constants.RIGHT:x-=textWidth;break;}switch(renderer._textBaseline){case constants.TOP:y+=this._textAscent(fontSize);break;case constants.CENTER:y+=this._textAscent(fontSize)/2;break;case constants.BOTTOM:y-=this._textDescent(fontSize);break;}return{x:x,y:y};};// path-utils function pathToPoints(cmds,options){var opts=parseOpts(options,{sampleFactor:0.1,simplifyThreshold:0});var len=pointAtLength(cmds,0,1),// total-length t=len/(len*opts.sampleFactor),pts=[];for(var i=0;i<len;i+=t){pts.push(pointAtLength(cmds,i));}if(opts.simplifyThreshold){/*var count = */simplify(pts,opts.simplifyThreshold);//console.log('Simplify: removed ' + count + ' pts'); }return pts;}function simplify(pts,angle){angle=typeof angle==='undefined'?0:angle;var num=0;for(var i=pts.length-1;pts.length>3&&i>=0;--i){if(collinear(at(pts,i-1),at(pts,i),at(pts,i+1),angle)){// Remove the middle point pts.splice(i%pts.length,1);num++;}}return num;}function splitPaths(cmds){var paths=[],current;for(var i=0;i<cmds.length;i++){if(cmds[i].type==='M'){if(current){paths.push(current);}current=[];}current.push(cmdToArr(cmds[i]));}paths.push(current);return paths;}function cmdToArr(cmd){var arr=[cmd.type];if(cmd.type==='M'||cmd.type==='L'){// moveto or lineto arr.push(cmd.x,cmd.y);}else if(cmd.type==='C'){arr.push(cmd.x1,cmd.y1,cmd.x2,cmd.y2,cmd.x,cmd.y);}else if(cmd.type==='Q'){arr.push(cmd.x1,cmd.y1,cmd.x,cmd.y);}// else if (cmd.type === 'Z') { /* no-op */ } return arr;}function parseOpts(options,defaults){if((typeof options==="undefined"?"undefined":_typeof(options))!=='object'){options=defaults;}else{for(var key in defaults){if(typeof options[key]==='undefined'){options[key]=defaults[key];}}}return options;}//////////////////////// Helpers //////////////////////////// function at(v,i){var s=v.length;return v[i<0?i%s+s:i%s];}function collinear(a,b,c,thresholdAngle){if(!thresholdAngle){return areaTriangle(a,b,c)===0;}if(typeof collinear.tmpPoint1==='undefined'){collinear.tmpPoint1=[];collinear.tmpPoint2=[];}var ab=collinear.tmpPoint1,bc=collinear.tmpPoint2;ab.x=b.x-a.x;ab.y=b.y-a.y;bc.x=c.x-b.x;bc.y=c.y-b.y;var dot=ab.x*bc.x+ab.y*bc.y,magA=Math.sqrt(ab.x*ab.x+ab.y*ab.y),magB=Math.sqrt(bc.x*bc.x+bc.y*bc.y),angle=Math.acos(dot/(magA*magB));return angle<thresholdAngle;}function areaTriangle(a,b,c){return(b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1]);}// Portions of below code copyright 2008 Dmitry Baranovskiy (via MIT license) function findDotsAtSegment(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,t){var t1=1-t,t13=Math.pow(t1,3),t12=Math.pow(t1,2),t2=t*t,t3=t2*t,x=t13*p1x+t12*3*t*c1x+t1*3*t*t*c2x+t3*p2x,y=t13*p1y+t12*3*t*c1y+t1*3*t*t*c2y+t3*p2y,mx=p1x+2*t*(c1x-p1x)+t2*(c2x-2*c1x+p1x),my=p1y+2*t*(c1y-p1y)+t2*(c2y-2*c1y+p1y),nx=c1x+2*t*(c2x-c1x)+t2*(p2x-2*c2x+c1x),ny=c1y+2*t*(c2y-c1y)+t2*(p2y-2*c2y+c1y),ax=t1*p1x+t*c1x,ay=t1*p1y+t*c1y,cx=t1*c2x+t*p2x,cy=t1*c2y+t*p2y,alpha=90-Math.atan2(mx-nx,my-ny)*180/Math.PI;if(mx>nx||my<ny){alpha+=180;}return{x:x,y:y,m:{x:mx,y:my},n:{x:nx,y:ny},start:{x:ax,y:ay},end:{x:cx,y:cy},alpha:alpha};}function getPointAtSegmentLength(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,length){return length==null?bezlen(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y):findDotsAtSegment(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,getTatLen(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,length));}function pointAtLength(path,length,istotal){path=path2curve(path);var x,y,p,l,sp='',subpaths={},point,len=0;for(var i=0,ii=path.length;i<ii;i++){p=path[i];if(p[0]==='M'){x=+p[1];y=+p[2];}else{l=getPointAtSegmentLength(x,y,p[1],p[2],p[3],p[4],p[5],p[6]);if(len+l>length){if(!istotal){point=getPointAtSegmentLength(x,y,p[1],p[2],p[3],p[4],p[5],p[6],length-len);return{x:point.x,y:point.y,alpha:point.alpha};}}len+=l;x=+p[5];y=+p[6];}sp+=p.shift()+p;}subpaths.end=sp;point=istotal?len:findDotsAtSegment(x,y,p[0],p[1],p[2],p[3],p[4],p[5],1);if(point.alpha){point={x:point.x,y:point.y,alpha:point.alpha};}return point;}function pathToAbsolute(pathArray){var res=[],x=0,y=0,mx=0,my=0,start=0;if(!pathArray){// console.warn("Unexpected state: undefined pathArray"); // shouldn't happen return res;}if(pathArray[0][0]==='M'){x=+pathArray[0][1];y=+pathArray[0][2];mx=x;my=y;start++;res[0]=['M',x,y];}var dots,crz=pathArray.length===3&&pathArray[0][0]==='M'&&pathArray[1][0].toUpperCase()==='R'&&pathArray[2][0].toUpperCase()==='Z';for(var r,pa,i=start,ii=pathArray.length;i<ii;i++){res.push(r=[]);pa=pathArray[i];if(pa[0]!==String.prototype.toUpperCase.call(pa[0])){r[0]=String.prototype.toUpperCase.call(pa[0]);switch(r[0]){case'A':r[1]=pa[1];r[2]=pa[2];r[3]=pa[3];r[4]=pa[4];r[5]=pa[5];r[6]=+(pa[6]+x);r[7]=+(pa[7]+y);break;case'V':r[1]=+pa[1]+y;break;case'H':r[1]=+pa[1]+x;break;case'R':dots=[x,y].concat(pa.slice(1));for(var j=2,jj=dots.length;j<jj;j++){dots[j]=+dots[j]+x;dots[++j]=+dots[j]+y;}res.pop();res=res.concat(catmullRom2bezier(dots,crz));break;case'M':mx=+pa[1]+x;my=+pa[2]+y;break;default:for(j=1,jj=pa.length;j<jj;j++){r[j]=+pa[j]+(j%2?x:y);}}}else if(pa[0]==='R'){dots=[x,y].concat(pa.slice(1));res.pop();res=res.concat(catmullRom2bezier(dots,crz));r=['R'].concat(pa.slice(-2));}else{for(var k=0,kk=pa.length;k<kk;k++){r[k]=pa[k];}}switch(r[0]){case'Z':x=mx;y=my;break;case'H':x=r[1];break;case'V':y=r[1];break;case'M':mx=r[r.length-2];my=r[r.length-1];break;default:x=r[r.length-2];y=r[r.length-1];}}return res;}function path2curve(path,path2){var p=pathToAbsolute(path),p2=path2&&pathToAbsolute(path2);var attrs={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null};var attrs2={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null};var pcoms1=[];// path commands of original path p var pcoms2=[];// path commands of original path p2 var ii;var processPath=function processPath(path,d,pcom){var nx,ny,tq={T:1,Q:1};if(!path){return['C',d.x,d.y,d.x,d.y,d.x,d.y];}if(!(path[0]in tq)){d.qx=d.qy=null;}switch(path[0]){case'M':d.X=path[1];d.Y=path[2];break;case'A':path=['C'].concat(a2c.apply(0,[d.x,d.y].concat(path.slice(1))));break;case'S':if(pcom==='C'||pcom==='S'){nx=d.x*2-d.bx;ny=d.y*2-d.by;}else{nx=d.x;ny=d.y;}path=['C',nx,ny].concat(path.slice(1));break;case'T':if(pcom==='Q'||pcom==='T'){d.qx=d.x*2-d.qx;d.qy=d.y*2-d.qy;}else{d.qx=d.x;d.qy=d.y;}path=['C'].concat(q2c(d.x,d.y,d.qx,d.qy,path[1],path[2]));break;case'Q':d.qx=path[1];d.qy=path[2];path=['C'].concat(q2c(d.x,d.y,path[1],path[2],path[3],path[4]));break;case'L':path=['C'].concat(l2c(d.x,d.y,path[1],path[2]));break;case'H':path=['C'].concat(l2c(d.x,d.y,path[1],d.y));break;case'V':path=['C'].concat(l2c(d.x,d.y,d.x,path[1]));break;case'Z':path=['C'].concat(l2c(d.x,d.y,d.X,d.Y));break;}return path;},fixArc=function fixArc(pp,i){if(pp[i].length>7){pp[i].shift();var pi=pp[i];while(pi.length){pcoms1[i]='A';if(p2){pcoms2[i]='A';}pp.splice(i++,0,['C'].concat(pi.splice(0,6)));}pp.splice(i,1);ii=Math.max(p.length,p2&&p2.length||0);}},fixM=function fixM(path1,path2,a1,a2,i){if(path1&&path2&&path1[i][0]==='M'&&path2[i][0]!=='M'){path2.splice(i,0,['M',a2.x,a2.y]);a1.bx=0;a1.by=0;a1.x=path1[i][1];a1.y=path1[i][2];ii=Math.max(p.length,p2&&p2.length||0);}};var pfirst='';// temporary holder for original path command var pcom='';// holder for previous path command of original path ii=Math.max(p.length,p2&&p2.length||0);for(var i=0;i<ii;i++){if(p[i]){pfirst=p[i][0];}// save current path command if(pfirst!=='C'){pcoms1[i]=pfirst;// Save current path command if(i){pcom=pcoms1[i-1];}// Get previous path command pcom }p[i]=processPath(p[i],attrs,pcom);if(pcoms1[i]!=='A'&&pfirst==='C'){pcoms1[i]='C';}fixArc(p,i);// fixArc adds also the right amount of A:s to pcoms1 if(p2){// the same procedures is done to p2 if(p2[i]){pfirst=p2[i][0];}if(pfirst!=='C'){pcoms2[i]=pfirst;if(i){pcom=pcoms2[i-1];}}p2[i]=processPath(p2[i],attrs2,pcom);if(pcoms2[i]!=='A'&&pfirst==='C'){pcoms2[i]='C';}fixArc(p2,i);}fixM(p,p2,attrs,attrs2,i);fixM(p2,p,attrs2,attrs,i);var seg=p[i],seg2=p2&&p2[i],seglen=seg.length,seg2len=p2&&seg2.length;attrs.x=seg[seglen-2];attrs.y=seg[seglen-1];attrs.bx=parseFloat(seg[seglen-4])||attrs.x;attrs.by=parseFloat(seg[seglen-3])||attrs.y;attrs2.bx=p2&&(parseFloat(seg2[seg2len-4])||attrs2.x);attrs2.by=p2&&(parseFloat(seg2[seg2len-3])||attrs2.y);attrs2.x=p2&&seg2[seg2len-2];attrs2.y=p2&&seg2[seg2len-1];}return p2?[p,p2]:p;}function a2c(x1,y1,rx,ry,angle,lac,sweep_flag,x2,y2,recursive){// for more information of where this Math came from visit: // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes var PI=Math.PI,_120=PI*120/180,f1,f2,cx,cy,rad=PI/180*(+angle||0),res=[],xy,rotate=function rotate(x,y,rad){var X=x*Math.cos(rad)-y*Math.sin(rad),Y=x*Math.sin(rad)+y*Math.cos(rad);return{x:X,y:Y};};if(!recursive){xy=rotate(x1,y1,-rad);x1=xy.x;y1=xy.y;xy=rotate(x2,y2,-rad);x2=xy.x;y2=xy.y;var x=(x1-x2)/2,y=(y1-y2)/2,h=x*x/(rx*rx)+y*y/(ry*ry);if(h>1){h=Math.sqrt(h);rx=h*rx;ry=h*ry;}var rx2=rx*rx,ry2=ry*ry;var k=(lac===sweep_flag?-1:1)*Math.sqrt(Math.abs((rx2*ry2-rx2*y*y-ry2*x*x)/(rx2*y*y+ry2*x*x)));cx=k*rx*y/ry+(x1+x2)/2;cy=k*-ry*x/rx+(y1+y2)/2;f1=Math.asin(((y1-cy)/ry).toFixed(9));f2=Math.asin(((y2-cy)/ry).toFixed(9));f1=x1<cx?PI-f1:f1;f2=x2<cx?PI-f2:f2;if(f1<0){f1=PI*2+f1;}if(f2<0){f2=PI*2+f2;}if(sweep_flag&&f1>f2){f1=f1-PI*2;}if(!sweep_flag&&f2>f1){f2=f2-PI*2;}}else{f1=recursive[0];f2=recursive[1];cx=recursive[2];cy=recursive[3];}var df=f2-f1;if(Math.abs(df)>_120){var f2old=f2,x2old=x2,y2old=y2;f2=f1+_120*(sweep_flag&&f2>f1?1:-1);x2=cx+rx*Math.cos(f2);y2=cy+ry*Math.sin(f2);res=a2c(x2,y2,rx,ry,angle,0,sweep_flag,x2old,y2old,[f2,f2old,cx,cy]);}df=f2-f1;var c1=Math.cos(f1),s1=Math.sin(f1),c2=Math.cos(f2),s2=Math.sin(f2),t=Math.tan(df/4),hx=4/3*rx*t,hy=4/3*ry*t,m1=[x1,y1],m2=[x1+hx*s1,y1-hy*c1],m3=[x2+hx*s2,y2-hy*c2],m4=[x2,y2];m2[0]=2*m1[0]-m2[0];m2[1]=2*m1[1]-m2[1];if(recursive){return[m2,m3,m4].concat(res);}else{res=[m2,m3,m4].concat(res).join().split(',');var newres=[];for(var i=0,ii=res.length;i<ii;i++){newres[i]=i%2?rotate(res[i-1],res[i],rad).y:rotate(res[i],res[i+1],rad).x;}return newres;}}// http://schepers.cc/getting-to-the-point function catmullRom2bezier(crp,z){var d=[];for(var i=0,iLen=crp.length;iLen-2*!z>i;i+=2){var p=[{x:+crp[i-2],y:+crp[i-1]},{x:+crp[i],y:+crp[i+1]},{x:+crp[i+2],y:+crp[i+3]},{x:+crp[i+4],y:+crp[i+5]}];if(z){if(!i){p[0]={x:+crp[iLen-2],y:+crp[iLen-1]};}else if(iLen-4===i){p[3]={x:+crp[0],y:+crp[1]};}else if(iLen-2===i){p[2]={x:+crp[0],y:+crp[1]};p[3]={x:+crp[2],y:+crp[3]};}}else{if(iLen-4===i){p[3]=p[2];}else if(!i){p[0]={x:+crp[i],y:+crp[i+1]};}}d.push(['C',(-p[0].x+6*p[1].x+p[2].x)/6,(-p[0].y+6*p[1].y+p[2].y)/6,(p[1].x+6*p[2].x-p[3].x)/6,(p[1].y+6*p[2].y-p[3].y)/6,p[2].x,p[2].y]);}return d;}function l2c(x1,y1,x2,y2){return[x1,y1,x2,y2,x2,y2];}function q2c(x1,y1,ax,ay,x2,y2){var _13=1/3,_23=2/3;return[_13*x1+_23*ax,_13*y1+_23*ay,_13*x2+_23*ax,_13*y2+_23*ay,x2,y2];}function bezlen(x1,y1,x2,y2,x3,y3,x4,y4,z){if(z==null){z=1;}z=z>1?1:z<0?0:z;var z2=z/2;var n=12;var Tvalues=[-0.1252,0.1252,-0.3678,0.3678,-0.5873,0.5873,-0.7699,0.7699,-0.9041,0.9041,-0.9816,0.9816];var sum=0;var Cvalues=[0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472];for(var i=0;i<n;i++){var ct=z2*Tvalues[i]+z2,xbase=base3(ct,x1,x2,x3,x4),ybase=base3(ct,y1,y2,y3,y4),comb=xbase*xbase+ybase*ybase;sum+=Cvalues[i]*Math.sqrt(comb);}return z2*sum;}function getTatLen(x1,y1,x2,y2,x3,y3,x4,y4,ll){if(ll<0||bezlen(x1,y1,x2,y2,x3,y3,x4,y4)<ll){return;}var t=1,step=t/2,t2=t-step,l,e=0.01;l=bezlen(x1,y1,x2,y2,x3,y3,x4,y4,t2);while(Math.abs(l-ll)>e){step/=2;t2+=(l<ll?1:-1)*step;l=bezlen(x1,y1,x2,y2,x3,y3,x4,y4,t2);}return t2;}function base3(t,p1,p2,p3,p4){var t1=-3*p1+9*p2-9*p3+3*p4,t2=t*t1+6*p1-12*p2+6*p3;return t*t2-3*p1+3*p2;}function cacheKey(){var hash='';for(var i=arguments.length-1;i>=0;--i){var v=arguments[i];hash+=v===Object(v)?JSON.stringify(v):v;}return hash;}module.exports=p5;},{"../core/constants":19,"../core/main":25}],61:[function(_dereq_,module,exports){/** * @module Data * @submodule Array Functions * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');/** * Adds a value to the end of an array. Extends the length of * the array by one. Maps to Array.push(). * * @method append * @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push">array.push(value)</a> instead. * @param {Array} array Array to append * @param {any} value to be added to the Array * @return {Array} the array that was appended to * @example * <div class='norender'><code> * function setup() { * var myArray = ['Mango', 'Apple', 'Papaya']; * print(myArray); // ['Mango', 'Apple', 'Papaya'] * * append(myArray, 'Peach'); * print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach'] * } * </code></div> */p5.prototype.append=function(array,value){array.push(value);return array;};/** * Copies an array (or part of an array) to another array. The src array is * copied to the dst array, beginning at the position specified by * srcPosition and into the position specified by dstPosition. The number of * elements to copy is determined by length. Note that copying values * overwrites existing values in the destination array. To append values * instead of overwriting them, use <a href="#/p5/concat">concat()</a>. * <br><br> * The simplified version with only two arguments, arrayCopy(src, dst), * copies an entire array to another of the same size. It is equivalent to * arrayCopy(src, 0, dst, 0, src.length). * <br><br> * Using this function is far more efficient for copying array data than * iterating through a for() loop and copying each element individually. * * @method arrayCopy * @deprecated * @param {Array} src the source Array * @param {Integer} srcPosition starting position in the source Array * @param {Array} dst the destination Array * @param {Integer} dstPosition starting position in the destination Array * @param {Integer} length number of Array elements to be copied * * @example * <div class='norender'><code> * var src = ['A', 'B', 'C']; * var dst = [1, 2, 3]; * var srcPosition = 1; * var dstPosition = 0; * var length = 2; * * print(src); // ['A', 'B', 'C'] * print(dst); // [ 1 , 2 , 3 ] * * arrayCopy(src, srcPosition, dst, dstPosition, length); * print(dst); // ['B', 'C', 3] * </code></div> *//** * @method arrayCopy * @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin">arr1.copyWithin(arr2)</a> instead. * @param {Array} src * @param {Array} dst * @param {Integer} [length] */p5.prototype.arrayCopy=function(src,srcPosition,dst,dstPosition,length){// the index to begin splicing from dst array var start;var end;if(typeof length!=='undefined'){end=Math.min(length,src.length);start=dstPosition;src=src.slice(srcPosition,end+srcPosition);}else{if(typeof dst!=='undefined'){// src, dst, length // rename so we don't get confused end=dst;end=Math.min(end,src.length);}else{// src, dst end=src.length;}start=0;// rename so we don't get confused dst=srcPosition;src=src.slice(0,end);}// Since we are not returning the array and JavaScript is pass by reference // we must modify the actual values of the array // instead of reassigning arrays Array.prototype.splice.apply(dst,[start,end].concat(src));};/** * Concatenates two arrays, maps to Array.concat(). Does not modify the * input arrays. * * @method concat * @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat">arr1.concat(arr2)</a> instead. * @param {Array} a first Array to concatenate * @param {Array} b second Array to concatenate * @return {Array} concatenated array * * @example * <div class = 'norender'><code> * function setup() { * var arr1 = ['A', 'B', 'C']; * var arr2 = [1, 2, 3]; * * print(arr1); // ['A','B','C'] * print(arr2); // [1,2,3] * * var arr3 = concat(arr1, arr2); * * print(arr1); // ['A','B','C'] * print(arr2); // [1, 2, 3] * print(arr3); // ['A','B','C', 1, 2, 3] * } * </code></div> */p5.prototype.concat=function(list0,list1){return list0.concat(list1);};/** * Reverses the order of an array, maps to Array.reverse() * * @method reverse * @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse">array.reverse()</a> instead. * @param {Array} list Array to reverse * @return {Array} the reversed list * @example * <div class='norender'><code> * function setup() { * var myArray = ['A', 'B', 'C']; * print(myArray); // ['A','B','C'] * * reverse(myArray); * print(myArray); // ['C','B','A'] * } * </code></div> */p5.prototype.reverse=function(list){return list.reverse();};/** * Decreases an array by one element and returns the shortened array, * maps to Array.pop(). * * @method shorten * @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop">array.pop()</a> instead. * @param {Array} list Array to shorten * @return {Array} shortened Array * @example * <div class = 'norender'><code> * function setup() { * var myArray = ['A', 'B', 'C']; * print(myArray); // ['A', 'B', 'C'] * var newArray = shorten(myArray); * print(myArray); // ['A','B','C'] * print(newArray); // ['A','B'] * } * </code></div> */p5.prototype.shorten=function(list){list.pop();return list;};/** * Randomizes the order of the elements of an array. Implements * <a href='http://Bost.Ocks.org/mike/shuffle/' target=_blank> * Fisher-Yates Shuffle Algorithm</a>. * * @method shuffle * @deprecated See <a href="https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array">shuffling an array with JS</a> instead. * @param {Array} array Array to shuffle * @param {Boolean} [bool] modify passed array * @return {Array} shuffled Array * @example * <div><code> * function setup() { * var regularArr = ['ABC', 'def', createVector(), TAU, Math.E]; * print(regularArr); * shuffle(regularArr, true); // force modifications to passed array * print(regularArr); * * // By default shuffle() returns a shuffled cloned array: * var newArr = shuffle(regularArr); * print(regularArr); * print(newArr); * } * </code></div> */p5.prototype.shuffle=function(arr,bool){var isView=ArrayBuffer&&ArrayBuffer.isView&&ArrayBuffer.isView(arr);arr=bool||isView?arr:arr.slice();var rnd,tmp,idx=arr.length;while(idx>1){rnd=Math.random()*idx|0;tmp=arr[--idx];arr[idx]=arr[rnd];arr[rnd]=tmp;}return arr;};/** * Sorts an array of numbers from smallest to largest, or puts an array of * words in alphabetical order. The original array is not modified; a * re-ordered array is returned. The count parameter states the number of * elements to sort. For example, if there are 12 elements in an array and * count is set to 5, only the first 5 elements in the array will be sorted. * * @method sort * @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">array.sort()</a> instead. * @param {Array} list Array to sort * @param {Integer} [count] number of elements to sort, starting from 0 * @return {Array} the sorted list * * @example * <div class = 'norender'><code> * function setup() { * var words = ['banana', 'apple', 'pear', 'lime']; * print(words); // ['banana', 'apple', 'pear', 'lime'] * var count = 4; // length of array * * words = sort(words, count); * print(words); // ['apple', 'banana', 'lime', 'pear'] * } * </code></div> * <div class = 'norender'><code> * function setup() { * var numbers = [2, 6, 1, 5, 14, 9, 8, 12]; * print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12] * var count = 5; // Less than the length of the array * * numbers = sort(numbers, count); * print(numbers); // [1,2,5,6,14,9,8,12] * } * </code></div> */p5.prototype.sort=function(list,count){var arr=count?list.slice(0,Math.min(count,list.length)):list;var rest=count?list.slice(Math.min(count,list.length)):[];if(typeof arr[0]==='string'){arr=arr.sort();}else{arr=arr.sort(function(a,b){return a-b;});}return arr.concat(rest);};/** * Inserts a value or an array of values into an existing array. The first * parameter specifies the initial array to be modified, and the second * parameter defines the data to be inserted. The third parameter is an index * value which specifies the array position from which to insert data. * (Remember that array index numbering starts at zero, so the first position * is 0, the second position is 1, and so on.) * * @method splice * @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice">array.splice()</a> instead. * @param {Array} list Array to splice into * @param {any} value value to be spliced in * @param {Integer} position in the array from which to insert data * @return {Array} the list * * @example * <div class = 'norender'><code> * function setup() { * var myArray = [0, 1, 2, 3, 4]; * var insArray = ['A', 'B', 'C']; * print(myArray); // [0, 1, 2, 3, 4] * print(insArray); // ['A','B','C'] * * splice(myArray, insArray, 3); * print(myArray); // [0,1,2,'A','B','C',3,4] * } * </code></div> */p5.prototype.splice=function(list,value,index){// note that splice returns spliced elements and not an array Array.prototype.splice.apply(list,[index,0].concat(value));return list;};/** * Extracts an array of elements from an existing array. The list parameter * defines the array from which the elements will be copied, and the start * and count parameters specify which elements to extract. If no count is * given, elements will be extracted from the start to the end of the array. * When specifying the start, remember that the first array element is 0. * This function does not change the source array. * * @method subset * @deprecated Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">array.slice()</a> instead. * @param {Array} list Array to extract from * @param {Integer} start position to begin * @param {Integer} [count] number of values to extract * @return {Array} Array of extracted elements * * @example * <div class = 'norender'><code> * function setup() { * var myArray = [1, 2, 3, 4, 5]; * print(myArray); // [1, 2, 3, 4, 5] * * var sub1 = subset(myArray, 0, 3); * var sub2 = subset(myArray, 2, 2); * print(sub1); // [1,2,3] * print(sub2); // [3,4] * } * </code></div> */p5.prototype.subset=function(list,start,count){if(typeof count!=='undefined'){return list.slice(start,start+count);}else{return list.slice(start,list.length);}};module.exports=p5;},{"../core/main":25}],62:[function(_dereq_,module,exports){/** * @module Data * @submodule Conversion * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');/** * Converts a string to its floating point representation. The contents of a * string must resemble a number, or NaN (not a number) will be returned. * For example, float("1234.56") evaluates to 1234.56, but float("giraffe") * will return NaN. * * When an array of values is passed in, then an array of floats of the same * length is returned. * * @method float * @param {String} str float string to parse * @return {Number} floating point representation of string * @example * <div><code> * var str = '20'; * var diameter = float(str); * ellipse(width / 2, height / 2, diameter, diameter); * </code></div> * * @alt * 20 by 20 white ellipse in the center of the canvas * */p5.prototype.float=function(str){if(str instanceof Array){return str.map(parseFloat);}return parseFloat(str);};/** * Converts a boolean, string, or float to its integer representation. * When an array of values is passed in, then an int array of the same length * is returned. * * @method int * @param {String|Boolean|Number} n value to parse * @param {Integer} [radix] the radix to convert to (default: 10) * @return {Number} integer representation of value * * @example * <div class='norender'><code> * print(int('10')); // 10 * print(int(10.31)); // 10 * print(int(-10)); // -10 * print(int(true)); // 1 * print(int(false)); // 0 * print(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9] * </code></div> *//** * @method int * @param {Array} ns values to parse * @return {Number[]} integer representation of values */p5.prototype.int=function(n,radix){radix=radix||10;if(typeof n==='string'){return parseInt(n,radix);}else if(typeof n==='number'){return n|0;}else if(typeof n==='boolean'){return n?1:0;}else if(n instanceof Array){return n.map(function(n){return p5.prototype.int(n,radix);});}};/** * Converts a boolean, string or number to its string representation. * When an array of values is passed in, then an array of strings of the same * length is returned. * * @method str * @param {String|Boolean|Number|Array} n value to parse * @return {String} string representation of value * @example * <div class='norender'><code> * print(str('10')); // "10" * print(str(10.31)); // "10.31" * print(str(-10)); // "-10" * print(str(true)); // "true" * print(str(false)); // "false" * print(str([true, '10.3', 9.8])); // [ "true", "10.3", "9.8" ] * </code></div> */p5.prototype.str=function(n){if(n instanceof Array){return n.map(p5.prototype.str);}else{return String(n);}};/** * Converts a number or string to its boolean representation. * For a number, any non-zero value (positive or negative) evaluates to true, * while zero evaluates to false. For a string, the value "true" evaluates to * true, while any other value evaluates to false. When an array of number or * string values is passed in, then a array of booleans of the same length is * returned. * * @method boolean * @param {String|Boolean|Number|Array} n value to parse * @return {Boolean} boolean representation of value * @example * <div class='norender'><code> * print(boolean(0)); // false * print(boolean(1)); // true * print(boolean('true')); // true * print(boolean('abcd')); // false * print(boolean([0, 12, 'true'])); // [false, true, false] * </code></div> */p5.prototype.boolean=function(n){if(typeof n==='number'){return n!==0;}else if(typeof n==='string'){return n.toLowerCase()==='true';}else if(typeof n==='boolean'){return n;}else if(n instanceof Array){return n.map(p5.prototype.boolean);}};/** * Converts a number, string representation of a number, or boolean to its byte * representation. A byte can be only a whole number between -128 and 127, so * when a value outside of this range is converted, it wraps around to the * corresponding byte representation. When an array of number, string or boolean * values is passed in, then an array of bytes the same length is returned. * * @method byte * @param {String|Boolean|Number} n value to parse * @return {Number} byte representation of value * * @example * <div class='norender'><code> * print(byte(127)); // 127 * print(byte(128)); // -128 * print(byte(23.4)); // 23 * print(byte('23.4')); // 23 * print(byte('hello')); // NaN * print(byte(true)); // 1 * print(byte([0, 255, '100'])); // [0, -1, 100] * </code></div> *//** * @method byte * @param {Array} ns values to parse * @return {Number[]} array of byte representation of values */p5.prototype.byte=function(n){var nn=p5.prototype.int(n,10);if(typeof nn==='number'){return(nn+128)%256-128;}else if(nn instanceof Array){return nn.map(p5.prototype.byte);}};/** * Converts a number or string to its corresponding single-character * string representation. If a string parameter is provided, it is first * parsed as an integer and then translated into a single-character string. * When an array of number or string values is passed in, then an array of * single-character strings of the same length is returned. * * @method char * @param {String|Number} n value to parse * @return {String} string representation of value * * @example * <div class='norender'><code> * print(char(65)); // "A" * print(char('65')); // "A" * print(char([65, 66, 67])); // [ "A", "B", "C" ] * print(join(char([65, 66, 67]), '')); // "ABC" * </code></div> *//** * @method char * @param {Array} ns values to parse * @return {String[]} array of string representation of values */p5.prototype.char=function(n){if(typeof n==='number'&&!isNaN(n)){return String.fromCharCode(n);}else if(n instanceof Array){return n.map(p5.prototype.char);}else if(typeof n==='string'){return p5.prototype.char(parseInt(n,10));}};/** * Converts a single-character string to its corresponding integer * representation. When an array of single-character string values is passed * in, then an array of integers of the same length is returned. * * @method unchar * @param {String} n value to parse * @return {Number} integer representation of value * * @example * <div class='norender'><code> * print(unchar('A')); // 65 * print(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ] * print(unchar(split('ABC', ''))); // [ 65, 66, 67 ] * </code></div> *//** * @method unchar * @param {Array} ns values to parse * @return {Number[]} integer representation of values */p5.prototype.unchar=function(n){if(typeof n==='string'&&n.length===1){return n.charCodeAt(0);}else if(n instanceof Array){return n.map(p5.prototype.unchar);}};/** * Converts a number to a string in its equivalent hexadecimal notation. If a * second parameter is passed, it is used to set the number of characters to * generate in the hexadecimal notation. When an array is passed in, an * array of strings in hexadecimal notation of the same length is returned. * * @method hex * @param {Number} n value to parse * @param {Number} [digits] * @return {String} hexadecimal string representation of value * * @example * <div class='norender'><code> * print(hex(255)); // "000000FF" * print(hex(255, 6)); // "0000FF" * print(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ] * </code></div> *//** * @method hex * @param {Number[]} ns array of values to parse * @param {Number} [digits] * @return {String[]} hexadecimal string representation of values */p5.prototype.hex=function(n,digits){digits=digits===undefined||digits===null?digits=8:digits;if(n instanceof Array){return n.map(function(n){return p5.prototype.hex(n,digits);});}else if(typeof n==='number'){if(n<0){n=0xffffffff+n+1;}var hex=Number(n).toString(16).toUpperCase();while(hex.length<digits){hex='0'+hex;}if(hex.length>=digits){hex=hex.substring(hex.length-digits,hex.length);}return hex;}};/** * Converts a string representation of a hexadecimal number to its equivalent * integer value. When an array of strings in hexadecimal notation is passed * in, an array of integers of the same length is returned. * * @method unhex * @param {String} n value to parse * @return {Number} integer representation of hexadecimal value * * @example * <div class='norender'><code> * print(unhex('A')); // 10 * print(unhex('FF')); // 255 * print(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ] * </code></div> *//** * @method unhex * @param {Array} ns values to parse * @return {Number[]} integer representations of hexadecimal value */p5.prototype.unhex=function(n){if(n instanceof Array){return n.map(p5.prototype.unhex);}else{return parseInt('0x'+n,16);}};module.exports=p5;},{"../core/main":25}],63:[function(_dereq_,module,exports){/** * @module Data * @submodule String Functions * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');_dereq_('../core/error_helpers');//return p5; //LM is this a mistake? /** * Combines an array of Strings into one String, each separated by the * character(s) used for the separator parameter. To join arrays of ints or * floats, it's necessary to first convert them to Strings using <a href="#/p5/nf">nf()</a> or * nfs(). * * @method join * @param {Array} list array of Strings to be joined * @param {String} separator String to be placed between each item * @return {String} joined String * @example * <div> * <code> * var array = ['Hello', 'world!']; * var separator = ' '; * var message = join(array, separator); * text(message, 5, 50); * </code> * </div> * * @alt * "hello world!" displayed middle left of canvas. * */p5.prototype.join=function(list,separator){p5._validateParameters('join',arguments);return list.join(separator);};/** * This function is used to apply a regular expression to a piece of text, * and return matching groups (elements found inside parentheses) as a * String array. If there are no matches, a null value will be returned. * If no groups are specified in the regular expression, but the sequence * matches, an array of length 1 (with the matched text as the first element * of the array) will be returned. * <br><br> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match at all. If the sequence * did match, an array is returned. * <br><br> * If there are groups (specified by sets of parentheses) in the regular * expression, then the contents of each will be returned in the array. * Element [0] of a regular expression match returns the entire matching * string, and the match groups start at element [1] (the first group is [1], * the second [2], and so on). * * @method match * @param {String} str the String to be searched * @param {String} regexp the regexp to be used for matching * @return {String[]} Array of Strings found * @example * <div> * <code> * var string = 'Hello p5js*!'; * var regexp = 'p5js\\*'; * var m = match(string, regexp); * text(m, 5, 50); * </code> * </div> * * @alt * "p5js*" displayed middle left of canvas. * */p5.prototype.match=function(str,reg){p5._validateParameters('match',arguments);return str.match(reg);};/** * This function is used to apply a regular expression to a piece of text, * and return a list of matching groups (elements found inside parentheses) * as a two-dimensional String array. If there are no matches, a null value * will be returned. If no groups are specified in the regular expression, * but the sequence matches, a two dimensional array is still returned, but * the second dimension is only of length one. * <br><br> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match at all. If the sequence * did match, a 2D array is returned. * <br><br> * If there are groups (specified by sets of parentheses) in the regular * expression, then the contents of each will be returned in the array. * Assuming a loop with counter variable i, element [i][0] of a regular * expression match returns the entire matching string, and the match groups * start at element [i][1] (the first group is [i][1], the second [i][2], * and so on). * * @method matchAll * @param {String} str the String to be searched * @param {String} regexp the regexp to be used for matching * @return {String[]} 2d Array of Strings found * @example * <div class="norender"> * <code> * var string = 'Hello p5js*! Hello world!'; * var regexp = 'Hello'; * matchAll(string, regexp); * </code> * </div> */p5.prototype.matchAll=function(str,reg){p5._validateParameters('matchAll',arguments);var re=new RegExp(reg,'g');var match=re.exec(str);var matches=[];while(match!==null){matches.push(match);// matched text: match[0] // match start: match.index // capturing group n: match[n] match=re.exec(str);}return matches;};/** * Utility function for formatting numbers into strings. There are two * versions: one for formatting floats, and one for formatting ints. * The values for the digits, left, and right parameters should always * be positive integers. * * @method nf * @param {Number|String} num the Number to format * @param {Integer|String} [left] number of digits to the left of the * decimal point * @param {Integer|String} [right] number of digits to the right of the * decimal point * @return {String} formatted String * * @example * <div> * <code> * function setup() { * background(200); * var num = 112.53106115; * * noStroke(); * fill(0); * textSize(14); * // Draw formatted numbers * text(nf(num, 5, 2), 10, 20); * * text(nf(num, 4, 3), 10, 55); * * text(nf(num, 3, 6), 10, 85); * * // Draw dividing lines * stroke(120); * line(0, 30, width, 30); * line(0, 65, width, 65); * } * </code> * </div> * * @alt * "0011253" top left, "0112.531" mid left, "112.531061" bottom left canvas *//** * @method nf * @param {Array} nums the Numbers to format * @param {Integer|String} [left] * @param {Integer|String} [right] * @return {String[]} formatted Strings */p5.prototype.nf=function(nums,left,right){p5._validateParameters('nf',arguments);if(nums instanceof Array){return nums.map(function(x){return doNf(x,left,right);});}else{var typeOfFirst=Object.prototype.toString.call(nums);if(typeOfFirst==='[object Arguments]'){if(nums.length===3){return this.nf(nums[0],nums[1],nums[2]);}else if(nums.length===2){return this.nf(nums[0],nums[1]);}else{return this.nf(nums[0]);}}else{return doNf(nums,left,right);}}};function doNf(num,left,right){var neg=num<0;var n=neg?num.toString().substring(1):num.toString();var decimalInd=n.indexOf('.');var intPart=decimalInd!==-1?n.substring(0,decimalInd):n;var decPart=decimalInd!==-1?n.substring(decimalInd+1):'';var str=neg?'-':'';if(typeof right!=='undefined'){var decimal='';if(decimalInd!==-1||right-decPart.length>0){decimal='.';}if(decPart.length>right){decPart=decPart.substring(0,right);}for(var i=0;i<left-intPart.length;i++){str+='0';}str+=intPart;str+=decimal;str+=decPart;for(var j=0;j<right-decPart.length;j++){str+='0';}return str;}else{for(var k=0;k<Math.max(left-intPart.length,0);k++){str+='0';}str+=n;return str;}}/** * Utility function for formatting numbers into strings and placing * appropriate commas to mark units of 1000. There are two versions: one * for formatting ints, and one for formatting an array of ints. The value * for the right parameter should always be a positive integer. * * @method nfc * @param {Number|String} num the Number to format * @param {Integer|String} [right] number of digits to the right of the * decimal point * @return {String} formatted String * * @example * <div> * <code> * function setup() { * background(200); * var num = 11253106.115; * var numArr = [1, 1, 2]; * * noStroke(); * fill(0); * textSize(12); * * // Draw formatted numbers * text(nfc(num, 4), 10, 30); * text(nfc(numArr, 2), 10, 80); * * // Draw dividing line * stroke(120); * line(0, 50, width, 50); * } * </code> * </div> * * @alt * "11,253,106.115" top middle and "1.00,1.00,2.00" displayed bottom mid *//** * @method nfc * @param {Array} nums the Numbers to format * @param {Integer|String} [right] * @return {String[]} formatted Strings */p5.prototype.nfc=function(num,right){p5._validateParameters('nfc',arguments);if(num instanceof Array){return num.map(function(x){return doNfc(x,right);});}else{return doNfc(num,right);}};function doNfc(num,right){num=num.toString();var dec=num.indexOf('.');var rem=dec!==-1?num.substring(dec):'';var n=dec!==-1?num.substring(0,dec):num;n=n.toString().replace(/\B(?=(\d{3})+(?!\d))/g,',');if(right===0){rem='';}else if(typeof right!=='undefined'){if(right>rem.length){rem+=dec===-1?'.':'';var len=right-rem.length+1;for(var i=0;i<len;i++){rem+='0';}}else{rem=rem.substring(0,right+1);}}return n+rem;}/** * Utility function for formatting numbers into strings. Similar to <a href="#/p5/nf">nf()</a> but * puts a "+" in front of positive numbers and a "-" in front of negative * numbers. There are two versions: one for formatting floats, and one for * formatting ints. The values for left, and right parameters * should always be positive integers. * * @method nfp * @param {Number} num the Number to format * @param {Integer} [left] number of digits to the left of the decimal * point * @param {Integer} [right] number of digits to the right of the * decimal point * @return {String} formatted String * * @example * <div> * <code> * function setup() { * background(200); * var num1 = 11253106.115; * var num2 = -11253106.115; * * noStroke(); * fill(0); * textSize(12); * * // Draw formatted numbers * text(nfp(num1, 4, 2), 10, 30); * text(nfp(num2, 4, 2), 10, 80); * * // Draw dividing line * stroke(120); * line(0, 50, width, 50); * } * </code> * </div> * * @alt * "+11253106.11" top middle and "-11253106.11" displayed bottom middle *//** * @method nfp * @param {Number[]} nums the Numbers to format * @param {Integer} [left] * @param {Integer} [right] * @return {String[]} formatted Strings */p5.prototype.nfp=function(){p5._validateParameters('nfp',arguments);var nfRes=p5.prototype.nf.apply(this,arguments);if(nfRes instanceof Array){return nfRes.map(addNfp);}else{return addNfp(nfRes);}};function addNfp(num){return parseFloat(num)>0?'+'+num.toString():num.toString();}/** * Utility function for formatting numbers into strings. Similar to <a href="#/p5/nf">nf()</a> but * puts a " " (space) in front of positive numbers and a "-" in front of * negative numbers. There are two versions: one for formatting floats, and * one for formatting ints. The values for the digits, left, and right * parameters should always be positive integers. * * @method nfs * @param {Number} num the Number to format * @param {Integer} [left] number of digits to the left of the decimal * point * @param {Integer} [right] number of digits to the right of the * decimal point * @return {String} formatted String * * @example * <div> * <code> * function setup() { * background(200); * var num1 = 11253106.115; * var num2 = -11253106.115; * * noStroke(); * fill(0); * textSize(12); * // Draw formatted numbers * text(nfs(num1, 4, 2), 10, 30); * * text(nfs(num2, 4, 2), 10, 80); * * // Draw dividing line * stroke(120); * line(0, 50, width, 50); * } * </code> * </div> * * @alt * "11253106.11" top middle and "-11253106.11" displayed bottom middle *//** * @method nfs * @param {Array} nums the Numbers to format * @param {Integer} [left] * @param {Integer} [right] * @return {String[]} formatted Strings */p5.prototype.nfs=function(){p5._validateParameters('nfs',arguments);var nfRes=p5.prototype.nf.apply(this,arguments);if(nfRes instanceof Array){return nfRes.map(addNfs);}else{return addNfs(nfRes);}};function addNfs(num){return parseFloat(num)>0?' '+num.toString():num.toString();}/** * The <a href="#/p5/split">split()</a> function maps to String.split(), it breaks a String into * pieces using a character or string as the delimiter. The delim parameter * specifies the character or characters that mark the boundaries between * each piece. A String[] array is returned that contains each of the pieces. * * The <a href="#/p5/splitTokens">splitTokens()</a> function works in a similar fashion, except that it * splits using a range of characters instead of a specific character or * sequence. * * @method split * @param {String} value the String to be split * @param {String} delim the String used to separate the data * @return {String[]} Array of Strings * @example * <div> * <code> * var names = 'Pat,Xio,Alex'; * var splitString = split(names, ','); * text(splitString[0], 5, 30); * text(splitString[1], 5, 50); * text(splitString[2], 5, 70); * </code> * </div> * * @alt * "pat" top left, "Xio" mid left and "Alex" displayed bottom left * */p5.prototype.split=function(str,delim){p5._validateParameters('split',arguments);return str.split(delim);};/** * The <a href="#/p5/splitTokens">splitTokens()</a> function splits a String at one or many character * delimiters or "tokens." The delim parameter specifies the character or * characters to be used as a boundary. * <br><br> * If no delim characters are specified, any whitespace character is used to * split. Whitespace characters include tab (\t), line feed (\n), carriage * return (\r), form feed (\f), and space. * * @method splitTokens * @param {String} value the String to be split * @param {String} [delim] list of individual Strings that will be used as * separators * @return {String[]} Array of Strings * @example * <div class = "norender"> * <code> * function setup() { * var myStr = 'Mango, Banana, Lime'; * var myStrArr = splitTokens(myStr, ','); * * print(myStrArr); // prints : ["Mango"," Banana"," Lime"] * } * </code> * </div> */p5.prototype.splitTokens=function(value,delims){p5._validateParameters('splitTokens',arguments);var d;if(typeof delims!=='undefined'){var str=delims;var sqc=/\]/g.exec(str);var sqo=/\[/g.exec(str);if(sqo&&sqc){str=str.slice(0,sqc.index)+str.slice(sqc.index+1);sqo=/\[/g.exec(str);str=str.slice(0,sqo.index)+str.slice(sqo.index+1);d=new RegExp('[\\['+str+'\\]]','g');}else if(sqc){str=str.slice(0,sqc.index)+str.slice(sqc.index+1);d=new RegExp('['+str+'\\]]','g');}else if(sqo){str=str.slice(0,sqo.index)+str.slice(sqo.index+1);d=new RegExp('['+str+'\\[]','g');}else{d=new RegExp('['+str+']','g');}}else{d=/\s/g;}return value.split(d).filter(function(n){return n;});};/** * Removes whitespace characters from the beginning and end of a String. In * addition to standard whitespace characters such as space, carriage return, * and tab, this function also removes the Unicode "nbsp" character. * * @method trim * @param {String} str a String to be trimmed * @return {String} a trimmed String * * @example * <div> * <code> * var string = trim(' No new lines\n '); * text(string + ' here', 2, 50); * </code> * </div> * * @alt * "No new lines here" displayed center canvas *//** * @method trim * @param {Array} strs an Array of Strings to be trimmed * @return {String[]} an Array of trimmed Strings */p5.prototype.trim=function(str){p5._validateParameters('trim',arguments);if(str instanceof Array){return str.map(this.trim);}else{return str.trim();}};module.exports=p5;},{"../core/error_helpers":21,"../core/main":25}],64:[function(_dereq_,module,exports){/** * @module IO * @submodule Time & Date * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');/** * p5.js communicates with the clock on your computer. The <a href="#/p5/day">day()</a> function * returns the current day as a value from 1 - 31. * * @method day * @return {Integer} the current day * @example * <div> * <code> * var d = day(); * text('Current day: \n' + d, 5, 50); * </code> * </div> * * @alt * Current day is displayed * */p5.prototype.day=function(){return new Date().getDate();};/** * p5.js communicates with the clock on your computer. The <a href="#/p5/hour">hour()</a> function * returns the current hour as a value from 0 - 23. * * @method hour * @return {Integer} the current hour * @example * <div> * <code> * var h = hour(); * text('Current hour:\n' + h, 5, 50); * </code> * </div> * * @alt * Current hour is displayed * */p5.prototype.hour=function(){return new Date().getHours();};/** * p5.js communicates with the clock on your computer. The <a href="#/p5/minute">minute()</a> function * returns the current minute as a value from 0 - 59. * * @method minute * @return {Integer} the current minute * @example * <div> * <code> * var m = minute(); * text('Current minute: \n' + m, 5, 50); * </code> * </div> * * @alt * Current minute is displayed * */p5.prototype.minute=function(){return new Date().getMinutes();};/** * Returns the number of milliseconds (thousandths of a second) since * starting the program. This information is often used for timing events and * animation sequences. * * @method millis * @return {Number} the number of milliseconds since starting the program * @example * <div> * <code> * var millisecond = millis(); * text('Milliseconds \nrunning: \n' + millisecond, 5, 40); * </code> * </div> * * @alt * number of milliseconds since program has started displayed * */p5.prototype.millis=function(){return window.performance.now();};/** * p5.js communicates with the clock on your computer. The <a href="#/p5/month">month()</a> function * returns the current month as a value from 1 - 12. * * @method month * @return {Integer} the current month * @example * <div> * <code> * var m = month(); * text('Current month: \n' + m, 5, 50); * </code> * </div> * * @alt * Current month is displayed * */p5.prototype.month=function(){return new Date().getMonth()+1;//January is 0! };/** * p5.js communicates with the clock on your computer. The <a href="#/p5/second">second()</a> function * returns the current second as a value from 0 - 59. * * @method second * @return {Integer} the current second * @example * <div> * <code> * var s = second(); * text('Current second: \n' + s, 5, 50); * </code> * </div> * * @alt * Current second is displayed * */p5.prototype.second=function(){return new Date().getSeconds();};/** * p5.js communicates with the clock on your computer. The <a href="#/p5/year">year()</a> function * returns the current year as an integer (2014, 2015, 2016, etc). * * @method year * @return {Integer} the current year * @example * <div> * <code> * var y = year(); * text('Current year: \n' + y, 5, 50); * </code> * </div> * * @alt * Current year is displayed * */p5.prototype.year=function(){return new Date().getFullYear();};module.exports=p5;},{"../core/main":25}],65:[function(_dereq_,module,exports){/** * @module Shape * @submodule 3D Primitives * @for p5 * @requires core * @requires p5.Geometry */'use strict';var p5=_dereq_('../core/main');_dereq_('./p5.Geometry');var constants=_dereq_('../core/constants');/** * Draw a plane with given a width and height * @method plane * @param {Number} [width] width of the plane * @param {Number} [height] height of the plane * @param {Integer} [detailX] Optional number of triangle * subdivisions in x-dimension * @param {Integer} [detailY] Optional number of triangle * subdivisions in y-dimension * @chainable * @example * <div> * <code> * //draw a plane with width 50 and height 50 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * plane(50, 50); * } * </code> * </div> * * @alt * Nothing displayed on canvas * Rotating interior view of a box with sides that change color. * 3d red and green gradient. * Rotating interior view of a cylinder with sides that change color. * Rotating view of a cylinder with sides that change color. * 3d red and green gradient. * rotating view of a multi-colored cylinder with concave sides. */p5.prototype.plane=function(width,height,detailX,detailY){this._assert3d('plane');p5._validateParameters('plane',arguments);if(typeof width==='undefined'){width=50;}if(typeof height==='undefined'){height=width;}if(typeof detailX==='undefined'){detailX=1;}if(typeof detailY==='undefined'){detailY=1;}var gId='plane|'+detailX+'|'+detailY;if(!this._renderer.geometryInHash(gId)){var _plane=function _plane(){var u,v,p;for(var i=0;i<=this.detailY;i++){v=i/this.detailY;for(var j=0;j<=this.detailX;j++){u=j/this.detailX;p=new p5.Vector(u-0.5,v-0.5,0);this.vertices.push(p);this.uvs.push(u,v);}}};var planeGeom=new p5.Geometry(detailX,detailY,_plane);planeGeom.computeFaces().computeNormals();if(detailX<=1&&detailY<=1){planeGeom._makeTriangleEdges()._edgesToVertices();}else{console.log('Cannot draw stroke on plane objects with more'+' than 1 detailX or 1 detailY');}this._renderer.createBuffers(gId,planeGeom);}this._renderer.drawBuffersScaled(gId,width,height,1);return this;};/** * Draw a box with given width, height and depth * @method box * @param {Number} [width] width of the box * @param {Number} [Height] height of the box * @param {Number} [depth] depth of the box * @param {Integer} [detailX] Optional number of triangle * subdivisions in x-dimension * @param {Integer} [detailY] Optional number of triangle * subdivisions in y-dimension * @chainable * @example * <div> * <code> * //draw a spinning box with width, height and depth 200 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(50); * } * </code> * </div> */p5.prototype.box=function(width,height,depth,detailX,detailY){this._assert3d('box');p5._validateParameters('box',arguments);if(typeof width==='undefined'){width=50;}if(typeof height==='undefined'){height=width;}if(typeof depth==='undefined'){depth=height;}var perPixelLighting=this._renderer.attributes&&this._renderer.attributes.perPixelLighting;if(typeof detailX==='undefined'){detailX=perPixelLighting?1:4;}if(typeof detailY==='undefined'){detailY=perPixelLighting?1:4;}var gId='box|'+detailX+'|'+detailY;if(!this._renderer.geometryInHash(gId)){var _box=function _box(){var cubeIndices=[[0,4,2,6],// -1, 0, 0],// -x [1,3,5,7],// +1, 0, 0],// +x [0,1,4,5],// 0, -1, 0],// -y [2,6,3,7],// 0, +1, 0],// +y [0,2,1,3],// 0, 0, -1],// -z [4,5,6,7]// 0, 0, +1] // +z ];//using strokeIndices instead of faces for strokes //to avoid diagonal stroke lines across face of box this.strokeIndices=[[0,1],[1,3],[3,2],[6,7],[8,9],[9,11],[14,15],[16,17],[17,19],[18,19],[20,21],[22,23]];for(var i=0;i<cubeIndices.length;i++){var cubeIndex=cubeIndices[i];var v=i*4;for(var j=0;j<4;j++){var d=cubeIndex[j];//inspired by lightgl: //https://github.com/evanw/lightgl.js //octants:https://en.wikipedia.org/wiki/Octant_(solid_geometry) var octant=new p5.Vector(((d&1)*2-1)/2,((d&2)-1)/2,((d&4)/2-1)/2);this.vertices.push(octant);this.uvs.push(j&1,(j&2)/2);}this.faces.push([v,v+1,v+2]);this.faces.push([v+2,v+1,v+3]);}};var boxGeom=new p5.Geometry(detailX,detailY,_box);boxGeom.computeNormals();if(detailX<=4&&detailY<=4){boxGeom._makeTriangleEdges()._edgesToVertices();}else{console.log('Cannot draw stroke on box objects with more'+' than 4 detailX or 4 detailY');}//initialize our geometry buffer with //the key val pair: //geometry Id, Geom object this._renderer.createBuffers(gId,boxGeom);}this._renderer.drawBuffersScaled(gId,width,height,depth);return this;};/** * Draw a sphere with given radius * @method sphere * @param {Number} [radius] radius of circle * @param {Integer} [detailX] number of segments, * the more segments the smoother geometry * default is 24 * @param {Integer} [detailY] number of segments, * the more segments the smoother geometry * default is 16 * @chainable * @example * <div> * <code> * // draw a sphere with radius 200 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * sphere(40); * } * </code> * </div> */p5.prototype.sphere=function(radius,detailX,detailY){this._assert3d('sphere');p5._validateParameters('sphere',arguments);if(typeof radius==='undefined'){radius=50;}if(typeof detailX==='undefined'){detailX=24;}if(typeof detailY==='undefined'){detailY=16;}this.ellipsoid(radius,radius,radius,detailX,detailY);return this;};/** * @private * Helper function for creating both cones and cyllinders * Will only generate well-defined geometry when bottomRadius, height > 0 * and topRadius >= 0 * If topRadius == 0, topCap should be false */var _truncatedCone=function _truncatedCone(bottomRadius,topRadius,height,detailX,detailY,bottomCap,topCap){bottomRadius=bottomRadius<=0?1:bottomRadius;topRadius=topRadius<0?0:topRadius;height=height<=0?bottomRadius:height;detailX=detailX<3?3:detailX;detailY=detailY<1?1:detailY;bottomCap=bottomCap===undefined?true:bottomCap;topCap=topCap===undefined?topRadius!==0:topCap;var start=bottomCap?-2:0;var end=detailY+(topCap?2:0);var vertsOnLayer={};//ensure constant slant for interior vertex normals var slant=Math.atan2(bottomRadius-topRadius,height);var yy,ii,jj,nextii,nextjj;for(yy=start;yy<=end;++yy){var v=yy/detailY;var y=height*v;var ringRadius;if(yy<0){//for the bottomCap edge y=0;v=0;ringRadius=bottomRadius;}else if(yy>detailY){//for the topCap edge y=height;v=1;ringRadius=topRadius;}else{//for the middle ringRadius=bottomRadius+(topRadius-bottomRadius)*v;}if(yy===-2||yy===detailY+2){//center of bottom or top caps ringRadius=0;}y-=height/2;//shift coordiate origin to the center of object vertsOnLayer[yy]=ringRadius===0?1:detailX;for(ii=0;ii<vertsOnLayer[yy];++ii){var u=ii/detailX;//VERTICES this.vertices.push(new p5.Vector(Math.sin(u*2*Math.PI)*ringRadius,y,Math.cos(u*2*Math.PI)*ringRadius));//VERTEX NORMALS this.vertexNormals.push(new p5.Vector(yy<0||yy>detailY?0:Math.sin(u*2*Math.PI)*Math.cos(slant),yy<0?-1:yy>detailY?1:Math.sin(slant),yy<0||yy>detailY?0:Math.cos(u*2*Math.PI)*Math.cos(slant)));//UVs this.uvs.push(u,v);}}var startIndex=0;if(bottomCap){for(jj=0;jj<vertsOnLayer[-1];++jj){nextjj=(jj+1)%vertsOnLayer[-1];this.faces.push([startIndex,startIndex+1+nextjj,startIndex+1+jj]);}startIndex+=vertsOnLayer[-2]+vertsOnLayer[-1];}for(yy=0;yy<detailY;++yy){for(ii=0;ii<vertsOnLayer[yy];++ii){if(vertsOnLayer[yy+1]===1){//top layer nextii=(ii+1)%vertsOnLayer[yy];this.faces.push([startIndex+ii,startIndex+nextii,startIndex+vertsOnLayer[yy]]);}else{//other side faces //should have vertsOnLayer[yy] === vertsOnLayer[yy + 1] nextii=(ii+1)%vertsOnLayer[yy];this.faces.push([startIndex+ii,startIndex+nextii,startIndex+vertsOnLayer[yy]+nextii]);this.faces.push([startIndex+ii,startIndex+vertsOnLayer[yy]+nextii,startIndex+vertsOnLayer[yy]+ii]);}}startIndex+=vertsOnLayer[yy];}if(topCap){startIndex+=vertsOnLayer[detailY];for(ii=0;ii<vertsOnLayer[detailY+1];++ii){nextii=(ii+1)%vertsOnLayer[detailY+1];this.faces.push([startIndex+ii,startIndex+nextii,startIndex+vertsOnLayer[detailY+1]]);}}};/** * Draw a cylinder with given radius and height * @method cylinder * @param {Number} [radius] radius of the surface * @param {Number} [height] height of the cylinder * @param {Integer} [detailX] number of segments, * the more segments the smoother geometry * default is 24 * @param {Integer} [detailY] number of segments in y-dimension, * the more segments the smoother geometry * default is 1 * @param {Boolean} [bottomCap] whether to draw the bottom of the cylinder * @param {Boolean} [topCap] whether to draw the top of the cylinder * @chainable * @example * <div> * <code> * //draw a spinning cylinder with radius 20 and height 50 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateZ(frameCount * 0.01); * cylinder(20, 50); * } * </code> * </div> */p5.prototype.cylinder=function(radius,height,detailX,detailY,bottomCap,topCap){this._assert3d('cylinder');p5._validateParameters('cylinder',arguments);if(typeof radius==='undefined'){radius=50;}if(typeof height==='undefined'){height=radius;}if(typeof detailX==='undefined'){detailX=24;}if(typeof detailY==='undefined'){detailY=1;}if(typeof topCap==='undefined'){topCap=true;}if(typeof bottomCap==='undefined'){bottomCap=true;}var gId='cylinder|'+detailX+'|'+detailY+'|'+bottomCap+'|'+topCap;if(!this._renderer.geometryInHash(gId)){var cylinderGeom=new p5.Geometry(detailX,detailY);_truncatedCone.call(cylinderGeom,1,1,1,detailX,detailY,bottomCap,topCap);cylinderGeom.computeNormals();if(detailX<=24&&detailY<=16){cylinderGeom._makeTriangleEdges()._edgesToVertices();}else{console.log('Cannot draw stroke on cylinder objects with more'+' than 24 detailX or 16 detailY');}this._renderer.createBuffers(gId,cylinderGeom);}this._renderer.drawBuffersScaled(gId,radius,height,radius);return this;};/** * Draw a cone with given radius and height * @method cone * @param {Number} [radius] radius of the bottom surface * @param {Number} [height] height of the cone * @param {Integer} [detailX] number of segments, * the more segments the smoother geometry * default is 24 * @param {Integer} [detailY] number of segments, * the more segments the smoother geometry * default is 1 * @param {Boolean} [cap] whether to draw the base of the cone * @chainable * @example * <div> * <code> * //draw a spinning cone with radius 40 and height 70 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateZ(frameCount * 0.01); * cone(40, 70); * } * </code> * </div> */p5.prototype.cone=function(radius,height,detailX,detailY,cap){this._assert3d('cone');p5._validateParameters('cone',arguments);if(typeof radius==='undefined'){radius=50;}if(typeof height==='undefined'){height=radius;}if(typeof detailX==='undefined'){detailX=24;}if(typeof detailY==='undefined'){detailY=1;}if(typeof cap==='undefined'){cap=true;}var gId='cone|'+detailX+'|'+detailY+'|'+cap;if(!this._renderer.geometryInHash(gId)){var coneGeom=new p5.Geometry(detailX,detailY);_truncatedCone.call(coneGeom,1,0,1,detailX,detailY,cap,false);//for cones we need to average Normals coneGeom.computeNormals();if(detailX<=24&&detailY<=16){coneGeom._makeTriangleEdges()._edgesToVertices();}else{console.log('Cannot draw stroke on cone objects with more'+' than 24 detailX or 16 detailY');}this._renderer.createBuffers(gId,coneGeom);}this._renderer.drawBuffersScaled(gId,radius,height,radius);return this;};/** * Draw an ellipsoid with given radius * @method ellipsoid * @param {Number} [radiusx] xradius of circle * @param {Number} [radiusy] yradius of circle * @param {Number} [radiusz] zradius of circle * @param {Integer} [detailX] number of segments, * the more segments the smoother geometry * default is 24. Avoid detail number above * 150, it may crash the browser. * @param {Integer} [detailY] number of segments, * the more segments the smoother geometry * default is 16. Avoid detail number above * 150, it may crash the browser. * @chainable * @example * <div> * <code> * // draw an ellipsoid with radius 20, 30 and 40. * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * ellipsoid(20, 30, 40); * } * </code> * </div> */p5.prototype.ellipsoid=function(radiusX,radiusY,radiusZ,detailX,detailY){this._assert3d('ellipsoid');p5._validateParameters('ellipsoid',arguments);if(typeof radiusX==='undefined'){radiusX=50;}if(typeof radiusY==='undefined'){radiusY=radiusX;}if(typeof radiusZ==='undefined'){radiusZ=radiusX;}if(typeof detailX==='undefined'){detailX=24;}if(typeof detailY==='undefined'){detailY=16;}var gId='ellipsoid|'+detailX+'|'+detailY;if(!this._renderer.geometryInHash(gId)){var _ellipsoid=function _ellipsoid(){for(var i=0;i<=this.detailY;i++){var v=i/this.detailY;var phi=Math.PI*v-Math.PI/2;var cosPhi=Math.cos(phi);var sinPhi=Math.sin(phi);for(var j=0;j<=this.detailX;j++){var u=j/this.detailX;var theta=2*Math.PI*u;var cosTheta=Math.cos(theta);var sinTheta=Math.sin(theta);var p=new p5.Vector(cosPhi*sinTheta,sinPhi,cosPhi*cosTheta);this.vertices.push(p);this.vertexNormals.push(p);this.uvs.push(u,v);}}};var ellipsoidGeom=new p5.Geometry(detailX,detailY,_ellipsoid);ellipsoidGeom.computeFaces();if(detailX<=24&&detailY<=24){ellipsoidGeom._makeTriangleEdges()._edgesToVertices();}else{console.log('Cannot draw stroke on ellipsoids with more'+' than 24 detailX or 24 detailY');}this._renderer.createBuffers(gId,ellipsoidGeom);}this._renderer.drawBuffersScaled(gId,radiusX,radiusY,radiusZ);return this;};/** * Draw a torus with given radius and tube radius * @method torus * @param {Number} [radius] radius of the whole ring * @param {Number} [tubeRadius] radius of the tube * @param {Integer} [detailX] number of segments in x-dimension, * the more segments the smoother geometry * default is 24 * @param {Integer} [detailY] number of segments in y-dimension, * the more segments the smoother geometry * default is 16 * @chainable * @example * <div> * <code> * //draw a spinning torus with radius 200 and tube radius 60 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * torus(50, 15); * } * </code> * </div> */p5.prototype.torus=function(radius,tubeRadius,detailX,detailY){this._assert3d('torus');p5._validateParameters('torus',arguments);if(typeof radius==='undefined'){radius=50;}else if(!radius){return;// nothing to draw }if(typeof tubeRadius==='undefined'){tubeRadius=10;}else if(!tubeRadius){return;// nothing to draw }if(typeof detailX==='undefined'){detailX=24;}if(typeof detailY==='undefined'){detailY=16;}var tubeRatio=(tubeRadius/radius).toPrecision(4);var gId='torus|'+tubeRatio+'|'+detailX+'|'+detailY;if(!this._renderer.geometryInHash(gId)){var _torus=function _torus(){for(var i=0;i<=this.detailY;i++){var v=i/this.detailY;var phi=2*Math.PI*v;var cosPhi=Math.cos(phi);var sinPhi=Math.sin(phi);var r=1+tubeRatio*cosPhi;for(var j=0;j<=this.detailX;j++){var u=j/this.detailX;var theta=2*Math.PI*u;var cosTheta=Math.cos(theta);var sinTheta=Math.sin(theta);var p=new p5.Vector(r*cosTheta,r*sinTheta,tubeRatio*sinPhi);var n=new p5.Vector(cosPhi*cosTheta,cosPhi*sinTheta,sinPhi);this.vertices.push(p);this.vertexNormals.push(n);this.uvs.push(u,v);}}};var torusGeom=new p5.Geometry(detailX,detailY,_torus);torusGeom.computeFaces();if(detailX<=24&&detailY<=16){torusGeom._makeTriangleEdges()._edgesToVertices();}else{console.log('Cannot draw strokes on torus object with more'+' than 24 detailX or 16 detailY');}this._renderer.createBuffers(gId,torusGeom);}this._renderer.drawBuffersScaled(gId,radius,radius,radius);return this;};/////////////////////// /// 2D primitives ///////////////////////// /** * Draws a point, a coordinate in space at the dimension of one pixel, * given x, y and z coordinates. The color of the point is determined * by the current stroke, while the point size is determined by current * stroke weight. * @private * @param {Number} x x-coordinate of point * @param {Number} y y-coordinate of point * @param {Number} z z-coordinate of point * @chainable * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(50); * stroke(255); * strokeWeight(4); * point(25, 0); * strokeWeight(3); * point(-25, 0); * strokeWeight(2); * point(0, 25); * strokeWeight(1); * point(0, -25); * } * </code> * </div> */p5.RendererGL.prototype.point=function(x,y,z){this._usePointShader();this.curPointShader.bindShader();if(typeof z==='undefined'){z=0;}var _vertex=[];_vertex.push(new p5.Vector(x,y,z));this._drawPoints(_vertex,this._pointVertexBuffer);this.curPointShader.unbindShader();return this;};p5.RendererGL.prototype.triangle=function(args){var x1=args[0],y1=args[1];var x2=args[2],y2=args[3];var x3=args[4],y3=args[5];var gId='tri';if(!this.geometryInHash(gId)){var _triangle=function _triangle(){var vertices=[];vertices.push(new p5.Vector(0,0,0));vertices.push(new p5.Vector(0,1,0));vertices.push(new p5.Vector(1,0,0));this.strokeIndices=[[0,1],[1,2],[2,0]];this.vertices=vertices;this.faces=[[0,1,2]];this.uvs=[0,0,0,1,1,1];};var triGeom=new p5.Geometry(1,1,_triangle);triGeom._makeTriangleEdges()._edgesToVertices();triGeom.computeNormals();this.createBuffers(gId,triGeom);}// only one triangle is cached, one point is at the origin, and the // two adjacent sides are tne unit vectors along the X & Y axes. // // this matrix multiplication transforms those two unit vectors // onto the required vector prior to rendering, and moves the // origin appropriately. var uMVMatrix=this.uMVMatrix.copy();try{// prettier-ignore var mult=new p5.Matrix([x2-x1,y2-y1,0,0,// the resulting unit X-axis x3-x1,y3-y1,0,0,// the resulting unit Y-axis 0,0,1,0,// the resulting unit Z-axis (unchanged) x1,y1,0,1// the resulting origin ]).mult(this.uMVMatrix);this.uMVMatrix=mult;this.drawBuffers(gId);}finally{this.uMVMatrix=uMVMatrix;}return this;};p5.RendererGL.prototype.ellipse=function(args){this.arc(args[0],args[1],args[2],args[3],0,constants.TWO_PI,constants.OPEN,args[4]);};p5.RendererGL.prototype.arc=function(args){var x=arguments[0];var y=arguments[1];var width=arguments[2];var height=arguments[3];var start=arguments[4];var stop=arguments[5];var mode=arguments[6];var detail=arguments[7]||25;var shape;var gId;// check if it is an ellipse or an arc if(Math.abs(stop-start)>=constants.TWO_PI){shape='ellipse';gId=shape+'|'+detail+'|';}else{shape='arc';gId=shape+'|'+start+'|'+stop+'|'+mode+'|'+detail+'|';}if(!this.geometryInHash(gId)){var _arc=function _arc(){this.strokeIndices=[];// if the start and stop angles are not the same, push vertices to the array if(start.toFixed(10)!==stop.toFixed(10)){// if the mode specified is PIE or null, push the mid point of the arc in vertices if(mode===constants.PIE||typeof mode==='undefined'){this.vertices.push(new p5.Vector(0.5,0.5,0));this.uvs.push([0.5,0.5]);}// vertices for the perimeter of the circle for(var i=0;i<=detail;i++){var u=i/detail;var theta=(stop-start)*u+start;var _x=0.5+Math.cos(theta)/2;var _y=0.5+Math.sin(theta)/2;this.vertices.push(new p5.Vector(_x,_y,0));this.uvs.push([_x,_y]);if(i<detail-1){this.faces.push([0,i+1,i+2]);this.strokeIndices.push([i+1,i+2]);}}// check the mode specified in order to push vertices and faces, different for each mode switch(mode){case constants.PIE:this.faces.push([0,this.vertices.length-2,this.vertices.length-1]);this.strokeIndices.push([0,1]);this.strokeIndices.push([this.vertices.length-2,this.vertices.length-1]);this.strokeIndices.push([0,this.vertices.length-1]);break;case constants.CHORD:this.strokeIndices.push([0,1]);this.strokeIndices.push([0,this.vertices.length-1]);break;case constants.OPEN:this.strokeIndices.push([0,1]);break;default:this.faces.push([0,this.vertices.length-2,this.vertices.length-1]);this.strokeIndices.push([this.vertices.length-2,this.vertices.length-1]);}}};var arcGeom=new p5.Geometry(detail,1,_arc);arcGeom.computeNormals();if(detail<=50){arcGeom._makeTriangleEdges()._edgesToVertices(arcGeom);}else{console.log('Cannot stroke '+shape+' with more than 50 detail');}this.createBuffers(gId,arcGeom);}var uMVMatrix=this.uMVMatrix.copy();try{this.uMVMatrix.translate([x,y,0]);this.uMVMatrix.scale(width,height,1);this.drawBuffers(gId);}finally{this.uMVMatrix=uMVMatrix;}return this;};p5.RendererGL.prototype.rect=function(args){var perPixelLighting=this.attributes.perPixelLighting;var x=args[0];var y=args[1];var width=args[2];var height=args[3];var detailX=args[4]||(perPixelLighting?1:24);var detailY=args[5]||(perPixelLighting?1:16);var gId='rect|'+detailX+'|'+detailY;if(!this.geometryInHash(gId)){var _rect=function _rect(){for(var i=0;i<=this.detailY;i++){var v=i/this.detailY;for(var j=0;j<=this.detailX;j++){var u=j/this.detailX;var p=new p5.Vector(u,v,0);this.vertices.push(p);this.uvs.push(u,v);}}// using stroke indices to avoid stroke over face(s) of rectangle if(detailX>0&&detailY>0){this.strokeIndices=[[0,detailX],[detailX,(detailX+1)*(detailY+1)-1],[(detailX+1)*(detailY+1)-1,(detailX+1)*detailY],[(detailX+1)*detailY,0]];}};var rectGeom=new p5.Geometry(detailX,detailY,_rect);rectGeom.computeFaces().computeNormals()._makeTriangleEdges()._edgesToVertices();this.createBuffers(gId,rectGeom);}// only a single rectangle (of a given detail) is cached: a square with // opposite corners at (0,0) & (1,1). // // before rendering, this square is scaled & moved to the required location. var uMVMatrix=this.uMVMatrix.copy();try{this.uMVMatrix.translate([x,y,0]);this.uMVMatrix.scale(width,height,1);this.drawBuffers(gId);}finally{this.uMVMatrix=uMVMatrix;}return this;};p5.RendererGL.prototype.quad=function(x1,y1,x2,y2,x3,y3,x4,y4){var gId='quad|'+x1+'|'+y1+'|'+x2+'|'+y2+'|'+x3+'|'+y3+'|'+x4+'|'+y4;if(!this.geometryInHash(gId)){var _quad=function _quad(){this.vertices.push(new p5.Vector(x1,y1,0));this.vertices.push(new p5.Vector(x2,y2,0));this.vertices.push(new p5.Vector(x3,y3,0));this.vertices.push(new p5.Vector(x4,y4,0));this.uvs.push(0,0,1,0,1,1,0,1);this.strokeIndices=[[0,1],[1,2],[2,3],[3,0]];};var quadGeom=new p5.Geometry(2,2,_quad);quadGeom.computeNormals()._makeTriangleEdges()._edgesToVertices();quadGeom.faces=[[0,1,2],[2,3,0]];this.createBuffers(gId,quadGeom);}this.drawBuffers(gId);return this;};//this implementation of bezier curve //is based on Bernstein polynomial // pretier-ignore p5.RendererGL.prototype.bezier=function(x1,y1,z1,// x2 x2,// y2 y2,// x3 z2,// y3 x3,// x4 y3,// y4 z3,x4,y4,z4){if(arguments.length===8){x4=x3;y4=y3;x3=y2;y3=x2;x2=z1;y2=x2;z1=z2=z3=z4=0;}var bezierDetail=this._pInst._bezierDetail||20;//value of Bezier detail this.beginShape();for(var i=0;i<=bezierDetail;i++){var c1=Math.pow(1-i/bezierDetail,3);var c2=3*(i/bezierDetail)*Math.pow(1-i/bezierDetail,2);var c3=3*Math.pow(i/bezierDetail,2)*(1-i/bezierDetail);var c4=Math.pow(i/bezierDetail,3);this.vertex(x1*c1+x2*c2+x3*c3+x4*c4,y1*c1+y2*c2+y3*c3+y4*c4,z1*c1+z2*c2+z3*c3+z4*c4);}this.endShape();return this;};// pretier-ignore p5.RendererGL.prototype.curve=function(x1,y1,z1,// x2 x2,// y2 y2,// x3 z2,// y3 x3,// x4 y3,// y4 z3,x4,y4,z4){if(arguments.length===8){x4=x3;y4=y3;x3=y2;y3=x2;x2=z1;y2=x2;z1=z2=z3=z4=0;}var curveDetail=this._pInst._curveDetail;this.beginShape();for(var i=0;i<=curveDetail;i++){var c1=Math.pow(i/curveDetail,3)*0.5;var c2=Math.pow(i/curveDetail,2)*0.5;var c3=i/curveDetail*0.5;var c4=0.5;var vx=c1*(-x1+3*x2-3*x3+x4)+c2*(2*x1-5*x2+4*x3-x4)+c3*(-x1+x3)+c4*(2*x2);var vy=c1*(-y1+3*y2-3*y3+y4)+c2*(2*y1-5*y2+4*y3-y4)+c3*(-y1+y3)+c4*(2*y2);var vz=c1*(-z1+3*z2-3*z3+z4)+c2*(2*z1-5*z2+4*z3-z4)+c3*(-z1+z3)+c4*(2*z2);this.vertex(vx,vy,vz);}this.endShape();return this;};/** * Draw a line given two points * @private * @param {Number} x0 x-coordinate of first vertex * @param {Number} y0 y-coordinate of first vertex * @param {Number} z0 z-coordinate of first vertex * @param {Number} x1 x-coordinate of second vertex * @param {Number} y1 y-coordinate of second vertex * @param {Number} z1 z-coordinate of second vertex * @chainable * @example * <div> * <code> * //draw a line * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * // Use fill instead of stroke to change the color of shape. * fill(255, 0, 0); * line(10, 10, 0, 60, 60, 20); * } * </code> * </div> */p5.RendererGL.prototype.line=function(){if(arguments.length===6){this.beginShape();this.vertex(arguments[0],arguments[1],arguments[2]);this.vertex(arguments[3],arguments[4],arguments[5]);this.endShape();}else if(arguments.length===4){this.beginShape();this.vertex(arguments[0],arguments[1],0);this.vertex(arguments[2],arguments[3],0);this.endShape();}return this;};p5.RendererGL.prototype.bezierVertex=function(){if(this.immediateMode._bezierVertex.length===0){throw Error('vertex() must be used once before calling bezierVertex()');}else{var w_x=[];var w_y=[];var w_z=[];var t,_x,_y,_z,i;var argLength=arguments.length;t=0;if(this._lookUpTableBezier.length===0||this._lutBezierDetail!==this._pInst._curveDetail){this._lookUpTableBezier=[];this._lutBezierDetail=this._pInst._curveDetail;var step=1/this._lutBezierDetail;var start=0;var end=1;var j=0;while(start<1){t=parseFloat(start.toFixed(6));this._lookUpTableBezier[j]=this._bezierCoefficients(t);if(end.toFixed(6)===step.toFixed(6)){t=parseFloat(end.toFixed(6))+parseFloat(start.toFixed(6));++j;this._lookUpTableBezier[j]=this._bezierCoefficients(t);break;}start+=step;end-=step;++j;}}var LUTLength=this._lookUpTableBezier.length;if(argLength===6){this.isBezier=true;w_x=[this.immediateMode._bezierVertex[0],arguments[0],arguments[2],arguments[4]];w_y=[this.immediateMode._bezierVertex[1],arguments[1],arguments[3],arguments[5]];for(i=0;i<LUTLength;i++){_x=w_x[0]*this._lookUpTableBezier[i][0]+w_x[1]*this._lookUpTableBezier[i][1]+w_x[2]*this._lookUpTableBezier[i][2]+w_x[3]*this._lookUpTableBezier[i][3];_y=w_y[0]*this._lookUpTableBezier[i][0]+w_y[1]*this._lookUpTableBezier[i][1]+w_y[2]*this._lookUpTableBezier[i][2]+w_y[3]*this._lookUpTableBezier[i][3];this.vertex(_x,_y);}this.immediateMode._bezierVertex[0]=arguments[4];this.immediateMode._bezierVertex[1]=arguments[5];}else if(argLength===9){this.isBezier=true;w_x=[this.immediateMode._bezierVertex[0],arguments[0],arguments[3],arguments[6]];w_y=[this.immediateMode._bezierVertex[1],arguments[1],arguments[4],arguments[7]];w_z=[this.immediateMode._bezierVertex[2],arguments[2],arguments[5],arguments[8]];for(i=0;i<LUTLength;i++){_x=w_x[0]*this._lookUpTableBezier[i][0]+w_x[1]*this._lookUpTableBezier[i][1]+w_x[2]*this._lookUpTableBezier[i][2]+w_x[3]*this._lookUpTableBezier[i][3];_y=w_y[0]*this._lookUpTableBezier[i][0]+w_y[1]*this._lookUpTableBezier[i][1]+w_y[2]*this._lookUpTableBezier[i][2]+w_y[3]*this._lookUpTableBezier[i][3];_z=w_z[0]*this._lookUpTableBezier[i][0]+w_z[1]*this._lookUpTableBezier[i][1]+w_z[2]*this._lookUpTableBezier[i][2]+w_z[3]*this._lookUpTableBezier[i][3];this.vertex(_x,_y,_z);}this.immediateMode._bezierVertex[0]=arguments[6];this.immediateMode._bezierVertex[1]=arguments[7];this.immediateMode._bezierVertex[2]=arguments[8];}}};p5.RendererGL.prototype.quadraticVertex=function(){if(this.immediateMode._quadraticVertex.length===0){throw Error('vertex() must be used once before calling quadraticVertex()');}else{var w_x=[];var w_y=[];var w_z=[];var t,_x,_y,_z,i;var argLength=arguments.length;t=0;if(this._lookUpTableQuadratic.length===0||this._lutQuadraticDetail!==this._pInst._curveDetail){this._lookUpTableQuadratic=[];this._lutQuadraticDetail=this._pInst._curveDetail;var step=1/this._lutQuadraticDetail;var start=0;var end=1;var j=0;while(start<1){t=parseFloat(start.toFixed(6));this._lookUpTableQuadratic[j]=this._quadraticCoefficients(t);if(end.toFixed(6)===step.toFixed(6)){t=parseFloat(end.toFixed(6))+parseFloat(start.toFixed(6));++j;this._lookUpTableQuadratic[j]=this._quadraticCoefficients(t);break;}start+=step;end-=step;++j;}}var LUTLength=this._lookUpTableQuadratic.length;if(argLength===4){this.isQuadratic=true;w_x=[this.immediateMode._quadraticVertex[0],arguments[0],arguments[2]];w_y=[this.immediateMode._quadraticVertex[1],arguments[1],arguments[3]];for(i=0;i<LUTLength;i++){_x=w_x[0]*this._lookUpTableQuadratic[i][0]+w_x[1]*this._lookUpTableQuadratic[i][1]+w_x[2]*this._lookUpTableQuadratic[i][2];_y=w_y[0]*this._lookUpTableQuadratic[i][0]+w_y[1]*this._lookUpTableQuadratic[i][1]+w_y[2]*this._lookUpTableQuadratic[i][2];this.vertex(_x,_y);}this.immediateMode._quadraticVertex[0]=arguments[2];this.immediateMode._quadraticVertex[1]=arguments[3];}else if(argLength===6){this.isQuadratic=true;w_x=[this.immediateMode._quadraticVertex[0],arguments[0],arguments[3]];w_y=[this.immediateMode._quadraticVertex[1],arguments[1],arguments[4]];w_z=[this.immediateMode._quadraticVertex[2],arguments[2],arguments[5]];for(i=0;i<LUTLength;i++){_x=w_x[0]*this._lookUpTableQuadratic[i][0]+w_x[1]*this._lookUpTableQuadratic[i][1]+w_x[2]*this._lookUpTableQuadratic[i][2];_y=w_y[0]*this._lookUpTableQuadratic[i][0]+w_y[1]*this._lookUpTableQuadratic[i][1]+w_y[2]*this._lookUpTableQuadratic[i][2];_z=w_z[0]*this._lookUpTableQuadratic[i][0]+w_z[1]*this._lookUpTableQuadratic[i][1]+w_z[2]*this._lookUpTableQuadratic[i][2];this.vertex(_x,_y,_z);}this.immediateMode._quadraticVertex[0]=arguments[3];this.immediateMode._quadraticVertex[1]=arguments[4];this.immediateMode._quadraticVertex[2]=arguments[5];}}};p5.RendererGL.prototype.curveVertex=function(){var w_x=[];var w_y=[];var w_z=[];var t,_x,_y,_z,i;t=0;var argLength=arguments.length;if(this._lookUpTableBezier.length===0||this._lutBezierDetail!==this._pInst._curveDetail){this._lookUpTableBezier=[];this._lutBezierDetail=this._pInst._curveDetail;var step=1/this._lutBezierDetail;var start=0;var end=1;var j=0;while(start<1){t=parseFloat(start.toFixed(6));this._lookUpTableBezier[j]=this._bezierCoefficients(t);if(end.toFixed(6)===step.toFixed(6)){t=parseFloat(end.toFixed(6))+parseFloat(start.toFixed(6));++j;this._lookUpTableBezier[j]=this._bezierCoefficients(t);break;}start+=step;end-=step;++j;}}var LUTLength=this._lookUpTableBezier.length;if(argLength===2){this.immediateMode._curveVertex.push(arguments[0]);this.immediateMode._curveVertex.push(arguments[1]);if(this.immediateMode._curveVertex.length===8){this.isCurve=true;w_x=this._bezierToCatmull([this.immediateMode._curveVertex[0],this.immediateMode._curveVertex[2],this.immediateMode._curveVertex[4],this.immediateMode._curveVertex[6]]);w_y=this._bezierToCatmull([this.immediateMode._curveVertex[1],this.immediateMode._curveVertex[3],this.immediateMode._curveVertex[5],this.immediateMode._curveVertex[7]]);for(i=0;i<LUTLength;i++){_x=w_x[0]*this._lookUpTableBezier[i][0]+w_x[1]*this._lookUpTableBezier[i][1]+w_x[2]*this._lookUpTableBezier[i][2]+w_x[3]*this._lookUpTableBezier[i][3];_y=w_y[0]*this._lookUpTableBezier[i][0]+w_y[1]*this._lookUpTableBezier[i][1]+w_y[2]*this._lookUpTableBezier[i][2]+w_y[3]*this._lookUpTableBezier[i][3];this.vertex(_x,_y);}for(i=0;i<argLength;i++){this.immediateMode._curveVertex.shift();}}}else if(argLength===3){this.immediateMode._curveVertex.push(arguments[0]);this.immediateMode._curveVertex.push(arguments[1]);this.immediateMode._curveVertex.push(arguments[2]);if(this.immediateMode._curveVertex.length===12){this.isCurve=true;w_x=this._bezierToCatmull([this.immediateMode._curveVertex[0],this.immediateMode._curveVertex[3],this.immediateMode._curveVertex[6],this.immediateMode._curveVertex[9]]);w_y=this._bezierToCatmull([this.immediateMode._curveVertex[1],this.immediateMode._curveVertex[4],this.immediateMode._curveVertex[7],this.immediateMode._curveVertex[10]]);w_z=this._bezierToCatmull([this.immediateMode._curveVertex[2],this.immediateMode._curveVertex[5],this.immediateMode._curveVertex[8],this.immediateMode._curveVertex[11]]);for(i=0;i<LUTLength;i++){_x=w_x[0]*this._lookUpTableBezier[i][0]+w_x[1]*this._lookUpTableBezier[i][1]+w_x[2]*this._lookUpTableBezier[i][2]+w_x[3]*this._lookUpTableBezier[i][3];_y=w_y[0]*this._lookUpTableBezier[i][0]+w_y[1]*this._lookUpTableBezier[i][1]+w_y[2]*this._lookUpTableBezier[i][2]+w_y[3]*this._lookUpTableBezier[i][3];_z=w_z[0]*this._lookUpTableBezier[i][0]+w_z[1]*this._lookUpTableBezier[i][1]+w_z[2]*this._lookUpTableBezier[i][2]+w_z[3]*this._lookUpTableBezier[i][3];this.vertex(_x,_y,_z);}for(i=0;i<argLength;i++){this.immediateMode._curveVertex.shift();}}}};module.exports=p5;},{"../core/constants":19,"../core/main":25,"./p5.Geometry":71}],66:[function(_dereq_,module,exports){/** * @module Lights, Camera * @submodule Interaction * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');/** * Allows movement around a 3D sketch using a mouse or trackpad. Left-clicking * and dragging will rotate the camera position about the center of the sketch, * right-clicking and dragging will pan the camera position without rotation, * and using the mouse wheel (scrolling) will move the camera closer or further * from the center of the sketch. This function can be called with parameters * dictating sensitivity to mouse movement along the X and Y axes. Calling * this function without parameters is equivalent to calling orbitControl(1,1). * To reverse direction of movement in either axis, enter a negative number * for sensitivity. * @method orbitControl * @for p5 * @param {Number} [sensitivityX] sensitivity to mouse movement along X axis * @param {Number} [sensitivityY] sensitivity to mouse movement along Y axis * @chainable * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * normalMaterial(); * } * function draw() { * background(200); * orbitControl(); * rotateY(0.5); * box(30, 50); * } * </code> * </div> * * @alt * Camera orbits around a box when mouse is hold-clicked & then moved. */// implementation based on three.js 'orbitControls': // https://github.com/mrdoob/three.js/blob/dev/examples/js/controls/OrbitControls.js p5.prototype.orbitControl=function(sensitivityX,sensitivityY){this._assert3d('orbitControl');p5._validateParameters('orbitControl',arguments);// If the mouse is not in bounds of the canvas, disable all behaviors: var mouseInCanvas=this.mouseX<this.width&&this.mouseX>0&&this.mouseY<this.height&&this.mouseY>0;if(!mouseInCanvas)return;var cam=this._renderer._curCamera;if(typeof sensitivityX==='undefined'){sensitivityX=1;}if(typeof sensitivityY==='undefined'){sensitivityY=sensitivityX;}// default right-mouse and mouse-wheel behaviors (context menu and scrolling, // respectively) are disabled here to allow use of those events for panning and // zooming // disable context menu for canvas element and add 'contextMenuDisabled' // flag to p5 instance if(this.contextMenuDisabled!==true){this.canvas.oncontextmenu=function(){return false;};this._setProperty('contextMenuDisabled',true);}// disable default scrolling behavior on the canvas element and add // 'wheelDefaultDisabled' flag to p5 instance if(this.wheelDefaultDisabled!==true){this.canvas.onwheel=function(){return false;};this._setProperty('wheelDefaultDisabled',true);}var scaleFactor=this.height<this.width?this.height:this.width;// ZOOM if there is a change in mouseWheelDelta if(this._mouseWheelDeltaY!==this._pmouseWheelDeltaY){// zoom according to direction of mouseWheelDeltaY rather than value if(this._mouseWheelDeltaY>0){this._renderer._curCamera._orbit(0,0,0.5*scaleFactor);}else{this._renderer._curCamera._orbit(0,0,-0.5*scaleFactor);}}if(this.mouseIsPressed){// ORBIT BEHAVIOR if(this.mouseButton===this.LEFT){var deltaTheta=-sensitivityX*(this.mouseX-this.pmouseX)/scaleFactor;var deltaPhi=sensitivityY*(this.mouseY-this.pmouseY)/scaleFactor;this._renderer._curCamera._orbit(deltaTheta,deltaPhi,0);}else if(this.mouseButton===this.RIGHT){// PANNING BEHAVIOR along X/Z camera axes and restricted to X/Z plane // in world space var local=cam._getLocalAxes();// normalize portions along X/Z axes var xmag=Math.sqrt(local.x[0]*local.x[0]+local.x[2]*local.x[2]);if(xmag!==0){local.x[0]/=xmag;local.x[2]/=xmag;}// normalize portions along X/Z axes var ymag=Math.sqrt(local.y[0]*local.y[0]+local.y[2]*local.y[2]);if(ymag!==0){local.y[0]/=ymag;local.y[2]/=ymag;}// move along those vectors by amount controlled by mouseX, pmouseY var dx=-1*sensitivityX*(this.mouseX-this.pmouseX);var dz=-1*sensitivityY*(this.mouseY-this.pmouseY);// restrict movement to XZ plane in world space cam.setPosition(cam.eyeX+dx*local.x[0]+dz*local.z[0],cam.eyeY,cam.eyeZ+dx*local.x[2]+dz*local.z[2]);}}return this;};/** * debugMode() helps visualize 3D space by adding a grid to indicate where the * ‘ground’ is in a sketch and an axes icon which indicates the +X, +Y, and +Z * directions. This function can be called without parameters to create a * default grid and axes icon, or it can be called according to the examples * above to customize the size and position of the grid and/or axes icon. The * grid is drawn using the most recently set stroke color and weight. To * specify these parameters, add a call to stroke() and strokeWeight() * just before the end of the draw() loop. * * By default, the grid will run through the origin (0,0,0) of the sketch * along the XZ plane * and the axes icon will be offset from the origin. Both the grid and axes * icon will be sized according to the current canvas size. Note that because the * grid runs parallel to the default camera view, it is often helpful to use * debugMode along with orbitControl to allow full view of the grid. * @method debugMode * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); * normalMaterial(); * debugMode(); * } * * function draw() { * background(200); * orbitControl(); * box(15, 30); * // Press the spacebar to turn debugMode off! * if (keyIsDown(32)) { * noDebugMode(); * } * } * </code> * </div> * @alt * a 3D box is centered on a grid in a 3D sketch. an icon * indicates the direction of each axis: a red line points +X, * a green line +Y, and a blue line +Z. the grid and icon disappear when the * spacebar is pressed. * * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); * normalMaterial(); * debugMode(GRID); * } * * function draw() { * background(200); * orbitControl(); * box(15, 30); * } * </code> * </div> * @alt * a 3D box is centered on a grid in a 3D sketch. * * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); * normalMaterial(); * debugMode(AXES); * } * * function draw() { * background(200); * orbitControl(); * box(15, 30); * } * </code> * </div> * @alt * a 3D box is centered in a 3D sketch. an icon * indicates the direction of each axis: a red line points +X, * a green line +Y, and a blue line +Z. * * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); * normalMaterial(); * debugMode(GRID, 100, 10, 0, 0, 0); * } * * function draw() { * background(200); * orbitControl(); * box(15, 30); * } * </code> * </div> * @alt * a 3D box is centered on a grid in a 3D sketch * * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); * normalMaterial(); * debugMode(100, 10, 0, 0, 0, 20, 0, -40, 0); * } * * function draw() { * noStroke(); * background(200); * orbitControl(); * box(15, 30); * // set the stroke color and weight for the grid! * stroke(255, 0, 150); * strokeWeight(0.8); * } * </code> * </div> * @alt * a 3D box is centered on a grid in a 3D sketch. an icon * indicates the direction of each axis: a red line points +X, * a green line +Y, and a blue line +Z. *//** * @method debugMode * @param {Constant} mode either GRID or AXES *//** * @method debugMode * @param {Constant} mode * @param {Number} [gridSize] size of one side of the grid * @param {Number} [gridDivisions] number of divisions in the grid * @param {Number} [xOff] X axis offset from origin (0,0,0) * @param {Number} [yOff] Y axis offset from origin (0,0,0) * @param {Number} [zOff] Z axis offset from origin (0,0,0) *//** * @method debugMode * @param {Constant} mode * @param {Number} [axesSize] size of axes icon * @param {Number} [xOff] * @param {Number} [yOff] * @param {Number} [zOff] *//** * @method debugMode * @param {Number} [gridSize] * @param {Number} [gridDivisions] * @param {Number} [xOff] * @param {Number} [yOff] * @param {Number} [zOff] * @param {Number} [axesSize] * @param {Number} [xOff] * @param {Number} [yOff] * @param {Number} [zOff] */p5.prototype.debugMode=function(){this._assert3d('debugMode');p5._validateParameters('debugMode',arguments);// start by removing existing 'post' registered debug methods for(var i=this._registeredMethods.post.length-1;i>=0;i--){// test for equality... if(this._registeredMethods.post[i].toString()===this._grid().toString()||this._registeredMethods.post[i].toString()===this._axesIcon().toString()){this._registeredMethods.post.splice(i,1);}}// then add new debugMode functions according to the argument list if(arguments[0]===constants.GRID){this.registerMethod('post',this._grid.call(this,arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]));}else if(arguments[0]===constants.AXES){this.registerMethod('post',this._axesIcon.call(this,arguments[1],arguments[2],arguments[3],arguments[4]));}else{this.registerMethod('post',this._grid.call(this,arguments[0],arguments[1],arguments[2],arguments[3],arguments[4]));this.registerMethod('post',this._axesIcon.call(this,arguments[5],arguments[6],arguments[7],arguments[8]));}};/** * Turns off debugMode() in a 3D sketch. * @method noDebugMode * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * camera(0, -30, 100, 0, 0, 0, 0, 1, 0); * normalMaterial(); * debugMode(); * } * * function draw() { * background(200); * orbitControl(); * box(15, 30); * // Press the spacebar to turn debugMode off! * if (keyIsDown(32)) { * noDebugMode(); * } * } * </code> * </div> * @alt * a 3D box is centered on a grid in a 3D sketch. an icon * indicates the direction of each axis: a red line points +X, * a green line +Y, and a blue line +Z. the grid and icon disappear when the * spacebar is pressed. */p5.prototype.noDebugMode=function(){this._assert3d('noDebugMode');// start by removing existing 'post' registered debug methods for(var i=this._registeredMethods.post.length-1;i>=0;i--){// test for equality... if(this._registeredMethods.post[i].toString()===this._grid().toString()||this._registeredMethods.post[i].toString()===this._axesIcon().toString()){this._registeredMethods.post.splice(i,1);}}};/** * For use with debugMode * @private * @method _grid * @param {Number} [size] size of grid sides * @param {Number} [div] number of grid divisions * @param {Number} [xOff] offset of grid center from origin in X axis * @param {Number} [yOff] offset of grid center from origin in Y axis * @param {Number} [zOff] offset of grid center from origin in Z axis */p5.prototype._grid=function(size,numDivs,xOff,yOff,zOff){if(typeof size==='undefined'){size=this.width/2;}if(typeof numDivs==='undefined'){// ensure at least 2 divisions numDivs=Math.round(size/30)<4?4:Math.round(size/30);}if(typeof xOff==='undefined'){xOff=0;}if(typeof yOff==='undefined'){yOff=0;}if(typeof zOff==='undefined'){zOff=0;}var spacing=size/numDivs;var halfSize=size/2;return function(){this.push();this.stroke(this._renderer.curStrokeColor[0]*255,this._renderer.curStrokeColor[1]*255,this._renderer.curStrokeColor[2]*255);this._renderer.uMVMatrix.set(this._renderer._curCamera.cameraMatrix.mat4[0],this._renderer._curCamera.cameraMatrix.mat4[1],this._renderer._curCamera.cameraMatrix.mat4[2],this._renderer._curCamera.cameraMatrix.mat4[3],this._renderer._curCamera.cameraMatrix.mat4[4],this._renderer._curCamera.cameraMatrix.mat4[5],this._renderer._curCamera.cameraMatrix.mat4[6],this._renderer._curCamera.cameraMatrix.mat4[7],this._renderer._curCamera.cameraMatrix.mat4[8],this._renderer._curCamera.cameraMatrix.mat4[9],this._renderer._curCamera.cameraMatrix.mat4[10],this._renderer._curCamera.cameraMatrix.mat4[11],this._renderer._curCamera.cameraMatrix.mat4[12],this._renderer._curCamera.cameraMatrix.mat4[13],this._renderer._curCamera.cameraMatrix.mat4[14],this._renderer._curCamera.cameraMatrix.mat4[15]);// Lines along X axis for(var q=0;q<=numDivs;q++){this.beginShape(this.LINES);this.vertex(-halfSize+xOff,yOff,q*spacing-halfSize+zOff);this.vertex(+halfSize+xOff,yOff,q*spacing-halfSize+zOff);this.endShape();}// Lines along Z axis for(var i=0;i<=numDivs;i++){this.beginShape(this.LINES);this.vertex(i*spacing-halfSize+xOff,yOff,-halfSize+zOff);this.vertex(i*spacing-halfSize+xOff,yOff,+halfSize+zOff);this.endShape();}this.pop();};};/** * For use with debugMode * @private * @method _axesIcon * @param {Number} [size] size of axes icon lines * @param {Number} [xOff] offset of icon from origin in X axis * @param {Number} [yOff] offset of icon from origin in Y axis * @param {Number} [zOff] offset of icon from origin in Z axis */p5.prototype._axesIcon=function(size,xOff,yOff,zOff){if(typeof size==='undefined'){size=this.width/20>40?this.width/20:40;}if(typeof xOff==='undefined'){xOff=-this.width/4;}if(typeof yOff==='undefined'){yOff=xOff;}if(typeof zOff==='undefined'){zOff=xOff;}return function(){this.push();this._renderer.uMVMatrix.set(this._renderer._curCamera.cameraMatrix.mat4[0],this._renderer._curCamera.cameraMatrix.mat4[1],this._renderer._curCamera.cameraMatrix.mat4[2],this._renderer._curCamera.cameraMatrix.mat4[3],this._renderer._curCamera.cameraMatrix.mat4[4],this._renderer._curCamera.cameraMatrix.mat4[5],this._renderer._curCamera.cameraMatrix.mat4[6],this._renderer._curCamera.cameraMatrix.mat4[7],this._renderer._curCamera.cameraMatrix.mat4[8],this._renderer._curCamera.cameraMatrix.mat4[9],this._renderer._curCamera.cameraMatrix.mat4[10],this._renderer._curCamera.cameraMatrix.mat4[11],this._renderer._curCamera.cameraMatrix.mat4[12],this._renderer._curCamera.cameraMatrix.mat4[13],this._renderer._curCamera.cameraMatrix.mat4[14],this._renderer._curCamera.cameraMatrix.mat4[15]);// X axis this.strokeWeight(2);this.stroke(255,0,0);this.beginShape(this.LINES);this.vertex(xOff,yOff,zOff);this.vertex(xOff+size,yOff,zOff);this.endShape();// Y axis this.stroke(0,255,0);this.beginShape(this.LINES);this.vertex(xOff,yOff,zOff);this.vertex(xOff,yOff+size,zOff);this.endShape();// Z axis this.stroke(0,0,255);this.beginShape(this.LINES);this.vertex(xOff,yOff,zOff);this.vertex(xOff,yOff,zOff+size);this.endShape();this.pop();};};module.exports=p5;},{"../core/constants":19,"../core/main":25}],67:[function(_dereq_,module,exports){/** * @module Lights, Camera * @submodule Lights * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');/** * Creates an ambient light with a color * * @method ambientLight * @param {Number} v1 red or hue value relative to * the current color range * @param {Number} v2 green or saturation value * relative to the current color range * @param {Number} v3 blue or brightness value * relative to the current color range * @param {Number} [alpha] the alpha value * @chainable * * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(0); * ambientLight(150); * ambientMaterial(250); * noStroke(); * sphere(25); * } * </code> * </div> * * @alt * evenly distributed light across a sphere * *//** * @method ambientLight * @param {String} value a color string * @chainable *//** * @method ambientLight * @param {Number} gray a gray value * @param {Number} [alpha] * @chainable *//** * @method ambientLight * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color * @chainable *//** * @method ambientLight * @param {p5.Color} color the ambient light color * @chainable */p5.prototype.ambientLight=function(v1,v2,v3,a){this._assert3d('ambientLight');p5._validateParameters('ambientLight',arguments);var color=this.color.apply(this,arguments);var shader=this._renderer._useLightShader();//@todo this is a bit icky. array uniforms have //to be multiples of the type 3(rgb) in this case. //a preallocated Float32Array(24) that we copy into //would be better shader.setUniform('uUseLighting',true);//in case there's no material color for the geometry shader.setUniform('uMaterialColor',this._renderer.curFillColor);this._renderer.ambientLightColors.push(color._array[0],color._array[1],color._array[2]);shader.setUniform('uAmbientColor',this._renderer.ambientLightColors);shader.setUniform('uAmbientLightCount',this._renderer.ambientLightColors.length/3);return this;};/** * Creates a directional light with a color and a direction * @method directionalLight * @param {Number} v1 red or hue value (depending on the current * color mode), * @param {Number} v2 green or saturation value * @param {Number} v3 blue or brightness value * @param {p5.Vector} position the direction of the light * @chainable * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(0); * //move your mouse to change light direction * var dirX = (mouseX / width - 0.5) * 2; * var dirY = (mouseY / height - 0.5) * 2; * directionalLight(250, 250, 250, -dirX, -dirY, 0.25); * ambientMaterial(250); * noStroke(); * sphere(25); * } * </code> * </div> * * @alt * light source on canvas changeable with mouse position * *//** * @method directionalLight * @param {Number[]|String|p5.Color} color color Array, CSS color string, * or <a href="#/p5.Color">p5.Color</a> value * @param {Number} x x axis direction * @param {Number} y y axis direction * @param {Number} z z axis direction * @chainable *//** * @method directionalLight * @param {Number[]|String|p5.Color} color * @param {p5.Vector} position * @chainable *//** * @method directionalLight * @param {Number} v1 * @param {Number} v2 * @param {Number} v3 * @param {Number} x * @param {Number} y * @param {Number} z * @chainable */p5.prototype.directionalLight=function(v1,v2,v3,x,y,z){this._assert3d('directionalLight');p5._validateParameters('directionalLight',arguments);var shader=this._renderer._useLightShader();//@TODO: check parameters number var color;if(v1 instanceof p5.Color){color=v1;}else{color=this.color(v1,v2,v3);}var _x,_y,_z;var v=arguments[arguments.length-1];if(typeof v==='number'){_x=arguments[arguments.length-3];_y=arguments[arguments.length-2];_z=arguments[arguments.length-1];}else{_x=v.x;_y=v.y;_z=v.z;}shader.setUniform('uUseLighting',true);//in case there's no material color for the geometry shader.setUniform('uMaterialColor',this._renderer.curFillColor);// normalize direction var l=Math.sqrt(_x*_x+_y*_y+_z*_z);this._renderer.directionalLightDirections.push(_x/l,_y/l,_z/l);shader.setUniform('uLightingDirection',this._renderer.directionalLightDirections);this._renderer.directionalLightColors.push(color._array[0],color._array[1],color._array[2]);shader.setUniform('uDirectionalColor',this._renderer.directionalLightColors);shader.setUniform('uDirectionalLightCount',this._renderer.directionalLightColors.length/3);return this;};/** * Creates a point light with a color and a light position * @method pointLight * @param {Number} v1 red or hue value (depending on the current * color mode), * @param {Number} v2 green or saturation value * @param {Number} v3 blue or brightness value * @param {Number} x x axis position * @param {Number} y y axis position * @param {Number} z z axis position * @chainable * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(0); * //move your mouse to change light position * var locX = mouseX - width / 2; * var locY = mouseY - height / 2; * // to set the light position, * // think of the world's coordinate as: * // -width/2,-height/2 -------- width/2,-height/2 * // | | * // | 0,0 | * // | | * // -width/2,height/2--------width/2,height/2 * pointLight(250, 250, 250, locX, locY, 50); * ambientMaterial(250); * noStroke(); * sphere(25); * } * </code> * </div> * * @alt * spot light on canvas changes position with mouse * *//** * @method pointLight * @param {Number} v1 * @param {Number} v2 * @param {Number} v3 * @param {p5.Vector} position the position of the light * @chainable *//** * @method pointLight * @param {Number[]|String|p5.Color} color color Array, CSS color string, * or <a href="#/p5.Color">p5.Color</a> value * @param {Number} x * @param {Number} y * @param {Number} z * @chainable *//** * @method pointLight * @param {Number[]|String|p5.Color} color * @param {p5.Vector} position * @chainable */p5.prototype.pointLight=function(v1,v2,v3,x,y,z){this._assert3d('pointLight');p5._validateParameters('pointLight',arguments);//@TODO: check parameters number var color;if(v1 instanceof p5.Color){color=v1;}else{color=this.color(v1,v2,v3);}var _x,_y,_z;var v=arguments[arguments.length-1];if(typeof v==='number'){_x=arguments[arguments.length-3];_y=arguments[arguments.length-2];_z=arguments[arguments.length-1];}else{_x=v.x;_y=v.y;_z=v.z;}var shader=this._renderer._useLightShader();shader.setUniform('uUseLighting',true);//in case there's no material color for the geometry shader.setUniform('uMaterialColor',this._renderer.curFillColor);this._renderer.pointLightPositions.push(_x,_y,_z);shader.setUniform('uPointLightLocation',this._renderer.pointLightPositions);this._renderer.pointLightColors.push(color._array[0],color._array[1],color._array[2]);shader.setUniform('uPointLightColor',this._renderer.pointLightColors);shader.setUniform('uPointLightCount',this._renderer.pointLightColors.length/3);return this;};module.exports=p5;},{"../core/main":25}],68:[function(_dereq_,module,exports){/** * @module Shape * @submodule 3D Models * @for p5 * @requires core * @requires p5.Geometry */'use strict';var p5=_dereq_('../core/main');_dereq_('./p5.Geometry');/** * Load a 3d model from an OBJ file. * <br><br> * One of the limitations of the OBJ format is that it doesn't have a built-in * sense of scale. This means that models exported from different programs might * be very different sizes. If your model isn't displaying, try calling * <a href="#/p5/loadModel">loadModel()</a> with the normalized parameter set to true. This will resize the * model to a scale appropriate for p5. You can also make additional changes to * the final size of your model with the <a href="#/p5/scale">scale()</a> function. * * @method loadModel * @param {String} path Path of the model to be loaded * @param {Boolean} normalize If true, scale the model to a * standardized size when loading * @param {function(p5.Geometry)} [successCallback] Function to be called * once the model is loaded. Will be passed * the 3D model object. * @param {function(Event)} [failureCallback] called with event error if * the image fails to load. * @return {p5.Geometry} the <a href="#/p5.Geometry">p5.Geometry</a> object * * @example * <div> * <code> * //draw a spinning octahedron * var octahedron; * * function preload() { * octahedron = loadModel('assets/octahedron.obj'); * } * * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * model(octahedron); * } * </code> * </div> * * @alt * Vertically rotating 3-d octahedron. * * @example * <div> * <code> * //draw a spinning teapot * var teapot; * * function preload() { * // Load model with normalise parameter set to true * teapot = loadModel('assets/teapot.obj', true); * } * * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * scale(0.4); // Scaled to make model fit into canvas * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * normalMaterial(); // For effect * model(teapot); * } * </code> * </div> * * @alt * Vertically rotating 3-d teapot with red, green and blue gradient. *//** * @method loadModel * @param {String} path * @param {function(p5.Geometry)} [successCallback] * @param {function(Event)} [failureCallback] * @return {p5.Geometry} the <a href="#/p5.Geometry">p5.Geometry</a> object */p5.prototype.loadModel=function(path){p5._validateParameters('loadModel',arguments);var normalize;var successCallback;var failureCallback;if(typeof arguments[1]==='boolean'){normalize=arguments[1];successCallback=arguments[2];failureCallback=arguments[3];}else{normalize=false;successCallback=arguments[1];failureCallback=arguments[2];}var model=new p5.Geometry();model.gid=path+'|'+normalize;var self=this;this.loadStrings(path,function(strings){parseObj(model,strings);if(normalize){model.normalize();}self._decrementPreload();if(typeof successCallback==='function'){successCallback(model);}}.bind(this),failureCallback);return model;};/** * Parse OBJ lines into model. For reference, this is what a simple model of a * square might look like: * * v -0.5 -0.5 0.5 * v -0.5 -0.5 -0.5 * v -0.5 0.5 -0.5 * v -0.5 0.5 0.5 * * f 4 3 2 1 */function parseObj(model,lines){// OBJ allows a face to specify an index for a vertex (in the above example), // but it also allows you to specify a custom combination of vertex, UV // coordinate, and vertex normal. So, "3/4/3" would mean, "use vertex 3 with // UV coordinate 4 and vertex normal 3". In WebGL, every vertex with different // parameters must be a different vertex, so loadedVerts is used to // temporarily store the parsed vertices, normals, etc., and indexedVerts is // used to map a specific combination (keyed on, for example, the string // "3/4/3"), to the actual index of the newly created vertex in the final // object. var loadedVerts={v:[],vt:[],vn:[]};var indexedVerts={};for(var line=0;line<lines.length;++line){// Each line is a separate object (vertex, face, vertex normal, etc) // For each line, split it into tokens on whitespace. The first token // describes the type. var tokens=lines[line].trim().split(/\b\s+/);if(tokens.length>0){if(tokens[0]==='v'||tokens[0]==='vn'){// Check if this line describes a vertex or vertex normal. // It will have three numeric parameters. var vertex=new p5.Vector(parseFloat(tokens[1]),parseFloat(tokens[2]),parseFloat(tokens[3]));loadedVerts[tokens[0]].push(vertex);}else if(tokens[0]==='vt'){// Check if this line describes a texture coordinate. // It will have two numeric parameters. var texVertex=[parseFloat(tokens[1]),parseFloat(tokens[2])];loadedVerts[tokens[0]].push(texVertex);}else if(tokens[0]==='f'){// Check if this line describes a face. // OBJ faces can have more than three points. Triangulate points. for(var tri=3;tri<tokens.length;++tri){var face=[];var vertexTokens=[1,tri-1,tri];for(var tokenInd=0;tokenInd<vertexTokens.length;++tokenInd){// Now, convert the given token into an index var vertString=tokens[vertexTokens[tokenInd]];var vertIndex=0;// TODO: Faces can technically use negative numbers to refer to the // previous nth vertex. I haven't seen this used in practice, but // it might be good to implement this in the future. if(indexedVerts[vertString]!==undefined){vertIndex=indexedVerts[vertString];}else{var vertParts=vertString.split('/');for(var i=0;i<vertParts.length;i++){vertParts[i]=parseInt(vertParts[i])-1;}vertIndex=indexedVerts[vertString]=model.vertices.length;model.vertices.push(loadedVerts.v[vertParts[0]].copy());if(loadedVerts.vt[vertParts[1]]){model.uvs.push(loadedVerts.vt[vertParts[1]].slice());}else{model.uvs.push([0,0]);}if(loadedVerts.vn[vertParts[2]]){model.vertexNormals.push(loadedVerts.vn[vertParts[2]].copy());}}face.push(vertIndex);}if(face[0]!==face[1]&&face[0]!==face[2]&&face[1]!==face[2]){model.faces.push(face);}}}}}// If the model doesn't have normals, compute the normals if(model.vertexNormals.length===0){model.computeNormals();}return model;}/** * Render a 3d model to the screen. * * @method model * @param {p5.Geometry} model Loaded 3d model to be rendered * @example * <div> * <code> * //draw a spinning octahedron * var octahedron; * * function preload() { * octahedron = loadModel('assets/octahedron.obj'); * } * * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * model(octahedron); * } * </code> * </div> * * @alt * Vertically rotating 3-d octahedron. * */p5.prototype.model=function(model){this._assert3d('model');p5._validateParameters('model',arguments);if(model.vertices.length>0){if(!this._renderer.geometryInHash(model.gid)){model._makeTriangleEdges()._edgesToVertices();this._renderer.createBuffers(model.gid,model);}this._renderer.drawBuffers(model.gid);}};module.exports=p5;},{"../core/main":25,"./p5.Geometry":71}],69:[function(_dereq_,module,exports){/** * @module Lights, Camera * @submodule Material * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');_dereq_('./p5.Texture');/** * Loads a custom shader from the provided vertex and fragment * shader paths. The shader files are loaded asynchronously in the * background, so this method should be used in <a href="#/p5/preload">preload()</a>. * * For now, there are three main types of shaders. p5 will automatically * supply appropriate vertices, normals, colors, and lighting attributes * if the parameters defined in the shader match the names. * * @method loadShader * @param {String} [vertFilename] path to file containing vertex shader * source code * @param {String} [fragFilename] path to file containing fragment shader * source code * @return {p5.Shader} a shader object created from the provided * vertex and fragment shader files. * * @example * <div modernizr='webgl'> * <code> * var mandel; * function preload() { * // load the shader definitions from files * mandel = loadShader('assets/shader.vert', 'assets/shader.frag'); * } * function setup() { * createCanvas(100, 100, WEBGL); * // use the shader * shader(mandel); * noStroke(); * mandel.setUniform('p', [-0.74364388703, 0.13182590421]); * } * * function draw() { * mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000)))); * quad(-1, -1, 1, -1, 1, 1, -1, 1); * } * </code> * </div> * * @alt * zooming Mandelbrot set. a colorful, infinitely detailed fractal. */p5.prototype.loadShader=function(vertFilename,fragFilename){p5._validateParameters('loadShader',arguments);var loadedShader=new p5.Shader();var self=this;var loadedFrag=false;var loadedVert=false;this.loadStrings(fragFilename,function(result){loadedShader._fragSrc=result.join('\n');loadedFrag=true;if(loadedVert){self._decrementPreload();}});this.loadStrings(vertFilename,function(result){loadedShader._vertSrc=result.join('\n');loadedVert=true;if(loadedFrag){self._decrementPreload();}});return loadedShader;};/** * @method createShader * @param {String} vertSrc source code for the vertex shader * @param {String} fragSrc source code for the fragment shader * @returns {p5.Shader} a shader object created from the provided * vertex and fragment shaders. * * @example * <div modernizr='webgl'> * <code> * // the 'varying's are shared between both vertex & fragment shaders * var varying = 'precision highp float; varying vec2 vPos;'; * * // the vertex shader is called for each vertex * var vs = * varying + * 'attribute vec3 aPosition;' + * 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }'; * * // the fragment shader is called for each pixel * var fs = * varying + * 'uniform vec2 p;' + * 'uniform float r;' + * 'const int I = 500;' + * 'void main() {' + * ' vec2 c = p + vPos * r, z = c;' + * ' float n = 0.0;' + * ' for (int i = I; i > 0; i --) {' + * ' if(z.x*z.x+z.y*z.y > 4.0) {' + * ' n = float(i)/float(I);' + * ' break;' + * ' }' + * ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' + * ' }' + * ' gl_FragColor = vec4(0.5-cos(n*17.0)/2.0,0.5-cos(n*13.0)/2.0,0.5-cos(n*23.0)/2.0,1.0);' + * '}'; * * var mandel; * function setup() { * createCanvas(100, 100, WEBGL); * * // create and initialize the shader * mandel = createShader(vs, fs); * shader(mandel); * noStroke(); * * // 'p' is the center point of the Mandelbrot image * mandel.setUniform('p', [-0.74364388703, 0.13182590421]); * } * * function draw() { * // 'r' is the size of the image in Mandelbrot-space * mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000)))); * quad(-1, -1, 1, -1, 1, 1, -1, 1); * } * </code> * </div> * * @alt * zooming Mandelbrot set. a colorful, infinitely detailed fractal. */p5.prototype.createShader=function(vertSrc,fragSrc){this._assert3d('createShader');p5._validateParameters('createShader',arguments);return new p5.Shader(this._renderer,vertSrc,fragSrc);};/** * The <a href="#/p5/shader">shader()</a> function lets the user provide a custom shader * to fill in shapes in WEBGL mode. Users can create their * own shaders by loading vertex and fragment shaders with * <a href="#/p5/loadShader">loadShader()</a>. * * @method shader * @chainable * @param {p5.Shader} [s] the desired <a href="#/p5.Shader">p5.Shader</a> to use for rendering * shapes. */p5.prototype.shader=function(s){this._assert3d('shader');p5._validateParameters('shader',arguments);if(s._renderer===undefined){s._renderer=this._renderer;}if(s.isStrokeShader()){this._renderer.setStrokeShader(s);}else{this._renderer.setFillShader(s);}return this;};/** * Normal material for geometry. You can view all * possible materials in this * <a href="https://p5js.org/examples/3d-materials.html">example</a>. * @method normalMaterial * @chainable * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * normalMaterial(); * sphere(50); * } * </code> * </div> * * @alt * Red, green and blue gradient. * */p5.prototype.normalMaterial=function(){this._assert3d('normalMaterial');p5._validateParameters('normalMaterial',arguments);this._renderer.drawMode=constants.FILL;this._renderer.setFillShader(this._renderer._getNormalShader());this._renderer.curFillColor=[1,1,1,1];this.noStroke();return this;};/** * Texture for geometry. You can view other possible materials in this * <a href="https://p5js.org/examples/3d-materials.html">example</a>. * @method texture * @param {p5.Image|p5.MediaElement|p5.Graphics} tex 2-dimensional graphics * to render as texture * @chainable * @example * <div> * <code> * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(0); * rotateZ(frameCount * 0.01); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * //pass image as texture * texture(img); * box(200, 200, 200); * } * </code> * </div> * * <div> * <code> * var pg; * function setup() { * createCanvas(100, 100, WEBGL); * pg = createGraphics(200, 200); * pg.textSize(100); * } * * function draw() { * background(0); * pg.background(255); * pg.text('hello!', 0, 100); * //pass image as texture * texture(pg); * plane(200); * } * </code> * </div> * * <div> * <code> * var vid; * function preload() { * vid = createVideo('assets/fingers.mov'); * vid.hide(); * vid.loop(); * } * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(0); * //pass video frame as texture * texture(vid); * plane(200); * } * </code> * </div> * * @alt * Rotating view of many images umbrella and grid roof on a 3d plane * black canvas * black canvas * */p5.prototype.texture=function(tex){this._assert3d('texture');p5._validateParameters('texture',arguments);this._renderer.drawMode=constants.TEXTURE;var shader=this._renderer._useLightShader();shader.setUniform('uSpecular',false);shader.setUniform('isTexture',true);shader.setUniform('uSampler',tex);this.noStroke();return this;};/** * Ambient material for geometry with a given color. You can view all * possible materials in this * <a href="https://p5js.org/examples/3d-materials.html">example</a>. * @method ambientMaterial * @param {Number} v1 gray value, red or hue value * (depending on the current color mode), * @param {Number} [v2] green or saturation value * @param {Number} [v3] blue or brightness value * @param {Number} [a] opacity * @chainable * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(0); * ambientLight(100); * pointLight(250, 250, 250, 100, 100, 0); * ambientMaterial(250); * sphere(50); * } * </code> * </div> * * @alt * radiating light source from top right of canvas * *//** * @method ambientMaterial * @param {Number[]|String|p5.Color} color color, color Array, or CSS color string * @chainable */p5.prototype.ambientMaterial=function(v1,v2,v3,a){this._assert3d('ambientMaterial');p5._validateParameters('ambientMaterial',arguments);var color=p5.prototype.color.apply(this,arguments);this._renderer.curFillColor=color._array;var shader=this._renderer._useLightShader();shader.setUniform('uMaterialColor',this._renderer.curFillColor);shader.setUniform('uSpecular',false);shader.setUniform('isTexture',false);return this;};/** * Specular material for geometry with a given color. You can view all * possible materials in this * <a href="https://p5js.org/examples/3d-materials.html">example</a>. * @method specularMaterial * @param {Number} v1 gray value, red or hue value * (depending on the current color mode), * @param {Number} [v2] green or saturation value * @param {Number} [v3] blue or brightness value * @param {Number} [a] opacity * @chainable * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(0); * ambientLight(100); * pointLight(250, 250, 250, 100, 100, 0); * specularMaterial(250); * sphere(50); * } * </code> * </div> * * @alt * diffused radiating light source from top right of canvas * *//** * @method specularMaterial * @param {Number[]|String|p5.Color} color color Array, or CSS color string * @chainable */p5.prototype.specularMaterial=function(v1,v2,v3,a){this._assert3d('specularMaterial');p5._validateParameters('specularMaterial',arguments);var color=p5.prototype.color.apply(this,arguments);this._renderer.curFillColor=color._array;var shader=this._renderer._useLightShader();shader.setUniform('uMaterialColor',this._renderer.curFillColor);shader.setUniform('uSpecular',true);shader.setUniform('isTexture',false);return this;};/** * @private blends colors according to color components. * If alpha value is less than 1, we need to enable blending * on our gl context. Otherwise opaque objects need to a depthMask. * @param {Number[]} color [description] * @return {Number[]]} Normalized numbers array */p5.RendererGL.prototype._applyColorBlend=function(colors){var gl=this.GL;var isTexture=this.drawMode===constants.TEXTURE;if(isTexture||colors[colors.length-1]<1.0){gl.depthMask(isTexture);gl.enable(gl.BLEND);gl.blendEquation(gl.FUNC_ADD);gl.blendFunc(gl.SRC_ALPHA,gl.ONE_MINUS_SRC_ALPHA);}else{gl.depthMask(true);gl.disable(gl.BLEND);}return colors;};module.exports=p5;},{"../core/constants":19,"../core/main":25,"./p5.Texture":77}],70:[function(_dereq_,module,exports){/** * @module Lights, Camera * @submodule Camera * @requires core */'use strict';var p5=_dereq_('../core/main');//////////////////////////////////////////////////////////////////////////////// // p5.Prototype Methods //////////////////////////////////////////////////////////////////////////////// /** * Sets the camera position for a 3D sketch. Parameters for this function define * the position for the camera, the center of the sketch (where the camera is * pointing), and an up direction (the orientation of the camera). * * When called with no arguments, this function creates a default camera * equivalent to * camera(0, 0, (height/2.0) / tan(PI*30.0 / 180.0), 0, 0, 0, 0, 1, 0); * @method camera * @for p5 * @param {Number} [x] camera position value on x axis * @param {Number} [y] camera position value on y axis * @param {Number} [z] camera position value on z axis * @param {Number} [centerX] x coordinate representing center of the sketch * @param {Number} [centerY] y coordinate representing center of the sketch * @param {Number} [centerZ] z coordinate representing center of the sketch * @param {Number} [upX] x component of direction 'up' from camera * @param {Number} [upY] y component of direction 'up' from camera * @param {Number} [upZ] z component of direction 'up' from camera * @chainable * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(204); * //move the camera away from the plane by a sin wave * camera(0, 0, 20 + sin(frameCount * 0.01) * 10, 0, 0, 0, 0, 1, 0); * plane(10, 10); * } * </code> * </div> * * @alt * White square repeatedly grows to fill canvas and then shrinks. * */p5.prototype.camera=function(){this._assert3d('camera');p5._validateParameters('camera',arguments);this._renderer._curCamera.camera.apply(this._renderer._curCamera,arguments);return this;};/** * Sets a perspective projection for the camera in a 3D sketch. This projection * represents depth through foreshortening: objects that are close to the camera * appear their actual size while those that are further away from the camera * appear smaller. The parameters to this function define the viewing frustum * (the truncated pyramid within which objects are seen by the camera) through * vertical field of view, aspect ratio (usually width/height), and near and far * clipping planes. * * When called with no arguments, the defaults * provided are equivalent to * perspective(PI/3.0, width/height, eyeZ/10.0, eyeZ*10.0), where eyeZ * is equal to ((height/2.0) / tan(PI*60.0/360.0)); * @method perspective * @for p5 * @param {Number} [fovy] camera frustum vertical field of view, * from bottom to top of view, in <a href="#/p5/angleMode">angleMode</a> units * @param {Number} [aspect] camera frustum aspect ratio * @param {Number} [near] frustum near plane length * @param {Number} [far] frustum far plane length * @chainable * @example * <div> * <code> * //drag the mouse to look around! * //you will see there's a vanishing point * function setup() { * createCanvas(100, 100, WEBGL); * perspective(PI / 3.0, width / height, 0.1, 500); * } * function draw() { * background(200); * orbitControl(); * normalMaterial(); * * rotateX(-0.3); * rotateY(-0.2); * translate(0, 0, -50); * * push(); * translate(-15, 0, sin(frameCount / 30) * 95); * box(30); * pop(); * push(); * translate(15, 0, sin(frameCount / 30 + PI) * 95); * box(30); * pop(); * } * </code> * </div> * * @alt * two colored 3D boxes move back and forth, rotating as mouse is dragged. * */p5.prototype.perspective=function(){this._assert3d('perspective');p5._validateParameters('perspective',arguments);this._renderer._curCamera.perspective.apply(this._renderer._curCamera,arguments);return this;};/** * Sets an orthographic projection for the camera in a 3D sketch and defines a * box-shaped viewing frustum within which objects are seen. In this projection, * all objects with the same dimension appear the same size, regardless of * whether they are near or far from the camera. The parameters to this * function specify the viewing frustum where left and right are the minimum and * maximum x values, top and bottom are the minimum and maximum y values, and near * and far are the minimum and maximum z values. If no parameters are given, the * default is used: ortho(-width/2, width/2, -height/2, height/2). * @method ortho * @for p5 * @param {Number} [left] camera frustum left plane * @param {Number} [right] camera frustum right plane * @param {Number} [bottom] camera frustum bottom plane * @param {Number} [top] camera frustum top plane * @param {Number} [near] camera frustum near plane * @param {Number} [far] camera frustum far plane * @chainable * @example * <div> * <code> * //drag the mouse to look around! * //there's no vanishing point * function setup() { * createCanvas(100, 100, WEBGL); * ortho(-width / 2, width / 2, height / 2, -height / 2, 0, 500); * } * function draw() { * background(200); * orbitControl(); * normalMaterial(); * * rotateX(0.2); * rotateY(-0.2); * push(); * translate(-15, 0, sin(frameCount / 30) * 65); * box(30); * pop(); * push(); * translate(15, 0, sin(frameCount / 30 + PI) * 65); * box(30); * pop(); * } * </code> * </div> * * @alt * two 3D boxes move back and forth along same plane, rotating as mouse is dragged. * */p5.prototype.ortho=function(){this._assert3d('ortho');p5._validateParameters('ortho',arguments);this._renderer._curCamera.ortho.apply(this._renderer._curCamera,arguments);return this;};//////////////////////////////////////////////////////////////////////////////// // p5.Camera //////////////////////////////////////////////////////////////////////////////// /** * Creates a new <a href="#/p5.Camera">p5.Camera</a> object and tells the * renderer to use that camera. * Returns the p5.Camera object. * @method createCamera * @return {p5.Camera} The newly created camera object. * @for p5 */p5.prototype.createCamera=function(){this._assert3d('createCamera');var _cam=new p5.Camera(this._renderer);// compute default camera settings, then set a default camera _cam._computeCameraDefaultSettings();_cam._setDefaultCamera();// set renderer current camera to the new camera this._renderer._curCamera=_cam;return _cam;};/** * This class describes a camera for use in p5's * <a href="https://github.com/processing/p5.js/wiki/Getting-started-with-WebGL-in-p5"> * WebGL mode</a>. It contains camera position, orientation, and projection * information necessary for rendering a 3D scene. * * New p5.Camera objects can be made through the * <a href="#/p5/createCamera">createCamera()</a> function and controlled through * the methods described below. A camera created in this way will use a default * position in the scene and a default perspective projection until these * properties are changed through the various methods available. It is possible * to create multiple cameras, in which case the current camera * can be set through the <a href="#/p5/setCamera">setCamera()</a> method. * * * Note: * The methods below operate in two coordinate systems: the 'world' coordinate * system describe positions in terms of their relationship to the origin along * the X, Y and Z axes whereas the camera's 'local' coordinate system * describes positions from the camera's point of view: left-right, up-down, * and forward-backward. The <a href="#/p5.Camera/move">move()</a> method, * for instance, moves the camera along its own axes, whereas the * <a href="#/p5.Camera/setPosition">setPosition()</a> * method sets the camera's position in world-space. * * * @class p5.Camera * @param {rendererGL} rendererGL instance of WebGL renderer * @example * <div> * <code> * var cam; * var delta = 0.01; * * function setup() { * createCanvas(100, 100, WEBGL); * normalMaterial(); * cam = createCamera(); * // set initial pan angle * cam.pan(-0.8); * } * * function draw() { * background(200); * * // pan camera according to angle 'delta' * cam.pan(delta); * * // every 160 frames, switch direction * if (frameCount % 160 === 0) { * delta *= -1; * } * * rotateX(frameCount * 0.01); * translate(-100, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * } * </code> * </div> * * @alt * camera view pans left and right across a series of rotating 3D boxes. * */p5.Camera=function(renderer){this._renderer=renderer;this.cameraType='default';this.cameraMatrix=new p5.Matrix();this.projMatrix=new p5.Matrix();};//////////////////////////////////////////////////////////////////////////////// // Camera Projection Methods //////////////////////////////////////////////////////////////////////////////// /** * Sets a perspective projection for a p5.Camera object and sets parameters * for that projection according to <a href="#/p5/perspective">perspective()</a> * syntax. * @method perspective * @for p5.Camera */p5.Camera.prototype.perspective=function(fovy,aspect,near,far){if(typeof fovy==='undefined'){fovy=this.defaultCameraFOV;// this avoids issue where setting angleMode(DEGREES) before calling // perspective leads to a smaller than expected FOV (because // _computeCameraDefaultSettings computes in radians) this.cameraFOV=fovy;}else{this.cameraFOV=this._renderer._pInst._toRadians(fovy);}if(typeof aspect==='undefined'){aspect=this.defaultAspectRatio;}if(typeof near==='undefined'){near=this.defaultCameraNear;}if(typeof far==='undefined'){far=this.defaultCameraFar;}if(near<=0.0001){near=0.01;console.log('Avoid perspective near plane values close to or below 0. '+'Setting value to 0.01.');}if(far<near){console.log('Perspective far plane value is less than near plane value. '+'Nothing will be shown.');}this.cameraFOV=this._renderer._pInst._toRadians(fovy);this.aspectRatio=aspect;this.cameraNear=near;this.cameraFar=far;this.projMatrix=p5.Matrix.identity();var f=1.0/Math.tan(this.cameraFOV/2);var nf=1.0/(this.cameraNear-this.cameraFar);// prettier-ignore this.projMatrix.set(f/aspect,0,0,0,0,-f,0,0,0,0,(far+near)*nf,-1,0,0,2*far*near*nf,0);if(this._isActive()){this._renderer.uPMatrix.set(this.projMatrix.mat4[0],this.projMatrix.mat4[1],this.projMatrix.mat4[2],this.projMatrix.mat4[3],this.projMatrix.mat4[4],this.projMatrix.mat4[5],this.projMatrix.mat4[6],this.projMatrix.mat4[7],this.projMatrix.mat4[8],this.projMatrix.mat4[9],this.projMatrix.mat4[10],this.projMatrix.mat4[11],this.projMatrix.mat4[12],this.projMatrix.mat4[13],this.projMatrix.mat4[14],this.projMatrix.mat4[15]);}this.cameraType='custom';};/** * Sets an orthographic projection for a p5.Camera object and sets parameters * for that projection according to <a href="#/p5/ortho">ortho()</a> syntax. * @method ortho * @for p5.Camera */p5.Camera.prototype.ortho=function(left,right,bottom,top,near,far){if(left===undefined)left=-this._renderer.width/2;if(right===undefined)right=+this._renderer.width/2;if(bottom===undefined)bottom=-this._renderer.height/2;if(top===undefined)top=+this._renderer.height/2;if(near===undefined)near=0;if(far===undefined)far=Math.max(this._renderer.width,this._renderer.height);var w=right-left;var h=top-bottom;var d=far-near;var x=+2.0/w;var y=+2.0/h;var z=-2.0/d;var tx=-(right+left)/w;var ty=-(top+bottom)/h;var tz=-(far+near)/d;this.projMatrix=p5.Matrix.identity();// prettier-ignore this.projMatrix.set(x,0,0,0,0,-y,0,0,0,0,z,0,tx,ty,tz,1);if(this._isActive()){this._renderer.uPMatrix.set(this.projMatrix.mat4[0],this.projMatrix.mat4[1],this.projMatrix.mat4[2],this.projMatrix.mat4[3],this.projMatrix.mat4[4],this.projMatrix.mat4[5],this.projMatrix.mat4[6],this.projMatrix.mat4[7],this.projMatrix.mat4[8],this.projMatrix.mat4[9],this.projMatrix.mat4[10],this.projMatrix.mat4[11],this.projMatrix.mat4[12],this.projMatrix.mat4[13],this.projMatrix.mat4[14],this.projMatrix.mat4[15]);}this.cameraType='custom';};//////////////////////////////////////////////////////////////////////////////// // Camera Orientation Methods //////////////////////////////////////////////////////////////////////////////// /** * Rotate camera view about arbitrary axis defined by x,y,z * based on http://learnwebgl.brown37.net/07_cameras/camera_rotating_motion.html * @method _rotateView * @private */p5.Camera.prototype._rotateView=function(a,x,y,z){var centerX=this.centerX;var centerY=this.centerY;var centerZ=this.centerZ;// move center by eye position such that rotation happens around eye position centerX-=this.eyeX;centerY-=this.eyeY;centerZ-=this.eyeZ;var rotation=p5.Matrix.identity(this._renderer._pInst);rotation.rotate(a,x,y,z);// prettier-ignore var rotatedCenter=[centerX*rotation.mat4[0]+centerY*rotation.mat4[4]+centerZ*rotation.mat4[8],centerX*rotation.mat4[1]+centerY*rotation.mat4[5]+centerZ*rotation.mat4[9],centerX*rotation.mat4[2]+centerY*rotation.mat4[6]+centerZ*rotation.mat4[10]];// add eye position back into center rotatedCenter[0]+=this.eyeX;rotatedCenter[1]+=this.eyeY;rotatedCenter[2]+=this.eyeZ;this.camera(this.eyeX,this.eyeY,this.eyeZ,rotatedCenter[0],rotatedCenter[1],rotatedCenter[2],this.upX,this.upY,this.upZ);};/** * Panning rotates the camera view to the left and right. * @method pan * @param {Number} angle amount to rotate camera in current * <a href="#/p5/angleMode">angleMode</a> units. * Greater than 0 values rotate counterclockwise (to the left). * @example * <div> * <code> * var cam; * var delta = 0.01; * * function setup() { * createCanvas(100, 100, WEBGL); * normalMaterial(); * cam = createCamera(); * // set initial pan angle * cam.pan(-0.8); * } * * function draw() { * background(200); * * // pan camera according to angle 'delta' * cam.pan(delta); * * // every 160 frames, switch direction * if (frameCount % 160 === 0) { * delta *= -1; * } * * rotateX(frameCount * 0.01); * translate(-100, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * } * </code> * </div> * * @alt * camera view pans left and right across a series of rotating 3D boxes. * */p5.Camera.prototype.pan=function(amount){var local=this._getLocalAxes();this._rotateView(amount,local.y[0],local.y[1],local.y[2]);};/** * Tilting rotates the camera view up and down. * @method tilt * @param {Number} angle amount to rotate camera in current * <a href="#/p5/angleMode">angleMode</a> units. * Greater than 0 values rotate counterclockwise (to the left). * @example * <div> * <code> * var cam; * var delta = 0.01; * * function setup() { * createCanvas(100, 100, WEBGL); * normalMaterial(); * cam = createCamera(); * // set initial tilt * cam.tilt(-0.8); * } * * function draw() { * background(200); * * // pan camera according to angle 'delta' * cam.tilt(delta); * * // every 160 frames, switch direction * if (frameCount % 160 === 0) { * delta *= -1; * } * * rotateY(frameCount * 0.01); * translate(0, -100, 0); * box(20); * translate(0, 35, 0); * box(20); * translate(0, 35, 0); * box(20); * translate(0, 35, 0); * box(20); * translate(0, 35, 0); * box(20); * translate(0, 35, 0); * box(20); * translate(0, 35, 0); * box(20); * } * </code> * </div> * * @alt * camera view tilts up and down across a series of rotating 3D boxes. */p5.Camera.prototype.tilt=function(amount){var local=this._getLocalAxes();this._rotateView(amount,local.x[0],local.x[1],local.x[2]);};/** * Reorients the camera to look at a position in world space. * @method lookAt * @for p5.Camera * @param {Number} x x position of a point in world space * @param {Number} y y position of a point in world space * @param {Number} z z position of a point in world space * @example * <div> * <code> * var cam; * * function setup() { * createCanvas(100, 100, WEBGL); * normalMaterial(); * cam = createCamera(); * } * * function draw() { * background(200); * * // look at a new random point every 60 frames * if (frameCount % 60 === 0) { * cam.lookAt(random(-100, 100), random(-50, 50), 0); * } * * rotateX(frameCount * 0.01); * translate(-100, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * } * </code> * </div> * * @alt * camera view of rotating 3D cubes changes to look at a new random * point every second . */p5.Camera.prototype.lookAt=function(x,y,z){this.camera(this.eyeX,this.eyeY,this.eyeZ,x,y,z,this.upX,this.upY,this.upZ);};//////////////////////////////////////////////////////////////////////////////// // Camera Position Methods //////////////////////////////////////////////////////////////////////////////// /** * Sets a camera's position and orientation. This is equivalent to calling * <a href="#/p5/camera">camera()</a> on a p5.Camera object. * @method camera * @for p5.Camera */p5.Camera.prototype.camera=function(eyeX,eyeY,eyeZ,centerX,centerY,centerZ,upX,upY,upZ){if(typeof eyeX==='undefined'){eyeX=this.defaultEyeX;eyeY=this.defaultEyeY;eyeZ=this.defaultEyeZ;centerX=eyeX;centerY=eyeY;centerZ=0;upX=0;upY=1;upZ=0;}this.eyeX=eyeX;this.eyeY=eyeY;this.eyeZ=eyeZ;this.centerX=centerX;this.centerY=centerY;this.centerZ=centerZ;this.upX=upX;this.upY=upY;this.upZ=upZ;var local=this._getLocalAxes();// the camera affects the model view matrix, insofar as it // inverse translates the world to the eye position of the camera // and rotates it. // prettier-ignore this.cameraMatrix.set(local.x[0],local.y[0],local.z[0],0,local.x[1],local.y[1],local.z[1],0,local.x[2],local.y[2],local.z[2],0,0,0,0,1);var tx=-eyeX;var ty=-eyeY;var tz=-eyeZ;this.cameraMatrix.translate([tx,ty,tz]);if(this._isActive()){this._renderer.uMVMatrix.set(this.cameraMatrix.mat4[0],this.cameraMatrix.mat4[1],this.cameraMatrix.mat4[2],this.cameraMatrix.mat4[3],this.cameraMatrix.mat4[4],this.cameraMatrix.mat4[5],this.cameraMatrix.mat4[6],this.cameraMatrix.mat4[7],this.cameraMatrix.mat4[8],this.cameraMatrix.mat4[9],this.cameraMatrix.mat4[10],this.cameraMatrix.mat4[11],this.cameraMatrix.mat4[12],this.cameraMatrix.mat4[13],this.cameraMatrix.mat4[14],this.cameraMatrix.mat4[15]);}return this;};/** * Move camera along its local axes while maintaining current camera orientation. * @method move * @param {Number} x amount to move along camera's left-right axis * @param {Number} y amount to move along camera's up-down axis * @param {Number} z amount to move along camera's forward-backward axis * @example * <div> * <code> * // see the camera move along its own axes while maintaining its orientation * var cam; * var delta = 0.5; * * function setup() { * createCanvas(100, 100, WEBGL); * normalMaterial(); * cam = createCamera(); * } * * function draw() { * background(200); * * // move the camera along its local axes * cam.move(delta, delta, 0); * * // every 100 frames, switch direction * if (frameCount % 150 === 0) { * delta *= -1; * } * * translate(-10, -10, 0); * box(50, 8, 50); * translate(15, 15, 0); * box(50, 8, 50); * translate(15, 15, 0); * box(50, 8, 50); * translate(15, 15, 0); * box(50, 8, 50); * translate(15, 15, 0); * box(50, 8, 50); * translate(15, 15, 0); * box(50, 8, 50); * } * </code> * </div> * * @alt * camera view moves along a series of 3D boxes, maintaining the same * orientation throughout the move */p5.Camera.prototype.move=function(x,y,z){var local=this._getLocalAxes();// scale local axes by movement amounts // based on http://learnwebgl.brown37.net/07_cameras/camera_linear_motion.html var dx=[local.x[0]*x,local.x[1]*x,local.x[2]*x];var dy=[local.y[0]*y,local.y[1]*y,local.y[2]*y];var dz=[local.z[0]*z,local.z[1]*z,local.z[2]*z];this.camera(this.eyeX+dx[0]+dy[0]+dz[0],this.eyeY+dx[1]+dy[1]+dz[1],this.eyeZ+dx[2]+dy[2]+dz[2],this.centerX+dx[0]+dy[0]+dz[0],this.centerY+dx[1]+dy[1]+dz[1],this.centerZ+dx[2]+dy[2]+dz[2],0,1,0);};/** * Set camera position in world-space while maintaining current camera * orientation. * @method setPosition * @param {Number} x x position of a point in world space * @param {Number} y y position of a point in world space * @param {Number} z z position of a point in world space * @example * <div> * <code> * // press '1' '2' or '3' keys to set camera position * * var cam; * * function setup() { * createCanvas(100, 100, WEBGL); * normalMaterial(); * cam = createCamera(); * } * * function draw() { * background(200); * * // '1' key * if (keyIsDown(49)) { * cam.setPosition(30, 0, 80); * } * // '2' key * if (keyIsDown(50)) { * cam.setPosition(0, 0, 80); * } * // '3' key * if (keyIsDown(51)) { * cam.setPosition(-30, 0, 80); * } * * box(20); * } * </code> * </div> * * @alt * camera position changes as the user presses keys, altering view of a 3D box */p5.Camera.prototype.setPosition=function(x,y,z){var diffX=x-this.eyeX;var diffY=y-this.eyeY;var diffZ=z-this.eyeZ;this.camera(x,y,z,this.centerX+diffX,this.centerY+diffY,this.centerZ+diffZ,0,1,0);};//////////////////////////////////////////////////////////////////////////////// // Camera Helper Methods //////////////////////////////////////////////////////////////////////////////// // @TODO: combine this function with _setDefaultCamera to compute these values // as-needed p5.Camera.prototype._computeCameraDefaultSettings=function(){this.defaultCameraFOV=60/180*Math.PI;this.defaultAspectRatio=this._renderer.width/this._renderer.height;this.defaultEyeX=0;this.defaultEyeY=0;this.defaultEyeZ=this._renderer.height/2.0/Math.tan(this.defaultCameraFOV/2.0);this.defaultCenterX=0;this.defaultCenterY=0;this.defaultCenterZ=0;this.defaultCameraNear=this.defaultEyeZ*0.1;this.defaultCameraFar=this.defaultEyeZ*10;};//detect if user didn't set the camera //then call this function below p5.Camera.prototype._setDefaultCamera=function(){this.cameraFOV=this.defaultCameraFOV;this.aspectRatio=this.defaultAspectRatio;this.eyeX=this.defaultEyeX;this.eyeY=this.defaultEyeY;this.eyeZ=this.defaultEyeZ;this.centerX=this.defaultCenterX;this.centerY=this.defaultCenterY;this.centerZ=this.defaultCenterZ;this.upX=0;this.upY=1;this.upZ=0;this.cameraNear=this.defaultCameraNear;this.cameraFar=this.defaultCameraFar;this.perspective();this.camera();this.cameraType='default';};p5.Camera.prototype._resize=function(){// If we're using the default camera, update the aspect ratio if(this.cameraType==='default'){this._computeCameraDefaultSettings();this._setDefaultCamera();}else{this.perspective(this.cameraFOV,this._renderer.width/this._renderer.height);}};/** * Returns a copy of a camera. * @method copy * @private */p5.Camera.prototype.copy=function(){var _cam=new p5.Camera(this._renderer);_cam.cameraFOV=this.cameraFOV;_cam.aspectRatio=this.aspectRatio;_cam.eyeX=this.eyeX;_cam.eyeY=this.eyeY;_cam.eyeZ=this.eyeZ;_cam.centerX=this.centerX;_cam.centerY=this.centerY;_cam.centerZ=this.centerZ;_cam.cameraNear=this.cameraNear;_cam.cameraFar=this.cameraFar;_cam.cameraType=this.cameraType;_cam.cameraMatrix=this.cameraMatrix.copy();_cam.projMatrix=this.projMatrix.copy();return _cam;};/** * Returns a camera's local axes: left-right, up-down, and forward-backward, * as defined by vectors in world-space. * @method _getLocalAxes * @private */p5.Camera.prototype._getLocalAxes=function(){// calculate camera local Z vector var z0=this.eyeX-this.centerX;var z1=this.eyeY-this.centerY;var z2=this.eyeZ-this.centerZ;// normalize camera local Z vector var eyeDist=Math.sqrt(z0*z0+z1*z1+z2*z2);if(eyeDist!==0){z0/=eyeDist;z1/=eyeDist;z2/=eyeDist;}// calculate camera Y vector var y0=this.upX;var y1=this.upY;var y2=this.upZ;// compute camera local X vector as up vector (local Y) cross local Z var x0=y1*z2-y2*z1;var x1=-y0*z2+y2*z0;var x2=y0*z1-y1*z0;// recompute y = z cross x y0=z1*x2-z2*x1;y1=-z0*x2+z2*x0;y2=z0*x1-z1*x0;// cross product gives area of parallelogram, which is < 1.0 for // non-perpendicular unit-length vectors; so normalize x, y here: var xmag=Math.sqrt(x0*x0+x1*x1+x2*x2);if(xmag!==0){x0/=xmag;x1/=xmag;x2/=xmag;}var ymag=Math.sqrt(y0*y0+y1*y1+y2*y2);if(ymag!==0){y0/=ymag;y1/=ymag;y2/=ymag;}return{x:[x0,x1,x2],y:[y0,y1,y2],z:[z0,z1,z2]};};/** * Orbits the camera about center point. For use with orbitControl(). * @method _orbit * @private * @param {Number} dTheta change in spherical coordinate theta * @param {Number} dPhi change in spherical coordinate phi * @param {Number} dRadius change in radius */p5.Camera.prototype._orbit=function(dTheta,dPhi,dRadius){var diffX=this.eyeX-this.centerX;var diffY=this.eyeY-this.centerY;var diffZ=this.eyeZ-this.centerZ;// get spherical coorinates for current camera position about origin var camRadius=Math.sqrt(diffX*diffX+diffY*diffY+diffZ*diffZ);// from https://github.com/mrdoob/three.js/blob/dev/src/math/Spherical.js#L72-L73 var camTheta=Math.atan2(diffX,diffZ);// equatorial angle var camPhi=Math.acos(Math.max(-1,Math.min(1,diffY/camRadius)));// polar angle // add change camTheta+=dTheta;camPhi+=dPhi;camRadius+=dRadius;// prevent zooming through the center: if(camRadius<0){camRadius=0.1;}// prevent rotation over the zenith / under bottom if(camPhi>Math.PI){camPhi=Math.PI;}else if(camPhi<=0){camPhi=0.001;}// from https://github.com/mrdoob/three.js/blob/dev/src/math/Vector3.js#L628-L632 var _x=Math.sin(camPhi)*camRadius*Math.sin(camTheta);var _y=Math.cos(camPhi)*camRadius;var _z=Math.sin(camPhi)*camRadius*Math.cos(camTheta);this.camera(_x+this.centerX,_y+this.centerY,_z+this.centerZ,this.centerX,this.centerY,this.centerZ,0,1,0);};/** * Returns true if camera is currently attached to renderer. * @method _isActive * @private */p5.Camera.prototype._isActive=function(){return this===this._renderer._curCamera;};/** * Sets rendererGL's current camera to a p5.Camera object. Allows switching * between multiple cameras. * @method setCamera * @param {p5.Camera} cam p5.Camera object * @for p5 * @example * <div> * <code> * var cam1, cam2; * var currentCamera; * * function setup() { * createCanvas(100, 100, WEBGL); * normalMaterial(); * * cam1 = createCamera(); * cam2 = createCamera(); * cam2.setPosition(30, 0, 50); * cam2.lookAt(0, 0, 0); * cam2.ortho(); * * // set variable for previously active camera: * currentCamera = 1; * } * * function draw() { * background(200); * * // camera 1: * cam1.lookAt(0, 0, 0); * cam1.setPosition(sin(frameCount / 60) * 200, 0, 100); * * // every 100 frames, switch between the two cameras * if (frameCount % 100 === 0) { * if (currentCamera === 1) { * setCamera(cam1); * currentCamera = 0; * } else { * setCamera(cam2); * currentCamera = 1; * } * } * * drawBoxes(); * } * * function drawBoxes() { * rotateX(frameCount * 0.01); * translate(-100, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * translate(35, 0, 0); * box(20); * } * </code> * </div> * * @alt * Canvas switches between two camera views, each showing a series of spinning * 3D boxes. */p5.prototype.setCamera=function(cam){this._renderer._curCamera=cam;// set the projection matrix (which is not normally updated each frame) this._renderer.uPMatrix.set(cam.projMatrix.mat4[0],cam.projMatrix.mat4[1],cam.projMatrix.mat4[2],cam.projMatrix.mat4[3],cam.projMatrix.mat4[4],cam.projMatrix.mat4[5],cam.projMatrix.mat4[6],cam.projMatrix.mat4[7],cam.projMatrix.mat4[8],cam.projMatrix.mat4[9],cam.projMatrix.mat4[10],cam.projMatrix.mat4[11],cam.projMatrix.mat4[12],cam.projMatrix.mat4[13],cam.projMatrix.mat4[14],cam.projMatrix.mat4[15]);};module.exports=p5.Camera;},{"../core/main":25}],71:[function(_dereq_,module,exports){//some of the functions are adjusted from Three.js(http://threejs.org) 'use strict';var p5=_dereq_('../core/main');/** * p5 Geometry class * @class p5.Geometry * @constructor * @param {Integer} [detailX] number of vertices on horizontal surface * @param {Integer} [detailY] number of vertices on horizontal surface * @param {function} [callback] function to call upon object instantiation. * */p5.Geometry=function(detailX,detailY,callback){//an array containing every vertex //@type [p5.Vector] this.vertices=[];//an array containing every vertex for stroke drawing this.lineVertices=[];//an array 1 normal per lineVertex with //final position representing which direction to //displace for strokeWeight //[[0,0,-1,1], [0,1,0,-1] ...]; this.lineNormals=[];//an array containing 1 normal per vertex //@type [p5.Vector] //[p5.Vector, p5.Vector, p5.Vector,p5.Vector, p5.Vector, p5.Vector,...] this.vertexNormals=[];//an array containing each three vertex indices that form a face //[[0, 1, 2], [2, 1, 3], ...] this.faces=[];//a 2D array containing uvs for every vertex //[[0.0,0.0],[1.0,0.0], ...] this.uvs=[];// a 2D array containing edge connectivity pattern for create line vertices //based on faces for most objects; this.edges=[];this.detailX=detailX!==undefined?detailX:1;this.detailY=detailY!==undefined?detailY:1;if(callback instanceof Function){callback.call(this);}return this;// TODO: is this a constructor? };/** * @method computeFaces * @chainable */p5.Geometry.prototype.computeFaces=function(){this.faces.length=0;var sliceCount=this.detailX+1;var a,b,c,d;for(var i=0;i<this.detailY;i++){for(var j=0;j<this.detailX;j++){a=i*sliceCount+j;// + offset; b=i*sliceCount+j+1;// + offset; c=(i+1)*sliceCount+j+1;// + offset; d=(i+1)*sliceCount+j;// + offset; this.faces.push([a,b,d]);this.faces.push([d,b,c]);}}return this;};p5.Geometry.prototype._getFaceNormal=function(faceId){//This assumes that vA->vB->vC is a counter-clockwise ordering var face=this.faces[faceId];var vA=this.vertices[face[0]];var vB=this.vertices[face[1]];var vC=this.vertices[face[2]];var ab=p5.Vector.sub(vB,vA);var ac=p5.Vector.sub(vC,vA);var n=p5.Vector.cross(ab,ac);var ln=p5.Vector.mag(n);var sinAlpha=ln/(p5.Vector.mag(ab)*p5.Vector.mag(ac));if(sinAlpha===0||isNaN(sinAlpha)){console.warn('p5.Geometry.prototype._getFaceNormal:','face has colinear sides or a repeated vertex');return n;}if(sinAlpha>1)sinAlpha=1;// handle float rounding error return n.mult(Math.asin(sinAlpha)/ln);};/** * computes smooth normals per vertex as an average of each * face. * @method computeNormals * @chainable */p5.Geometry.prototype.computeNormals=function(){var vertexNormals=this.vertexNormals;var vertices=this.vertices;var faces=this.faces;var iv;// initialize the vertexNormals array with empty vectors vertexNormals.length=0;for(iv=0;iv<vertices.length;++iv){vertexNormals.push(new p5.Vector());}// loop through all the faces adding its normal to the normal // of each of its vertices for(var f=0;f<faces.length;++f){var face=faces[f];var faceNormal=this._getFaceNormal(f);// all three vertices get the normal added for(var fv=0;fv<3;++fv){var vertexIndex=face[fv];vertexNormals[vertexIndex].add(faceNormal);}}// normalize the normals for(iv=0;iv<vertices.length;++iv){vertexNormals[iv].normalize();}return this;};/** * Averages the vertex normals. Used in curved * surfaces * @method averageNormals * @chainable */p5.Geometry.prototype.averageNormals=function(){for(var i=0;i<=this.detailY;i++){var offset=this.detailX+1;var temp=p5.Vector.add(this.vertexNormals[i*offset],this.vertexNormals[i*offset+this.detailX]);temp=p5.Vector.div(temp,2);this.vertexNormals[i*offset]=temp;this.vertexNormals[i*offset+this.detailX]=temp;}return this;};/** * Averages pole normals. Used in spherical primitives * @method averagePoleNormals * @chainable */p5.Geometry.prototype.averagePoleNormals=function(){//average the north pole var sum=new p5.Vector(0,0,0);for(var i=0;i<this.detailX;i++){sum.add(this.vertexNormals[i]);}sum=p5.Vector.div(sum,this.detailX);for(i=0;i<this.detailX;i++){this.vertexNormals[i]=sum;}//average the south pole sum=new p5.Vector(0,0,0);for(i=this.vertices.length-1;i>this.vertices.length-1-this.detailX;i--){sum.add(this.vertexNormals[i]);}sum=p5.Vector.div(sum,this.detailX);for(i=this.vertices.length-1;i>this.vertices.length-1-this.detailX;i--){this.vertexNormals[i]=sum;}return this;};/** * Create a 2D array for establishing stroke connections * @private * @chainable */p5.Geometry.prototype._makeTriangleEdges=function(){this.edges.length=0;if(Array.isArray(this.strokeIndices)){for(var i=0,max=this.strokeIndices.length;i<max;i++){this.edges.push(this.strokeIndices[i]);}}else{for(var j=0;j<this.faces.length;j++){this.edges.push([this.faces[j][0],this.faces[j][1]]);this.edges.push([this.faces[j][1],this.faces[j][2]]);this.edges.push([this.faces[j][2],this.faces[j][0]]);}}return this;};/** * Create 4 vertices for each stroke line, two at the beginning position * and two at the end position. These vertices are displaced relative to * that line's normal on the GPU * @private * @chainable */p5.Geometry.prototype._edgesToVertices=function(){this.lineVertices.length=0;this.lineNormals.length=0;for(var i=0;i<this.edges.length;i++){var begin=this.vertices[this.edges[i][0]];var end=this.vertices[this.edges[i][1]];var dir=end.copy().sub(begin).normalize();var a=begin.array();var b=begin.array();var c=end.array();var d=end.array();var dirAdd=dir.array();var dirSub=dir.array();// below is used to displace the pair of vertices at beginning and end // in opposite directions dirAdd.push(1);dirSub.push(-1);this.lineNormals.push(dirAdd,dirSub,dirAdd,dirAdd,dirSub,dirSub);this.lineVertices.push(a,b,c,c,b,d);}return this;};/** * Modifies all vertices to be centered within the range -100 to 100. * @method normalize * @chainable */p5.Geometry.prototype.normalize=function(){if(this.vertices.length>0){// Find the corners of our bounding box var maxPosition=this.vertices[0].copy();var minPosition=this.vertices[0].copy();for(var i=0;i<this.vertices.length;i++){maxPosition.x=Math.max(maxPosition.x,this.vertices[i].x);minPosition.x=Math.min(minPosition.x,this.vertices[i].x);maxPosition.y=Math.max(maxPosition.y,this.vertices[i].y);minPosition.y=Math.min(minPosition.y,this.vertices[i].y);maxPosition.z=Math.max(maxPosition.z,this.vertices[i].z);minPosition.z=Math.min(minPosition.z,this.vertices[i].z);}var center=p5.Vector.lerp(maxPosition,minPosition,0.5);var dist=p5.Vector.sub(maxPosition,minPosition);var longestDist=Math.max(Math.max(dist.x,dist.y),dist.z);var scale=200/longestDist;for(i=0;i<this.vertices.length;i++){this.vertices[i].sub(center);this.vertices[i].mult(scale);}}return this;};module.exports=p5.Geometry;},{"../core/main":25}],72:[function(_dereq_,module,exports){/** * @requires constants * @todo see methods below needing further implementation. * future consideration: implement SIMD optimizations * when browser compatibility becomes available * https://developer.mozilla.org/en-US/docs/Web/JavaScript/ * Reference/Global_Objects/SIMD */'use strict';var p5=_dereq_('../core/main');var GLMAT_ARRAY_TYPE=Array;var isMatrixArray=function isMatrixArray(x){return x instanceof Array;};if(typeof Float32Array!=='undefined'){GLMAT_ARRAY_TYPE=Float32Array;isMatrixArray=function isMatrixArray(x){return x instanceof Array||x instanceof Float32Array;};}/** * A class to describe a 4x4 matrix * for model and view matrix manipulation in the p5js webgl renderer. * @class p5.Matrix * @private * @constructor * @param {Array} [mat4] array literal of our 4x4 matrix */p5.Matrix=function(){var args=new Array(arguments.length);for(var i=0;i<args.length;++i){args[i]=arguments[i];}// This is default behavior when object // instantiated using createMatrix() // @todo implement createMatrix() in core/math.js if(args.length&&args[args.length-1]instanceof p5){this.p5=args[args.length-1];}if(args[0]==='mat3'){this.mat3=Array.isArray(args[1])?args[1]:new GLMAT_ARRAY_TYPE([1,0,0,0,1,0,0,0,1]);}else{this.mat4=Array.isArray(args[0])?args[0]:new GLMAT_ARRAY_TYPE([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);}return this;};/** * Sets the x, y, and z component of the vector using two or three separate * variables, the data from a p5.Matrix, or the values from a float array. * * @method set * @param {p5.Matrix|Float32Array|Number[]} [inMatrix] the input p5.Matrix or * an Array of length 16 * @chainable *//** * @method set * @param {Number[]} elements 16 numbers passed by value to avoid * array copying. * @chainable */p5.Matrix.prototype.set=function(inMatrix){if(inMatrix instanceof p5.Matrix){this.mat4=inMatrix.mat4;return this;}else if(isMatrixArray(inMatrix)){this.mat4=inMatrix;return this;}else if(arguments.length===16){this.mat4[0]=arguments[0];this.mat4[1]=arguments[1];this.mat4[2]=arguments[2];this.mat4[3]=arguments[3];this.mat4[4]=arguments[4];this.mat4[5]=arguments[5];this.mat4[6]=arguments[6];this.mat4[7]=arguments[7];this.mat4[8]=arguments[8];this.mat4[9]=arguments[9];this.mat4[10]=arguments[10];this.mat4[11]=arguments[11];this.mat4[12]=arguments[12];this.mat4[13]=arguments[13];this.mat4[14]=arguments[14];this.mat4[15]=arguments[15];}return this;};/** * Gets a copy of the vector, returns a p5.Matrix object. * * @method get * @return {p5.Matrix} the copy of the p5.Matrix object */p5.Matrix.prototype.get=function(){return new p5.Matrix(this.mat4,this.p5);};/** * return a copy of a matrix * @method copy * @return {p5.Matrix} the result matrix */p5.Matrix.prototype.copy=function(){var copied=new p5.Matrix(this.p5);copied.mat4[0]=this.mat4[0];copied.mat4[1]=this.mat4[1];copied.mat4[2]=this.mat4[2];copied.mat4[3]=this.mat4[3];copied.mat4[4]=this.mat4[4];copied.mat4[5]=this.mat4[5];copied.mat4[6]=this.mat4[6];copied.mat4[7]=this.mat4[7];copied.mat4[8]=this.mat4[8];copied.mat4[9]=this.mat4[9];copied.mat4[10]=this.mat4[10];copied.mat4[11]=this.mat4[11];copied.mat4[12]=this.mat4[12];copied.mat4[13]=this.mat4[13];copied.mat4[14]=this.mat4[14];copied.mat4[15]=this.mat4[15];return copied;};/** * return an identity matrix * @method identity * @return {p5.Matrix} the result matrix */p5.Matrix.identity=function(pInst){return new p5.Matrix(pInst);};/** * transpose according to a given matrix * @method transpose * @param {p5.Matrix|Float32Array|Number[]} a the matrix to be * based on to transpose * @chainable */p5.Matrix.prototype.transpose=function(a){var a01,a02,a03,a12,a13,a23;if(a instanceof p5.Matrix){a01=a.mat4[1];a02=a.mat4[2];a03=a.mat4[3];a12=a.mat4[6];a13=a.mat4[7];a23=a.mat4[11];this.mat4[0]=a.mat4[0];this.mat4[1]=a.mat4[4];this.mat4[2]=a.mat4[8];this.mat4[3]=a.mat4[12];this.mat4[4]=a01;this.mat4[5]=a.mat4[5];this.mat4[6]=a.mat4[9];this.mat4[7]=a.mat4[13];this.mat4[8]=a02;this.mat4[9]=a12;this.mat4[10]=a.mat4[10];this.mat4[11]=a.mat4[14];this.mat4[12]=a03;this.mat4[13]=a13;this.mat4[14]=a23;this.mat4[15]=a.mat4[15];}else if(isMatrixArray(a)){a01=a[1];a02=a[2];a03=a[3];a12=a[6];a13=a[7];a23=a[11];this.mat4[0]=a[0];this.mat4[1]=a[4];this.mat4[2]=a[8];this.mat4[3]=a[12];this.mat4[4]=a01;this.mat4[5]=a[5];this.mat4[6]=a[9];this.mat4[7]=a[13];this.mat4[8]=a02;this.mat4[9]=a12;this.mat4[10]=a[10];this.mat4[11]=a[14];this.mat4[12]=a03;this.mat4[13]=a13;this.mat4[14]=a23;this.mat4[15]=a[15];}return this;};/** * invert matrix according to a give matrix * @method invert * @param {p5.Matrix|Float32Array|Number[]} a the matrix to be * based on to invert * @chainable */p5.Matrix.prototype.invert=function(a){var a00,a01,a02,a03,a10,a11,a12,a13;var a20,a21,a22,a23,a30,a31,a32,a33;if(a instanceof p5.Matrix){a00=a.mat4[0];a01=a.mat4[1];a02=a.mat4[2];a03=a.mat4[3];a10=a.mat4[4];a11=a.mat4[5];a12=a.mat4[6];a13=a.mat4[7];a20=a.mat4[8];a21=a.mat4[9];a22=a.mat4[10];a23=a.mat4[11];a30=a.mat4[12];a31=a.mat4[13];a32=a.mat4[14];a33=a.mat4[15];}else if(isMatrixArray(a)){a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];a30=a[12];a31=a[13];a32=a[14];a33=a[15];}var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;// Calculate the determinant var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det){return null;}det=1.0/det;this.mat4[0]=(a11*b11-a12*b10+a13*b09)*det;this.mat4[1]=(a02*b10-a01*b11-a03*b09)*det;this.mat4[2]=(a31*b05-a32*b04+a33*b03)*det;this.mat4[3]=(a22*b04-a21*b05-a23*b03)*det;this.mat4[4]=(a12*b08-a10*b11-a13*b07)*det;this.mat4[5]=(a00*b11-a02*b08+a03*b07)*det;this.mat4[6]=(a32*b02-a30*b05-a33*b01)*det;this.mat4[7]=(a20*b05-a22*b02+a23*b01)*det;this.mat4[8]=(a10*b10-a11*b08+a13*b06)*det;this.mat4[9]=(a01*b08-a00*b10-a03*b06)*det;this.mat4[10]=(a30*b04-a31*b02+a33*b00)*det;this.mat4[11]=(a21*b02-a20*b04-a23*b00)*det;this.mat4[12]=(a11*b07-a10*b09-a12*b06)*det;this.mat4[13]=(a00*b09-a01*b07+a02*b06)*det;this.mat4[14]=(a31*b01-a30*b03-a32*b00)*det;this.mat4[15]=(a20*b03-a21*b01+a22*b00)*det;return this;};/** * Inverts a 3x3 matrix * @method invert3x3 * @chainable */p5.Matrix.prototype.invert3x3=function(){var a00=this.mat3[0];var a01=this.mat3[1];var a02=this.mat3[2];var a10=this.mat3[3];var a11=this.mat3[4];var a12=this.mat3[5];var a20=this.mat3[6];var a21=this.mat3[7];var a22=this.mat3[8];var b01=a22*a11-a12*a21;var b11=-a22*a10+a12*a20;var b21=a21*a10-a11*a20;// Calculate the determinant var det=a00*b01+a01*b11+a02*b21;if(!det){return null;}det=1.0/det;this.mat3[0]=b01*det;this.mat3[1]=(-a22*a01+a02*a21)*det;this.mat3[2]=(a12*a01-a02*a11)*det;this.mat3[3]=b11*det;this.mat3[4]=(a22*a00-a02*a20)*det;this.mat3[5]=(-a12*a00+a02*a10)*det;this.mat3[6]=b21*det;this.mat3[7]=(-a21*a00+a01*a20)*det;this.mat3[8]=(a11*a00-a01*a10)*det;return this;};/** * transposes a 3x3 p5.Matrix by a mat3 * @method transpose3x3 * @param {Number[]} mat3 1-dimensional array * @chainable */p5.Matrix.prototype.transpose3x3=function(mat3){var a01=mat3[1],a02=mat3[2],a12=mat3[5];this.mat3[1]=mat3[3];this.mat3[2]=mat3[6];this.mat3[3]=a01;this.mat3[5]=mat3[7];this.mat3[6]=a02;this.mat3[7]=a12;return this;};/** * converts a 4x4 matrix to its 3x3 inverse tranform * commonly used in MVMatrix to NMatrix conversions. * @method invertTranspose * @param {p5.Matrix} mat4 the matrix to be based on to invert * @chainable * @todo finish implementation */p5.Matrix.prototype.inverseTranspose=function(matrix){if(this.mat3===undefined){console.error('sorry, this function only works with mat3');}else{//convert mat4 -> mat3 this.mat3[0]=matrix.mat4[0];this.mat3[1]=matrix.mat4[1];this.mat3[2]=matrix.mat4[2];this.mat3[3]=matrix.mat4[4];this.mat3[4]=matrix.mat4[5];this.mat3[5]=matrix.mat4[6];this.mat3[6]=matrix.mat4[8];this.mat3[7]=matrix.mat4[9];this.mat3[8]=matrix.mat4[10];}var inverse=this.invert3x3();// check inverse succeded if(inverse){inverse.transpose3x3(this.mat3);}else{// in case of singularity, just zero the matrix for(var i=0;i<9;i++){this.mat3[i]=0;}}return this;};/** * inspired by Toji's mat4 determinant * @method determinant * @return {Number} Determinant of our 4x4 matrix */p5.Matrix.prototype.determinant=function(){var d00=this.mat4[0]*this.mat4[5]-this.mat4[1]*this.mat4[4],d01=this.mat4[0]*this.mat4[6]-this.mat4[2]*this.mat4[4],d02=this.mat4[0]*this.mat4[7]-this.mat4[3]*this.mat4[4],d03=this.mat4[1]*this.mat4[6]-this.mat4[2]*this.mat4[5],d04=this.mat4[1]*this.mat4[7]-this.mat4[3]*this.mat4[5],d05=this.mat4[2]*this.mat4[7]-this.mat4[3]*this.mat4[6],d06=this.mat4[8]*this.mat4[13]-this.mat4[9]*this.mat4[12],d07=this.mat4[8]*this.mat4[14]-this.mat4[10]*this.mat4[12],d08=this.mat4[8]*this.mat4[15]-this.mat4[11]*this.mat4[12],d09=this.mat4[9]*this.mat4[14]-this.mat4[10]*this.mat4[13],d10=this.mat4[9]*this.mat4[15]-this.mat4[11]*this.mat4[13],d11=this.mat4[10]*this.mat4[15]-this.mat4[11]*this.mat4[14];// Calculate the determinant return d00*d11-d01*d10+d02*d09+d03*d08-d04*d07+d05*d06;};/** * multiply two mat4s * @method mult * @param {p5.Matrix|Float32Array|Number[]} multMatrix The matrix * we want to multiply by * @chainable */p5.Matrix.prototype.mult=function(multMatrix){var _src;if(multMatrix===this||multMatrix===this.mat4){_src=this.copy().mat4;// only need to allocate in this rare case }else if(multMatrix instanceof p5.Matrix){_src=multMatrix.mat4;}else if(isMatrixArray(multMatrix)){_src=multMatrix;}else{return;// nothing to do. }// each row is used for the multiplier var b0=this.mat4[0],b1=this.mat4[1],b2=this.mat4[2],b3=this.mat4[3];this.mat4[0]=b0*_src[0]+b1*_src[4]+b2*_src[8]+b3*_src[12];this.mat4[1]=b0*_src[1]+b1*_src[5]+b2*_src[9]+b3*_src[13];this.mat4[2]=b0*_src[2]+b1*_src[6]+b2*_src[10]+b3*_src[14];this.mat4[3]=b0*_src[3]+b1*_src[7]+b2*_src[11]+b3*_src[15];b0=this.mat4[4];b1=this.mat4[5];b2=this.mat4[6];b3=this.mat4[7];this.mat4[4]=b0*_src[0]+b1*_src[4]+b2*_src[8]+b3*_src[12];this.mat4[5]=b0*_src[1]+b1*_src[5]+b2*_src[9]+b3*_src[13];this.mat4[6]=b0*_src[2]+b1*_src[6]+b2*_src[10]+b3*_src[14];this.mat4[7]=b0*_src[3]+b1*_src[7]+b2*_src[11]+b3*_src[15];b0=this.mat4[8];b1=this.mat4[9];b2=this.mat4[10];b3=this.mat4[11];this.mat4[8]=b0*_src[0]+b1*_src[4]+b2*_src[8]+b3*_src[12];this.mat4[9]=b0*_src[1]+b1*_src[5]+b2*_src[9]+b3*_src[13];this.mat4[10]=b0*_src[2]+b1*_src[6]+b2*_src[10]+b3*_src[14];this.mat4[11]=b0*_src[3]+b1*_src[7]+b2*_src[11]+b3*_src[15];b0=this.mat4[12];b1=this.mat4[13];b2=this.mat4[14];b3=this.mat4[15];this.mat4[12]=b0*_src[0]+b1*_src[4]+b2*_src[8]+b3*_src[12];this.mat4[13]=b0*_src[1]+b1*_src[5]+b2*_src[9]+b3*_src[13];this.mat4[14]=b0*_src[2]+b1*_src[6]+b2*_src[10]+b3*_src[14];this.mat4[15]=b0*_src[3]+b1*_src[7]+b2*_src[11]+b3*_src[15];return this;};/** * scales a p5.Matrix by scalars or a vector * @method scale * @param {p5.Vector|Float32Array|Number[]} s vector to scale by * @chainable */p5.Matrix.prototype.scale=function(x,y,z){if(x instanceof p5.Vector){// x is a vector, extract the components from it. y=x.y;z=x.z;x=x.x;// must be last }else if(x instanceof Array){// x is an array, extract the components from it. y=x[1];z=x[2];x=x[0];// must be last }this.mat4[0]*=x;this.mat4[1]*=x;this.mat4[2]*=x;this.mat4[3]*=x;this.mat4[4]*=y;this.mat4[5]*=y;this.mat4[6]*=y;this.mat4[7]*=y;this.mat4[8]*=z;this.mat4[9]*=z;this.mat4[10]*=z;this.mat4[11]*=z;return this;};/** * rotate our Matrix around an axis by the given angle. * @method rotate * @param {Number} a The angle of rotation in radians * @param {p5.Vector|Number[]} axis the axis(es) to rotate around * @chainable * inspired by Toji's gl-matrix lib, mat4 rotation */p5.Matrix.prototype.rotate=function(a,x,y,z){var _a=this.p5?this.p5._toRadians(a):a;if(x instanceof p5.Vector){// x is a vector, extract the components from it. y=x.y;z=x.z;x=x.x;//must be last }else if(x instanceof Array){// x is an array, extract the components from it. y=x[1];z=x[2];x=x[0];//must be last }var len=Math.sqrt(x*x+y*y+z*z);x*=1/len;y*=1/len;z*=1/len;var a00=this.mat4[0];var a01=this.mat4[1];var a02=this.mat4[2];var a03=this.mat4[3];var a10=this.mat4[4];var a11=this.mat4[5];var a12=this.mat4[6];var a13=this.mat4[7];var a20=this.mat4[8];var a21=this.mat4[9];var a22=this.mat4[10];var a23=this.mat4[11];//sin,cos, and tan of respective angle var sA=Math.sin(_a);var cA=Math.cos(_a);var tA=1-cA;// Construct the elements of the rotation matrix var b00=x*x*tA+cA;var b01=y*x*tA+z*sA;var b02=z*x*tA-y*sA;var b10=x*y*tA-z*sA;var b11=y*y*tA+cA;var b12=z*y*tA+x*sA;var b20=x*z*tA+y*sA;var b21=y*z*tA-x*sA;var b22=z*z*tA+cA;// rotation-specific matrix multiplication this.mat4[0]=a00*b00+a10*b01+a20*b02;this.mat4[1]=a01*b00+a11*b01+a21*b02;this.mat4[2]=a02*b00+a12*b01+a22*b02;this.mat4[3]=a03*b00+a13*b01+a23*b02;this.mat4[4]=a00*b10+a10*b11+a20*b12;this.mat4[5]=a01*b10+a11*b11+a21*b12;this.mat4[6]=a02*b10+a12*b11+a22*b12;this.mat4[7]=a03*b10+a13*b11+a23*b12;this.mat4[8]=a00*b20+a10*b21+a20*b22;this.mat4[9]=a01*b20+a11*b21+a21*b22;this.mat4[10]=a02*b20+a12*b21+a22*b22;this.mat4[11]=a03*b20+a13*b21+a23*b22;return this;};/** * @todo finish implementing this method! * translates * @method translate * @param {Number[]} v vector to translate by * @chainable */p5.Matrix.prototype.translate=function(v){var x=v[0],y=v[1],z=v[2]||0;this.mat4[12]+=this.mat4[0]*x+this.mat4[4]*y+this.mat4[8]*z;this.mat4[13]+=this.mat4[1]*x+this.mat4[5]*y+this.mat4[9]*z;this.mat4[14]+=this.mat4[2]*x+this.mat4[6]*y+this.mat4[10]*z;this.mat4[15]+=this.mat4[3]*x+this.mat4[7]*y+this.mat4[11]*z;};p5.Matrix.prototype.rotateX=function(a){this.rotate(a,1,0,0);};p5.Matrix.prototype.rotateY=function(a){this.rotate(a,0,1,0);};p5.Matrix.prototype.rotateZ=function(a){this.rotate(a,0,0,1);};/** * sets the perspective matrix * @method perspective * @param {Number} fovy [description] * @param {Number} aspect [description] * @param {Number} near near clipping plane * @param {Number} far far clipping plane * @chainable */p5.Matrix.prototype.perspective=function(fovy,aspect,near,far){var f=1.0/Math.tan(fovy/2),nf=1/(near-far);this.mat4[0]=f/aspect;this.mat4[1]=0;this.mat4[2]=0;this.mat4[3]=0;this.mat4[4]=0;this.mat4[5]=f;this.mat4[6]=0;this.mat4[7]=0;this.mat4[8]=0;this.mat4[9]=0;this.mat4[10]=(far+near)*nf;this.mat4[11]=-1;this.mat4[12]=0;this.mat4[13]=0;this.mat4[14]=2*far*near*nf;this.mat4[15]=0;return this;};/** * sets the ortho matrix * @method ortho * @param {Number} left [description] * @param {Number} right [description] * @param {Number} bottom [description] * @param {Number} top [description] * @param {Number} near near clipping plane * @param {Number} far far clipping plane * @chainable */p5.Matrix.prototype.ortho=function(left,right,bottom,top,near,far){var lr=1/(left-right),bt=1/(bottom-top),nf=1/(near-far);this.mat4[0]=-2*lr;this.mat4[1]=0;this.mat4[2]=0;this.mat4[3]=0;this.mat4[4]=0;this.mat4[5]=-2*bt;this.mat4[6]=0;this.mat4[7]=0;this.mat4[8]=0;this.mat4[9]=0;this.mat4[10]=2*nf;this.mat4[11]=0;this.mat4[12]=(left+right)*lr;this.mat4[13]=(top+bottom)*bt;this.mat4[14]=(far+near)*nf;this.mat4[15]=1;return this;};/** * PRIVATE */// matrix methods adapted from: // https://developer.mozilla.org/en-US/docs/Web/WebGL/ // gluPerspective // // function _makePerspective(fovy, aspect, znear, zfar){ // var ymax = znear * Math.tan(fovy * Math.PI / 360.0); // var ymin = -ymax; // var xmin = ymin * aspect; // var xmax = ymax * aspect; // return _makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); // } //// //// glFrustum //// //function _makeFrustum(left, right, bottom, top, znear, zfar){ // var X = 2*znear/(right-left); // var Y = 2*znear/(top-bottom); // var A = (right+left)/(right-left); // var B = (top+bottom)/(top-bottom); // var C = -(zfar+znear)/(zfar-znear); // var D = -2*zfar*znear/(zfar-znear); // var frustrumMatrix =[ // X, 0, A, 0, // 0, Y, B, 0, // 0, 0, C, D, // 0, 0, -1, 0 //]; //return frustrumMatrix; // } // function _setMVPMatrices(){ ////an identity matrix ////@TODO use the p5.Matrix class to abstract away our MV matrices and ///other math //var _mvMatrix = //[ // 1.0,0.0,0.0,0.0, // 0.0,1.0,0.0,0.0, // 0.0,0.0,1.0,0.0, // 0.0,0.0,0.0,1.0 //]; module.exports=p5.Matrix;},{"../core/main":25}],73:[function(_dereq_,module,exports){/** * Welcome to RendererGL Immediate Mode. * Immediate mode is used for drawing custom shapes * from a set of vertices. Immediate Mode is activated * when you call <a href="#/p5/beginShape">beginShape()</a> & de-activated when you call <a href="#/p5/endShape">endShape()</a>. * Immediate mode is a style of programming borrowed * from OpenGL's (now-deprecated) immediate mode. * It differs from p5.js' default, Retained Mode, which caches * geometries and buffers on the CPU to reduce the number of webgl * draw calls. Retained mode is more efficient & performative, * however, Immediate Mode is useful for sketching quick * geometric ideas. */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');/** * Begin shape drawing. This is a helpful way of generating * custom shapes quickly. However in WEBGL mode, application * performance will likely drop as a result of too many calls to * <a href="#/p5/beginShape">beginShape()</a> / <a href="#/p5/endShape">endShape()</a>. As a high performance alternative, * please use p5.js geometry primitives. * @private * @method beginShape * @param {Number} mode webgl primitives mode. beginShape supports the * following modes: * POINTS,LINES,LINE_STRIP,LINE_LOOP,TRIANGLES, * TRIANGLE_STRIP,and TRIANGLE_FAN. * @chainable */p5.RendererGL.prototype.beginShape=function(mode){//default shape mode is line_strip this.immediateMode.shapeMode=mode!==undefined?mode:constants.LINE_STRIP;//if we haven't yet initialized our //immediateMode vertices & buffers, create them now! if(this.immediateMode.vertices===undefined){this.immediateMode.vertices=[];this.immediateMode.edges=[];this.immediateMode.lineVertices=[];this.immediateMode.vertexColors=[];this.immediateMode.lineNormals=[];this.immediateMode.uvCoords=[];this.immediateMode.vertexBuffer=this.GL.createBuffer();this.immediateMode.colorBuffer=this.GL.createBuffer();this.immediateMode.uvBuffer=this.GL.createBuffer();this.immediateMode.lineVertexBuffer=this.GL.createBuffer();this.immediateMode.lineNormalBuffer=this.GL.createBuffer();this.immediateMode.pointVertexBuffer=this.GL.createBuffer();this.immediateMode._bezierVertex=[];this.immediateMode._quadraticVertex=[];this.immediateMode._curveVertex=[];}else{this.immediateMode.vertices.length=0;this.immediateMode.edges.length=0;this.immediateMode.lineVertices.length=0;this.immediateMode.lineNormals.length=0;this.immediateMode.vertexColors.length=0;this.immediateMode.uvCoords.length=0;}this.isImmediateDrawing=true;return this;};/** * adds a vertex to be drawn in a custom Shape. * @private * @method vertex * @param {Number} x x-coordinate of vertex * @param {Number} y y-coordinate of vertex * @param {Number} z z-coordinate of vertex * @chainable * @TODO implement handling of <a href="#/p5.Vector">p5.Vector</a> args */p5.RendererGL.prototype.vertex=function(x,y){var z,u,v;// default to (x, y) mode: all other arugments assumed to be 0. z=u=v=0;if(arguments.length===3){// (x, y, z) mode: (u, v) assumed to be 0. z=arguments[2];}else if(arguments.length===4){// (x, y, u, v) mode: z assumed to be 0. u=arguments[2];v=arguments[3];}else if(arguments.length===5){// (x, y, z, u, v) mode z=arguments[2];u=arguments[3];v=arguments[4];}var vert=new p5.Vector(x,y,z);this.immediateMode.vertices.push(vert);var vertexColor=this.curFillColor||[0.5,0.5,0.5,1.0];this.immediateMode.vertexColors.push(vertexColor[0],vertexColor[1],vertexColor[2],vertexColor[3]);this.immediateMode.uvCoords.push(u,v);this.immediateMode._bezierVertex[0]=x;this.immediateMode._bezierVertex[1]=y;this.immediateMode._bezierVertex[2]=z;this.immediateMode._quadraticVertex[0]=x;this.immediateMode._quadraticVertex[1]=y;this.immediateMode._quadraticVertex[2]=z;return this;};/** * End shape drawing and render vertices to screen. * @chainable */p5.RendererGL.prototype.endShape=function(mode,isCurve,isBezier,isQuadratic,isContour,shapeKind){if(this.immediateMode.shapeMode===constants.POINTS){this._usePointShader();this.curPointShader.bindShader();this._drawPoints(this.immediateMode.vertices,this.immediateMode.pointVertexBuffer);this.curPointShader.unbindShader();}else if(this.immediateMode.vertices.length>1){this._useImmediateModeShader();if(this._doStroke&&this.drawMode!==constants.TEXTURE){for(var i=0;i<this.immediateMode.vertices.length-1;i++){this.immediateMode.edges.push([i,i+1]);}if(mode===constants.CLOSE){this.immediateMode.edges.push([this.immediateMode.vertices.length-1,0]);}p5.Geometry.prototype._edgesToVertices.call(this.immediateMode);this._drawStrokeImmediateMode();}if(this._doFill){if(this.isBezier||this.isQuadratic||this.isCurve){var contours=[new Float32Array(this._vToNArray(this.immediateMode.vertices))];var polyTriangles=this._triangulate(contours);this.immediateMode.vertices=[];for(var j=0,polyTriLength=polyTriangles.length;j<polyTriLength;j=j+3){this.vertex(polyTriangles[j],polyTriangles[j+1],polyTriangles[j+2]);}}this._drawFillImmediateMode(mode,isCurve,isBezier,isQuadratic,isContour,shapeKind);}}//clear out our vertexPositions & colors arrays //after rendering this.immediateMode.vertices.length=0;this.immediateMode.vertexColors.length=0;this.immediateMode.uvCoords.length=0;this.isImmediateDrawing=false;this.isBezier=false;this.isQuadratic=false;this.isCurve=false;this.immediateMode._bezierVertex.length=0;this.immediateMode._quadraticVertex.length=0;this.immediateMode._curveVertex.length=0;return this;};p5.RendererGL.prototype._drawFillImmediateMode=function(mode,isCurve,isBezier,isQuadratic,isContour,shapeKind){var gl=this.GL;this.curFillShader.bindShader();// initialize the fill shader's 'aPosition' buffer if(this.curFillShader.attributes.aPosition){//vertex position Attribute this._bindBuffer(this.immediateMode.vertexBuffer,gl.ARRAY_BUFFER,this._vToNArray(this.immediateMode.vertices),Float32Array,gl.DYNAMIC_DRAW);this.curFillShader.enableAttrib(this.curFillShader.attributes.aPosition.location,3,gl.FLOAT,false,0,0);}// initialize the fill shader's 'aVertexColor' buffer if(this.drawMode===constants.FILL&&this.curFillShader.attributes.aVertexColor){this._bindBuffer(this.immediateMode.colorBuffer,gl.ARRAY_BUFFER,this.immediateMode.vertexColors,Float32Array,gl.DYNAMIC_DRAW);this.curFillShader.enableAttrib(this.curFillShader.attributes.aVertexColor.location,4,gl.FLOAT,false,0,0);}// initialize the fill shader's 'aTexCoord' buffer if(this.drawMode===constants.TEXTURE&&this.curFillShader.attributes.aTexCoord){//texture coordinate Attribute this._bindBuffer(this.immediateMode.uvBuffer,gl.ARRAY_BUFFER,this.immediateMode.uvCoords,Float32Array,gl.DYNAMIC_DRAW);this.curFillShader.enableAttrib(this.curFillShader.attributes.aTexCoord.location,2,gl.FLOAT,false,0,0);}//if (true || mode) { if(this.drawMode===constants.FILL||this.drawMode===constants.TEXTURE){switch(this.immediateMode.shapeMode){case constants.LINE_STRIP:case constants.LINES:case constants.TRIANGLES:this.immediateMode.shapeMode=this.isBezier||this.isQuadratic||this.isCurve?constants.TRIANGLES:constants.TRIANGLE_FAN;break;}}else{switch(this.immediateMode.shapeMode){case constants.LINE_STRIP:case constants.LINES:this.immediateMode.shapeMode=constants.LINE_LOOP;break;}}//} //QUADS & QUAD_STRIP are not supported primitives modes //in webgl. if(this.immediateMode.shapeMode===constants.QUADS||this.immediateMode.shapeMode===constants.QUAD_STRIP){throw new Error('sorry, '+this.immediateMode.shapeMode+' not yet implemented in webgl mode.');}else{this._applyColorBlend(this.curFillColor);gl.enable(gl.BLEND);gl.drawArrays(this.immediateMode.shapeMode,0,this.immediateMode.vertices.length);this._pInst._pixelsDirty=true;}// todo / optimizations? leave bound until another shader is set? this.curFillShader.unbindShader();};p5.RendererGL.prototype._drawStrokeImmediateMode=function(){var gl=this.GL;this.curStrokeShader.bindShader();// initialize the stroke shader's 'aPosition' buffer if(this.curStrokeShader.attributes.aPosition){this._bindBuffer(this.immediateMode.lineVertexBuffer,gl.ARRAY_BUFFER,this._flatten(this.immediateMode.lineVertices),Float32Array,gl.STATIC_DRAW);this.curStrokeShader.enableAttrib(this.curStrokeShader.attributes.aPosition.location,3,gl.FLOAT,false,0,0);}// initialize the stroke shader's 'aDirection' buffer if(this.curStrokeShader.attributes.aDirection){this._bindBuffer(this.immediateMode.lineNormalBuffer,gl.ARRAY_BUFFER,this._flatten(this.immediateMode.lineNormals),Float32Array,gl.STATIC_DRAW);this.curStrokeShader.enableAttrib(this.curStrokeShader.attributes.aDirection.location,4,gl.FLOAT,false,0,0);}this._applyColorBlend(this.curStrokeColor);gl.drawArrays(gl.TRIANGLES,0,this.immediateMode.lineVertices.length);// todo / optimizations? leave bound until another shader is set? this.curStrokeShader.unbindShader();this._pInst._pixelsDirty=true;};module.exports=p5.RendererGL;},{"../core/constants":19,"../core/main":25}],74:[function(_dereq_,module,exports){//Retained Mode. The default mode for rendering 3D primitives //in WEBGL. 'use strict';var p5=_dereq_('../core/main');var hashCount=0;/** * _initBufferDefaults * @private * @description initializes buffer defaults. runs each time a new geometry is * registered * @param {String} gId key of the geometry object */p5.RendererGL.prototype._initBufferDefaults=function(gId){this._freeBuffers(gId);//@TODO remove this limit on hashes in gHash hashCount++;if(hashCount>1000){var key=Object.keys(this.gHash)[0];delete this.gHash[key];hashCount--;}//create a new entry in our gHash this.gHash[gId]={};};p5.RendererGL.prototype._freeBuffers=function(gId){var geometry=this.gHash[gId];if(!geometry){return;}delete this.gHash[gId];hashCount--;var gl=this.GL;geometry.vertexBuffer&&gl.deleteBuffer(geometry.vertexBuffer);geometry.normalBuffer&&gl.deleteBuffer(geometry.normalBuffer);geometry.lineNormalBuffer&&gl.deleteBuffer(geometry.lineNormalBuffer);geometry.uvBuffer&&gl.deleteBuffer(geometry.uvBuffer);geometry.indexBuffer&&gl.deleteBuffer(geometry.indexBuffer);geometry.lineVertexBuffer&&gl.deleteBuffer(geometry.lineVertexBuffer);};/** * createBuffers description * @private * @param {String} gId key of the geometry object * @param {p5.Geometry} obj contains geometry data */p5.RendererGL.prototype.createBuffers=function(gId,obj){var gl=this.GL;//initialize the gl buffers for our geom groups this._initBufferDefaults(gId);var geometry=this.gHash[gId];geometry.numberOfItems=obj.faces.length*3;geometry.lineVertexCount=obj.lineVertices.length;this._useColorShader();// initialize the stroke shader's 'aPosition' buffer, if used if(this.curStrokeShader.attributes.aPosition){geometry.lineVertexBuffer=gl.createBuffer();this._bindBuffer(geometry.lineVertexBuffer,gl.ARRAY_BUFFER,this._flatten(obj.lineVertices),Float32Array,gl.STATIC_DRAW);this.curStrokeShader.enableAttrib(this.curStrokeShader.attributes.aPosition.location,3,gl.FLOAT,false,0,0);}// initialize the stroke shader's 'aDirection' buffer, if used if(this.curStrokeShader.attributes.aDirection){geometry.lineNormalBuffer=gl.createBuffer();this._bindBuffer(geometry.lineNormalBuffer,gl.ARRAY_BUFFER,this._flatten(obj.lineNormals),Float32Array,gl.STATIC_DRAW);this.curStrokeShader.enableAttrib(this.curStrokeShader.attributes.aDirection.location,4,gl.FLOAT,false,0,0);}// initialize the fill shader's 'aPosition' buffer, if used if(this.curFillShader.attributes.aPosition){geometry.vertexBuffer=gl.createBuffer();// allocate space for vertex positions this._bindBuffer(geometry.vertexBuffer,gl.ARRAY_BUFFER,this._vToNArray(obj.vertices),Float32Array,gl.STATIC_DRAW);this.curFillShader.enableAttrib(this.curFillShader.attributes.aPosition.location,3,gl.FLOAT,false,0,0);}// allocate space for faces geometry.indexBuffer=gl.createBuffer();this._bindBuffer(geometry.indexBuffer,gl.ELEMENT_ARRAY_BUFFER,this._flatten(obj.faces),Uint16Array,gl.STATIC_DRAW);// initialize the fill shader's 'aNormal' buffer, if used if(this.curFillShader.attributes.aNormal){geometry.normalBuffer=gl.createBuffer();// allocate space for normals this._bindBuffer(geometry.normalBuffer,gl.ARRAY_BUFFER,this._vToNArray(obj.vertexNormals),Float32Array,gl.STATIC_DRAW);this.curFillShader.enableAttrib(this.curFillShader.attributes.aNormal.location,3,gl.FLOAT,false,0,0);}// initialize the fill shader's 'aTexCoord' buffer, if used if(this.curFillShader.attributes.aTexCoord){geometry.uvBuffer=gl.createBuffer();// tex coords this._bindBuffer(geometry.uvBuffer,gl.ARRAY_BUFFER,this._flatten(obj.uvs),Float32Array,gl.STATIC_DRAW);this.curFillShader.enableAttrib(this.curFillShader.attributes.aTexCoord.location,2,gl.FLOAT,false,0,0);}//} return geometry;};/** * Draws buffers given a geometry key ID * @private * @param {String} gId ID in our geom hash * @chainable */p5.RendererGL.prototype.drawBuffers=function(gId){var gl=this.GL;this._useColorShader();var geometry=this.gHash[gId];if(this._doStroke&&geometry.lineVertexCount>0){this.curStrokeShader.bindShader();// bind the stroke shader's 'aPosition' buffer if(geometry.lineVertexBuffer){this._bindBuffer(geometry.lineVertexBuffer,gl.ARRAY_BUFFER);this.curStrokeShader.enableAttrib(this.curStrokeShader.attributes.aPosition.location,3,gl.FLOAT,false,0,0);}// bind the stroke shader's 'aDirection' buffer if(geometry.lineNormalBuffer){this._bindBuffer(geometry.lineNormalBuffer,gl.ARRAY_BUFFER);this.curStrokeShader.enableAttrib(this.curStrokeShader.attributes.aDirection.location,4,gl.FLOAT,false,0,0);}this._applyColorBlend(this.curStrokeColor);this._drawArrays(gl.TRIANGLES,gId);this.curStrokeShader.unbindShader();}if(this._doFill!==false){this.curFillShader.bindShader();// bind the fill shader's 'aPosition' buffer if(geometry.vertexBuffer){//vertex position buffer this._bindBuffer(geometry.vertexBuffer,gl.ARRAY_BUFFER);this.curFillShader.enableAttrib(this.curFillShader.attributes.aPosition.location,3,gl.FLOAT,false,0,0);}if(geometry.indexBuffer){//vertex index buffer this._bindBuffer(geometry.indexBuffer,gl.ELEMENT_ARRAY_BUFFER);}// bind the fill shader's 'aNormal' buffer if(geometry.normalBuffer){this._bindBuffer(geometry.normalBuffer,gl.ARRAY_BUFFER);this.curFillShader.enableAttrib(this.curFillShader.attributes.aNormal.location,3,gl.FLOAT,false,0,0);}// bind the fill shader's 'aTexCoord' buffer if(geometry.uvBuffer){// uv buffer this._bindBuffer(geometry.uvBuffer,gl.ARRAY_BUFFER);this.curFillShader.enableAttrib(this.curFillShader.attributes.aTexCoord.location,2,gl.FLOAT,false,0,0);}this._applyColorBlend(this.curFillColor);this._drawElements(gl.TRIANGLES,gId);this.curFillShader.unbindShader();}return this;};/** * Calls drawBuffers() with a scaled model/view matrix. * * This is used by various 3d primitive methods (in primitives.js, eg. plane, * box, torus, etc...) to allow caching of un-scaled geometries. Those * geometries are generally created with unit-length dimensions, cached as * such, and then scaled appropriately in this method prior to rendering. * * @private * @method drawBuffersScaled * @param {String} gId ID in our geom hash * @param {Number} scaleX the amount to scale in the X direction * @param {Number} scaleY the amount to scale in the Y direction * @param {Number} scaleZ the amount to scale in the Z direction */p5.RendererGL.prototype.drawBuffersScaled=function(gId,scaleX,scaleY,scaleZ){var uMVMatrix=this.uMVMatrix.copy();try{this.uMVMatrix.scale(scaleX,scaleY,scaleZ);this.drawBuffers(gId);}finally{this.uMVMatrix=uMVMatrix;}};p5.RendererGL.prototype._drawArrays=function(drawMode,gId){this.GL.drawArrays(drawMode,0,this.gHash[gId].lineVertexCount);this._pInst._pixelsDirty=true;return this;};p5.RendererGL.prototype._drawElements=function(drawMode,gId){this.GL.drawElements(drawMode,this.gHash[gId].numberOfItems,this.GL.UNSIGNED_SHORT,0);this._pInst._pixelsDirty=true;};p5.RendererGL.prototype._drawPoints=function(vertices,vertexBuffer){var gl=this.GL;this._bindBuffer(vertexBuffer,gl.ARRAY_BUFFER,this._vToNArray(vertices),Float32Array,gl.STATIC_DRAW);this.curPointShader.enableAttrib(this.curPointShader.attributes.aPosition.location,3,gl.FLOAT,false,0,0);gl.drawArrays(gl.Points,0,vertices.length);};module.exports=p5.RendererGL;},{"../core/main":25}],75:[function(_dereq_,module,exports){'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');var libtess=_dereq_('libtess');_dereq_('./p5.Shader');_dereq_('./p5.Camera');_dereq_('../core/p5.Renderer');_dereq_('./p5.Matrix');var defaultShaders={immediateVert:"attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uResolution;\nuniform float uPointSize;\n\nvarying vec4 vColor;\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n gl_PointSize = uPointSize;\n}\n",vertexColorVert:"attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nvarying vec4 vColor;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n}\n",vertexColorFrag:"precision mediump float;\nvarying vec4 vColor;\nvoid main(void) {\n gl_FragColor = vColor;\n}",normalVert:"attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvarying vec3 vVertexNormal;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vVertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertTexCoord = aTexCoord;\n}\n",normalFrag:"precision mediump float;\nvarying vec3 vVertexNormal;\nvoid main(void) {\n gl_FragColor = vec4(vVertexNormal, 1.0);\n}",basicFrag:"precision mediump float;\nvarying vec3 vVertexNormal;\nuniform vec4 uMaterialColor;\nvoid main(void) {\n gl_FragColor = uMaterialColor;\n}",lightVert:"attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uViewMatrix;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\nuniform int uDirectionalLightCount;\nuniform int uPointLightCount;\n\nuniform vec3 uAmbientColor[8];\nuniform vec3 uLightingDirection[8];\nuniform vec3 uDirectionalColor[8];\nuniform vec3 uPointLightLocation[8];\nuniform vec3 uPointLightColor[8];\nuniform bool uSpecular;\n\nvarying vec3 vVertexNormal;\nvarying vec2 vVertTexCoord;\nvarying vec3 vLightWeighting;\n\nvoid main(void){\n\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\n vec3 vertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertexNormal = vertexNormal;\n vVertTexCoord = aTexCoord;\n\n vec4 mvPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n vec3 eyeDirection = normalize(-mvPosition.xyz);\n\n float shininess = 32.0;\n float specularFactor = 2.0;\n float diffuseFactor = 0.3;\n\n vec3 ambientLightFactor = vec3(0.0);\n\n for (int i = 0; i < 8; i++) {\n if (uAmbientLightCount == i) break;\n ambientLightFactor += uAmbientColor[i];\n }\n\n\n vec3 directionalLightFactor = vec3(0.0);\n\n for (int j = 0; j < 8; j++) {\n if (uDirectionalLightCount == j) break;\n vec3 dir = uLightingDirection[j];\n float directionalLightWeighting = max(dot(vertexNormal, -dir), 0.0);\n directionalLightFactor += uDirectionalColor[j] * directionalLightWeighting;\n }\n\n\n vec3 pointLightFactor = vec3(0.0);\n\n for (int k = 0; k < 8; k++) {\n if (uPointLightCount == k) break;\n vec3 loc = (uViewMatrix * vec4(uPointLightLocation[k], 1.0)).xyz;\n vec3 lightDirection = normalize(loc - mvPosition.xyz);\n\n float directionalLightWeighting = max(dot(vertexNormal, lightDirection), 0.0);\n\n float specularLightWeighting = 0.0;\n if (uSpecular ){\n vec3 reflectionDirection = reflect(-lightDirection, vertexNormal);\n specularLightWeighting = pow(max(dot(reflectionDirection, eyeDirection), 0.0), shininess);\n }\n\n pointLightFactor += uPointLightColor[k] * (specularFactor * specularLightWeighting\n + directionalLightWeighting * diffuseFactor);\n }\n\n vLightWeighting = ambientLightFactor + directionalLightFactor + pointLightFactor;\n}\n",lightTextureFrag:"precision mediump float;\n\nuniform vec4 uMaterialColor;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uUseLighting;\n\nvarying vec3 vLightWeighting;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n gl_FragColor = isTexture ? texture2D(uSampler, vVertTexCoord) : uMaterialColor;\n if (uUseLighting)\n gl_FragColor.rgb *= vLightWeighting;\n}",phongVert:"precision mediump float;\n\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform vec3 uAmbientColor[8];\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\n\nvoid main(void){\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n\n // Pass varyings to fragment shader\n vViewPosition = viewModelPosition.xyz;\n gl_Position = uProjectionMatrix * viewModelPosition; \n\n vNormal = normalize(uNormalMatrix * normalize(aNormal));\n vTexCoord = aTexCoord;\n\n vAmbientColor = vec3(0.0);\n for (int i = 0; i < 8; i++) {\n if (uAmbientLightCount == i) break;\n vAmbientColor += uAmbientColor[i];\n }\n}\n",phongFrag:"precision mediump float;\n\n//uniform mat4 uModelViewMatrix;\nuniform mat4 uViewMatrix;\n\nuniform vec4 uMaterialColor;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uUseLighting;\n\nuniform vec3 uLightingDirection[8];\nuniform vec3 uDirectionalColor[8];\nuniform vec3 uPointLightLocation[8];\nuniform vec3 uPointLightColor[8];\nuniform bool uSpecular;\n\nuniform int uDirectionalLightCount;\nuniform int uPointLightCount;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\n\nvec3 V;\nvec3 N;\n\nconst float shininess = 32.0;\nconst float specularFactor = 2.0;\nconst float diffuseFactor = 0.73;\n\nstruct LightResult {\n\tfloat specular;\n\tfloat diffuse;\n};\n\nfloat phongSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float shininess) {\n\n vec3 R = normalize(reflect(-lightDirection, surfaceNormal)); \n return pow(max(0.0, dot(R, viewDirection)), shininess);\n}\n\nfloat lambertDiffuse(\n vec3 lightDirection,\n vec3 surfaceNormal) {\n return max(0.0, dot(-lightDirection, surfaceNormal));\n}\n\nLightResult light(vec3 lightVector) {\n\n vec3 L = normalize(lightVector);\n\n //compute our diffuse & specular terms\n LightResult lr;\n if (uSpecular)\n lr.specular = phongSpecular(L, V, N, shininess);\n lr.diffuse = lambertDiffuse(L, N);\n return lr;\n}\n\nvoid main(void) {\n\n V = normalize(vViewPosition);\n N = vNormal;\n\n vec3 diffuse = vec3(0.0);\n float specular = 0.0;\n\n for (int j = 0; j < 8; j++) {\n if (uDirectionalLightCount == j) break;\n\n LightResult result = light(uLightingDirection[j]);\n diffuse += result.diffuse * uDirectionalColor[j];\n specular += result.specular;\n }\n\n for (int k = 0; k < 8; k++) {\n if (uPointLightCount == k) break;\n\n vec3 lightPosition = (uViewMatrix * vec4(uPointLightLocation[k], 1.0)).xyz;\n vec3 lightVector = vViewPosition - lightPosition;\n\t\n //calculate attenuation\n float lightDistance = length(lightVector);\n float falloff = 500.0 / (lightDistance + 500.0);\n\n LightResult result = light(lightVector);\n diffuse += result.diffuse * falloff * uPointLightColor[k];\n specular += result.specular * falloff;\n }\n\n gl_FragColor = isTexture ? texture2D(uSampler, vTexCoord) : uMaterialColor;\n gl_FragColor.rgb = gl_FragColor.rgb * (diffuse * diffuseFactor + vAmbientColor) + specular * specularFactor;\n}",fontVert:"precision mediump float;\n\nattribute vec3 aPosition;\nattribute vec2 aTexCoord;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nuniform vec4 uGlyphRect;\nuniform float uGlyphOffset;\n\nvarying vec2 vTexCoord;\nvarying float w;\n\nvoid main() {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // scale by the size of the glyph's rectangle\n positionVec4.xy *= uGlyphRect.zw - uGlyphRect.xy;\n\n // move to the corner of the glyph\n positionVec4.xy += uGlyphRect.xy;\n\n // move to the letter's line offset\n positionVec4.x += uGlyphOffset;\n \n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vTexCoord = aTexCoord;\n w = gl_Position.w;\n}\n",fontFrag:"#extension GL_OES_standard_derivatives : enable\nprecision mediump float;\n\n#if 0\n // simulate integer math using floats\n\t#define int float\n\t#define ivec2 vec2\n\t#define INT(x) float(x)\n\n\tint ifloor(float v) { return floor(v); }\n\tivec2 ifloor(vec2 v) { return floor(v); }\n\n#else\n // use native integer math\n\tprecision mediump int;\n\t#define INT(x) x\n\n\tint ifloor(float v) { return int(v); }\n\tint ifloor(int v) { return v; }\n\tivec2 ifloor(vec2 v) { return ivec2(v); }\n\n#endif\n\nuniform sampler2D uSamplerStrokes;\nuniform sampler2D uSamplerRowStrokes;\nuniform sampler2D uSamplerRows;\nuniform sampler2D uSamplerColStrokes;\nuniform sampler2D uSamplerCols;\n\nuniform ivec2 uStrokeImageSize;\nuniform ivec2 uCellsImageSize;\nuniform ivec2 uGridImageSize;\n\nuniform ivec2 uGridOffset;\nuniform ivec2 uGridSize;\nuniform vec4 uMaterialColor;\n\nvarying vec2 vTexCoord;\n\n// some helper functions\nint round(float v) { return ifloor(v + 0.5); }\nivec2 round(vec2 v) { return ifloor(v + 0.5); }\nfloat saturate(float v) { return clamp(v, 0.0, 1.0); }\nvec2 saturate(vec2 v) { return clamp(v, 0.0, 1.0); }\n\nint mul(float v1, int v2) {\n return ifloor(v1 * float(v2));\n}\n\nivec2 mul(vec2 v1, ivec2 v2) {\n return ifloor(v1 * vec2(v2) + 0.5);\n}\n\n// unpack a 16-bit integer from a float vec2\nint getInt16(vec2 v) {\n ivec2 iv = round(v * 255.0);\n return iv.x * INT(128) + iv.y;\n}\n\nvec2 pixelScale;\nvec2 coverage = vec2(0.0);\nvec2 weight = vec2(0.5);\nconst float minDistance = 1.0/8192.0;\nconst float hardness = 1.05; // amount of antialias\n\n// the maximum number of curves in a glyph\nconst int N = INT(250);\n\n// retrieves an indexed pixel from a sampler\nvec4 getTexel(sampler2D sampler, int pos, ivec2 size) {\n int width = size.x;\n int y = ifloor(pos / width);\n int x = pos - y * width; // pos % width\n\n return texture2D(sampler, (vec2(x, y) + 0.5) / vec2(size));\n}\n\nvoid calulateCrossings(vec2 p0, vec2 p1, vec2 p2, out vec2 C1, out vec2 C2) {\n\n // get the coefficients of the quadratic in t\n vec2 a = p0 - p1 * 2.0 + p2;\n vec2 b = p0 - p1;\n vec2 c = p0 - vTexCoord;\n\n // found out which values of 't' it crosses the axes\n vec2 surd = sqrt(max(vec2(0.0), b * b - a * c));\n vec2 t1 = ((b - surd) / a).yx;\n vec2 t2 = ((b + surd) / a).yx;\n\n // approximate straight lines to avoid rounding errors\n if (abs(a.y) < 0.001)\n t1.x = t2.x = c.y / (2.0 * b.y);\n\n if (abs(a.x) < 0.001)\n t1.y = t2.y = c.x / (2.0 * b.x);\n\n // plug into quadratic formula to find the corrdinates of the crossings\n C1 = ((a * t1 - b * 2.0) * t1 + c) * pixelScale;\n C2 = ((a * t2 - b * 2.0) * t2 + c) * pixelScale;\n}\n\nvoid coverageX(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n // determine on which side of the x-axis the points lie\n bool y0 = p0.y > vTexCoord.y;\n bool y1 = p1.y > vTexCoord.y;\n bool y2 = p2.y > vTexCoord.y;\n\n // could web be under the curve (after t1)?\n if (y1 ? !y2 : y0) {\n // add the coverage for t1\n coverage.x += saturate(C1.x + 0.5);\n // calculate the anti-aliasing for t1\n weight.x = min(weight.x, abs(C1.x));\n }\n\n // are we outside the curve (after t2)?\n if (y1 ? !y0 : y2) {\n // subtract the coverage for t2\n coverage.x -= saturate(C2.x + 0.5);\n // calculate the anti-aliasing for t2\n weight.x = min(weight.x, abs(C2.x));\n }\n}\n\n// this is essentially the same as coverageX, but with the axes swapped\nvoid coverageY(vec2 p0, vec2 p1, vec2 p2) {\n\n vec2 C1, C2;\n calulateCrossings(p0, p1, p2, C1, C2);\n\n bool x0 = p0.x > vTexCoord.x;\n bool x1 = p1.x > vTexCoord.x;\n bool x2 = p2.x > vTexCoord.x;\n\n if (x1 ? !x2 : x0) {\n coverage.y -= saturate(C1.y + 0.5);\n weight.y = min(weight.y, abs(C1.y));\n }\n\n if (x1 ? !x0 : x2) {\n coverage.y += saturate(C2.y + 0.5);\n weight.y = min(weight.y, abs(C2.y));\n }\n}\n\nvoid main() {\n\n // calculate the pixel scale based on screen-coordinates\n pixelScale = hardness / fwidth(vTexCoord);\n\n // which grid cell is this pixel in?\n ivec2 gridCoord = ifloor(vTexCoord * vec2(uGridSize));\n\n // intersect curves in this row\n {\n // the index into the row info bitmap\n int rowIndex = gridCoord.y + uGridOffset.y;\n // fetch the info texel\n vec4 rowInfo = getTexel(uSamplerRows, rowIndex, uGridImageSize);\n // unpack the rowInfo\n int rowStrokeIndex = getInt16(rowInfo.xy);\n int rowStrokeCount = getInt16(rowInfo.zw);\n\n for (int iRowStroke = INT(0); iRowStroke < N; iRowStroke++) {\n if (iRowStroke >= rowStrokeCount)\n break;\n\n // each stroke is made up of 3 points: the start and control point\n // and the start of the next curve.\n // fetch the indices of this pair of strokes:\n vec4 strokeIndices = getTexel(uSamplerRowStrokes, rowStrokeIndex++, uCellsImageSize);\n\n // unpack the stroke index\n int strokePos = getInt16(strokeIndices.xy);\n\n // fetch the two strokes\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n\n // calculate the coverage\n coverageX(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n // intersect curves in this column\n {\n int colIndex = gridCoord.x + uGridOffset.x;\n vec4 colInfo = getTexel(uSamplerCols, colIndex, uGridImageSize);\n int colStrokeIndex = getInt16(colInfo.xy);\n int colStrokeCount = getInt16(colInfo.zw);\n \n for (int iColStroke = INT(0); iColStroke < N; iColStroke++) {\n if (iColStroke >= colStrokeCount)\n break;\n\n vec4 strokeIndices = getTexel(uSamplerColStrokes, colStrokeIndex++, uCellsImageSize);\n\n int strokePos = getInt16(strokeIndices.xy);\n vec4 stroke0 = getTexel(uSamplerStrokes, strokePos + INT(0), uStrokeImageSize);\n vec4 stroke1 = getTexel(uSamplerStrokes, strokePos + INT(1), uStrokeImageSize);\n coverageY(stroke0.xy, stroke0.zw, stroke1.xy);\n }\n }\n\n weight = saturate(1.0 - weight * 2.0);\n float distance = max(weight.x + weight.y, minDistance); // manhattan approx.\n float antialias = abs(dot(coverage, weight) / distance);\n float cover = min(abs(coverage.x), abs(coverage.y));\n gl_FragColor = uMaterialColor;\n gl_FragColor.a *= saturate(max(antialias, cover));\n}",lineVert:"/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform vec4 uViewport;\n\n// using a scale <1 moves the lines towards the camera\n// in order to prevent popping effects due to half of\n// the line disappearing behind the geometry faces.\nvec3 scale = vec3(0.9995);\n\nattribute vec4 aPosition;\nattribute vec4 aDirection;\n \nvoid main() {\n vec4 posp = uModelViewMatrix * aPosition;\n vec4 posq = uModelViewMatrix * (aPosition + vec4(aDirection.xyz, 0));\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // Discussed here:\n // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848 \n posp.xyz = posp.xyz * scale;\n posq.xyz = posq.xyz * scale;\n\n vec4 p = uProjectionMatrix * posp;\n vec4 q = uProjectionMatrix * posq;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don't care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can't remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangent = normalize((q.xy*p.w - p.xy*q.w) * uViewport.zw);\n\n // flip tangent to normal (it's already normalized)\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float thickness = aDirection.w * uStrokeWeight;\n vec2 offset = normal * thickness / 2.0;\n\n // Perspective ---\n // convert from world to clip by multiplying with projection scaling factor\n // to get the right thickness (see https://github.com/processing/processing/issues/5182)\n // invert Y, projections in Processing invert Y\n vec2 perspScale = (uProjectionMatrix * vec4(1, -1, 0, 0)).xy;\n\n // No Perspective ---\n // multiply by W (to cancel out division by W later in the pipeline) and\n // convert from screen to clip (derived from clip to screen above)\n vec2 noPerspScale = p.w / (0.5 * uViewport.zw);\n\n //gl_Position.xy = p.xy + offset.xy * mix(noPerspScale, perspScale, float(perspective > 0));\n gl_Position.xy = p.xy + offset.xy * perspScale;\n gl_Position.zw = p.zw;\n}\n",lineFrag:"precision mediump float;\nprecision mediump int;\n\nuniform vec4 uMaterialColor;\n\nvoid main() {\n gl_FragColor = uMaterialColor;\n}",pointVert:"attribute vec3 aPosition;\nuniform float uPointSize;\nvarying float vStrokeWeight;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nvoid main() {\n\tvec4 positionVec4 = vec4(aPosition, 1.0);\n\tgl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\tgl_PointSize = uPointSize;\n\tvStrokeWeight = uPointSize;\n}",pointFrag:"precision mediump float;\nprecision mediump int;\nuniform vec4 uMaterialColor;\nvarying float vStrokeWeight;\n\nvoid main(){\n\tfloat mask = 0.0;\n\n\t// make a circular mask using the gl_PointCoord (goes from 0 - 1 on a point)\n // might be able to get a nicer edge on big strokeweights with smoothstep but slightly less performant\n\n\tmask = step(0.98, length(gl_PointCoord * 2.0 - 1.0));\n\n\t// if strokeWeight is 1 or less lets just draw a square\n\t// this prevents weird artifacting from carving circles when our points are really small\n\t// if strokeWeight is larger than 1, we just use it as is\n\n\tmask = mix(0.0, mask, clamp(floor(vStrokeWeight - 0.5),0.0,1.0));\n\n\t// throw away the borders of the mask\n // otherwise we get weird alpha blending issues\n\n\tif(mask > 0.98){\n discard;\n \t}\n\n \tgl_FragColor = vec4(uMaterialColor.rgb * (1.0 - mask), uMaterialColor.a) ;\n}"};/** * 3D graphics class * @private * @class p5.RendererGL * @constructor * @extends p5.Renderer * @todo extend class to include public method for offscreen * rendering (FBO). * */p5.RendererGL=function(elt,pInst,isMainCanvas,attr){p5.Renderer.call(this,elt,pInst,isMainCanvas);this.attributes={};attr=attr||{};this.attributes.alpha=attr.alpha===undefined?true:attr.alpha;this.attributes.depth=attr.depth===undefined?true:attr.depth;this.attributes.stencil=attr.stencil===undefined?true:attr.stencil;this.attributes.antialias=attr.antialias===undefined?false:attr.antialias;this.attributes.premultipliedAlpha=attr.premultipliedAlpha===undefined?false:attr.premultipliedAlpha;this.attributes.preserveDrawingBuffer=attr.preserveDrawingBuffer===undefined?true:attr.preserveDrawingBuffer;this.attributes.perPixelLighting=attr.perPixelLighting===undefined?false:attr.perPixelLighting;this._initContext();this.isP3D=true;//lets us know we're in 3d mode this.GL=this.drawingContext;// lights this.ambientLightColors=[];this.directionalLightDirections=[];this.directionalLightColors=[];this.pointLightPositions=[];this.pointLightColors=[];/** * model view, projection, & normal * matrices */this.uMVMatrix=new p5.Matrix();this.uPMatrix=new p5.Matrix();this.uNMatrix=new p5.Matrix('mat3');// Camera this._curCamera=new p5.Camera(this);this._curCamera._computeCameraDefaultSettings();this._curCamera._setDefaultCamera();//Geometry & Material hashes this.gHash={};this._defaultLightShader=undefined;this._defaultImmediateModeShader=undefined;this._defaultNormalShader=undefined;this._defaultColorShader=undefined;this._defaultPointShader=undefined;this.curFillShader=undefined;this.curStrokeShader=undefined;this.curPointShader=undefined;this._useColorShader();this.setStrokeShader(this._getLineShader());this._usePointShader();this._pointVertexBuffer=this.GL.createBuffer();//Imediate Mode //default drawing is done in Retained Mode this.isImmediateDrawing=false;this.immediateMode={};// note: must call fill() and stroke () AFTER // default shader has been set. this.fill(255,255,255,255);//this.stroke(0, 0, 0, 255); this.pointSize=5.0;//default point size this.strokeWeight(1);this.stroke(0,0,0);// array of textures created in this gl context via this.getTexture(src) this.textures=[];this._curveTightness=6;// lookUpTable for coefficients needed to be calculated for bezierVertex, same are used for curveVertex this._lookUpTableBezier=[];// lookUpTable for coefficients needed to be calculated for quadraticVertex this._lookUpTableQuadratic=[];// current curveDetail in the Bezier lookUpTable this._lutBezierDetail=0;// current curveDetail in the Quadratic lookUpTable this._lutQuadraticDetail=0;this._tessy=this._initTessy();this.fontInfos={};return this;};p5.RendererGL.prototype=Object.create(p5.Renderer.prototype);////////////////////////////////////////////// // Setting ////////////////////////////////////////////// p5.RendererGL.prototype._initContext=function(){try{this.drawingContext=this.canvas.getContext('webgl',this.attributes)||this.canvas.getContext('experimental-webgl',this.attributes);if(this.drawingContext===null){throw new Error('Error creating webgl context');}else{console.log('p5.RendererGL: enabled webgl context');var gl=this.drawingContext;gl.enable(gl.DEPTH_TEST);gl.depthFunc(gl.LEQUAL);gl.viewport(0,0,gl.drawingBufferWidth,gl.drawingBufferHeight);this._viewport=this.drawingContext.getParameter(this.drawingContext.VIEWPORT);}}catch(er){throw er;}};//This is helper function to reset the context anytime the attributes //are changed with setAttributes() p5.RendererGL.prototype._resetContext=function(attr,options,callback){var w=this.width;var h=this.height;var defaultId=this.canvas.id;var c=this.canvas;if(c){c.parentNode.removeChild(c);}c=document.createElement('canvas');c.id=defaultId;if(this._pInst._userNode){this._pInst._userNode.appendChild(c);}else{document.body.appendChild(c);}this._pInst.canvas=c;var renderer=new p5.RendererGL(this._pInst.canvas,this._pInst,true,attr);this._pInst._setProperty('_renderer',renderer);renderer.resize(w,h);renderer._applyDefaults();this._pInst._elements.push(renderer);if(typeof callback==='function'){//setTimeout with 0 forces the task to the back of the queue, this ensures that //we finish switching out the renderer setTimeout(function(){callback.apply(window._renderer,options);},0);}};/** * @module Rendering * @submodule Rendering * @for p5 *//** * Set attributes for the WebGL Drawing context. * This is a way of adjusting ways that the WebGL * renderer works to fine-tune the display and performance. * This should be put in setup(). * The available attributes are: * <br> * alpha - indicates if the canvas contains an alpha buffer * default is true * <br><br> * depth - indicates whether the drawing buffer has a depth buffer * of at least 16 bits - default is true * <br><br> * stencil - indicates whether the drawing buffer has a stencil buffer * of at least 8 bits * <br><br> * antialias - indicates whether or not to perform anti-aliasing * default is false * <br><br> * premultipliedAlpha - indicates that the page compositor will assume * the drawing buffer contains colors with pre-multiplied alpha * default is false * <br><br> * preserveDrawingBuffer - if true the buffers will not be cleared and * and will preserve their values until cleared or overwritten by author * (note that p5 clears automatically on draw loop) * default is true * <br><br> * perPixelLighting - if true, per-pixel lighting will be used in the * lighting shader. * default is false * <br><br> * @method setAttributes * @for p5 * @param {String} key Name of attribute * @param {Boolean} value New value of named attribute * @example * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(255); * push(); * rotateZ(frameCount * 0.02); * rotateX(frameCount * 0.02); * rotateY(frameCount * 0.02); * fill(0, 0, 0); * box(50); * pop(); * } * </code> * </div> * <br> * Now with the antialias attribute set to true. * <br> * <div> * <code> * function setup() { * createCanvas(100, 100, WEBGL); * setAttributes('antialias', true); * } * * function draw() { * background(255); * push(); * rotateZ(frameCount * 0.02); * rotateX(frameCount * 0.02); * rotateY(frameCount * 0.02); * fill(0, 0, 0); * box(50); * pop(); * } * </code> * </div> * * <div> * <code> * // press the mouse button to enable perPixelLighting * function setup() { * createCanvas(100, 100, WEBGL); * noStroke(); * fill(255); * } * * var lights = [ * { c: '#f00', t: 1.12, p: 1.91, r: 0.2 }, * { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 }, * { c: '#00f', t: 1.37, p: 1.57, r: 0.2 }, * { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 }, * { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 }, * { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 } * ]; * * function draw() { * var t = millis() / 1000 + 1000; * background(0); * directionalLight(color('#222'), 1, 1, 1); * * for (var i = 0; i < lights.length; i++) { * var light = lights[i]; * pointLight( * color(light.c), * p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r) * ); * } * * specularMaterial(255); * sphere(width * 0.1); * * rotateX(t * 0.77); * rotateY(t * 0.83); * rotateZ(t * 0.91); * torus(width * 0.3, width * 0.07, 30, 10); * } * * function mousePressed() { * setAttributes('perPixelLighting', true); * noStroke(); * fill(255); * } * function mouseReleased() { * setAttributes('perPixelLighting', false); * noStroke(); * fill(255); * } * </code> * </div> * * @alt a rotating cube with smoother edges *//** * @method setAttributes * @for p5 * @param {Object} obj object with key-value pairs */p5.prototype.setAttributes=function(key,value){this._assert3d('setAttributes');//@todo_FES var attr;if(typeof value!=='undefined'){attr={};attr[key]=value;}else if(key instanceof Object){attr=key;}this.push();this._renderer._resetContext(attr);this.pop();};/** * @class p5.RendererGL */p5.RendererGL.prototype._update=function(){// reset model view and apply initial camera transform // (containing only look at info; no projection). this.uMVMatrix.set(this._curCamera.cameraMatrix.mat4[0],this._curCamera.cameraMatrix.mat4[1],this._curCamera.cameraMatrix.mat4[2],this._curCamera.cameraMatrix.mat4[3],this._curCamera.cameraMatrix.mat4[4],this._curCamera.cameraMatrix.mat4[5],this._curCamera.cameraMatrix.mat4[6],this._curCamera.cameraMatrix.mat4[7],this._curCamera.cameraMatrix.mat4[8],this._curCamera.cameraMatrix.mat4[9],this._curCamera.cameraMatrix.mat4[10],this._curCamera.cameraMatrix.mat4[11],this._curCamera.cameraMatrix.mat4[12],this._curCamera.cameraMatrix.mat4[13],this._curCamera.cameraMatrix.mat4[14],this._curCamera.cameraMatrix.mat4[15]);// reset light data for new frame. this.ambientLightColors.length=0;this.directionalLightDirections.length=0;this.directionalLightColors.length=0;this.pointLightPositions.length=0;this.pointLightColors.length=0;};/** * [background description] */p5.RendererGL.prototype.background=function(){var _col=this._pInst.color.apply(this._pInst,arguments);var _r=_col.levels[0]/255;var _g=_col.levels[1]/255;var _b=_col.levels[2]/255;var _a=_col.levels[3]/255;this.GL.clearColor(_r,_g,_b,_a);this.GL.depthMask(true);this.GL.clear(this.GL.COLOR_BUFFER_BIT|this.GL.DEPTH_BUFFER_BIT);};//@TODO implement this // p5.RendererGL.prototype.clear = function() { //@TODO // }; ////////////////////////////////////////////// // COLOR ////////////////////////////////////////////// /** * Basic fill material for geometry with a given color * @method fill * @class p5.RendererGL * @param {Number|Number[]|String|p5.Color} v1 gray value, * red or hue value (depending on the current color mode), * or color Array, or CSS color string * @param {Number} [v2] green or saturation value * @param {Number} [v3] blue or brightness value * @param {Number} [a] opacity * @chainable * @example * <div> * <code> * function setup() { * createCanvas(200, 200, WEBGL); * } * * function draw() { * background(0); * noStroke(); * fill(100, 100, 240); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(75, 75, 75); * } * </code> * </div> * * @alt * black canvas with purple cube spinning * */p5.RendererGL.prototype.fill=function(v1,v2,v3,a){//see material.js for more info on color blending in webgl var color=p5.prototype.color.apply(this._pInst,arguments);this.curFillColor=color._array;if(this.isImmediateDrawing){this.setFillShader(this._getImmediateModeShader());}else{this.setFillShader(this._getColorShader());}this.drawMode=constants.FILL;this.curFillShader.setUniform('uMaterialColor',this.curFillColor);};/** * Basic stroke material for geometry with a given color * @method stroke * @param {Number|Number[]|String|p5.Color} v1 gray value, * red or hue value (depending on the current color mode), * or color Array, or CSS color string * @param {Number} [v2] green or saturation value * @param {Number} [v3] blue or brightness value * @param {Number} [a] opacity * @example * <div> * <code> * function setup() { * createCanvas(200, 200, WEBGL); * } * * function draw() { * background(0); * stroke(240, 150, 150); * fill(100, 100, 240); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(75, 75, 75); * } * </code> * </div> * * @alt * black canvas with purple cube with pink outline spinning * */p5.RendererGL.prototype.stroke=function(r,g,b,a){//@todo allow transparency in stroking currently doesn't have //any impact and causes problems with specularMaterial arguments[3]=255;var color=p5.prototype.color.apply(this._pInst,arguments);this.curStrokeColor=color._array;this.curStrokeShader.setUniform('uMaterialColor',this.curStrokeColor);this.curPointShader.setUniform('uMaterialColor',color._array);};/** * Change weight of stroke * @method strokeWeight * @param {Number} stroke weight to be used for drawing * @example * <div> * <code> * function setup() { * createCanvas(200, 400, WEBGL); * setAttributes('antialias', true); * } * * function draw() { * background(0); * noStroke(); * translate(0, -100, 0); * stroke(240, 150, 150); * fill(100, 100, 240); * push(); * strokeWeight(8); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * sphere(75); * pop(); * push(); * translate(0, 200, 0); * strokeWeight(1); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * sphere(75); * pop(); * } * </code> * </div> * * @alt * black canvas with two purple rotating spheres with pink * outlines the sphere on top has much heavier outlines, * */p5.RendererGL.prototype.strokeWeight=function(w){if(this.curStrokeWeight!==w){this.pointSize=w;this.curStrokeWeight=w;this.curStrokeShader.setUniform('uStrokeWeight',w);this.curPointShader.setUniform('uPointSize',w);}};/** * Returns an array of [R,G,B,A] values for any pixel or grabs a section of * an image. If no parameters are specified, the entire image is returned. * Use the x and y parameters to get the value of one pixel. Get a section of * the display window by specifying additional w and h parameters. When * getting an image, the x and y parameters define the coordinates for the * upper-left corner of the image, regardless of the current imageMode(). * <br><br> * If the pixel requested is outside of the image window, [0,0,0,255] is * returned. * <br><br> * Getting the color of a single pixel with get(x, y) is easy, but not as fast * as grabbing the data directly from pixels[]. The equivalent statement to * get(x, y) is using pixels[] with pixel density d * * @private * @method get * @param {Number} [x] x-coordinate of the pixel * @param {Number} [y] y-coordinate of the pixel * @param {Number} [w] width * @param {Number} [h] height * @return {Number[]|Color|p5.Image} color of pixel at x,y in array format * [R, G, B, A] or <a href="#/p5.Image">p5.Image</a> */p5.RendererGL.prototype.get=function(x,y,w,h){return p5.Renderer2D.prototype.get.apply(this,[x,y,w,h]);};/** * Loads the pixels data for this canvas into the pixels[] attribute. * Note that updatePixels() and set() do not work. * Any pixel manipulation must be done directly to the pixels[] array. * * @private * @method loadPixels * */p5.RendererGL.prototype.loadPixels=function(){//@todo_FES if(this.attributes.preserveDrawingBuffer!==true){console.log('loadPixels only works in WebGL when preserveDrawingBuffer '+'is true.');return;}var pd=this._pInst._pixelDensity;var x=0;var y=0;var w=this.width;var h=this.height;w*=pd;h*=pd;//if there isn't a renderer-level temporary pixels buffer //make a new one if(typeof this.pixels==='undefined'){this.pixels=new Uint8Array(this.GL.drawingBufferWidth*this.GL.drawingBufferHeight*4);}this.GL.readPixels(x,y,w,h,this.GL.RGBA,this.GL.UNSIGNED_BYTE,this.pixels);this._pInst._setProperty('pixels',this.pixels);};////////////////////////////////////////////// // HASH | for geometry ////////////////////////////////////////////// p5.RendererGL.prototype.geometryInHash=function(gId){return this.gHash[gId]!==undefined;};/** * [resize description] * @private * @param {Number} w [description] * @param {Number} h [description] */p5.RendererGL.prototype.resize=function(w,h){p5.Renderer.prototype.resize.call(this,w,h);this.GL.viewport(0,0,this.GL.drawingBufferWidth,this.GL.drawingBufferHeight);this._viewport=this.GL.getParameter(this.GL.VIEWPORT);this._curCamera._resize();//resize pixels buffer if(typeof this.pixels!=='undefined'){this.pixels=new Uint8Array(this.GL.drawingBufferWidth*this.GL.drawingBufferHeight*4);}};/** * clears color and depth buffers * with r,g,b,a * @private * @param {Number} r normalized red val. * @param {Number} g normalized green val. * @param {Number} b normalized blue val. * @param {Number} a normalized alpha val. */p5.RendererGL.prototype.clear=function(){var _r=arguments[0]||0;var _g=arguments[1]||0;var _b=arguments[2]||0;var _a=arguments[3]||0;this.GL.clearColor(_r,_g,_b,_a);this.GL.clear(this.GL.COLOR_BUFFER_BIT|this.GL.DEPTH_BUFFER_BIT);};/** * [translate description] * @private * @param {Number} x [description] * @param {Number} y [description] * @param {Number} z [description] * @chainable * @todo implement handle for components or vector as args */p5.RendererGL.prototype.translate=function(x,y,z){if(x instanceof p5.Vector){z=x.z;y=x.y;x=x.x;}this.uMVMatrix.translate([x,y,z]);return this;};/** * Scales the Model View Matrix by a vector * @private * @param {Number | p5.Vector | Array} x [description] * @param {Number} [y] y-axis scalar * @param {Number} [z] z-axis scalar * @chainable */p5.RendererGL.prototype.scale=function(x,y,z){this.uMVMatrix.scale(x,y,z);return this;};p5.RendererGL.prototype.rotate=function(rad,axis){if(typeof axis==='undefined'){return this.rotateZ(rad);}arguments[0]=this._pInst._fromRadians(rad);p5.Matrix.prototype.rotate.apply(this.uMVMatrix,arguments);return this;};p5.RendererGL.prototype.rotateX=function(rad){this.rotate(rad,1,0,0);return this;};p5.RendererGL.prototype.rotateY=function(rad){this.rotate(rad,0,1,0);return this;};p5.RendererGL.prototype.rotateZ=function(rad){this.rotate(rad,0,0,1);return this;};p5.RendererGL.prototype.push=function(){// get the base renderer style var style=p5.Renderer.prototype.push.apply(this);// add webgl-specific style properties var properties=style.properties;properties.uMVMatrix=this.uMVMatrix.copy();properties.uPMatrix=this.uPMatrix.copy();properties._curCamera=this._curCamera;// make a copy of the current camera for the push state // this preserves any references stored using 'createCamera' this._curCamera=this._curCamera.copy();return style;};p5.RendererGL.prototype.resetMatrix=function(){this.uMVMatrix=p5.Matrix.identity(this._pInst);return this;};////////////////////////////////////////////// // SHADER ////////////////////////////////////////////// /* * Initializes and uses the specified shader, then returns * that shader. Note: initialization and resetting the program * is only used if needed (say, if a new value is provided) * so it is safe to call this method with the same shader multiple * times without a signficant performance hit). * * @method setFillShader * @param {p5.Shader} [s] a p5.Shader object * @return {p5.Shader} the current, updated fill shader */p5.RendererGL.prototype.setFillShader=function(s){if(this.curFillShader!==s){// only do setup etc. if shader is actually new. this.curFillShader=s;// safe to do this multiple times; // init() will bail early if has already been run. this.curFillShader.init();//this.curFillShader.useProgram(); }// always return this.curFillShader, even if no change was made. return this.curFillShader;};p5.RendererGL.prototype.setPointShader=function(s){if(this.curPointShader!==s){// only do setup etc. if shader is actually new. this.curPointShader=s;// safe to do this multiple times; // init() will bail early if has already been run. this.curPointShader.init();}return this.curPointShader;};/* * @method setStrokeShader * @param {p5.Shader} [s] a p5.Shader object * @return {p5.Shader} the current, updated stroke shader */p5.RendererGL.prototype.setStrokeShader=function(s){if(this.curStrokeShader!==s){// only do setup etc. if shader is actually new. this.curStrokeShader=s;// safe to do this multiple times; // init() will bail early if has already been run. this.curStrokeShader.init();//this.curStrokeShader.useProgram(); }// always return this.curLineShader, even if no change was made. return this.curStrokeShader;};/* * shaders are created and cached on a per-renderer basis, * on the grounds that each renderer will have its own gl context * and the shader must be valid in that context. * * */p5.RendererGL.prototype._useLightShader=function(){if(!this.curFillShader||!this.curFillShader.isLightShader()){this.setFillShader(this._getLightShader());}return this.curFillShader;};p5.RendererGL.prototype._useColorShader=function(){// looking at the code within the glsl files, I'm not really // sure why these are two different shaders. but, they are, // and if we're drawing in retain mode but the shader is the // immediate mode one, we need to switch. // TODO: what if curFillShader is _any_ other shader? if(!this.curFillShader||this.curFillShader===this._defaultImmediateModeShader){// there are different immediate mode and retain mode color shaders. // if we're using the immediate mode one, we need to switch to // one that works for retain mode. this.setFillShader(this._getColorShader());}return this.curFillShader;};p5.RendererGL.prototype._usePointShader=function(){if(!this.curPointShader){this.setPointShader(this._getPointShader());}return this.curPointShader;};p5.RendererGL.prototype._useImmediateModeShader=function(){// TODO: what if curFillShader is _any_ other shader? if(!this.curFillShader||this.curFillShader===this._defaultColorShader){// this is the fill/stroke shader for retain mode. // must switch to immediate mode shader before drawing! this.setFillShader(this._getImmediateModeShader());// note that if we're using the texture shader... // this shouldn't change. :) }return this.curFillShader;};p5.RendererGL.prototype._getLightShader=function(){if(!this._defaultLightShader){if(this.attributes.perPixelLighting){this._defaultLightShader=new p5.Shader(this,defaultShaders.phongVert,defaultShaders.phongFrag);}else{this._defaultLightShader=new p5.Shader(this,defaultShaders.lightVert,defaultShaders.lightTextureFrag);}}//this.drawMode = constants.FILL; return this._defaultLightShader;};p5.RendererGL.prototype._getImmediateModeShader=function(){if(!this._defaultImmediateModeShader){this._defaultImmediateModeShader=new p5.Shader(this,defaultShaders.immediateVert,defaultShaders.vertexColorFrag);}//this.drawMode = constants.FILL; return this._defaultImmediateModeShader;};p5.RendererGL.prototype._getNormalShader=function(){if(!this._defaultNormalShader){this._defaultNormalShader=new p5.Shader(this,defaultShaders.normalVert,defaultShaders.normalFrag);}//this.drawMode = constants.FILL; return this._defaultNormalShader;};p5.RendererGL.prototype._getColorShader=function(){if(!this._defaultColorShader){this._defaultColorShader=new p5.Shader(this,defaultShaders.normalVert,defaultShaders.basicFrag);}//this.drawMode = constants.FILL; return this._defaultColorShader;};p5.RendererGL.prototype._getPointShader=function(){if(!this._defaultPointShader){this._defaultPointShader=new p5.Shader(this,defaultShaders.pointVert,defaultShaders.pointFrag);}return this._defaultPointShader;};p5.RendererGL.prototype._getLineShader=function(){if(!this._defaultLineShader){this._defaultLineShader=new p5.Shader(this,defaultShaders.lineVert,defaultShaders.lineFrag);}//this.drawMode = constants.STROKE; return this._defaultLineShader;};p5.RendererGL.prototype._getFontShader=function(){if(!this._defaultFontShader){this.GL.getExtension('OES_standard_derivatives');this._defaultFontShader=new p5.Shader(this,defaultShaders.fontVert,defaultShaders.fontFrag);}return this._defaultFontShader;};p5.RendererGL.prototype._getEmptyTexture=function(){if(!this._emptyTexture){// a plain white texture RGBA, full alpha, single pixel. var im=new p5.Image(1,1);im.set(0,0,255);this._emptyTexture=new p5.Texture(this,im);}return this._emptyTexture;};p5.RendererGL.prototype.getTexture=function(img){var textures=this.textures;for(var it=0;it<textures.length;++it){var texture=textures[it];if(texture.src===img)return texture;}var tex=new p5.Texture(this,img);this.textures.push(tex);return tex;};//Binds a buffer to the drawing context //when passed more than two arguments it also updates or initializes //the data associated with the buffer p5.RendererGL.prototype._bindBuffer=function(buffer,target,values,type,usage){this.GL.bindBuffer(target,buffer);if(values!==undefined){var data=new type(values);this.GL.bufferData(target,data,usage);}};////////////////////////// //// SMOOTHING ///////////////////////// p5.RendererGL.prototype.smooth=function(){if(this.attributes.antialias===false){this._pInst.setAttributes('antialias',true);}};p5.RendererGL.prototype.noSmooth=function(){if(this.attributes.antialias===true){this._pInst.setAttributes('antialias',false);}};/////////////////////////////// //// UTILITY FUNCTIONS ////////////////////////////// /** * turn a two dimensional array into one dimensional array * @private * @param {Array} arr 2-dimensional array * @return {Array} 1-dimensional array * [[1, 2, 3],[4, 5, 6]] -> [1, 2, 3, 4, 5, 6] */p5.RendererGL.prototype._flatten=function(arr){//when empty, return empty if(arr.length===0){return[];}else if(arr.length>20000){//big models , load slower to avoid stack overflow //faster non-recursive flatten via axelduch //stackoverflow.com/questions/27266550/how-to-flatten-nested-array-in-javascript var toString=Object.prototype.toString;var arrayTypeStr='[object Array]';var result=[];var nodes=arr.slice();var node;node=nodes.pop();do{if(toString.call(node)===arrayTypeStr){nodes.push.apply(nodes,node);}else{result.push(node);}}while(nodes.length&&(node=nodes.pop())!==undefined);result.reverse();// we reverse result to restore the original order return result;}else{//otherwise if model within limits for browser //use faster recursive loading return[].concat.apply([],arr);}};/** * turn a p5.Vector Array into a one dimensional number array * @private * @param {p5.Vector[]} arr an array of p5.Vector * @return {Number[]} a one dimensional array of numbers * [p5.Vector(1, 2, 3), p5.Vector(4, 5, 6)] -> * [1, 2, 3, 4, 5, 6] */p5.RendererGL.prototype._vToNArray=function(arr){return this._flatten(arr.map(function(item){return[item.x,item.y,item.z];}));};/** * ensures that p5 is using a 3d renderer. throws an error if not. */p5.prototype._assert3d=function(name){if(!this._renderer.isP3D)throw new Error(name+"() is only supported in WEBGL mode. If you'd like to use 3D graphics"+' and WebGL, see https://p5js.org/examples/form-3d-primitives.html'+' for more information.');};// function to initialize GLU Tesselator p5.RendererGL.prototype._initTessy=function initTesselator(){// function called for each vertex of tesselator output function vertexCallback(data,polyVertArray){polyVertArray[polyVertArray.length]=data[0];polyVertArray[polyVertArray.length]=data[1];polyVertArray[polyVertArray.length]=data[2];}function begincallback(type){if(type!==libtess.primitiveType.GL_TRIANGLES){console.log('expected TRIANGLES but got type: '+type);}}function errorcallback(errno){console.log('error callback');console.log('error number: '+errno);}// callback for when segments intersect and must be split function combinecallback(coords,data,weight){return[coords[0],coords[1],coords[2]];}function edgeCallback(flag){// don't really care about the flag, but need no-strip/no-fan behavior }var tessy=new libtess.GluTesselator();tessy.gluTessCallback(libtess.gluEnum.GLU_TESS_VERTEX_DATA,vertexCallback);tessy.gluTessCallback(libtess.gluEnum.GLU_TESS_BEGIN,begincallback);tessy.gluTessCallback(libtess.gluEnum.GLU_TESS_ERROR,errorcallback);tessy.gluTessCallback(libtess.gluEnum.GLU_TESS_COMBINE,combinecallback);tessy.gluTessCallback(libtess.gluEnum.GLU_TESS_EDGE_FLAG,edgeCallback);return tessy;};p5.RendererGL.prototype._triangulate=function(contours){// libtess will take 3d verts and flatten to a plane for tesselation // since only doing 2d tesselation here, provide z=1 normal to skip // iterating over verts only to get the same answer. // comment out to test normal-generation code this._tessy.gluTessNormal(0,0,1);var triangleVerts=[];this._tessy.gluTessBeginPolygon(triangleVerts);for(var i=0;i<contours.length;i++){this._tessy.gluTessBeginContour();var contour=contours[i];for(var j=0;j<contour.length;j+=3){var coords=[contour[j],contour[j+1],contour[j+2]];this._tessy.gluTessVertex(coords,coords);}this._tessy.gluTessEndContour();}// finish polygon this._tessy.gluTessEndPolygon();return triangleVerts;};// function to calculate BezierVertex Coefficients p5.RendererGL.prototype._bezierCoefficients=function(t){var t2=t*t;var t3=t2*t;var mt=1-t;var mt2=mt*mt;var mt3=mt2*mt;return[mt3,3*mt2*t,3*mt*t2,t3];};// function to calculate QuadraticVertex Coefficients p5.RendererGL.prototype._quadraticCoefficients=function(t){var t2=t*t;var mt=1-t;var mt2=mt*mt;return[mt2,2*mt*t,t2];};// function to convert Bezier coordinates to Catmull Rom Splines p5.RendererGL.prototype._bezierToCatmull=function(w){var p1=w[1];var p2=w[1]+(w[2]-w[0])/this._curveTightness;var p3=w[2]-(w[3]-w[1])/this._curveTightness;var p4=w[2];var p=[p1,p2,p3,p4];return p;};module.exports=p5.RendererGL;},{"../core/constants":19,"../core/main":25,"../core/p5.Renderer":28,"./p5.Camera":70,"./p5.Matrix":72,"./p5.Shader":76,"libtess":10}],76:[function(_dereq_,module,exports){/** * This module defines the p5.Shader class * @module Lights, Camera * @submodule Shaders * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');/** * Shader class for WEBGL Mode * @class p5.Shader * @param {p5.RendererGL} renderer an instance of p5.RendererGL that * will provide the GL context for this new p5.Shader * @param {String} vertSrc source code for the vertex shader (as a string) * @param {String} fragSrc source code for the fragment shader (as a string) */p5.Shader=function(renderer,vertSrc,fragSrc){// TODO: adapt this to not take ids, but rather, // to take the source for a vertex and fragment shader // to enable custom shaders at some later date this._renderer=renderer;this._vertSrc=vertSrc;this._fragSrc=fragSrc;this._vertShader=-1;this._fragShader=-1;this._glProgram=0;this._loadedAttributes=false;this.attributes={};this._loadedUniforms=false;this.uniforms={};this._bound=false;this.samplers=[];};/** * Creates, compiles, and links the shader based on its * sources for the vertex and fragment shaders (provided * to the constructor). Populates known attributes and * uniforms from the shader. * @method init * @chainable * @private */p5.Shader.prototype.init=function(){if(this._glProgram===0/* or context is stale? */){var gl=this._renderer.GL;// @todo: once custom shading is allowed, // friendly error messages should be used here to share // compiler and linker errors. //set up the shader by // 1. creating and getting a gl id for the shader program, // 2. compliling its vertex & fragment sources, // 3. linking the vertex and fragment shaders this._vertShader=gl.createShader(gl.VERTEX_SHADER);//load in our default vertex shader gl.shaderSource(this._vertShader,this._vertSrc);gl.compileShader(this._vertShader);// if our vertex shader failed compilation? if(!gl.getShaderParameter(this._vertShader,gl.COMPILE_STATUS)){console.error('Yikes! An error occurred compiling the vertex shader:'+gl.getShaderInfoLog(this._vertShader));return null;}this._fragShader=gl.createShader(gl.FRAGMENT_SHADER);//load in our material frag shader gl.shaderSource(this._fragShader,this._fragSrc);gl.compileShader(this._fragShader);// if our frag shader failed compilation? if(!gl.getShaderParameter(this._fragShader,gl.COMPILE_STATUS)){console.error('Darn! An error occurred compiling the fragment shader:'+gl.getShaderInfoLog(this._fragShader));return null;}this._glProgram=gl.createProgram();gl.attachShader(this._glProgram,this._vertShader);gl.attachShader(this._glProgram,this._fragShader);gl.linkProgram(this._glProgram);if(!gl.getProgramParameter(this._glProgram,gl.LINK_STATUS)){console.error('Snap! Error linking shader program: '+gl.getProgramInfoLog(this._glProgram));}this._loadAttributes();this._loadUniforms();}return this;};/** * Queries the active attributes for this shader and loads * their names and locations into the attributes array. * @method _loadAttributes * @private */p5.Shader.prototype._loadAttributes=function(){if(this._loadedAttributes){return;}this.attributes={};var gl=this._renderer.GL;var numAttributes=gl.getProgramParameter(this._glProgram,gl.ACTIVE_ATTRIBUTES);for(var i=0;i<numAttributes;++i){var attributeInfo=gl.getActiveAttrib(this._glProgram,i);var name=attributeInfo.name;var location=gl.getAttribLocation(this._glProgram,name);var attribute={};attribute.name=name;attribute.location=location;attribute.type=attributeInfo.type;attribute.size=attributeInfo.size;this.attributes[name]=attribute;}this._loadedAttributes=true;};/** * Queries the active uniforms for this shader and loads * their names and locations into the uniforms array. * @method _loadUniforms * @private */p5.Shader.prototype._loadUniforms=function(){if(this._loadedUniforms){return;}var gl=this._renderer.GL;// Inspect shader and cache uniform info var numUniforms=gl.getProgramParameter(this._glProgram,gl.ACTIVE_UNIFORMS);var samplerIndex=0;for(var i=0;i<numUniforms;++i){var uniformInfo=gl.getActiveUniform(this._glProgram,i);var uniform={};uniform.location=gl.getUniformLocation(this._glProgram,uniformInfo.name);uniform.size=uniformInfo.size;var uniformName=uniformInfo.name;//uniforms thats are arrays have their name returned as //someUniform[0] which is a bit silly so we trim it //off here. The size property tells us that its an array //so we dont lose any information by doing this if(uniformInfo.size>1){uniformName=uniformName.substring(0,uniformName.indexOf('[0]'));}uniform.name=uniformName;uniform.type=uniformInfo.type;if(uniform.type===gl.SAMPLER_2D){uniform.samplerIndex=samplerIndex;samplerIndex++;this.samplers.push(uniform);}this.uniforms[uniformName]=uniform;}this._loadedUniforms=true;};p5.Shader.prototype.compile=function(){// TODO };/** * initializes (if needed) and binds the shader program. * @method bindShader * @private */p5.Shader.prototype.bindShader=function(){this.init();if(!this._bound){this.useProgram();this._bound=true;this.bindTextures();this._setMatrixUniforms();if(this===this._renderer.curStrokeShader){this._setViewportUniform();}}};/** * @method unbindShader * @chainable * @private */p5.Shader.prototype.unbindShader=function(){if(this._bound){this.unbindTextures();//this._renderer.GL.useProgram(0); ?? this._bound=false;}return this;};p5.Shader.prototype.bindTextures=function(){var gl=this._renderer.GL;for(var i=0;i<this.samplers.length;i++){var uniform=this.samplers[i];var tex=uniform.texture;if(tex===undefined){// user hasn't yet supplied a texture for this slot. // (or there may not be one--maybe just lighting), // so we supply a default texture instead. tex=this._renderer._getEmptyTexture();}gl.activeTexture(gl.TEXTURE0+uniform.samplerIndex);tex.bindTexture();tex.update();gl.uniform1i(uniform.location,uniform.samplerIndex);}};p5.Shader.prototype.updateTextures=function(){for(var i=0;i<this.samplers.length;i++){var uniform=this.samplers[i];var tex=uniform.texture;if(tex){tex.update();}}};p5.Shader.prototype.unbindTextures=function(){// TODO: migrate stuff from material.js here // - OR - have material.js define this function };p5.Shader.prototype._setMatrixUniforms=function(){this.setUniform('uProjectionMatrix',this._renderer.uPMatrix.mat4);this.setUniform('uModelViewMatrix',this._renderer.uMVMatrix.mat4);this.setUniform('uViewMatrix',this._renderer._curCamera.cameraMatrix.mat4);if(this===this._renderer.curFillShader){this._renderer.uNMatrix.inverseTranspose(this._renderer.uMVMatrix);this.setUniform('uNormalMatrix',this._renderer.uNMatrix.mat3);}};p5.Shader.prototype._setViewportUniform=function(){this.setUniform('uViewport',this._renderer._viewport);};/** * @method useProgram * @chainable * @private */p5.Shader.prototype.useProgram=function(){var gl=this._renderer.GL;gl.useProgram(this._glProgram);return this;};/** * Wrapper around gl.uniform functions. * As we store uniform info in the shader we can use that * to do type checking on the supplied data and call * the appropriate function. * @method setUniform * @chainable * @param {String} uniformName the name of the uniform in the * shader program * @param {Object|Number|Boolean|Number[]} data the data to be associated * with that uniform; type varies (could be a single numerical value, array, * matrix, or texture / sampler reference) */p5.Shader.prototype.setUniform=function(uniformName,data){//@todo update all current gl.uniformXX calls var uniform=this.uniforms[uniformName];if(!uniform){//@todo warning? return;}var location=uniform.location;var gl=this._renderer.GL;// todo: is this safe to do here? // todo: store the values another way? this.useProgram();// TODO BIND? switch(uniform.type){case gl.BOOL:if(data===true){gl.uniform1i(location,1);}else{gl.uniform1i(location,0);}break;case gl.INT:if(uniform.size>1){data.length&&gl.uniform1iv(location,data);}else{gl.uniform1i(location,data);}break;case gl.FLOAT:if(uniform.size>1){data.length&&gl.uniform1fv(location,data);}else{gl.uniform1f(location,data);}break;case gl.FLOAT_MAT3:gl.uniformMatrix3fv(location,false,data);break;case gl.FLOAT_MAT4:gl.uniformMatrix4fv(location,false,data);break;case gl.FLOAT_VEC2:if(uniform.size>1){data.length&&gl.uniform2fv(location,data);}else{gl.uniform2f(location,data[0],data[1]);}break;case gl.FLOAT_VEC3:if(uniform.size>1){data.length&&gl.uniform3fv(location,data);}else{gl.uniform3f(location,data[0],data[1],data[2]);}break;case gl.FLOAT_VEC4:if(uniform.size>1){data.length&&gl.uniform4fv(location,data);}else{gl.uniform4f(location,data[0],data[1],data[2],data[3]);}break;case gl.INT_VEC2:if(uniform.size>1){data.length&&gl.uniform2iv(location,data);}else{gl.uniform2i(location,data[0],data[1]);}break;case gl.INT_VEC3:if(uniform.size>1){data.length&&gl.uniform3iv(location,data);}else{gl.uniform3i(location,data[0],data[1],data[2]);}break;case gl.INT_VEC4:if(uniform.size>1){data.length&&gl.uniform4iv(location,data);}else{gl.uniform4i(location,data[0],data[1],data[2],data[3]);}break;case gl.SAMPLER_2D:gl.activeTexture(gl.TEXTURE0+uniform.samplerIndex);uniform.texture=this._renderer.getTexture(data);gl.uniform1i(uniform.location,uniform.samplerIndex);break;//@todo complete all types }return this;};/* NONE OF THIS IS FAST OR EFFICIENT BUT BEAR WITH ME * * these shader "type" query methods are used by various * facilities of the renderer to determine if changing * the shader type for the required action (for example, * do we need to load the default lighting shader if the * current shader cannot handle lighting?) * **/p5.Shader.prototype.isLightShader=function(){return this.uniforms.uUseLighting!==undefined||this.uniforms.uAmbientLightCount!==undefined||this.uniforms.uDirectionalLightCount!==undefined||this.uniforms.uPointLightCount!==undefined||this.uniforms.uAmbientColor!==undefined||this.uniforms.uDirectionalColor!==undefined||this.uniforms.uPointLightLocation!==undefined||this.uniforms.uPointLightColor!==undefined||this.uniforms.uLightingDirection!==undefined||this.uniforms.uSpecular!==undefined;};p5.Shader.prototype.isTextureShader=function(){return this.samplerIndex>0;};p5.Shader.prototype.isColorShader=function(){return this.attributes.aVertexColor!==undefined||this.uniforms.uMaterialColor!==undefined;};p5.Shader.prototype.isTexLightShader=function(){return this.isLightShader()&&this.isTextureShader();};p5.Shader.prototype.isStrokeShader=function(){return this.uniforms.uStrokeWeight!==undefined;};/** * @method enableAttrib * @chainable * @private */p5.Shader.prototype.enableAttrib=function(loc,size,type,normalized,stride,offset){var gl=this._renderer.GL;if(loc!==-1){gl.enableVertexAttribArray(loc);gl.vertexAttribPointer(loc,size,type,normalized,stride,offset);}return this;};module.exports=p5.Shader;},{"../core/main":25}],77:[function(_dereq_,module,exports){/** * This module defines the p5.Texture class * @module Lights, Camera * @submodule Material * @for p5 * @requires core */'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');/** * Texture class for WEBGL Mode * @private * @class p5.Texture * @param {p5.RendererGL} renderer an instance of p5.RendererGL that * will provide the GL context for this new p5.Texture * @param {p5.Image|p5.Graphics|p5.Element|p5.MediaElement|ImageData} [obj] the * object containing the image data to store in the texture. */p5.Texture=function(renderer,obj){this._renderer=renderer;var gl=this._renderer.GL;this.src=obj;this.glTex=undefined;this.glTarget=gl.TEXTURE_2D;this.glFormat=gl.RGBA;this.mipmaps=false;this.glMinFilter=gl.LINEAR;this.glMagFilter=gl.LINEAR;this.glWrapS=gl.CLAMP_TO_EDGE;this.glWrapT=gl.CLAMP_TO_EDGE;// used to determine if this texture might need constant updating // because it is a video or gif. this.isSrcMediaElement=typeof p5.MediaElement!=='undefined'&&obj instanceof p5.MediaElement;this._videoPrevUpdateTime=0;this.isSrcHTMLElement=typeof p5.Element!=='undefined'&&obj instanceof p5.Element&&!(obj instanceof p5.Graphics);this.isSrcP5Image=obj instanceof p5.Image;this.isSrcP5Graphics=obj instanceof p5.Graphics;this.isImageData=typeof ImageData!=='undefined'&&obj instanceof ImageData;var textureData=this._getTextureDataFromSource();this.width=textureData.width;this.height=textureData.height;this.init(textureData);return this;};p5.Texture.prototype._getTextureDataFromSource=function(){var textureData;if(this.isSrcP5Image){// param is a p5.Image textureData=this.src.canvas;}else if(this.isSrcMediaElement||this.isSrcP5Graphics||this.isSrcHTMLElement){// if param is a video HTML element textureData=this.src.elt;}else if(this.isImageData){textureData=this.src;}return textureData;};/** * Initializes common texture parameters, creates a gl texture, * tries to upload the texture for the first time if data is * already available. * @private * @method init */p5.Texture.prototype.init=function(data){var gl=this._renderer.GL;this.glTex=gl.createTexture();this.bindTexture();//gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,this.glMagFilter);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,this.glMinFilter);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,this.glWrapS);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,this.glWrapT);if(this.width===0||this.height===0||this.isSrcMediaElement&&!this.src.loadedmetadata){// assign a 1x1 empty texture initially, because data is not yet ready, // so that no errors occur in gl console! var tmpdata=new Uint8Array([1,1,1,1]);gl.texImage2D(this.glTarget,0,gl.RGBA,1,1,0,this.glFormat,gl.UNSIGNED_BYTE,tmpdata);}else{// data is ready: just push the texture! gl.texImage2D(this.glTarget,0,this.glFormat,this.glFormat,gl.UNSIGNED_BYTE,data);}};/** * Checks if the source data for this texture has changed (if it's * easy to do so) and reuploads the texture if necessary. If it's not * possible or to expensive to do a calculation to determine wheter or * not the data has occurred, this method simply re-uploads the texture. * @method update */p5.Texture.prototype.update=function(){var data=this.src;if(data.width===0||data.height===0){return false;// nothing to do! }var textureData=this._getTextureDataFromSource();var updated=false;var gl=this._renderer.GL;// pull texture from data, make sure width & height are appropriate if(textureData.width!==this.width||textureData.height!==this.height){updated=true;// make sure that if the width and height of this.src have changed // for some reason, we update our metadata and upload the texture again this.width=textureData.width;this.height=textureData.height;if(this.isSrcP5Image){data.setModified(false);}else if(this.isSrcMediaElement||this.isSrcHTMLElement){// on the first frame the metadata comes in, the size will be changed // from 0 to actual size, but pixels may not be available. // flag for update in a future frame. // if we don't do this, a paused video, for example, may not // send the first frame to texture memory. data.setModified(true);}}else if(this.isSrcP5Image){// for an image, we only update if the modified field has been set, // for example, by a call to p5.Image.set if(data.isModified()){updated=true;data.setModified(false);}}else if(this.isSrcMediaElement){// for a media element (video), we'll check if the current time in // the video frame matches the last time. if it doesn't match, the // video has advanced or otherwise been taken to a new frame, // and we need to upload it. if(data.isModified()){// p5.MediaElement may have also had set/updatePixels, etc. called // on it and should be updated, or may have been set for the first // time! updated=true;data.setModified(false);}else if(data.loadedmetadata){// if the meta data has been loaded, we can ask the video // what it's current position (in time) is. if(this._videoPrevUpdateTime!==data.time()){// update the texture in gpu mem only if the current // video timestamp does not match the timestamp of the last // time we uploaded this texture (and update the time we // last uploaded, too) this._videoPrevUpdateTime=data.time();updated=true;}}}else if(this.isImageData){if(data._dirty){data._dirty=false;updated=true;}}else{/* data instanceof p5.Graphics, probably */// there is not enough information to tell if the texture can be // conditionally updated; so to be safe, we just go ahead and upload it. updated=true;}if(updated){this.bindTexture();gl.texImage2D(this.glTarget,0,this.glFormat,this.glFormat,gl.UNSIGNED_BYTE,textureData);}return updated;};/** * Binds the texture to the appropriate GL target. * @method bindTexture */p5.Texture.prototype.bindTexture=function(){// bind texture using gl context + glTarget and // generated gl texture object var gl=this._renderer.GL;gl.bindTexture(this.glTarget,this.glTex);return this;};/** * Unbinds the texture from the appropriate GL target. * @method unbindTexture */p5.Texture.prototype.unbindTexture=function(){// unbind per above, disable texturing on glTarget var gl=this._renderer.GL;gl.bindTexture(this.glTarget,null);};/** * Sets how a texture is be interpolated when upscaled or downscaled. * Nearest filtering uses nearest neighbor scaling when interpolating * Linear filtering uses WebGL's linear scaling when interpolating * @method setInterpolation * @param {String} downScale Specifies the texture filtering when * textures are shrunk. Options are LINEAR or NEAREST * @param {String} upScale Specifies the texture filtering when * textures are magnified. Options are LINEAR or NEAREST * @todo implement mipmapping filters */p5.Texture.prototype.setInterpolation=function(downScale,upScale){var gl=this._renderer.GL;if(downScale===constants.NEAREST){this.glMinFilter=gl.NEAREST;}else{this.glMinFilter=gl.LINEAR;}if(upScale===constants.NEAREST){this.glMagFilter=gl.NEAREST;}else{this.glMagFilter=gl.LINEAR;}this.bindTexture();gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,this.glMinFilter);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,this.glMagFilter);this.unbindTexture();};/** * Sets the texture wrapping mode. This controls how textures behave * when their uv's go outside of the 0 - 1 range. There are three options: * CLAMP, REPEAT, and MIRROR. REPEAT & MIRROR are only available if the texture * is a power of two size (128, 256, 512, 1024, etc.). * @method setWrapMode * @param {String} wrapX Controls the horizontal texture wrapping behavior * @param {String} wrapY Controls the vertical texture wrapping behavior */p5.Texture.prototype.setWrapMode=function(wrapX,wrapY){var gl=this._renderer.GL;// for webgl 1 we need to check if the texture is power of two // if it isn't we will set the wrap mode to CLAMP // webgl2 will support npot REPEAT and MIRROR but we don't check for it yet var isPowerOfTwo=function isPowerOfTwo(x){return(x&x-1)===0;};var widthPowerOfTwo=isPowerOfTwo(this.width);var heightPowerOfTwo=isPowerOfTwo(this.width);if(wrapX===constants.REPEAT){if(widthPowerOfTwo&&heightPowerOfTwo){this.glWrapS=gl.REPEAT;}else{console.warn('You tried to set the wrap mode to REPEAT but the texture size is not a power of two. Setting to CLAMP instead');this.glWrapS=gl.CLAMP_TO_EDGE;}}else if(wrapX===constants.MIRROR){if(widthPowerOfTwo&&heightPowerOfTwo){this.glWrapS=gl.MIRRORED_REPEAT;}else{console.warn('You tried to set the wrap mode to MIRROR but the texture size is not a power of two. Setting to CLAMP instead');this.glWrapS=gl.CLAMP_TO_EDGE;}}else{// falling back to default if didn't get a proper mode this.glWrapS=gl.CLAMP_TO_EDGE;}if(wrapY===constants.REPEAT){if(widthPowerOfTwo&&heightPowerOfTwo){this.glWrapT=gl.REPEAT;}else{console.warn('You tried to set the wrap mode to REPEAT but the texture size is not a power of two. Setting to CLAMP instead');this.glWrapT=gl.CLAMP_TO_EDGE;}}else if(wrapY===constants.MIRROR){if(widthPowerOfTwo&&heightPowerOfTwo){this.glWrapT=gl.MIRRORED_REPEAT;}else{console.warn('You tried to set the wrap mode to MIRROR but the texture size is not a power of two. Setting to CLAMP instead');this.glWrapT=gl.CLAMP_TO_EDGE;}}else{// falling back to default if didn't get a proper mode this.glWrapT=gl.CLAMP_TO_EDGE;}this.bindTexture();gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,this.glWrapS);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,this.glWrapT);this.unbindTexture();};module.exports=p5.Texture;},{"../core/constants":19,"../core/main":25}],78:[function(_dereq_,module,exports){'use strict';var p5=_dereq_('../core/main');var constants=_dereq_('../core/constants');_dereq_('./p5.Shader');_dereq_('./p5.RendererGL');// Text/Typography // @TODO: p5.RendererGL.prototype._applyTextProperties=function(){//@TODO finish implementation //console.error('text commands not yet implemented in webgl'); };p5.RendererGL.prototype.textWidth=function(s){if(this._isOpenType()){return this._textFont._textWidth(s,this._textSize);}return 0;// TODO: error };// rendering constants // the number of rows/columns dividing each glyph var charGridWidth=9;var charGridHeight=charGridWidth;// size of the image holding the bezier stroke info var strokeImageWidth=64;var strokeImageHeight=64;// size of the image holding the stroke indices for each row/col var gridImageWidth=64;var gridImageHeight=64;// size of the image holding the offset/length of each row/col stripe var cellImageWidth=64;var cellImageHeight=64;/** * @private * @class ImageInfos * @param {Integer} width * @param {Integer} height * * the ImageInfos class holds a list of ImageDatas of a given size. */function ImageInfos(width,height){this.width=width;this.height=height;this.infos=[];// the list of images /** * * @method findImage * @param {Integer} space * @return {Object} contains the ImageData, and pixel index into that * ImageData where the free space was allocated. * * finds free space of a given size in the ImageData list */this.findImage=function(space){var imageSize=this.width*this.height;if(space>imageSize)throw new Error('font is too complex to render in 3D');// search through the list of images, looking for one with // anough unused space. var imageInfo,imageData;for(var ii=this.infos.length-1;ii>=0;--ii){var imageInfoTest=this.infos[ii];if(imageInfoTest.index+space<imageSize){// found one imageInfo=imageInfoTest;imageData=imageInfoTest.imageData;break;}}if(!imageInfo){try{// create a new image imageData=new ImageData(this.width,this.height);}catch(err){// for browsers that don't support ImageData constructors (ie IE11) // create an ImageData using the old method var canvas=document.getElementsByTagName('canvas')[0];var created=!canvas;if(!canvas){// create a temporary canvas canvas=document.createElement('canvas');canvas.style.display='none';document.body.appendChild(canvas);}var ctx=canvas.getContext('2d');if(ctx){imageData=ctx.createImageData(this.width,this.height);}if(created){// distroy the temporary canvas, if necessary document.body.removeChild(canvas);}}// construct & dd the new image info imageInfo={index:0,imageData:imageData};this.infos.push(imageInfo);}var index=imageInfo.index;imageInfo.index+=space;// move to the start of the next image imageData._dirty=true;return{imageData:imageData,index:index};};}/** * @function setPixel * @param {Object} imageInfo * @param {Number} r * @param {Number} g * @param {Number} b * @param {Number} a * * writes the next pixel into an indexed ImageData */function setPixel(imageInfo,r,g,b,a){var imageData=imageInfo.imageData;var pixels=imageData.data;var index=imageInfo.index++*4;pixels[index++]=r;pixels[index++]=g;pixels[index++]=b;pixels[index++]=a;}var SQRT3=Math.sqrt(3);/** * @private * @class FontInfo * @param {Object} font an opentype.js font object * * contains cached images and glyph information for an opentype font */var FontInfo=function FontInfo(font){this.font=font;// the bezier curve coordinates this.strokeImageInfos=new ImageInfos(strokeImageWidth,strokeImageHeight);// lists of curve indices for each row/column slice this.colDimImageInfos=new ImageInfos(gridImageWidth,gridImageHeight);this.rowDimImageInfos=new ImageInfos(gridImageWidth,gridImageHeight);// the offset & length of each row/col slice in the glyph this.colCellImageInfos=new ImageInfos(cellImageWidth,cellImageHeight);this.rowCellImageInfos=new ImageInfos(cellImageWidth,cellImageHeight);// the cached information for each glyph this.glyphInfos={};/** * @method getGlyphInfo * @param {Glyph} glyph the x positions of points in the curve * @returns {Object} the glyphInfo for that glyph * * calculates rendering info for a glyph, including the curve information, * row & column stripes compiled into textures. */this.getGlyphInfo=function(glyph){// check the cache var gi=this.glyphInfos[glyph.index];if(gi)return gi;// get the bounding box of the glyph from opentype.js var bb=glyph.getBoundingBox();var xMin=bb.x1;var yMin=bb.y1;var gWidth=bb.x2-xMin;var gHeight=bb.y2-yMin;var cmds=glyph.path.commands;// don't bother rendering invisible glyphs if(gWidth===0||gHeight===0||!cmds.length){return this.glyphInfos[glyph.index]={};}var i;var strokes=[];// the strokes in this glyph var rows=[];// the indices of strokes in each row var cols=[];// the indices of strokes in each column for(i=charGridWidth-1;i>=0;--i){cols.push([]);}for(i=charGridHeight-1;i>=0;--i){rows.push([]);}/** * @function push * @param {Number[]} xs the x positions of points in the curve * @param {Number[]} ys the y positions of points in the curve * @param {Object} v the curve information * * adds a curve to the rows & columns that it intersects with */function push(xs,ys,v){var index=strokes.length;// the index of this stroke strokes.push(v);// add this stroke to the list /** * @function minMax * @param {Number[]} rg the list of values to compare * @param {Number} min the initial minimum value * @param {Number} max the initial maximum value * * find the minimum & maximum value in a list of values */function minMax(rg,min,max){for(var i=rg.length;i-->0;){var v=rg[i];if(min>v)min=v;if(max<v)max=v;}return{min:min,max:max};}// loop through the rows & columns that the curve intersects // adding the curve to those slices var mmX=minMax(xs,1,0);var ixMin=Math.max(Math.floor(mmX.min*charGridWidth),0);var ixMax=Math.min(Math.ceil(mmX.max*charGridWidth),charGridWidth);for(var iCol=ixMin;iCol<ixMax;++iCol){cols[iCol].push(index);}var mmY=minMax(ys,1,0);var iyMin=Math.max(Math.floor(mmY.min*charGridHeight),0);var iyMax=Math.min(Math.ceil(mmY.max*charGridHeight),charGridHeight);for(var iRow=iyMin;iRow<iyMax;++iRow){rows[iRow].push(index);}}/** * @function clamp * @param {Number} v the value to clamp * @param {Number} min the minimum value * @param {Number} max the maxmimum value * * clamps a value between a minimum & maximum value */function clamp(v,min,max){if(v<min)return min;if(v>max)return max;return v;}/** * @function byte * @param {Number} v the value to scale * * converts a floating-point number in the range 0-1 to a byte 0-255 */function byte(v){return clamp(255*v,0,255);}/** * @private * @class Cubic * @param {Number} p0 the start point of the curve * @param {Number} c0 the first control point * @param {Number} c1 the second control point * @param {Number} p1 the end point * * a cubic curve */function Cubic(p0,c0,c1,p1){this.p0=p0;this.c0=c0;this.c1=c1;this.p1=p1;/** * @method toQuadratic * @return {Object} the quadratic approximation * * converts the cubic to a quadtratic approximation by * picking an appropriate quadratic control point */this.toQuadratic=function(){return{x:this.p0.x,y:this.p0.y,x1:this.p1.x,y1:this.p1.y,cx:((this.c0.x+this.c1.x)*3-(this.p0.x+this.p1.x))/4,cy:((this.c0.y+this.c1.y)*3-(this.p0.y+this.p1.y))/4};};/** * @method quadError * @return {Number} the error * * calculates the magnitude of error of this curve's * quadratic approximation. */this.quadError=function(){return p5.Vector.sub(p5.Vector.sub(this.p1,this.p0),p5.Vector.mult(p5.Vector.sub(this.c1,this.c0),3)).mag()/2;};/** * @method split * @param {Number} t the value (0-1) at which to split * @return {Cubic} the second part of the curve * * splits the cubic into two parts at a point 't' along the curve. * this cubic keeps its start point and its end point becomes the * point at 't'. the 'end half is returned. */this.split=function(t){var m1=p5.Vector.lerp(this.p0,this.c0,t);var m2=p5.Vector.lerp(this.c0,this.c1,t);var mm1=p5.Vector.lerp(m1,m2,t);this.c1=p5.Vector.lerp(this.c1,this.p1,t);this.c0=p5.Vector.lerp(m2,this.c1,t);var pt=p5.Vector.lerp(mm1,this.c0,t);var part1=new Cubic(this.p0,m1,mm1,pt);this.p0=pt;return part1;};/** * @method splitInflections * @return {Cubic[]} the non-inflecting pieces of this cubic * * returns an array containing 0, 1 or 2 cubics split resulting * from splitting this cubic at its inflection points. * this cubic is (potentially) altered and returned in the list. */this.splitInflections=function(){var a=p5.Vector.sub(this.c0,this.p0);var b=p5.Vector.sub(p5.Vector.sub(this.c1,this.c0),a);var c=p5.Vector.sub(p5.Vector.sub(p5.Vector.sub(this.p1,this.c1),a),p5.Vector.mult(b,2));var cubics=[];// find the derivative coefficients var A=b.x*c.y-b.y*c.x;if(A!==0){var B=a.x*c.y-a.y*c.x;var C=a.x*b.y-a.y*b.x;var disc=B*B-4*A*C;if(disc>=0){if(A<0){A=-A;B=-B;C=-C;}var Q=Math.sqrt(disc);var t0=(-B-Q)/(2*A);// the first inflection point var t1=(-B+Q)/(2*A);// the second inflection point // test if the first inflection point lies on the curve if(t0>0&&t0<1){// split at the first inflection point cubics.push(this.split(t0));// scale t2 into the second part t1=1-(1-t1)/(1-t0);}// test if the second inflection point lies on the curve if(t1>0&&t1<1){// split at the second inflection point cubics.push(this.split(t1));}}}cubics.push(this);return cubics;};}/** * @function cubicToQuadratics * @param {Number} x0 * @param {Number} y0 * @param {Number} cx0 * @param {Number} cy0 * @param {Number} cx1 * @param {Number} cy1 * @param {Number} x1 * @param {Number} y1 * @returns {Cubic[]} an array of cubics whose quadratic approximations * closely match the civen cubic. * * converts a cubic curve to a list of quadratics. */function cubicToQuadratics(x0,y0,cx0,cy0,cx1,cy1,x1,y1){// create the Cubic object and split it at its inflections var cubics=new Cubic(new p5.Vector(x0,y0),new p5.Vector(cx0,cy0),new p5.Vector(cx1,cy1),new p5.Vector(x1,y1)).splitInflections();var qs=[];// the final list of quadratics var precision=30/SQRT3;// for each of the non-inflected pieces of the original cubic for(var i=0;i<cubics.length;i++){var cubic=cubics[i];// the cubic is iteratively split in 3 pieces: // the first piece is accumulated in 'qs', the result. // the last piece is accumulated in 'tail', temporarily. // the middle piece is repeatedly split again, while necessary. var tail=[];var t3;for(;;){// calculate this cubic's precision t3=precision/cubic.quadError();if(t3>=0.5*0.5*0.5){break;// not too bad, we're done }// find a split point based on the error var t=Math.pow(t3,1.0/3.0);// split the cubic in 3 var start=cubic.split(t);var middle=cubic.split(1-t/(1-t));qs.push(start);// the first part tail.push(cubic);// the last part cubic=middle;// iterate on the middle piece }if(t3<1){// a little excess error, split the middle in two qs.push(cubic.split(0.5));}// add the middle piece to the result qs.push(cubic);// finally add the tail, reversed, onto the result Array.prototype.push.apply(qs,tail.reverse());}return qs;}/** * @function pushLine * @param {Number} x0 * @param {Number} y0 * @param {Number} x1 * @param {Number} y1 * * add a straight line to the row/col grid of a glyph */function pushLine(x0,y0,x1,y1){var mx=(x0+x1)/2;var my=(y0+y1)/2;push([x0,x1],[y0,y1],{x:x0,y:y0,cx:mx,cy:my});}/** * @function samePoint * @param {Number} x0 * @param {Number} y0 * @param {Number} x1 * @param {Number} y1 * @return {Boolean} true if the two points are sufficiently close * * tests if two points are close enough to be considered the same */function samePoint(x0,y0,x1,y1){return Math.abs(x1-x0)<0.00001&&Math.abs(y1-y0)<0.00001;}var x0,y0,xs,ys;for(var iCmd=0;iCmd<cmds.length;++iCmd){var cmd=cmds[iCmd];// scale the coordinates to the range 0-1 var x1=(cmd.x-xMin)/gWidth;var y1=(cmd.y-yMin)/gHeight;// don't bother if this point is the same as the last if(samePoint(x0,y0,x1,y1))continue;switch(cmd.type){case'M':// move xs=x1;ys=y1;break;case'L':// line pushLine(x0,y0,x1,y1);break;case'Q':// quadratic var cx=(cmd.x1-xMin)/gWidth;var cy=(cmd.y1-yMin)/gHeight;push([x0,x1,cx],[y0,y1,cy],{x:x0,y:y0,cx:cx,cy:cy});break;case'Z':// end if(!samePoint(x0,y0,xs,ys)){// add an extra line closing the loop, if necessary pushLine(x0,y0,xs,ys);strokes.push({x:xs,y:ys});}else{strokes.push({x:x0,y:y0});}break;case'C':// cubic var cx1=(cmd.x1-xMin)/gWidth;var cy1=(cmd.y1-yMin)/gHeight;var cx2=(cmd.x2-xMin)/gWidth;var cy2=(cmd.y2-yMin)/gHeight;var qs=cubicToQuadratics(x0,y0,cx1,cy1,cx2,cy2,x1,y1);for(var iq=0;iq<qs.length;iq++){var q=qs[iq].toQuadratic();push([q.x,q.x1,q.cx],[q.y,q.y1,q.cy],q);}break;default:throw new Error('unknown command type: '+cmd.type);}x0=x1;y0=y1;}// allocate space for the strokes var strokeCount=strokes.length;var strokeImageInfo=this.strokeImageInfos.findImage(strokeCount);var strokeOffset=strokeImageInfo.index;// fill the stroke image for(var il=0;il<strokeCount;++il){var s=strokes[il];setPixel(strokeImageInfo,byte(s.x),byte(s.y),byte(s.cx),byte(s.cy));}/** * @function layout * @param {Number[][]} dim * @param {ImageInfo[]} dimImageInfos * @param {ImageInfo[]} cellImageInfos * @return {Object} * * lays out the curves in a dimension (row or col) into two * images, one for the indices of the curves themselves, and * one containing the offset and length of those index spans. */function layout(dim,dimImageInfos,cellImageInfos){var dimLength=dim.length;// the number of slices in this dimension var dimImageInfo=dimImageInfos.findImage(dimLength);var dimOffset=dimImageInfo.index;// calculate the total number of stroke indices in this dimension var totalStrokes=0;for(var id=0;id<dimLength;++id){totalStrokes+=dim[id].length;}// allocate space for the stroke indices var cellImageInfo=cellImageInfos.findImage(totalStrokes);// for each slice in the glyph for(var i=0;i<dimLength;++i){var strokeIndices=dim[i];var strokeCount=strokeIndices.length;var cellLineIndex=cellImageInfo.index;// write the offset and count into the glyph slice image setPixel(dimImageInfo,cellLineIndex>>7,cellLineIndex&0x7f,strokeCount>>7,strokeCount&0x7f);// for each stroke index in that slice for(var iil=0;iil<strokeCount;++iil){// write the stroke index into the slice's image var strokeIndex=strokeIndices[iil]+strokeOffset;setPixel(cellImageInfo,strokeIndex>>7,strokeIndex&0x7f,0,0);}}return{cellImageInfo:cellImageInfo,dimOffset:dimOffset,dimImageInfo:dimImageInfo};}// initialize the info for this glyph gi=this.glyphInfos[glyph.index]={glyph:glyph,uGlyphRect:[bb.x1,-bb.y1,bb.x2,-bb.y2],strokeImageInfo:strokeImageInfo,strokes:strokes,colInfo:layout(cols,this.colDimImageInfos,this.colCellImageInfos),rowInfo:layout(rows,this.rowDimImageInfos,this.rowCellImageInfos)};gi.uGridOffset=[gi.colInfo.dimOffset,gi.rowInfo.dimOffset];return gi;};};p5.RendererGL.prototype._renderText=function(p,line,x,y,maxY){if(y>=maxY||!this._doFill){return;// don't render lines beyond our maxY position }if(!this._isOpenType()){console.log('WEBGL: only opentype fonts are supported');return p;}p.push();// fix to #803 // remember this state, so it can be restored later var curFillShader=this.curFillShader;var doStroke=this._doStroke;var drawMode=this.drawMode;this.curFillShader=null;this._doStroke=false;this.drawMode=constants.TEXTURE;// get the cached FontInfo object var font=this._textFont.font;var fontInfo=this._textFont._fontInfo;if(!fontInfo){fontInfo=this._textFont._fontInfo=new FontInfo(font);}// calculate the alignment and move/scale the view accordingly var pos=this._textFont._handleAlignment(this,line,x,y);var fontSize=this._textSize;var scale=fontSize/font.unitsPerEm;this.translate(pos.x,pos.y,0);this.scale(scale,scale,1);// initialize the font shader var gl=this.GL;var initializeShader=!this._defaultFontShader;var sh=this.setFillShader(this._getFontShader());if(initializeShader){// these are constants, really. just initialize them one-time. sh.setUniform('uGridImageSize',[gridImageWidth,gridImageHeight]);sh.setUniform('uCellsImageSize',[cellImageWidth,cellImageHeight]);sh.setUniform('uStrokeImageSize',[strokeImageWidth,strokeImageHeight]);sh.setUniform('uGridSize',[charGridWidth,charGridHeight]);}this._applyColorBlend(this.curFillColor);var g=this.gHash['glyph'];if(!g){// create the geometry for rendering a quad var geom=this._textGeom=new p5.Geometry(1,1,function(){for(var i=0;i<=1;i++){for(var j=0;j<=1;j++){this.vertices.push(new p5.Vector(j,i,0));this.uvs.push(j,i);}}});geom.computeFaces().computeNormals();g=this.createBuffers('glyph',geom);}// bind the shader buffers this._bindBuffer(g.vertexBuffer,gl.ARRAY_BUFFER);sh.enableAttrib(sh.attributes.aPosition.location,3,gl.FLOAT,false,0,0);this._bindBuffer(g.indexBuffer,gl.ELEMENT_ARRAY_BUFFER);this._bindBuffer(g.uvBuffer,gl.ARRAY_BUFFER);sh.enableAttrib(sh.attributes.aTexCoord.location,2,gl.FLOAT,false,0,0);// this will have to do for now... sh.setUniform('uMaterialColor',this.curFillColor);try{var dx=0;// the x position in the line var glyphPrev=null;// the previous glyph, used for kerning var shaderBound=false;// fetch the glyphs in the line of text var glyphs=font.stringToGlyphs(line);for(var ig=0;ig<glyphs.length;++ig){var glyph=glyphs[ig];// kern if(glyphPrev)dx+=font.getKerningValue(glyphPrev,glyph);var gi=fontInfo.getGlyphInfo(glyph);if(gi.uGlyphRect){var rowInfo=gi.rowInfo;var colInfo=gi.colInfo;sh.setUniform('uSamplerStrokes',gi.strokeImageInfo.imageData);sh.setUniform('uSamplerRowStrokes',rowInfo.cellImageInfo.imageData);sh.setUniform('uSamplerRows',rowInfo.dimImageInfo.imageData);sh.setUniform('uSamplerColStrokes',colInfo.cellImageInfo.imageData);sh.setUniform('uSamplerCols',colInfo.dimImageInfo.imageData);sh.setUniform('uGridOffset',gi.uGridOffset);sh.setUniform('uGlyphRect',gi.uGlyphRect);sh.setUniform('uGlyphOffset',dx);if(!shaderBound){shaderBound=true;sh.bindShader();// first time around, bind the shader fully }else{sh.bindTextures();// afterwards, only textures need updating }// draw it gl.drawElements(gl.TRIANGLES,6,this.GL.UNSIGNED_SHORT,0);}dx+=glyph.advanceWidth;glyphPrev=glyph;}}finally{// clean up sh.unbindShader();this.curFillShader=curFillShader;this._doStroke=doStroke;this.drawMode=drawMode;p.pop();}this._pInst._pixelsDirty=true;return p;};},{"../core/constants":19,"../core/main":25,"./p5.RendererGL":75,"./p5.Shader":76}]},{},[14])(14);}); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2))) /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var g; // This works in non-strict mode g = function () { return this; }(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1, eval)("this"); } catch (e) { // This works if the window reference is available if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 3 */, /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj;}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};!function(e,t){"object"==( false?"undefined":_typeof(exports))&&"object"==( false?"undefined":_typeof(module))?module.exports=t(): true?!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (t), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)):"object"==(typeof exports==="undefined"?"undefined":_typeof(exports))?exports.ml5=t():e.ml5=t();}(window,function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports;}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r});},n.r=function(e){Object.defineProperty(e,"__esModule",{value:!0});},n.n=function(e){var t=e&&e.__esModule?function(){return e.default;}:function(){return e;};return n.d(t,"a",t),t;},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t);},n.p="/",n(n.s=555);}([function(e,t,n){"use strict";n.r(t),n.d(t,"assertArgumentsAreTensors",function(){return i;}),n.d(t,"shuffle",function(){return o;}),n.d(t,"clamp",function(){return s;}),n.d(t,"randUniform",function(){return u;}),n.d(t,"distSquared",function(){return c;}),n.d(t,"assert",function(){return l;}),n.d(t,"assertShapesMatch",function(){return f;}),n.d(t,"assertTypesMatch",function(){return p;}),n.d(t,"flatten",function(){return h;}),n.d(t,"inferShape",function(){return d;}),n.d(t,"sizeFromShape",function(){return m;}),n.d(t,"isScalarShape",function(){return g;}),n.d(t,"arraysEqual",function(){return y;}),n.d(t,"isInt",function(){return v;}),n.d(t,"tanh",function(){return b;}),n.d(t,"sizeToSquarishShape",function(){return w;}),n.d(t,"createShuffledIndices",function(){return x;}),n.d(t,"rightPad",function(){return k;}),n.d(t,"repeatedTry",function(){return O;}),n.d(t,"getQueryParams",function(){return S;}),n.d(t,"inferFromImplicitShape",function(){return N;}),n.d(t,"squeezeShape",function(){return E;}),n.d(t,"getTypedArrayFromDType",function(){return I;}),n.d(t,"isTensorInList",function(){return T;}),n.d(t,"checkForNaN",function(){return A;}),n.d(t,"flattenNameArrayMap",function(){return C;}),n.d(t,"unflattenToNameArrayMap",function(){return P;}),n.d(t,"hasEncodingLoss",function(){return _;}),n.d(t,"copyTypedArray",function(){return R;}),n.d(t,"isTypedArray",function(){return M;}),n.d(t,"bytesPerElement",function(){return j;}),n.d(t,"isFunction",function(){return D;}),n.d(t,"extractTensorsFromContainer",function(){return L;}),n.d(t,"extractTensorsFromAny",function(){return z;});var r=n(6);function a(e,t,n){l(e instanceof r.a,"Argument '"+t+"' passed to '"+n+"' must be a Tensor, but got "+(typeof e==="undefined"?"undefined":_typeof(e))+".");}function i(e,t){var n=function n(_n2){var r=e[_n2];Array.isArray(r)?r.forEach(function(e,r){a(e,_n2+"["+r+"]",t);}):a(r,_n2,t);};for(var r in e){n(r);}}function o(e){for(var t=e.length,n=0,r=0;t>0;){r=Math.random()*t|0,n=e[--t],e[t]=e[r],e[r]=n;}}function s(e,t,n){return Math.max(e,Math.min(t,n));}function u(e,t){return Math.random()*(t-e)+e;}function c(e,t){for(var n=0,r=0;r<e.length;r++){var a=Number(e[r])-Number(t[r]);n+=a*a;}return n;}function l(e,t){if(!e)throw new Error(t);}function f(e,t,n){void 0===n&&(n=""),l(y(e,t),n+" Shapes "+e+" and "+t+" must match");}function p(e,t){l(e.dtype===t.dtype," The dtypes of the first("+e.dtype+") and second("+t.dtype+") input must match");}function h(e,t){if(void 0===t&&(t=[]),Array.isArray(e))for(var n=0;n<e.length;++n){h(e[n],t);}else t.push(e);return t;}function d(e){if(M(e))return[e.length];if(!Array.isArray(e))return[];for(var t=[];e instanceof Array;){t.push(e.length),e=e[0];}return t;}function m(e){if(0===e.length)return 1;for(var t=e[0],n=1;n<e.length;n++){t*=e[n];}return t;}function g(e){return 0===e.length;}function y(e,t){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++){if(e[n]!==t[n])return!1;}return!0;}function v(e){return e%1==0;}function b(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;var t=Math.exp(2*e);return(t-1)/(t+1);}function w(e){for(var t=Math.floor(Math.sqrt(e));t>1;--t){if(e%t==0)return[t,e/t];}return[1,e];}function x(e){for(var t=new Uint32Array(e),n=0;n<e;++n){t[n]=n;}return o(t),t;}function k(e,t){return t<=e.length?e:e+" ".repeat(t-e.length);}function O(e,t,n){return void 0===t&&(t=function t(e){return 0;}),new Promise(function(r,a){var i=0,o=function o(){if(e())r();else{var s=t(++i);null!=n&&i>=n?a():setTimeout(o,s);}};setTimeout(o,0);});}function S(e){var t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(e){for(var n=[],r=1;r<arguments.length;r++){n[r-1]=arguments[r];}return function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"");}(t,n[0],n[1]),n.join("=");}),t;}function N(e,t){for(var n=1,r=-1,a=0;a<e.length;++a){if(e[a]>0)n*=e[a];else if(-1===e[a]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found - 1 at dim "+r+" and dim "+a);r=a;}else if(e[a]<=0)throw Error("Shapes can not be <= 0. Found "+e[a]+" at dim "+a);}if(-1===r){if(t>0&&t!==n)throw Error("Size("+t+") must match the product of shape "+e);return e;}if(t%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+n);var i=e.slice();return i[r]=t/n,i;}function E(e,t){for(var n=[],r=[],a=0,i=0;i<e.length;++i){if(null!=t){if(t[a]===i&&e[i]>1)throw new Error("Can't squeeze axis "+i+" since its dim '"+e[i]+"' is not 1");(null==t[a]||t[a]>i)&&1===e[i]&&(n.push(e[i]),r.push(i)),t[a]<=i&&a++;}e[i]>1&&(n.push(e[i]),r.push(i));}return{newShape:n,keptDims:r};}function I(e,t){var n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error("Unknown data type "+e);n=new Uint8Array(t);}return n;}function T(e,t){for(var n=0;n<t.length;n++){if(t[n].id===e.id)return!0;}return!1;}function A(e,t,n){if("float32"===t)for(var r=0;r<e.length;r++){if(isNaN(e[r]))throw Error("The result of the '"+n+"' has NaNs.");}}function C(e,t){var n=[];if(e instanceof r.a)n.push(e);else for(var a=e,i=0;i<t.length;i++){n.push(a[t[i]]);}return n;}function P(e,t){if(e.length!==t.length)throw new Error("Cannot unflatten Tensor[], keys and arrays are not of same length.");for(var n={},r=0;r<e.length;r++){n[e[r]]=t[r];}return n;}function _(e,t){return!("float32"===t||"int32"===t&&"float32"!==e||"bool"===t&&"bool"===e);}function R(e,t){if(null==t||"float32"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){for(var n=new Uint8Array(e.length),r=0;r<n.length;++r){0!==Math.round(e[r])&&(n[r]=1);}return n;}throw new Error("Unknown data type "+t);}function M(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array;}function j(e){if("float32"===e||"int32"===e)return 4;if("bool"===e)return 1;throw new Error("Unknown dtype "+e);}function D(e){return!!(e&&e.constructor&&e.call&&e.apply);}function L(e){return z(e);}function z(e){if(null==e)return[];if(e instanceof r.a)return[e];var t=[],n=e;if(!function(e){return Array.isArray(e)||"object"==(typeof e==="undefined"?"undefined":_typeof(e));}(n))return[];for(var a in n){var i=h(n[a]).filter(function(e){return e instanceof r.a;});t.push.apply(t,i);}return t;}},function(e,t,n){"use strict";var r=n(9),a=n(2),i=n(3),o=n(0),s=n(11),u=n(4),c=function c(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},l=function(){function e(){}return e.batchNormalization2d=function(t,n,r,a,i,s){return void 0===a&&(a=.001),o.assert(2===t.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+t.rank+"."),o.assert(2===n.rank||1===n.rank,"Error in batchNormalization2D: mean must be rank 2 or rank 1 but got rank "+n.rank+"."),o.assert(2===r.rank||1===r.rank,"Error in batchNormalization2D: variance must be rank 2 or rank 1 but got rank "+r.rank+"."),null!=i&&o.assert(2===i.rank||1===i.rank,"Error in batchNormalization2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."),null!=s&&o.assert(2===s.rank||1===s.rank,"Error in batchNormalization2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."),e.batchNormalization(t,n,r,a,i,s);},e.batchNormalization3d=function(t,n,r,a,i,s){return void 0===a&&(a=.001),o.assert(3===t.rank,"Error in batchNormalization3D: x must be rank 3 but got rank "+t.rank+"."),o.assert(3===n.rank||1===n.rank,"Error in batchNormalization3D: mean must be rank 3 or rank 1 but got rank "+n.rank+"."),o.assert(3===r.rank||1===r.rank,"Error in batchNormalization3D: variance must be rank 3 or rank 1 but got rank "+r.rank+"."),null!=i&&o.assert(3===i.rank||1===i.rank,"Error in batchNormalization3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."),null!=s&&o.assert(3===s.rank||1===s.rank,"Error in batchNormalization3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."),e.batchNormalization(t,n,r,a,i,s);},e.batchNormalization4d=function(t,n,r,a,i,s){return void 0===a&&(a=.001),o.assert(4===t.rank,"Error in batchNormalization4D: x must be rank 4 but got rank "+t.rank+"."),o.assert(4===n.rank||1===n.rank,"Error in batchNormalization4D: mean must be rank 4 or rank 1 but got rank "+n.rank+"."),o.assert(4===r.rank||1===r.rank,"Error in batchNormalization4D: variance must be rank 4 or rank 1 but got rank "+r.rank+"."),null!=i&&o.assert(4===i.rank||1===i.rank,"Error in batchNormalization4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."),null!=s&&o.assert(4===s.rank||1===s.rank,"Error in batchNormalization4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."),e.batchNormalization(t,n,r,a,i,s);},e.batchNormalization=function(e,t,n,a,u,c){var l;return void 0===a&&(a=.001),o.assertArgumentsAreTensors({x:e,mean:t,variance:n},"batchNormalization"),null!=u&&o.assertArgumentsAreTensors({scale:u},"batchNormalization"),null!=c&&o.assertArgumentsAreTensors({offset:c},"batchNormalization"),o.assert(t.rank===n.rank,"Batch normalization gradient requires mean and variance to have equal ranks."),o.assert(null==c||t.rank===c.rank,"Batch normalization gradient requires mean and offset to have equal ranks."),o.assert(null==u||t.rank===u.rank,"Batch normalization gradient requires mean and scale to have equal ranks."),l=0===e.rank||1===e.rank?e.as4D(1,1,1,e.size):2===e.rank?e.as4D(1,1,e.shape[0],e.shape[1]):3===e.rank?e.as4D(1,e.shape[0],e.shape[1],e.shape[2]):e,i.ENV.engine.runKernel(function(e){return e.batchNormalization(l,f(t),f(n),a,f(u),f(c));},{x:e,mean:t,variance:n,scale:u,offset:c},function(i){var o=null==u?r.a.scalar(1):u,c=Object(s.d)(t.shape,l.shape),f=[];if(1===t.rank){for(var p=0;p<l.shape.length-1;++p){f.push(l.shape[p]);}f.push(1);}var h=e.sub(t),d=i.mul(o),m=Ft(n.add(r.a.scalar(a))),g=m.mul(m).mul(m).mul(r.a.scalar(-.5));return{x:function x(){return 1===t.rank?i.mul(r.a.tile(m.as4D(1,1,1,t.shape[0]),f)).mul(o).reshape(e.shape):i.mul(m).mul(o).reshape(e.shape);},mean:function mean(){var e=m.mul(r.a.scalar(-1)).mul(d);return 1===t.rank&&(e=e.sum(c)),e.reshape(t.shape);},variance:function variance(){var e=g.mul(h).mul(d);return 1===t.rank&&(e=e.sum(c)),e.reshape(t.shape);},scale:function scale(){var e=h.mul(m),n=i.mul(e);return 1===t.rank&&(n=n.sum(c)),n.reshape(t.shape);},offset:function offset(){var e=i;return 1===t.rank&&(e=e.sum(c)),e.reshape(t.shape);}};}).reshape(e.shape);},c([u.a],e,"batchNormalization2d",null),c([u.a],e,"batchNormalization3d",null),c([u.a],e,"batchNormalization4d",null),c([Object(a.a)({heading:"Operations",subheading:"Normalization"})],e,"batchNormalization",null),e;}();function f(e){return null==e?null:0===e.rank?e.as1D():1===e.rank?e:2===e.rank?e.as4D(1,1,e.shape[0],e.shape[1]):3===e.rank?e.as4D(1,e.shape[0],e.shape[1],e.shape[2]):e;}var p=n(20),h=function h(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},d=function(){function e(){}return e.add=function(e,t){o.assertArgumentsAreTensors({a:e,b:t},"add"),o.assertTypesMatch(e,t);var n=s.a(e.shape,t.shape);return i.ENV.engine.runKernel(function(n){return n.add(e,t);},{a:e,b:t},function(r){return{a:function a(){var t=r,a=s.d(e.shape,n);return a.length>0&&(t=t.sum(a)),t.reshape(e.shape);},b:function b(){var e=r,a=s.d(t.shape,n);return a.length>0&&(e=e.sum(a)),e.reshape(t.shape);}};});},e.addStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in addStrict: "),e.add(t);},e.sub=function(e,t){o.assertArgumentsAreTensors({a:e,b:t},"sub"),o.assertTypesMatch(e,t);var n=s.a(e.shape,t.shape);return i.ENV.engine.runKernel(function(n){return n.subtract(e,t);},{a:e,b:t},function(r){return{a:function a(){var t=r,a=s.d(e.shape,n);return a.length>0&&(t=t.sum(a)),t.reshape(e.shape);},b:function b(){var e=r,a=s.d(t.shape,n);return a.length>0&&(e=e.sum(a)),e.neg().reshape(t.shape);}};});},e.subStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in subStrict: "),e.sub(t);},e.pow=function(e,t){o.assertArgumentsAreTensors({base:e,exp:t},"pow");var n=s.a(e.shape,t.shape);return e=e.cast(Object(p.c)(e.dtype,t.dtype)),t=t.cast(Object(p.c)(e.dtype,t.dtype)),i.ENV.engine.runKernel(function(n,r){return r(n.pow(e,t));},{base:e,exp:t},function(r,a){var i=a[0];return{base:function base(){var a=r.mul(t.toFloat().mul(i.div(e))),o=s.d(e.shape,n);return o.length>0&&(a=a.sum(o)),a.reshape(e.shape);},exp:function exp(){var a=r.mul(i.mul(e.log()).toFloat()),o=s.d(t.shape,n);return o.length>0&&(a=a.sum(o)),a.reshape(t.shape);}};});},e.powStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in powStrict: "),e.pow(t);},e.mul=function(e,t){o.assertArgumentsAreTensors({a:e,b:t},"mul"),o.assertTypesMatch(e,t);var n=s.a(e.shape,t.shape);return i.ENV.engine.runKernel(function(n){return n.multiply(e,t);},{a:e,b:t},function(r){return{a:function a(){var a=r.mul(t.toFloat()),i=s.d(e.shape,n);return i.length>0?a.sum(i).reshape(e.shape):a;},b:function b(){var a=r.mul(e.toFloat()),i=s.d(t.shape,n);return i.length>0?a.sum(i).reshape(t.shape):a;}};});},e.mulStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in multiplyStrict: "),e.mul(t);},e.div=function(e,t){o.assertArgumentsAreTensors({a:e,b:t},"div"),o.assertTypesMatch(e,t);var n=s.a(e.shape,t.shape);return i.ENV.engine.runKernel(function(n){return n.divide(e,t);},{a:e,b:t},function(r){return{a:function a(){var a=r.div(t.toFloat()),i=s.d(e.shape,n);return i.length>0?a.sum(i).reshape(e.shape):a;},b:function b(){var a=r.mul(e.toFloat()),i=s.d(t.shape,n);i.length>0&&(a=a.sum(i).reshape(t.shape));var o=t.square();return a.div(o.toFloat()).neg();}};});},e.divStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in divideStrict: "),e.div(t);},e.mod=function(e,t){o.assertArgumentsAreTensors({a:e,b:t},"mod"),o.assertTypesMatch(e,t);var n=s.a(e.shape,t.shape);return i.ENV.engine.runKernel(function(n){return n.mod(e,t);},{a:e,b:t},function(r){return{a:function a(){var t=s.d(e.shape,n);return t.length>0?r.sum(t).reshape(e.shape):r;},b:function b(){var a=r.mul(e.div(t).floor().neg()),i=s.d(t.shape,n);return i.length>0?a.sum(i).reshape(t.shape):a;}};});},e.modStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in modStrict: "),e.mod(t);},e.minimum=function(e,t){return o.assertArgumentsAreTensors({a:e,b:t},"minimum"),o.assertTypesMatch(e,t),"bool"===e.dtype&&(e=e.toInt()),"bool"===t.dtype&&(t=t.toInt()),s.a(e.shape,t.shape),i.ENV.engine.runKernel(function(n){return n.minimum(e,t);},{a:e,b:t},function(n){return{a:function a(){return n.mul(e.lessEqual(t).toFloat());},b:function b(){return n.mul(e.greater(t).toFloat());}};});},e.minimumStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in minimumStrict: "),e.minimum(t);},e.maximum=function(e,t){return o.assertArgumentsAreTensors({a:e,b:t},"maximum"),o.assertTypesMatch(e,t),"bool"===e.dtype&&(e=e.toInt()),"bool"===t.dtype&&(t=t.toInt()),s.a(e.shape,t.shape),i.ENV.engine.runKernel(function(n){return n.maximum(e,t);},{a:e,b:t},function(n){return{a:function a(){return n.mul(e.greaterEqual(t).toFloat());},b:function b(){return n.mul(e.less(t).toFloat());}};});},e.maximumStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in minimumStrict: "),e.maximum(t);},e.squaredDifference=function(e,t){return o.assertArgumentsAreTensors({a:e,b:t},"squaredDifference"),o.assertTypesMatch(e,t),s.a(e.shape,t.shape),i.ENV.engine.runKernel(function(n){return n.squaredDifference(e,t);},{a:e,b:t},function(n){var r=Dn(2);return{a:function a(){return n.mul(e.sub(t).mul(r));},b:function b(){return n.mul(t.sub(e).mul(r));}};});},e.squaredDifferenceStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(t);},e.atan2=function(t,n){o.assertArgumentsAreTensors({a:t,b:n},"atan2"),o.assertTypesMatch(t,n);var r=s.a(t.shape,n.shape);return i.ENV.engine.runKernel(function(e){return e.atan2(t,n);},{a:t,b:n},function(_a2){return{a:function a(){var i=e.add(Bt(t),Bt(n)),o=_a2.mul(n.div(i)),u=s.d(t.shape,r);return u.length>0&&(o=o.sum(u)),o.reshape(t.shape);},b:function b(){var i=e.add(Bt(t),Bt(n)),o=Tt(_a2.mul(t.div(i))),u=s.d(n.shape,r);return u.length>0&&(o=o.sum(u)),o.reshape(n.shape);}};});},h([Object(a.a)({heading:"Operations",subheading:"Arithmetic"}),u.a],e,"add",null),h([u.a],e,"addStrict",null),h([Object(a.a)({heading:"Operations",subheading:"Arithmetic"}),u.a],e,"sub",null),h([u.a],e,"subStrict",null),h([Object(a.a)({heading:"Operations",subheading:"Arithmetic"}),u.a],e,"pow",null),h([u.a],e,"powStrict",null),h([Object(a.a)({heading:"Operations",subheading:"Arithmetic"}),u.a],e,"mul",null),h([u.a],e,"mulStrict",null),h([Object(a.a)({heading:"Operations",subheading:"Arithmetic"}),u.a],e,"div",null),h([u.a],e,"divStrict",null),h([Object(a.a)({heading:"Operations",subheading:"Arithmetic"}),u.a],e,"mod",null),h([u.a],e,"modStrict",null),h([Object(a.a)({heading:"Operations",subheading:"Arithmetic"}),u.a],e,"minimum",null),h([u.a],e,"minimumStrict",null),h([Object(a.a)({heading:"Operations",subheading:"Arithmetic"}),u.a],e,"maximum",null),h([u.a],e,"maximumStrict",null),h([Object(a.a)({heading:"Operations",subheading:"Arithmetic"}),u.a],e,"squaredDifference",null),h([u.a],e,"squaredDifferenceStrict",null),h([u.a],e,"atan2",null),e;}(),m=function m(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},g=function(){function e(){}return e.notEqual=function(e,t){return o.assertArgumentsAreTensors({a:e,b:t},"notEqual"),o.assertTypesMatch(e,t),s.a(e.shape,t.shape),i.ENV.engine.runKernel(function(n){return n.notEqual(e,t);},{a:e,b:t});},e.notEqualStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in notEqualStrict: "),e.notEqual(t);},e.less=function(e,t){return o.assertArgumentsAreTensors({a:e,b:t},"less"),o.assertTypesMatch(e,t),s.a(e.shape,t.shape),i.ENV.engine.runKernel(function(n){return n.less(e,t);},{a:e,b:t});},e.lessStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in lessStrict: "),e.less(t);},e.equal=function(e,t){return o.assertArgumentsAreTensors({a:e,b:t},"equal"),o.assertTypesMatch(e,t),s.a(e.shape,t.shape),i.ENV.engine.runKernel(function(n){return n.equal(e,t);},{a:e,b:t});},e.equalStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in equalStrict: "),e.equal(t);},e.lessEqual=function(e,t){return o.assertArgumentsAreTensors({a:e,b:t},"lessEqual"),o.assertTypesMatch(e,t),s.a(e.shape,t.shape),i.ENV.engine.runKernel(function(n){return n.lessEqual(e,t);},{a:e,b:t});},e.lessEqualStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in lessEqualStrict: "),e.lessEqual(t);},e.greater=function(e,t){return o.assertArgumentsAreTensors({a:e,b:t},"greater"),o.assertTypesMatch(e,t),s.a(e.shape,t.shape),i.ENV.engine.runKernel(function(n){return n.greater(e,t);},{a:e,b:t});},e.greaterStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in greaterStrict: "),e.greater(t);},e.greaterEqual=function(e,t){return o.assertArgumentsAreTensors({a:e,b:t},"greaterEqual"),o.assertTypesMatch(e,t),s.a(e.shape,t.shape),i.ENV.engine.runKernel(function(n){return n.greaterEqual(e,t);},{a:e,b:t});},e.greaterEqualStrict=function(e,t){return o.assertShapesMatch(e.shape,t.shape,"Error in greaterEqualStrict: "),e.greaterEqual(t);},m([Object(a.a)({heading:"Operations",subheading:"Logical"}),u.a],e,"notEqual",null),m([u.a],e,"notEqualStrict",null),m([Object(a.a)({heading:"Operations",subheading:"Logical"}),u.a],e,"less",null),m([u.a],e,"lessStrict",null),m([Object(a.a)({heading:"Operations",subheading:"Logical"}),u.a],e,"equal",null),m([u.a],e,"equalStrict",null),m([Object(a.a)({heading:"Operations",subheading:"Logical"}),u.a],e,"lessEqual",null),m([u.a],e,"lessEqualStrict",null),m([Object(a.a)({heading:"Operations",subheading:"Logical"}),u.a],e,"greater",null),m([u.a],e,"greaterStrict",null),m([Object(a.a)({heading:"Operations",subheading:"Logical"}),u.a],e,"greaterEqual",null),m([u.a],e,"greaterEqualStrict",null),e;}(),y=n(63);function v(e,t,n,r,a,i){void 0===i&&(i="channelsLast");var o,s=w(t),u=s[0],c=s[1];if("channelsLast"===i)o=[u,c,e[3],e[3]];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);o=[u,c,e[1],e[1]];}return b(e,o,n,1,r,a,!1,i);}function b(e,t,n,r,a,i,s,u){void 0===s&&(s=!1),void 0===u&&(u="channelsLast");var c=[-1,-1,-1,-1],l=c[0],f=c[1],p=c[2],h=c[3];if("channelsLast"===u)l=e[0],f=e[1],p=e[2],h=e[3];else{if("channelsFirst"!==u)throw new Error("Unknown dataFormat "+u);l=e[0],h=e[1],f=e[2],p=e[3];}var d,m=t[0],g=t[1],y=t[3],v=w(n),b=v[0],O=v[1],S=w(r),N=S[0],E=S[1],I=function(e,t,n,r,a,i,s,u){var c,l,f;if("number"==typeof e){c={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};var p=function(e,t,n,r,a,i){null==a&&(a=function(e,t,n,r){void 0===r&&(r=1);var a=x(t,r);return Math.floor((e[0]*(n-1)-n+a)/2);}(e,t,r));var s=e[1],u=k((e[0]-t+2*a)/r+1,i);o.assert(o.isInt(u),"The output # of rows ("+u+") must be an integer. Change the stride and/or zero pad parameters");var c=k((s-t+2*a)/r+1,i);return o.assert(o.isInt(c),"The output # of columns ("+c+") must be an integer. Change the stride and/or zero pad parameters"),[u,c,1];}([t,n,1],i,0,r,e,u);l=p[0],f=p[1];}else if("same"===e){var h=((l=Math.ceil(t/r))-1)*r+i-t,d=((f=Math.ceil(n/a))-1)*a+s-n,m=Math.floor(h/2),g=h-m,y=Math.floor(d/2);c={top:m,bottom:g,left:y,right:d-y,type:"SAME"};}else{if("valid"!==e)throw Error("Unknown padding parameter: "+e);c={top:0,bottom:0,left:0,right:0,type:"VALID"},l=Math.ceil((t-i+1)/r),f=Math.ceil((n-s+1)/a);}return{padInfo:c,outHeight:l,outWidth:f};}(a,f,p,b,O,x(m,N),x(g,E),i),T=I.padInfo,A=I.outHeight,C=I.outWidth,P=s?y*h:y;return"channelsFirst"===u?d=[l,P,A,C]:"channelsLast"===u&&(d=[l,A,C,P]),{batchSize:l,dataFormat:u,inHeight:f,inWidth:p,inChannels:h,outHeight:A,outWidth:C,outChannels:P,padInfo:T,strideHeight:b,strideWidth:O,filterHeight:m,filterWidth:g,dilationHeight:N,dilationWidth:E,inShape:e,outShape:d,filterShape:t};}function w(e){return"number"==typeof e?[e,e]:e;}function x(e,t){return t<=1?e:e+(e-1)*(t-1);}function k(e,t){if(!t)return e;switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error("Unknown roundingMode "+t);}}var O=function O(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},S=function(){function e(){}return e.conv1d=function(t,n,r,a,i,s,u){void 0===i&&(i="NWC"),void 0===s&&(s=1),o.assertArgumentsAreTensors({x:t,filter:n},"conv1d");var c=t,l=!1;2===t.rank&&(l=!0,c=t.as3D(1,t.shape[0],t.shape[1])),o.assert(3===c.rank,"Error in conv1d: input must be rank 3, but got rank "+c.rank+"."),o.assert(3===n.rank,"Error in conv1d: filter must be rank 3, but got rank "+n.rank+"."),null!=u&&o.assert(o.isInt(a),"Error in conv1d: pad must be an integer when using, dimRoundingMode "+u+" but got pad "+a+"."),o.assert(c.shape[2]===n.shape[1],"Error in conv1d: depth of input ("+c.shape[2]+") must match input depth for filter "+n.shape[1]+"."),o.assert(E(r,s),"Error in conv1D: Either stride or dilation must be 1. Got stride "+r+" and dilation '"+s+"'"),o.assert("NWC"===i,"Error in conv1d: got dataFormat of "+i+" but only NWC is currently supported.");var f=n.as4D(1,n.shape[0],n.shape[1],n.shape[2]),p=c.as4D(c.shape[0],1,c.shape[1],c.shape[2]),h=[1,r],d=[1,s],m=e.conv2d(p,f,h,a,"NHWC",d,u);return l?m.as2D(m.shape[2],m.shape[3]):m.as3D(m.shape[0],m.shape[2],m.shape[3]);},e.conv2d=function(t,n,r,a,s,u,c){void 0===s&&(s="NHWC"),void 0===u&&(u=[1,1]),o.assertArgumentsAreTensors({x:t,filter:n},"conv2d");var l=t,f=!1;3===t.rank&&(f=!0,l=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),o.assert(4===l.rank,"Error in conv2d: input must be rank 4, but got rank "+l.rank+"."),o.assert(4===n.rank,"Error in conv2d: filter must be rank 4, but got rank "+n.rank+"."),null!=c&&o.assert(o.isInt(a),"Error in conv2d: pad must be an integer when using, dimRoundingMode "+c+" but got pad "+a+"."),o.assert(l.shape[3]===n.shape[2],"Error in conv2d: depth of input ("+l.shape[3]+") must match input depth for filter "+n.shape[2]+"."),o.assert(E(r,u),"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"),o.assert("NHWC"===s,"Error in conv2d: got dataFormat of "+s+" but only NHWC is currently supported.");var p=b(l.shape,n.shape,r,u,a,c),h=i.ENV.engine.runKernel(function(e){return e.conv2d(l,n,p);},{x:l,filter:n},function(t){return o.assert(N(u),"Error in gradient of conv2D: dilation rates greater than 1 are notyet supported in gradients. Got dilations '"+u+"'"),{x:function x(){return e.conv2dDerInput(l.shape,t,n,r,a);},filter:function filter(){return e.conv2dDerFilter(l,t,n.shape,r,a);}};});return f?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h;},e.conv2dDerInput=function(e,t,n,r,a,s){o.assertArgumentsAreTensors({dy:t,filter:n},"conv2dDerInput"),o.assert(e.length===t.rank,"Length of inShape ("+e.length+") and rank of dy ("+t.rank+") must match");var u=e,c=t,l=!1;3===t.rank&&(l=!0,c=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),u=[1,e[0],e[1],e[2]]);var f=u[3],p=c.shape[3];o.assert(4===u.length,"Error in conv2dDerInput: inShape must be length 4, but got length "+u.length+"."),o.assert(4===c.rank,"Error in conv2dDerInput: dy must be rank 4, but got rank "+c.rank),o.assert(4===n.rank,"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank),o.assert(f===n.shape[2],"Error in conv2dDerInput: depth of input ("+f+") must match input depth for filter "+n.shape[2]+"."),o.assert(p===n.shape[3],"Error in conv2dDerInput: depth of output ("+p+") must match output depth for filter "+n.shape[3]+"."),null!=s&&o.assert(o.isInt(a),"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+a+".");var h=b(u,n.shape,r,1,a,s),d=i.ENV.engine.runKernel(function(e){return e.conv2dDerInput(c,n,h);},{dy4D:c});return l?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d;},e.conv2dDerFilter=function(e,t,n,r,a,s){o.assertArgumentsAreTensors({x:e,dy:t},"conv2dDerFilter");var u=e;3===e.rank&&(u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var c=t;3===c.rank&&(c=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),o.assert(4===u.rank,"Error in conv2dDerFilter: input must be rank 4, but got shape "+u.shape+"."),o.assert(4===c.rank,"Error in conv2dDerFilter: dy must be rank 4, but got shape "+c.shape+"."),o.assert(4===n.length,"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."),o.assert(u.shape[3]===n[2],"Error in conv2dDerFilter: depth of input "+u.shape[3]+") must match input depth in filter ("+n[2]+"."),o.assert(c.shape[3]===n[3],"Error in conv2dDerFilter: depth of dy ("+c.shape[3]+") must match output depth for filter ("+n[3]+")."),null!=s&&o.assert(o.isInt(a),"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+a+".");var l=b(u.shape,n,r,1,a,s);return i.ENV.engine.runKernel(function(e){return e.conv2dDerFilter(u,c,l);},{x4D:u,dy4D:c});},e.conv2dTranspose=function(t,n,r,a,i,s){return o.assertArgumentsAreTensors({x:t,filter:n},"conv2dTranspose"),e.conv2dDerInput(r,t,n,a,i,s);},e.depthwiseConv2d=function(e,t,n,r,a,s,u){void 0===a&&(a="NHWC"),void 0===s&&(s=[1,1]),o.assertArgumentsAreTensors({x:e,filter:t},"depthwiseConv2d");var c=e,l=!1;3===e.rank&&(l=!0,c=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),o.assert(4===c.rank,"Error in depthwiseConv2d: input must be rank 4, but got rank "+c.rank+"."),o.assert(4===t.rank,"Error in depthwiseConv2d: filter must be rank 4, but got rank "+t.rank+"."),o.assert(c.shape[3]===t.shape[2],"Error in depthwiseConv2d: number of input channels ("+c.shape[3]+") must match the inChannels dimension in filter "+t.shape[2]+"."),null==s&&(s=[1,1]),o.assert(E(n,s),"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+s+"'"),null!=u&&o.assert(o.isInt(r),"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+u+" but got pad "+r+".");var f=b(c.shape,t.shape,n,s,r,u,!0),p=i.ENV.engine.runKernel(function(e){return e.depthwiseConv2D(c,t,f);},{x:c,filter:t},function(e){return o.assert(N(s),"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+s+"'"),{x:function x(){return function(e,t,n,r){var a=t,o=!1;3===t.rank&&(o=!0,a=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var s=i.ENV.engine.runKernel(function(e){return e.depthwiseConv2DDerInput(a,n,r);},{dy4D:a});return o?s.as3D(s.shape[1],s.shape[2],s.shape[3]):s;}(c.shape,e,t,f);},filter:function filter(){return function(e,t,n,r){var a=e;3===e.rank&&(a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var o=t;return 3===o.rank&&(o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),i.ENV.engine.runKernel(function(e){return e.depthwiseConv2DDerFilter(a,o,r);},{x4D:a,dy4D:o});}(c,e,t.shape,f);}};});return l?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p;},e.separableConv2d=function(t,n,r,a,i,s,u){void 0===s&&(s=[1,1]),void 0===u&&(u="NHWC"),o.assertArgumentsAreTensors({x:t,depthwiseFilter:n,pointwiseFilter:r},"separableConv2d");var c=t,l=!1;if(3===t.rank&&(l=!0,c=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),"NCHW"===u)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");o.assert(4===c.rank,"Error in separableConv2d: input must be rank 4, but got rank "+c.rank+"."),o.assert(4===n.rank,"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+n.rank+"."),o.assert(4===r.rank,"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+n.rank+"."),o.assert(1===r.shape[0],"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+r.shape[0]+"."),o.assert(1===r.shape[1],"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+r.shape[1]+".");var f=n.shape[2],p=n.shape[3];o.assert(r.shape[2]===f*p,"Error in separableConv2d: the third dimension of pointwise filter must be "+f*p+", but got "+r.shape[2]+".");var h=e.depthwiseConv2d(c,n,a,i,u,s),d=e.conv2d(h,r,1,"valid",u);return l?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d;},O([Object(a.a)({heading:"Operations",subheading:"Convolution"}),u.a],e,"conv1d",null),O([Object(a.a)({heading:"Operations",subheading:"Convolution"}),u.a],e,"conv2d",null),O([u.a],e,"conv2dDerInput",null),O([u.a],e,"conv2dDerFilter",null),O([Object(a.a)({heading:"Operations",subheading:"Convolution"}),u.a],e,"conv2dTranspose",null),O([Object(a.a)({heading:"Operations",subheading:"Convolution"}),u.a],e,"depthwiseConv2d",null),O([Object(a.a)({heading:"Operations",subheading:"Convolution"}),u.a],e,"separableConv2d",null),e;}();function N(e){var t=function(e){return"number"==typeof e?[e,e]:e;}(e),n=t[0],r=t[1];return 1===n&&1===r;}function E(e,t){return N(e)||N(t);}var I=function I(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},T=function(){function e(){}return e.resizeBilinear=function(e,t,n){void 0===n&&(n=!1),o.assertArgumentsAreTensors({images:e},"resizeBilinear"),o.assert(3===e.rank||4===e.rank,"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+e.rank+"."),o.assert(2===t.length,"Error in resizeBilinear: new shape must 2D, but got shape "+t+".");var r=e,a=!1;3===e.rank&&(a=!0,r=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var s=t[0],u=t[1],c=i.ENV.engine.runKernel(function(e,t){return e.resizeBilinear(r,s,u,n);},{batchImages:r},function(e,t){return{batchImages:function batchImages(){return i.ENV.engine.runKernel(function(t){return t.resizeBilinearBackprop(e,r,n);},{});}};});return a?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c;},e.resizeNearestNeighbor=function(e,t,n){void 0===n&&(n=!1),o.assertArgumentsAreTensors({images:e},"resizeNearestNeighbor"),o.assert(3===e.rank||4===e.rank,"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+e.rank+"."),o.assert(2===t.length,"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."),o.assert("float32"===e.dtype||"int32"===e.dtype,"`images` must have `int32` or `float32` as dtype");var r=e,a=!1;3===e.rank&&(a=!0,r=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var s=t[0],u=t[1],c=i.ENV.engine.runKernel(function(e){return e.resizeNearestNeighbor(r,s,u,n);},{batchImages:r});return a?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c;},I([Object(a.a)({heading:"Operations",subheading:"Images",namespace:"image"}),u.a],e,"resizeBilinear",null),I([Object(a.a)({heading:"Operations",subheading:"Images",namespace:"image"}),u.a],e,"resizeNearestNeighbor",null),e;}(),A=n(80),C=function(){function e(){}return e.gramSchmidt=function(e){var t;if(Array.isArray(e)){t=!1,Object(o.assert)(null!=e&&e.length>0,"Gram-Schmidt process: input must not be null, undefined, or empty");for(var n=e[0].shape[0],r=1;r<e.length;++r){Object(o.assert)(e[r].shape[0]===n,"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+e[r].shape[0]+" vs. "+n+")");}}else t=!0,e=qn(e,e.shape[0],0).map(function(e){return In(e,[0]);});Object(o.assert)(e.length<=e[0].shape[0],"Gram-Schmidt: Number of vectors ("+e.length+") exceeds number of dimensions ("+e[0].shape[0]+").");var a=[],i=e,s=function s(e){a.push(A.a.tidy(function(){var t=i[e];if(e>0)for(var n=0;n<e;++n){var r=We(a[n].mulStrict(t)).mul(a[n]);t=t.sub(r);}return t.div(fn(t,"euclidean"));}));};for(r=0;r<e.length;++r){s(r);}return t?Wn(a,0):a;},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}i>3&&o&&Object.defineProperty(t,n,o);}([Object(a.a)({heading:"Operations",subheading:"Linear Algebra"}),u.a],e,"gramSchmidt",null),e;}(),P=function P(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},_=function(){function e(){}return e.logicalNot=function(e){return o.assertArgumentsAreTensors({x:e},"logicalNot"),o.assert("bool"===e.dtype,"Error Array must be of type bool."),i.ENV.engine.runKernel(function(t){return t.logicalNot(e);},{x:e});},e.logicalAnd=function(e,t){return o.assertArgumentsAreTensors({a:e,b:t},"logicalAnd"),o.assert("bool"===e.dtype&&"bool"===t.dtype,"Error Array must be of type bool."),s.a(e.shape,t.shape),i.ENV.engine.runKernel(function(n){return n.logicalAnd(e,t);},{a:e,b:t});},e.logicalOr=function(e,t){return o.assertArgumentsAreTensors({a:e,b:t},"logicalOr"),o.assert("bool"===e.dtype&&"bool"===t.dtype,"Error Array must be of type bool."),s.a(e.shape,t.shape),i.ENV.engine.runKernel(function(n){return n.logicalOr(e,t);},{a:e,b:t});},e.logicalXor=function(t,n){return o.assertArgumentsAreTensors({a:t,b:n},"logicalXor"),o.assert("bool"===t.dtype&&"bool"===n.dtype,"Error Array must be of type bool."),s.a(t.shape,n.shape),e.logicalOr(t,n).logicalAnd(e.logicalAnd(t,n).logicalNot());},e.where=function(e,t,n){o.assertArgumentsAreTensors({condition:e,a:t,b:n},"where"),o.assert("bool"===e.dtype,"Error Condition must be of type bool."),o.assertShapesMatch(t.shape,n.shape,"Error in where: "),1===e.rank?o.assert(e.shape[0]===t.shape[0],"The first dimension of `a` must match the size of `condition`."):o.assertShapesMatch(e.shape,n.shape,"Error in where: ");var r=p.c(t.dtype,n.dtype);return i.ENV.engine.runKernel(function(a){return a.where(e,t,n,r);},{condition:e,a:t,b:n});},P([Object(a.a)({heading:"Operations",subheading:"Logical"}),u.a],e,"logicalNot",null),P([Object(a.a)({heading:"Operations",subheading:"Logical"}),u.a],e,"logicalAnd",null),P([Object(a.a)({heading:"Operations",subheading:"Logical"}),u.a],e,"logicalOr",null),P([Object(a.a)({heading:"Operations",subheading:"Logical"}),u.a],e,"logicalXor",null),P([Object(a.a)({heading:"Operations",subheading:"Logical"}),u.a],e,"where",null),e;}(),R=n(44),M=function(){function e(){}return e.localResponseNormalization=function(e,t,n,r,a){void 0===t&&(t=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===a&&(a=.5),o.assertArgumentsAreTensors({x:e},"localResponseNormalization"),o.assert(4===e.rank||3===e.rank,"Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank "+e.rank+"."),o.assert(o.isInt(t),"Error in localResponseNormalization3D: radius must be an integer\n but got radius "+t+".");var s=e,u=!1;3===e.rank&&(u=!0,s=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var c=i.ENV.engine.runKernel(function(e){return e.localResponseNormalization4D(s,t,n,r,a);},{x4D:s});return u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c;},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}i>3&&o&&Object.defineProperty(t,n,o);}([Object(a.a)({heading:"Operations",subheading:"Normalization"}),u.a],e,"localResponseNormalization",null),e;}(),j=function j(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},D=function(){function e(){}return e.multiRNNCell=function(e,t,n,r){o.assertArgumentsAreTensors({data:t,c:n,h:r},"multiRNNCell");for(var a=t,i=[],s=0;s<e.length;s++){var u=e[s](a,n[s],r[s]);i.push(u[0]),i.push(u[1]),a=u[1];}var c=[],l=[];for(s=0;s<i.length;s+=2){c.push(i[s]),l.push(i[s+1]);}return[c,l];},e.basicLSTMCell=function(e,t,n,r,a,i){o.assertArgumentsAreTensors({forgetBias:e,lstmKernel:t,lstmBias:n,data:r,c:a,h:i},"basicLSTMCell");var s=r.concat(i,1).matMul(t).add(n),u=s.shape[0],c=s.shape[1]/4,l=[u,c],f=s.slice([0,0],l),p=s.slice([0,c],l),h=s.slice([0,2*c],l),d=s.slice([0,3*c],l),m=f.sigmoid().mulStrict(p.tanh()).addStrict(a.mulStrict(e.add(h).sigmoid()));return[m,m.tanh().mulStrict(d.sigmoid())];},j([Object(a.a)({heading:"Operations",subheading:"RNN"}),u.a],e,"multiRNNCell",null),j([Object(a.a)({heading:"Operations",subheading:"RNN"}),u.a],e,"basicLSTMCell",null),e;}(),L=function L(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},z=function(){function e(){}return e.matMul=function(e,t,n,r){void 0===n&&(n=!1),void 0===r&&(r=!1),o.assertArgumentsAreTensors({a:e,b:t},"matMul");var a=n?e.shape[0]:e.shape[1],s=r?t.shape[1]:t.shape[0];return o.assert(2===e.rank&&2===t.rank,"Error in matMul: inputs must be rank 2, got ranks "+e.rank+" and "+t.rank+"."),o.assert(a===s,"Error in matMul: inner shapes ("+a+") and ("+s+") of Tensors with shapes "+e.shape+" and "+t.shape+" and transposeA="+n+" and transposeB="+r+" must match."),i.ENV.engine.runKernel(function(a){return a.matMul(e,t,n,r);},{a:e,b:t},function(_a3){return n||r?!n&&r?{a:function a(){return _a3.matMul(t.toFloat(),!1,!1);},b:function b(){return _a3.matMul(e.toFloat(),!0,!1);}}:n&&!r?{a:function a(){return t.toFloat().matMul(_a3,!1,!0);},b:function b(){return e.toFloat().matMul(_a3,!1,!1);}}:{a:function a(){return t.toFloat().matMul(_a3,!0,!0);},b:function b(){return _a3.matMul(e.toFloat(),!0,!0);}}:{a:function a(){return _a3.matMul(t.toFloat(),!1,!0);},b:function b(){return e.toFloat().matMul(_a3,!0,!1);}};});},e.vectorTimesMatrix=function(e,t){return o.assert(1===e.rank,"Error in vectorTimesMatrix: first input must be rank 1, but got rank "+e.rank+"."),o.assert(2===t.rank,"Error in vectorTimesMatrix: second input must be rank 2, but got rank "+t.rank+"."),o.assert(e.size===t.shape[0],"Error in vectorTimesMatrix: size of vector ("+e.size+") must match first dimension of matrix ("+t.shape[0]+")"),e.as2D(1,-1).matMul(t).as1D();},e.matrixTimesVector=function(e,t){return o.assert(1===t.rank,"Error in matrixTimesVector: second input must rank 1, but got rank "+t.rank+"."),o.assert(2===e.rank,"Error in matrixTimesVector: first input must be a rank 2, but got rank "+e.rank+"."),o.assert(t.size===e.shape[1],"Error in matrixTimesVector: size of first rank 1 input "+t.size+" must match inner dimension of second rank 2 input, but got shape "+e.shape+"."),e.matMul(t.as2D(-1,1)).as1D();},e.dotProduct=function(e,t){return o.assert(1===e.rank&&1===t.rank,"Error in dotProduct: inputs must be rank 1, but got ranks "+e.rank+" and "+t.rank+"."),o.assert(e.size===t.size,"Error in dotProduct: size of inputs ("+e.size+") and ("+t.size+") must match."),e.as2D(1,-1).matMul(t.as2D(-1,1)).asScalar();},e.outerProduct=function(e,t){return o.assert(1===e.rank&&1===t.rank,"Error in outerProduct: inputs must be rank 1, but got ranks "+e.rank+" and "+t.rank+"."),e.as2D(-1,1).matMul(t.as2D(1,-1));},e.dot=function(e,t){o.assert(!(1!==e.rank&&2!==e.rank||1!==t.rank&&2!==t.rank),"Error in dot: inputs must all be rank 1 or 2, but got ranks "+e.rank+" and "+t.rank+".");var n=1===e.rank?e.size:e.shape[1],r=1===t.rank?t.size:t.shape[0];return o.assert(n===r,"Error in dot: inner dimensions of inputs must match, but got "+n+" and "+r+"."),1===e.rank&&1===t.rank?e.as2D(1,-1).matMul(t.as2D(-1,1)).asScalar():1===e.rank&&2===t.rank?e.as2D(1,-1).matMul(t.as2D(t.shape[0],t.shape[1])).as1D():2===e.rank&&1===t.rank?e.matMul(t.as2D(-1,1)).as1D():e.matMul(t.as2D(t.shape[0],t.shape[1]));},L([Object(a.a)({heading:"Operations",subheading:"Matrices"}),u.a],e,"matMul",null),L([u.a],e,"vectorTimesMatrix",null),L([u.a],e,"matrixTimesVector",null),L([u.a],e,"dotProduct",null),L([Object(a.a)({heading:"Operations",subheading:"Matrices"}),u.a],e,"outerProduct",null),L([Object(a.a)({heading:"Operations",subheading:"Matrices"}),u.a],e,"dot",null),e;}(),F=function(){function e(){}return e.movingAverage=function(e,t,n,a,i){void 0===i&&(i=!0),o.assertArgumentsAreTensors({v:e,x:t},"movingAverage"),o.assertTypesMatch(e,t),o.assert(o.arraysEqual(e.shape,t.shape),"Shape mismatch in v and x");var s=r.a.scalar(1);n="number"==typeof n?r.a.scalar(n):n;var u=s.sub(n),c=t.sub(e).mul(u);return i&&(o.assert(null!=a,"When using zeroDebias: true, step is required."),a="number"==typeof a?r.a.scalar(a):a,c=c.div(s.sub(d.pow(n,a)))),e.add(c);},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}i>3&&o&&Object.defineProperty(t,n,o);}([Object(a.a)({heading:"Operations",subheading:"Moving Average"}),u.a],e,"movingAverage",null),e;}(),B=n(8),V=function(){function e(){}return e.norm=function(e,t,n,r){void 0===t&&(t="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1),o.assertArgumentsAreTensors({x:e},"norm");var a=function e(t,n,r){if(void 0===r&&(r=null),0===t.rank)return t.abs();if(1!==t.rank&&null===r)return e(t.reshape([-1]),n,r);if(1===t.rank||"number"==typeof r||r instanceof Array&&1===r.length){if(1===n)return t.abs().sum(r);if(n===1/0)return t.abs().max(r);if(n===-1/0)return t.abs().min(r);if("euclidean"===n||2===n)return t.abs().pow(Dn(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n);}if(r instanceof Array&&2===r.length){if(1===n)return t.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return t.abs().sum(r[1]).max(r[0]);if(n===-1/0)return t.abs().sum(r[1]).min(r[0]);if("fro"===n||"euclidean"===n)return t.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n);}throw new Error("Error in norm: invalid axis: "+r);}(e,t,n),i=a.shape;if(r){var s=B.g(n,e.shape);i=B.c(a.shape,s);}return a.reshape(i);},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}i>3&&o&&Object.defineProperty(t,n,o);}([Object(a.a)({heading:"Operations",subheading:"Matrices"}),u.a],e,"norm",null),e;}(),U=function U(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},W=function(){function e(){}return e.maxPool=function(t,n,r,a,s){o.assertArgumentsAreTensors({x:t},"maxPool");var u=t,c=!1;3===t.rank&&(c=!0,u=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),o.assert(4===u.rank,"Error in maxPool: input must be rank 4 but got rank "+u.rank+"."),null!=s&&o.assert(o.isInt(a),"Error in maxPool: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+a+".");var l=v(u.shape,n,r,a,s),f=i.ENV.engine.runKernel(function(e,t){return t(e.maxPool(u,l));},{x:u},function(t,i){var o=i[0];return{x:function x(){return e.maxPoolBackprop(t,u,o,n,r,a);}};});return c?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f;},e.maxPoolBackprop=function(e,t,n,r,a,s,u){o.assertArgumentsAreTensors({dy:e,input:t,output:n},"maxPoolBackprop"),o.assert(t.rank===e.rank,"Rank of input ("+t.rank+") does not match rank of dy ("+e.rank+")"),o.assert(4===e.rank,"Error in maxPoolBackprop: dy must be rank 4 but got rank "+e.rank+"."),o.assert(4===t.rank,"Error in maxPoolBackprop: input must be rank 4 but got rank "+t.rank+"."),null!=u&&o.assert(o.isInt(s),"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+u+" but got pad "+s+".");var c=v(t.shape,r,a,s,u);return i.ENV.engine.runKernel(function(r){return r.maxPoolBackprop(e,t,n,c);},{dy:e,input:t});},e.avgPool=function(t,n,r,a,s){o.assertArgumentsAreTensors({x:t},"avgPool"),o.assert("float32"===t.dtype,"The input dtype to avgPool must be float32");var u=t,c=!1;3===t.rank&&(c=!0,u=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),o.assert(4===u.rank,"Error in avgPool: x must be rank 4 but got rank "+u.rank+"."),null!=s&&o.assert(o.isInt(a),"Error in avgPool: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+a+".");var l=v(u.shape,n,r,a),f=i.ENV.engine.runKernel(function(e){return e.avgPool(u,l);},{x:u},function(t){return{x:function x(){return e.avgPoolBackprop(t,u,n,r,a);}};});return f=f.cast(t.dtype),c?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f;},e.avgPoolBackprop=function(e,t,n,r,a){o.assertArgumentsAreTensors({dy:e,input:t},"avgPoolBackprop"),o.assert(t.rank===e.rank,"Rank of input ("+t.rank+") does not match rank of dy ("+e.rank+")");var s=t,u=e,c=!1;3===t.rank&&(c=!0,s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),o.assert(4===u.rank,"Error in avgPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."),o.assert(4===s.rank,"Error in avgPoolBackprop: input must be rank 4 but got rank "+s.rank+".");var l=v(s.shape,n,r,a),f=i.ENV.engine.runKernel(function(e){return e.avgPoolBackprop(u,s,l);},{dy4D:u,input4D:s});return c?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f;},U([Object(a.a)({heading:"Operations",subheading:"Convolution"}),u.a],e,"maxPool",null),U([u.a],e,"maxPoolBackprop",null),U([Object(a.a)({heading:"Operations",subheading:"Convolution"}),u.a],e,"avgPool",null),U([u.a],e,"avgPoolBackprop",null),e;}(),G=n(39),q=function(){function e(){}return e.reverse1d=function(t){return o.assert(1===t.rank,"Error in reverse1D: x must be rank 1 but got\n rank "+t.rank+"."),e.reverse(t,0);},e.reverse2d=function(t,n){return o.assert(2===t.rank,"Error in reverse2D: x must be rank 2 but got\n rank "+t.rank+"."),e.reverse(t,n);},e.reverse3d=function(t,n){return o.assert(3===t.rank,"Error in reverse3D: x must be rank 3 but got\n rank "+t.rank+"."),e.reverse(t,n);},e.reverse4d=function(t,n){return o.assert(4===t.rank,"Error in reverse4D: x must be rank 4 but got\n rank "+t.rank+"."),e.reverse(t,n);},e.reverse=function(e,t){if(o.assertArgumentsAreTensors({x:e},"reverse"),0===e.rank)return e.clone();var n=Object(B.g)(t,e.shape);return i.ENV.engine.runKernel(function(t){return t.reverse(e,n);},{x:e},function(e){return{x:function x(){return e.reverse(n);}};}).reshapeAs(e);},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}i>3&&o&&Object.defineProperty(t,n,o);}([Object(a.a)({heading:"Tensors",subheading:"Slicing and Joining"}),u.a],e,"reverse",null),e;}(),H=n(90),K=function(){function e(){}return e.slice1d=function(t,n,r){return o.assert(1===t.rank,"slice1d expects a rank-1 tensor, but got a rank-"+t.rank+" tensor"),e.slice(t,[n],[r]);},e.slice2d=function(t,n,r){return o.assert(2===t.rank,"slice1d expects a rank-2 tensor, but got a rank-"+t.rank+" tensor"),e.slice(t,n,r);},e.slice3d=function(t,n,r){return o.assert(3===t.rank,"slice1d expects a rank-3 tensor, but got a rank-"+t.rank+" tensor"),e.slice(t,n,r);},e.slice4d=function(t,n,r){return o.assert(4===t.rank,"slice1d expects a rank-4 tensor, but got a rank-"+t.rank+" tensor"),e.slice(t,n,r);},e.slice=function(e,t,n){if(o.assertArgumentsAreTensors({x:e},"slice"),0===e.rank)throw new Error("Slicing scalar is not possible");var r,a;r="number"==typeof t?[t].concat(new Array(e.rank-1).fill(0)):t.length<e.rank?t.concat(new Array(e.rank-t.length).fill(0)):t,a=(a=null==n?new Array(e.rank).fill(-1):"number"==typeof n?[n].concat(new Array(e.rank-1).fill(-1)):n.length<e.rank?n.concat(new Array(e.rank-n.length).fill(-1)):n).map(function(t,n){return t>=0?t:(o.assert(-1===t,"Bad value in size"),e.shape[n]-r[n]);}),H.a(e,r,a);var s=e.shape;return i.ENV.engine.runKernel(function(t){return t.slice(e,r,a);},{x:e},function(e){for(var t=[],n=0;n<e.rank;n++){t.push([r[n],s[n]-r[n]-a[n]]);}return{x:function x(){return e.pad(t);}};});},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}i>3&&o&&Object.defineProperty(t,n,o);}([Object(a.a)({heading:"Tensors",subheading:"Slicing and Joining"}),u.a],e,"slice",null),e;}(),X=n(7),J=function J(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},Y=function(){function e(){}return e.softmax=function(e,t){if(void 0===t&&(t=-1),o.assertArgumentsAreTensors({logits:e},"softmax"),-1===t&&(t=e.rank-1),t!==e.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+e.rank+" and dim was "+t);return Object(X.a)(function(e){var n=e.logSumExp([t],!0),r=e.toFloat().sub(n).exp();return{value:r,gradFunc:function gradFunc(e){var n=e.mul(r);return n.sub(n.sum([t],!0).mul(r));}};})(e);},e.softmaxCrossEntropy=function(e,t,n){if(void 0===n&&(n=-1),o.assertArgumentsAreTensors({labels:e,logits:t},"softmaxCrossEntropy"),o.assertShapesMatch(e.shape,t.shape,"Error in softmaxCrossEntropy: "),-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+t.rank+" and dim was "+n);return Object(X.a)(function(e,t){var r=t.softmax(n);return{value:Dn(1e-5).add(r).log().mul(e).neg().sum([n]),gradFunc:function gradFunc(t){var a=B.c(t.shape,[n]);return[t.reshape(a).mul(e.toFloat().sub(r)),t.reshape(a).mul(r.sub(e.toFloat()))];}};})(e,t);},J([Object(a.a)({heading:"Operations",subheading:"Normalization"}),u.a],e,"softmax",null),J([Object(a.a)({heading:"Training",subheading:"Losses",namespace:"losses"}),u.a],e,"softmaxCrossEntropy",null),e;}(),Q=function(){function e(){}return e.stridedSlice=function(e,t,n,r,a,s){return void 0===a&&(a=0),void 0===s&&(s=0),o.assertArgumentsAreTensors({x:e},"stridedSlice"),i.ENV.engine.runKernel(function(i){return i.stridedSlice(e,t,n,r,a,s);},{x:e});},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}i>3&&o&&Object.defineProperty(t,n,o);}([Object(a.a)({heading:"Operations",subheading:"Slicing and Joining"}),u.a],e,"stridedSlice",null),e;}(),Z=function(){function e(){}return e.transpose=function(e,t){return o.assertArgumentsAreTensors({x:e},"transpose"),null==t&&(t=e.shape.map(function(e,t){return t;}).reverse()),o.assert(e.rank===t.length,"Error in transpose: rank of input "+e.rank+" must match length of perm "+t+"."),t.forEach(function(n){o.assert(n>=0&&n<e.rank,"All entries in 'perm' must be between 0 and "+(e.rank-1)+" but got "+t);}),e.rank<=1?e.clone():i.ENV.engine.runKernel(function(n){return n.transpose(e,t);},{x:e},function(e){var n=B.f(t);return{x:function x(){return e.transpose(n);}};});},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}i>3&&o&&Object.defineProperty(t,n,o);}([Object(a.a)({heading:"Operations",subheading:"Matrices"}),u.a],e,"transpose",null),e;}(),$=n(55),ee=function ee(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},te=function(){function e(){}return e.neg=function(e){return o.assertArgumentsAreTensors({x:e},"neg"),i.ENV.engine.runKernel(function(t){return t.neg(e);},{x:e},function(e){return{x:function x(){return e.neg();}};});},e.ceil=function(e){return o.assertArgumentsAreTensors({x:e},"ceil"),i.ENV.engine.runKernel(function(t){return t.ceil(e);},{x:e},function(e){return{x:function x(){return bn(e);}};});},e.floor=function(e){return o.assertArgumentsAreTensors({x:e},"floor"),i.ENV.engine.runKernel(function(t){return t.floor(e);},{x:e},function(e){return{x:function x(){return bn(e);}};});},e.sign=function(e){return o.assertArgumentsAreTensors({x:e},"sign"),i.ENV.engine.runKernel(function(t){return t.sign(e);},{x:e},function(e){return{x:function x(){return bn(e);}};});},e.round=function(e){return o.assertArgumentsAreTensors({x:e},"round"),i.ENV.engine.runKernel(function(t){return t.round(e);},{x:e},function(e){return{x:function x(){return bn(e);}};});},e.exp=function(e){return o.assertArgumentsAreTensors({x:e},"exp"),i.ENV.engine.runKernel(function(t,n){return n(t.exp(e));},{x:e},function(e,t){var n=t[0];return{x:function x(){return e.mulStrict(n);}};});},e.expm1=function(e){return o.assertArgumentsAreTensors({x:e},"expm1"),i.ENV.engine.runKernel(function(t){return t.expm1(e);},{x:e},function(t){return{x:function x(){return t.mulStrict(e.exp());}};});},e.log=function(e){return o.assertArgumentsAreTensors({x:e},"log"),i.ENV.engine.runKernel(function(t){return t.log(e);},{x:e},function(t){return{x:function x(){return t.divStrict(e.toFloat());}};});},e.log1p=function(e){return o.assertArgumentsAreTensors({x:e},"log1p"),i.ENV.engine.runKernel(function(t){return t.log1p(e);},{x:e},function(t){return{x:function x(){return t.divStrict(e.add(Dn(1)));}};});},e.sqrt=function(e){return o.assertArgumentsAreTensors({x:e},"sqrt"),i.ENV.engine.runKernel(function(t){return t.sqrt(e);},{x:e},function(t){return{x:function x(){return t.divStrict(e.toFloat().sqrt().mul(Dn(2)));}};});},e.rsqrt=function(e){return o.assertArgumentsAreTensors({x:e},"rsqrt"),i.ENV.engine.runKernel(function(t){return t.rsqrt(e);},{x:e},function(t){return{x:function x(){return t.divStrict(e.pow(Dn(1.5)).mul(Dn(2))).neg();}};});},e.square=function(e){return o.assertArgumentsAreTensors({x:e},"square"),i.ENV.engine.runKernel(function(t){return t.square(e);},{x:e},function(t){return{x:function x(){return t.mulStrict(e.toFloat().mul(Dn(2)));}};});},e.reciprocal=function(e){return o.assertArgumentsAreTensors({x:e},"reciprocal"),i.ENV.engine.runKernel(function(t){return t.reciprocal(e);},{x:e},function(t){return{x:function x(){return t.divStrict(e.square().neg());}};});},e.abs=function(e){return o.assertArgumentsAreTensors({x:e},"abs"),i.ENV.engine.runKernel(function(t){return t.abs(e);},{x:e},function(t){return{x:function x(){return t.mulStrict(e.toFloat().step(-1));}};});},e.clipByValue=function(e,t,n){return o.assertArgumentsAreTensors({x:e},"clipByValue"),o.assert(t<=n,"Error in clip: min ("+t+") must be less than or equal to max ("+n+")."),i.ENV.engine.runKernel(function(r){return r.clip(e,t,n);},{x:e},function(r){return{x:function x(){return r.where(e.greater(Dn(t)).logicalAnd(e.less(Dn(n))),bn(r));}};});},e.relu=function(e){return o.assertArgumentsAreTensors({x:e},"relu"),"bool"===e.dtype?e.toInt():i.ENV.engine.runKernel(function(t){return t.relu(e);},{x:e},function(t){var n=e.step();return{x:function x(){return t.mulStrict(n.toFloat());}};});},e.elu=function(e){return o.assertArgumentsAreTensors({x:e},"elu"),i.ENV.engine.runKernel(function(t,n){return n(t.elu(e));},{x:e},function(e,t){var n=t[0];return{x:function x(){return i.ENV.engine.runKernel(function(t){return t.eluDer(e,n);},{dy:e,y:n});}};});},e.selu=function(e){return o.assertArgumentsAreTensors({x:e},"selu"),i.ENV.engine.runKernel(function(t){return t.selu(e);},{x:e},function(t){return{x:function x(){var n=e.greater(Dn(0)),r=Dn($.b),a=Dn($.a),i=t.mul(a),o=t.mul(r).mul(e.toFloat().exp());return st(n,i,o);}};});},e.leakyRelu=function(e,t){return void 0===t&&(t=.2),o.assertArgumentsAreTensors({x:e},"leakyRelu"),Yt(Dn(t).mul(e),e);},e.prelu=function(e,t){o.assertArgumentsAreTensors({x:e,alpha:t},"prelu");var n=Dn(0);return Yt(n,e).add(t.mul(Zt(n,e)));},e.sigmoid=function(e){return o.assertArgumentsAreTensors({x:e},"sigmoid"),i.ENV.engine.runKernel(function(t,n){return n(t.sigmoid(e));},{x:e},function(e,t){var n=t[0];return{x:function x(){return e.mulStrict(n.mul(Dn(1).sub(n)));}};});},e.logSigmoid=function(e){return o.assertArgumentsAreTensors({x:e},"logSigmoid"),i.ENV.engine.runKernel(function(t){return t.softplus(e.neg()).neg();},{x:e},function(t){return{x:function x(){return t.mulStrict(e.neg().sigmoid());}};});},e.softplus=function(e){return o.assertArgumentsAreTensors({x:e},"softplus"),i.ENV.engine.runKernel(function(t){return t.softplus(e);},{x:e},function(t){return{x:function x(){return t.mulStrict(e.sigmoid());}};});},e.sin=function(e){return o.assertArgumentsAreTensors({x:e},"sin"),i.ENV.engine.runKernel(function(t){return t.sin(e);},{x:e},function(t){return{x:function x(){return e.toFloat().cos().mulStrict(t);}};});},e.cos=function(e){return o.assertArgumentsAreTensors({x:e},"cos"),i.ENV.engine.runKernel(function(t){return t.cos(e);},{x:e},function(t){return{x:function x(){return e.toFloat().sin().neg().mulStrict(t);}};});},e.tan=function(e){return o.assertArgumentsAreTensors({x:e},"tan"),i.ENV.engine.runKernel(function(t){return t.tan(e);},{x:e},function(t){return{x:function x(){return t.divStrict(e.cos().square());}};});},e.asin=function(t){return o.assertArgumentsAreTensors({x:t},"asin"),i.ENV.engine.runKernel(function(e){return e.asin(t);},{x:t},function(n){return{x:function x(){return n.divStrict(e.sqrt(Dn(1).sub(t.toFloat().square())));}};});},e.acos=function(t){return o.assertArgumentsAreTensors({x:t},"acos"),i.ENV.engine.runKernel(function(e){return e.acos(t);},{x:t},function(n){return{x:function x(){return n.divStrict(e.sqrt(Dn(1).sub(t.toFloat().square()))).neg();}};});},e.atan=function(e){return o.assertArgumentsAreTensors({x:e},"atan"),i.ENV.engine.runKernel(function(t){return t.atan(e);},{x:e},function(t){return{x:function x(){return t.divStrict(Dn(1).add(e.toFloat().square()));}};});},e.sinh=function(e){return o.assertArgumentsAreTensors({x:e},"sinh"),i.ENV.engine.runKernel(function(t){return t.sinh(e);},{x:e},function(t){return{x:function x(){return e.toFloat().cosh().mulStrict(t);}};});},e.cosh=function(e){return o.assertArgumentsAreTensors({x:e},"cosh"),i.ENV.engine.runKernel(function(t){return t.cosh(e);},{x:e},function(t){return{x:function x(){return e.toFloat().sinh().mulStrict(t);}};});},e.tanh=function(e){return o.assertArgumentsAreTensors({x:e},"tanh"),i.ENV.engine.runKernel(function(t,n){return n(t.tanh(e));},{x:e},function(e,t){var n=t[0];return{x:function x(){return Dn(1).sub(n.square()).mulStrict(e);}};});},e.asinh=function(t){return o.assertArgumentsAreTensors({x:t},"asinh"),i.ENV.engine.runKernel(function(e){return e.asinh(t);},{x:t},function(n){return{x:function x(){return n.divStrict(e.sqrt(Dn(1).add(t.toFloat().square())));}};});},e.acosh=function(t){return o.assertArgumentsAreTensors({x:t},"acosh"),i.ENV.engine.runKernel(function(e){return e.acosh(t);},{x:t},function(n){return{x:function x(){return n.divStrict(e.sqrt(t.toFloat().square().sub(Dn(1))));}};});},e.atanh=function(e){return o.assertArgumentsAreTensors({x:e},"atanh"),i.ENV.engine.runKernel(function(t){return t.atanh(e);},{x:e},function(t){return{x:function x(){return t.divStrict(Dn(1).sub(e.toFloat().square()));}};});},e.erf=function(e){return o.assert("int32"===e.dtype||"float32"===e.dtype,"Input dtype must be `int32` or `float32`."),"int32"===e.dtype&&(e=e.toFloat()),i.ENV.engine.runKernel(function(t){return t.erf(e);},{x:e},function(t){return{x:function x(){return t.mulStrict(Dn(2/Math.sqrt(Math.PI)).mul(e.square().neg().exp()));}};});},e.step=function(e,t){return void 0===t&&(t=0),o.assertArgumentsAreTensors({x:e},"step"),i.ENV.engine.runKernel(function(n){return n.step(e,t);},{x:e},function(e){return{x:function x(){return bn(e);}};});},ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"neg",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"ceil",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"floor",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"sign",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"round",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"exp",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"expm1",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"log",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"log1p",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"sqrt",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"rsqrt",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"square",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"reciprocal",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"abs",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"clipByValue",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"relu",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"elu",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"selu",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"leakyRelu",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"prelu",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"sigmoid",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"logSigmoid",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"softplus",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"sin",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"cos",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"tan",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"asin",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"acos",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"atan",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"sinh",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"cosh",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"tanh",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"asinh",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"acosh",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"atanh",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"erf",null),ee([Object(a.a)({heading:"Operations",subheading:"Basic math"}),u.a],e,"step",null),e;}(),ne=n(6);n.d(t,"o",function(){return re;}),n.d(t,"p",function(){return ae;}),n.d(t,"q",function(){return ie;}),n.d(t,"r",function(){return oe;}),n.d(t,"x",function(){return se;}),n.d(t,"y",function(){return ue;}),n.d(t,"z",function(){return ce;}),n.d(t,"A",function(){return le;}),n.d(t,"B",function(){return fe;}),n.d(t,"C",function(){return pe;}),n.d(t,"D",function(){return he;}),n.d(t,"E",function(){return de;}),n.d(t,"I",function(){return me;}),n.d(t,"Ub",function(){return ge;}),n.d(t,"Ua",function(){return ye;}),n.d(t,"Va",function(){return ve;}),n.d(t,"ub",function(){return be;}),n.d(t,"Fc",function(){return we;}),n.d(t,"L",function(){return xe;}),n.d(t,"m",function(){return ke;}),n.d(t,"Xa",function(){return Oe;}),n.d(t,"Bc",function(){return Se;}),n.d(t,"Lb",function(){return Ne;}),n.d(t,"Mb",function(){return Ee;}),n.d(t,"Nb",function(){return Ie;}),n.d(t,"Ob",function(){return Te;}),n.d(t,"Pb",function(){return Ae;}),n.d(t,"Zb",function(){return Ce;}),n.d(t,"ac",function(){return Pe;}),n.d(t,"bc",function(){return _e;}),n.d(t,"cc",function(){return Re;}),n.d(t,"dc",function(){return Me;}),n.d(t,"oc",function(){return je;}),n.d(t,"f",function(){return De;}),n.d(t,"g",function(){return Le;}),n.d(t,"Oa",function(){return ze;}),n.d(t,"Wa",function(){return Fe;}),n.d(t,"ab",function(){return Be;}),n.d(t,"bb",function(){return Ve;}),n.d(t,"gb",function(){return Ue;}),n.d(t,"rc",function(){return We;}),n.d(t,"Dc",function(){return Ge;}),n.d(t,"N",function(){return qe;}),n.d(t,"O",function(){return He;}),n.d(t,"Y",function(){return Ke;}),n.d(t,"Ba",function(){return Xe;}),n.d(t,"Z",function(){return Je;}),n.d(t,"Aa",function(){return Ye;}),n.d(t,"Ea",function(){return Qe;}),n.d(t,"Ha",function(){return Ze;}),n.d(t,"Fa",function(){return $e;}),n.d(t,"Ga",function(){return et;}),n.d(t,"ob",function(){return tt;}),n.d(t,"pb",function(){return nt;}),n.d(t,"Qa",function(){return rt;}),n.d(t,"Pa",function(){return at;}),n.d(t,"Ra",function(){return it;}),n.d(t,"Sa",function(){return ot;}),n.d(t,"Gc",function(){return st;}),n.d(t,"a",function(){return ut;}),n.d(t,"b",function(){return ct;}),n.d(t,"c",function(){return lt;}),n.d(t,"h",function(){return ft;}),n.d(t,"i",function(){return pt;}),n.d(t,"j",function(){return ht;}),n.d(t,"l",function(){return dt;}),n.d(t,"u",function(){return mt;}),n.d(t,"v",function(){return gt;}),n.d(t,"F",function(){return yt;}),n.d(t,"G",function(){return vt;}),n.d(t,"M",function(){return bt;}),n.d(t,"Q",function(){return wt;}),n.d(t,"S",function(){return xt;}),n.d(t,"V",function(){return kt;}),n.d(t,"Wb",function(){return Ot;}),n.d(t,"Da",function(){return St;}),n.d(t,"La",function(){return Nt;}),n.d(t,"Ma",function(){return Et;}),n.d(t,"Na",function(){return It;}),n.d(t,"mb",function(){return Tt;}),n.d(t,"Cb",function(){return At;}),n.d(t,"Jb",function(){return Ct;}),n.d(t,"Ib",function(){return Pt;}),n.d(t,"Qb",function(){return _t;}),n.d(t,"Tb",function(){return Rt;}),n.d(t,"Vb",function(){return Mt;}),n.d(t,"Xb",function(){return jt;}),n.d(t,"Yb",function(){return Dt;}),n.d(t,"fc",function(){return Lt;}),n.d(t,"hc",function(){return zt;}),n.d(t,"Rb",function(){return Ft;}),n.d(t,"ic",function(){return Bt;}),n.d(t,"nc",function(){return Vt;}),n.d(t,"sc",function(){return Ut;}),n.d(t,"tc",function(){return Wt;}),n.d(t,"P",function(){return Gt;}),n.d(t,"d",function(){return qt;}),n.d(t,"e",function(){return Ht;}),n.d(t,"k",function(){return Kt;}),n.d(t,"J",function(){return Xt;}),n.d(t,"K",function(){return Jt;}),n.d(t,"Ya",function(){return Yt;}),n.d(t,"Za",function(){return Qt;}),n.d(t,"cb",function(){return Zt;}),n.d(t,"db",function(){return $t;}),n.d(t,"eb",function(){return en;}),n.d(t,"fb",function(){return tn;}),n.d(t,"ib",function(){return nn;}),n.d(t,"jb",function(){return rn;}),n.d(t,"Ab",function(){return an;}),n.d(t,"Bb",function(){return on;}),n.d(t,"pc",function(){return sn;}),n.d(t,"qc",function(){return un;}),n.d(t,"jc",function(){return cn;}),n.d(t,"kc",function(){return ln;}),n.d(t,"nb",function(){return fn;}),n.d(t,"t",function(){return pn;}),n.d(t,"w",function(){return hn;}),n.d(t,"W",function(){return dn;}),n.d(t,"Ac",function(){return mn;}),n.d(t,"rb",function(){return gn;}),n.d(t,"sb",function(){return yn;}),n.d(t,"Hc",function(){return vn;}),n.d(t,"Ic",function(){return bn;}),n.d(t,"T",function(){return wn;}),n.d(t,"Eb",function(){return xn;}),n.d(t,"Fb",function(){return kn;}),n.d(t,"Cc",function(){return On;}),n.d(t,"Gb",function(){return Sn;}),n.d(t,"lb",function(){return Nn;}),n.d(t,"Kb",function(){return En;}),n.d(t,"lc",function(){return In;}),n.d(t,"zc",function(){return Tn;}),n.d(t,"X",function(){return An;}),n.d(t,"qb",function(){return Cn;}),n.d(t,"Ja",function(){return Pn;}),n.d(t,"Hb",function(){return _n;}),n.d(t,"s",function(){return Rn;}),n.d(t,"U",function(){return Mn;}),n.d(t,"uc",function(){return jn;}),n.d(t,"Sb",function(){return Dn;}),n.d(t,"vc",function(){return Ln;}),n.d(t,"wc",function(){return zn;}),n.d(t,"xc",function(){return Fn;}),n.d(t,"yc",function(){return Bn;}),n.d(t,"Db",function(){return Vn;}),n.d(t,"R",function(){return Un;}),n.d(t,"mc",function(){return Wn;}),n.d(t,"Ec",function(){return Gn;}),n.d(t,"gc",function(){return qn;}),n.d(t,"H",function(){return Hn;}),n.d(t,"vb",function(){return Kn;}),n.d(t,"wb",function(){return Xn;}),n.d(t,"xb",function(){return Jn;}),n.d(t,"yb",function(){return Yn;}),n.d(t,"zb",function(){return Qn;}),n.d(t,"hb",function(){return Zn;}),n.d(t,"n",function(){return $n;}),n.d(t,"kb",function(){return er;}),n.d(t,"ec",function(){return tr;}),n.d(t,"Ka",function(){return nr;}),n.d(t,"Ia",function(){return rr;}),n.d(t,"Ta",function(){return ar;}),n.d(t,"Ca",function(){return ir;}),n.d(t,"tb",function(){return u.a;});var re=l.batchNormalization,ae=l.batchNormalization2d,ie=l.batchNormalization3d,oe=l.batchNormalization4d,se=y.a.concat,ue=y.a.concat1d,ce=y.a.concat2d,le=y.a.concat3d,fe=y.a.concat4d,pe=S.conv1d,he=S.conv2d,de=S.conv2dTranspose,me=S.depthwiseConv2d,ge=S.separableConv2d,ye=z.matMul,ve=z.matrixTimesVector,be=z.outerProduct,we=z.vectorTimesMatrix,xe=z.dot,ke=W.avgPool,Oe=W.maxPool,Se=Z.transpose,Ne=q.reverse,Ee=q.reverse1d,Ie=q.reverse2d,Te=q.reverse3d,Ae=q.reverse4d,Ce=K.slice,Pe=K.slice1d,_e=K.slice2d,Re=K.slice3d,Me=K.slice4d,je=Q.stridedSlice,De=G.a.argMax,Le=G.a.argMin,ze=G.a.logSumExp,Fe=G.a.max,Be=G.a.mean,Ve=G.a.min,Ue=G.a.moments,We=G.a.sum,Ge=G.a.unsortedSegmentSum,qe=g.equal,He=g.equalStrict,Ke=g.greater,Xe=g.greaterStrict,Je=g.greaterEqual,Ye=g.greaterEqualStrict,Qe=g.less,Ze=g.lessStrict,$e=g.lessEqual,et=g.lessEqualStrict,tt=g.notEqual,nt=g.notEqualStrict,rt=_.logicalNot,at=_.logicalAnd,it=_.logicalOr,ot=_.logicalXor,st=_.where,ut=te.abs,ct=te.acos,lt=te.acosh,ft=te.asin,pt=te.asinh,ht=te.atan,dt=te.atanh,mt=te.ceil,gt=te.clipByValue,yt=te.cos,vt=te.cosh,bt=te.elu,wt=te.exp,xt=te.expm1,kt=te.floor,Ot=te.sign,St=te.leakyRelu,Nt=te.log,Et=te.log1p,It=te.logSigmoid,Tt=te.neg,At=te.prelu,Ct=te.relu,Pt=te.reciprocal,_t=te.round,Rt=te.selu,Mt=te.sigmoid,jt=te.sin,Dt=te.sinh,Lt=te.softplus,zt=te.sqrt,Ft=te.rsqrt,Bt=te.square,Vt=te.step,Ut=te.tan,Wt=te.tanh,Gt=te.erf,qt=d.add,Ht=d.addStrict,Kt=d.atan2,Xt=d.div,Jt=d.divStrict,Yt=d.maximum,Qt=d.maximumStrict,Zt=d.minimum,$t=d.minimumStrict,en=d.mod,tn=d.modStrict,nn=d.mul,rn=d.mulStrict,an=d.pow,on=d.powStrict,sn=d.sub,un=d.subStrict,cn=d.squaredDifference,ln=d.squaredDifferenceStrict,fn=V.norm,pn=r.a.cast,hn=r.a.clone,dn=r.a.fromPixels,mn=r.a.toPixels,gn=r.a.ones,yn=r.a.onesLike,vn=r.a.zeros,bn=r.a.zerosLike,wn=r.a.eye,xn=r.a.rand,kn=r.a.randomNormal,On=r.a.truncatedNormal,Sn=r.a.randomUniform,Nn=r.a.multinomial,En=r.a.reshape,In=r.a.squeeze,Tn=r.a.tile,An=r.a.gather,Cn=r.a.oneHot,Pn=r.a.linspace,_n=r.a.range,Rn=r.a.buffer,Mn=r.a.fill,jn=r.a.tensor,Dn=r.a.scalar,Ln=r.a.tensor1d,zn=r.a.tensor2d,Fn=r.a.tensor3d,Bn=r.a.tensor4d,Vn=r.a.print,Un=r.a.expandDims,Wn=r.a.stack,Gn=r.a.unstack,qn=r.a.split,Hn=r.a.cumsum,Kn=r.a.pad,Xn=r.a.pad1d,Jn=r.a.pad2d,Yn=r.a.pad3d,Qn=r.a.pad4d,Zn=F.movingAverage,$n=D.basicLSTMCell,er=D.multiRNNCell,tr=Y.softmax,nr=M.localResponseNormalization,rr=C;ne.a,p.a,R.b;var ar={absoluteDifference:R.a.absoluteDifference,computeWeightedLoss:R.a.computeWeightedLoss,cosineDistance:R.a.cosineDistance,hingeLoss:R.a.hingeLoss,huberLoss:R.a.huberLoss,logLoss:R.a.logLoss,meanSquaredError:R.a.meanSquaredError,softmaxCrossEntropy:Y.softmaxCrossEntropy},ir={resizeBilinear:T.resizeBilinear,resizeNearestNeighbor:T.resizeNearestNeighbor};},function(e,t,n){"use strict";function r(e){return function(){for(var e=[],t=0;t<arguments.length;t++){e[t]=arguments[t];}};}n.d(t,"a",function(){return r;});},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"Type",function(){return r;}),n.d(t,"URL_PROPERTIES",function(){return c;}),n.d(t,"Environment",function(){return d;}),n.d(t,"ENV",function(){return y;});var r,a=n(241),i=n(2),o=n(227),s=n(0),u=function u(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;};!function(e){e[e.NUMBER=0]="NUMBER",e[e.BOOLEAN=1]="BOOLEAN",e[e.STRING=2]="STRING";}(r||(r={}));var c=[{name:"DEBUG",type:r.BOOLEAN},{name:"IS_BROWSER",type:r.BOOLEAN},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:r.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:r.BOOLEAN},{name:"WEBGL_VERSION",type:r.NUMBER},{name:"WEBGL_FLOAT_TEXTURE_ENABLED",type:r.BOOLEAN},{name:"WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED",type:r.BOOLEAN},{name:"BACKEND",type:r.STRING}];function l(e,t){return null!=e.getExtension(t);}function f(e){if(0===e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var t=document.createElement("canvas");return 1===e?t.getContext("webgl")||t.getContext("experimental-webgl"):t.getContext("webgl2");}function p(e){if(null!=e){var t=e.getExtension("WEBGL_lose_context");if(null==t)throw new Error("Extension WEBGL_lose_context not supported on this browser.");t.loseContext();}}function h(e){var t=f(e);return null!=t&&(p(t),!0);}var d=function(){function e(e){this.features={},this.registry={},null!=e&&(this.features=e),this.get("DEBUG")&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.");}return e.setBackend=function(e,t){if(void 0===t&&(t=!1),!(e in y.registry))throw new Error("Backend type '"+e+"' not found in registry");y.initBackend(e,t);},e.getBackend=function(){return y.initDefaultBackend(),y.currentBackend;},e.disposeVariables=function(){y.engine.disposeVariables();},e.memory=function(){return y.engine.memory();},e.prototype.get=function(e){return e in this.features?this.features[e]:(this.features[e]=this.evaluateFeature(e),this.features[e]);},e.prototype.set=function(e,t){this.features[e]=t;},e.prototype.getBestBackendType=function(){var e=this;if(0===Object.keys(this.registry).length)throw new Error("No backend found in registry.");return Object.keys(this.registry).map(function(t){return{name:t,entry:e.registry[t]};}).sort(function(e,t){return t.entry.priority-e.entry.priority;})[0].name;},e.prototype.evaluateFeature=function(e){if("DEBUG"===e)return!1;if("IS_BROWSER"===e)return"undefined"!=typeof window;if("BACKEND"===e)return this.getBestBackendType();if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"===e){var t=this.get("WEBGL_VERSION");return 0===t?0:function(e){if(0===e)return 0;var t,n=f(e);return t=l(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:l(n,"EXT_disjoint_timer_query")?1:0,null!=n&&p(n),t;}(t);}if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE"===e)return this.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!a.a();if("WEBGL_VERSION"===e)return h(2)?2:h(1)?1:0;if("WEBGL_FLOAT_TEXTURE_ENABLED"===e)return function(e){if(0===e)return!1;var t=f(e);if(1===e){if(!l(t,"OES_texture_float"))return!1;}else if(!l(t,"EXT_color_buffer_float"))return!1;var n=t.createFramebuffer(),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);var a=2===e?t.RGBA32F:t.RGBA;t.texImage2D(t.TEXTURE_2D,0,a,1,1,0,t.RGBA,t.FLOAT,null),t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var i=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;t.readPixels(0,0,1,1,t.RGBA,t.FLOAT,new Float32Array(4));var o=t.getError()===t.NO_ERROR;return p(t),i&&o;}(this.get("WEBGL_VERSION"));if("WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED"===e)return function(e){if(e>0)return!1;if(2!==e)return!1;var t=f(e),n=l(t,"WEBGL_get_buffer_sub_data_async");return p(t),n;}(this.get("WEBGL_VERSION"));throw new Error("Unknown feature "+e+".");},e.prototype.setFeatures=function(e){this.features=e;},e.prototype.reset=function(){this.features=g(),null!=this.globalEngine&&(this.globalEngine.dispose(),this.globalEngine=null);},e.prototype.initBackend=function(e,t){void 0===t&&(t=!1),this.currentBackend=e,null!=this.globalEngine&&this.globalEngine.dispose();var n=y.findBackend(e);this.globalEngine=new o.a(n,t);},e.prototype.findBackend=function(e){return e in this.registry?this.registry[e].backend:null;},e.prototype.registerBackend=function(e,t,n){void 0===n&&(n=1),e in this.registry&&console.warn(e+" backend was already registered");try{var r=t();return this.registry[e]={backend:r,priority:n},!0;}catch(e){return console.warn(e.message),!1;}},e.prototype.removeBackend=function(e){if(!(e in this.registry))throw new Error(e+" backend not found in registry");this.registry[e].backend.dispose(),delete this.registry[e];},Object.defineProperty(e.prototype,"engine",{get:function get(){return this.initDefaultBackend(),this.globalEngine;},enumerable:!0,configurable:!0}),e.prototype.initDefaultBackend=function(){null==this.globalEngine&&this.initBackend(y.get("BACKEND"),!1);},u([Object(i.a)({heading:"Environment"})],e,"setBackend",null),u([Object(i.a)({heading:"Environment"})],e,"getBackend",null),u([Object(i.a)({heading:"Environment"})],e,"disposeVariables",null),u([Object(i.a)({heading:"Performance",subheading:"Memory"})],e,"memory",null),e;}(),m="tfjsflags";function g(){var e={};if("undefined"==typeof window||void 0===window.location)return e;var t=s.getQueryParams(window.location.search);if(m in t){var n={};t[m].split(",").forEach(function(e){var t=e.split(":"),r=t[0],a=t[1];n[r]=a;}),c.forEach(function(t){t.name in n&&(console.log("Setting feature override from URL "+t.name+": "+n[t.name]),t.type===r.NUMBER?e[t.name]=+n[t.name]:t.type===r.BOOLEAN?e[t.name]="true"===n[t.name]:t.type===r.STRING?e[t.name]=n[t.name]:console.warn("Unknown URL param: "+t.name+"."));});}return e;}var y=function(){var t=function(){var t;if("undefined"!=typeof window)t=window;else{if(void 0===e)throw new Error("Could not find a global object");t=e;}return t;}();return t.ENV=t.ENV||new d(g()),t.ENV;}();}.call(this,n(101));},function(e,t,n){"use strict";n.d(t,"a",function(){return a;});var r=n(7);function a(e,t,n){var a=n.value;return n.value=function(){for(var e=[],n=0;n<arguments.length;n++){e[n]=arguments[n];}return Object(r.f)(t,function(){return a.apply(void 0,e);});},n;}},function(e,t,n){var r=n(13),a=n(43),i=n(28),o=n(27),s=n(42),u=function u(e,t,n){var c,l,f,p,h=e&u.F,d=e&u.G,m=e&u.S,g=e&u.P,y=e&u.B,v=d?r:m?r[t]||(r[t]={}):(r[t]||{}).prototype,b=d?a:a[t]||(a[t]={}),w=b.prototype||(b.prototype={});for(c in d&&(n=t),n){f=((l=!h&&v&&void 0!==v[c])?v:n)[c],p=y&&l?s(f,r):g&&"function"==typeof f?s(Function.call,f):f,v&&o(v,c,f,e&u.U),b[c]!=f&&i(b,c,p),g&&w[c]!=f&&(w[c]=f);}};r.core=a,u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,e.exports=u;},function(e,t,n){"use strict";n.d(t,"b",function(){return l;}),n.d(t,"a",function(){return f;}),n.d(t,"c",function(){return p;}),n.d(t,"d",function(){return h;});var r=n(2),a=n(3),i=n(1),o=n(123),s=n(0),u=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),c=function c(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},l=function(){function e(e,t,n){if(this.dtype=t,null!=n){var r=n.length,a=s.sizeFromShape(e);s.assert(r===a,"Length of values '"+r+"' does not match the size inferred by the shape '"+a+"'");}this.shape=e.slice(),this.values=n||s.getTypedArrayFromDType(t,s.sizeFromShape(e)),this.strides=d(e),this.size=s.sizeFromShape(e);}return e.prototype.set=function(e){for(var t=[],n=1;n<arguments.length;n++){t[n-1]=arguments[n];}0===t.length&&(t=[0]),s.assert(t.length===this.rank,"The number of provided coordinates ("+t.length+") must match the rank ("+this.rank+")");var r=this.locToIndex(t);this.values[r]=e;},e.prototype.get=function(){for(var e=[],t=0;t<arguments.length;t++){e[t]=arguments[t];}0===e.length&&(e=[0]);for(var n=e[e.length-1],r=0;r<e.length-1;++r){n+=this.strides[r]*e[r];}return this.values[n];},e.prototype.locToIndex=function(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];for(var t=e[e.length-1],n=0;n<e.length-1;++n){t+=this.strides[n]*e[n];}return t;},e.prototype.indexToLoc=function(e){if(0===this.rank)return[];if(1===this.rank)return[e];for(var t=new Array(this.shape.length),n=0;n<t.length-1;++n){t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];}return t[t.length-1]=e,t;},Object.defineProperty(e.prototype,"rank",{get:function get(){return this.shape.length;},enumerable:!0,configurable:!0}),e.prototype.toTensor=function(){return f.make(this.shape,{values:this.values},this.dtype);},c([Object(r.a)({heading:"Tensors",subheading:"Creation"})],e.prototype,"set",null),c([Object(r.a)({heading:"Tensors",subheading:"Creation"})],e.prototype,"get",null),c([Object(r.a)({heading:"Tensors",subheading:"Creation"})],e.prototype,"toTensor",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e);}(),f=function(){function e(e,n,r,i){this.isDisposed=!1,this.size=s.sizeFromShape(e),null!=r&&s.assert(this.size===r.length,"Constructing tensor of shape ("+this.size+") should match the length of values ("+r.length+")"),this.shape=e.slice(),this.dtype=n||"float32",this.strides=d(e),this.dataId=null!=i?i:{},this.id=t.nextId++,this.rankType=this.rank<5?this.rank.toString():"higher",a.ENV.engine.registerTensor(this),null!=r&&a.ENV.engine.write(this.dataId,r);}return t=e,e.make=function(e,n,r){return new t(e,r,n.values,n.dataId);},e.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D();},e.prototype.asScalar=function(){return this.throwIfDisposed(),s.assert(1===this.size,"The array must have only 1 element."),this.reshape([]);},e.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size]);},e.prototype.as2D=function(e,t){return this.throwIfDisposed(),this.reshape([e,t]);},e.prototype.as3D=function(e,t,n){return this.throwIfDisposed(),this.reshape([e,t,n]);},e.prototype.as4D=function(e,t,n,r){return this.throwIfDisposed(),this.reshape([e,t,n,r]);},e.prototype.asType=function(e){return this.throwIfDisposed(),i.t(this,e);},Object.defineProperty(e.prototype,"rank",{get:function get(){return this.shape.length;},enumerable:!0,configurable:!0}),e.prototype.get=function(){for(var e=[],t=0;t<arguments.length;t++){e[t]=arguments[t];}s.assert(e.length===this.rank,"Number of coordinates in get() must match the rank of the tensor"),this.throwIfDisposed(),0===e.length&&(e=[0]);for(var n=e[e.length-1],r=0;r<e.length-1;++r){n+=this.strides[r]*e[r];}return this.dataSync()[n];},e.prototype.buffer=function(){return i.s(this.shape,this.dtype,this.dataSync());},e.prototype.data=function(){return function(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});}(this,void 0,void 0,function(){return function(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}}(this,function(e){return this.throwIfDisposed(),[2,a.ENV.engine.read(this.dataId)];});});},e.prototype.dataSync=function(){return this.throwIfDisposed(),a.ENV.engine.readSync(this.dataId);},e.prototype.dispose=function(){this.isDisposed||(this.isDisposed=!0,a.ENV.engine.disposeTensor(this));},e.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.");},e.prototype.toFloat=function(){return this.asType("float32");},e.prototype.toInt=function(){return this.asType("int32");},e.prototype.toBool=function(){return this.asType("bool");},e.prototype.print=function(e){return void 0===e&&(e=!1),i.Db(this,e);},e.prototype.reshape=function(e){return this.throwIfDisposed(),i.Kb(this,e);},e.prototype.reshapeAs=function(e){return this.throwIfDisposed(),this.reshape(e.shape);},e.prototype.expandDims=function(e){return void 0===e&&(e=0),i.R(this,e);},e.prototype.cumsum=function(e,t,n){return void 0===e&&(e=0),void 0===t&&(t=!1),void 0===n&&(n=!1),i.H(this,e,t,n);},e.prototype.squeeze=function(e){return this.throwIfDisposed(),i.lc(this,e);},e.prototype.clone=function(){return this.throwIfDisposed(),i.w(this);},e.prototype.toString=function(e){return void 0===e&&(e=!1),o.a(this,e);},e.prototype.tile=function(e){return this.throwIfDisposed(),i.zc(this,e);},e.prototype.gather=function(e,t){return void 0===t&&(t=0),this.throwIfDisposed(),i.X(this,e,t);},e.prototype.matMul=function(e,t,n){return void 0===t&&(t=!1),void 0===n&&(n=!1),this.throwIfDisposed(),i.Ua(this,e,t,n);},e.prototype.dot=function(e){return this.throwIfDisposed(),i.L(this,e);},e.prototype.norm=function(e,t,n){return void 0===e&&(e="euclidean"),void 0===t&&(t=null),void 0===n&&(n=!1),this.throwIfDisposed(),i.nb(this,e,t,n);},e.prototype.slice=function(e,t){return this.throwIfDisposed(),i.Zb(this,e,t);},e.prototype.reverse=function(e){return this.throwIfDisposed(),i.Lb(this,e);},e.prototype.concat=function(e,t){return void 0===t&&(t=0),this.throwIfDisposed(),i.x([this,e],t);},e.prototype.stack=function(e,t){return void 0===t&&(t=0),i.mc([this,e],t);},e.prototype.unstack=function(e,t){return void 0===t&&(t=0),i.Ec(this,t);},e.prototype.pad=function(e,t){return void 0===t&&(t=0),i.vb(this,e,t);},e.prototype.batchNormalization=function(e,t,n,r,a){return void 0===n&&(n=.001),this.throwIfDisposed(),i.o(this,e,t,n,r,a);},e.prototype.logSumExp=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),i.Oa(this,e,t);},e.prototype.sum=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),i.rc(this,e,t);},e.prototype.mean=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),i.ab(this,e,t);},e.prototype.min=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),i.bb(this,e,t);},e.prototype.max=function(e,t){return void 0===e&&(e=null),void 0===t&&(t=!1),this.throwIfDisposed(),i.Wa(this,e,t);},e.prototype.argMin=function(e){return void 0===e&&(e=null),this.throwIfDisposed(),i.g(this,e);},e.prototype.argMax=function(e){return void 0===e&&(e=null),this.throwIfDisposed(),i.f(this,e);},e.prototype.cast=function(e){return this.throwIfDisposed(),i.t(this,e);},e.prototype.add=function(e){return this.throwIfDisposed(),i.d(this,e);},e.prototype.addStrict=function(e){return this.throwIfDisposed(),i.e(this,e);},e.prototype.sub=function(e){return this.throwIfDisposed(),i.pc(this,e);},e.prototype.subStrict=function(e){return this.throwIfDisposed(),i.qc(this,e);},e.prototype.pow=function(e){return this.throwIfDisposed(),i.Ab(this,e);},e.prototype.powStrict=function(e){return this.throwIfDisposed(),i.Bb(this,e);},e.prototype.mul=function(e){return this.throwIfDisposed(),i.ib(this,e);},e.prototype.mulStrict=function(e){return this.throwIfDisposed(),i.jb(this,e);},e.prototype.div=function(e){return this.throwIfDisposed(),i.J(this,e);},e.prototype.divStrict=function(e){return this.throwIfDisposed(),i.K(this,e);},e.prototype.minimum=function(e){return this.throwIfDisposed(),i.cb(this,e);},e.prototype.minimumStrict=function(e){return this.throwIfDisposed(),i.db(this,e);},e.prototype.maximum=function(e){return this.throwIfDisposed(),i.Ya(this,e);},e.prototype.maximumStrict=function(e){return this.throwIfDisposed(),i.Za(this,e);},e.prototype.mod=function(e){return this.throwIfDisposed(),i.eb(this,e);},e.prototype.modStrict=function(e){return this.throwIfDisposed(),i.fb(this,e);},e.prototype.squaredDifference=function(e){return this.throwIfDisposed(),i.jc(this,e);},e.prototype.squaredDifferenceStrict=function(e){return this.throwIfDisposed(),i.kc(this,e);},e.prototype.transpose=function(e){return this.throwIfDisposed(),i.Bc(this,e);},e.prototype.notEqual=function(e){return this.throwIfDisposed(),i.ob(this,e);},e.prototype.notEqualStrict=function(e){return this.throwIfDisposed(),i.pb(this,e);},e.prototype.less=function(e){return this.throwIfDisposed(),i.Ea(this,e);},e.prototype.lessStrict=function(e){return this.throwIfDisposed(),i.Ha(this,e);},e.prototype.equal=function(e){return this.throwIfDisposed(),i.N(this,e);},e.prototype.equalStrict=function(e){return this.throwIfDisposed(),i.O(this,e);},e.prototype.lessEqual=function(e){return this.throwIfDisposed(),i.Fa(this,e);},e.prototype.lessEqualStrict=function(e){return this.throwIfDisposed(),i.Ga(this,e);},e.prototype.greater=function(e){return this.throwIfDisposed(),i.Y(this,e);},e.prototype.greaterStrict=function(e){return this.throwIfDisposed(),i.Ba(this,e);},e.prototype.greaterEqual=function(e){return this.throwIfDisposed(),i.Z(this,e);},e.prototype.greaterEqualStrict=function(e){return this.throwIfDisposed(),i.Aa(this,e);},e.prototype.logicalAnd=function(e){return this.throwIfDisposed(),i.Pa(this,e);},e.prototype.logicalOr=function(e){return this.throwIfDisposed(),i.Ra(this,e);},e.prototype.logicalNot=function(){return this.throwIfDisposed(),i.Qa(this);},e.prototype.logicalXor=function(e){return this.throwIfDisposed(),i.Sa(this,e);},e.prototype.where=function(e,t){return this.throwIfDisposed(),i.Gc(e,this,t);},e.prototype.neg=function(){return this.throwIfDisposed(),i.mb(this);},e.prototype.ceil=function(){return this.throwIfDisposed(),i.u(this);},e.prototype.floor=function(){return this.throwIfDisposed(),i.V(this);},e.prototype.sign=function(){return this.throwIfDisposed(),i.Wb(this);},e.prototype.exp=function(){return this.throwIfDisposed(),i.Q(this);},e.prototype.expm1=function(){return this.throwIfDisposed(),i.S(this);},e.prototype.log=function(){return this.throwIfDisposed(),i.La(this);},e.prototype.log1p=function(){return this.throwIfDisposed(),i.Ma(this);},e.prototype.sqrt=function(){return this.throwIfDisposed(),i.hc(this);},e.prototype.rsqrt=function(){return this.throwIfDisposed(),i.Rb(this);},e.prototype.square=function(){return this.throwIfDisposed(),i.ic(this);},e.prototype.reciprocal=function(){return this.throwIfDisposed(),i.Ib(this);},e.prototype.abs=function(){return this.throwIfDisposed(),i.a(this);},e.prototype.clipByValue=function(e,t){return this.throwIfDisposed(),i.v(this,e,t);},e.prototype.relu=function(){return this.throwIfDisposed(),i.Jb(this);},e.prototype.elu=function(){return this.throwIfDisposed(),i.M(this);},e.prototype.selu=function(){return this.throwIfDisposed(),i.Tb(this);},e.prototype.leakyRelu=function(e){return void 0===e&&(e=.2),this.throwIfDisposed(),i.Da(this,e);},e.prototype.prelu=function(e){return this.throwIfDisposed(),i.Cb(this,e);},e.prototype.sigmoid=function(){return this.throwIfDisposed(),i.Vb(this);},e.prototype.logSigmoid=function(){return this.throwIfDisposed(),i.Na(this);},e.prototype.softplus=function(){return this.throwIfDisposed(),i.fc(this);},e.prototype.sin=function(){return this.throwIfDisposed(),i.Xb(this);},e.prototype.cos=function(){return this.throwIfDisposed(),i.F(this);},e.prototype.tan=function(){return this.throwIfDisposed(),i.sc(this);},e.prototype.asin=function(){return this.throwIfDisposed(),i.h(this);},e.prototype.acos=function(){return this.throwIfDisposed(),i.b(this);},e.prototype.atan=function(){return this.throwIfDisposed(),i.j(this);},e.prototype.sinh=function(){return this.throwIfDisposed(),i.Yb(this);},e.prototype.cosh=function(){return this.throwIfDisposed(),i.G(this);},e.prototype.tanh=function(){return this.throwIfDisposed(),i.tc(this);},e.prototype.asinh=function(){return this.throwIfDisposed(),i.i(this);},e.prototype.acosh=function(){return this.throwIfDisposed(),i.c(this);},e.prototype.atanh=function(){return this.throwIfDisposed(),i.l(this);},e.prototype.erf=function(){return this.throwIfDisposed(),i.P(this);},e.prototype.round=function(){return this.throwIfDisposed(),i.Qb(this);},e.prototype.step=function(e){return void 0===e&&(e=0),this.throwIfDisposed(),i.nc(this,e);},e.prototype.softmax=function(e){return void 0===e&&(e=-1),this.throwIfDisposed(),i.ec(this,e);},e.prototype.resizeBilinear=function(e,t){return void 0===t&&(t=!1),this.throwIfDisposed(),i.Ca.resizeBilinear(this,e,t);},e.prototype.resizeNearestNeighbor=function(e,t){return void 0===t&&(t=!1),this.throwIfDisposed(),i.Ca.resizeNearestNeighbor(this,e,t);},e.prototype.conv1d=function(e,t,n,r,a,o){return void 0===r&&(r="NWC"),void 0===a&&(a=1),this.throwIfDisposed(),i.C(this,e,t,n,r,a,o);},e.prototype.conv2d=function(e,t,n,r,a,o){return void 0===r&&(r="NHWC"),void 0===a&&(a=[1,1]),this.throwIfDisposed(),i.D(this,e,t,n,r,a,o);},e.prototype.conv2dTranspose=function(e,t,n,r,a){return this.throwIfDisposed(),i.E(this,e,t,n,r,a);},e.prototype.depthwiseConv2D=function(e,t,n,r,a,o){return void 0===r&&(r="NHWC"),void 0===a&&(a=[1,1]),this.throwIfDisposed(),i.I(this,e,t,n,r,a,o);},e.prototype.avgPool=function(e,t,n,r){return this.throwIfDisposed(),i.m(this,e,t,n,r);},e.prototype.maxPool=function(e,t,n,r){return this.throwIfDisposed(),i.Xa(this,e,t,n,r);},e.prototype.localResponseNormalization=function(e,t,n,r){return void 0===e&&(e=5),void 0===t&&(t=1),void 0===n&&(n=1),void 0===r&&(r=.5),i.Ka(this,e,t,n,r);},e.prototype.variable=function(e,t,n){return void 0===e&&(e=!0),this.throwIfDisposed(),p.variable(this,e,t,n);},e.prototype.unsortedSegmentSum=function(e,t,n){return void 0===n&&(n=0),this.throwIfDisposed(),i.Dc(this,e,t,n);},e.nextId=0,c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"flatten",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"asScalar",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"as1D",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"as2D",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"as3D",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"as4D",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"asType",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"buffer",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"data",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"dataSync",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"dispose",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"toFloat",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"toInt",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"toBool",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"print",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"reshape",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"reshapeAs",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"expandDims",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"cumsum",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"squeeze",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"clone",null),c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e.prototype,"toString",null),t=c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],e);var t;}(),p=function(e){function t(t,r,i){void 0===r&&(r=!0);var o=e.call(this,t.shape,t.dtype,null,t.dataId)||this;return o.trainable=r,o.name=i,null==o.name&&(o.name=n.nextVarId.toString(),n.nextVarId++),a.ENV.engine.registerVariable(o),o;}return u(t,e),n=t,t.variable=function(e,t,r,a){return void 0===t&&(t=!0),null!=a&&a!==e.dtype&&(e=e.asType(a)),new n(e,t,r);},t.prototype.assign=function(e){if(e.dtype!==this.dtype)throw new Error("dtype of the new value ("+e.dtype+") and previous value ("+this.dtype+") must match");if(!s.arraysEqual(e.shape,this.shape))throw new Error("shape of the new value ("+e.shape+") and previous value ("+this.shape+") must match");a.ENV.engine.disposeTensor(this),this.dataId=e.dataId,a.ENV.engine.registerTensor(this);},t.nextVarId=0,c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],t.prototype,"assign",null),c([Object(r.a)({heading:"Tensors",subheading:"Creation"})],t,"variable",null),n=c([Object(r.a)({heading:"Tensors",subheading:"Classes"})],t);var n;}(f),h=p.variable;function d(e){var t=e.length;if(t<2)return[];var n=new Array(t-1);n[t-2]=e[t-1];for(var r=t-3;r>=0;--r){n[r]=n[r+1]*e[r+1];}return n;}},function(e,t,n){"use strict";var r=n(2),a=n(3),i=n(6),o=n(0),s=function s(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},u=function(){function e(){}return e.gradScope=function(e,t){return f(e,t,!0);},e.grad=function(e){return o.assert(o.isFunction(e),"The f passed in grad(f) must be a function"),function(t,n){return o.assert(t instanceof i.a,"The x passed in grad(f)(x) must be a tensor"),o.assert(null==n||n instanceof i.a,"The dy passed in grad(f)(x, dy) must be a tensor"),f(function(){var r=a.ENV.engine.gradients(function(){return e(t);},[t],n),i=r.value,s=r.grads;return null!=n&&o.assertShapesMatch(i.shape,n.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),c(s),s[0];});};},e.grads=function(e){return o.assert(o.isFunction(e),"The f passed in grads(f) must be a function"),function(t,n){return o.assert(Array.isArray(t)&&t.every(function(e){return e instanceof i.a;}),"The args passed in grads(f)(args) must be an array of tensors"),o.assert(null==n||n instanceof i.a,"The dy passed in grads(f)(args, dy) must be a tensor"),f(function(){var r=a.ENV.engine.gradients(function(){return e.apply(void 0,t);},t,n),i=r.value,s=r.grads;return null!=n&&o.assertShapesMatch(i.shape,n.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),c(s),s;});};},e.valueAndGrad=function(e){return o.assert(o.isFunction(e),"The f passed in valueAndGrad(f) must be a function"),function(t,n){o.assert(t instanceof i.a,"The x passed in valueAndGrad(f)(x) must be a tensor"),o.assert(null==n||n instanceof i.a,"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");var r=a.ENV.engine.gradients(function(){return e(t);},[t],n),s=r.grads,u=r.value;return c(s),{grad:s[0],value:u};};},e.valueAndGrads=function(e){return o.assert(o.isFunction(e),"The f passed in valueAndGrads(f) must be a function"),function(t,n){o.assert(Array.isArray(t)&&t.every(function(e){return e instanceof i.a;}),"The args passed in valueAndGrads(f)(args) must be array of tensors"),o.assert(null==n||n instanceof i.a,"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");var r=a.ENV.engine.gradients(function(){return e.apply(void 0,t);},t,n);return null!=n&&o.assertShapesMatch(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),c(r.grads),r;};},e.variableGrads=function(e,t){if(o.assert(o.isFunction(e),"The f passed in variableGrads(f) must be a function"),o.assert(null==t||Array.isArray(t)&&t.every(function(e){return e instanceof i.c;}),"The varList passed in variableGrads(f, varList) must be an array of variables"),null==t)for(var n in t=[],a.ENV.engine.registeredVariables){t.push(a.ENV.engine.registeredVariables[n]);}var r=t.length;t=t.filter(function(e){return e.trainable;}),o.assert(t.length>0,"variableGrads() expects at least one of the input variables to be trainable, but none of the "+r+" variables is trainable.");var s=a.ENV.engine.gradients(e,t,null,!0),u=s.value,c=s.grads;o.assert(c.some(function(e){return null!=e;}),"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),o.assert(0===u.rank,"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+u.rank+" tensor");var l={};return t.forEach(function(e,t){null!=c[t]&&(l[e.name]=c[t]);}),{value:u,grads:l};},e.customGrad=function(e){return a.ENV.engine.customGrad(e);},s([Object(r.a)({heading:"Training",subheading:"Gradients"})],e,"grad",null),s([Object(r.a)({heading:"Training",subheading:"Gradients"})],e,"grads",null),s([Object(r.a)({heading:"Training",subheading:"Gradients"})],e,"valueAndGrad",null),s([Object(r.a)({heading:"Training",subheading:"Gradients"})],e,"valueAndGrads",null),s([Object(r.a)({heading:"Training",subheading:"Gradients"})],e,"variableGrads",null),s([Object(r.a)({heading:"Training",subheading:"Gradients"})],e,"customGrad",null),e;}();function c(e){if(e.filter(function(e){return null==e;}).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.");}var l=n(80);n.d(t,"f",function(){return f;}),n.d(t,"e",function(){return p;}),n.d(t,"b",function(){return h;}),n.d(t,"g",function(){return d;}),n.d(t,"c",function(){return m;}),n.d(t,"h",function(){return g;}),n.d(t,"d",function(){return y;}),n.d(t,"i",function(){return v;}),n.d(t,"j",function(){return b;}),n.d(t,"a",function(){return w;});var f=l.a.tidy,p=l.a.keep,h=l.a.dispose,d=l.a.time,m=u.grad,g=u.valueAndGrad,y=u.grads,v=u.valueAndGrads,b=u.variableGrads,w=u.customGrad;},function(e,t,n){"use strict";n.d(t,"b",function(){return i;}),n.d(t,"c",function(){return o;}),n.d(t,"g",function(){return s;}),n.d(t,"a",function(){return u;}),n.d(t,"d",function(){return c;}),n.d(t,"f",function(){return l;}),n.d(t,"e",function(){return f;});var r=n(0);function a(e,t){for(var n=0;n<e.length;++n){if(e[e.length-n-1]!==t-1-n)return!1;}return!0;}function i(e,t){for(var n=[],r=e.length,a=0;a<r;a++){-1===t.indexOf(a)&&n.push(e[a]);}return[n,t.map(function(t){return e[t];})];}function o(e,t){return function(e,t,n){for(var r=e.length+t.length,a=[],i=0,o=0,s=0;s<r;s++){-1===n.indexOf(s)?a.push(e[i++]):a.push(t[o++]);}return a;}(e,t.map(function(e){return 1;}),t);}function s(e,t){var n=t.length;return e=null==e?t.map(function(e,t){return t;}):[].concat(e),r.assert(e.every(function(e){return e>=-n&&e<n;}),"All values in axis param must be in range [-"+n+", "+n+") but got axis "+e),r.assert(e.every(function(e){return r.isInt(e);}),"All values in axis param must be integers but got axis "+e),e.map(function(e){return e<0?n+e:e;});}function u(e,t,n){r.assert(a(t,n),e+" supports only inner-most axes for now. Got axes "+t+" and rank-"+n+" input.");}function c(e,t){if(a(e,t))return null;for(var n=[],r=0;r<t;++r){-1===e.indexOf(r)&&n.push(r);}return e.forEach(function(e){return n.push(e);}),n;}function l(e){return e.map(function(e,t){return[t,e];}).sort(function(e,t){return e[1]-t[1];}).map(function(e){return e[0];});}function f(e,t){for(var n=[],r=t-e;r<t;++r){n.push(r);}return n;}},function(e,t,n){"use strict";var r=n(2),a=n(3),i=n(6),o=n(123),s=n(0),u=n(8),c=n(63),l=n(4),f=n(122),p=function(){function e(e,t,n,r,a){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var i=a||Math.random();this.random=f.alea(i.toString());}return e.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var e=this.nextVal;return this.nextVal=NaN,e;}for(var t,n,r=!1;!r;){var a=void 0,i=void 0,o=void 0;do{o=(a=2*this.random()-1)*a+(i=2*this.random()-1)*i;}while(o>=1||0===o);var s=Math.sqrt(-2*Math.log(o)/o);t=this.mean+this.stdDev*a*s,n=this.mean+this.stdDev*i*s,this.truncated&&!this.isValidTruncated(t)||(r=!0);}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(t);},e.prototype.convertValue=function(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e);},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower;},e;}(),h=n(39);n.d(t,"a",function(){return m;});var d=function d(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},m=function(){function e(){}return e.tensor=function(e,t,n){void 0===n&&(n="float32");var r=s.inferShape(e);return null!=t&&1!==r.length&&s.assertShapesMatch(t,r,"Error creating a new Tensor. Inferred shape ("+r+") does not match the provided shape ("+t+"). "),s.isTypedArray(e)||Array.isArray(e)||(e=[e]),t=t||r,i.a.make(t,{values:function(e,t){return function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t;}(e,t)?e:(Array.isArray(e)&&(e=s.flatten(e)),s.copyTypedArray(e,t));}(e,n)},n);},e.scalar=function(t,n){if(void 0===n&&(n="float32"),s.isTypedArray(t)||Array.isArray(t))throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean)");return e.tensor(t,[],n);},e.tensor1d=function(t,n){void 0===n&&(n="float32");var r=s.inferShape(t);if(1!==r.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return e.tensor(t,r,n);},e.tensor2d=function(t,n,r){if(void 0===r&&(r="float32"),null!=n&&2!==n.length)throw new Error("tensor2d() requires shape to have two numbers");var a=s.inferShape(t);if(2!==a.length&&1!==a.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===a.length&&null==n)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return n=n||a,e.tensor(t,n,r);},e.tensor3d=function(t,n,r){if(void 0===r&&(r="float32"),null!=n&&3!==n.length)throw new Error("tensor3d() requires shape to have three numbers");var a=s.inferShape(t);if(3!==a.length&&1!==a.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===a.length&&null==n)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return n=n||a,e.tensor(t,n,r);},e.tensor4d=function(t,n,r){if(void 0===r&&(r="float32"),null!=n&&4!==n.length)throw new Error("tensor4d() requires shape to have four numbers");var a=s.inferShape(t);if(4!==a.length&&1!==a.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===a.length&&null==n)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return n=n||a,e.tensor(t,n,r);},e.ones=function(e,t){void 0===t&&(t="float32");var n=function(e,t){for(var n=g(e,t),r=0;r<n.length;r++){n[r]=1;}return n;}(s.sizeFromShape(e),t);return i.a.make(e,{values:n},t);},e.zeros=function(e,t){void 0===t&&(t="float32");var n=g(s.sizeFromShape(e),t);return i.a.make(e,{values:n},t);},e.fill=function(e,t,n){void 0===n&&(n="float32");var r=s.getTypedArrayFromDType(n,s.sizeFromShape(e));return r.fill(t),i.a.make(e,{values:r},n);},e.onesLike=function(t){return s.assertArgumentsAreTensors({x:t},"onesLike"),e.ones(t.shape,t.dtype);},e.zerosLike=function(t){return s.assertArgumentsAreTensors({x:t},"zerosLike"),e.zeros(t.shape,t.dtype);},e.clone=function(e){return s.assertArgumentsAreTensors({x:e},"clone"),a.ENV.engine.runKernel(function(t){return i.a.make(e.shape,{dataId:e.dataId},e.dtype);},{x:e},function(e){return{x:function x(){return e.toFloat();}};});},e.eye=function(t,n,r,a){void 0===a&&(a="float32"),null==n&&(n=t);for(var i=e.buffer([t,n],a),o=t<=n?t:n,s=0;s<o;++s){i.set(1,s,s);}var u=i.toTensor().as2D(t,n);if(null==r)return u;if(1===r.length)return e.tile(e.expandDims(u,0),[r[0],1,1]);if(2===r.length)return e.tile(e.expandDims(e.expandDims(u,0),0),[r[0],r[1],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+r.length+"D.");},e.randomNormal=function(t,n,r,a,i){if(void 0===n&&(n=0),void 0===r&&(r=1),null!=a&&"bool"===a)throw new Error("Unsupported data type "+a);for(var o=new p(n,r,a,!1,i),s=e.buffer(t,a),u=0;u<s.values.length;u++){s.values[u]=o.nextValue();}return s.toTensor();},e.truncatedNormal=function(t,n,r,a,i){if(void 0===n&&(n=0),void 0===r&&(r=1),null!=a&&"bool"===a)throw new Error("Unsupported data type "+a);for(var o=new p(n,r,a,!0,i),s=e.buffer(t,a),u=0;u<s.values.length;u++){s.values[u]=o.nextValue();}return s.toTensor();},e.randomUniform=function(t,n,r,a){void 0===n&&(n=0),void 0===r&&(r=1),void 0===a&&(a="float32");for(var i=e.buffer(t,a),o=0;o<i.values.length;o++){i.values[o]=s.randUniform(n,r);}return i.toTensor();},e.rand=function(e,t,n){var r=s.sizeFromShape(e),a=null;if(null==n||"float32"===n)a=new Float32Array(r);else if("int32"===n)a=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);a=new Uint8Array(r);}for(var o=0;o<r;o++){a[o]=t();}return i.a.make(e,{values:a},n);},e.multinomial=function(e,t,n,r){void 0===r&&(r=!1),s.assertArgumentsAreTensors({logits:e},"multinomial");var i=e.size,o=e.rank;if(i<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+i+".");if(o>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+o);n=n||Math.random();var u=1===o?e.as2D(1,-1):e,c=a.ENV.engine.runKernel(function(e){return e.multinomial(u,r,t,n);},{logits2D:u});return 1===o?c.as1D():c;},e.oneHot=function(e,t,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),s.assert("int32"===e.dtype,"Indices must be of dtype `int32`"),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);return a.ENV.engine.runKernel(function(a){return a.oneHot(e,t,n,r);},{indices:e});},e.fromPixels=function(e,t){if(void 0===t&&(t=3),t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return a.ENV.engine.fromPixels(e,t);},e.toPixels=function(e,t){return function(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});}(this,void 0,void 0,function(){var n,r,a,i,o,u,c,l,f,p,h,d,m,g,y,v,b,w,x;return function(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}}(this,function(k){switch(k.label){case 0:if(s.assertArgumentsAreTensors({img:e},"toPixels"),2!==e.rank&&3!==e.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+e.rank+".");if(n=e.shape.slice(0,2),r=n[0],a=n[1],(i=2===e.rank?1:e.shape[2])>4||2===i)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+i);return o=e.min(),u=e.max(),[4,o.data()];case 1:return c=k.sent()[0],[4,u.data()];case 2:if(l=k.sent()[0],o.dispose(),u.dispose(),"float32"===e.dtype){if(c<0||l>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+c+" - "+l+"].");}else{if("int32"!==e.dtype)throw new Error("Unsupported type for toPixels: "+e.dtype+". Please use float32 or int32 tensors.");if(c<0||l>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+c+" - "+l+"].");}return[4,e.data()];case 3:for(f=k.sent(),p="float32"===e.dtype?255:1,h=new Uint8ClampedArray(a*r*4),d=0;d<r*a;++d){m=void 0,g=void 0,y=void 0,v=void 0,1===i?(m=f[d]*p,g=f[d]*p,y=f[d]*p,v=255):3===i?(m=f[3*d]*p,g=f[3*d+1]*p,y=f[3*d+2]*p,v=255):4===i&&(m=f[4*d]*p,g=f[4*d+1]*p,y=f[4*d+2]*p,v=f[4*d+3]*p),h[0+(b=4*d)]=Math.round(m),h[b+1]=Math.round(g),h[b+2]=Math.round(y),h[b+3]=Math.round(v);}return null!=t&&(t.width=a,t.height=r,w=t.getContext("2d"),x=new ImageData(h,a,r),w.putImageData(x,0,0)),[2,h];}});});},e.reshape=function(e,t){return s.assertArgumentsAreTensors({x:e},"reshape"),t=s.inferFromImplicitShape(t,e.size),s.assert(e.size===s.sizeFromShape(t),"new shape and old shape must have the same number of elements."),a.ENV.engine.runKernel(function(n){return n.reshape(e,t);},{x:e},function(t){return{x:function x(){return t.reshape(e.shape);}};});},e.squeeze=function(t,n){return s.assertArgumentsAreTensors({x:t},"squeeze"),e.reshape(t,s.squeezeShape(t.shape,n).newShape);},e.cast=function(e,t){return s.assertArgumentsAreTensors({x:e},"cast"),a.ENV.engine.runKernel(function(n){return n.cast(e,t);},{x:e},function(e){return{x:function x(){return e.clone();}};});},e.tile=function(t,n){return s.assertArgumentsAreTensors({x:t},"tile"),s.assert(t.rank===n.length,"Error in transpose: rank of input "+t.rank+" must match length of reps "+n+"."),a.ENV.engine.runKernel(function(e){return e.tile(t,n);},{x:t},function(r){return{x:function x(){var a=e.zerosLike(t);if(1===t.rank)for(var i=0;i<n[0];++i){a=a.add(r.slice([i*t.shape[0]],[t.shape[0]]));}else if(2===t.rank)for(i=0;i<n[0];++i){for(var o=0;o<n[1];++o){a=a.add(r.slice([i*t.shape[0],o*t.shape[1]],[t.shape[0],t.shape[1]]));}}else if(3===t.rank)for(i=0;i<n[0];++i){for(o=0;o<n[1];++o){for(var s=0;s<n[2];++s){a=a.add(r.slice([i*t.shape[0],o*t.shape[1],s*t.shape[2]],[t.shape[0],t.shape[1],t.shape[2]]));}}}else{if(4!==t.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+t.rank+" tensors yet.");for(i=0;i<n[0];++i){for(o=0;o<n[1];++o){for(s=0;s<n[2];++s){for(var u=0;u<n[3];++u){a=a.add(r.slice([i*t.shape[0],o*t.shape[1],s*t.shape[2],u*t.shape[3]],[t.shape[0],t.shape[1],t.shape[2],t.shape[3]]));}}}}}return a;}};});},e.gather=function(e,t,n){return void 0===n&&(n=0),s.assertArgumentsAreTensors({x:e,indices:t},"gather"),s.assert("int32"===t.dtype,"Indices must be of dtype `int32`"),n=Object(u.g)(n,e.shape)[0],a.ENV.engine.runKernel(function(r){return r.gather(e,t,n);},{x:e},function(r){return{x:function x(){return h.a.unsortedSegmentSum(r,t,e.shape[n],n);}};});},e.pad1d=function(t,n,r){return void 0===r&&(r=0),s.assert(2===n.length,"Invalid number of paddings. Must be length of 2."),e.pad(t,[n],r);},e.pad2d=function(t,n,r){return void 0===r&&(r=0),s.assert(2===n.length&&2===n[0].length&&2===n[1].length,"Invalid number of paddings. Must be length of 2 each."),e.pad(t,n,r);},e.pad3d=function(t,n,r){return void 0===r&&(r=0),s.assert(3===n.length&&2===n[0].length&&2===n[1].length&&2===n[2].length,"Invalid number of paddings. Must be length of 2 each."),e.pad(t,n,r);},e.pad4d=function(t,n,r){return void 0===r&&(r=0),s.assert(4===n.length&&2===n[0].length&&2===n[1].length&&2===n[2].length&&2===n[3].length,"Invalid number of paddings. Must be length of 2 each."),e.pad(t,n,r);},e.pad=function(e,t,n){if(void 0===n&&(n=0),s.assertArgumentsAreTensors({x:e},"pad"),0===e.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var r=t.map(function(e){return e[0];});return a.ENV.engine.runKernel(function(r){return r.pad(e,t,n);},{x:e},function(t){return{x:function x(){return t.slice(r,e.shape);}};});},e.stack=function(e,t){if(void 0===t&&(t=0),s.assertArgumentsAreTensors({tensors:e},"stack"),s.assert(e.length>=1,"Pass at least one tensor to tf.stack"),1===e.length)return e[0].expandDims(t);var n=e[0].rank,r=e[0].shape,a=e[0].dtype;s.assert(t<=n,"Axis must be <= rank of the tensor"),e.forEach(function(e){s.assertShapesMatch(r,e.shape,"All tensors passed to stack must have matching shapes");}),e.forEach(function(e){s.assert(a===e.dtype,"All tensors passed to stack must have matching dtypes");});var i=e.map(function(e){return e.expandDims(t);});return c.a.concat(i,t);},e.unstack=function(e,t){void 0===t&&(t=0);for(var n,r=e.shape[t],a=Array(e.rank-1).fill(0),i=0,o=0;o<e.rank;o++){o!==t&&(a[i]=e.shape[o],i++);}n=Array(r).fill(1);var s=Array(e.rank).fill(0),u=e.shape.slice();return n.map(function(n){u[t]=n;var r=e.slice(s,u);return s[t]+=n,r.reshape(a);});},e.split=function(e,t,n){var r;void 0===n&&(n=0),s.assertArgumentsAreTensors({x:e},"split"),n=Object(u.g)(n,e.shape)[0],"number"==typeof t?(s.assert(e.shape[n]%t==0,"Number of splits must evenly divide the axis."),r=Array(t).fill(e.shape[n]/t)):(s.assert(e.shape[n]===t.reduce(function(e,t){return e+t;}),"The sum of sizes must match the size of the axis dimension."),r=t);var a=Array(e.rank).fill(0),i=e.shape.slice();return r.map(function(t){i[n]=t;var r=e.slice(a,i);return a[n]+=t,r;});},e.cumsum=function(e,t,n,r){void 0===t&&(t=0),void 0===n&&(n=!1),void 0===r&&(r=!1),s.assertArgumentsAreTensors({x:e},"cumsum"),t|=0;var i=Object(u.d)([t],e.rank),o=e;null!=i&&(o=e.transpose(i));var c=Object(u.e)(1,e.rank)[0],l=a.ENV.engine.runKernel(function(e){return e.cumsum(o,c,n,r);},{permutedX:o},function(e){return{permutedX:function permutedX(){return e.cumsum(t,n,!r);}};});return null!=i&&(l=l.transpose(i)),l;},e.expandDims=function(t,n){void 0===n&&(n=0),s.assertArgumentsAreTensors({x:t},"expandDims"),s.assert(n<=t.rank,"Axis must be <= rank of the tensor");var r=t.shape.slice();return r.splice(n,0,1),e.reshape(t,r);},e.linspace=function(t,n,r){if(0===r)throw new Error("Cannot request zero samples");var a=(n-t)/(r-1),i=g(r,"float32");i[0]=t;for(var o=1;o<i.length;o++){i[o]=i[o-1]+a;}return e.tensor1d(i,"float32");},e.range=function(t,n,r,a){if(void 0===r&&(r=1),void 0===a&&(a="float32"),0===r)throw new Error("Cannot have a step of zero");if(t===n||t<n&&r<0||n<t&&r>1)return e.zeros([0],a);var i=g(Math.abs(Math.ceil((n-t)/r)),a);n<t&&1===r&&(r=-1),i[0]=t;for(var o=1;o<i.length;o++){i[o]=i[o-1]+r;}return e.tensor1d(i,a);},e.buffer=function(e,t,n){return void 0===t&&(t="float32"),new i.b(e,t,n);},e.print=function(e,t){void 0===t&&(t=!1),console.log(o.a(e,t));},d([Object(r.a)({heading:"Tensors",subheading:"Creation"})],e,"tensor",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"})],e,"scalar",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"})],e,"tensor1d",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"})],e,"tensor2d",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"})],e,"tensor3d",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"})],e,"tensor4d",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"ones",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"zeros",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"fill",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"onesLike",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"zerosLike",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"clone",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"eye",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"randomNormal",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"truncatedNormal",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"randomUniform",null),d([l.a],e,"rand",null),d([l.a],e,"multinomial",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"oneHot",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"}),l.a],e,"fromPixels",null),d([Object(r.a)({heading:"Visualization"})],e,"toPixels",null),d([Object(r.a)({heading:"Tensors",subheading:"Transformations"}),l.a],e,"reshape",null),d([Object(r.a)({heading:"Tensors",subheading:"Transformations"})],e,"squeeze",null),d([Object(r.a)({heading:"Tensors",subheading:"Transformations"}),l.a],e,"cast",null),d([Object(r.a)({heading:"Tensors",subheading:"Slicing and Joining"}),l.a],e,"tile",null),d([Object(r.a)({heading:"Tensors",subheading:"Slicing and Joining"}),l.a],e,"gather",null),d([Object(r.a)({heading:"Tensors",subheading:"Transformations"}),l.a],e,"pad",null),d([Object(r.a)({heading:"Tensors",subheading:"Slicing and Joining"}),l.a],e,"stack",null),d([Object(r.a)({heading:"Tensors",subheading:"Slicing and Joining"}),l.a],e,"unstack",null),d([Object(r.a)({heading:"Tensors",subheading:"Slicing and Joining"}),l.a],e,"split",null),d([Object(r.a)({heading:"Operations",subheading:"Scan"})],e,"cumsum",null),d([Object(r.a)({heading:"Tensors",subheading:"Transformations"}),l.a],e,"expandDims",null),d([l.a,Object(r.a)({heading:"Tensors",subheading:"Creation"})],e,"linspace",null),d([l.a,Object(r.a)({heading:"Tensors",subheading:"Creation"})],e,"range",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"})],e,"buffer",null),d([Object(r.a)({heading:"Tensors",subheading:"Creation"})],e,"print",null),e;}();function g(e,t){if(null==t||"float32"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error("Unknown data type $ {dtype}");}},function(e,t,n){"use strict";n.r(t);var r={};n.d(r,"createWebGLRenderingContext",function(){return ie;}),n.d(r,"createWebGLRenderingContextFromCanvas",function(){return oe;}),n.d(r,"callAndCheck",function(){return se;}),n.d(r,"enableDebugWebGLErrorChecking",function(){return ce;}),n.d(r,"checkWebGLError",function(){return le;}),n.d(r,"getWebGLErrorMessage",function(){return fe;}),n.d(r,"getExtensionOrThrow",function(){return pe;}),n.d(r,"createVertexShader",function(){return he;}),n.d(r,"createFragmentShader",function(){return de;}),n.d(r,"createProgram",function(){return ge;}),n.d(r,"linkProgram",function(){return ye;}),n.d(r,"validateProgram",function(){return ve;}),n.d(r,"createStaticVertexBuffer",function(){return be;}),n.d(r,"createStaticIndexBuffer",function(){return we;}),n.d(r,"queryMaxTextureSize",function(){return xe;}),n.d(r,"getChannelsPerTexture",function(){return ke;}),n.d(r,"createTexture",function(){return Oe;}),n.d(r,"validateTextureSize",function(){return Se;}),n.d(r,"createFramebuffer",function(){return Ne;}),n.d(r,"bindVertexBufferToProgramAttribute",function(){return Ee;}),n.d(r,"bindTextureUnit",function(){return Ie;}),n.d(r,"unbindTextureUnit",function(){return Te;}),n.d(r,"getProgramUniformLocationOrThrow",function(){return Ae;}),n.d(r,"getProgramUniformLocation",function(){return Ce;}),n.d(r,"bindTextureToProgramUniformSampler",function(){return Pe;}),n.d(r,"bindCanvasToFramebuffer",function(){return _e;}),n.d(r,"bindColorTextureToFramebuffer",function(){return Re;}),n.d(r,"unbindColorTextureFromFramebuffer",function(){return Me;}),n.d(r,"validateFramebuffer",function(){return je;}),n.d(r,"getFramebufferErrorMessage",function(){return De;}),n.d(r,"getTextureShapeFromLogicalShape",function(){return Fe;});var a={};n.d(a,"getWebGLContextAttributes",function(){return Ue;}),n.d(a,"createWebGLContext",function(){return We;}),n.d(a,"createVertexShader",function(){return Ge;}),n.d(a,"createVertexBuffer",function(){return qe;}),n.d(a,"createIndexBuffer",function(){return He;}),n.d(a,"createMatrixTexture",function(){return Ye;}),n.d(a,"createColorMatrixTexture",function(){return Qe;}),n.d(a,"createPackedMatrixTexture",function(){return Ze;}),n.d(a,"bindVertexProgramAttributeStreams",function(){return $e;}),n.d(a,"uploadPixelDataToTexture",function(){return et;}),n.d(a,"uploadMatrixToTexture",function(){return nt;}),n.d(a,"uploadMatrixToPackedTexture",function(){return rt;}),n.d(a,"downloadMatrixFromOutputTextureAsync",function(){return ot;}),n.d(a,"downloadMatrixFromOutputTexture",function(){return st;}),n.d(a,"downloadMatrixFromRGBAColorTexture",function(){return ut;}),n.d(a,"downloadMatrixFromPackedOutputTexture",function(){return ct;});var i={};n.d(i,"browserFiles",function(){return Un;}),n.d(i,"browserHTTPRequest",function(){return Yn;}),n.d(i,"copyModel",function(){return tr;}),n.d(i,"decodeWeights",function(){return Qt;}),n.d(i,"encodeWeights",function(){return Yt;}),n.d(i,"getLoadHandlers",function(){return er;}),n.d(i,"getModelArtifactsInfoForJSON",function(){return tn;}),n.d(i,"getSaveHandlers",function(){return $n;}),n.d(i,"listModels",function(){return nr;}),n.d(i,"loadWeights",function(){return Hn;}),n.d(i,"moveModel",function(){return rr;}),n.d(i,"registerLoadRouter",function(){return Zn;}),n.d(i,"registerSaveRouter",function(){return Qn;}),n.d(i,"removeModel",function(){return ar;});var o={};n.d(o,"Serializable",function(){return ir;}),n.d(o,"SerializationMap",function(){return or;});var s={};n.d(s,"WEBGL_ENVS",function(){return sr;}),n.d(s,"CPU_ENVS",function(){return ur;}),n.d(s,"ALL_ENVS",function(){return cr;}),n.d(s,"TEST_EPSILON",function(){return lr;}),n.d(s,"expectArraysClose",function(){return fr;}),n.d(s,"expectPromiseToFail",function(){return pr;}),n.d(s,"expectArraysEqual",function(){return hr;}),n.d(s,"expectNumbersClose",function(){return dr;}),n.d(s,"expectValuesInRange",function(){return gr;});var u={};n.d(u,"MathBackendWebGL",function(){return Bt;}),n.d(u,"GPGPUContext",function(){return pt;}),n.d(u,"gpgpu_util",function(){return a;}),n.d(u,"webgl_util",function(){return r;});var c=n(3),l=n(8),f=n(1),p=30;function h(e){return e<=p?e:function(e,t){for(var n=t;n<e;++n){if(e%n==0)return n;}return e;}(e,Math.floor(Math.sqrt(e)));}var d=n(90),m=n(6),g=n(20),y=n(0),v=n(9);function b(e,t,n){if(!y.hasEncodingLoss(e.dtype,t))return m.a.make(e.shape,{dataId:e.dataId},t);if("int32"===t)return n.int(e);if("bool"===t)return n.notEqual(e,v.a.scalar(0,e.dtype));throw new Error("Error in Cast: unknown dtype argument ("+t+")");}function w(e,t){return m.a.make(t,{dataId:e.dataId},e.dtype);}var x,k=function k(e,t,n){this.variableNames=["A"];var r=e.windowSize,a=e.batchSize,i=e.inSize,o=Math.ceil(i/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,o];var s="max"===t?">":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = 0;\n float bestValue = getA(batch, inOffset);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n ";},O=function O(e){this.variableNames=["dy"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=1/(t*n);this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n const float avgMultiplier = float("+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+t+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n ";},S=n(11),N=function N(e,t,n,r,a,i){this.outputShape=[],this.supportsBroadcasting=!0,this.variableNames=["x","mean","variance"],S.a(e,t),S.a(e,n);var o="0.0";null!=r&&(S.a(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var s="1.0";null!=a&&(S.a(e,a),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=e,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+o+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+i+"));\n setOutput((x - mean) * inv + offset);\n }\n ";},E=function E(e,t,n){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.outputShape=S.a(t,n),this.userCode="\n float binaryOperation(float a, float b) {\n "+e+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n ";},I=function I(e,t,n){this.variableNames=["A"],this.outputShape=e;var r=t.toFixed(20),a=n.toFixed(20);this.userCode="\n void main() {\n float value = getAAtOutCoords();\n if (isNaN(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, "+r+", "+a+"));\n }\n ";},T=n(62),A=function A(e,t){this.variableNames=["A","B"],this.outputShape=[],this.outputShape=T.c(e,t,1),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n float value = 0.0;\n if (yC < "+e[1]+") {\n value = getA(yR, yC);\n } else {\n yC -= "+e[1]+";\n value = getB(yR, yC);\n }\n\n setOutput(value);\n }\n ";},C=function C(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+t+" - "+r+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+a+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n ";},P=function P(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+t+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+t+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+e.outChannels+"; d2++) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n ";},_=function _(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;var t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+i+" + dm;\n\n float dotProd = 0.0;\n\n // TODO: Vec4 over the batch size\n for (int b = 0; b < "+e.batchSize+"; b++) {\n for (int yR = 0; yR < "+e.outHeight+"; yR++) {\n int xR = wR + yR * "+t+" - "+r+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+e.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+a+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n ";},R=function R(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+t+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+t+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n ";},M=function M(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.padInfo.top,n=e.padInfo.left,r=e.strideHeight,a=e.strideWidth,i=e.dilationHeight,o=e.dilationWidth,s=e.filterHeight,u=e.filterWidth,c=4*Math.floor(e.inChannels/4),l=e.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+r+", "+a+");\n const ivec2 pads = ivec2("+t+", "+n+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+"; wR++) {\n int xR = xRCorner + wR * "+i+";\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+"; wC++) {\n int xC = xCCorner + wC * "+o+";\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+c+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===l)+") {\n dotProd +=\n getX(batch, xR, xC, "+c+") *\n getW(wR, wC, "+c+", d2);\n } else if ("+(2===l)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+c+"),\n getX(batch, xR, xC, "+c+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+c+", d2),\n getW(wR, wC, "+c+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===l)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+c+"),\n getX(batch, xR, xC, "+c+" + 1),\n getX(batch, xR, xC, "+c+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+c+", d2),\n getW(wR, wC, "+c+" + 1, d2),\n getW(wR, wC, "+c+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n ";},j=function j(e){this.variableNames=["x","W"],this.outputShape=e.outShape;var t=e.inHeight,n=e.inWidth,r=e.padInfo.top,a=e.padInfo.left,i=e.strideHeight,o=e.strideWidth,s=e.dilationHeight,u=e.dilationWidth,c=e.filterHeight,l=e.filterWidth,f=e.outChannels/e.inChannels;this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+r+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+f+";\n int q = d2 - d1 * "+f+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+c+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+t+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+n+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n setOutput(dotProd);\n }\n ";};function D(e,t){return[t,e];}function L(e,t){return e*t;}!function(e){e[e.FLOAT=0]="FLOAT",e[e.UNSIGNED_BYTE=1]="UNSIGNED_BYTE";}(x||(x={}));var z=-2e4,F=(2e4-z)/255,B=[1,1/255,1/65025,1/16581375],V=[1,255,65025],U=0;function W(e,t){return[Math.ceil(t/2),Math.ceil(e/2)];}function G(e,t){var n=W(e,t);return n[0]*n[1]*4;}function q(e,t,n,r){var a=c.ENV.get("WEBGL_FLOAT_TEXTURE_ENABLED")?X:H,i=c.ENV.get("WEBGL_FLOAT_TEXTURE_ENABLED")?J:K,o=e.map(function(e){return"uniform sampler2D "+e.name+";";}).join("\n"),s=e.map(function(e){return function(e,t,n){var r=function(e){var t=e.name,n=e.shapeInfo.texShape,r="get"+t.charAt(0).toUpperCase()+t.slice(1)+"Flat",a=n[0],i=n[1];return 1===i&&1===a?"\n float "+r+"(int index) {\n return sampleTexture("+t+", halfCR);\n }\n ":1===i?"\n float "+r+"(int index) {\n vec2 uv = vec2(0.5, (float(index) + 0.5) / "+a+".0);\n return sampleTexture("+t+", uv);\n }\n ":1===a?"\n float "+r+"(int index) {\n vec2 uv = vec2((float(index) + 0.5) / "+i+".0, 0.5);\n return sampleTexture("+t+", uv);\n }\n ":"\n float "+r+"(int index) {\n vec2 uv = UVfrom1D("+a+", "+i+", index);\n return sampleTexture("+t+", uv);\n }\n ";}(e);return r+=function e(t){var n=t.shapeInfo.logicalShape;switch(n.length){case 0:return function(e){var t=e.name;return"\n float get"+t.charAt(0).toUpperCase()+t.slice(1)+"() {\n return sampleTexture("+t+", halfCR);\n }\n ";}(t);case 1:return function(e){var t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);return"\n float "+n+"(int index) {\n return "+n+"Flat(index);\n }\n ";}(t);case 2:return function(t){var n=t.shapeInfo.logicalShape,r=t.shapeInfo.texShape,a=t.name,i="get"+a.charAt(0).toUpperCase()+a.slice(1),o=r[0],s=r[1];if(y.arraysEqual(n,r))return"\n float "+i+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+s+".0, "+o+".0);\n return sampleTexture("+a+", uv);\n }\n ";var u=y.squeezeShape(n),c=u.newShape,l=u.keptDims,f=c;if(f.length<n.length){var p=Z(t,f);return"\n "+e(p)+"\n float "+i+"(int row, int col) {\n return "+i+"("+$(["row","col"],l)+");\n }\n ";}return 1===s?"\n float "+i+"(int row, int col) {\n int index = row * "+n[1]+" + col;\n vec2 uv = vec2(0.5, (float(index) + 0.5) / "+o+".0);\n return sampleTexture("+a+", uv);\n }\n ":1===o?"\n float "+i+"(int row, int col) {\n int index = row * "+n[1]+" + col;\n vec2 uv = vec2((float(index) + 0.5) / "+s+".0, 0.5);\n return sampleTexture("+a+", uv);\n }\n ":"\n float "+i+"(int row, int col) {\n vec2 uv = UVfrom2D("+o+", "+s+", "+n[1]+", row, col);\n return sampleTexture("+a+", uv);\n }\n";}(t);case 3:return function(t){var n=t.shapeInfo.texShape,r=t.shapeInfo.logicalShape,a=t.name,i="get"+a.charAt(0).toUpperCase()+a.slice(1),o=n[0],s=n[1],u=r[1]*r[2],c=r[2],l=y.squeezeShape(r),f=l.newShape,p=l.keptDims,h=f;if(h.length<r.length){var d=Z(t,h);return"\n "+e(d)+"\n float "+i+"(int row, int col, int depth) {\n return "+i+"("+$(["row","col","depth"],p)+");\n }\n ";}return s===u?"\n float "+i+"(int row, int col, int depth) {\n int texR = row;\n int texC = col * "+c+" + depth;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+s+".0, "+o+".0);\n return sampleTexture("+a+", uv);\n }\n ":s===c?"\n float "+i+"(int row, int col, int depth) {\n int texR = row * "+r[1]+" + col;\n int texC = depth;\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+s+".0, "+o+".0);\n return sampleTexture("+a+", uv);\n }\n ":"\n float "+i+"(int row, int col, int depth) {\n vec2 uv = UVfrom3D(\n "+o+", "+s+", "+u+", "+c+", row, col, depth);\n return sampleTexture("+a+", uv);\n }\n ";}(t);case 4:return function(t){var n=t.shapeInfo.logicalShape,r=t.shapeInfo.texShape,a=t.name,i="get"+a.charAt(0).toUpperCase()+a.slice(1),o=r[0],s=r[1],u=n[3],c=n[2]*u,l=n[1]*c,f=y.squeezeShape(n),p=f.newShape,h=f.keptDims;if(p.length<n.length){var d=Z(t,p);return"\n "+e(d)+"\n float "+i+"(int row, int col, int depth, int depth2) {\n return "+i+"("+$(["row","col","depth","depth2"],h)+");\n }\n ";}return s===l?"\n float "+i+"(int row, int col, int depth, int depth2) {\n int texR = row;\n int texC = col * "+c+" + depth * "+u+" + depth2;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+s+".0, "+o+".0);\n return sampleTexture("+a+", uv);\n }\n ":s===u?"\n float "+i+"(int row, int col, int depth, int depth2) {\n int texR = row * "+n[1]*n[2]+" + col * "+n[2]+" + depth;\n int texC = depth2;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+s+".0, "+o+".0);\n return sampleTexture("+a+", uv);\n }\n ":"\n float "+i+"(int row, int col, int depth, int depth2) {\n vec2 uv = UVfrom4D("+o+", "+s+", "+l+", "+c+",\n "+u+", row, col, depth, depth2);\n return sampleTexture("+a+", uv);\n }\n ";}(t);default:throw new Error(n.length+"-D input sampling is not yet supported");}}(e),(n||y.arraysEqual(e.shapeInfo.logicalShape,t.logicalShape))&&(r+=function(e,t,n){var r=e.shapeInfo.texShape,a=e.name,i=a.charAt(0).toUpperCase()+a.slice(1),o="get"+i+"AtOutCoords",s=S.c(e.shapeInfo.logicalShape,t.logicalShape),u=e.shapeInfo.logicalShape.length,c=t.logicalShape.length,l=n&&(c>u||s.length>0),f=S.b(s);if(l&&!f)return function(e,t,n,r){var a=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o="int";2===i?o="ivec2":3===i?o="ivec3":4===i&&(o="ivec4");var s=S.c(e.shapeInfo.logicalShape,t.logicalShape),u=i-a;return"\n float "+r+"() {\n "+o+" coords = getOutputCoords();\n "+(0===a?"":i<2&&s.length>=1?"coords = 0;":s.map(function(e){return"coords["+(e+u)+"] = 0;";}).join("\n"))+"\n return get"+n+"("+(i<2&&a>0?"coords":e.shapeInfo.logicalShape.map(function(e,t){return"coords["+(t+u)+"]";}).join(", "))+");\n }\n ";}(e,t,i,o);var p=t.texShape;if(y.arraysEqual(r,p))return"\n float "+o+"() {\n return sampleTexture("+a+", resultUV);\n }\n ";var h=y.sizeFromShape(r),d="";return l&&f&&(d="\n int mainPart = index / "+h+";\n index -= mainPart * "+h+";\n "),"\n float "+o+"() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+p[0]+", "+p[1]+"));\n int index = resTexRC.x * "+p[1]+" + resTexRC.y;\n "+d+"\n int texR = index / "+r[1]+";\n int texC = index - texR * "+r[1]+";\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+r[1]+".0, "+r[0]+".0);\n\n return sampleTexture("+a+", uv);\n }\n ";}(e,t,n)),r;}(e,t,r);}).join("\n"),u=t.texShape,l=function(e,t){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t){return 1===t[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+t[1]+".0);\n }\n ":1===t[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+t[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n return resTexRC.x * "+t[1]+" + resTexRC.y;\n }\n ";}(0,t);case 2:return function(e,t){return y.arraysEqual(e,t)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+t[0]+", "+t[1]+"));\n }\n ":1===e[1]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ":1===e[0]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ":"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+e[1]+";\n int c = index - r * "+e[1]+";\n return ivec2(r, c);\n }\n ";}(e,t);case 3:return function(e,t){var n=e[1]*e[2],r=e[2];return"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n int r = index / "+n+";\n index -= r * "+n+";\n int c = index / "+r+";\n int d = index - c * "+r+";\n return ivec3(r, c, d);\n }\n ";}(e,t);case 4:return function(e,t){var n=e[3],r=e[2]*n,a=e[1]*r;return"\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+t[0]+", "+t[1]+"));\n int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n int r = index / "+a+";\n index -= r * "+a+";\n\n int c = index / "+r+";\n index -= c * "+r+";\n\n int d = index / "+n+";\n int d2 = index - d * "+n+";\n\n return ivec4(r, c, d, d2);\n }\n ";}(e,t);default:throw new Error(e.length+"-D output sampling is not yet supported");}}(t.logicalShape,u);return[Y,a,i,o,l,s,n].join("\n");}var H="\n uniform float NaN;\n\n const vec4 floatDeltas = vec4(\n 1.0,\n 1.0 / 255.0,\n 1.0 / (255.0 * 255.0),\n 1.0 / (255.0 * 255.0 * 255.0)\n );\n const float minValue = "+z+".0;\n const float maxValue = 20000.0;\n const float range = (maxValue - minValue) / 255.0;\n const vec2 dotRange = vec2(1.0, range);\n\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n vec4 sampleValue = texture2D(textureSampler, uv);\n if (all(equal(sampleValue, vec4("+U+")))) {\n return NaN;\n }\n\n vec4 encValue = floor(sampleValue * 255.0 + 0.5);\n float decodedValue = dot(encValue, floatDeltas);\n return dot(vec2(minValue, decodedValue), dotRange);\n }\n",K="\n const vec4 floatPowers = vec4(\n 1.0,\n 255.0,\n 255.0 * 255.0,\n 255.0 * 255.0 * 255.0\n );\n const vec2 recipRange = vec2(1.0/range);\n const vec2 recipRange255 = vec2(1.0/(maxValue - minValue));\n\n void setOutput(float decodedValue) {\n if (isNaN(decodedValue)) {\n gl_FragColor = vec4("+U+");\n return;\n }\n\n float a = dot(vec2(decodedValue, -minValue), recipRange);\n float b = fract(a) * 255.0;\n float c = fract(b) * 255.0;\n float d = fract(c) * 255.0;\n gl_FragColor = floor(vec4(a, b, c, d)) / 255.0;\n\n // TODO(dsmilkov): Version above gets better accuracy but probably slower\n // than the version below. Benchmark to determine if the accuracy is worth\n // the cost.\n\n // float normValue = dot(vec2(decodedValue, -minValue), recipRange255);\n // vec4 f = normValue * floatPowers;\n // gl_FragColor = floor(fract(f) * 255.0) / 255.0;\n }\n",X="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return texture2D(textureSampler, uv).r;\n }\n",J="\n void setOutput(float val) {\n gl_FragColor = vec4(val, 0, 0, 0);\n }\n",Y="\n precision highp float;\n precision highp int;\n varying vec2 resultUV;\n const vec2 halfCR = vec2(0.5, 0.5);\n\n bool isNaN(float val) {\n float v1 = val * val;\n float v2 = val * val;\n return v1 == v2 ? false : true;\n }\n\n bool hasNaN(vec4 values) {\n vec4 v1 = values * values;\n vec4 v2 = values * values;\n return any(notEqual(v1, v2));\n }\n\n float getNaN(vec4 values) {\n return dot(vec4(1), values);\n }\n\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n \nvec2 UVfrom1D(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom2D(int texNumR, int texNumC, int numC, int row, int col) {\n int index = row * numC + col;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom3D(int texNumR, int texNumC, int stride0,\n int stride1, int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n \nvec2 UVfrom4D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int row, int col, int depth,\n int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n\n";function Q(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";throw Error("GPU for rank "+e+" is not yet supported");}function Z(e,t){var n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n;}function $(e,t){return t.map(function(t){return e[t];}).join(", ");}var ee=function ee(e,t,n){this.variableNames=["x"],this.outputShape=e;var r=e.length,a=e[e.length-1],i=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+a+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+Q(r)+" coords = getOutputCoords();\n int end = "+te(r,"coords")+";\n float val = 0.0;\n for (int i = "+a+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+i+" end) {\n continue;\n }\n if (idx == end && "+t+") {\n continue;\n }\n "+te(r,"coords")+" = idx;\n val += getX("+function(e,t){if(1===e)return""+t;if(2===e)return t+".x, "+t+".y";if(3===e)return t+".x, "+t+".y, "+t+".z";if(4===e)return t+".x, "+t+".y, "+t+".z, "+t+".w";throw Error("Cumulative sum for rank "+e+" is not yet supported");}(r,"coords")+");\n }\n setOutput(val);\n }\n ";};function te(e,t){if(1===e)return""+t;if(2===e)return t+".y";if(3===e)return t+".z";if(4===e)return t+".w";throw Error("Cumulative sum for rank "+e+" is not yet supported");}var ne=function ne(e){this.variableNames=["A"];var t=e[0],n=e[1];this.outputShape=e,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+n+".0, "+t+".0);\n\n vec4 values = texture2D(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n ";},re=function re(e,t,n){this.variableNames=["A","indices"];var r=e.slice();r[n]=t,this.outputShape=r,this.rank=r.length;var a=Q(this.rank),i=function(e,t){var n=e.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=0;i<e.length;i++){i===t?a.push("int(getIndices("+r[i]+"))"):a.push(""+r[i]);}return a.join();}(e,n);this.userCode="\n void main() {\n "+a+" resRC = getOutputCoords();\n setOutput(getA("+i+"));\n }\n ";},ae=null;function ie(e){var t=document.createElement("canvas");return t.width=1,t.height=1,oe(t,e);}function oe(e,t){var n,r=c.ENV.get("WEBGL_VERSION");if(2===r?n=e.getContext("webgl2",t):1===r&&(n=e.getContext("webgl",t)||e.getContext("experimental-webgl",t)),0===r||null==n)throw new Error("This browser does not support WebGL.");return n;}function se(e,t){var n=t();return le(e),n;}var ue=!1;function ce(e){ue=e;}function le(e){if(ue){var t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+fe(e,t));}}function fe(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+t;}}function pe(e,t){return Le(e,function(){return e.getExtension(t);},'Extension "'+t+'" not supported on this browser.');}function he(e,t){var n=Le(e,function(){return e.createShader(e.VERTEX_SHADER);},"Unable to create vertex WebGLShader.");if(se(e,function(){return e.shaderSource(n,t);}),se(e,function(){return e.compileShader(n);}),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n;}function de(e,t){var n=Le(e,function(){return e.createShader(e.FRAGMENT_SHADER);},"Unable to create fragment WebGLShader.");if(se(e,function(){return e.shaderSource(n,t);}),se(e,function(){return e.compileShader(n);}),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw function(e,t){var n=me.exec(t);if(null==n)return console.log("Couldn't parse line number in error: "+t),void console.log(e);for(var r=+n[1],a=e.split("\n"),i=a.length.toString().length+2,o=a.map(function(e,t){return y.rightPad((t+1).toString(),i)+e;}),s=0,u=0;u<o.length;u++){s=Math.max(o[u].length,s);}var c=o.slice(0,r-1),l=o.slice(r-1,r),f=o.slice(r);console.log(c.join("\n")),console.log(t.split("\n")[0]),console.log("%c "+y.rightPad(l[0],s),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(f.join("\n"));}(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n;}var me=/ERROR: [0-9]+:([0-9]+):/g;function ge(e){return Le(e,function(){return e.createProgram();},"Unable to create WebGLProgram.");}function ye(e,t){if(se(e,function(){return e.linkProgram(t);}),!1===e.getProgramParameter(t,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.");}function ve(e,t){if(se(e,function(){return e.validateProgram(t);}),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.");}function be(e,t){var n=Le(e,function(){return e.createBuffer();},"Unable to create WebGLBuffer");return se(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,n);}),se(e,function(){return e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW);}),n;}function we(e,t){var n=Le(e,function(){return e.createBuffer();},"Unable to create WebGLBuffer");return se(e,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n);}),se(e,function(){return e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW);}),n;}function xe(e){return null!=ae?ae:ae=se(e,function(){return e.getParameter(e.MAX_TEXTURE_SIZE);});}function ke(){return c.ENV.get("WEBGL_FLOAT_TEXTURE_ENABLED")&&2===c.ENV.get("WEBGL_VERSION")?1:4;}function Oe(e){return Le(e,function(){return e.createTexture();},"Unable to create WebGLTexture.");}function Se(e,t,n){var r=xe(e);if(t<=0||n<=0){var a="["+t+"x"+n+"]";throw new Error("Requested texture size "+a+" is invalid.");}if(t>r||n>r)throw a="["+t+"x"+n+"]",new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU ["+r+"x"+r+"].");}function Ne(e){return Le(e,function(){return e.createFramebuffer();},"Unable to create WebGLFramebuffer.");}function Ee(e,t,n,r,a,i,o){var s=e.getAttribLocation(t,n);return-1!==s&&(se(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,r);}),se(e,function(){return e.vertexAttribPointer(s,a,e.FLOAT,!1,i,o);}),se(e,function(){return e.enableVertexAttribArray(s);}),!0);}function Ie(e,t,n){ze(e,n),se(e,function(){return e.activeTexture(e.TEXTURE0+n);}),se(e,function(){return e.bindTexture(e.TEXTURE_2D,t);});}function Te(e,t){ze(e,t),se(e,function(){return e.activeTexture(e.TEXTURE0+t);}),se(e,function(){return e.bindTexture(e.TEXTURE_2D,null);});}function Ae(e,t,n){return Le(e,function(){return e.getUniformLocation(t,n);},'uniform "'+n+'" not present in program.');}function Ce(e,t,n){return e.getUniformLocation(t,n);}function Pe(e,t,n,r,a){se(e,function(){return Ie(e,n,a);}),se(e,function(){return e.uniform1i(r,a);});}function _e(e){se(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null);}),se(e,function(){return e.viewport(0,0,e.canvas.width,e.canvas.height);}),se(e,function(){return e.scissor(0,0,e.canvas.width,e.canvas.height);});}function Re(e,t,n){se(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,n);}),se(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0);});}function Me(e,t){se(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,t);}),se(e,function(){return e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0);});}function je(e){var t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+De(e,t));}function De(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t;}}function Le(e,t,n){var r=se(e,function(){return t();});if(null==r)throw new Error(n);return r;}function ze(e,t){var n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].");}function Fe(e,t){2!==t.length&&(t=y.squeezeShape(t).newShape);var n=xe(e),r=y.sizeFromShape(t);return t.length<=1&&r<=n?[r,1]:2===t.length&&t[0]<=n&&t[1]<=n?t:3===t.length&&t[0]<=n&&t[1]*t[2]<=n?[t[0],t[1]*t[2]]:4===t.length&&t[0]<=n&&t[1]*t[2]*t[3]<=n?[t[0],t[1]*t[2]*t[3]]:y.sizeToSquarishShape(r);}var Be=function Be(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},Ve=function Ve(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}};function Ue(){return{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};}function We(e){var t,n={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};return se(t=null!=e?oe(e,n):ie(n),function(){return t.disable(t.DEPTH_TEST);}),se(t,function(){return t.disable(t.STENCIL_TEST);}),se(t,function(){return t.disable(t.BLEND);}),se(t,function(){return t.disable(t.DITHER);}),se(t,function(){return t.disable(t.POLYGON_OFFSET_FILL);}),se(t,function(){return t.disable(t.SAMPLE_COVERAGE);}),se(t,function(){return t.enable(t.SCISSOR_TEST);}),se(t,function(){return t.enable(t.CULL_FACE);}),se(t,function(){return t.cullFace(t.BACK);}),t;}function Ge(e){return he(e,"\n precision highp float;\n attribute vec3 clipSpacePos;\n attribute vec2 uv;\n varying vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }");}function qe(e){return be(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]));}function He(e){return we(e,new Uint16Array([0,1,2,2,1,3]));}function Ke(e,t){return c.ENV.get("WEBGL_FLOAT_TEXTURE_ENABLED")&&2===c.ENV.get("WEBGL_VERSION")?4===t?e.RGBA:e.RED:e.RGBA;}function Xe(e){return c.ENV.get("WEBGL_FLOAT_TEXTURE_ENABLED")?e.FLOAT:e.UNSIGNED_BYTE;}function Je(e,t,n,r){Se(e,t,n);var a=Oe(e),i=e.TEXTURE_2D,o=function(e,t){return c.ENV.get("WEBGL_FLOAT_TEXTURE_ENABLED")&&2===c.ENV.get("WEBGL_VERSION")?4===t?e.RGBA32F:e.R32F:e.RGBA;}(e,r),s=Ke(e,r);return se(e,function(){return e.bindTexture(i,a);}),se(e,function(){return e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE);}),se(e,function(){return e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);}),se(e,function(){return e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST);}),se(e,function(){return e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST);}),se(e,function(){return e.texImage2D(i,0,o,t,n,0,s,Xe(e),null);}),se(e,function(){return e.bindTexture(e.TEXTURE_2D,null);}),a;}function Ye(e,t,n){var r=D(t,n);return Je(e,r[0],r[1],1);}function Qe(e,t,n){var r=function(e,t){return[4*n,e];}(t);return Je(e,r[0],r[1],4);}function Ze(e,t,n){var r=W(t,n);return Je(e,r[0],r[1],4);}function $e(e,t,n){return se(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,n);}),Ee(e,t,"clipSpacePos",n,3,20,0)&&Ee(e,t,"uv",n,2,20,12);}function et(e,t,n){se(e,function(){return e.bindTexture(e.TEXTURE_2D,t);}),se(e,function(){return e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n);}),se(e,function(){return e.bindTexture(e.TEXTURE_2D,null);});}function tt(e,t,n,r,a,i){var o=Ke(e,i);Se(e,n,r),se(e,function(){return e.bindTexture(e.TEXTURE_2D,t);}),se(e,function(){return e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,o,Xe(e),a);}),se(e,function(){return e.bindTexture(e.TEXTURE_2D,null);});}function nt(e,t,n,r,a,i){var o,s=D(n,r),u=s[0],l=s[1];if(c.ENV.get("WEBGL_FLOAT_TEXTURE_ENABLED")){var f=1===i?ke():i;1===f?o=a:function(e,t,n){var r=L(e.length,n);if(t.length<r)throw new Error("unpackedArray length ("+t.length+") must be >= "+r);for(var a=0,i=0;i<e.length;++i){t[a]=e[i],a+=n;}}(a,o=new Float32Array(L(a.length,f)),f);}else o=function(e){for(var t=new Uint8Array(4*e.length),n=function n(_n3){var r=e[_n3/4];if(isNaN(r))return t[_n3]=U,t[_n3+1]=U,t[_n3+2]=U,t[_n3+3]=U,"continue";var a=(r-z)/F,i=V.map(function(e){return e*a;}).map(function(e){return Math.floor(e%1*255);});t[_n3]=Math.floor(a),t[_n3+1]=i[0],t[_n3+2]=i[1],t[_n3+3]=i[2];},r=0;r<t.length;r+=4){n(r);}return t;}(a);tt(e,t,u,l,o,i);}function rt(e,t,n,r,a){var i=W(n,r),o=i[0],s=i[1],u=new Float32Array(G(n,r));!function(e,t,n,r){var a=G(t,n);if(r.length<a)throw new Error("packedRGBA length ("+r.length+") must be >= "+a);for(var i=W(t,n),o=i[0],s=i[1],u=n%2==1,c=t%2==1,l=Math.floor(n/2),f=Math.floor(t/2),p=u?4:0,h=n,d=0,m=0;m<f;++m){for(var g=2*m*n,y=0;y<l;++y){var v=g+2*y;r[d]=e[v],r[d+1]=e[v+1],r[d+2]=e[v+h],r[d+3]=e[v+h+1],d+=4;}d+=p;}if(u){v=n-1,d=4*(o-1);var b=2*n;for(p=4*o,m=0;m<f;++m){r[d]=e[v],r[d+2]=e[v+n],v+=b,d+=p;}}if(c)for(v=(t-1)*n,d=(s-1)*o*4,y=0;y<l;++y){r[d++]=e[v++],r[d++]=e[v++],d+=2;}u&&c&&(r[r.length-4]=e[e.length-1]);}(a,n,r,u),tt(e,t,o,s,u,4);}function at(e,t,n){return c.ENV.get("WEBGL_FLOAT_TEXTURE_ENABLED")?new Float32Array(L(e*t,n)):new Uint8Array(e*t*n);}function it(e,t,n,r){if(c.ENV.get("WEBGL_FLOAT_TEXTURE_ENABLED")){var a=new Float32Array(t*n);return function(e,t,n){var r=function(e,t){if(e%t!=0)throw new Error("unpackedSize ("+e+") must be a multiple of "+t);return e/t;}(e.length,n);if(t.length<r)throw new Error("matrix length ("+t.length+") must be >= "+r);for(var a=0,i=0;i<e.length;i+=n){t[a++]=e[i];}}(e,a,r),a;}return function(e){for(var t=new Float32Array(e.length/4),n=function n(_n4){if(e[_n4]===U&&e[_n4+1]===U&&e[_n4+2]===U&&e[_n4+3]===U)return t[_n4/4]=NaN,"continue";var r=0;B.forEach(function(t,a){r+=t*e[_n4+a];});var a=r*F+z;t[_n4/4]=a;},r=0;r<e.length;r+=4){n(r);}return t;}(e);}function ot(e,t,n,r){return Be(this,void 0,void 0,function(){var a,i,o,s,u;return Ve(this,function(c){switch(c.label){case 0:return a=e,o=at(n,r,i=4),s=o instanceof Float32Array?4*o.length:o,u=e.createBuffer(),se(e,function(){return e.bindBuffer(a.PIXEL_PACK_BUFFER,u);}),se(e,function(){return e.bufferData(a.PIXEL_PACK_BUFFER,s,e.STATIC_DRAW);}),se(e,function(){return a.readPixels(0,0,r,n,e.RGBA,Xe(e),0);}),[4,t.getBufferSubDataAsync(a.PIXEL_PACK_BUFFER,0,o)];case 1:return c.sent(),[2,it(o,n,r,i)];}});});}function st(e,t,n){var r=D(t,n),a=r[0],i=r[1],o=at(t,n,4);return se(e,function(){return e.readPixels(0,0,a,i,e.RGBA,Xe(e),o);}),it(o,t,n,4);}function ut(e,t,n,r){var a=t*n*4,i=new Uint8Array(a);se(e,function(){return e.readPixels(0,0,n,t,e.RGBA,e.UNSIGNED_BYTE,i);});for(var o=new Float32Array(a),s=0;s<i.length;s++){o[s]=i[s];}var u=new Float32Array(t*n*r);return function(e,t,n){var r=e.length*n/4;if(t.length<r)throw new Error("matrix length ("+t.length+") must be >= "+r);for(var a=0,i=0;i<e.length;i+=4){for(var o=0;o<n;o++){t[a++]=e[i+o];}}}(o,u,r),u;}function ct(e,t,n){var r=W(t,n),a=r[0],i=r[1],o=new Float32Array(G(t,n));se(e,function(){return e.readPixels(0,0,a,i,e.RGBA,Xe(e),o);});var s=new Float32Array(t*n);return function(e,t,n,r){var a=t*n;if(a<r.length)throw new Error("matrix length ("+r.length+") must be >= "+a);for(var i=n%2==1,o=t%2==1,s=Math.floor(n/2),u=Math.floor(t/2),c=W(t,n),l=c[0],f=c[1],p=i?4:0,h=n+(i?1:0),d=0,m=0,g=n,y=0;y<u;++y){for(var v=0;v<s;++v){r[m++]=e[d++],r[m++]=e[d++],r[g++]=e[d++],r[g++]=e[d++];}d+=p,m+=h,g+=h;}if(i){d=4*(l-1);var b=n-1;for(p=4*l,h=2*n,y=0;y<u;++y){r[b]=e[d],r[b+n]=e[d+2],d+=p,b+=h;}}if(o)for(d=(f-1)*l*4,b=(t-1)*n,v=0;v<s;++v){r[b++]=e[d++],r[b++]=e[d++],d+=2;}return i&&o&&(r[r.length-1]=e[e.length-4]),r;}(o,t,n,s);}var lt=function lt(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},ft=function ft(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},pt=function(){function e(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.autoDebugValidate=!1,this.vertexAttrsAreBound=!1,this.gl=null!=e?e:We(),1===c.ENV.get("WEBGL_VERSION")?(this.textureFloatExtension=pe(this.gl,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float")):this.colorBufferFloatExtension=pe(this.gl,"EXT_color_buffer_float"),this.loseContextExtension=pe(this.gl,"WEBGL_lose_context"),c.ENV.get("WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED")&&(this.getBufferSubDataAsyncExtension=this.gl.getExtension("WEBGL_get_buffer_sub_data_async")),this.vertexBuffer=qe(this.gl),this.indexBuffer=He(this.gl),this.framebuffer=Ne(this.gl);}return e.prototype.dispose=function(){var e=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var t=this.gl;se(t,function(){return t.finish();}),se(t,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null);}),se(t,function(){return t.deleteFramebuffer(e.framebuffer);}),se(t,function(){return t.bindBuffer(t.ARRAY_BUFFER,null);}),se(t,function(){return t.deleteBuffer(e.vertexBuffer);}),se(t,function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);}),se(t,function(){return t.deleteBuffer(e.indexBuffer);}),this.loseContextExtension.loseContext(),this.disposed=!0;}},e.prototype.enableAutomaticDebugValidation=function(e){this.autoDebugValidate=e,ce(e);},e.prototype.createMatrixTexture=function(e,t){return this.throwIfDisposed(),Ye(this.gl,e,t);},e.prototype.uploadPixelDataToTexture=function(e,t){this.throwIfDisposed(),et(this.gl,e,t);},e.prototype.createPackedMatrixTexture=function(e,t){return this.throwIfDisposed(),Ze(this.gl,e,t);},e.prototype.deleteMatrixTexture=function(e){var t=this;this.throwIfDisposed(),this.outputTexture===e&&(Me(this.gl,this.framebuffer),this.outputTexture=null),se(this.gl,function(){return t.gl.deleteTexture(e);});},e.prototype.uploadMatrixToTexture=function(e,t,n,r){return this.throwIfDisposed(),nt(this.gl,e,t,n,r,1);},e.prototype.uploadMatrixToPackedTexture=function(e,t,n,r){return this.throwIfDisposed(),rt(this.gl,e,t,n,r);},e.prototype.downloadMatrixFromTexture=function(e,t,n){var r=this;return this.downloadMatrixDriver(e,function(){return st(r.gl,t,n);});},e.prototype.downloadMatrixFromTextureAsync=function(e,t,n){return lt(this,void 0,void 0,function(){var r=this;return ft(this,function(a){if(null==this.getBufferSubDataAsyncExtension)throw new Error("Cannot download matrix from output texture asynchronously, WEBGL_get_buffer_sub_data_async is not enabled.");return[2,this.downloadMatrixDriverAsync(e,function(){return ot(r.gl,r.getBufferSubDataAsyncExtension,t,n);})];});});},e.prototype.downloadMatrixFromRGBAColorTexture=function(e,t,n,r){var a=this;return this.downloadMatrixDriver(e,function(){return ut(a.gl,t,n,r);});},e.prototype.downloadMatrixFromPackedTexture=function(e,t,n){var r=this;return this.downloadMatrixDriver(e,function(){return ct(r.gl,t,n);});},e.prototype.createProgram=function(e){this.throwIfDisposed();var t=this.gl,n=de(t,e),r=Ge(t),a=ge(t);return se(t,function(){return t.attachShader(a,r);}),se(t,function(){return t.attachShader(a,n);}),ye(t,a),this.autoDebugValidate&&ve(t,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=$e(t,this.program,this.vertexBuffer)),a;},e.prototype.deleteProgram=function(e){var t=this;this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&se(this.gl,function(){return t.gl.deleteProgram(e);});},e.prototype.setProgram=function(e){var t=this;this.throwIfDisposed(),this.program=e,null!=this.program&&this.autoDebugValidate&&ve(this.gl,this.program),se(this.gl,function(){return t.gl.useProgram(e);});},e.prototype.getUniformLocation=function(e,t,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?Ae(this.gl,e,t):Ce(this.gl,e,t);},e.prototype.getAttributeLocation=function(e,t){var n=this;return this.throwIfDisposed(),se(this.gl,function(){return n.gl.getAttribLocation(e,t);});},e.prototype.getUniformLocationNoThrow=function(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t);},e.prototype.setInputMatrixTexture=function(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),Pe(this.gl,this.program,e,t,n);},e.prototype.setOutputMatrixTexture=function(e,t,n){this.setOutputMatrixTextureDriver(e,n,t);},e.prototype.setOutputPackedMatrixTexture=function(e,t,n){this.throwIfDisposed();var r=W(t,n),a=r[0],i=r[1];this.setOutputMatrixTextureDriver(e,a,i);},e.prototype.setOutputMatrixWriteRegion=function(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t);},e.prototype.setOutputPackedMatrixWriteRegion=function(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.");},e.prototype.debugValidate=function(){null!=this.program&&ve(this.gl,this.program),je(this.gl);},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.autoDebugValidate&&this.debugValidate(),se(e,function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0);});},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),se(this.gl,function(){return e.gl.finish();});},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=pe(this.gl,2===c.ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension;},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension();},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension();},e.prototype.runQuery=function(e){var t=this.beginQuery();return e(),this.endQuery(),this.pollQueryTime(t);},e.prototype.beginQuery=function(){if(2===c.ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n;}var r=this.getQueryTimerExtensionWebGL1(),a=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,a),a;},e.prototype.endQuery=function(){if(2!==c.ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT);}else{var t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT);}},e.prototype.isQueryAvailable=function(e,t){if(0===t)return!0;if(2===t){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),a=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE),i=this.gl.getParameter(r.GPU_DISJOINT_EXT);return a&&!i;}return a=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT),i=this.gl.getParameter(r.GPU_DISJOINT_EXT),a&&!i;},e.prototype.pollQueryTime=function(e){var t=this;return new Promise(function(n,r){var a=c.ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION");y.repeatedTry(function(){return t.isQueryAvailable(e,a);}).then(function(){return n(t.getQueryTime(e,a));}).catch(function(){console.warn("Disjoint query timer never available."),n(-1);});});},e.prototype.getQueryTime=function(e,t){if(0===t)return null;if(2===t){var n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6;}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6;},e.prototype.downloadMatrixDriverSetup=function(e){this.throwIfDisposed(),Re(this.gl,e,this.framebuffer),this.autoDebugValidate&&je(this.gl);},e.prototype.downloadMatrixDriverTeardown=function(){null!=this.outputTexture?(Re(this.gl,this.outputTexture,this.framebuffer),this.autoDebugValidate&&je(this.gl)):Me(this.gl,this.framebuffer);},e.prototype.downloadMatrixDriver=function(e,t){this.downloadMatrixDriverSetup(e);var n=t();return this.downloadMatrixDriverTeardown(),n;},e.prototype.downloadMatrixDriverAsync=function(e,t){return lt(this,void 0,void 0,function(){var n;return ft(this,function(r){switch(r.label){case 0:return this.downloadMatrixDriverSetup(e),[4,t()];case 1:return n=r.sent(),this.downloadMatrixDriverTeardown(),[2,n];}});});},e.prototype.setOutputMatrixTextureDriver=function(e,t,n){this.throwIfDisposed();var r=this.gl;Re(r,e,this.framebuffer),this.autoDebugValidate&&je(r),this.outputTexture=e,se(r,function(){return r.viewport(0,0,t,n);}),se(r,function(){return r.scissor(0,0,t,n);});},e.prototype.setOutputMatrixWriteRegionDriver=function(e,t,n,r){var a=this;this.throwIfDisposed(),se(this.gl,function(){return a.gl.scissor(e,t,n,r);});},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.");},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.");},e;}();function ht(){return!c.ENV.get("WEBGL_FLOAT_TEXTURE_ENABLED");}function dt(e,t){if(e.length!==t.length)throw Error("Binary was compiled with "+e.length+" inputs, but was executed with "+t.length+" inputs");e.forEach(function(e,n){var r=e.logicalShape,a=e.texShape,i=t[n].tensor.shape,o=t[n].texData.texShape;if(!y.arraysEqual(r,i))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+i+" must match");if(!y.arraysEqual(a,o))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+a+" and "+o+" must match");});}var mt=function mt(e,t,n){var r,a;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)a="resRC",r="resRC";else{for(var i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],s=[],u=0;u<t.length;u++){s.push(""+i[u]),u<e&&o.push(""+i[u]);}r=o.join(),a=s.join();}var c=Q(n);this.userCode="\n void main() {\n "+c+" resRC = getOutputCoords();\n float cVal = getC("+r+");\n if (cVal >= 1.0) {\n setOutput(getA("+a+"));\n } else {\n setOutput(getB("+a+"));\n }\n }\n ";},gt=function gt(e,t,n,r,a){this.variableNames=["x"],this.outputShape=[];var i,o=t,s=e[3]-1;this.outputShape=e;var u="float("+n+") + float("+r+") * sum";i=.5===a?"inversesqrt("+u+")":1===a?"1.0/("+u+")":"exp(log("+u+") * float(-"+a+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+o+"; j <= "+o+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+i+";\n setOutput(val);\n }\n ";},yt=function yt(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;var t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,s=t*n-1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+t+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+e.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+a+".0;\n\n if (dyC < 0.0 || dyC >= "+e.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+s+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+n+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n ";},vt=function vt(e,t,n,r){void 0===n&&(n=!1),void 0===r&&(r=!1),this.variableNames=["matrixA","matrixB"];var a=n?e[1]:e[0],i=r?t[0]:t[1],o=n?e[0]:e[1];this.outputShape=[a,i];var s=function s(e,t){return n?t+" + "+e+", aRow":"aRow, "+t+" + "+e;},u=function u(e,t){return r?"bCol, "+t+" + "+e:t+" + "+e+", bCol";},c=4*Math.floor(o/4),l=o%4;this.userCode=" float dotARowBCol(int aRow, int bCol) {\n float result = 0.0;\n for (int i = 0; i < "+c+"; i += 4) {\n vec4 a = vec4(\n getMatrixA("+s(0,"i")+"),\n getMatrixA("+s(1,"i")+"),\n getMatrixA("+s(2,"i")+"),\n getMatrixA("+s(3,"i")+")\n );\n vec4 b = vec4(\n getMatrixB("+u(0,"i")+"),\n getMatrixB("+u(1,"i")+"),\n getMatrixB("+u(2,"i")+"),\n getMatrixB("+u(3,"i")+")\n );\n\n result += dot(a, b);\n }\n\n if ("+(1===l)+") {\n result += getMatrixA("+s(0,c)+") *\n getMatrixB("+u(0,c)+");\n } else if ("+(2===l)+") {\n vec2 a = vec2(\n getMatrixA("+s(0,c)+"),\n getMatrixA("+s(1,c)+")\n );\n vec2 b = vec2(\n getMatrixB("+u(0,c)+"),\n getMatrixB("+u(1,c)+")\n );\n result += dot(a, b);\n } else if ("+(3===l)+") {\n vec3 a = vec3(\n getMatrixA("+s(0,c)+"),\n getMatrixA("+s(1,c)+"),\n getMatrixA("+s(2,c)+")\n );\n vec3 b = vec3(\n getMatrixB("+u(0,c)+"),\n getMatrixB("+u(1,c)+"),\n getMatrixB("+u(2,c)+")\n );\n result += dot(a, b);\n }\n\n return result;\n }\n\n void main() {\n ivec2 resRC = getOutputCoords();\n setOutput(dotARowBCol(resRC.x, resRC.y));\n }\n ";},bt=function(){function e(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(t-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(t-1)+"));\n }\n ";}return e.prototype.getCustomSetupFunc=function(e){var t=this;return function(n,r){null==t.seedLoc&&(t.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(t.seedLoc,e);};},e;}(),wt=function wt(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+r+"), float("+n+"),\n float(index == coords.y)));\n }\n ";},xt=function xt(e,t,n){this.variableNames=["x"],this.outputShape=t.map(function(t,n){return t[0]+e[n]+t[1];});var r=e.length,a=Q(r),i=t.map(function(e){return e[0];}).join(","),o=t.map(function(t,n){return t[0]+e[n];}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+a+" start = "+a+"("+i+");\n "+a+" end = "+a+"("+o+");\n\n void main() {\n "+a+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+a+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+i+";\n int end = "+o+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n ";},kt=function kt(e,t,n){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");var r=e.filterHeight,a=e.filterWidth,i=e.strideHeight,o=e.strideWidth,s=e.padInfo.top,u=e.padInfo.left;this.outputShape=e.outShape;var c="avg"===t,l="0.0";if(c||(l="-1.0 / 0.0"),n)this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+s+", "+u+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < "+r+"; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+a+"; wC++) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+e.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+a+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var f=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(f="avgValue / count");var p=4*Math.floor(a/4),h=a%4,d="\n if ("+c+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+i+", "+o+");\n const ivec2 pads = ivec2("+s+", "+u+");\n const float initializationValue = "+l+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+e.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+l+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+r+"; wR++) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+e.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC += 4) {\n int xC = xCCorner + wC;\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n getValue(batch, xR, xC + 3, d)\n );\n\n "+d+"\n }\n\n int xC = xCCorner + "+p+";\n if ("+(1===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+d+"\n } else if ("+(2===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n initializationValue,\n initializationValue\n );\n\n "+d+"\n } else if ("+(3===h)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + 1, d),\n getValue(batch, xR, xC + 2, d),\n initializationValue\n );\n\n "+d+"\n }\n }\n setOutput("+f+");\n }\n ";}},Ot=function Ot(e,t){this.variableNames=["x"];var n=e.windowSize,r=e.batchSize,a=e.inSize,i=Math.ceil(a/n);this.outputShape=[r,i];var o="sum"===t,s="0.0";o||(s="min"===t?"1.0 / 0.0":"-1.0 / 0.0");var u="min"===t?"min":"max",c=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===t&&(c="sumValue");var l=4*Math.floor(n/4),f=n%4,p="\n if ("+o+") {\n sumValue += dot(values, ones);\n } else {\n minMaxValue = "+u+"(values, minMaxValue);\n }\n ",h="";a%n>0&&(h="\n if (inIdx < 0 || inIdx >= "+a+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+s+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+h+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n vec4 minMaxValue = vec4("+s+");\n float sumValue = 0.0;\n\n for (int i = 0; i < "+l+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+p+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===f)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n "+p+"\n } else if ("+(2===f)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n "+p+"\n } else if ("+(3===f)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n "+p+"\n }\n setOutput("+c+");\n }\n ";},St=function St(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var r=t.shape,a=r[1],i=r[2],o=e.shape,s=o[1],u=o[2],c=[n&&s>1?a-1:a,n&&u>1?i-1:i],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],f=c[0]/l[0],p=c[1]/l[1],h=1/f,d=1/p,m=2*Math.ceil(h)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+f+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+h+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(a-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(i-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n ";},Nt=function Nt(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var a=e[0],i=e[1],o=e[2],s=e[3];this.outputShape=[a,t,n,s];var u=[r&&t>1?i-1:i,r&&n>1?o-1:o],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/c[0]+",\n "+u[1]/c[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n ";},Et=function Et(e,t,n,r){this.variableNames=["A"],this.outputShape=[];var a=e[0],i=e[1],o=e[2],s=e[3];this.outputShape=[a,t,n,s];var u=r?[i-1,o-1]:[i,o],c=r?[t-1,n-1]:[t,n],l=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/c[0]+",\n "+u[1]/c[1]+");\n const vec2 inputShapeRC = vec2("+i+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+l+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n ";},It=function It(e,t){this.variableNames=["x"];var n=e.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=e,1!==n){var r=e.map(function(n,r){return function(n){return-1!==t.indexOf(n)&&1!==e[n]?e[n]+" - coords["+n+"] - 1":"coords["+n+"]";}(r);}).join(","),a=Q(n);this.userCode="\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n ";}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+e[0]+" - coord - 1));\n }\n ";},Tt=function(){function e(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;var t=Q(this.rank),n=function(e){if(1===e)return"sourceLoc";if(2===e)return"sourceLoc.x, sourceLoc.y";if(3===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z";if(4===e)return"sourceLoc.x, sourceLoc.y, sourceLoc.z, sourceLoc.w";throw Error("Slicing for rank "+e+" is not yet supported");}(this.rank);this.userCode="\n uniform "+t+" start;\n\n void main() {\n "+t+" sourceLoc = start + getOutputCoords();\n setOutput(getSource("+n+"));\n }\n ";}return e.prototype.getCustomSetupFunc=function(e){var t=this;if(e.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+e.length+")");return function(n,r){if(null!=t.startLoc||(t.startLoc=n.getUniformLocationNoThrow(r,"start"),null!=t.startLoc))if(1===t.rank)n.gl.uniform1i(t.startLoc,e[0]);else if(2===t.rank)n.gl.uniform2i(t.startLoc,e[0],e[1]);else if(3===t.rank)n.gl.uniform3i(t.startLoc,e[0],e[1],e[2]);else{if(4!==t.rank)throw Error("Slicing for rank "+t.rank+" is not yet supported");n.gl.uniform4i(t.startLoc,e[0],e[1],e[2],e[3]);}};},e;}(),At=function At(e,t,n){this.variableNames=["x"],this.outputShape=n,this.rank=n.length;var r,a=Q(this.rank);r=1===this.rank?"coords * strides + begin":n.map(function(e,t){return"coords["+t+"] * strides["+t+"] + begin["+t+"]";}).join(","),this.userCode="\n "+a+" begin = "+a+"("+e+");\n "+a+" strides = "+a+"("+t+");\n\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n ";},Ct=function(){function e(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.allocatedTextures=[],this.usedTextureCount={};}return e.prototype.acquireTexture=function(e,t){void 0===t&&(t=x.FLOAT);var n=Pt(e,t);if(n in this.freeTextures||(this.freeTextures[n]=[]),n in this.usedTextureCount||(this.usedTextureCount[n]=0),this.usedTextureCount[n]++,this.freeTextures[n].length>0)return this.numFreeTextures--,this.numUsedTextures++,this.log(),this.freeTextures[n].shift();this.numUsedTextures++,this.log();var r=this.gpgpu.createMatrixTexture(e[0],e[1]);return this.allocatedTextures.push(r),r;},e.prototype.releaseTexture=function(e,t,n){void 0===n&&(n=x.FLOAT);var r=Pt(t,n);r in this.freeTextures||(this.freeTextures[r]=[]),this.freeTextures[r].push(e),this.numFreeTextures++,this.numUsedTextures--,this.usedTextureCount[r]--,this.log();},e.prototype.log=function(){if(this.logEnabled){var e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+e+")");}},e.prototype.getNumUsedTextures=function(){return this.numUsedTextures;},e.prototype.getNumFreeTextures=function(){return this.numFreeTextures;},e.prototype.dispose=function(){var e=this;null!=this.allocatedTextures&&(this.allocatedTextures.forEach(function(t){e.gpgpu.deleteMatrixTexture(t);}),this.freeTextures=null,this.allocatedTextures=null,this.usedTextureCount=null,this.numUsedTextures=0,this.numFreeTextures=0);},e;}();function Pt(e,t){return e[0]+"_"+e[1]+"_"+t;}var _t=function _t(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r<n.length;r++){n[r]=e[r]*t[r];}this.outputShape=n,this.rank=n.length;var a=Q(this.rank),i=function(e){var t=e.length;if(t>4)throw Error("Tile for rank "+t+" is not yet supported");if(1===t)return"imod(resRC, "+e[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[],a=0;a<e.length;a++){r.push("imod("+n[a]+", "+e[a]+")");}return r.join();}(e);this.userCode="\n void main() {\n "+a+" resRC = getOutputCoords();\n setOutput(getA("+i+"));\n }\n ";},Rt=function Rt(e,t){this.variableNames=["A"];for(var n=new Array(e.length),r=0;r<n.length;r++){n[r]=e[t[r]];}this.outputShape=n,this.rank=n.length;var a=Q(this.rank),i=function(e){var t=e.length;if(t>4)throw Error("Transpose for rank "+t+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=new Array(t),a=0;a<e.length;a++){r[e[a]]=n[a];}return r.join();}(t);this.userCode="\n void main() {\n "+a+" resRC = getOutputCoords();\n setOutput(getA("+i+"));\n }\n ";},Mt=n(55),jt=function jt(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode="\n float unaryOperation(float x) {\n "+t+"\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n ";},Dt="if (isNaN(x)) return x;",Lt="\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = "+Mt.b+";\n float scale = "+Mt.a+";\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n",zt=function zt(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},Ft=function Ft(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},Bt=function(){function e(e,t){if(void 0===t&&(t=!0),this.gpgpu=e,this.delayedStorage=t,this.texData=new WeakMap(),this.uploadWaitMs=0,this.downloadWaitMs=0,this.binaryCache={},this.disposed=!1,c.ENV.get("WEBGL_VERSION")<1)throw new Error("WebGL is not supported on this device");"undefined"!=typeof document&&(this.canvas=document.createElement("canvas")),null==e?(this.gpgpu=new pt(We(this.canvas)),this.gpgpuCreatedLocally=!0):this.gpgpuCreatedLocally=!1,this.textureManager=new Ct(this.gpgpu);}return e.prototype.register=function(e,t,n){if(this.texData.has(e))throw new Error("Data buffer is already registered");this.texData.set(e,{shape:t,dtype:n,values:null,texture:null,texShape:null,texType:x.FLOAT});},e.prototype.fromPixels=function(e,t){if(null==e)throw new Error("MathBackendWebGL.writePixels(): pixels can not be null");var n=[e.height,e.width],r=[e.height,e.width,t];if(e instanceof HTMLVideoElement){if(null==this.fromPixelsCanvas){if("undefined"==typeof document)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");if("complete"!==document.readyState)throw new Error("The DOM is not ready yet. Please call tf.fromPixels() once the DOM is ready. One way to do that is to add an event listener for `DOMContentLoaded` on the document object");this.fromPixelsCanvas=document.createElement("canvas");}this.fromPixelsCanvas.width=e.width,this.fromPixelsCanvas.height=e.height,this.fromPixelsCanvas.getContext("2d").drawImage(e,0,0,e.width,e.height),e=this.fromPixelsCanvas;}var a=m.a.make(n,{},"int32");this.texData.get(a.dataId).texType=x.UNSIGNED_BYTE,this.gpgpu.uploadPixelDataToTexture(this.getTexture(a.dataId),e);var i=new ne(r),o=this.compileAndRun(i,[a]);return a.dispose(),o;},e.prototype.write=function(e,t){if(null==t)throw new Error("MathBackendWebGL.write(): values can not be null");this.throwIfNoData(e);var n=this.texData.get(e),r=n.texture,a=n.texShape,i=n.texType;null!=r&&(this.textureManager.releaseTexture(r,a,i),n.texture=null,n.texShape=null),n.values=t,this.delayedStorage||this.uploadToGPU(e);},e.prototype.readSync=function(e){this.throwIfNoData(e);var t=this.texData.get(e),n=t.texture,r=t.values,a=t.texShape;if(null!=r)return this.cacheOnCPU(e),r;var i,o=null!=this.activeTimers;o&&(i=performance.now());var s=this.gpgpu.downloadMatrixFromTexture(n,a[0],a[1]);return o&&(this.downloadWaitMs+=performance.now()-i),this.cacheOnCPU(e,s),t.values;},e.prototype.read=function(e){return zt(this,void 0,void 0,function(){var t,n,r,a,i;return Ft(this,function(o){switch(o.label){case 0:return this.throwIfNoData(e),t=this.texData.get(e),n=t.texture,r=t.values,a=t.texShape,null!=r?(this.cacheOnCPU(e),[2,r]):c.ENV.get("WEBGL_GET_BUFFER_SUB_DATA_ASYNC_EXTENSION_ENABLED")?[4,this.gpgpu.downloadMatrixFromTextureAsync(n,a[0],a[1])]:[3,2];case 1:return i=o.sent(),this.cacheOnCPU(e,i),[2,t.values];case 2:return 0===c.ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?[2,this.readSync(e)]:[4,this.gpgpu.runQuery(function(){})];case 3:return o.sent(),[2,this.readSync(e)];}});});},e.prototype.time=function(e){return zt(this,void 0,void 0,function(){var t,n,r,a,i,o;return Ft(this,function(s){switch(s.label){case 0:return t=this.activeTimers,n=[],r=!1,null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e(),a=y.flatten(this.activeTimers),this.activeTimers=t,r&&(this.programTimersStack=null),[4,Promise.all(a).then(function(e){var t=0;return e.forEach(function(e){return t+=e;}),t;})];case 1:return i=s.sent(),o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:i,wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,o];}});});},e.prototype.memory=function(){return{unreliable:!1};},e.prototype.startTimer=function(){return c.ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:performance.now(),endMs:null};},e.prototype.endTimer=function(e){return c.ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),e):(e.endMs=performance.now(),e);},e.prototype.getQueryTime=function(e){return zt(this,void 0,void 0,function(){var t;return Ft(this,function(n){return c.ENV.get("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.pollQueryTime(e)]:[2,(t=e).endMs-t.startMs];});});},e.prototype.disposeData=function(e){if(this.texData.has(e)){var t=this.texData.get(e),n=t.texture,r=t.texShape,a=t.texType;null!=n&&this.textureManager.releaseTexture(n,r,a),this.texData.delete(e);}},e.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture;},e.prototype.getTextureData=function(e){return this.uploadToGPU(e),this.texData.get(e);},e.prototype.getGPGPUContext=function(){return this.gpgpu;},e.prototype.getCanvas=function(){return this.canvas;},e.prototype.slice=function(e,t,n){var r=new Tt(n),a=r.getCustomSetupFunc(t);return this.compileAndRun(r,[e],null,a);},e.prototype.stridedSlice=function(e,t,n,r,a,i){var o=Object(d.b)(e.shape,t,n,r,a,i),s=o[0],u=o[1];if(u.some(function(e){return 0===e;}))return f.uc([],u);var c=new At(s,r,u);return this.compileAndRun(c,[e]);},e.prototype.reverse=function(e,t){var n=new It(e.shape,t);return this.compileAndRun(n,[e]);},e.prototype.concat=function(e,t){var n=new A(e.shape,t.shape);return this.compileAndRun(n,[e,t]);},e.prototype.neg=function(e){var t=new jt(e.shape,"return -x;");return this.compileAndRun(t,[e]);},e.prototype.matMul=function(e,t,n,r){var a=new vt(e.shape,t.shape,n,r);return this.compileAndRun(a,[e,t]);},e.prototype.multiply=function(e,t){var n=new E("return a * b;",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,g.c(e.dtype,t.dtype));return this.compileAndRun(n,[e,t],r);},e.prototype.batchNormalization=function(e,t,n,r,a,i){var o=[e,t,n],s=null;null!=i&&(s=i.shape,o.push(i));var u=null;null!=a&&(u=a.shape,o.push(a));var c=new N(e.shape,t.shape,n.shape,s,u,r);return this.compileAndRun(c,o);},e.prototype.localResponseNormalization4D=function(e,t,n,r,a){var i=new gt(e.shape,t,n,r,a);return this.compileAndRun(i,[e]);},e.prototype.tile=function(e,t){var n=new _t(e.shape,t);return this.compileAndRun(n,[e]);},e.prototype.pad=function(e,t,n){var r=new xt(e.shape,t,n);return this.compileAndRun(r,[e]);},e.prototype.transpose=function(e,t){var n=new Rt(e.shape,t);return this.compileAndRun(n,[e]);},e.prototype.gather=function(e,t,n){var r=new re(e.shape,t.size,n);return this.compileAndRun(r,[e,t]);},e.prototype.reduce=function(e,t,n){var r=e.shape[0],a=e.shape[1],i=h(a),o=new Ot({windowSize:i,inSize:a,batchSize:r},t),s=o.outputShape,u=s[0],c=s[1],l=this.makeOutputArray([u,c],n);return this.compileAndRun(o,[e],l),1===l.shape[1]?l:this.reduce(l,t,n);},e.prototype.argReduce=function(e,t,n){void 0===n&&(n=null);var r=e.shape[0],a=e.shape[1];null!=n&&(r=n.shape[0],a=n.shape[1]);var i=h(a),o=new k({windowSize:i,inSize:a,batchSize:r},t,null==n),s=o.outputShape,u=s[0],c=s[1],l=this.makeOutputArray([u,c],"int32"),f=[e];return null!=n&&f.push(n),this.compileAndRun(o,f,l),1===l.shape[1]?l:this.argReduce(e,t,l);},e.prototype.sum=function(e,t){l.a("sum",t,e.rank);var n=l.b(e.shape,t),r=n[0],a=n[1],i=y.sizeFromShape(a),o=e.as2D(-1,i),s=g.b(e.dtype);return this.reduce(o,"sum",s).reshape(r);},e.prototype.argMin=function(e,t){var n=[t];l.a("argMin",n,e.rank);var r=l.b(e.shape,n),a=r[0],i=r[1],o=y.sizeFromShape(i),s=e.as2D(-1,o);return this.argReduce(s,"min").reshape(a);},e.prototype.argMax=function(e,t){var n=[t];l.a("argMax",n,e.rank);var r=l.b(e.shape,n),a=r[0],i=r[1],o=y.sizeFromShape(i),s=e.as2D(-1,o);return this.argReduce(s,"max").reshape(a);},e.prototype.cumsum=function(e,t,n,r){if(t!==e.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(e.rank-1)+" but got axis="+t);var a=new ee(e.shape,n,r);return this.compileAndRun(a,[e]);},e.prototype.equal=function(e,t){var n=new E("return float(a == b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r);},e.prototype.notEqual=function(e,t){var n=new E("return float(a != b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r);},e.prototype.less=function(e,t){var n=new E("return float(a < b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r);},e.prototype.lessEqual=function(e,t){var n=new E("return float(a <= b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r);},e.prototype.greater=function(e,t){var n=new E("return float(a > b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r);},e.prototype.greaterEqual=function(e,t){var n=new E("return float(a >= b);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r);},e.prototype.logicalNot=function(e){var t=new jt(e.shape,"return float(!(x >= 1.0));");return this.compileAndRun(t,[e]);},e.prototype.logicalAnd=function(e,t){var n=new E("return float(a >= 1.0 && b >= 1.0);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r);},e.prototype.logicalOr=function(e,t){var n=new E("return float(a >= 1.0 || b >= 1.0);",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[e,t],r);},e.prototype.where=function(e,t,n,r){var a=new mt(e.rank,t.shape,t.rank),i=this.makeOutputArray(a.outputShape,r);return this.compileAndRun(a,[e,t,n],i);},e.prototype.topKValues=function(e,t){throw new Error("topKValues GPU not yet implemented!");},e.prototype.topKIndices=function(e,t){throw new Error("topKIndices GPU not yet implemented!");},e.prototype.min=function(e,t){l.a("min",t,e.rank);var n=l.b(e.shape,t),r=n[0],a=n[1],i=y.sizeFromShape(a),o=e.as2D(-1,i);return this.reduce(o,"min",o.dtype).reshape(r);},e.prototype.minimum=function(e,t){var n=new E("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return min(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t]);},e.prototype.mod=function(e,t){var n=new E("return mod(a, b);",e.shape,t.shape);return this.compileAndRun(n,[e,t]);},e.prototype.max=function(e,t){l.a("max",t,e.rank);var n=l.b(e.shape,t),r=n[0],a=n[1],i=y.sizeFromShape(a),o=e.as2D(-1,i);return this.reduce(o,"max",o.dtype).reshape(r);},e.prototype.maximum=function(e,t){var n=new E("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return max(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t]);},e.prototype.squaredDifference=function(e,t){var n=new E("return (a - b) * (a - b);",e.shape,t.shape);return this.compileAndRun(n,[e,t]);},e.prototype.divide=function(e,t){var n,r;"int32"===e.dtype&&"int32"===t.dtype?(n="\n float resultSign = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n int result = ia / ib;\n int amodb = ia - ib * result;\n\n if (resultSign < 0.0 && amodb != 0) {\n result -= 1;\n }\n return float(result);\n",r="int32"):(n="return a / b;",r="float32");var a=new E(n,e.shape,t.shape),i=this.makeOutputArray(a.outputShape,r);return this.compileAndRun(a,[e,t],i);},e.prototype.add=function(e,t){var n=new E("return a + b;",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,g.c(e.dtype,t.dtype));return this.compileAndRun(n,[e,t],r);},e.prototype.subtract=function(e,t){var n=new E("return a - b;",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,g.c(e.dtype,t.dtype));return this.compileAndRun(n,[e,t],r);},e.prototype.pow=function(e,t){var n=new E("\n return (round(mod(b, 2.0)) == 0 || round(mod(b, 2.0)) == 2) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",e.shape,t.shape),r=this.makeOutputArray(n.outputShape,g.c(e.dtype,t.dtype));return this.compileAndRun(n,[e,t],r);},e.prototype.ceil=function(e){var t=new jt(e.shape,"return ceil(x);");return this.compileAndRun(t,[e]);},e.prototype.floor=function(e){var t=new jt(e.shape,"return floor(x);");return this.compileAndRun(t,[e]);},e.prototype.sign=function(e){var t=new jt(e.shape,"\n if (isNaN(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(t,[e]);},e.prototype.round=function(e){var t=new jt(e.shape,"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n");return this.compileAndRun(t,[e]);},e.prototype.exp=function(e){var t=new jt(e.shape,"return exp(x);");return this.compileAndRun(t,[e]);},e.prototype.expm1=function(e){var t=new jt(e.shape,"return exp(x) - 1.0;");return this.compileAndRun(t,[e]);},e.prototype.log=function(e){var t=new jt(e.shape,"return log(x);");return this.compileAndRun(t,[e]);},e.prototype.log1p=function(e){var t=new jt(e.shape,"return log(1.0 + x);");return this.compileAndRun(t,[e]);},e.prototype.sqrt=function(e){var t=new jt(e.shape,"return sqrt(x);");return this.compileAndRun(t,[e]);},e.prototype.rsqrt=function(e){var t=new jt(e.shape,"return inversesqrt(x);");return this.compileAndRun(t,[e]);},e.prototype.square=function(e){var t=new jt(e.shape,"return x * x;");return this.compileAndRun(t,[e]);},e.prototype.reciprocal=function(e){var t=new jt(e.shape,"return 1.0 / x;");return this.compileAndRun(t,[e]);},e.prototype.relu=function(e){var t=new jt(e.shape,"if (isNaN(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n");return this.compileAndRun(t,[e]);},e.prototype.elu=function(e){var t=new jt(e.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(t,[e]);},e.prototype.eluDer=function(e,t){var n=new E("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,t.shape);return this.compileAndRun(n,[e,t]);},e.prototype.selu=function(e){var t=new jt(e.shape,Lt);return this.compileAndRun(t,[e]);},e.prototype.int=function(e){var t=new jt(e.shape,"return float(int(x));"),n=this.makeOutputArray(t.outputShape,"int32");return this.compileAndRun(t,[e],n);},e.prototype.clip=function(e,t,n){var r=new I(e.shape,t,n);return this.compileAndRun(r,[e]);},e.prototype.abs=function(e){var t=new jt(e.shape,"return abs(x);");return this.compileAndRun(t,[e]);},e.prototype.sigmoid=function(e){var t=new jt(e.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(t,[e]);},e.prototype.softplus=function(e){var t=new jt(e.shape,"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n");return this.compileAndRun(t,[e]);},e.prototype.sin=function(e){var t=new jt(e.shape,"return sin(x);");return this.compileAndRun(t,[e]);},e.prototype.cos=function(e){var t=new jt(e.shape,"return cos(x);");return this.compileAndRun(t,[e]);},e.prototype.tan=function(e){var t=new jt(e.shape,"return tan(x);");return this.compileAndRun(t,[e]);},e.prototype.asin=function(e){var t=new jt(e.shape,"return asin(x);");return this.compileAndRun(t,[e]);},e.prototype.acos=function(e){var t=new jt(e.shape,"return acos(x);");return this.compileAndRun(t,[e]);},e.prototype.atan=function(e){var t=new jt(e.shape,"if (isNaN(x)) return x;\n return atan(x);\n");return this.compileAndRun(t,[e]);},e.prototype.atan2=function(e,t){var n=new E("\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n\n return atan(a, b);\n",e.shape,t.shape);return this.compileAndRun(n,[e,t]);},e.prototype.sinh=function(e){var t=new jt(e.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e]);},e.prototype.cosh=function(e){var t=new jt(e.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[e]);},e.prototype.tanh=function(e){var t=new jt(e.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(t,[e]);},e.prototype.asinh=function(e){var t=new jt(e.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(t,[e]);},e.prototype.acosh=function(e){var t=new jt(e.shape,"return log(x + sqrt(x * x - 1.0));");return this.compileAndRun(t,[e]);},e.prototype.atanh=function(e){var t=new jt(e.shape,"return (log(1.0 + x) - log(1.0 - x)) / 2.0;");return this.compileAndRun(t,[e]);},e.prototype.erf=function(e){var t=new jt(e.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(t,[e]);},e.prototype.step=function(e,t){var n=new jt(e.shape,function(e){return void 0===e&&(e=0),Dt+"\n return x > 0.0 ? 1.0 : float("+e+");\n ";}(t));return this.compileAndRun(n,[e]);},e.prototype.conv2d=function(e,t,n){var r=new M(n);return this.compileAndRun(r,[e,t]);},e.prototype.conv2dDerInput=function(e,t,n){var r=new P(n);return this.compileAndRun(r,[e,t]);},e.prototype.conv2dDerFilter=function(e,t,n){var r=new C(n);return this.compileAndRun(r,[e,t]);},e.prototype.depthwiseConv2D=function(e,t,n){var r=new j(n);return this.compileAndRun(r,[e,t]);},e.prototype.depthwiseConv2DDerInput=function(e,t,n){var r=new R(n);return this.compileAndRun(r,[e,t]);},e.prototype.depthwiseConv2DDerFilter=function(e,t,n){var r=new _(n);return this.compileAndRun(r,[e,t]);},e.prototype.maxPool=function(e,t){var n=new kt(t,"max",!1),r=this.makeOutputArray(n.outputShape,e.dtype);return this.compileAndRun(n,[e],r);},e.prototype.avgPool=function(e,t){var n=new kt(t,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[e],r);},e.prototype.maxPoolBackprop=function(e,t,n,r){var a=new kt(r,"max",!0),i=this.compileAndRun(a,[t]),o=new yt(r),s=this.makeOutputArray(o.outputShape,t.dtype),u=this.compileAndRun(o,[e,i],s);return i.dispose(),u;},e.prototype.avgPoolBackprop=function(e,t,n){var r=new O(n),a=this.makeOutputArray(r.outputShape,t.dtype);return this.compileAndRun(r,[e],a);},e.prototype.cast=function(e,t){return b(e,t,this);},e.prototype.reshape=function(e,t){return w(e,t);},e.prototype.resizeBilinear=function(e,t,n,r){var a=new Nt(e.shape,t,n,r);return this.compileAndRun(a,[e]);},e.prototype.resizeBilinearBackprop=function(e,t,n){var r=new St(e,t,n);return this.compileAndRun(r,[e]);},e.prototype.resizeNearestNeighbor=function(e,t,n,r){var a=new Et(e.shape,t,n,r);return this.compileAndRun(a,[e]);},e.prototype.multinomial=function(e,t,n,r){var a=t?e:f.ec(e),i=a.shape[0],o=a.shape[1],s=new bt(i,o,n),u=this.makeOutputArray(s.outputShape,"int32"),c=s.getCustomSetupFunc(r);return this.compileAndRun(s,[a],u,c);},e.prototype.oneHot=function(e,t,n,r){var a=new wt(e.size,t,n,r);return this.compileAndRun(a,[e]);},e.prototype.makeOutputArray=function(e,t){return m.a.make(e,{},t);},e.prototype.compileAndRun=function(e,t,n,r){var a=this;null==n&&(n=this.makeOutputArray(e.outputShape,t[0].dtype));var i=t.map(function(e){return a.uploadToGPU(e.dataId),{tensor:e,texData:a.texData.get(e.dataId)};});this.uploadToGPU(n.dataId);var o,s={tensor:n,texData:this.texData.get(n.dataId)},u=function(e,t,n){var r="";t.concat(n).forEach(function(e){r+=e.tensor.shape+"_"+e.texData.texShape;});var a=e.userCode,i=(!0===e.supportsBroadcasting).toString();return e.constructor.name+"_"+i+"_"+r+"_"+a;}(e,i,s),c=this.getAndSaveBinary(u,function(){return function(e,t,n,r){for(var a=t.userCode,i=n.map(function(e,n){var r={logicalShape:e.tensor.shape,texShape:e.texData.texShape};return{name:t.variableNames[n],shapeInfo:r};}),o=i.map(function(e){return e.shapeInfo;}),s={logicalShape:r.tensor.shape,texShape:r.texData.texShape},u=q(i,s,a,!0===t.supportsBroadcasting),c=e.createProgram(u),l={},f=0;f<t.variableNames.length;f++){var p=t.variableNames[f];l[p]=e.getUniformLocation(c,p);}return ht()&&(l.NaN=e.getUniformLocation(c,"NaN",!1)),{program:t,source:u,webGLProgram:c,uniformLocations:l,gpgpu:e,inShapeInfos:o,outShapeInfo:s};}(a.gpgpu,e,i,s);}),l=null!=this.activeTimers;return l&&(o=this.startTimer()),function(e,t,n,r){dt(e.inShapeInfos,t),dt([e.outShapeInfo],[n]);var a=n.texData.texture,i=n.texData.texShape,o=e.gpgpu;o.setOutputMatrixTexture(a,i[0],i[1]),o.setProgram(e.webGLProgram),t.forEach(function(t,n){var r=t.texData.texture,a=e.program.variableNames[n],i=e.uniformLocations[a];o.setInputMatrixTexture(r,i,n);}),ht()&&o.gl.uniform1f(e.uniformLocations.NaN,NaN),null!=r&&r(o,e.webGLProgram),o.executeProgram();}(c,i,s,r),l&&(o=this.endTimer(o),this.activeTimers.push(this.getQueryTime(o))),n;},e.prototype.getAndSaveBinary=function(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e];},e.prototype.getTextureManager=function(){return this.textureManager;},e.prototype.dispose=function(){if(!this.disposed){for(var e in this.binaryCache){this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram);}this.textureManager.dispose(),this.canvas.remove(),null!=this.fromPixelsCanvas&&this.fromPixelsCanvas.remove(),this.gpgpuCreatedLocally&&this.gpgpu.dispose(),this.disposed=!0;}},e.prototype.throwIfNoData=function(e){if(!this.texData.has(e))throw new Error("WebGL backend: No data found for this tensor. Did you change your backend in the middle of the program? New backends can't use Tensors created with previous backends");},e.prototype.uploadToGPU=function(e){this.throwIfNoData(e);var t=this.texData.get(e),n=t.shape,r=t.values,a=t.texture,i=(t.dtype,t.texType);if(null==a){var o,s=null!=this.activeTimers;s&&(o=performance.now());var u=Fe(this.gpgpu.gl,n);t.texShape=u;var c=this.textureManager.acquireTexture(u,i);t.texture=c,null!=r&&(this.gpgpu.uploadMatrixToTexture(c,u[0],u[1],r instanceof Float32Array?r:new Float32Array(r)),t.values=null,s&&(this.uploadWaitMs+=performance.now()-o));}},e.prototype.cacheOnCPU=function(e,t){var n=this.delayedStorage,r=this.texData.get(e),a=r.texture,i=r.texShape,o=r.dtype,s=r.texType;n&&null!=a&&(this.textureManager.releaseTexture(a,i,s),r.texture=null,r.texShape=null),null!=t&&(r.values=function(e,t){if("float32"===t)return e;if("int32"===t||"bool"===t){for(var n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length),r=0;r<n.length;++r){n[r]=Math.round(e[r]);}return n;}throw new Error("Unknown dtype "+t);}(t,o));},e;}();c.ENV.registerBackend("webgl",function(){return new Bt();},2);var Vt=n(122),Ut=function Ut(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},Wt=function Wt(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},Gt=function(){function e(){this.data=new WeakMap(),"undefined"!=typeof document&&(this.canvas=document.createElement("canvas"));}return e.prototype.register=function(e,t,n){if(this.data.has(e))throw new Error("Data buffer is already registered");this.data.set(e,null);},e.prototype.write=function(e,t){if(null==t)throw new Error("MathBackendCPU.write(): values can not be null");this.throwIfNoData(e),this.data.set(e,t);},e.prototype.fromPixels=function(e,t){if(null==e)throw new Error("MathBackendCPU.writePixels(): pixels can not be null");var n,r;if(e instanceof ImageData)n=e.data;else if(e instanceof HTMLCanvasElement)n=e.getContext("2d").getImageData(0,0,e.width,e.height).data;else{if(!(e instanceof HTMLImageElement||e instanceof HTMLVideoElement))throw new Error("pixels is of unknown type: "+e.constructor.name);if(null==this.canvas)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.canvas.width=e.width,this.canvas.height=e.height,this.canvas.getContext("2d").drawImage(e,0,0,e.width,e.height),n=this.canvas.getContext("2d").getImageData(0,0,e.width,e.height).data;}if(4===t)r=new Int32Array(n);else{var a=e.width*e.height;r=new Int32Array(a*t);for(var i=0;i<a;i++){for(var o=0;o<t;++o){r[i*t+o]=n[4*i+o];}}}var s=[e.height,e.width,t];return Object(f.xc)(r,s,"int32");},e.prototype.read=function(e){return Ut(this,void 0,void 0,function(){return Wt(this,function(t){return[2,this.readSync(e)];});});},e.prototype.readSync=function(e){return this.throwIfNoData(e),this.data.get(e);},e.prototype.disposeData=function(e){this.data.has(e)&&this.data.delete(e);},e.prototype.time=function(e){return Ut(this,void 0,void 0,function(){var t;return Wt(this,function(n){return t=performance.now(),e(),[2,{kernelMs:performance.now()-t}];});});},e.prototype.memory=function(){return{unreliable:!0};},e.prototype.throwIfNoData=function(e){if(!this.data.has(e))throw new Error("CPU backend: No data found for this tensor. Did you change your backend in the middle of the program? New backends can't use Tensors created with previous backends");},e.prototype.slice=function(e,t,n){for(var r=f.s(n,e.dtype),a=0;a<r.size;++a){var i=r.indexToLoc(a),o=i.map(function(e,n){return e+t[n];});r.set.apply(r,[e.get.apply(e,o)].concat(i));}return r.toTensor();},e.prototype.stridedSlice=function(e,t,n,r,a,i){var o=Object(d.b)(e.shape,t,n,r,a,i),s=o[0],u=o[1];if(u.some(function(e){return 0===e;}))return f.uc([],u);for(var c=f.s(u,e.dtype),l=0;l<c.size;l++){for(var p=c.indexToLoc(l),h=new Array(p.length),m=0;m<h.length;m++){h[m]=p[m]*r[m]+s[m];}c.set.apply(c,[e.get.apply(e,h)].concat(p));}return c.toTensor();},e.prototype.reverse=function(e,t){for(var n=f.s(e.shape,e.dtype),r=e.buffer(),a=function a(_a4){var i=n.indexToLoc(_a4),o=i.slice();t.forEach(function(t){return o[t]=e.shape[t]-1-o[t];}),n.set.apply(n,[r.get.apply(r,o)].concat(i));},i=0;i<n.size;i++){a(i);}return n.toTensor();},e.prototype.concat=function(e,t){var n=T.c(e.shape,t.shape,1),r=f.s(n,e.dtype);if(1===e.shape[0]&&1===t.shape[0]){var a=e.dataSync(),i=t.dataSync(),o=r.values;return o.set(a,0),o.set(i,e.size),r.toTensor();}for(var s=0;s<n[0];++s){for(var u=0;u<e.shape[1];++u){r.set(e.get(s,u),s,u);}for(u=0;u<t.shape[1];++u){r.set(t.get(s,u),s,u+e.shape[1]);}}return r.toTensor();},e.prototype.neg=function(e){return this.multiply(f.Sb(-1),e);},e.prototype.add=function(e,t){return this.broadcastedBinaryOp(e,t,g.c(e.dtype,t.dtype),function(e,t){return e+t;});},e.prototype.subtract=function(e,t){return this.broadcastedBinaryOp(e,t,g.c(e.dtype,t.dtype),function(e,t){return e-t;});},e.prototype.pow=function(e,t){return this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){return Math.pow(e,t);});},e.prototype.matMul=function(e,t,n,r){for(var a=n?e.shape[0]:e.shape[1],i=n?e.shape[1]:e.shape[0],o=r?t.shape[0]:t.shape[1],s=e.dataSync(),u=t.dataSync(),c=n?[1,e.strides[0]]:[e.strides[0],1],l=c[0],p=c[1],h=r?[t.strides[0],1]:[1,t.strides[0]],d=h[0],m=h[1],g=i*l,y=o*d,v=new Float32Array(i*o),b=0,w=0;w<g;w+=l){for(var x=0;x<y;x+=d){for(var k=w,O=x,S=0,N=0;N<a;++N){S+=s[k]*u[O],k+=p,O+=m;}v[b++]=S;}}return f.wc(v,[i,o]);},e.prototype.multiply=function(e,t){return this.broadcastedBinaryOp(e,t,g.c(e.dtype,t.dtype),function(e,t){return e*t;});},e.prototype.divide=function(e,t){var n,r;return"int32"===e.dtype&&"int32"===t.dtype?(r="int32",n=function n(e,t){return Math.floor(e/t);}):(r="float32",n=function n(e,t){return e/t;}),this.broadcastedBinaryOp(e,t,r,n);},e.prototype.sum=function(e,t){l.a("sum",t,e.rank);for(var n=l.b(e.shape,t),r=n[0],a=n[1],i=g.c(e.dtype,"int32"),o=f.Hc(r,i),s=y.sizeFromShape(a),u=o.dataSync(),c=e.dataSync(),p=0;p<u.length;++p){for(var h=p*s,d=0,m=0;m<s;++m){d+=c[h+m];}u[p]=d;}return o;},e.prototype.argMin=function(e,t){var n=[t];l.a("argMin",n,e.rank);for(var r=l.b(e.shape,n),a=r[0],i=r[1],o=f.Hc(a,"int32"),s=y.sizeFromShape(i),u=o.dataSync(),c=e.dataSync(),p=0;p<u.length;++p){for(var h=p*s,d=c[h],m=0,g=0;g<s;++g){var v=c[h+g];v<d&&(d=v,m=g);}u[p]=m;}return o;},e.prototype.argMax=function(e,t){var n=[t];l.a("argMax",n,e.rank);for(var r=l.b(e.shape,n),a=r[0],i=r[1],o=f.Hc(a,"int32"),s=y.sizeFromShape(i),u=o.dataSync(),c=e.dataSync(),p=0;p<u.length;++p){for(var h=p*s,d=c[h],m=0,g=0;g<s;++g){var v=c[h+g];v>d&&(d=v,m=g);}u[p]=m;}return o;},e.prototype.cumsum=function(e,t,n,r){if(t!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" but got axis="+t);for(var a=g.c(e.dtype,"int32"),i=f.Hc(e.shape,a),o=i.dataSync(),s=e.dataSync(),u=e.shape[e.rank-1],c=r?function(e,t){return e+u-t-1;}:function(e,t){return e+t;},l=0;l<s.length;l+=u){for(var p=0;p<u;p++){var h=c(l,p);if(0===p)o[h]=n?0:s[h];else{var d=c(l,p-1);o[h]=n?s[d]+o[d]:s[h]+o[d];}}}return i;},e.prototype.equal=function(e,t){return this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e===t?1:0;});},e.prototype.notEqual=function(e,t){return this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e!==t?1:0;});},e.prototype.less=function(e,t){return this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e<t?1:0;});},e.prototype.lessEqual=function(e,t){return this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e<=t?1:0;});},e.prototype.greater=function(e,t){return this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e>t?1:0;});},e.prototype.greaterEqual=function(e,t){return this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e>=t?1:0;});},e.prototype.logicalNot=function(e){for(var t=e.dataSync(),n=new Int32Array(t.length),r=0;r<t.length;++r){n[r]=t[r]?0:1;}return m.a.make(e.shape,{values:n},"bool");},e.prototype.logicalAnd=function(e,t){return this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e&&t;});},e.prototype.logicalOr=function(e,t){return this.broadcastedBinaryOp(e,t,"bool",function(e,t){return e||t;});},e.prototype.where=function(e,t,n,r){for(var a=e.dataSync(),i=t.dataSync(),o=n.dataSync(),s=f.Hc(t.shape,r),u=s.dataSync(),c=0,l=0===e.rank||e.rank>1||1===t.rank?1:t.shape[1],p=0;p<a.length;p++){for(var h=0;h<l;h++){1===a[p]?u[c++]=i[p]:u[c++]=o[p];}}return s;},e.prototype.topKValues=function(e,t){return this.topK(e,t).values;},e.prototype.topKIndices=function(e,t){return this.topK(e,t).indices;},e.prototype.topK=function(e,t){for(var n=e.dataSync(),r=[],a=0;a<n.length;a++){r.push({value:n[a],index:a});}r.sort(function(e,t){return t.value-e.value;});var i=y.getTypedArrayFromDType(e.dtype,t),o=new Int32Array(t);for(a=0;a<t;a++){i[a]=r[a].value,o[a]=r[a].index;}return{values:f.vc(i,e.dtype),indices:f.vc(o,"int32")};},e.prototype.min=function(e,t){l.a("min",t,e.rank);for(var n=l.b(e.shape,t),r=n[0],a=n[1],i=f.Hc(r,e.dtype),o=y.sizeFromShape(a),s=i.dataSync(),u=e.dataSync(),c=0;c<s.length;++c){for(var p=c*o,h=u[0],d=0;d<o;++d){var m=u[p+d];m<h&&(h=m);}s[c]=h;}return i;},e.prototype.minimum=function(e,t){return this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){return Math.min(e,t);});},e.prototype.mod=function(e,t){return this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){var n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t;});},e.prototype.max=function(e,t){l.a("max",t,e.rank);for(var n=l.b(e.shape,t),r=n[0],a=n[1],i=f.Hc(r,e.dtype),o=y.sizeFromShape(a),s=i.dataSync(),u=e.dataSync(),c=0;c<s.length;++c){for(var p=c*o,h=u[p],d=0;d<o;++d){var m=u[p+d];m>h&&(h=m);}s[c]=h;}return i;},e.prototype.maximum=function(e,t){return this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){return Math.max(e,t);});},e.prototype.squaredDifference=function(e,t){return this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){var n=e-t;return n*n;});},e.prototype.ceil=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){n[r]=Math.ceil(t[r]);}return m.a.make(e.shape,{values:n});},e.prototype.floor=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){n[r]=Math.floor(t[r]);}return m.a.make(e.shape,{values:n});},e.prototype.sign=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){t[r]<0?n[r]=-1:t[r]>0?n[r]=1:n[r]=0;}return m.a.make(e.shape,{values:n});},e.prototype.round=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){var a=Math.floor(t[r]);t[r]-a<.5?n[r]=Math.floor(t[r]):t[r]-a>.5?n[r]=Math.ceil(t[r]):n[r]=a%2==0?a:a+1;}return m.a.make(e.shape,{values:n});},e.prototype.exp=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){n[r]=Math.exp(t[r]);}return m.a.make(e.shape,{values:n});},e.prototype.expm1=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){n[r]=Math.expm1(t[r]);}return m.a.make(e.shape,{values:n});},e.prototype.log=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){var a=t[r];n[r]=Math.log(a);}return m.a.make(e.shape,{values:n});},e.prototype.log1p=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){var a=t[r];n[r]=Math.log1p(a);}return m.a.make(e.shape,{values:n});},e.prototype.sqrt=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){var a=t[r];n[r]=Math.sqrt(a);}return m.a.make(e.shape,{values:n});},e.prototype.rsqrt=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){var a=t[r];n[r]=1/Math.sqrt(a);}return m.a.make(e.shape,{values:n});},e.prototype.square=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){var a=t[r];n[r]=a*a;}return m.a.make(e.shape,{values:n});},e.prototype.reciprocal=function(e){for(var t=e.dataSync(),n=new Float32Array(t.length),r=0;r<t.length;++r){n[r]=1/t[r];}return m.a.make(e.shape,{values:n});},e.prototype.relu=function(e){for(var t=f.Hc(e.shape,e.dtype),n=t.dataSync(),r=e.dataSync(),a=0;a<r.length;++a){n[a]=Math.max(0,r[a]);}return t;},e.prototype.elu=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){var a=n[r];t[r]=a>=0?a:Math.exp(a)-1;}return m.a.make(e.shape,{values:t});},e.prototype.eluDer=function(e,t){for(var n=new Float32Array(t.size),r=t.dataSync(),a=e.dataSync(),i=0;i<r.length;++i){var o=r[i];n[i]=o>=1?a[i]:a[i]*(o+1);}return m.a.make(t.shape,{values:n});},e.prototype.selu=function(e){for(var t=Mt.b,n=Mt.a,r=new Float32Array(e.size),a=e.dataSync(),i=0;i<a.length;++i){var o=a[i];r[i]=o>=0?n*o:t*(Math.exp(o)-1);}return m.a.make(e.shape,{values:r});},e.prototype.clip=function(e,t,n){for(var r=new Float32Array(e.size),a=e.dataSync(),i=0;i<a.length;++i){r[i]=Math.min(n,Math.max(t,a[i]));}return m.a.make(e.shape,{values:r});},e.prototype.abs=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.abs(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.int=function(e){for(var t=new Int32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=n[r];}return m.a.make(e.shape,{values:t},"int32");},e.prototype.sigmoid=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=1/(1+Math.exp(-n[r]));}return m.a.make(e.shape,{values:t});},e.prototype.softplus=function(e){for(var t=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(e.size),r=e.dataSync(),a=0;a<r.length;++a){var i,o=r[a]>-t,s=r[a]<t,u=Math.exp(r[a]);i=s?u:o?r[a]:Math.log(1+u),n[a]=i;}return m.a.make(e.shape,{values:n});},e.prototype.sin=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.sin(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.cos=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.cos(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.tan=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.tan(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.asin=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.asin(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.acos=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.acos(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.atan=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.atan(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.atan2=function(e,t){return this.broadcastedBinaryOp(e,t,e.dtype,function(e,t){return Math.atan2(e,t);});},e.prototype.sinh=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.sinh(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.cosh=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.cosh(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.tanh=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=y.tanh(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.asinh=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.asinh(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.acosh=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.acosh(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.atanh=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){t[r]=Math.atanh(n[r]);}return m.a.make(e.shape,{values:t});},e.prototype.erf=function(e){for(var t=new Float32Array(e.size),n=e.dataSync(),r=0;r<n.length;++r){var a=n[r],i=1/(1+.3275911*a);t[r]=1-((((1.061405429*i-1.453152027)*i+1.421413741)*i-.284496736)*i+.254829592)*i*Math.exp(-a*a);}return m.a.make(e.shape,{values:t});},e.prototype.step=function(e,t){void 0===t&&(t=0);for(var n=new Float32Array(e.size),r=e.dataSync(),a=0;a<r.length;++a){var i=r[a];isNaN(i)?n[a]=NaN:n[a]=i>0?1:t;}return m.a.make(e.shape,{values:n});},e.prototype.conv2d=function(e,t,n){for(var r=n.filterHeight,a=n.filterWidth,i=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c=f.s(n.outShape,e.dtype),l=0;l<n.batchSize;++l){for(var p=0;p<n.outChannels;++p){for(var h=0;h<n.outHeight;++h){for(var d=h*n.strideHeight-s,m=0;m<n.outWidth;++m){for(var g=m*n.strideWidth-u,y=0,v=0;v<r;v++){var b=d+v*i;if(!(b<0||b>=n.inHeight))for(var w=0;w<a;w++){var x=g+w*o;if(!(x<0||x>=n.inWidth))for(var k=0;k<n.inChannels;++k){y+=e.get(l,b,x,k)*t.get(v,w,k,p);}}}c.set(y,l,h,m,p);}}}}return c.toTensor();},e.prototype.conv2dDerInput=function(e,t,n){for(var r=f.s(n.inShape,"float32"),a=r.values,i=r.strides,o=i[0],s=i[1],u=i[2],c=e.dataSync(),l=e.strides,p=l[0],h=l[1],d=l[2],m=t.dataSync(),g=t.strides,y=g[0],v=g[1],b=g[2],w=n.batchSize,x=n.filterHeight,k=n.filterWidth,O=n.inChannels,S=n.inHeight,N=n.inWidth,E=n.outChannels,I=n.outHeight,T=n.outWidth,A=n.strideHeight,C=n.strideWidth,P=x-1-n.padInfo.top,_=k-1-n.padInfo.left,R=0;R<w;++R){for(var M=0;M<O;++M){for(var j=0;j<S;++j){for(var D=j-P,L=Math.max(0,Math.ceil(D/A)),z=Math.min(I,(x+D)/A),F=0;F<N;++F){for(var B=F-_,V=Math.max(0,Math.ceil(B/C)),U=Math.min(T,(k+B)/C),W=0,G=L;G<z;++G){for(var q=G*A-D,H=V;H<U;++H){for(var K=p*R+h*G+d*H,X=y*(x-1-q)+v*(k-1-(H*C-B))+b*M,J=0;J<E;++J){W+=c[K+J]*m[X+J];}}}a[o*R+s*j+u*F+M]=W;}}}}return r.toTensor();},e.prototype.conv2dDerFilter=function(e,t,n){for(var r=n.strideHeight,a=n.strideWidth,i=n.filterHeight,o=n.filterWidth,s=f.s(n.filterShape,"float32"),u=n.padInfo.left,c=n.padInfo.top,l=0;l<i;++l){for(var p=Math.max(0,Math.ceil((c-l)/r)),h=Math.min(n.outHeight,(n.inHeight+c-l)/r),d=0;d<o;++d){for(var m=Math.max(0,Math.ceil((u-d)/a)),g=Math.min(n.outWidth,(n.inWidth+u-d)/a),y=0;y<n.inChannels;++y){for(var v=0;v<n.outChannels;++v){for(var b=0,w=0;w<n.batchSize;++w){for(var x=p;x<h;++x){for(var k=l+x*r-c,O=m;O<g;++O){var S=d+O*a-u;b+=e.get(w,k,S,y)*t.get(w,x,O,v);}}}s.set(b,l,d,y,v);}}}}return s.toTensor();},e.prototype.depthwiseConv2D=function(e,t,n){for(var r=n.filterHeight,a=n.filterWidth,i=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c=n.outChannels/n.inChannels,l=f.s(n.outShape,e.dtype),p=0;p<n.batchSize;++p){for(var h=0;h<n.inChannels;++h){for(var d=0;d<n.outHeight;++d){for(var m=d*n.strideHeight-s,g=0;g<n.outWidth;++g){for(var y=g*n.strideWidth-u,v=0;v<c;++v){for(var b=0,w=0;w<r;++w){var x=m+w*i;if(!(x<0||x>=n.inHeight))for(var k=0;k<a;++k){var O=y+k*o;O<0||O>=n.inWidth||(b+=e.get(p,x,O,h)*t.get(w,k,h,v));}}l.set(b,p,d,g,h*c+v);}}}}}return l.toTensor();},e.prototype.depthwiseConv2DDerInput=function(e,t,n){for(var r=f.s(n.inShape,"float32"),a=r.values,i=r.strides,o=i[0],s=i[1],u=i[2],c=e.dataSync(),l=e.strides,p=l[0],h=l[1],d=l[2],m=t.dataSync(),g=t.strides,y=g[0],v=g[1],b=g[2],w=n.batchSize,x=n.filterHeight,k=n.filterWidth,O=n.inChannels,S=n.inHeight,N=n.inWidth,E=n.outChannels,I=n.outHeight,T=n.outWidth,A=n.strideHeight,C=n.strideWidth,P=x-1-n.padInfo.top,_=k-1-n.padInfo.left,R=E/O,M=0;M<w;++M){for(var j=0;j<O;++j){for(var D=0;D<S;++D){for(var L=D-P,z=Math.max(0,Math.ceil(L/A)),F=Math.min(I,(x+L)/A),B=0;B<N;++B){for(var V=B-_,U=Math.max(0,Math.ceil(V/C)),W=Math.min(T,(k+V)/C),G=0,q=z;q<F;++q){for(var H=q*A-L,K=U;K<W;++K){for(var X=p*M+h*q+d*K,J=y*(x-1-H)+v*(k-1-(K*C-V))+b*j,Y=0;Y<R;++Y){G+=c[X+(j*R+Y)]*m[J+Y];}}}a[o*M+s*D+u*B+j]=G;}}}}return r.toTensor();},e.prototype.depthwiseConv2DDerFilter=function(e,t,n){for(var r=n.strideHeight,a=n.strideWidth,i=n.filterHeight,o=n.filterWidth,s=f.s(n.filterShape,"float32"),u=n.padInfo.left,c=n.padInfo.top,l=n.outChannels/n.inChannels,p=0;p<i;++p){for(var h=Math.max(0,Math.ceil((c-p)/r)),d=Math.min(n.outHeight,(n.inHeight+c-p)/r),m=0;m<o;++m){for(var g=Math.max(0,Math.ceil((u-m)/a)),y=Math.min(n.outWidth,(n.inWidth+u-m)/a),v=0;v<n.outChannels;++v){for(var b=Math.trunc(v/l),w=v%l,x=0,k=0;k<n.batchSize;++k){for(var O=h;O<d;++O){for(var S=p+O*r-c,N=g;N<y;++N){var E=m+N*a-u;x+=e.get(k,S,E,b)*t.get(k,O,N,v);}}}s.set(x,p,m,b,w);}}}return s.toTensor();},e.prototype.tile=function(e,t){for(var n=new Array(e.rank),r=0;r<n.length;r++){n[r]=e.shape[r]*t[r];}var a=f.s(n,e.dtype),i=e.buffer();for(r=0;r<a.values.length;++r){for(var o=a.indexToLoc(r),s=new Array(e.rank),u=0;u<s.length;u++){s[u]=o[u]%e.shape[u];}var c=i.locToIndex(s);a.values[r]=i.values[c];}return a.toTensor();},e.prototype.pad=function(e,t,n){var r=t.map(function(t,n){return t[0]+e.shape[n]+t[1];}),a=t.map(function(e){return e[0];}),i=e.buffer(),o=f.s(r,e.dtype);0!==n&&o.values.fill(n);for(var s=0;s<e.size;s++){var u=i.indexToLoc(s),c=u.map(function(e,t){return e+a[t];});o.set.apply(o,[e.get.apply(e,u)].concat(c));}return o.toTensor();},e.prototype.transpose=function(e,t){for(var n=new Array(e.rank),r=0;r<n.length;r++){n[r]=e.shape[t[r]];}var a=e.dataSync(),i=Object(f.s)(n,e.dtype),o=e.buffer();for(r=0;r<e.size;++r){for(var s=o.indexToLoc(r),u=new Array(s.length),c=0;c<u.length;c++){u[c]=s[t[c]];}var l=i.locToIndex(u);i.values[l]=a[r];}return i.toTensor();},e.prototype.gather=function(e,t,n){var r=e.shape.slice(),a=t.dataSync();r[n]=a.length;for(var i=Object(f.s)(r,e.dtype),o=e.buffer(),s=0;s<i.size;++s){var u=i.indexToLoc(s),c=u.slice();c[n]=a[u[n]];var l=o.locToIndex(c);i.values[s]=o.values[l];}return i.toTensor();},e.prototype.pool=function(e,t,n){for(var r=t.strideHeight,a=t.strideWidth,i=t.filterHeight,o=t.filterWidth,s=f.s(t.outShape,"float32"),u=t.padInfo.top,c=t.padInfo.left,l=0;l<t.batchSize;++l){for(var p=0;p<t.inChannels;++p){for(var h=0;h<t.outHeight;++h){for(var d=h*r-u,m=Math.max(0,d),g=Math.min(t.inHeight,i+d),y=0;y<t.outWidth;++y){for(var v=y*a-c,b=Math.max(0,v),w=Math.min(t.inWidth,o+v),x="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,k=0,O=0,S=m;S<g;++S){for(var N=b;N<w;++N){var E=e.get(l,S,N,p);"max"===n&&E>x?x=E:"avg"===n&&(k+=E,O++);}if(isNaN(x))break;}s.set("avg"===n?k/O:x,l,h,y,p);}}}}return s.toTensor();},e.prototype.maxPool=function(e,t){return this.pool(e,t,"max");},e.prototype.maxPoolPositions=function(e,t){for(var n=f.s(t.outShape,"int32"),r=t.strideHeight,a=t.strideWidth,i=t.filterHeight,o=t.filterWidth,s=t.padInfo.top,u=t.padInfo.left,c=0;c<t.batchSize;++c){for(var l=0;l<t.inChannels;++l){for(var p=0;p<t.outHeight;++p){for(var h=p*r-s,d=Math.max(0,h),m=Math.min(t.inHeight,i+h),g=0;g<t.outWidth;++g){for(var y=g*a-u,v=Math.max(0,y),b=Math.min(t.inWidth,o+y),w=Number.NEGATIVE_INFINITY,x=-1,k=d;k<m;++k){for(var O=k-h,S=v;S<b;++S){var N=S-y,E=e.get(c,k,S,l);E>w&&(w=E,x=O*o+N);}}n.set(x,c,p,g,l);}}}}return n.toTensor();},e.prototype.maxPoolBackprop=function(e,t,n,r){for(var a=this.maxPoolPositions(t,r),i=r.strideHeight,o=r.strideWidth,s=r.filterHeight,u=r.filterWidth,c=u-1-r.padInfo.left,l=s-1-r.padInfo.top,p=f.s(t.shape,"float32"),h=0;h<r.batchSize;++h){for(var d=0;d<r.inChannels;++d){for(var m=0;m<r.inHeight;++m){for(var g=0;g<r.inWidth;++g){for(var y=m-l,v=g-c,b=0,w=0;w<s;++w){var x=(y+w)/i;if(!(x<0||x>=r.outHeight||Math.floor(x)!==x))for(var k=0;k<u;++k){var O=(v+k)/o;if(!(O<0||O>=r.outWidth||Math.floor(O)!==O)){var S=s*u-1-a.get(h,x,O,d)===w*u+k?1:0;0!==S&&(b+=e.get(h,x,O,d)*S);}}}p.set(b,h,m,g,d);}}}}return p.toTensor();},e.prototype.avgPoolBackprop=function(e,t,n){for(var r=n.strideHeight,a=n.strideWidth,i=n.filterHeight,o=n.filterWidth,s=o-1-n.padInfo.left,u=i-1-n.padInfo.top,c=f.s(t.shape,"float32"),l=1/(i*o),p=0;p<n.batchSize;++p){for(var h=0;h<n.inChannels;++h){for(var d=0;d<n.inHeight;++d){for(var m=0;m<n.inWidth;++m){for(var g=d-u,y=m-s,v=0,b=0;b<i;++b){var w=(g+b)/r;if(!(w<0||w>=n.outHeight||Math.floor(w)!==w))for(var x=0;x<o;++x){var k=(y+x)/a;k<0||k>=n.outWidth||Math.floor(k)!==k||(v+=e.get(p,w,k,h));}}c.set(v*l,p,d,m,h);}}}}return c.toTensor();},e.prototype.cast=function(e,t){return b(e,t,this);},e.prototype.reshape=function(e,t){return w(e,t);},e.prototype.avgPool=function(e,t){return this.pool(e,t,"avg").toFloat();},e.prototype.resizeBilinear=function(e,t,n,r){for(var a=e.shape,i=a[0],o=a[1],s=a[2],u=a[3],c=f.s([i,t,n,u],e.dtype),l=[r&&t>1?o-1:o,r&&n>1?s-1:s],p=[r&&t>1?t-1:t,r&&n>1?n-1:n],h=0;h<i;h++){for(var d=0;d<t;d++){for(var m=0;m<n;m++){for(var g=0;g<u;g++){var y=l[0]*d/p[0],v=l[1]*m/p[1],b=Math.floor(y),w=Math.min(o-1,Math.ceil(y)),x=Math.floor(v),k=Math.min(s-1,Math.ceil(v)),O=e.get(h,b,x,g),S=e.get(h,w,x,g),N=v-x,E=O+(e.get(h,b,k,g)-O)*N,I=E+(S+(e.get(h,w,k,g)-S)*N-E)*(y-b);c.set(I,h,d,m,g);}}}}return c.toTensor();},e.prototype.resizeBilinearBackprop=function(e,t,n){for(var r=t.shape,a=r[0],i=r[1],o=r[2],s=r[3],u=e.shape,c=u[1],l=u[2],p=f.s([a,i,o,s],t.dtype),h=[n&&c>1?i-1:i,n&&l>1?o-1:o],d=[n&&c>1?c-1:c,n&&l>1?l-1:l],m=h[0]/d[0],g=h[1]/d[1],y=0;y<a;y++){for(var v=0;v<c;v++){for(var b=v*m,w=Math.floor(b),x=Math.min(Math.ceil(b),i-1),k=b-w,O=1-k,S=0;S<l;S++){for(var N=S*g,E=Math.floor(N),I=Math.min(Math.ceil(N),o-1),T=N-E,A=1-T,C=0;C<s;C++){var P=e.get(y,v,S,C),_=p.get(y,w,E,C);_+=P*O*A,p.set(_,y,w,E,C);var R=p.get(y,w,I,C);R+=P*O*T,p.set(R,y,w,I,C);var M=p.get(y,x,E,C);M+=P*k*A,p.set(M,y,x,E,C);var j=p.get(y,x,I,C);j+=P*k*T,p.set(j,y,x,I,C);}}}}return p.toTensor();},e.prototype.resizeNearestNeighbor=function(e,t,n,r){for(var a=e.shape,i=a[0],o=a[1],s=a[2],u=a[3],c=f.s([i,t,n,u],e.dtype),l=r?[o-1,s-1]:[o,s],p=r?[t-1,n-1]:[t,n],h=0;h<i;h++){for(var d=0;d<t;d++){for(var m=0;m<n;m++){for(var g=0;g<u;g++){var y=l[0]*d/p[0],v=l[1]*m/p[1],b=Math.min(o-1,r?Math.round(y):Math.floor(y)),w=Math.min(s-1,r?Math.round(v):Math.floor(v)),x=e.get(h,b,w,g);c.set(x,h,d,m,g);}}}}return c.toTensor();},e.prototype.batchNormalization=function(e,t,n,r,a,i){for(var o=e.dataSync(),s=t.dataSync(),u=n.dataSync(),c=a?a.dataSync():new Float32Array([1]),l=i?i.dataSync():new Float32Array([0]),p=new Float32Array(o.length),h=0;h<o.length;h++){p[h]=l[h%l.length]+(o[h]-s[h%s.length])*c[h%c.length]/Math.sqrt(u[h%u.length]+r);}return Object(f.yc)(p,e.shape);},e.prototype.localResponseNormalization4D=function(e,t,n,r,a){var i=f.s(e.shape,"float32"),o=t,s=i.shape[3]-1;function u(t,n,r,a){for(var i=0,u=Math.max(0,a-o);u<=Math.min(a+o,s);u++){var c=e.get(t,n,r,u);i+=c*c;}return i;}for(var c=0;c<i.shape[0];c++){for(var l=0;l<=i.shape[1];l++){for(var p=0;p<i.shape[2];p++){for(var h=0;h<i.shape[3];h++){var d=u(c,l,p,h),m=e.get(c,l,p,h)*Math.pow(n+r*d,-a);i.set(m,c,l,p,h);}}}}return i.toTensor();},e.prototype.multinomial=function(e,t,n,r){for(var a=t?e:f.ec(e),i=a.shape[0],o=a.shape[1],s=f.Hc([i,n],"int32"),u=s.dataSync(),c=a.dataSync(),l=0;l<i;++l){var p=l*o,h=new Float32Array(o-1);h[0]=c[p];for(var d=1;d<h.length;++d){h[d]=h[d-1]+c[p+d];}for(var m=Vt.alea(r.toString()),g=l*n,y=0;y<n;++y){var v=m();u[g+y]=h.length;for(var b=0;b<h.length;b++){if(v<h[b]){u[g+y]=b;break;}}}}return s;},e.prototype.oneHot=function(e,t,n,r){var a=new Float32Array(e.size*t);a.fill(r);for(var i=0;i<e.size;++i){a[i*t+e.get(i)]=n;}return f.wc(a,[e.size,t]);},e.prototype.broadcastedBinaryOp=function(e,t,n,r){for(var a=S.a(e.shape,t.shape),i=f.s(a,n),o=e.dataSync(),s=t.dataSync(),u=S.c(e.shape,a),c=S.c(t.shape,a),l=e.buffer(),p=t.buffer(),h=function h(n){var a=i.indexToLoc(n),f=a.slice(-e.rank);u.forEach(function(e){return f[e]=0;});var h=l.locToIndex(f),d=a.slice(-t.rank);c.forEach(function(e){return d[e]=0;});var m=p.locToIndex(d);i.values[n]=r(o[h],s[m]);},d=0;d<i.values.length;++d){h(d);}return i.toTensor();},e.prototype.dispose=function(){},e;}();c.ENV.registerBackend("cpu",function(){return new Gt();},1);var qt=n(2),Ht=function(){function e(){}return e.nextFrame=function(){return new Promise(function(e){return requestAnimationFrame(function(){return e();});});},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}i>3&&o&&Object.defineProperty(t,n,o);}([Object(qt.a)({heading:"Performance",subheading:"Timing"})],e,"nextFrame",null),e;}(),Kt={float32:4,int32:4,uint16:2,uint8:1,bool:1},Xt=function Xt(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},Jt=function Jt(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}};function Yt(e){return Xt(this,void 0,void 0,function(){var t,n,r,a;return Jt(this,function(i){switch(i.label){case 0:for(r in t=[],n=[],e){if("float32"!==(a=e[r]).dtype&&"int32"!==a.dtype&&"bool"!==a.dtype)throw new Error("Unsupported dtype in weight '"+r+"': "+a.dtype);t.push({name:r,shape:a.shape,dtype:a.dtype}),n.push(a.data());}return[4,Promise.all(n)];case 1:return[2,{data:function(e){if(null===e)throw new Error("Invalid input value: "+JSON.stringify(e));var t=0;e.forEach(function(e){if(e instanceof Float32Array||e instanceof Int32Array)t+=4*e.length;else{if(!(e instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+e.constructor.name);t+=e.length;}});var n=new Uint8Array(t),r=0;return e.forEach(function(e){n.set(new Uint8Array(e.buffer),r),e instanceof Float32Array||e instanceof Int32Array?r+=4*e.length:r+=e.length;}),n.buffer;}(i.sent()),specs:t}];}});});}function Qt(e,t){for(var n={},r=0,a=0,i=t;a<i.length;a++){var o=i[a],s=o.name,u=o.dtype,c=o.shape;if(null!=o.quantization)throw new Error("decodeWeights does not support quantization yet, but encountered weight '"+s+" with quantization.'");var l=Object(y.sizeFromShape)(c),f=void 0;if("float32"===u)f=v.a.tensor(new Float32Array(e,r,l),c,"float32");else if("int32"===u)f=v.a.tensor(new Int32Array(e,r,l),c,"int32");else{if("bool"!==u)throw new Error("Unsupported dtype in weight '"+s+"': "+u);f=v.a.tensor(new Uint8Array(e,r,l),c,"bool");}n[s]=f,r+=l*Kt[u];}return n;}function Zt(e){return new Blob([e]).size;}function $t(e){var t=0;e.forEach(function(e){t+=e.byteLength;});var n=new Uint8Array(t),r=0;return e.forEach(function(e){n.set(new Uint8Array(e),r),r+=e.byteLength;}),n.buffer;}function en(e){for(e=e.trim();e.endsWith("/");){e=e.slice(0,e.length-1);}var t=e.split("/");return t[t.length-1];}function tn(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date(),modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:Zt(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:Zt(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength};}var nn=function(){function e(){this.saveRouters=[],this.loadRouters=[];}return e.getInstance=function(){return null==e.instance&&(e.instance=new e()),e.instance;},e.registerSaveRouter=function(t){e.getInstance().saveRouters.push(t);},e.registerLoadRouter=function(t){e.getInstance().loadRouters.push(t);},e.getSaveHandlers=function(t){return e.getHandlers(t,"save");},e.getLoadHandlers=function(t){return e.getHandlers(t,"load");},e.getHandlers=function(e,t){var n=[];return("load"===t?this.getInstance().loadRouters:this.getInstance().saveRouters).forEach(function(t){var r=t(e);null!==r&&n.push(r);}),n;},e;}(),rn=function rn(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},an=function an(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},on=function on(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},sn="://",un=function(){function e(){this.managers={};}return e.getInstance=function(){return null==e.instance&&(e.instance=new e()),e.instance;},e.registerManager=function(t,n){Object(y.assert)(null!=t,"scheme must not be undefined or null."),t.endsWith(sn)&&(t=t.slice(0,t.indexOf(sn))),Object(y.assert)(t.length>0,"scheme must not be an empty string.");var r=e.getInstance();Object(y.assert)(null==r.managers[t],"A model store manager is already registered for scheme '"+t+"'."),r.managers[t]=n;},e.getManager=function(e){var t=this.getInstance().managers[e];if(null==t)throw new Error("Cannot find model manager for scheme '"+e+"'");return t;},e.getSchemes=function(){return Object.keys(this.getInstance().managers);},e;}();function cn(e){if(-1===e.indexOf(sn))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+un.getSchemes().join(","));return{scheme:e.split(sn)[0],path:e.split(sn)[1]};}function ln(e,t,n){return void 0===n&&(n=!1),an(this,void 0,void 0,function(){var r,a,i,o,s,u,c,l,f;return on(this,function(p){switch(p.label){case 0:return Object(y.assert)(e!==t,"Old path and new path are the same: '"+e+"'"),r=nn.getLoadHandlers(e),Object(y.assert)(r.length>0,"Copying failed because no load handler is found for source URL "+e+"."),Object(y.assert)(r.length<2,"Copying failed because more than one ("+r.length+") load handlers for source URL "+e+"."),a=r[0],i=nn.getSaveHandlers(t),Object(y.assert)(i.length>0,"Copying failed because no save handler is found for destination URL "+t+"."),Object(y.assert)(i.length<2,"Copying failed because more than one ("+r.length+") save handlers for destination URL "+t+"."),o=i[0],s=cn(e).scheme,u=cn(e).path,c=s===cn(e).scheme,[4,a.load()];case 1:return l=p.sent(),n&&c?[4,un.getManager(s).removeModel(u)]:[3,3];case 2:p.sent(),p.label=3;case 3:return[4,o.save(l)];case 4:return f=p.sent(),!n||c?[3,6]:[4,un.getManager(s).removeModel(u)];case 5:p.sent(),p.label=6;case 6:return[2,f.modelArtifactsInfo];}});});}var fn=function(){function e(){}return e.listModels=function(){return an(this,void 0,void 0,function(){var e,t,n,r,a,i,o;return on(this,function(s){switch(s.label){case 0:e=un.getSchemes(),t={},n=0,r=e,s.label=1;case 1:return n<r.length?(a=r[n],[4,un.getManager(a).listModels()]):[3,4];case 2:for(o in i=s.sent()){t[a+sn+o]=i[o];}s.label=3;case 3:return n++,[3,1];case 4:return[2,t];}});});},e.removeModel=function(e){return an(this,void 0,void 0,function(){var t;return on(this,function(n){switch(n.label){case 0:return t=cn(e),[4,un.getManager(t.scheme).removeModel(t.path)];case 1:return[2,n.sent()];}});});},e.copyModel=function(e,t){return an(this,void 0,void 0,function(){return on(this,function(n){switch(n.label){case 0:return[4,ln(e,t,!1)];case 1:return[2,n.sent()];}});});},e.moveModel=function(e,t){return an(this,void 0,void 0,function(){return on(this,function(n){switch(n.label){case 0:return[4,ln(e,t,!0)];case 1:return[2,n.sent()];}});});},rn([Object(qt.a)({heading:"Models",subheading:"Management"})],e,"listModels",null),rn([Object(qt.a)({heading:"Models",subheading:"Management"})],e,"removeModel",null),rn([Object(qt.a)({heading:"Models",subheading:"Management"})],e,"copyModel",null),rn([Object(qt.a)({heading:"Models",subheading:"Management"})],e,"moveModel",null),e;}(),pn=function pn(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},hn=function hn(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},dn="tensorflowjs",mn="models_store",gn="model_info_store";function yn(){if(!c.ENV.get("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var e=window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t;}function vn(e){var t=e.result;t.createObjectStore(mn,{keyPath:"modelPath"}),t.createObjectStore(gn,{keyPath:"modelPath"});}var bn=function(){function e(e){if(this.indexedDB=yn(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e;}return e.prototype.save=function(e){return pn(this,void 0,void 0,function(){return hn(this,function(t){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,e)];});});},e.prototype.load=function(){return pn(this,void 0,void 0,function(){return hn(this,function(e){return[2,this.databaseAction(this.modelPath)];});});},e.prototype.databaseAction=function(e,t){var n=this;return new Promise(function(e,r){var a=n.indexedDB.open(dn,1);a.onupgradeneeded=function(){return vn(a);},a.onsuccess=function(){var i=a.result;if(null==t){var o=i.transaction(mn,"readonly"),s=o.objectStore(mn).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return i.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));e(s.result.modelArtifacts);},s.onerror=function(e){return i.close(),r(s.error);},o.oncomplete=function(){return i.close();};}else{var u,c=tn(t),l=i.transaction(gn,"readwrite"),f=l.objectStore(gn),p=f.put({modelPath:n.modelPath,modelArtifactsInfo:c});p.onsuccess=function(){var a=(u=i.transaction(mn,"readwrite")).objectStore(mn).put({modelPath:n.modelPath,modelArtifacts:t,modelArtifactsInfo:c});a.onsuccess=function(){return e({modelArtifactsInfo:c});},a.onerror=function(e){var t=(f=l.objectStore(gn)).delete(n.modelPath);t.onsuccess=function(){return i.close(),r(a.error);},t.onerror=function(e){return i.close(),r(a.error);};};},p.onerror=function(e){return i.close(),r(p.error);},l.oncomplete=function(){null==u?i.close():u.oncomplete=function(){return i.close();};};}},a.onerror=function(e){return r(a.error);};});},e.URL_SCHEME="indexeddb://",e;}(),wn=function wn(e){return c.ENV.get("IS_BROWSER")&&e.startsWith(bn.URL_SCHEME)?function(e){return new bn(e);}(e.slice(bn.URL_SCHEME.length)):null;};nn.registerSaveRouter(wn),nn.registerLoadRouter(wn);var xn=function(){function e(){this.indexedDB=yn();}return e.prototype.listModels=function(){return pn(this,void 0,void 0,function(){var e=this;return hn(this,function(t){return[2,new Promise(function(t,n){var r=e.indexedDB.open(dn,1);r.onupgradeneeded=function(){return vn(r);},r.onsuccess=function(){var e=r.result,a=e.transaction(gn,"readonly"),i=a.objectStore(gn).getAll();i.onsuccess=function(){for(var e={},n=0,r=i.result;n<r.length;n++){var a=r[n];e[a.modelPath]=a.modelArtifactsInfo;}t(e);},i.onerror=function(t){return e.close(),n(i.error);},a.oncomplete=function(){return e.close();};},r.onerror=function(e){return n(r.error);};})];});});},e.prototype.removeModel=function(e){return pn(this,void 0,void 0,function(){var t=this;return hn(this,function(n){return e=function(e){return e.startsWith(bn.URL_SCHEME)?e.slice(bn.URL_SCHEME.length):e;}(e),[2,new Promise(function(n,r){var a=t.indexedDB.open(dn,1);a.onupgradeneeded=function(){return vn(a);},a.onsuccess=function(){var t,i=a.result,o=i.transaction(gn,"readwrite"),s=o.objectStore(gn),u=s.get(e);u.onsuccess=function(){if(null==u.result)return i.close(),r(new Error("Cannot find model with path '"+e+"' in IndexedDB."));var a=s.delete(e),o=function o(){var a=(t=i.transaction(mn,"readwrite")).objectStore(mn).delete(e);a.onsuccess=function(){return n(u.result.modelArtifactsInfo);},a.onerror=function(e){return r(u.error);};};a.onsuccess=o,a.onerror=function(e){return o(),i.close(),r(u.error);};},u.onerror=function(e){return i.close(),r(u.error);},o.oncomplete=function(){null==t?i.close():t.oncomplete=function(){return i.close();};};},a.onerror=function(e){return r(a.error);};})];});});},e;}();if(c.ENV.get("IS_BROWSER"))try{un.registerManager(bn.URL_SCHEME,new xn());}catch(e){}var kn=function kn(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},On=function On(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},Sn="/",Nn="tensorflowjs_models",En="info",In="model_topology",Tn="weight_specs",An="weight_data";function Cn(e){return{info:[Nn,e,En].join(Sn),topology:[Nn,e,In].join(Sn),weightSpecs:[Nn,e,Tn].join(Sn),weightData:[Nn,e,An].join(Sn)};}function Pn(e){var t=e.split(Sn);if(t.length<3)throw new Error("Invalid key format: "+e);return t.slice(1,t.length-1).join(Sn);}var _n=function(){function e(e){if(!c.ENV.get("IS_BROWSER")||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Cn(this.modelPath);}return e.prototype.save=function(e){return kn(this,void 0,void 0,function(){var t,n,r,a;return On(this,function(i){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=tn(e);try{return this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e)));}(e.weightData)),[2,{modelArtifactsInfo:r}];}catch(e){for(a in this.keys){this.LS.removeItem(this.keys[a]);}throw new Error("Failed to save model '"+this.modelPath+"' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes="+r.modelTopologyBytes+", weightSpecsBytes="+r.weightSpecsBytes+", weightDataBytes="+r.weightDataBytes+".");}return[2];});});},e.prototype.load=function(){return kn(this,void 0,void 0,function(){var e,t,n,r,a;return On(this,function(i){if(null==(e=JSON.parse(this.LS.getItem(this.keys.info))))throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(t={},null==(n=JSON.parse(this.LS.getItem(this.keys.topology))))throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(t.modelTopology=n,null==(r=JSON.parse(this.LS.getItem(this.keys.weightSpecs))))throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(t.weightSpecs=r,null==(a=this.LS.getItem(this.keys.weightData)))throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return t.weightData=function(e){for(var t=atob(a),n=new Uint8Array(t.length),r=0;r<t.length;++r){n.set([t.charCodeAt(r)],r);}return n.buffer;}(),[2,t];});});},e.URL_SCHEME="localstorage://",e;}(),Rn=function Rn(e){return c.ENV.get("IS_BROWSER")&&e.startsWith(_n.URL_SCHEME)?function(e){return new _n(e);}(e.slice(_n.URL_SCHEME.length)):null;};nn.registerSaveRouter(Rn),nn.registerLoadRouter(Rn);var Mn=function(){function e(){Object(y.assert)(c.ENV.get("IS_BROWSER"),"Current environment is not a web browser"),Object(y.assert)(void 0!==window.localStorage,"Current browser does not appear to support localStorage"),this.LS=window.localStorage;}return e.prototype.listModels=function(){return kn(this,void 0,void 0,function(){var e,t,n,r,a,i;return On(this,function(o){for(e={},t=Nn+Sn,n=Sn+En,r=0;r<this.LS.length;++r){(a=this.LS.key(r)).startsWith(t)&&a.endsWith(n)&&(i=Pn(a),e[i]=JSON.parse(this.LS.getItem(a)));}return[2,e];});});},e.prototype.removeModel=function(e){return kn(this,void 0,void 0,function(){var t,n;return On(this,function(r){if(e=function(e){return e.startsWith(_n.URL_SCHEME)?e.slice(_n.URL_SCHEME.length):e;}(e),t=Cn(e),null==this.LS.getItem(t.info))throw new Error("Cannot find model at path '"+e+"'");return n=JSON.parse(this.LS.getItem(t.info)),this.LS.removeItem(t.info),this.LS.removeItem(t.topology),this.LS.removeItem(t.weightSpecs),this.LS.removeItem(t.weightData),[2,n];});});},e;}();if(c.ENV.get("IS_BROWSER"))try{un.registerManager(_n.URL_SCHEME,new Mn());}catch(e){}var jn=function jn(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},Dn=function Dn(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},Ln="model",zn=".json",Fn=".weights.bin",Bn=function(){function e(t){if(!c.ENV.get("IS_BROWSER"))throw new Error("triggerDownloads() cannot proceed because the current environment is not a browser.");t.startsWith(e.URL_SCHEME)&&(t=t.slice(e.URL_SCHEME.length)),null!=t&&0!==t.length||(t=Ln),this.modelTopologyFileName=t+zn,this.weightDataFileName=t+Fn;}return e.prototype.save=function(e){return jn(this,void 0,void 0,function(){var t,n,r,a,i,o;return Dn(this,function(s){if(t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"})),e.modelTopology instanceof ArrayBuffer)throw new Error("DownloadTrigger.save() does not support saving model topology in binary formats yet.");return n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,weightsManifest:n},a=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),(i=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,i.href=a,i.click(),null!=e.weightData&&((o=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,o.href=t,o.click()),[2,{modelArtifactsInfo:tn(e)}];});});},e.URL_SCHEME="downloads://",e;}(),Vn=function(){function e(e){if(null==e||e.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+e);this.files=e;}return e.prototype.load=function(){return jn(this,void 0,void 0,function(){var e,t,n=this;return Dn(this,function(r){return e=this.files[0],t=this.files.slice(1),[2,new Promise(function(r,a){var i=new FileReader();i.onload=function(i){var o=JSON.parse(i.target.result),s=o.modelTopology;if(null!=s){0===t.length&&r({modelTopology:s});var u=o.weightsManifest;if(null!=u){var c;try{c=n.checkManifestAndWeightFiles(u,t);}catch(e){return void a(e);}var l=[],f=[],p=[];u.forEach(function(e){e.paths.forEach(function(e){f.push(e),p.push(null);}),l.push.apply(l,e.weights);}),u.forEach(function(e){e.paths.forEach(function(e){var t=new FileReader();t.onload=function(t){var n=t.target.result,a=f.indexOf(e);p[a]=n,-1===p.indexOf(null)&&r({modelTopology:s,weightSpecs:l,weightData:$t(p)});},t.onerror=function(t){a("Failed to weights data from file of path '"+e+"'.");},t.readAsArrayBuffer(c[e]);});});}else a(new Error("weightManifest field is missing from file "+e.name));}else a(new Error("modelTopology field is missing from file "+e.name));},i.onerror=function(t){a("Failed to read model topology and weights manifest JSON from file '"+e.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.");},i.readAsText(e);})];});});},e.prototype.checkManifestAndWeightFiles=function(e,t){for(var n=[],r=t.map(function(e){return en(e.name);}),a={},i=0,o=e;i<o.length;i++){o[i].paths.forEach(function(e){var i=en(e);if(-1!==n.indexOf(i))throw new Error("Duplicate file basename found in weights manifest: '"+i+"'");if(n.push(i),-1===r.indexOf(i))throw new Error("Weight file with basename '"+i+"' is not provided.");a[e]=t[r.indexOf(i)];});}if(n.length!==t.length)throw new Error("Mismatch in the number of files in weights manifest ("+n.length+") and the number of weight files provided ("+t.length+").");return a;},e;}();function Un(e){return new Vn(e);}nn.registerSaveRouter(function(e){return c.ENV.get("IS_BROWSER")&&e.startsWith(Bn.URL_SCHEME)?function(e){return void 0===e&&(e="model"),new Bn(e);}(e.slice(Bn.URL_SCHEME.length)):null;});var Wn=function Wn(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},Gn=function Gn(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}};function qn(e,t){return Wn(this,void 0,void 0,function(){var n,r;return Gn(this,function(a){switch(a.label){case 0:return n=e.map(function(e){return fetch(e,t);}),[4,Promise.all(n)];case 1:return r=a.sent(),[4,Promise.all(r.map(function(e){return e.arrayBuffer();}))];case 2:return[2,a.sent()];}});});}function Hn(e,t,n,r){return void 0===t&&(t=""),Wn(this,void 0,void 0,function(){var a,i,o,s,u,c,l,p,h,d;return Gn(this,function(m){switch(m.label){case 0:if(a=e.map(function(){return!1;}),i={},o=null!=n?n.map(function(){return!1;}):[],s=[],e.forEach(function(e,t){var r=0;e.weights.forEach(function(e){var u="quantization"in e?e.quantization.dtype:e.dtype,c=Kt[u]*y.sizeFromShape(e.shape),l=function l(){a[t]=!0,null==i[t]&&(i[t]=[]),i[t].push({manifestEntry:e,groupOffset:r,sizeBytes:c});};null!=n?n.forEach(function(t,n){t===e.name&&(l(),o[n]=!0);}):l(),s.push(e.name),r+=c;});}),!o.every(function(e){return e;}))throw u=n.filter(function(e,t){return!o[t];}),new Error("Could not find weights in manifest with names: "+u.join(", ")+". \nManifest JSON has weights with names: "+s.join(", ")+".");return c=a.reduce(function(e,t,n){return t&&e.push(n),e;},[]),l=[],c.forEach(function(n){e[n].paths.forEach(function(e){var n=t+(t.endsWith("/")?"":"/")+e;l.push(n);});}),[4,qn(l,r)];case 1:return p=m.sent(),h={},d=0,c.forEach(function(t){for(var n=e[t].paths.length,r=0,a=0;a<n;a++){r+=p[d+a].byteLength;}for(var o=new ArrayBuffer(r),s=new Uint8Array(o),u=0,c=0;c<n;c++){var l=new Uint8Array(p[d+c]);s.set(l,u),u+=l.byteLength;}i[t].forEach(function(e){var t,n=o.slice(e.groupOffset,e.groupOffset+e.sizeBytes),r=e.manifestEntry.dtype;if("quantization"in e.manifestEntry){var a=e.manifestEntry.quantization;if("uint8"!==a.dtype&&"uint16"!==a.dtype)throw new Error("Weight "+e.manifestEntry.name+" has unknown quantization dtype "+a.dtype+".");var i="uint8"===a.dtype?new Uint8Array(n):new Uint16Array(n);if("float32"===r)t=Float32Array.from(i,function(e){return e*a.scale+a.min;});else{if("int32"!==r)throw new Error("Weight "+e.manifestEntry.name+" has a dtype not supported by quantization: "+r);t=Int32Array.from(i,function(e){return Math.round(e*a.scale+a.min);});}}else if("float32"===r)t=new Float32Array(n);else{if("int32"!==r)throw new Error("Weight "+e.manifestEntry.name+" has unknown dtype "+r+".");t=new Int32Array(n);}var s=e.manifestEntry.name;if(null!=h[s])throw new Error("Duplicate weight with name "+s+". Please make sure weights names are unique in the manifest JSON.");h[s]=Object(f.uc)(t,e.manifestEntry.shape,e.manifestEntry.dtype);}),d+=n;}),[2,h];}});});}var Kn=function Kn(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},Xn=function Xn(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},Jn=function(){function e(e,t){if(this.DEFAULT_METHOD="POST",!c.ENV.get("IS_BROWSER"))throw new Error("browserHTTPRequest is not supported outside the web browser.");if(Object(y.assert)(null!=e&&e.length>0,"URL path for browserHTTPRequest must not be null, undefined or empty."),this.path=e,null!=t&&null!=t.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t||{};}return e.prototype.save=function(e){return Kn(this,void 0,void 0,function(){var t,n,r,a;return Xn(this,function(i){switch(i.label){case 0:if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData(),n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,weightsManifest:n},t.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,fetch(this.path,t)];case 1:if(200===(a=i.sent()).status)return[2,{modelArtifactsInfo:tn(e),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".");}});});},e.prototype.load=function(){return Kn(this,void 0,void 0,function(){var e,t,n,r,a,i,o,s,u,c,l,f;return Xn(this,function(p){switch(p.label){case 0:return[4,fetch(this.path,this.requestInit)];case 1:return[4,p.sent().json()];case 2:if(e=p.sent(),t=e.modelTopology,n=e.weightsManifest,null==t&&null==n)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");if(null==n)return[3,4];for(i=e.weightsManifest,r=[],o=0,s=i;o<s.length;o++){u=s[o],r.push.apply(r,u.weights);}return(c=this.path.substring(0,this.path.lastIndexOf("/"))).endsWith("/")||(c+="/"),l=[],i.forEach(function(e){e.paths.forEach(function(e){l.push(c+e);});}),f=$t,[4,qn(l,this.requestInit)];case 3:a=f.apply(void 0,[p.sent()]),p.label=4;case 4:return[2,{modelTopology:t,weightSpecs:r,weightData:a}];}});});},e.URL_SCHEMES=["http://","https://"],e;}();function Yn(e,t){return new Jn(e,t);}nn.registerSaveRouter(function(e){if(c.ENV.get("IS_BROWSER")){for(var t=0,n=Jn.URL_SCHEMES;t<n.length;t++){var r=n[t];if(e.startsWith(r))return Yn(e);}return null;}return null;});var Qn=nn.registerSaveRouter,Zn=nn.registerLoadRouter,$n=nn.getSaveHandlers,er=nn.getLoadHandlers,tr=fn.copyModel,nr=fn.listModels,rr=fn.moveModel,ar=fn.removeModel,ir=function(){function e(){}return e.prototype.getClassName=function(){return this.constructor.className;},e.fromConfig=function(e,t){return new e(t);},e;}(),or=function(){function e(){this.classNameMap={};}return e.getMap=function(){return null==e.instance&&(e.instance=new e()),e.instance;},e.register=function(e){this.getMap().classNameMap[e.className]=[e,e.fromConfig];},e;}(),sr={BACKEND:"test-webgl"},ur={BACKEND:"test-cpu"},cr={},lr=.001;function fr(e,t,n){if(void 0===n&&(n=lr),e instanceof m.a||t instanceof m.a){if(e instanceof m.a&&t instanceof m.a){if(e.dtype!==t.dtype)throw new Error("Arrays are of different type actual: "+e.dtype+" vs expected: "+t.dtype+".");if(!y.arraysEqual(e.shape,t.shape))throw new Error("Arrays are of different shape actual: "+e.shape+" vs expected: "+t.shape+".");}}else{var r=e.constructor.name,a=t.constructor.name;if(r!==a)throw new Error("Arrays are of different type actual: "+r+" vs expected: "+a);}var i,o;if(i=e instanceof m.a?e.dataSync():e,o=t instanceof m.a?t.dataSync():t,i.length!==o.length)throw new Error("Arrays have different lengths actual: "+i.length+" vs expected: "+o.length+".\nActual: "+i+".\nExpected: "+o+".");for(var s=0;s<o.length;++s){var u=i[s],c=o[s];if(!mr(u,Number(c),n))throw new Error("Arrays differ: actual["+s+"] = "+u+", expected["+s+"] = "+c+".\nActual: "+i+".\nExpected: "+o+".");}}function pr(e,t){e().then(function(){return t.fail();},function(){return t();});}function hr(e,t){return fr(e,t,0);}function dr(e,t,n){if(void 0===n&&(n=lr),!mr(e,t,n))throw new Error("Numbers differ: actual === "+e+", expected === "+t);}function mr(e,t,n){return!(!isNaN(e)||!isNaN(t))||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n);}function gr(e,t,n){var r;r=e instanceof m.a?e.dataSync():e;for(var a=0;a<r.length;a++){if(r[a]<t||r[a]>n)throw new Error("Value out of range:"+r[a]+" low: "+t+", high: "+n);}}var yr=n(7),vr=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),br=function br(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},wr=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return vr(t,e),t.prototype.minimize=function(e,t,n){void 0===t&&(t=!1);var r=this.computeGradients(e,n),a=r.value,i=r.grads;return this.applyGradients(i),Object.keys(i).forEach(function(e){return i[e].dispose();}),t?a:(a.dispose(),null);},t.prototype.computeGradients=function(e,t){return Object(yr.j)(e,t);},br([Object(qt.a)({heading:"Training",subheading:"Optimizers"})],t.prototype,"minimize",null),br([Object(qt.a)({heading:"Training",subheading:"Classes",namespace:"train"})],t);}(ir),xr=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),kr=function(e){function t(t,n,r){void 0===r&&(r=1e-8);var a=e.call(this)||this;return a.learningRate=t,a.rho=n,a.epsilon=r,a.accumulatedGrads={},a.accumulatedUpdates={},a.c=Object(yr.e)(Object(f.Sb)(-t)),a.epsilonScalar=Object(yr.e)(Object(f.Sb)(r)),a.rhoScalar=Object(yr.e)(Object(f.Sb)(n)),a.oneMinusRho=Object(yr.e)(Object(f.Sb)(1-n)),a;}return xr(t,e),t.prototype.applyGradients=function(e){var t=this,n=function n(_n5){var a=c.ENV.engine.registeredVariables[_n5];null==r.accumulatedGrads[_n5]&&Object(yr.f)(function(){t.accumulatedGrads[_n5]=Object(f.Ic)(a).variable(!1);}),null==r.accumulatedUpdates[_n5]&&Object(yr.f)(function(){t.accumulatedUpdates[_n5]=Object(f.Ic)(a).variable(!1);});var i=e[_n5],o=r.accumulatedGrads[_n5],s=r.accumulatedUpdates[_n5];Object(yr.f)(function(){var e=t.rhoScalar.mul(o).add(t.oneMinusRho.mul(i.square())),r=s.add(t.epsilonScalar).sqrt().div(o.add(t.epsilonScalar).sqrt()).mul(i),u=t.rhoScalar.mul(s).add(t.oneMinusRho.mul(r.square()));t.accumulatedGrads[_n5].assign(e),t.accumulatedUpdates[_n5].assign(u);var c=t.c.mul(r).add(a);a.assign(c);});},r=this;for(var a in e){n(a);}},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.rhoScalar.dispose(),this.oneMinusRho.dispose(),null!=this.accumulatedUpdates&&(Object.keys(this.accumulatedUpdates).forEach(function(t){return e.accumulatedUpdates[t].dispose();}),Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose();}));},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon};},t.fromConfig=function(e,t){return new e(t.learningRate,t.rho,t.epsilon);},t.className="AdadeltaOptimizer",t;}(wr);or.register(kr);var Or=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Sr=function(e){function t(t,n){void 0===n&&(n=.1);var r=e.call(this)||this;return r.learningRate=t,r.initialAccumulatorValue=n,r.accumulatedGrads={},r.c=Object(yr.e)(Object(f.Sb)(-t)),r.epsilon=Object(yr.e)(Object(f.Sb)(1e-8)),r;}return Or(t,e),t.prototype.applyGradients=function(e){var t=this,n=function n(_n6){var a=c.ENV.engine.registeredVariables[_n6];null==r.accumulatedGrads[_n6]&&Object(yr.f)(function(){t.accumulatedGrads[_n6]=Object(f.U)(a.shape,t.initialAccumulatorValue).variable(!1);});var i=e[_n6],o=r.accumulatedGrads[_n6];Object(yr.f)(function(){var e=o.add(i.square());t.accumulatedGrads[_n6].assign(e);var r=t.c.mul(i.div(e.add(t.epsilon).sqrt())).add(a);a.assign(r);});},r=this;for(var a in e){n(a);}},t.prototype.dispose=function(){var e=this;this.epsilon.dispose(),this.c.dispose(),null!=this.accumulatedGrads&&Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose();});},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue};},t.fromConfig=function(e,t){return new e(t.learningRate,t.initialAccumulatorValue);},t.className="AdagradOptimizer",t;}(wr);or.register(Sr);var Nr=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Er=function(e){function t(t,n,r,a){void 0===a&&(a=1e-8);var i=e.call(this)||this;return i.learningRate=t,i.beta1=n,i.beta2=r,i.epsilon=a,i.accumulatedFirstMoment={},i.accumulatedSecondMoment={},i.c=Object(yr.e)(Object(f.Sb)(-t)),i.epsScalar=Object(yr.e)(Object(f.Sb)(a)),i.beta1Scalar=Object(yr.e)(Object(f.Sb)(n)),i.beta2Scalar=Object(yr.e)(Object(f.Sb)(r)),Object(yr.f)(function(){i.accBeta1=Object(f.Sb)(n).variable(),i.accBeta2=Object(f.Sb)(r).variable();}),i.oneMinusBeta1=Object(yr.e)(Object(f.Sb)(1-n)),i.oneMinusBeta2=Object(yr.e)(Object(f.Sb)(1-r)),i.one=Object(yr.e)(Object(f.Sb)(1)),i;}return Nr(t,e),t.prototype.applyGradients=function(e){var t=this;Object(yr.f)(function(){var n=t.one.sub(t.accBeta1),r=t.one.sub(t.accBeta2);for(var a in e){var i=c.ENV.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var o=!1;t.accumulatedFirstMoment[a]=Object(f.Ic)(i).variable(o);}null==t.accumulatedSecondMoment[a]&&(o=!1,t.accumulatedSecondMoment[a]=Object(f.Ic)(i).variable(o));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedSecondMoment[a],p=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),h=t.beta2Scalar.mul(l).add(t.oneMinusBeta2.mul(s.square())),d=p.div(n),m=h.div(r);t.accumulatedFirstMoment[a].assign(p),t.accumulatedSecondMoment[a].assign(h);var g=t.c.mul(d.div(t.epsScalar.add(m.sqrt()))).add(i);i.assign(g);}t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar)),t.accBeta2.assign(t.accBeta2.mul(t.beta2Scalar));});},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.accBeta1.dispose(),this.accBeta2.dispose(),this.oneMinusBeta1.dispose(),this.oneMinusBeta2.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose();}),null!=this.accumulatedSecondMoment&&Object.keys(this.accumulatedSecondMoment).forEach(function(t){return e.accumulatedSecondMoment[t].dispose();});},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon};},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon);},t.className="AdamOptimizer",t;}(wr);or.register(Er);var Ir=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Tr=function(e){function t(t,n,r,a,i){void 0===a&&(a=1e-8),void 0===i&&(i=0);var o=e.call(this)||this;return o.learningRate=t,o.beta1=n,o.beta2=r,o.epsilon=a,o.decay=i,o.accumulatedFirstMoment={},o.accumulatedWeightedInfNorm={},o.c=Object(yr.e)(Object(f.Sb)(-t)),o.epsScalar=Object(yr.e)(Object(f.Sb)(a)),o.beta1Scalar=Object(yr.e)(Object(f.Sb)(n)),o.beta2Scalar=Object(yr.e)(Object(f.Sb)(r)),o.decayScalar=Object(yr.e)(Object(f.Sb)(i)),Object(yr.f)(function(){o.iteration=Object(f.Sb)(0).variable(),o.accBeta1=Object(f.Sb)(n).variable();}),o.oneMinusBeta1=Object(yr.e)(Object(f.Sb)(1-n)),o.one=Object(yr.e)(Object(f.Sb)(1)),o;}return Ir(t,e),t.prototype.applyGradients=function(e){var t=this;Object(yr.f)(function(){var n=t.one.sub(t.accBeta1),r=t.c.div(t.one.add(t.decayScalar.mul(t.iteration)));for(var a in e){var i=c.ENV.engine.registeredVariables[a];if(null==t.accumulatedFirstMoment[a]){var o=!1;t.accumulatedFirstMoment[a]=Object(f.Ic)(i).variable(o);}null==t.accumulatedWeightedInfNorm[a]&&(o=!1,t.accumulatedWeightedInfNorm[a]=Object(f.Ic)(i).variable(o));var s=e[a],u=t.accumulatedFirstMoment[a],l=t.accumulatedWeightedInfNorm[a],p=t.beta1Scalar.mul(u).add(t.oneMinusBeta1.mul(s)),h=t.beta2Scalar.mul(l),d=s.abs(),m=h.maximum(d);t.accumulatedFirstMoment[a].assign(p),t.accumulatedWeightedInfNorm[a].assign(m);var g=r.div(n).mul(p.div(t.epsScalar.add(m))).add(i);i.assign(g);}t.iteration.assign(t.iteration.add(t.one)),t.accBeta1.assign(t.accBeta1.mul(t.beta1Scalar));});},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.accBeta1.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.oneMinusBeta1.dispose(),this.decayScalar.dispose(),this.iteration.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose();}),null!=this.accumulatedWeightedInfNorm&&Object.keys(this.accumulatedWeightedInfNorm).forEach(function(t){return e.accumulatedWeightedInfNorm[t].dispose();});},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay};},t.fromConfig=function(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay);},t.className="AdamaxOptimizer",t;}(wr);or.register(Tr);var Ar=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Cr=function(e){function t(t){var n=e.call(this)||this;return n.learningRate=t,n.setLearningRate(t),n;}return Ar(t,e),t.prototype.applyGradients=function(e){var t=this;Object.keys(e).forEach(function(n){var r=e[n],a=c.ENV.engine.registeredVariables[n];Object(yr.f)(function(){var e=t.c.mul(r).add(a);a.assign(e);});});},t.prototype.setLearningRate=function(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Object(yr.e)(Object(f.Sb)(-e));},t.prototype.dispose=function(){this.c.dispose();},t.prototype.getConfig=function(){return{learningRate:this.learningRate};},t.fromConfig=function(e,t){return new e(t.learningRate);},t.className="SGDOptimizer",t;}(wr);or.register(Cr);var Pr=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),_r=function(e){function t(t,n,r){void 0===r&&(r=!1);var a=e.call(this,t)||this;return a.learningRate=t,a.momentum=n,a.useNesterov=r,a.m=Object(f.Sb)(a.momentum),a.accumulations={},a;}return Pr(t,e),t.prototype.applyGradients=function(e){var t=this,n=function n(_n7){var a=c.ENV.engine.registeredVariables[_n7];null==r.accumulations[_n7]&&Object(yr.f)(function(){t.accumulations[_n7]=Object(f.Ic)(a).variable(!1);});var i=r.accumulations[_n7],o=e[_n7];Object(yr.f)(function(){var e,r=t.m.mul(i).add(o);e=t.useNesterov?t.c.mul(o.add(r.mul(t.m))).add(a):t.c.mul(r).add(a),t.accumulations[_n7].assign(r),a.assign(e);});},r=this;for(var a in e){n(a);}},t.prototype.dispose=function(){if(e.prototype.dispose.call(this),this.m.dispose(),null!=this.accumulations)for(var t in this.accumulations){this.accumulations[t].dispose();}},t.prototype.setMomentum=function(e){this.momentum=e;},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov};},t.fromConfig=function(e,t){return new e(t.learningRate,t.momentum,t.useNesterov);},t.className="MomentumOptimizer",t;}(Cr);or.register(_r);var Rr=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Mr=function(e){function t(t,n,r,a,i){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===a&&(a=1e-8),void 0===i&&(i=!1);var o=e.call(this)||this;return o.learningRate=t,o.decay=n,o.momentum=r,o.epsilon=a,o.accumulatedMeanSquares={},o.accumulatedMeanGrads={},o.accumulatedMoments={},o.c=Object(yr.e)(Object(f.Sb)(t)),o.epsilonScalar=Object(yr.e)(Object(f.Sb)(a)),o.decayScalar=Object(yr.e)(Object(f.Sb)(n)),o.momentumScalar=Object(yr.e)(Object(f.Sb)(r)),o.oneMinusDecay=Object(yr.e)(Object(f.Sb)(1-n)),o.centered=i,o;}return Rr(t,e),t.prototype.applyGradients=function(e){var t=this,n=function n(_n8){var a=c.ENV.engine.registeredVariables[_n8];null==r.accumulatedMeanSquares[_n8]&&Object(yr.f)(function(){t.accumulatedMeanSquares[_n8]=Object(f.Ic)(a).variable(!1);}),null==r.accumulatedMeanGrads[_n8]&&r.centered&&Object(yr.f)(function(){t.accumulatedMeanGrads[_n8]=Object(f.Ic)(a).variable(!1);}),null==r.accumulatedMoments[_n8]&&Object(yr.f)(function(){t.accumulatedMoments[_n8]=Object(f.Ic)(a).variable(!1);});var i=r.accumulatedMeanSquares[_n8],o=r.accumulatedMeanGrads[_n8],s=r.accumulatedMoments[_n8],u=e[_n8];Object(yr.f)(function(){var e=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u.square()));if(t.centered){var r=t.decayScalar.mul(o).add(t.oneMinusDecay.mul(u)),c=t.momentumScalar.mul(s).add(t.c.mul(u).div(e.sub(r.square().add(t.epsilonScalar)).sqrt()));t.accumulatedMeanSquares[_n8].assign(e),t.accumulatedMeanGrads[_n8].assign(r),t.accumulatedMoments[_n8].assign(c);var l=a.sub(c);a.assign(l);}else{var f=t.decayScalar.mul(i).add(t.oneMinusDecay.mul(u.square()));c=t.momentumScalar.mul(s).add(t.c.mul(u).div(f.add(t.epsilonScalar).sqrt())),t.accumulatedMeanSquares[_n8].assign(f),t.accumulatedMoments[_n8].assign(c),l=a.sub(c),a.assign(l);}});},r=this;for(var a in e){n(a);}},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.decayScalar.dispose(),this.momentumScalar.dispose(),this.oneMinusDecay.dispose(),null!=this.accumulatedMeanSquares&&Object.keys(this.accumulatedMeanSquares).forEach(function(t){return e.accumulatedMeanSquares[t].dispose();}),null!=this.accumulatedMeanGrads&&this.centered&&Object.keys(this.accumulatedMeanGrads).forEach(function(t){return e.accumulatedMeanGrads[t].dispose();}),null!=this.accumulatedMoments&&Object.keys(this.accumulatedMoments).forEach(function(t){return e.accumulatedMoments[t].dispose();});},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered};},t.fromConfig=function(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered);},t.className="RMSPropOptimizer",t;}(wr);or.register(Mr);var jr=n(44),Dr=function Dr(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},Lr=function(){function e(){}return e.sgd=function(e){return new Cr(e);},e.momentum=function(e,t,n){return void 0===n&&(n=!1),new _r(e,t,n);},e.rmsprop=function(e,t,n,r,a){return void 0===t&&(t=.9),void 0===n&&(n=0),void 0===r&&(r=1e-8),void 0===a&&(a=!1),new Mr(e,t,n,r,a);},e.adam=function(e,t,n,r){return void 0===e&&(e=.001),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=1e-8),new Er(e,t,n,r);},e.adadelta=function(e,t,n){return void 0===e&&(e=.001),void 0===t&&(t=.95),void 0===n&&(n=1e-8),new kr(e,t,n);},e.adamax=function(e,t,n,r,a){return void 0===e&&(e=.002),void 0===t&&(t=.9),void 0===n&&(n=.999),void 0===r&&(r=1e-8),void 0===a&&(a=0),new Tr(e,t,n,r,a);},e.adagrad=function(e,t){return void 0===t&&(t=.1),new Sr(e,t);},Dr([Object(qt.a)({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"sgd",null),Dr([Object(qt.a)({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"momentum",null),Dr([Object(qt.a)({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"rmsprop",null),Dr([Object(qt.a)({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"adam",null),Dr([Object(qt.a)({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"adadelta",null),Dr([Object(qt.a)({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"adamax",null),Dr([Object(qt.a)({heading:"Training",subheading:"Optimizers",namespace:"train"})],e,"adagrad",null),e;}(),zr={sgd:Lr.sgd,momentum:Lr.momentum,adadelta:Lr.adadelta,adagrad:Lr.adagrad,rmsprop:Lr.rmsprop,adamax:Lr.adamax,adam:Lr.adam},Fr=c.Environment.setBackend,Br=c.Environment.getBackend,Vr=c.Environment.disposeVariables,Ur=c.Environment.memory,Wr=Ht.nextFrame,Gr=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),qr=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r;}return Gr(t,e),t;}(Error),Hr=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r;}return Gr(t,e),t;}(Error),Kr=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r;}return Gr(t,e),t;}(Error),Xr=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r;}return Gr(t,e),t;}(Error),Jr=function(e){function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r;}return Gr(t,e),t;}(Error),Yr=(function(e){Gr(function t(n){var r=e.call(this,n)||this;return Object.setPrototypeOf(r,t.prototype),r;},e);}(Error),Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){for(var a in t=arguments[n]){Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);}}return e;});function Qr(e,t){if(Array.isArray(e)){for(var n=[],r=0;r<t;r++){n=n.concat(e);}return n;}return(n=new Array(t)).fill(e),n;}function Zr(e,t){if(!e)throw new Jr(t);}function $r(e,t){for(var n=0,r=0,a=e;r<a.length;r++){a[r]===t&&n++;}return n;}function ea(e){return 1===e.length?e[0]:e;}function ta(e){return Array.isArray(e)?e:[e];}function na(e){return Array.isArray(e)&&Array.isArray(e[0]);}function ra(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e];}function aa(e){var t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==t[0]?t:"private"+t;}function ia(e){return e.length<=1?e:-1===e.indexOf("_")?e:e.replace(/[_]+(\w|$)/g,function(e,t){return t.toUpperCase();});}var oa={};function sa(e){return null===e||void 0===e?null:{className:e.getClassName(),config:e.getConfig()};}function ua(e,t,n,r){if(void 0===t&&(t={}),void 0===n&&(n={}),void 0===r&&(r="object"),"string"==typeof e){var a=e,i=void 0;if(a in n)i=n[a];else if(a in oa)i=oa[a];else if(null==(i=t[a]))throw new Kr("Unknown "+r+": "+e);return i;}var o=e;if(null==o.className||null==o.config)throw new Kr(r+": Improper config format: "+JSON.stringify(o)+".\n'className' and 'config' must set.");var s,u,c,l=o.className,f=void 0,p=void 0;if(l in n?(f=(s=n.get(l))[0],p=s[1]):l in oa?(f=(u=oa.className)[0],p=u[1]):l in t&&(f=(c=t[l])[0],p=c[1]),null==f)throw new Kr("Unknown "+r+": "+l);if(null!=p){for(var h={},d=0,m=Object.keys(oa);d<m.length;d++){h[x=m[d]]=oa[x];}for(var g=0,y=Object.keys(n);g<y.length;g++){h[x=y[g]]=n[x];}o.config.customObjects=h;for(var v=Yr({},oa),b=0,w=Object.keys(n);b<w.length;b++){var x=w[b];oa[x]=n[x];}var k=p(f,o.config);return oa=Yr({},v),k;}v=Yr({},oa);for(var O=0,S=Object.keys(n);O<S.length;O++){x=S[O],oa[x]=n[x];}return k=new f(o.config),oa=Yr({},v),k;}function ca(e){var t;if(Array.isArray(e)){if(1!==e.length)throw new Kr("Expected Tensor length to be 1; got "+e.length);t=e[0];}else t=e;return t;}function la(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return(e=e)[0];throw new Kr("Expected exactly 1 Shape; got "+e.length);}return e;}function fa(e,t){return-1*function(e,t){return e<t?-1:e>t?1:0;}(e,t);}function pa(e){if(null==e)return e;for(var t=[],n=0,r=e;n<r.length;n++){var a=r[n];-1===t.indexOf(a)&&t.push(a);}return t;}function ha(e){if(null==e)throw new Kr("Invalid value in obj: "+JSON.stringify(e));for(var t in e){if(e.hasOwnProperty(t))return!1;}return!0;}function da(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new Kr(n+" is not a valid "+t+". Valid values are "+e+" or null/undefined.");}var ma=new Map(),ga=["channelsFirst","channelsLast"];function ya(e){da(ga,"DataFormat",e);}var va=["valid","same","causal"];function ba(e){da(va,"PaddingMode",e);}var wa=["max","avg"],xa=[],ka="/";function Oa(e){if(!Ea(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===xa.length?"":xa.join(ka)+ka)+e;}function Sa(e){if(!Ea(e))throw new Error("Not a valid tensor name: '"+e+"'");ma.has(e)||ma.set(e,0);var t=ma.get(e);if(ma.set(e,ma.get(e)+1),t>0){var n=e+"_"+t;return ma.set(n,1),n;}return e;}var Na=new RegExp(/^[A-Za-z][A-Za-z0-9\._\/]*$/);function Ea(e){return!!e.match(Na);}function Ia(e){return e===parseInt(e.toString(),10);}function Ta(e,t,n){null==t&&(t=0),null==n&&(n=e.length);for(var r=1,a=t;a<n;++a){r*=e[a];}return r;}function Aa(e){return e=Array.isArray(e)?new Float32Array(e):e,Object(f.vc)(e);}function Ca(e){return f.bb(Aa(e)).dataSync()[0];}function Pa(e){return f.Wa(Aa(e)).dataSync()[0];}function _a(e,t){if(t<e)throw new Kr("end ("+t+") < begin ("+e+") is forbidden.");for(var n=[],r=e;r<t;++r){n.push(r);}return n;}var Ra=0;function Ma(){return Ra++;}var ja=function(){function e(e,t,n,r,a,i,o){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=r,this.callArgs=a,this.outputTensorIndex=o,this.id=Ma(),null!=i&&(this.originalName=Oa(i),this.name=Sa(this.originalName)),this.rank=t.length;}return function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;}([Object(qt.a)({heading:"Models",subheading:"Classes"})],e);}(),Da="Variable",La=function(){function e(e,t,n,r,a){void 0===t&&(t="float32"),void 0===n&&(n=Da),void 0===r&&(r=!0),void 0===a&&(a=null),this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=Ma(),n=null==n?Da:n,this.originalName=Oa(n),this.name=Sa(this.originalName),this.trainable=r,this.constraint=a,this.val=m.d(e,this.trainable,this.name,this.dtype);}return e.prototype.read=function(){return this.val;},e.prototype.write=function(e){return function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape));}(this.val,e),this.val.assign(e),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val)),this;},e;}();function za(e){return e.map(function(e){return e.read();});}function Fa(e){e.map(function(e){e[0].write(e[1]);});}var Ba="float32",Va={float32:{},int32:{}};function Ua(e,t){return void 0===t&&(t=Ba),null==Va[t][e]&&(Va[t][e]=Object(f.Sb)(e,t),yr.e(Va[t][e])),Va[t][e];}var Wa=function Wa(){return 1e-7;};function Ga(e){return e.shape;}function qa(e){return e.shape;}function Ha(e){return e instanceof m.a?Ba:e.dtype;}function Ka(e,t){return e.asType(t);}function Xa(e,t){void 0===t&&(t=-1);var n=Ga(e).slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),e.reshape(n);}function Ja(e,t,n){return Object(yr.f)(function(){switch(e.rank){case 1:return f.ac(e,t,n);case 2:return f.bc(e,[t,0],[n,e.shape[1]]);case 3:return f.cc(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return f.dc(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);default:throw new Kr("sliceAlongFirstAxis() received an unsupported tensor rank: "+e.rank);}});}function Ya(e,t,n){return Object(yr.f)(function(){switch(e.rank){case 1:return f.ac(e,t,n);case 2:return f.bc(e,[0,t],[e.shape[0],n]);case 3:return f.cc(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return f.dc(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new Kr("sliceAlongLastAxis() received an unsupported tensor rank: "+e.rank);}});}function Qa(e,t,n,r){return Object(yr.f)(function(){switch(e.rank){case 1:return f.ac(e,t,n);case 2:switch(r){case 1:return Ja(e,t,n);case 2:return Ya(e,t,n);default:throw new Kr("The axis is not within the rank of the tensor "+r);}case 3:switch(r){case 1:return Ja(e,t,n);case 2:return f.cc(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Ya(e,t,n);default:throw new Kr("The axis is not within the rank of the tensor "+r);}case 4:switch(r){case 1:return Ja(e,t,n);case 2:return f.dc(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return f.dc(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Ya(e,t,n);default:throw new Kr("The axis is not within the rank of the tensor "+r);}default:throw new Kr("sliceAlongLastAxis() received an unsupported tensor rank: "+e.rank);}});}function Za(e,t){var n;return void 0===t&&(t=-1),t<0&&(t=0!==(n=e[0].rank)?n:0),t===e[0].rank&&(t=-1),f.x(e,t);}function $a(e,t){switch(e.rank){case 1:return f.y([e,t]);case 2:return f.z([e,t],0);case 3:return f.A([e,t],0);case 4:return f.B([e,t],0);default:throw new Kr("concatAlongFirstAxis() received an unsupported tensor rank: "+e.rank);}}function ei(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new Kr("The length of input n ("+t.length+") does not match the number of dimensions in input x ("+e.rank+")");return f.zc(e,t);}function ti(e){return e.clone();}function ni(e,t){return f.ib(e,t);}function ri(e,t){return f.d(e,t);}function ai(e,t,n,r,a){return void 0===t&&(t=0),void 0===n&&(n=1),f.Fb(e,t,n,r,a);}function ii(e,t){if(2!==t.rank)throw new Xr("dot support for y other than rank 2 is not yet implemented: y shape = "+Ga);if(2===e.rank)return f.Ua(e,t);if(3===e.rank){var n=e.shape[0],r=e.shape[1],a=e.shape[2];return e=e.reshape([n*r,a]),f.Ua(e,t).reshape([n,r,t.shape[1]]);}throw new Xr("dot support for x of rank "+e.rank+" is not yet implemented: x shape = "+Ga);}function oi(e,t,n){return Object(yr.f)(function(){return t=Array.isArray(t)?Object(f.vc)(t,"int32"):t.toInt(),f.X(e,t,n);});}function si(e){return f.jb(e,e);}function ui(e,t,n){return Object(yr.f)(function(){if(null==n&&(n="channelsLast"),ya(n),1!==t.rank&&t.rank!==e.rank)throw new Kr("Unexpected bias dimensions: "+t.rank+"; expected it to be 1 or "+e.rank);var r,a=t.shape;if(5===e.rank)"channelsFirst"===n?r=1===a.length?e.add(t.reshape([1,a[0],1,1,1])):e.add(t.reshape([1,a[3],a[0],a[1],a[2]])):"channelsLast"===n&&(r=1===a.length?e.add(t.reshape([1,1,1,1,a[0]])):e.add(t.reshape([1].concat(a))));else if(4===e.rank)"channelsFirst"===n?r=1===a.length?e.add(t.reshape([1,a[0],1,1])):e.add(t.reshape([1,a[2],a[0],a[1]])):"channelsLast"===n&&(r=1===a.length?e.add(t.reshape([1,1,1,a[0]])):e.add(t.reshape([1].concat(a))));else if(3===e.rank)"channelsFirst"===n?r=1===a.length?e.add(t.reshape([1,a[0],1])):e.add(t.reshape([1,a[1],a[0]])):"channelsLast"===n&&(r=1===a.length?e.add(t.reshape([1,1,a[0]])):e.add(t.reshape([1].concat(a))));else{if(!(e.rank<3))throw new Kr("Unsupported input rank by biasAdd: "+e.rank);r=e.add(t);}return r;});}function ci(e,t){return function(e,t){xa.push(e);try{var n=t();return xa.pop(),n;}catch(e){throw xa.pop(),e;}}(e,t);}var li={};function fi(e){return void 0===e&&(e=""),e in li||(li[e]=0),li[e]+=1,e+li[e].toString();}var pi=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}();function hi(e,t){return Object(yr.f)(function(){return f.hc(f.rc(si(e),t,!0));});}var di=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return pi(t,e),t.prototype.getConfig=function(){return{};},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;}([Object(qt.a)({heading:"Constraints",subheading:"Classes",namespace:"constraints"})],t);}(o.Serializable),mi=function(e){function t(t){var n=e.call(this)||this;return n.defaultMaxValue=2,n.defaultAxis=0,n.maxValue=null!=t.maxValue?t.maxValue:n.defaultMaxValue,n.axis=null!=t.axis?t.axis:n.defaultAxis,n;}return pi(t,e),t.prototype.apply=function(e){var t=this;return Object(yr.f)(function(){var n=hi(e,t.axis),r=f.v(n,0,t.maxValue);return f.ib(e,f.J(r,ri(Ua(Wa()),n)));});},t.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis};},t.className="MaxNorm",t;}(di);o.SerializationMap.register(mi);var gi=function(e){function t(t){var n=e.call(this)||this;return n.defaultAxis=0,n.axis=null!=t.axis?t.axis:n.defaultAxis,n;}return pi(t,e),t.prototype.apply=function(e){var t=this;return Object(yr.f)(function(){return f.J(e,ri(Ua(Wa()),hi(e,t.axis)));});},t.prototype.getConfig=function(){return{axis:this.axis};},t.className="UnitNorm",t;}(di);o.SerializationMap.register(gi);var yi=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return pi(t,e),t.prototype.apply=function(e){return f.Jb(e);},t.className="NonNeg",t;}(di);o.SerializationMap.register(yi);var vi=function(e){function t(t){var n=e.call(this)||this;return n.defaultMinValue=0,n.defaultMaxValue=1,n.defaultRate=1,n.defaultAxis=0,n.minValue=null!=t.minValue?t.minValue:n.defaultMinValue,n.maxValue=null!=t.maxValue?t.maxValue:n.defaultMaxValue,n.rate=null!=t.rate?t.rate:n.defaultRate,n.axis=null!=t.axis?t.axis:n.defaultAxis,n;}return pi(t,e),t.prototype.apply=function(e){var t=this;return Object(yr.f)(function(){var n=hi(e,t.axis),r=f.d(ni(Ua(t.rate),f.v(n,t.minValue,t.maxValue)),ni(Ua(1-t.rate),n));return f.ib(e,f.J(r,ri(Ua(Wa()),n)));});},t.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis};},t.className="MinMaxNorm",t;}(di);o.SerializationMap.register(vi);var bi={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function wi(e){return sa(e);}function xi(e,t){return void 0===t&&(t={}),ua(e,o.SerializationMap.getMap().classNameMap,t,"constraint");}function ki(e){return null==e?null:"string"==typeof e?xi({className:e in bi?bi[e]:e,config:{}}):e instanceof di?e:xi(e);}function Oi(e,t){return void 0===t&&(t={}),ua(e,o.SerializationMap.getMap().classNameMap,t,"layer");}function Si(e,t,n){return("inboundNodes"===e||"outputLayers"===e||"inputLayers"===e)&&0===t&&"string"==typeof n;}function Ni(e,t){if(null===e)return null;if("string"==typeof e)return ia(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){for(var n=[],r=e.length,a=0;a<r;++a){var i=e[a];Si(t,a,i)?n.push(i):n.push(Ni(i,t));}return n;}for(var o={},s=0,u=Object.keys(e);s<u.length;s++){var c=u[s],l=e[c];if("name"===c&&"string"==typeof l)o[c]=l;else{var f=ia(c);o[f]=Ni(l,f);}}return o;}var Ei=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Ii=function Ii(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},Ti=function Ti(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{};},Ai=0,Ci=function(){function e(e,t){this.callArgs=t,this.id=Ai++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(var n=0,r=e.inboundLayers;n<r.length;n++){var a=r[n];null!=a&&a.outboundNodes.push(this);}e.outboundLayer.inboundNodes.push(this);}return e.prototype.getConfig=function(){for(var e=[],t=0,n=this.inboundLayers;t<n.length;t++){var r=n[t];null!=r?e.push(r.name):e.push(null);}return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices};},e;}(),Pi=0,_i=function(e){function t(t){var n=e.call(this)||this;n._callHook=null,n._addedWeightNames=[],n._stateful=!1,n.id=Pi++,n.activityRegularizer=null,n.inputSpec=null,n.supportsMasking=!1,n._trainableWeights=[],n._nonTrainableWeights=[],n._losses=[],n._updates=[],n._built=!1,n.inboundNodes=[],n.outboundNodes=[];var r=t.name;if(!r){var a=n.getClassName();r=aa(a)+"_"+fi(a);}if(n.name=r,n.trainable=null==t.trainable||t.trainable,n.updatable=null==t.updatable||t.updatable,null!=t.inputShape||null!=t.batchInputShape){var i=void 0;if(null!=t.batchInputShape)i=t.batchInputShape;else if(null!=t.inputShape){var o=null;null!=t.batchSize&&(o=t.batchSize),i=[o].concat(t.inputShape);}n.batchInputShape=i;var s=t.dtype;null==s&&(s=t.inputDType),null==s&&(s="float32"),n.dtype=s;}return null!=t.weights?n.initialWeights=t.weights:n.initialWeights=null,n;}return Ei(t,e),t.nodeKey=function(e,t){return e.name+"_ib-"+t.toString();},t.prototype.getNodeAtIndex=function(e,t){if(0===this.inboundNodes.length)throw new Hr("The layer has never been called and thus has no defined "+t+".");if(this.inboundNodes.length<=e)throw new Kr("Asked to get "+t+" at node "+e+", but the layer has only "+this.inboundNodes.length+" inbound nodes.");return this.inboundNodes[e];},t.prototype.getInputAt=function(e){return ea(this.getNodeAtIndex(e,"input").inputTensors);},t.prototype.getOutputAt=function(e){return ea(this.getNodeAtIndex(e,"output").outputTensors);},Object.defineProperty(t.prototype,"input",{get:function get(){if(this.inboundNodes.length>1)throw new qr("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(0===this.inboundNodes.length)throw new qr("Layer "+this.name+" is not connected, no input to return.");return ea(this.getNodeAtIndex(0,"input").inputTensors);},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function get(){if(0===this.inboundNodes.length)throw new qr("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new qr("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return ea(this.getNodeAtIndex(0,"output").outputTensors);},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function get(){return this._losses;},enumerable:!0,configurable:!0}),t.prototype.calculateLosses=function(){return this.losses.map(function(e){return e();});},Object.defineProperty(t.prototype,"updates",{get:function get(){return this._updates;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"built",{get:function get(){return this._built;},set:function set(e){this._built=e;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function get(){return this.trainable?this._trainableWeights:[];},set:function set(e){this._trainableWeights=e;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function get(){return this.trainable?this._nonTrainableWeights:this._trainableWeights.concat(this._nonTrainableWeights);},set:function set(e){this._nonTrainableWeights=e;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function get(){return this.trainableWeights.concat(this.nonTrainableWeights);},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stateful",{get:function get(){return this._stateful;},enumerable:!0,configurable:!0}),t.prototype.assertInputCompatibility=function(e){if(e=ta(e),null!=this.inputSpec&&0!==this.inputSpec.length){var t=ta(this.inputSpec);if(e.length!==t.length)throw new Kr("Layer "+this.name+" expects "+t.length+" inputs, but it received "+e.length+" input tensors. Input received: "+e);for(var n=0;n<e.length;n++){var r=e[n],a=t[n];if(null!=a){var i=r.rank;if(null!=a.ndim&&i!==a.ndim)throw new Kr("Input "+n+" is incompatible with layer "+this.name+": expected ndim="+a.ndim+", found ndim="+i);if(null!=a.maxNDim&&i>a.maxNDim)throw new Kr("Input "+n+" is incompatible with layer "+this.name+": expected max_ndim="+a.maxNDim+", found ndim="+i);if(null!=a.minNDim&&i<a.minNDim)throw new Kr("Input "+n+" is incompatible with layer "+this.name+": expected min_ndim="+a.minNDim+", found ndim="+i+".");if(null!=a.dtype&&Ha(r)!==a.dtype){var o=Ha(r);throw new Kr("Input "+n+" is incompatible with layer "+this.name+" : expected dtype="+a.dtype+", found dtype="+o+".");}if(a.axes){var s=qa(r);for(var u in a.axes){var c=Number(u),l=a.axes[u],f=c>=0?s[c]:s[s.length+c];if(null!=l&&-1===[l,null].indexOf(f))throw new Kr("Input "+n+" is incompatible with layer "+this.name+": expected axis "+c+" of input shape to have value "+l+" but got shape "+s+".");}}if(null!=a.shape){s=qa(r);for(var p=0;p<a.shape.length;++p){var h=a.shape[p],d=s[p];if(null!=h&&null!=d&&h!==d)throw new Kr("Input "+n+" is incompatible with layer "+this.name+": expected shape="+a.shape+", found shape=${xShape}.");}}}}}},t.prototype.call=function(e,t){return e;},t.prototype.invokeCallHook=function(e,t){null!=this._callHook&&this._callHook(e,t);},t.prototype.setCallHook=function(e){this._callHook=e;},t.prototype.clearCallHook=function(){this._callHook=null;},t.prototype.apply=function(e,t){var n=this;t=t||{};for(var r=ta(e),a=!0,i=0,o=r;i<o.length;i++){if(!(o[i]instanceof ja)){a=!1;break;}}for(var s=!0,u=0,c=r;u<c.length;u++){if(c[u]instanceof ja){s=!1;break;}}if(a===s)throw new Kr("Arguments to apply() must be all SymbolicTensors or all Tensors");return ci(this.name,function(){if(!n.built){n.assertInputCompatibility(e);for(var a=[],i=0,o=ta(e);i<o.length;i++){var u=o[i];a.push(qa(u));}n.build(ea(a)),n.built=!0,n.initialWeights&&n.setWeights(n.initialWeights);}if(n.assertInputCompatibility(e),s){for(var c=[],l=0,f=ta(m=n.call(e,t));l<f.length;l++){var p=f[l];-1!==r.indexOf(p)&&(p=ti(p)),c.push(p);}if(m=ea(c),null!=n.activityRegularizer)throw new Xr("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m;}var h=function(e){for(var t=[],n=0,r=e=ta(e);n<r.length;n++){var a=r[n];t.push(qa(a));}return ea(t);}(e),d=n.computeOutputShape(h),m=void 0;if(m=null!=d&&d.length>0&&Array.isArray(d[0])?d.map(function(r,a){return new ja("float32",r,n,ta(e),t,n.name,a);}):new ja("float32",d,n,ta(e),t,n.name),n.addInboundNode(e,m,null,null,h,d,t),null!=n.activityRegularizer)throw new Xr("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m;});},t.prototype.build=function(e){this.built=!0;},t.prototype.getWeights=function(e){return void 0===e&&(e=!1),za(e?this.trainableWeights:this.weights);},t.prototype.setWeights=function(e){var t=this;Object(yr.f)(function(){var n=t.weights;if(n.length!==e.length)throw new Kr('You called setWeights(weights) on layer "'+t.name+'" with a weight list of length '+e.length+", but the layer was expecting "+n.length+" weights. Provided weights: "+e+"...");if(0!==n.length){for(var r=[],a=za(n),i=0;i<a.length;++i){var o=a[i],s=n[i],u=e[i];if(!y.arraysEqual(o.shape,u.shape))throw new Kr("Layer weight shape "+o.shape+" not compatible with provided weight shape "+u.shape);r.push([s,u]);}Fa(r);}});},t.prototype.addWeight=function(e,t,n,r,a,i,o){if(-1!==this._addedWeightNames.indexOf(e))throw new Kr("Duplicate weight name "+e+" for layer "+this.name);this._addedWeightNames.push(e),null==n&&(n="float32");var s=new La(r.apply(t,n),n,e,i,o);return null!=a&&this.addLoss(function(){return a.apply(s.read());}),null==i&&(i=!0),i?this._trainableWeights.push(s):this._nonTrainableWeights.push(s),s;},t.prototype.addLoss=function(e){var t;null==e||Array.isArray(e)&&0===e.length||(e=ta(e),void 0!==this._losses&&null!==this._losses&&(t=this.losses).push.apply(t,e));},t.prototype.computeOutputShape=function(e){return e;},t.prototype.computeMask=function(e,t){var n=this;if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError("Layer "+this.name+" does not support masking,but was passed an inputMask.");t.forEach(function(e){if(null!=e)throw new TypeError("Layer "+n.name+" does not support masking,but was passed an inputMask.");});}return null;}return t;},t.prototype.addInboundNode=function(e,t,n,r,a,i,o){void 0===o&&(o=null);var s=ta(e);t=ta(t),n=ta(n),r=ta(r),a=ra(a),i=ra(i);for(var u=[],c=[],l=[],f=0,p=s;f<p.length;f++){var h=p[f];u.push(h.sourceLayer),c.push(h.nodeIndex),l.push(h.tensorIndex);}new Ci({outboundLayer:this,inboundLayers:u,nodeIndices:c,tensorIndices:l,inputTensors:s,outputTensors:t,inputMasks:n,outputMasks:r,inputShapes:a,outputShapes:i},o);for(var d=0;d<t.length;d++){t[d].sourceLayer=this,t[d].nodeIndex=this.inboundNodes.length-1,t[d].tensorIndex=d;}},t.prototype.getConfig=function(){var e={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(e.batchInputShape=this.batchInputShape),null!=this.dtype&&(e.dtype=this.dtype),e;},Ii([Object(qt.a)({heading:"Models",subheading:"Classes"})],t.prototype,"apply",null),Ii([Object(qt.a)({heading:"Layers",subheading:"Classes",namespace:"layers"})],t);}(o.Serializable),Ri=function(e){function t(t){var n=e.call(this,{dtype:t.dtype,name:null!=t.name?t.name:fi("input").toString()})||this;if(null==t.batchSize&&(t.batchSize=null),null==t.sparse&&(t.sparse=!1),n.trainable=!1,n.built=!0,n.sparse=t.sparse,null!=t.inputShape&&null!=t.batchInputShape)throw new Kr("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");var r=t.batchInputShape;if(null==r){if(null==t.inputShape)throw new Kr("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");r=[t.batchSize].concat(t.inputShape);}else if(null!=t.batchSize)throw new Kr("Cannot specify batchSize if batchInputShape isspecified when creating an InputLayer.");var a=t.dtype||"float32";n.batchInputShape=r,n.dtype=a,n.inputSpec=[{shape:r}];var i=new ja(n.dtype,n.batchInputShape,n,[],{},n.name);return i.nodeIndex=0,i.tensorIndex=0,new Ci({outboundLayer:n,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[i],outputTensors:[i],inputMasks:[null],outputMasks:[null],inputShapes:[r],outputShapes:[r]}),n;}return Ei(t,e),t.prototype.apply=function(e,t){throw new Kr("Cannot pass any input to an InputLayer's apply() method. InputLayer name: "+this.name);},t.prototype.getConfig=function(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name};},t.className="InputLayer",t;}(_i);function Mi(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new Kr("Please provide either a `shape` or `batchShape` argument to Input, but not both.");var t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));var n=e.dtype;return null==n&&(n="float32"),new Ri({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0];}o.SerializationMap.register(Ri);var ji=function(e){function t(n){var r=e.call(this,{})||this;if(r.containerNodes=new Set(),r.name=n.name,null==r.name){var a=r.getClassName().toLowerCase();r.name=fi(a);}if(r.supportsMasking=!1,r.trainable=!0,r.updatable=!0,Array.isArray(n.inputs)?r.inputs=n.inputs.slice():r.inputs=[n.inputs],Array.isArray(n.outputs)?r.outputs=n.outputs.slice():r.outputs=[n.outputs],pa(r.inputs).length!==r.inputs.length)throw new Kr("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: "+r.inputs.map(function(e){return e.name;}));pa(r.outputs).length!==r.outputs.length&&console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: "+r.outputs.map(function(e){return e.name;})),r.inputLayers=[],r.inputLayersNodeIndices=[],r.inputLayersTensorIndices=[],r.outputLayers=[],r.outputLayersNodeIndices=[],r.outputLayersTensorIndices=[],r.layers=[];for(var i=0,o=r.outputs;i<o.length;i++){var s=(E=o[i]).sourceLayer,u=E.nodeIndex,c=E.tensorIndex;r.outputLayers.push(s),r.outputLayersNodeIndices.push(u),r.outputLayersTensorIndices.push(c);}for(var l=0,f=r.inputs;l<f.length;l++){s=(E=f[l]).sourceLayer,u=E.nodeIndex,c=E.tensorIndex,Zr(0===u,"input layer has >1 nodes"),Zr(0===c,"input layer has >1 tensors"),r.inputLayers.push(s),r.inputLayersNodeIndices.push(u),r.inputLayersTensorIndices.push(c);}r.inputNames=[],r.outputNames=[],r.feedInputShapes=[],r.feedInputNames=[],r.feedOutputNames=[];for(var p=0;p<r.inputLayers.length;p++){if(!((s=r.inputLayers[p])instanceof Ri))throw new TypeError("Input layers to a Model must be InputLayer objects. Received inputs: "+n.inputs+". Input "+p+" (0-based) originates from layer type "+s.getClassName()+".");r.inputNames.push(s.name),r.feedInputShapes.push(s.batchInputShape),r.feedInputNames.push(s.name);}for(var h=0,d=r.outputLayers;h<d.length;h++){s=d[h],r.outputNames.push(s.name);}r.internalInputShapes=r.inputs.map(function(e){return e.shape;}),r.internalOutputShapes=r.outputs.map(function(e){return e.shape;});for(var m={},g={},y={},v={},b={},w=[],x=function x(e,n,a,i,o,s){null!=i&&null!=o&&null!=s||(i=e.sourceLayer,o=e.nodeIndex,s=e.tensorIndex);var u=i.inboundNodes[o];if(-1!==a.indexOf(u))throw new Hr("The tensor "+e.name+' at layer "'+i.name+'" is part of a cycle.');if(-1===n.indexOf(u)){r.containerNodes.add(t.nodeKey(i,o)),(i.id in b)||(b[i.id]=Object.keys(b).length),-1===a.indexOf(u)&&a.push(u);for(var c=u.inboundLayers.length,l=0;l<c;l++){var f=u.inputTensors[l],p=u.inboundLayers[l],h=u.nodeIndices[l],d=u.tensorIndices[l];x(f,n,a,p,h,d);}for(n.push(u);a.indexOf(u)>=0;){a.splice(a.indexOf(u),1);}w.push(u);}},k=[],O=[],S=0,N=r.outputs;S<N.length;S++){var E=N[S];x(E,k,O);}for(var I=0,T=w.slice().reverse();I<T.length;I++){g[(Y=T[I]).id]=Y,Y.id in m||(m[Y.id]=0);var A=m[Y.id],C=null==y[Y.outboundLayer.id]?0:y[Y.outboundLayer.id];for(A=Math.max(A,C),y[Y.outboundLayer.id]=A,v[Y.outboundLayer.id]=Y.outboundLayer,m[Y.id]=A,p=0;p<Y.inboundLayers.length;p++){var P=Y.inboundLayers[p],_=(u=Y.nodeIndices[p],P.inboundNodes[u]),R=null==m[_.id]?0:m[_.id];m[_.id]=Math.max(A+1,R),g[_.id]=_;}}var M={};for(var j in m){(A=m[j])in M||(M[A]=[]),M[A].push(g[j]);}var D={};for(var L in y){(A=y[L])in D||(D[A]=[]),D[A].push(v[L]);}var z=Object.keys(D).map(function(e){return parseInt(e,10);}).sort(fa);r.layers=[];for(var F=0,B=z;F<B.length;F++){var V=D[A=B[F]];V.sort(function(e,t){var n=b[e.id],r=b[t.id];return n<r?-1:n>r?1:0;});for(var U=0,W=V;U<W.length;U++){s=W[U],r.layers.push(s);}}r.layersByDepth=D,z=Object.keys(M).map(function(e){return parseInt(e,10);}).sort(fa);for(var G=r.inputs.slice(),q=[],H=0,K=z;H<K.length;H++){for(var X=0,J=M[A=K[H]];X<J.length;X++){var Y;if(null!=(s=(Y=J[X]).outboundLayer)){for(var Q=0,Z=Y.inputTensors;Q<Z.length;Q++){if(E=Z[Q],-1===G.indexOf(E))throw new Hr("Graph disconnected: cannot obtain value for tensor "+E+' at layer "'+s.name+'". The following previous layers were accessed without issue: '+q);}for(var $=0,ee=Y.outputTensors;$<ee.length;$++){E=ee[$],G.push(E);}q.push(s.name);}}}r.nodesByDepth=M;for(var te=r.layers.map(function(e){return e.name;}),ne=function ne(e){var t=te.filter(function(t){return t===e;}).length;if(1!==t)throw new Hr('The name "'+e+'" is used '+t+" times in the model. All layer names should be unique. Layer names: "+JSON.stringify(te));},re=0,ae=te;re<ae.length;re++){ne(ae[re]);}return r.outboundNodes=[],r.inboundNodes=[],new Ci({outboundLayer:r,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:r.inputs,outputTensors:r.outputs,inputMasks:r.inputs.map(function(e){return null;}),outputMasks:r.outputs.map(function(e){return null;}),inputShapes:r.inputs.map(function(e){return e.shape;}),outputShapes:r.outputs.map(function(e){return e.shape;})}),r.built=!0,r;}return Ei(t,e),Object.defineProperty(t.prototype,"trainableWeights",{get:function get(){if(this._trainableWeights.length>0)throw new Kr("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var e=[],t=0,n=this.layers;t<n.length;t++){var r=n[t];e=e.concat(r.trainableWeights);}return e;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function get(){for(var e=[],t=0,n=this.layers;t<n.length;t++){var r=n[t];e.push.apply(e,r.nonTrainableWeights);}if(!this.trainable){for(var a=[],i=0,o=this.layers;i<o.length;i++){r=o[i],a.push.apply(a,r.trainableWeights);}return a.concat(e);}return e;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function get(){return this.trainableWeights.concat(this.nonTrainableWeights);},enumerable:!0,configurable:!0}),t.prototype.loadWeights=function(e,t,n){void 0===t&&(t=!1),void 0===n&&(n=!1),n?function(e,t){for(var n={},r=0,a=0,i=t;a<i.length;a++){for(var o=0,s=i[a].weights;o<s.length;o++){var u=s[o];if(null!=n[u.originalName])throw new Kr("Duplicate weight name: "+u.originalName);n[u.originalName]=u,r++;}}var c=[];for(var l in e){c.push([n[l],e[l]]),delete n[l];}var f=[];for(var p in n){f.push(p);}if(f.length>0)throw new Kr(f.length+" of "+r+" weights are not set: "+f);Fa(c);}(e,this.layers):function(e,t,n){void 0===n&&(n=!1);for(var r=e.keras_version,a=e.backend,i=t.map(function(e){return e.name;}),o={},s=0,u=t;s<u.length;s++){null!=(w=u[s]).name&&(null==o[w.name]&&(o[w.name]=[]),o[w.name].push(w));}for(var c=e.weights,l=[],f=0;f<i.length;++f){var p=i[f],h=c[p];null==h&&(h=[]);for(var d=[],m=0;m<h.length;++m){var g=h[m];d.push(new La(Di(g.dtype,g.shape,g.value)));}for(var v=0,b=o[p];v<b.length;v++){var w,x=(w=b[v]).weights;if((d=Li(w,d,r,a)).length!==x.length){if(!n)throw new Kr("Layer #"+f+' (named "'+w.name+'") expects '+x.length+" weight(s), but the saved weights have "+d.length+" element(s).");console.warn("Skipping loading of weights of layer "+w.name+" due to mismatch in number of weights: ("+d.length+" vs "+x.length+").");}for(var k=0;k<d.length;++k){!n||y.arraysEqual(x[k].shape,d[k].shape)?l.push([x[k],d[k].read()]):console.warn("Skipping loading of weights for layer "+w.name+" due to mismatch in shape ("+x[k].shape+" vs "+d[k].shape+")");}}}Fa(l);}(e,this.layers,t);},t.prototype.updatedConfig=function(){var e=this.getConfig();return{className:this.getClassName(),config:e,kerasVersion:"tfjs-layers 0.6.4",backend:"TensorFlow.js"};},t.prototype.toJSON=function(e,t){void 0===t&&(t=!0);var n=function e(t,n){if(null===t||void 0===t)return null;if("string"==typeof t)return aa(t);if("number"==typeof t||"boolean"==typeof t)return t;if(t instanceof Array){for(var r=[],a=t.length,i=0;i<a;++i){var o=t[i];Si(n,i,o)?r.push(o):r.push(e(o,n));}return r;}for(var s={},u=0,c=Object.keys(t);u<c.length;u++){var l=c[u],f=t[l];s[aa(l)]="name"!==l&&"className"!==l||"string"!=typeof f?e(f,l):f;}return s;}(this.updatedConfig());return t?JSON.stringify(n):n;},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){var r;return e=ta(e),r="mask"in t?ta(t.mask):Qr(null,e.length),n.runInternalGraph(e,r)[0];});},t.prototype.computeMask=function(e,t){var n=this;return Object(yr.f)(function(){var r;return e=ta(e),r=null==t?Qr(null,e.length):ta(t),n.runInternalGraph(e,r)[1];});},t.prototype.computeOutputShape=function(e){var t=ra(e);if(t.length!==this.inputLayers.length)throw new Kr("Invalid inputShape argument "+e+": model has "+this.inputLayers.length+" tensor inputs.");for(var n={},r=0;r<t.length;r++){var a=this.inputLayers[r],i=t[r];n[O=a.name+"_0_0"]=i;}var o=Object.keys(this.nodesByDepth).map(function(e){return parseInt(e,10);}).sort(fa);if(o.length>1)for(var s=0,u=o;s<u.length;s++){for(var c=u[s],l=0,f=this.nodesByDepth[c];l<f.length;l++){var p=f[l];if(a=p.outboundLayer,-1===this.inputLayers.map(function(e){return e.id;}).indexOf(a.id)){for(var h=[],d=0;d<p.inboundLayers.length;d++){var m=p.inboundLayers[d],g=p.nodeIndices[d],y=p.tensorIndices[d],v=n[O=m.name+"_"+g+"_"+y];h.push(v);}var b=ra(a.computeOutputShape(ea(h))),w=a.inboundNodes.indexOf(p);for(d=0;d<b.length;d++){n[O=a.name+"_"+w+"_"+d]=b[d];}}}}var x=[],k=[];for(r=0;r<this.outputLayers.length;r++){a=this.outputLayers[r],w=this.outputLayersNodeIndices[r],y=this.outputLayersTensorIndices[r];var O=a.name+"_"+w+"_"+y;k.push(O);}for(r=0;r<k.length;r++){var S=k[r];Zr(S in n),x.push(n[S]);}return ea(x);},t.prototype.runInternalGraph=function(e,t){null==t&&(t=Qr(null,e.length));for(var n={},r=0;r<this.inputs.length;++r){var a=this.inputs[r],i=e[r],o=t[r];n[a.id]=[i,o];}for(var s=0,u=Object.keys(this.nodesByDepth).map(function(e){return parseInt(e,10);}).sort(fa);s<u.length;s++){for(var c=u[s],l=0,f=this.nodesByDepth[c];l<f.length;l++){for(var p=f[l],h=p.outboundLayer,d=p.inputTensors,m=p.outputTensors,g=new Array(),y=0,v=d;y<v.length;y++){(a=v[y]).id in n&&g.push(n[a.id]);}if(g.length===d.length){var b={},w=void 0,x=void 0,k=void 0,O=void 0;if(null!=p.callArgs&&(b=p.callArgs),1===g.length){var S=g[0],N=S[0],E=S[1];null==b.mask&&(b.mask=E),k=ta(h.call(N,b)),O=ta(h.computeMask(N,E)),w=[N],x=[E];}else w=g.map(function(e){return e[0];}),x=g.map(function(e){return e[1];}),null==b.mask&&(b.mask=x),k=ta(h.call(w,b)),O=ta(h.computeMask(w,x));if(h.activityRegularizer)throw new Xr("Model invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(r=0;r<m.length;++r){a=m[r],i=k[r],o=O[r],n[a.id]=[i,o];}}}}for(var I=[],T=[],A=[],C=0,P=this.outputs;C<P.length;C++){Zr((a=P[C]).id in n,"Could not compute output "+a.name+" : "+a.id);var _=n[a.id],R=_[0];o=_[1],A.push(R.shape),I.push(R),T.push(o);}return[I,T,A];},t.prototype.buildNodeConversionMap=function(e){for(var n,r={},a=0,i=this.layers;a<i.length;a++){var o=i[a];n=o instanceof t?1:0;for(var s=0;s<o.inboundNodes.length;s++){var u=t.nodeKey(o,s);u in this.containerNodes&&(r[u]=n,n+=1);}}return r;},t.prototype.getLayer=function(e,t){if(null!=t){if(this.layers.length<=t)throw new Kr("Was asked to retrieve layer at index "+t+", but model only has "+this.layers.length+" layer(s).");return this.layers[t];}if(null==e)throw new Kr("Provide either a layer name or layer index");for(var n=0,r=this.layers;n<r.length;n++){var a=r[n];if(a.name===e)return a;}throw new Kr("No such layer: "+e);},t.prototype.calculateLosses=function(){var e=this;return Object(yr.f)(function(){for(var n=[],r=0,a=e.layers;r<a.length;r++){for(var i=a[r],o=0;o<i.inboundNodes.length;++o){var s=t.nodeKey(i,o);e.containerNodes.has(s)&&n.push.apply(n,i.calculateLosses());}}return n;});},t.prototype.getConfig=function(){for(var e={name:this.name},n=this.buildNodeConversionMap(this.layers),r=[],a=0,i=this.layers;a<i.length;a++){for(var o=(b=i[a]).getClassName(),s=b.getConfig(),u=[],c=0;c<b.inboundNodes.length;c++){var l=b.inboundNodes[c],f=t.nodeKey(b,c),p={};if(this.containerNodes.has(f)&&(l.callArgs&&(-1===JSON.stringify(l.callArgs).indexOf("undefined")?p=l.callArgs:(console.warn("Layer "+b.name+" was passed non-serializable keyword arguments: "+l.callArgs+". They will not be included in the serialized model (and thus will be missing at deserialization time)."),p={})),l.inboundLayers.length>0)){for(var h=[],d=0;d<l.inboundLayers.length;d++){var m=l.inboundLayers[d],g=l.nodeIndices[d],y=l.tensorIndices[d];null!==(x=n[t.nodeKey(m,g)])&&void 0!==x||(x=0),h.push([m.name,x,y,p]);}u.push(h);}}r.push({name:b.name,className:o,config:s,inboundNodes:u});}e.layers=r;var v=[];for(d=0;d<this.inputLayers.length;d++){var b=this.inputLayers[d];g=this.inputLayersNodeIndices[d],f=t.nodeKey(b,g),this.containerNodes.has(f)&&(null!==(x=n[f])&&void 0!==x||(x=0),y=this.inputLayersTensorIndices[d],v.push([b.name,x,y]));}e.inputLayers=v;var w=[];for(d=0;d<this.outputLayers.length;d++){var x;if(b=this.outputLayers[d],g=this.outputLayersNodeIndices[d],f=t.nodeKey(b,g),this.containerNodes.has(f))null!==(x=n[f])&&void 0!==x||(x=0),y=this.outputLayersTensorIndices[d],w.push([b.name,x,y]);}return e.outputLayers=w,e;},t.fromConfig=function(e,t){var n={},r={};function a(e,t){e.name in r?r[e.name].push(t):r[e.name]=[t];}function i(e,t){for(var r,i=[],o=0,s=t;o<s.length;o++){var u=s[o],c=u[0],l=u[1],f=u[2];if(3===u.length)r={};else{if(4!==u.length)throw new Kr("Improperly formatted model config for layer "+JSON.stringify(e)+": "+JSON.stringify(u));r=u[3];}if(!(c in n))return void a(e,t);var p=n[c];if(p.inboundNodes.length<=l)return void a(e,t);var h=p.inboundNodes[l];i.push(h.outputTensors[f]);}i.length>0&&e.apply(ea(i),r);}function o(e){var r=e.name,i=Oi(e,null!=t.customObjects?t.customObjects:{});n[r]=i;for(var o=0,s=e.inboundNodes;o<s.length;o++){var u=s[o];if(!(u instanceof Array))throw new Kr("Corrupted configuration, expected array for nodeData: "+u);a(i,u);}}for(var s=t.name,u=t.layers,c=0,l=u;c<l.length;c++){o(h=l[c]);}for(;!ha(r);){for(var f=0,p=u;f<p.length;f++){var h=p[f];if((E=n[h.name]).name in r){for(var d=0,m=r[E.name];d<m.length;d++){i(E,m[d]);}delete r[E.name];}}}for(var g=[],y=[],v=0,b=t.inputLayers;v<b.length;v++){var w=(h=b[v])[0],x=h[1],k=h[2];Zr(w in n);var O=(E=n[w]).inboundNodes[x].outputTensors;g.push(O[k]);}for(var S=0,N=t.outputLayers;S<N.length;S++){var E;w=(h=N[S])[0],x=h[1],k=h[2],Zr(w in n),O=(E=n[w]).inboundNodes[x].outputTensors,y.push(O[k]);}return new e({inputs:g,outputs:y,name:s});},Object.defineProperty(t.prototype,"stateful",{get:function get(){if(this._stateful)throw new Kr("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(var e=0,t=this.layers;e<t.length;e++){if(t[e].stateful)return!0;}return!1;},enumerable:!0,configurable:!0}),Ii([Object(qt.a)({heading:"Layers",subheading:"Classes",namespace:"layers",subclasses:["Model"]})],t.prototype,"getLayer",null),t;}(_i);function Di(e,t,n){var r=function(e){switch(e){case"float32":return"float32";default:throw new Kr("Invalid dtype: "+e);}}(e);return m.a.make(t,{values:0===t.length?n:y.flatten(n)},r);}function Li(e,t,n,r){if(!n.startsWith("2."))throw new Kr("Unsupported Keras version in weights being loaded: "+n);return t;}var zi=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Fi=function Fi(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},Bi=function Bi(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},Vi=function(){function e(){this.validationData=null,this.model=null;}return e.prototype.setParams=function(e){this.params=e;},e.prototype.setModel=function(e){this.model=e;},e.prototype.onEpochBegin=function(e,t){return Fi(this,void 0,void 0,function(){return Bi(this,function(e){return[2];});});},e.prototype.onEpochEnd=function(e,t){return Fi(this,void 0,void 0,function(){return Bi(this,function(e){return[2];});});},e.prototype.onBatchBegin=function(e,t){return Fi(this,void 0,void 0,function(){return Bi(this,function(e){return[2];});});},e.prototype.onBatchEnd=function(e,t){return Fi(this,void 0,void 0,function(){return Bi(this,function(e){return[2];});});},e.prototype.onTrainBegin=function(e){return Fi(this,void 0,void 0,function(){return Bi(this,function(e){return[2];});});},e.prototype.onTrainEnd=function(e){return Fi(this,void 0,void 0,function(){return Bi(this,function(e){return[2];});});},e;}(),Ui=function(){function e(e,t){void 0===t&&(t=10),null==e&&(e=[]),this.callbacks=e,this.queueLength=t;}return e.prototype.append=function(e){this.callbacks.push(e);},e.prototype.setParams=function(e){for(var t=0,n=this.callbacks;t<n.length;t++){n[t].setParams(e);}},e.prototype.setModel=function(e){for(var t=0,n=this.callbacks;t<n.length;t++){n[t].setModel(e);}},e.prototype.onEpochBegin=function(e,t){return Fi(this,void 0,void 0,function(){var n,r;return Bi(this,function(a){switch(a.label){case 0:null==t&&(t={}),n=0,r=this.callbacks,a.label=1;case 1:return n<r.length?[4,r[n].onEpochBegin(e,t)]:[3,4];case 2:a.sent(),a.label=3;case 3:return n++,[3,1];case 4:return[2];}});});},e.prototype.onEpochEnd=function(e,t){return Fi(this,void 0,void 0,function(){var n,r;return Bi(this,function(a){switch(a.label){case 0:null==t&&(t={}),n=0,r=this.callbacks,a.label=1;case 1:return n<r.length?[4,r[n].onEpochEnd(e,t)]:[3,4];case 2:a.sent(),a.label=3;case 3:return n++,[3,1];case 4:return[2];}});});},e.prototype.onBatchBegin=function(e,t){return Fi(this,void 0,void 0,function(){var n,r;return Bi(this,function(a){switch(a.label){case 0:null==t&&(t={}),n=0,r=this.callbacks,a.label=1;case 1:return n<r.length?[4,r[n].onBatchBegin(e,t)]:[3,4];case 2:a.sent(),a.label=3;case 3:return n++,[3,1];case 4:return[2];}});});},e.prototype.onBatchEnd=function(e,t){return Fi(this,void 0,void 0,function(){var n,r;return Bi(this,function(a){switch(a.label){case 0:null==t&&(t={}),n=0,r=this.callbacks,a.label=1;case 1:return n<r.length?[4,r[n].onBatchEnd(e,t)]:[3,4];case 2:a.sent(),a.label=3;case 3:return n++,[3,1];case 4:return[2];}});});},e.prototype.onTrainBegin=function(e){return Fi(this,void 0,void 0,function(){var t,n;return Bi(this,function(r){switch(r.label){case 0:null==e&&(e={}),t=0,n=this.callbacks,r.label=1;case 1:return t<n.length?[4,n[t].onTrainBegin(e)]:[3,4];case 2:r.sent(),r.label=3;case 3:return t++,[3,1];case 4:return[2];}});});},e.prototype.onTrainEnd=function(e){return Fi(this,void 0,void 0,function(){var t,n;return Bi(this,function(r){switch(r.label){case 0:null==e&&(e={}),t=0,n=this.callbacks,r.label=1;case 1:return t<n.length?[4,n[t].onTrainEnd(e)]:[3,4];case 2:r.sent(),r.label=3;case 3:return t++,[3,1];case 4:return[2];}});});},e;}(),Wi=function(e){function t(){return e.call(this)||this;}return zi(t,e),t.prototype.onEpochBegin=function(e,t){return Fi(this,void 0,void 0,function(){return Bi(this,function(e){return this.seen=0,this.totals={},[2];});});},t.prototype.onBatchEnd=function(e,t){return Fi(this,void 0,void 0,function(){var e,n,r,a,i=this;return Bi(this,function(o){for(a in null==t&&(t={}),e=null==t.size?0:t.size,this.seen+=e,n=function n(_n9){var a=t[_n9];"number"==typeof a?(r.totals.hasOwnProperty(_n9)||(r.totals[_n9]=0),r.totals[_n9]=r.totals[_n9]+a*e):(r.totals.hasOwnProperty(_n9)||(r.totals[_n9]=Ua(0)),Object(yr.f)(function(){i.totals[_n9]=ri(i.totals[_n9],Object(f.ib)(a,Ua(e))),Object(yr.e)(i.totals[_n9]);}));},r=this,t){n(a);}return[2];});});},t.prototype.onEpochEnd=function(e,t){return Fi(this,void 0,void 0,function(){var e,n,r,a,i,o=this;return Bi(this,function(s){if(null!=t)for(e=function e(_e2){if(null==n.totals[_e2])return"continue";"number"==typeof n.totals[_e2]?t[_e2]=n.totals[_e2]/n.seen:Object(yr.f)(function(){t[_e2]=ni(Object(f.J)(Ua(1),Ua(o.seen)),o.totals[_e2]),o.totals[_e2].dispose(),Object(yr.e)(t[_e2]);});},n=this,r=0,a=this.params.metrics;r<a.length;r++){i=a[r],e(i);}return[2];});});},t;}(Vi);function Gi(e){return Fi(this,void 0,void 0,function(){var t,n,r,a,i,o,s;return Bi(this,function(u){switch(u.label){case 0:if(null==e)return[2];for(r in t=[],n=[],e){"number"!=typeof(a=e[r])&&(i=a,t.push(i.data()),n.push(r));}return[4,Promise.all(t)];case 1:for(o=u.sent(),s=0;s<o.length;++s){e[n[s]]=o[s][0];}return[2];}});});}var qi=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return zi(t,e),t.prototype.onTrainBegin=function(e){return Fi(this,void 0,void 0,function(){return Bi(this,function(e){return this.epoch=[],this.history={},[2];});});},t.prototype.onEpochEnd=function(e,t){return Fi(this,void 0,void 0,function(){var n;return Bi(this,function(r){for(n in null==t&&(t={}),this.epoch.push(e),t){null==this.history[n]&&(this.history[n]=[]),this.history[n].push(t[n]);}return[2];});});},t.prototype.syncData=function(){return Fi(this,void 0,void 0,function(){var e,t,n,r,a,i,o,s,u;return Bi(this,function(c){switch(c.label){case 0:for(r in e=[],t=[],n=[],this.history){for(a=this.history[r],i=0;i<a.length;++i){"number"!=typeof a[i]&&(o=a[i],e.push(o.data()),t.push(r),n.push(i));}}return[4,Promise.all(e)];case 1:for(s=c.sent(),u=0;u<s.length;++u){this.history[t[u]][n[u]].dispose(),this.history[t[u]][n[u]]=s[u][0];}return[2];}});});},t;}(Vi),Hi=function(e){function t(t){var n=e.call(this)||this;return n.trainBegin=t.onTrainBegin,n.trainEnd=t.onTrainEnd,n.epochBegin=t.onEpochBegin,n.epochEnd=t.onEpochEnd,n.batchBegin=t.onBatchBegin,n.batchEnd=t.onBatchEnd,n;}return zi(t,e),t.prototype.onEpochBegin=function(e,t){return Fi(this,void 0,void 0,function(){return Bi(this,function(n){switch(n.label){case 0:return null==this.epochBegin?[3,3]:[4,Gi(t)];case 1:return n.sent(),[4,this.epochBegin(e,t)];case 2:n.sent(),n.label=3;case 3:return[2];}});});},t.prototype.onEpochEnd=function(e,t){return Fi(this,void 0,void 0,function(){return Bi(this,function(n){switch(n.label){case 0:return null==this.epochEnd?[3,3]:[4,Gi(t)];case 1:return n.sent(),[4,this.epochEnd(e,t)];case 2:n.sent(),n.label=3;case 3:return[2];}});});},t.prototype.onBatchBegin=function(e,t){return Fi(this,void 0,void 0,function(){return Bi(this,function(n){switch(n.label){case 0:return null==this.batchBegin?[3,3]:[4,Gi(t)];case 1:return n.sent(),[4,this.batchBegin(e,t)];case 2:n.sent(),n.label=3;case 3:return[2];}});});},t.prototype.onBatchEnd=function(e,t){return Fi(this,void 0,void 0,function(){return Bi(this,function(n){switch(n.label){case 0:return null==this.batchEnd?[3,3]:[4,Gi(t)];case 1:return n.sent(),[4,this.batchEnd(e,t)];case 2:n.sent(),n.label=3;case 3:return[2];}});});},t.prototype.onTrainBegin=function(e){return Fi(this,void 0,void 0,function(){return Bi(this,function(t){switch(t.label){case 0:return null==this.trainBegin?[3,3]:[4,Gi(e)];case 1:return t.sent(),[4,this.trainBegin(e)];case 2:t.sent(),t.label=3;case 3:return[2];}});});},t.prototype.onTrainEnd=function(e){return Fi(this,void 0,void 0,function(){return Bi(this,function(t){switch(t.label){case 0:return null==this.trainEnd?[3,3]:[4,Gi(e)];case 1:return t.sent(),[4,this.trainEnd(e)];case 2:t.sent(),t.label=3;case 3:return[2];}});});},t;}(Vi);function Ki(e,t){return Object(yr.f)(function(){var n=f.rc(si(e),t,!0),r=ni(Object(f.Sb)(Wa()),f.sb(e)),a=f.hc(f.Ya(n,r));return f.J(e,a);});}function Xi(e,t){return Object(yr.f)(function(){return f.ab(si(f.pc(t,e)),-1);});}function Ji(e,t){return Object(yr.f)(function(){return f.ab(f.a(f.pc(t,e)),-1);});}function Yi(e,t){return Object(yr.f)(function(){var n=f.pc(e,t),r=f.v(f.a(e),Wa(),Number.MAX_VALUE),a=f.a(f.J(n,r));return ni(Ua(100),f.ab(a,-1));});}function Qi(e,t){return Object(yr.f)(function(){var n=Ua(1),r=f.v(t,Wa(),Number.MAX_VALUE),a=f.La(ri(n,r)),i=f.v(e,Wa(),Number.MAX_VALUE),o=f.La(ri(n,i));return f.ab(si(f.pc(a,o)),-1);});}function Zi(e,t){return Object(yr.f)(function(){var n=Ua(0),r=Ua(1),a=f.Ya(n,f.pc(r,f.ib(e,t)));return f.ab(si(a),-1);});}function $i(e,t){return Object(yr.f)(function(){var n=Ua(0),r=Ua(1),a=f.Ya(n,f.pc(r,f.ib(e,t)));return f.ab(a,-1);});}function eo(e,t){return Object(yr.f)(function(){var n=Ua(0),r=Ua(1),a=f.rc(f.ib(e,t),-1),i=f.Wa(f.ib(f.pc(r,e),t),-1);return f.Ya(n,ri(r,f.pc(i,a)));});}function to(e,t){return Object(yr.f)(function(){var n=Ua(Math.log(2)),r=f.pc(t,e),a=f.pc(f.d(r,f.fc(ni(Ua(-2),r))),n);return f.ab(a,-1);});}function no(e,t,n){return void 0===n&&(n=!1),Object(yr.f)(function(){if(n)t=f.ec(t);else{var r=f.rc(t,Ga(t).length-1,!0);t=f.J(t,r);}return t=f.v(t,Wa(),1-Wa()),f.mb(f.rc(f.ib(e.toFloat(),f.La(t)),Ga(t).length-1));});}function ro(e,t,n){return void 0===n&&(n=!1),Object(yr.f)(function(){var r=f.V(function(e){var t=[Ta(e.shape)];return e.reshape(t);}(e)).toInt(),a=Ga(t);return no(f.qb(r,a[a.length-1]).reshape(a),t,n);});}function ao(e,t){return Object(yr.f)(function(){var n;return n=f.v(t,Wa(),1-Wa()),n=f.La(f.J(n,f.pc(f.sb(n),n))),f.ab(function(e,t){return Object(yr.f)(function(){var n=f.Ya(t,f.Ic(t)),r=f.ib(t,e),a=f.La(f.d(Ua(1),f.Q(f.mb(f.a(t)))));return f.d(f.pc(n,r),a);});}(e,n),-1);});}function io(e,t){return Object(yr.f)(function(){var n=f.v(e,Wa(),1),r=f.v(t,Wa(),1);return f.rc(f.ib(e,f.La(f.J(n,r))),-1);});}function oo(e,t){return Object(yr.f)(function(){var n=f.La(ri(Ua(Wa()),t));return f.ab(f.pc(t,f.ib(e,n)),-1);});}function so(e,t){return Object(yr.f)(function(){var n=Ki(e,-1),r=Ki(t,-1),a=f.ib(n,r);return f.mb(f.rc(a,-1));});}function uo(e){var t={meanSquaredError:Xi,meanAbsoluteError:Ji,meanAbsolutePercentageError:Yi,meanSquaredLogarithmicError:Qi,squaredHinge:Zi,hinge:$i,categoricalHinge:eo,logcosh:to,categoricalCrossentropy:no,sparseCategoricalCrossentropy:ro,binaryCrossentropy:ao,kullbackLeiblerDivergence:io,poisson:oo,cosineProximity:so};if("string"==typeof e){if(e in t)return t[e];throw new Kr("Unknown loss "+e);}return e;}function co(e,t){return Object(yr.f)(function(){var n=ni(Ua(.5),f.sb(t)),r=Ka(f.Y(t,n),e.dtype);return f.ab(f.N(e,r),-1);});}function lo(e,t){return Object(yr.f)(function(){return Ka(f.N(f.f(e,-1),f.f(t,-1)),"float32");});}function fo(e,t){return ao(e,t);}function po(e,t){throw new Xr();}var ho=Xi,mo=Xi,go=Ji,yo=Ji,vo=Yi,bo=Yi,wo=no,xo=so,ko=ro,Oo=function(){function e(t){if(this.id2Value={},t instanceof e)for(var n in t.id2Value){this.id2Value[n]=t.id2Value[n];}else{if(null==t)return;for(var r=0,a=t;r<a.length;r++){var i=a[r];this.add(i.key,i.value);}}}return e.prototype.add=function(e,t){if(function(e,t){if(null!=e.dtype&&e.dtype!==t.dtype)throw new Kr("The dtype of the feed ("+t.dtype+") is incompatible with that of the key '"+e.name+"' ("+e.dtype+").");if(null!=e.shape){if(e.shape.length!==t.shape.length)throw new Kr("The rank of feed ("+t.shape.length+") does not match the rank of the key ("+e.shape.length+").");for(var n=0;n<e.shape.length;++n){if(null!=e.shape[n]&&e.shape[n]!==t.shape[n])throw new Kr("The "+n+"-th dimension of the feed ("+t.shape[n]+") is incompatible with that of the key ("+e.shape[n]+").");}}}(e,t),null!=this.id2Value[e.id])throw new Kr("Duplicate key: name="+e.name+", id="+e.id);return this.id2Value[e.id]=t,this;},e.prototype.addFeed=function(e){this.add(e.key,e.value);},e.prototype.hasKey=function(e){return null!=this.id2Value[e.id];},e.prototype.getValue=function(e){if(null==this.id2Value[e.id])throw new Kr("Nonexistent key: "+JSON.stringify(e));return this.id2Value[e.id];},e;}();function So(e,t,n){for(var r=Array.isArray(e),a=r?e:[e],i=[],o=new Oo(t),s=0,u=a;s<u.length;s++){var c=u[s];i.push(No(c,o,n));}return r?i:i[0];}function No(e,t,n){if(t.hasKey(e))return t.getValue(e);if(e.sourceLayer instanceof Ri)throw new Kr("Missing a feed value for SymbolicTensor from InputLayer '"+Ri.name+"'");for(var r=[],a=0,i=e.inputs;a<i.length;a++){var o=No(i[a],t,n);r.push(o);}var s=e.sourceLayer.apply(r,n);Array.isArray(s)||(s=[s]);for(var u=function(e){var t;if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{for(var n=null,r=0;r<e.sourceLayer.inboundNodes.length;++r){for(var a=0,i=e.sourceLayer.inboundNodes[r].outputTensors;a<i.length;a++){if(i[a].id===e.id){n=r;break;}}}t=e.sourceLayer.getOutputAt(n);}return t;}(e),c=Array.isArray(u)?u:[u],l=0;l<c.length;++l){t.add(c[l],s[l]);}return 1===s.length?s[0]:s[e.outputTensorIndex];}var Eo,Io=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),To=function To(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},Ao=function Ao(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},Co=function Co(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}};function Po(e){return Array.isArray(e);}function _o(e){return!function(e){return e instanceof m.a;}(e)&&!Po(e);}function Ro(e,t,n,r,a){if(void 0===r&&(r=!0),void 0===a&&(a=""),null==t||0===t.length){if(null!=e){var i=!1;if(Po(e)&&e.length>0)i=!0;else if(_o(e)){for(var o in e){if(e.hasOwnProperty(o)){i=!0;break;}}}else i=!0;if(i)throw new Kr("Error when checking model "+a+" expected no data, but got "+e);}return[];}if(null==e)return t.map(function(e){return null;});var s;if(_o(e)){e=e,s=[];for(var u=0,c=t;u<c.length;u++){var l=c[u];if(null==e[l])throw new Kr('No data provided for "'+l+'". Need data for each key in: '+t);s.push(e[l]);}}else if(Po(e)){if((e=e).length!==t.length)throw new Kr("Error when checking model "+a+": the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see "+t.length+" Tensor(s), but instead got the following list of Tensor(s): "+e);s=e;}else{if(e=e,t.length>1)throw new Kr("The model "+a+" expects "+t.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+e.shape);s=[e];}for(var f=0;f<t.length;++f){1===(p=s[f]).shape.length&&(s[f]=Xa(p,1));}if(null!=n)for(f=0;f<t.length;++f){if(null!=n[f]){var p;if((p=s[f]).shape.length!==n[f].length)throw new Kr("Error when checking "+a+": expected "+t[f]+" to have "+n[f].length+" dimension(s). but got array with shape "+p.shape);for(var h=0;h<n[f].length;++h){if(0!==h||r){var d=p.shape[h],m=n[f][h];if(null!=m&&m>=0&&d!==m)throw new Kr("Error when checking "+a+": expected "+t[f]+" to have shape ["+n[f]+"], but got array with shape ["+p.shape+"].");}}}}return s;}function Mo(e,t){for(var n=[],r=0,a=null;r<e;){(a=r+t)>=e&&(a=e),n.push([r,a]),r=a;}return n;}function jo(e,t,n){return null==e?[null]:Array.isArray(e)?e.map(function(e){return Ja(e,t,n-t);}):Ja(e,t,n-t);}function Do(e,t){return null==e?null:Array.isArray(e)?e.map(function(e){return Do(e,t);}):oi(e,"int32"===t.dtype?t:t.toInt());}function Lo(e,t,n,r,a){var i;if(void 0===r&&(r=!0),void 0===a&&(a=""),Array.isArray(e)){if(e.length!==t.length)throw new Kr("Error when checking model "+a+": the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see "+t.length+" Tensor(s), but instead got "+e.length+" Tensors(s).");i=e;}else{if(t.length>1)throw new Kr("The model expects "+t.length+" "+a+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(e.shape)+".");i=[e];}if(null!=n)for(var o=0;o<t.length;++o){if(null!=n[o]){var s=i[o];if(s.shape.length!==n[o].length)throw new Kr("Error when checking "+a+": expected "+t[o]+" to have "+n[o].length+" dimension(s), but got array with shape "+JSON.stringify(s.shape));for(var u=0;u<n[o].length;++u){if(0!==u||r){var c=s.shape[u],l=n[o][u];if(null!=l&&l!==c)throw new Kr("Error when checking "+a+": expected "+t[o]+" to have shape "+JSON.stringify(n[o])+" but got array with shape "+JSON.stringify(s.shape)+".");}}}}}!function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE";}(Eo||(Eo={}));var zo=function(e){function t(t){return e.call(this,t)||this;}return Io(t,e),t.prototype.compile=function(e){var t=this;if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"==typeof e.optimizer)this.optimizer=function(e){var t={Adagrad:function Adagrad(){return zr.adagrad(.01);},Adam:function Adam(){return zr.adam(.001,.9,.999,Wa());},RMSProp:function RMSProp(){return zr.rmsprop(.001,.9,null,Wa());},SGD:function SGD(){return zr.sgd(.01);}};if(t.adagrad=t.Adagrad,t.adam=t.Adam,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new Kr("Unknown Optimizer "+e);}(e.optimizer);else{if(!(e.optimizer instanceof wr))throw new Kr("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer=e.optimizer;}var n=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss){if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new Kr("When passing an Array as loss, it should have one entry per model output. The model has "+this.outputs.length+" output(s), but you passed loss="+e.loss+".");var r=e.loss;n=r.map(function(e){return uo(e);});}else{var a=uo(e.loss);this.outputs.map(function(e){n.push(a);});}}else{for(var i in e.loss=e.loss,e.loss){if(-1===this.outputNames.indexOf(i))throw new Kr('Unknown entry in loss dictionary: "'+i+'". Only expect the following keys: '+this.outputNames);}for(var o in this.outputNames){null==e.loss[o]&&console.warn('Output "'+o+'" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to '+o+" during training"),n.push(uo(e.loss[o]));}}this.lossFunctions=n,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(var s=0;s<this.outputs.length;++s){var u=this.internalOutputShapes[s],c=this.outputNames[s];this.feedOutputNames.push(c),this.feedOutputShapes.push(u),this.feedLossFns.push(this.lossFunctions[s]);}var l=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],ci("loss",function(){for(var e=0;e<t.outputs.length;++e){if(-1===l.indexOf(e)){var n=t.lossFunctions[e];t.outputs.length>1&&(t.metricsTensors.push([n,e]),t.metricsNames.push(t.outputNames[e]+"_loss"));}}});var f=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map(function(e){return[];});if(Array.isArray(e))return t.map(function(t){return e;});if(null!=e){for(var n=[],r=0,a=t;r<a.length;r++){var i=a[r],o=e.hasOwnProperty(i)?e[i]:[];Array.isArray(o)||(o=[o]),n.push(o);}return n;}throw new TypeError("Type of metrics argument not understood. Expected an Array or Object, found: "+e);}(e.metrics,this.outputNames);ci("metric",function(){for(var e=function e(_e3){if(-1!==l.indexOf(_e3))return"continue";!function(n){for(var r,a,i,o=function o(n){if(-1!==["accuracy","acc","crossentropy","ce"].indexOf(n)){var o=t.internalOutputShapes[_e3];1===o[o.length-1]||t.lossFunctions[_e3]===ao?-1!==["accuracy","acc"].indexOf(n)?a=co:-1!==["crossentropy","ce"].indexOf(n)&&(a=fo):t.lossFunctions[_e3]===ro?-1!==["accuracy","acc"].indexOf(n)?a=po:-1!==["crossentropy","ce"].indexOf(n)&&(a=ko):-1!==["accuracy","acc"].indexOf(n)?a=lo:-1!==["crossentropy","ce"].indexOf(n)&&(a=wo);var s=void 0;-1!==["accuracy","acc"].indexOf(n)?s="acc":-1!==["crossentropy","ce"].indexOf(n)&&(s="ce"),i=a,r=""+s;}else{var u=function(e){var t={binaryAccuracy:co,categoricalAccuracy:lo,categoricalCrossentropy:wo,sparseCategoricalCrossentropy:ko,mse:ho,MSE:mo,mae:go,MAE:yo,mape:vo,MAPE:bo,cosine:xo};if("string"==typeof e&&(e in t))return t[e];if("string"!=typeof e&&null!=e)return e;throw new Kr("Unknown metric "+e);}(n);i=u,r=""+n;}var c;ci(r,function(){c=i;}),function(e,n,r){t.outputNames.length>1&&(n=t.outputNames[e]+"_"+n),t.metricsNames.push(n),t.metricsTensors.push([r,e]);}(_e3,r,c);},s=0,u=f[_e3];s<u.length;s++){o(u[s]);}}();},n=0;n<t.outputs.length;++n){e(n);}}),this.collectedTrainableWeights=this.trainableWeights;},t.prototype.checkTrainableWeightsConsistency=function(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?");},t.prototype.evaluate=function(e,t,n){void 0===n&&(n={});var r=null==n.batchSize?32:n.batchSize,a=this.standardizeUserData(e,t,!0,r),i=a[0].concat(a[1]);this.makeTestFunction();var o=this.testFunction;return ea(this.testLoop(o,i,r,n.verbose,n.steps));},t.prototype.checkNumSamples=function(e,t,n,r){var a;if(void 0===r&&(r="steps"),null!=n){if(a=null,null!=t)throw new Kr("If "+r+" is set, batchSize must be null or undefined.Got batchSize = "+t);}else{if(null==e)throw new Kr("Either the input data should have a defined shape, or "+r+" shoud be specified.");a=Array.isArray(e)?e[0].shape[0]:e.shape[0];}return a;},t.prototype.predictLoop=function(e,t,n){var r=this;void 0===t&&(t=32),void 0===n&&(n=!1);var a=this.checkNumSamples(e);if(n)throw new Xr("Verbose predictLoop() is not implemented yet.");for(var i=Mo(a,t),o=[],s=function s(t){var n=yr.f(function(){var n=i[t][0],a=i[t][1],o=jo(e,n,a),s=[];if(Array.isArray(o))for(var u=0;u<o.length;++u){s.push({key:r.inputs[u],value:o[u]});}else s.push({key:r.inputs[0],value:o});var c=new Oo(s);return So(r.outputs,c);});if(0===t)for(var a=0,s=n;a<s.length;a++){var u=s[a];o.push(u);}else for(var c=0;c<n.length;++c){o[c]=$a(o[c],n[c]);}},u=0;u<i.length;++u){s(u);}return ea(o);},t.prototype.predict=function(e,t){void 0===t&&(t={}),Lo(e,this.inputNames,this.feedInputShapes,!1);var n=null==t.batchSize?32:t.batchSize;return this.predictLoop(e,n);},t.prototype.predictOnBatch=function(e){return Lo(e,this.inputNames,this.feedInputShapes,!0),this.predictLoop(e,e.shape[0]);},t.prototype.standardizeUserData=function(e,t,n,r){if(void 0===n&&(n=!0),null==this.optimizer)throw new Hr("You must compile a model before training/testing. Use Model.compile(modelCompileConfig).");for(var a=[],i=0;i<this.feedOutputShapes.length;++i){var o=this.feedOutputShapes[i];this.feedLossFns[i]===ro?a.push(o.slice(0,o.length-1).concat([1])):a.push(o);}if(function(e,t,n){var r=pa(e.map(function(e){return e.shape[0];}));r.sort();var a=pa(t.map(function(e){return e.shape[0];}));if(a.sort(),r.length>1)throw new Kr("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(e){return e.shape;})));if(a.length>1)throw new Kr("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map(function(e){return e.shape;})));if(r.length>0&&a.length>0&&!y.arraysEqual(r,a))throw new Kr("Input Tensors should have the same number of samples as target Tensors. Found "+r[0]+" input sample(s) and "+a[0]+" target sample(s).");}(e=Ro(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=Ro(t,this.feedOutputNames,a,!1,"target")),function(e,t,n){for(var r=[Xi,ao,no],a=0;a<e.length;++a){var i=e[a],o=t[a],s=n[a];if(null!=o){if(o===no&&1===i.shape[i.shape.length-1])throw new Kr("You are passing a target array of shape "+i.shape+" while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].");if(-1!==r.indexOf(o))for(var u=i.shape.slice(1),c=s.slice(1),l=0;l<u.length;++l){var f=u[l],p=c[l];if(null!=p&&f!==p)throw new Kr("A target Tensor with shape "+i.shape+" was passed for an output of shape "+s+", while using a loss function that expects targets to have the same shape as the output.");}}}}(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=r&&r>0&&e[0].shape[0]%r!=0)throw new Kr("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+r+". Found: "+e[0].shape[0]+" sample(s).");return[e,t,null];},t.prototype.fitLoop=function(e,t,n,r,a,i,o,s,u,c,l,p,h,d){return void 0===p&&(p=0),Ao(this,void 0,void 0,function(){var m,g,v,b,w,x,k,O=this;return Co(this,function(S){switch(S.label){case 0:if(null==r&&(r=32),null==a&&(a=1),null==c&&(c=!0),null==p&&(p=0),m=!1,null!=s&&null!=u&&(m=!0),null!=d&&(m=!0,null==h))throw new Kr("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");if(null!=(g=this.checkNumSamples(t,r,h,"steps_per_epoch"))&&(v=_a(0,g)),this.history=new qi(),o=(o=null==o?[new Wi()]:[new Wi()].concat(o)).concat([this.history]),i>0)throw new Xr("Verbose mode is not implemented yet.");return(b=new Ui(o)).setModel(this),b.setParams({epochs:a,steps:h,verbose:i,doValidation:m,metrics:l}),[4,b.onTrainBegin()];case 1:S.sent(),this.stopTraining=!1,w=function w(a){var i,o,l,p,d;return Co(this,function(w){switch(w.label){case 0:return[4,b.onEpochBegin(a)];case 1:if(w.sent(),i={},null==h)return[3,2];throw new Xr("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===c)throw new Xr("batch shuffling is not implemneted yet");c&&y.shuffle(v),o=Object(f.vc)(v),l=Mo(g,r),p=function p(a){var c;return Co(this,function(f){switch(f.label){case 0:return c={},[4,b.onBatchBegin(a,c)];case 1:return f.sent(),yr.f(function(){var f=l[a][0],p=l[a][1],h=Ja(o,f,p-f);c.batch=a,c.size=p-f;for(var d=Do(t,h),g=e(d),y=0;y<n.length;++y){var v=n[y],b=g[y];c[v]=b,yr.e(b);}if(a===l.length-1&&m){var w=O.testLoop(s,u,r);for(y=0;y<n.length;++y){v=n[y],b=w[y],yr.e(b),i["val_"+v]=b;}}}),[4,b.onBatchEnd(a,c)];case 2:return f.sent(),function(e){if(null!=e)for(var t in e){var n=e[t];"number"!=typeof n&&n.dispose();}}(c),x.stopTraining?[2,"break"]:[2];}});},d=0,w.label=3;case 3:return d<l.length?[5,p(d)]:[3,6];case 4:if("break"===w.sent())return[3,6];w.label=5;case 5:return++d,[3,3];case 6:o.dispose(),w.label=7;case 7:return[4,b.onEpochEnd(a,i)];case 8:return w.sent(),x.stopTraining?[2,"break"]:[2];}});},x=this,k=p,S.label=2;case 2:return k<a?[5,w(k)]:[3,5];case 3:if("break"===S.sent())return[3,5];S.label=4;case 4:return++k,[3,2];case 5:return[4,b.onTrainEnd()];case 6:return S.sent(),[4,this.history.syncData()];case 7:return S.sent(),[2,this.history];}});});},t.prototype.testLoop=function(e,t,n,r,a){void 0===r&&(r=0);var i=this.checkNumSamples(t,n,a,"steps"),o=[];if(1===r)throw new Xr("Verbose mode is not implemented yet.");if(null!=a)throw new Xr("steps mode in testLoop() is not implemented yet");for(var s=Mo(i,n),u=Object(f.vc)(_a(0,i)),c=0;c<s.length;++c){var l=s[c][0],p=s[c][1],h=e(Do(t,Ja(u,l,p-l)));if(0===c)for(var d=0;d<h.length;++d){o.push(Ua(0));}for(d=0;d<h.length;++d){var m=h[d];o[d]=f.d(o[d],ni(Ua(p-l),m));}}for(d=0;d<o.length;++d){o[d]=f.J(o[d],Ua(i));}return o;},t.prototype.getDedupedMetricsNames=function(){for(var e=this.metricsNames,t=[],n=0;n<e.length;++n){var r=e[n],a=r;$r(e,r)>1&&(a+="_"+$r(e.slice(0,n),r)),t.push(a);}return t;},t.prototype.makeTestFunction=function(){var e=this;this.testFunction=function(t){return yr.f(function(){for(var n,r=[],a=t.slice(0,e.inputs.length),i=t.slice(e.inputs.length,e.inputs.length+e.outputs.length),o=[],s=0;s<e.inputs.length;++s){o.push({key:e.inputs[s],value:a[s]});}var u=new Oo(o),c=So(e.outputs,u);for(s=0;s<e.lossFunctions.length;++s){var l=e.lossFunctions[s],p=f.ab(l(i[s],c[s]));n=0===s?p:f.d(n,p),r.push(n);}for(s=0;s<e.metricsTensors.length;++s){var h=e.metricsTensors[s][0],d=e.metricsTensors[s][1],m=f.ab(h(i[d],c[d]));r.push(m);}return r;});};},t.prototype.fit=function(e,t,n){return void 0===n&&(n={}),Ao(this,void 0,void 0,function(){var r,a,i,o,s,u,c,l,p,h,d,m,g,y,v,b,w,x,k,O=this;return Co(this,function(S){switch(S.label){case 0:if(r=null==n.batchSize?32:n.batchSize,a=this.standardizeUserData(e,t,!1,r),i=a[0],o=a[1],s=!1,p=!1,null!=n.validationData&&n.validationData.length>0){if(s=!0,2!==n.validationData.length)throw 3===n.validationData.length?new Xr("validationData including sample weights is not supported yet."):new Kr("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+n.validationData+" is invalid.");u=n.validationData[0],c=n.validationData[1],h=this.standardizeUserData(u,c,!0,r),u=h[0],c=h[1],l=u.concat(c);}else null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1?(s=!0,d=Math.floor(i[0].shape[0]*(1-n.validationSplit)),m=i[0].shape[0],u=jo(i,d,m),i=jo(i,0,d),c=jo(o,d,m),o=jo(o,0,d),p=!0,l=u.concat(c)):null!=n.validationSteps&&(s=!0);return g=i.concat(o),this.checkTrainableWeightsConsistency(),y=function y(e){var t=[],n=[],r=e.slice(0,O.inputs.length),a=e.slice(O.inputs.length,O.inputs.length+O.outputs.length),i=[],o=O.collectedTrainableWeights.map(function(e){return e.read();});return[O.optimizer.minimize(function(){for(var e=[],o=0;o<O.inputs.length;++o){e.push({key:O.inputs[o],value:r[o]});}var s,u=new Oo(e),c=So(O.outputs,u,{training:!0});for(o=0;o<O.lossFunctions.length;++o){var l=(0,O.lossFunctions[o])(a[o],c[o]);t.push(l);var p=f.ab(l);n.push(p),s=0===o?l:f.d(s,l);}for(o=0;o<O.metricsTensors.length;++o){var h=O.metricsTensors[o][0],d=O.metricsTensors[o][1],m=f.ab(h(a[d],c[d]));yr.e(m),i.push(m);}return s=f.ab(s),O.calculateLosses().forEach(function(e){s=f.d(s,e);}),s;},!0,o)].concat(i);},v=this.getDedupedMetricsNames(),s?(this.makeTestFunction(),b=this.testFunction,w=v.slice().concat(v.map(function(e){return"val_"+e;}))):(b=null,l=[],w=v.slice()),x=function(e){return null==e?null:e instanceof Vi?[e]:Array.isArray(e)&&e[0]instanceof Vi?e:ta(e).map(function(e){return new Hi(e);});}(n.callbacks),[4,this.fitLoop(y,g,v,r,n.epochs,n.verbose,x,b,l,n.shuffle,w,null,null,null)];case 1:return k=S.sent(),p&&(l.forEach(function(e){return e.dispose();}),i.forEach(function(e){return e.dispose();}),o.forEach(function(e){return e.dispose();})),[2,k];}});});},t.prototype.getNamedWeights=function(e){for(var t={},n=null!=e&&e.trainableOnly,r=n?this.trainableWeights:this.weights,a=this.getWeights(n),i=0;i<r.length;++i){n&&!r[i].trainable||(t[r[i].originalName]=a[i]);}return t;},t.prototype.save=function(e,t){return Ao(this,void 0,void 0,function(){var n,r,a,o,s;return Co(this,function(u){switch(u.label){case 0:if("string"==typeof e){if(0===(n=i.getSaveHandlers(e)).length)throw new Kr("Cannot find any save handlers for URL '"+e+"'");if(n.length>1)throw new Kr("Found more than one ("+n.length+") save handlers for URL '"+e+"'");e=n[0];}if(null==e.save)throw new Kr("Model.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,i.encodeWeights(this.getNamedWeights(t))];case 1:return r=u.sent(),a=!1,o=null,s=this.toJSON(o,a),[2,e.save({modelTopology:s,weightData:r.data,weightSpecs:r.specs})];}});});},t.className="Model",To([Object(qt.a)({heading:"Models",subheading:"Classes",configParamIndices:[0]})],t.prototype,"compile",null),To([Object(qt.a)({heading:"Models",subheading:"Classes",configParamIndices:[2]})],t.prototype,"evaluate",null),To([Object(qt.a)({heading:"Models",subheading:"Classes",configParamIndices:[1]})],t.prototype,"predict",null),To([Object(qt.a)({heading:"Models",subheading:"Classes"})],t.prototype,"predictOnBatch",null),To([Object(qt.a)({heading:"Models",subheading:"Classes",configParamIndices:[2]})],t.prototype,"fit",null),To([Object(qt.a)({heading:"Models",subheading:"Classes"})],t);}(ji);o.SerializationMap.register(zo);var Fo=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Bo=["fanIn","fanOut","fanAvg"],Vo=["normal","uniform"],Uo=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return Fo(t,e),t.prototype.fromConfigUsesCustomObjects=function(){return!1;},t.prototype.getConfig=function(){return{};},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;}([Object(qt.a)({heading:"Initializers",subheading:"Classes",namespace:"initializers"})],t);}(o.Serializable),Wo=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return Fo(t,e),t.prototype.apply=function(e,t){return Object(f.Hc)(e,t);},t.className="Zeros",t;}(Uo);o.SerializationMap.register(Wo);var Go=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return Fo(t,e),t.prototype.apply=function(e,t){return Object(f.rb)(e,t);},t.className="Ones",t;}(Uo);o.SerializationMap.register(Go);var qo=function(e){function t(t){var n=e.call(this)||this;return n.value=t.value,n;}return Fo(t,e),t.prototype.apply=function(e,t){var n=this;return Object(yr.f)(function(){return ni(Object(f.Sb)(n.value),Object(f.rb)(e,t));});},t.prototype.getConfig=function(){return{value:this.value};},t.className="Constant",t;}(Uo);o.SerializationMap.register(qo);var Ho=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MINVAL=-.05,n.DEFAULT_MAXVAL=.05,n.minval=t.minval||n.DEFAULT_MINVAL,n.maxval=t.maxval||n.DEFAULT_MAXVAL,n.seed=t.seed,n;}return Fo(t,e),t.prototype.apply=function(e,t){return Object(f.Gb)(e,this.minval,this.maxval,t);},t.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed};},t.className="RandomUniform",t;}(Uo);o.SerializationMap.register(Ho);var Ko=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=t.mean||n.DEFAULT_MEAN,n.stddev=t.stddev||n.DEFAULT_STDDEV,n.seed=t.seed,n;}return Fo(t,e),t.prototype.apply=function(e,t){if("bool"===t)throw new Xr("randomNormal does not support dType bool.");return ai(e,this.mean,this.stddev,t,this.seed);},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed};},t.className="RandomNormal",t;}(Uo);o.SerializationMap.register(Ko);var Xo=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=t.mean||n.DEFAULT_MEAN,n.stddev=t.stddev||n.DEFAULT_STDDEV,n.seed=t.seed,n;}return Fo(t,e),t.prototype.apply=function(e,t){if("bool"===t)throw new Xr("truncatedNormal does not support dType bool.");return Object(f.Cc)(e,this.mean,this.stddev,t,this.seed);},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed};},t.className="TruncatedNormal",t;}(Uo);o.SerializationMap.register(Xo);var Jo=function(e){function t(t){var n=e.call(this)||this;return n.gain=null!=t.gain?Object(f.Sb)(t.gain):Ua(1),n;}return Fo(t,e),t.prototype.apply=function(e,t){var n=this;return Object(yr.f)(function(){if(2!==e.length||e[0]!==e[1])throw new Kr("Identity matrix initializer can only be used for 2D square matrices.");return ni(n.gain,Object(f.T)(e[0]));});},t.prototype.getConfig=function(){return{gain:this.gain.get()};},t.className="Identity",t;}(Uo);o.SerializationMap.register(Jo);var Yo=function(e){function t(t){var n=e.call(this)||this;if(t.scale<0)throw new Kr("scale must be a positive float. Got: "+t.scale);return n.scale=null==t.scale?1:t.scale,n.mode=t.mode,function(e){da(Bo,"FanMode",e);}(n.mode),n.distribution=t.distribution,function(e){da(Vo,"Distribution",e);}(n.distribution),n.seed=t.seed,n;}return Fo(t,e),t.prototype.apply=function(e,t){var n=function(e,t){var n,r;if(void 0===t&&(t="channelsLast"),ya(t),2===e.length)n=e[0],r=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){var a=Ta(e,2);n=e[1]*a,r=e[0]*a;}else"channelsLast"===t&&(a=Ta(e,0,e.length-2),n=e[e.length-2]*a,r=e[e.length-1]*a);}else{var i=Ta(e);n=Math.sqrt(i),r=Math.sqrt(i);}return[n,r];}(e),r=n[0],a=n[1],i=this.scale;if("fanIn"===this.mode?i/=Math.max(1,r):"fanOut"===this.mode?i/=Math.max(1,a):i/=Math.max(1,(r+a)/2),"normal"===this.distribution){var o=Math.sqrt(i);if("bool"===t)throw new Xr(this.getClassName()+" does not support dType bool.");return Object(f.Cc)(e,0,o,t,this.seed);}var s=Math.sqrt(3*i);return Object(f.Gb)(e,-s,s,t);},t.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed};},t.className="VarianceScaling",t;}(Uo);o.SerializationMap.register(Yo);var Qo=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==t?null:t.seed})||this;}return Fo(t,e),t.prototype.getClassName=function(){return Yo.className;},t;}(Yo),Zo=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==t?null:t.seed})||this;}return Fo(t,e),t.prototype.getClassName=function(){return Yo.className;},t;}(Yo),$o=function(e){function t(t){return e.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this;}return Fo(t,e),t.prototype.getClassName=function(){return Yo.className;},t;}(Yo),es=function(e){function t(t){return e.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this;}return Fo(t,e),t.prototype.getClassName=function(){return Yo.className;},t;}(Yo),ts=function(e){function t(t){var n=e.call(this)||this;if(n.DEFAULT_GAIN=1,n.gain=null==t.gain?n.DEFAULT_GAIN:t.gain,n.seed=t.seed,null!=n.seed)throw new Xr("Random seed is not implemented for Orthogonal Initializer yet.");return n;}return Fo(t,e),t.prototype.apply=function(e,t){var n=this;return Object(yr.f)(function(){if(2!==e.length)throw new Xr("The Orthogonal Initializer does not support non-2D shapes yet.");e[0]*e[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+e[0]*e[1]+") elements: Slowness may result.");var t=ai(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32"),r=f.Ia.gramSchmidt(t);return e[0]>e[1]&&(r=r.transpose()),ni(Ua(n.gain),r);});},t.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed};},t.className="Orthogonal",t;}(Uo);o.SerializationMap.register(ts);var ns={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",identity:"Identity",leCunNormal:"LeCunNormal",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function rs(e,t){return void 0===t&&(t={}),ua(e,o.SerializationMap.getMap().classNameMap,t,"initializer");}function as(e){return sa(e);}function is(e){if("string"==typeof e){var t=e in ns?ns[e]:e;return"GlorotUniform"===t?new Qo():"GlorotNormal"===t?new Zo():"HeNormal"===t?new $o():"LeCunNormal"===t?new es():rs({className:t,config:{}});}return e instanceof Uo?e:rs(e);}var os=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),ss=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.getConfig=function(){return{};},t;}(o.Serializable),us=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.apply=function(e,t){return void 0===t&&(t=1),function(e,t){if(void 0===t&&(t=1),1!==t)throw new Xr("Support for alpha values other than 1 ("+t+") is not implemented yet.");return f.M(e);}(e,t);},t.className="elu",t;}(ss);o.SerializationMap.register(us);var cs=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.apply=function(e){return f.Tb(e);},t.className="selu",t;}(ss);o.SerializationMap.register(cs);var ls=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.apply=function(e){return f.Jb(e);},t.className="relu",t;}(ss);o.SerializationMap.register(ls);var fs=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.apply=function(e){return Object(yr.f)(function(){return f.cb(Ua(6),f.Jb(e));});},t.className="relu6",t;}(ss);o.SerializationMap.register(fs);var ps=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.apply=function(e){return e;},t.className="linear",t;}(ss);o.SerializationMap.register(ps);var hs=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.apply=function(e){return f.Vb(e);},t.className="sigmoid",t;}(ss);o.SerializationMap.register(hs);var ds=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.apply=function(e){return function(e){return Object(yr.f)(function(){var t=ri(Ua(.5),ni(Ua(.2),e));return f.v(t,0,1);});}(e);},t.className="hardSigmoid",t;}(ss);o.SerializationMap.register(ds);var ms=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.apply=function(e){return f.fc(e);},t.className="softplus",t;}(ss);o.SerializationMap.register(ms);var gs=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.apply=function(e){return function(e){return Object(yr.f)(function(){return f.J(e,f.d(Ua(1),f.a(e)));});}(e);},t.className="softsign",t;}(ss);o.SerializationMap.register(gs);var ys=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.apply=function(e){return f.tc(e);},t.className="tanh",t;}(ss);o.SerializationMap.register(ys);var vs=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return os(t,e),t.prototype.apply=function(e,t){return void 0===t&&(t=-1),f.ec(e,t);},t.className="softmax",t;}(ss);function bs(e){return e.getClassName();}function ws(e,t){return void 0===t&&(t={}),ua(e,o.SerializationMap.getMap().classNameMap,t,"activation");}function xs(e){return null==e?ws({className:"linear",config:{}}):"string"==typeof e?ws({className:e,config:{}}):e instanceof ss?e:ws(e);}o.SerializationMap.register(vs);var ks=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Os=function(e){function t(t){var n=e.call(this,null==t?{}:t)||this;return n.DEFAULT_ALPHA=.3,null==t&&(t={}),n.alpha=null==t.alpha?n.DEFAULT_ALPHA:t.alpha,n;}return ks(t,e),t.prototype.call=function(e,t){var n=ca(e);return Object(f.Da)(n,this.alpha);},t.prototype.computeOutputShape=function(e){return e;},t.prototype.getConfig=function(){var t={alpha:this.alpha},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="LeakyReLU",t;}(_i);o.SerializationMap.register(Os);var Ss=function(e){function t(t){var n=e.call(this,null==t?{}:t)||this;if(n.DEFAULT_ALPHA=1,null==t&&(t={}),null!=t.alpha&&t.alpha!==n.DEFAULT_ALPHA)throw new Xr("Non-default alpha value ("+t.alpha+") is not supported by the ELU layer yet.");return n.alpha=null==t.alpha?n.DEFAULT_ALPHA:t.alpha,n;}return ks(t,e),t.prototype.call=function(e,t){var n=ca(e);return Object(f.M)(n);},t.prototype.computeOutputShape=function(e){return e;},t.prototype.getConfig=function(){var t={alpha:this.alpha},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="ELU",t;}(_i);o.SerializationMap.register(Ss);var Ns=function(e){function t(t){var n=e.call(this,null==t?{}:t)||this;return n.DEFAULT_THETA=1,null==t&&(t={}),n.theta=null==t.theta?n.DEFAULT_THETA:t.theta,n.thetaTensor=Ua(n.theta),n;}return ks(t,e),t.prototype.call=function(e,t){var n=ca(e);return n.mul(Ka(n.greater(this.thetaTensor),"float32"));},t.prototype.computeOutputShape=function(e){return e;},t.prototype.getConfig=function(){var t={theta:this.theta},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="ThresholdedReLU",t;}(_i);o.SerializationMap.register(Ns);var Es=function(e){function t(t){var n=e.call(this,null==t?{}:t)||this;return n.DEFAULT_AXIS=1,null==t&&(t={}),n.softmax=new vs().apply,n.axis=null==t.axis?n.DEFAULT_AXIS:t.axis,n;}return ks(t,e),t.prototype.call=function(e,t){var n=ca(e);return this.softmax(n,this.axis);},t.prototype.computeOutputShape=function(e){return e;},t.prototype.getConfig=function(){var t={axis:this.axis},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="Softmax",t;}(_i);o.SerializationMap.register(Es);var Is=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Ts=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return Is(t,e),t;}(o.Serializable),As=function(e){function t(t){var n=e.call(this)||this,r=null==t||null==t.l1?.01:t.l1,a=null==t||null==t.l2?.01:t.l2;return n.hasL1=0!==r,n.hasL2=0!==a,n.l1=Ua(r),n.l2=Ua(a),n;}return Is(t,e),t.prototype.apply=function(e){var t=this;return Object(yr.f)(function(){var n=Object(f.Hc)([1]);return t.hasL1&&(n=Object(f.d)(n,Object(f.rc)(ni(t.l1,Object(f.a)(e))))),t.hasL2&&(n=Object(f.d)(n,Object(f.rc)(ni(t.l2,si(e))))),n.asScalar();});},t.prototype.getConfig=function(){return{l1:this.l1.dataSync()[0],l2:this.l2.dataSync()[0]};},t.fromConfig=function(e,t){return new e({l1:t.l1,l2:t.l2});},t.className="L1L2",function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;}([Object(qt.a)({heading:"Regularizers",namespace:"regularizers"})],t);}(Ts);o.SerializationMap.register(As);var Cs={l1l2:"L1L2"};function Ps(e){return sa(e);}function _s(e,t){return void 0===t&&(t={}),ua(e,o.SerializationMap.getMap().classNameMap,t,"regularizer");}function Rs(e){return null==e?null:"string"==typeof e?_s({className:e in Cs?Cs[e]:e,config:{}}):e instanceof Ts?e:_s(e);}function Ms(e,t,n){if("number"==typeof e)return Qr(e,t);if(e.length!==t)throw new Kr("The "+n+" argument must be a tuple of "+t+" integers. Received: "+e.length+" elements.");for(var r=0;r<t;++r){var a=e[r];if(!Ia(a))throw new Kr("The "+n+" argument must be a tuple of "+t+" integers. Received: "+JSON.stringify(e)+" including a non-integer number "+a);}return e;}function js(e,t,n,r,a){return void 0===a&&(a=1),null==e?e:(i="same"===n?e:e-(t+(t-1)*(a-1))+1,Math.floor((i+r-1)/r));var i;}function Ds(e,t,n,r){if(null==e)return null;if("valid"===r)e=e*t+Pa([n-t,0]);else{if("same"!==r)throw new Kr("Unsupport padding mode: "+r+".");e*=t;}return e;}var Ls=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}();function zs(e,t){return Object(yr.f)(function(){return ya(t),"channelsFirst"===t?f.Bc(e,[0,2,3,1]):e;});}var Fs=function(e){function t(t,n){var r=e.call(this,n)||this;if(r.kernel=null,r.bias=null,r.DEFAULT_KERNEL_INITIALIZER="glorotNormal",r.DEFAULT_BIAS_INITIALIZER="zeros",r.rank=t,1!==r.rank&&2!==r.rank)throw new Xr("Convolution layer for rank other than 1 or 2 ("+r.rank+") is not implemented yet.");if(r.filters=n.filters,r.kernelSize=Ms(n.kernelSize,t,"kernelSize"),r.strides=Ms(null==n.strides?1:n.strides,t,"strides"),r.padding=null==n.padding?"valid":n.padding,ba(r.padding),r.dataFormat=null==n.dataFormat?"channelsLast":n.dataFormat,ya(r.dataFormat),r.dilationRate=null==n.dilationRate?1:n.dilationRate,1===r.rank&&Array.isArray(r.dilationRate)&&1!==r.dilationRate.length)throw new Kr("dilationRate must be a number or an array of a single number for 1D convolution, but received "+JSON.stringify(r.dilationRate));if(2===r.rank)if("number"==typeof r.dilationRate)r.dilationRate=[r.dilationRate,r.dilationRate];else if(2!==r.dilationRate.length)throw new Kr("dilationRate must be a number or array of two numbers for 2D convolution, but received "+JSON.stringify(r.dilationRate));return r.activation=xs(n.activation),r.useBias=null==n.useBias||n.useBias,r.kernelInitializer=is(n.kernelInitializer||r.DEFAULT_KERNEL_INITIALIZER),r.biasInitializer=is(n.biasInitializer||r.DEFAULT_BIAS_INITIALIZER),r.kernelConstraint=ki(n.kernelConstraint),r.biasConstraint=ki(n.biasConstraint),r.kernelRegularizer=Rs(n.kernelRegularizer),r.biasRegularizer=Rs(n.biasRegularizer),r.activityRegularizer=Rs(n.activityRegularizer),r;}return Ls(t,e),t.prototype.build=function(e){e=la(e);var t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Kr("The channel dimension of the input should be defined. Found "+e[t]);var n,r=e[t],a=this.kernelSize.concat([r,this.filters]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:(n={},n[t]=r,n)}],this.built=!0;},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){var t;e=ca(e);var r=null==n.bias?null:n.bias.read();if(1===n.rank)t=function(e,t,n,r,a,i,o){return void 0===r&&(r=1),void 0===a&&(a="valid"),void 0===o&&(o=1),Object(yr.f)(function(){if(null==i&&(i="channelsLast"),ya(i),3!==e.shape.length)throw new Kr("The input of a conv1dWithBias operation should be 3, but is "+e.shape.length+" instead.");if(3!==t.shape.length)throw new Kr("The kernel for a conv1dWithBias operation should be 3, but is "+t.shape.length+" instead");if(null!=n&&1!==n.shape.length)throw new Kr("The bias for a conv1dWithBias operation should be 1, but is "+t.shape.length+" instead");if("channelsFirst"===i&&(e=f.Bc(e,[0,2,1])),"causal"===a)throw new Xr("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");var s=f.C(e,t,r,"same"===a?"same":"valid","NWC",o);return null!=n&&(s=ui(s,n)),s;});}(e,n.kernel.read(),r,n.strides[0],n.padding,n.dataFormat,n.dilationRate);else if(2===n.rank)t=function(e,t,n,r,a,i,o){return void 0===r&&(r=[1,1]),void 0===a&&(a="valid"),Object(yr.f)(function(){if(null==i&&(i="channelsLast"),ya(i),3!==e.rank&&4!==e.rank)throw new Kr("conv2dWithBias expects input to be of rank 3 or 4, but received "+e.rank+".");if(3!==t.rank&&4!==t.rank)throw new Kr("conv2dWithBias expects kernel to be of rank 3 or 4, but received "+e.rank+".");var s=zs(e,i);if("causal"===a)throw new Xr("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return s=f.D(s,t,r,"same"===a?"same":"valid","NHWC",o),null!=n&&(s=ui(s,n)),"channelsFirst"===i&&(s=f.Bc(s,[0,3,1,2])),s;});}(e,n.kernel.read(),r,n.strides,n.padding,n.dataFormat,n.dilationRate);else if(3===n.rank)throw new Xr("3D convolution is not implemented yet.");return null!=n.activation&&(t=n.activation.apply(t)),t;});},t.prototype.computeOutputShape=function(e){e=la(e);for(var t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2),r=0;r<n.length;++r){var a=js(n[r],this.kernelSize[r],this.padding,this.strides[r],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[r]);t.push(a);}var i=[e[0]];return"channelsLast"===this.dataFormat?(i=i.concat(t)).push(this.filters):(i.push(this.filters),i=i.concat(t)),i;},t.prototype.getConfig=function(){var t={rank:this.rank,filters:this.filters,kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:bs(this.activation),useBias:this.useBias,kernelInitializer:as(this.kernelInitializer),biasInitializer:as(this.biasInitializer),kernelRegularizer:Ps(this.kernelRegularizer),biasRegularizer:Ps(this.biasRegularizer),activityRegularizer:Ps(this.activityRegularizer),kernelConstraint:wi(this.kernelConstraint),biasConstraint:wi(this.biasConstraint)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t;}(_i),Bs=function(e){function t(t){return e.call(this,2,t)||this;}return Ls(t,e),t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,t;},t.className="Conv2D",t;}(Fs);o.SerializationMap.register(Bs);var Vs=function(e){function t(t){var n=e.call(this,t)||this;if(n.inputSpec=[new Ti({ndim:4})],"same"!==n.padding&&"valid"!==n.padding)throw new Kr("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+n.padding);return n;}return Ls(t,e),t.prototype.build=function(e){if(4!==(e=la(e)).length)throw new Kr("Input should have rank 4; Received input shape: "+JSON.stringify(e));var t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Kr("The channel dimension of the inputs should be defined. Found `None`.");var n,r=e[t],a=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Ti({ndim:4,axes:(n={},n[t]=r,n)})],this.built=!0;},t.prototype.call=function(e,t){var n=this;return yr.f(function(){var t=ca(e);if(4!==t.shape.length)throw new Kr("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+t.shape.length);var r,a,i=t.shape,o=i[0];"channelsFirst"===n.dataFormat?(r=2,a=3):(r=1,a=2);var s=i[r],u=i[a],c=n.kernelSize[0],l=n.kernelSize[1],p=n.strides[0],h=n.strides[1],d=[o,Ds(s,p,c,n.padding),Ds(u,h,l,n.padding),n.filters];"channelsLast"!==n.dataFormat&&(t=f.Bc(t,[0,2,3,1]));var m=f.E(t,n.kernel.read(),d,n.strides,n.padding);return"channelsLast"!==n.dataFormat&&(m=f.Bc(m,[0,3,1,2])),null!=n.bias&&(m=ui(m,n.bias.read(),n.dataFormat)),null!=n.activation&&(m=n.activation.apply(m)),m;});},t.prototype.computeOutputShape=function(e){var t,n,r,a=(e=la(e)).slice();"channelsFirst"===this.dataFormat?(t=1,n=2,r=3):(t=3,n=1,r=2);var i=this.kernelSize[0],o=this.kernelSize[1],s=this.strides[0],u=this.strides[1];return a[t]=this.filters,a[n]=Ds(a[n],s,i,this.padding),a[r]=Ds(a[r],u,o,this.padding),a;},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.dilationRate,t;},t.className="Conv2DTranspose",t;}(Bs);o.SerializationMap.register(Vs);var Us=function(e){function t(t){return e.call(this,2,t)||this;}return Ls(t,e),t.className="SeparableConv2D",t;}(function(e){function t(t,n){var r=e.call(this,t,n)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,null==n.filters)throw new Kr("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=n.kernelInitializer||null!=n.kernelRegularizer||null!=n.kernelConstraint)throw new Kr("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=n.padding&&"same"!==n.padding&&"valid"!==n.padding)throw new Kr("SeparableConv"+r.rank+"D supports only padding modes: 'same' and 'valid', but received "+JSON.stringify(n.padding));return r.depthMultiplier=null==n.depthMultiplier?1:n.depthMultiplier,r.depthwiseInitializer=is(n.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=Rs(n.depthwiseRegularizer),r.depthwiseConstraint=ki(n.depthwiseConstraint),r.pointwiseInitializer=is(n.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=Rs(n.pointwiseRegularizer),r.pointwiseConstraint=ki(n.pointwiseConstraint),r;}return Ls(t,e),t.prototype.build=function(e){if((e=la(e)).length<this.rank+2)throw new Kr("Inputs to SeparableConv"+this.rank+"D should have rank "+(this.rank+2)+", but received input shape: "+JSON.stringify(e));var t,n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n]||e[n]<0)throw new Kr("The channel dimension of the inputs should be defined, but found "+JSON.stringify(e[n]));for(var r=e[n],a=this.kernelSize.concat([r,this.depthMultiplier]),i=[],o=0;o<this.rank;++o){i.push(1);}i.push(r*this.depthMultiplier,this.filters),this.depthwiseKernel=this.addWeight("depthwise_kernel",a,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",i,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,!0,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.inputSpec=[new Ti({ndim:this.rank+2,axes:(t={},t[n]=r,t)})],this.built=!0;},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){var t;if(e=ca(e),1===n.rank)throw new Xr("1D separable convolution is not implemented yet.");return 2===n.rank&&("channelsFirst"===n.dataFormat&&(e=f.Bc(e,[0,2,3,1])),t=f.Ub(e,n.depthwiseKernel.read(),n.pointwiseKernel.read(),n.strides,n.padding,n.dilationRate,"NHWC")),n.useBias&&(t=ui(t,n.bias.read(),n.dataFormat)),null!=n.activation&&(t=n.activation.apply(t)),"channelsFirst"===n.dataFormat&&(t=f.Bc(t,[0,3,1,2])),t;});},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,delete t.kernelInitializer,delete t.kernelRegularizer,delete t.kernelConstraint,t.depthwiseInitializer=as(this.depthwiseInitializer),t.pointwiseInitializer=as(this.pointwiseInitializer),t.depthwiseRegularizer=Ps(this.depthwiseRegularizer),t.pointwiseRegularizer=Ps(this.pointwiseRegularizer),t.depthwiseConstraint=wi(this.depthwiseConstraint),t.pointwiseConstraint=wi(this.pointwiseConstraint),t;},t.className="SeparableConv",t;}(Fs));o.SerializationMap.register(Us);var Ws=function(e){function t(t){var n=e.call(this,1,t)||this;return n.inputSpec=[{ndim:3}],n;}return Ls(t,e),t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,delete t.dataFormat,t;},t.className="Conv1D",t;}(Fs);o.SerializationMap.register(Ws);var Gs=function(e){function t(t){var n=e.call(this,t)||this;return"number"==typeof t.cropping?n.cropping=[[t.cropping,t.cropping],[t.cropping,t.cropping]]:"number"==typeof t.cropping[0]?n.cropping=[[t.cropping[0],t.cropping[0]],[t.cropping[1],t.cropping[1]]]:n.cropping=t.cropping,n.dataFormat=void 0===t.dataFormat?"channelsLast":t.dataFormat,n.inputSpec=[{ndim:4}],n;}return Ls(t,e),t.prototype.computeOutputShape=function(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]];},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){return e=ca(e),"channelsLast"===n.dataFormat?Qa(Qa(e,n.cropping[0][0],e.shape[1]-n.cropping[0][0]-n.cropping[0][1],2),n.cropping[1][0],e.shape[2]-n.cropping[1][1]-n.cropping[1][0],3):Qa(Qa(e,n.cropping[0][0],e.shape[2]-n.cropping[0][0]-n.cropping[0][1],3),n.cropping[1][0],e.shape[3]-n.cropping[1][1]-n.cropping[1][0],4);});},t.prototype.getConfig=function(){var t={cropping:this.cropping,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="Cropping2D",t;}(_i);o.SerializationMap.register(Gs);var qs=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_SIZE=[2,2],n.inputSpec=[{ndim:4}],n.size=void 0===t.size?n.DEFAULT_SIZE:t.size,n.dataFormat=void 0===t.dataFormat?"channelsLast":t.dataFormat,n;}return Ls(t,e),t.prototype.computeOutputShape=function(e){if("channelsFirst"===this.dataFormat){var t=this.size[0]*e[2],n=this.size[1]*e[3];return[e[0],e[1],t,n];}return t=this.size[0]*e[1],n=this.size[1]*e[2],[e[0],t,n,e[3]];},t.prototype.call=function(e,t){var n=this;return yr.f(function(){var t=ca(e),r=t.shape;if("channelsFirst"===n.dataFormat){t=f.Bc(t,[0,2,3,1]);var a=n.size[0]*r[2],i=n.size[1]*r[3],o=t.resizeNearestNeighbor([a,i]);return f.Bc(o,[0,3,1,2]);}return a=n.size[0]*r[1],i=n.size[1]*r[2],t.resizeNearestNeighbor([a,i]);});},t.prototype.getConfig=function(){var t={size:this.size,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="UpSampling2D",t;}(_i);o.SerializationMap.register(qs);var Hs=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Ks=function(e){function t(t){var n=e.call(this,t)||this;return n.depthwiseKernel=null,n.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,n.depthwiseInitializer=is(t.depthwiseInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.depthwiseConstraint=ki(t.depthwiseConstraint),n.depthwiseRegularizer=Rs(t.depthwiseRegularizer),n;}return Hs(t,e),t.prototype.build=function(e){if((e=la(e)).length<4)throw new Kr("Inputs to DepthwiseConv2D should have rank 4. Received input shape: "+JSON.stringify(e)+".");var t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new Kr("The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not ("+e[t]+").");var n=e[t],r=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0;},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){var t=function(e,t,n,r,a,i){return void 0===n&&(n=[1,1]),void 0===r&&(r="valid"),Object(yr.f)(function(){null==a&&(a="channelsLast"),ya(a);var i=zs(e,a);if(4!==e.rank)throw new Kr("Input for depthwiseConv2d is required to be 4-D, but is instead "+e.rank+"-D");if(4!==t.rank)throw new Kr("depthwiseKernel is required to be 4-D, but is instead "+t.rank+"-D");return i=f.I(i,t,n,"same"===r?"same":"valid","NHWC",null),"channelsFirst"===a&&(i=f.Bc(i,[0,3,1,2])),i;});}(e=ca(e),n.depthwiseKernel.read(),n.strides,n.padding,n.dataFormat);return n.useBias&&(t=ui(t,n.bias.read(),n.dataFormat)),null!=n.activation&&(t=n.activation.apply(t)),t;});},t.prototype.computeOutputShape=function(e){e=la(e);var t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],r="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,a=js(t,this.kernelSize[0],this.padding,this.strides[0]),i=js(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],r,a,i]:[e[0],a,i,r];},t.className="DepthwiseConv2D",t;}(Bs);o.SerializationMap.register(Ks);var Xs=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Js=function(e){function t(t){var n=e.call(this,t)||this;if(n.rate=Math.max(Math.min(t.rate,1),0),n.rateScalar=Ua(n.rate),n.noiseShape=t.noiseShape,n.seed=t.seed,null!=n.seed)throw new Xr("Non-default seed is not implemented in Dropout layer yet: "+n.seed);return n.supportsMasking=!0,n;}return Xs(t,e),t.prototype.getNoiseShape=function(e){if(null==this.noiseShape)return this.noiseShape;for(var t=e.shape,n=[],r=0;r<this.noiseShape.length;++r){n.push(null==this.noiseShape[r]?t[r]:this.noiseShape[r]);}return n;},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){n.invokeCallHook(e,t);var r=ca(e);if(null!=n.noiseShape&&!y.arraysEqual(r.shape,n.noiseShape))throw new Xr("Non-default noise shape is not implemented in Dropout layer yet: "+JSON.stringify(n.noiseShape));if(0<n.rate&&n.rate<1){var a=null!=t.training&&t.training,i=n.getNoiseShape(r);return function(e,t,n){return void 0===n&&(n=!1),n?e():r;}(function(){return function(e,t,n,r){return Object(yr.f)(function(){if(null!=n&&!y.arraysEqual(e.shape,n))throw new Xr("Non-default noise shape is not implemented yet: "+JSON.stringify(n));if(null!=r)throw new Xr("seed is not implemented for dropout yet.");var a=f.nc(f.d(f.mb(t),f.Gb(e.shape,0,1,"float32")));return a=f.ib(f.J(Ua(1),f.pc(Ua(1),t)),a),f.ib(e,a);});}(r,n.rateScalar,i,n.seed);},0,a);}return e;});},t.prototype.getConfig=function(){var t={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="Dropout",t;}(_i);o.SerializationMap.register(Js);var Ys=function(e){function t(t){var n=e.call(this,t)||this;if(n.activation=null,n.useBias=!0,n.kernel=null,n.bias=null,n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_BIAS_INITIALIZER="zeros",null==t.batchInputShape&&null==t.inputShape&&null!=t.inputDim){var r=null;null!=t.batchSize&&(r=t.batchSize),n.batchInputShape=[r,t.inputDim];}return n.units=t.units,n.activation=xs(t.activation),null!=t.useBias&&(n.useBias=t.useBias),n.kernelInitializer=is(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.biasInitializer=is(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelConstraint=ki(t.kernelConstraint),n.biasConstraint=ki(t.biasConstraint),n.kernelRegularizer=Rs(t.kernelRegularizer),n.biasRegularizer=Rs(t.biasRegularizer),n.activityRegularizer=Rs(t.activityRegularizer),n.inputSpec=[{minNDim:2}],n;}return Xs(t,e),t.prototype.build=function(e){var t,n=(e=la(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[n,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:(t={},t[-1]=n,t)}],this.built=!0;},t.prototype.computeOutputShape=function(e){var t=(e=la(e)).slice();return t[t.length-1]=this.units,t;},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){n.invokeCallHook(e,t);var r=ii(ca(e),n.kernel.read());return null!=n.bias&&(r=ui(r,n.bias.read())),null!=n.activation&&(r=n.activation.apply(r)),r;});},t.prototype.getConfig=function(){var t={units:this.units,activation:bs(this.activation),useBias:this.useBias,kernelInitializer:as(this.kernelInitializer),biasInitializer:as(this.biasInitializer),kernelRegularizer:Ps(this.kernelRegularizer),biasRegularizer:Ps(this.biasRegularizer),activityRegularizer:Ps(this.activityRegularizer),kernelConstraint:wi(this.kernelConstraint),biasConstraint:wi(this.biasConstraint)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="Dense",t;}(_i);o.SerializationMap.register(Ys);var Qs=function(e){function t(t){var n=e.call(this,t||{})||this;return n.inputSpec=[{minNDim:3}],n;}return Xs(t,e),t.prototype.computeOutputShape=function(e){for(var t=0,n=(e=la(e)).slice(1);t<n.length;t++){if(null==n[t])throw new Kr('The shape of the input to "Flatten" is not fully defined (got '+e.slice(1)+'). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.');}return[e[0],Ta(e,1)];},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){return n.invokeCallHook(e,t),function(e){if(e.rank<=1)throw new Kr("batchFlatten requires a minimum rank of 2. Got rank: "+e.rank+".");var t=[e.shape[0],Ta(e.shape,1)];return e.reshape(t);}(ca(e));});},t.className="Flatten",t;}(_i);o.SerializationMap.register(Qs);var Zs=function(e){function t(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.activation=xs(t.activation),n;}return Xs(t,e),t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){n.invokeCallHook(e,t);var r=ca(e);return n.activation.apply(r);});},t.prototype.getConfig=function(){var t={activation:bs(this.activation)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="Activation",t;}(_i);o.SerializationMap.register(Zs);var $s=function(e){function t(t){var n=e.call(this,t)||this;return n.n=t.n,n.inputSpec=[{ndim:2}],n;}return Xs(t,e),t.prototype.computeOutputShape=function(e){return[e[0],this.n,e[1]];},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){return function(e,t){return Object(yr.f)(function(){if(2!==e.shape.length)throw new Kr("repeat() expects a rank-2 tensor, but received a rank-"+e.shape.length+" tensor.");return ei(Xa(e,1),[1,t,1]);});}(e=ca(e),n.n);});},t.prototype.getConfig=function(){var t={n:this.n},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="RepeatVector",t;}(_i);o.SerializationMap.register($s);var eu=function(e){function t(t){var n=e.call(this,t)||this;n.targetShape=t.targetShape;for(var r=0;r<n.targetShape.length;++r){n.isUnknown(n.targetShape[r])&&(n.targetShape[r]=null);}return n;}return Xs(t,e),t.prototype.isUnknown=function(e){return e<0||null==e;},t.prototype.fixUnknownDimension=function(e,t){for(var n="Total size of new array must be unchanged.",r=t.slice(),a=1,i=null,o=0;o<r.length;++o){var s=r[o];if(this.isUnknown(s)){if(null!==i)throw new Kr("Can only specifiy one unknown dimension.");i=o;}else a*=s;}var u=Ta(e);if(null!==i){if(0===a||u%a!=0)throw new Kr(n);r[i]=u/a;}else if(u!==a)throw new Kr(n);return r;},t.prototype.computeOutputShape=function(e){for(var t=!1,n=0;n<e.length;++n){if(this.isUnknown(e[n])){t=!0;break;}}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape));},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){n.invokeCallHook(e,t);var r=ca(e),a=Ga(r),i=a.slice(0,1).concat(n.fixUnknownDimension(a.slice(1),n.targetShape));return r.reshape(i);});},t.prototype.getConfig=function(){var t={targetShape:this.targetShape},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="Reshape",t;}(_i);o.SerializationMap.register(eu);var tu=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),nu=function(e){function t(t){var n=e.call(this,t)||this;if(n.embeddings=null,n.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==t.batchInputShape&&null==t.inputShape){var r=null;null!=t.batchSize&&(r=t.batchSize),null==t.inputLength?n.batchInputShape=[r,null]:n.batchInputShape=[r].concat(ta(t.inputLength));}return n.inputDim=t.inputDim,n.outputDim=t.outputDim,n.embeddingsInitializer=is(t.embeddingsInitializer||n.DEFAULT_EMBEDDINGS_INITIALIZER),n.embeddingsRegularizer=Rs(t.embeddingsRegularizer),n.activityRegularizer=Rs(t.activityRegularizer),n.embeddingsConstraint=ki(t.embeddingsConstraint),n.maskZero=t.maskZero,n.inputLength=t.inputLength,n;}return tu(t,e),t.prototype.build=function(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0;},t.prototype.computeMask=function(e,t){throw new Xr("computeMask has not been implemented for Embedding yet");},t.prototype.computeOutputShape=function(e){if(e=la(e),null==this.inputLength)return e.concat([this.outputDim]);var t=ta(this.inputLength);if(t.length!==e.length-1)throw new Kr('"inputLength" is '+this.inputLength+", but received input shape has shape "+e);for(var n=0,r=0;r<t.length;++r){var a=t[r],i=e[r+1];if(null!=a&&null!=i&&a!==i)throw new Kr('"inputLength" is '+this.inputLength+", but received input shape has shape "+e);null==a&&(t[n]=i),n++;}return[e[0]].concat(t,[this.outputDim]);},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){n.invokeCallHook(e,t);var r=ca(e);return"int32"!==Ha(r)&&(r=Ka(r,"int32")),oi(n.embeddings.read(),r.as1D()).reshape(la(n.computeOutputShape(r.shape)));});},t.prototype.getConfig=function(){var t={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:as(this.embeddingsInitializer),embeddingsRegularizer:Ps(this.embeddingsRegularizer),activityRegularizer:Ps(this.activityRegularizer),embeddingsConstraint:wi(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="Embedding",t;}(_i);o.SerializationMap.register(nu);var ru=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),au=function(e){function t(t){var n=e.call(this,t||{})||this;return n.supportsMasking=!0,n;}return ru(t,e),t.prototype.mergeFunction=function(e){throw new Xr();},t.prototype.computeElementwiseOpOutputShape=function(e,t){if(null==e||null==t)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(0===t.length)return e;for(var n=e.slice(0,e.length-t.length),r=0;r<t.length;++r){var a=e[e.length-t.length+r],i=t[r];if(null==a||null==i||a<0||i<0)n.push(null);else if(1===a)n.push(i);else if(1===i)n.push(a);else{if(a!==i)throw new Kr("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(a);}}return n;},t.prototype.build=function(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[la(e)]),(e=e).length<2)throw new Kr("A merge layer should be called on an Array of at least 2 inputs. Got "+e.length+" input(s).");for(var t=[],n=0,r=e;n<r.length;n++){null!=(o=r[n])&&null!==o[0]&&t.push(o[0]);}if((t=pa(t)).length>1)throw new Kr("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(e)+".");for(var a=null==e[0]?null:e[0].slice(1),i=1;i<e.length;++i){var o=null==e[i]?null:e[i].slice(1);a=this.computeElementwiseOpOutputShape(a,o);}var s=e.map(function(e){return e.length;});-1===e.indexOf(null)&&1===pa(s).length?this.reshapeRequired=!1:this.reshapeRequired=!0;},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){if(e=e,n.reshapeRequired){var t=[],r=e.map(function(e){return e.rank;});if(-1===r.indexOf(null)){for(var a=Pa(r),i=0,o=e;i<o.length;i++){for(var s=(h=o[i]).rank,u=0;u<a-s;++u){h=Xa(h,1);}t.push(h);}return n.mergeFunction(t);}for(var c=!1,l=0,p=e;l<p.length;l++){var h;if(null==(s=(h=p[l]).rank)){var d=Ga(h),m=d[0],g=d.slice(1).concat([m]),y=h.reshape([m].concat(Ta(d.slice(1))));y=(y=f.Bc(y,[1,0])).reshape(g),t.push(y),c=!0;}else if(s>1){var v=_a(1,s).concat([0]);t.push(f.Bc(h,v)),c=!0;}else t.push(h);}var b=n.mergeFunction(t),w=b.rank;if(c)if(null==w){var x=Ga(b);g=[m=x[x.length-1]].concat(x.slice(0,x.length-1)),b=f.Bc(b.reshape([-1,m]),[1,0]).reshape(g);}else w>1&&(v=[w-1].concat(_a(0,w-1)),b=f.Bc(b,v));return b;}return n.mergeFunction(e);});},t.prototype.computeOutputShape=function(e){var t;t=null==(e=e)[0]?null:e[0].slice(1);for(var n=1;n<e.length;++n){var r=null==e[n]?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,r);}for(var a=[],i=0,o=e;i<o.length;i++){null!=(r=o[i])&&null!==r[0]&&a.push(r[0]);}return 1===(a=pa(a)).length?a.concat(t):[null].concat(t);},t;}(_i),iu=function(e){function t(t){return e.call(this,t)||this;}return ru(t,e),t.prototype.mergeFunction=function(e){return Object(yr.f)(function(){for(var t=f.Hc(e[0].shape),n=0,r=e;n<r.length;n++){var a=r[n];t=f.d(t,a);}return t;});},t.className="Add",t;}(au);o.SerializationMap.register(iu);var ou=function(e){function t(t){return e.call(this,t)||this;}return ru(t,e),t.prototype.mergeFunction=function(e){return Object(yr.f)(function(){for(var t=f.rb(e[0].shape),n=0,r=e;n<r.length;n++){var a=r[n];t=f.ib(t,a);}return t;});},t.className="Multiply",t;}(au);o.SerializationMap.register(ou);var su=function(e){function t(t){return e.call(this,t)||this;}return ru(t,e),t.prototype.mergeFunction=function(e){return Object(yr.f)(function(){for(var t=f.Hc(e[0].shape),n=0,r=e;n<r.length;n++){var a=r[n];t=f.d(t,a);}return ni(Ua(1/e.length),t);});},t.className="Average",t;}(au);o.SerializationMap.register(su);var uu=function(e){function t(t){return e.call(this,t)||this;}return ru(t,e),t.prototype.mergeFunction=function(e){return Object(yr.f)(function(){for(var t=e[0],n=1;n<e.length;++n){t=f.Ya(t,e[n]);}return t;});},t.className="Maximum",t;}(au);o.SerializationMap.register(uu);var cu=function(e){function t(t){return e.call(this,t)||this;}return ru(t,e),t.prototype.mergeFunction=function(e){return Object(yr.f)(function(){for(var t=e[0],n=1;n<e.length;++n){t=f.cb(t,e[n]);}return t;});},t.className="Minimum",t;}(au);o.SerializationMap.register(cu);var lu=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_AXIS=-1,null==t&&(t={}),n.axis=null==t.axis?n.DEFAULT_AXIS:t.axis,n.supportsMasking=!0,n.reshapeRequired=!1,n;}return ru(t,e),t.prototype.build=function(e){if(!Array.isArray(e)||!Array.isArray(e[0])||1===e.length)throw new Kr("A `Concatenate` layer should be called on a list of at least 2 inputs");for(var t=!0,n=0,r=e=e;n<r.length;n++){if(null!=(l=r[n])){t=!1;break;}}if(!t){for(var a=[],i=0;i<e.length;++i){var o=e[i].slice();o.splice(this.axis,1);for(var s=!1,u=0,c=a;u<c.length;u++){var l=c[u];if(y.arraysEqual(l,o)){s=!0;break;}}s||a.push(o);}if(a.length>1)throw new Kr("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e));}},t.prototype.mergeFunction=function(e){var t=this;return Object(yr.f)(function(){return Za(e,t.axis);});},t.prototype.computeOutputShape=function(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new Kr("A `Concatenate` layer should be called on a list of inputs.");for(var t=e,n=t[0].slice(),r=this.axis<0?n.length+this.axis:this.axis,a=0,i=t.slice(1);a<i.length;a++){var o=i[a];if(null==n[r]||null==o[r]){n[r]=null;break;}n[r]+=o[r];}return n;},t.prototype.getConfig=function(){var t={axis:this.axis},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="Concatenate",t;}(au);o.SerializationMap.register(lu);var fu=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}();function pu(e,t,n,r,a,i){var o;if(void 0===i&&(i=.001),2===e.rank)o=f.p(e,t,n,i,a,r);else if(3===e.rank)o=f.q(e,t,n,i,a,r);else{if(4!==e.rank)throw new Xr("batchNormalization is not implememnted for array of rank "+e.rank+" yet");o=f.r(e,t,n,i,a,r);}return o;}var hu=function(e){function t(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.axis=null==t.axis?-1:t.axis,n.momentum=null==t.momentum?.99:t.momentum,n.epsilon=null==t.epsilon?.001:t.epsilon,n.center=null==t.center||t.center,n.scale=null==t.scale||t.scale,n.betaInitializer=is(t.betaInitializer||"zeros"),n.gammaInitializer=is(t.gammaInitializer||"ones"),n.movingMeanInitializer=is(t.movingMeanInitializer||"zeros"),n.movingVarianceInitializer=is(t.movingVarianceInitializer||"ones"),n.betaConstraint=ki(t.betaConstraint),n.gammaConstraint=ki(t.gammaConstraint),n.betaRegularizer=Rs(t.betaRegularizer),n.gammaRegularizer=Rs(t.gammaRegularizer),n.stepCount=0,n;}return fu(t,e),t.prototype.build=function(e){e=la(e);var t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new Kr("Axis "+t+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(e)+".");this.inputSpec=[new Ti({ndim:e.length,axes:(r={},r[t]=n,r)})];var r,a=[n];this.scale&&(this.gamma=this.addWeight("gamma",a,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",a,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",a,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",a,null,this.movingVarianceInitializer,null,!1),this.built=!0;},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){var r=null!=t.training&&t.training,a=ca(e),i=Ga(a),o=i.length,s=_a(0,o),u=n.axis>=0?n.axis:n.axis+o;s.splice(u,1);var c=Qr(1,o);c[u]=i[u];var l=s.slice();l.sort();var p=!y.arraysEqual(l,_a(0,o).slice(0,o-1));if(!r)return function(){if(p){var e=n.movingMean.read().reshape(c),t=n.movingVariance.read().reshape(c),r=n.center?n.beta.read().reshape(c):null,i=n.scale?n.gamma.read().reshape(c):null;return pu(a,e,t,r,i,n.epsilon);}return pu(a,n.movingMean.read(),n.movingVariance.read(),null==n.beta?null:n.beta.read(),null==n.gamma?null:n.gamma.read(),n.epsilon);}();var h=function(e,t,n,r,a){return void 0===a&&(a=.001),y.arraysEqual(r.slice().sort(),_a(0,e.rank-1))?function(e,t,n,r,a){return void 0===a&&(a=.001),Object(yr.f)(function(){var i=f.gb(e,r),o=i.mean,s=i.variance;return[pu(e,o,s,n,t,a),o,s];});}(e,t,n,r,a):function(e,t,n,r,a){return void 0===a&&(a=.001),Object(yr.f)(function(){for(var i=f.gb(e,r),o=i.mean,s=i.variance,u=[],c=0,l=_a(0,e.rank);c<l.length;c++){var p=l[c];-1!==r.indexOf(p)?u.push(1):u.push(e.shape[p]);}var h=o.reshape(u),d=s.reshape(u),m=null==t?null:t.reshape(u),g=null==n?null:n.reshape(u);return[pu(e,h,d,g,m,a),o,s];});}(e,t,n,r,a);}(a,n.gamma.read(),n.beta.read(),s,n.epsilon),d=h[0],m=h[1],g=h[2],v=Ta(s.map(function(e){return a.shape[e];})),b=g.mul(Ua(v/(v-(1+n.epsilon))));return function(){n.stepCount++;var e=f.hb(n.movingMean.read(),m,n.momentum,n.stepCount);n.movingMean.write(e);var t=f.hb(n.movingVariance.read(),b,n.momentum,n.stepCount);n.movingVariance.write(t);}(),d;});},t.prototype.getConfig=function(){var t={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:as(this.betaInitializer),gammaInitializer:as(this.gammaInitializer),movingMeanInitializer:as(this.movingMeanInitializer),movingVarianceInitializer:as(this.movingVarianceInitializer),betaRegularizer:Ps(this.betaRegularizer),gammaRegularizer:Ps(this.gammaRegularizer),betaConstraint:wi(this.betaConstraint),gammaConstraint:wi(this.gammaConstraint)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="BatchNormalization",t;}(_i);o.SerializationMap.register(hu);var du=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),mu=function(e){function t(t){var n=this;if(null==t&&(t={}),(n=e.call(this,t)||this).dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,null==t.padding)n.padding=[[1,1],[1,1]];else if("number"==typeof t.padding)n.padding=[[t.padding,t.padding],[t.padding,t.padding]];else{if(t.padding=t.padding,2!==t.padding.length)throw new Kr("ZeroPadding2D expects padding to be a length-2 array, but received a length-"+t.padding.length+" array.");var r=void 0,a=void 0;if("number"==typeof t.padding[0])r=[t.padding[0],t.padding[0]],a=[t.padding[1],t.padding[1]];else{if(t.padding=t.padding,2!==t.padding[0].length)throw new Kr("ZeroPadding2D expects height padding to be a length-2 array, but received a length-"+t.padding[0].length+" array.");if(r=t.padding[0],2!==t.padding[1].length)throw new Kr("ZeroPadding2D expects width padding to be a length-2 array, but received a length-"+t.padding[1].length+" array.");a=t.padding[1];}n.padding=[r,a];}return n.inputSpec=[new Ti({ndim:4})],n;}return du(t,e),t.prototype.computeOutputShape=function(e){var t,n;return e=la(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]]);},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){return function(e,t,n){return Object(yr.f)(function(){if(4!==e.rank)throw new Kr("temporalPadding expects input tensor to be 4-D, but received a "+e.rank+"-D tensor.");if(null==t&&(t=[[1,1],[1,1]]),2!==t.length||2!==t[0].length||2!==t[1].length)throw new Kr("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==n&&(n="channelsLast"),"channelsLast"!==n&&"channelsFirst"!==n)throw new Kr("Unknown data format: "+n+". Supported data formats are 'channelsLast' and 'channelsFirst.");var r;return r="channelsFirst"===n?[[0,0],[0,0],t[0],t[1]]:[[0,0],t[0],t[1],[0,0]],f.vb(e,r);});}(ca(e),n.padding,n.dataFormat);});},t.prototype.getConfig=function(){var t={padding:this.padding,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="ZeroPadding2D",t;}(_i);o.SerializationMap.register(mu);var gu=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}();function yu(e,t,n,r,a,i){return Object(yr.f)(function(){var o;ya(a),da(wa,"PoolMode",i),ba(r),null==n&&(n=[1,1]),null==r&&(r="valid"),null==a&&(a="channelsLast"),null==i&&(i="max"),e=zs(e,a);var s="same"===r?"same":"valid";return o="max"===i?f.Xa(e,t,n,s):f.m(e,t,n,s),"channelsFirst"===a&&(o=f.Bc(o,[0,3,1,2])),o;});}var vu=function(e){function t(t){var n=this;if(null==t.poolSize&&(t.poolSize=2),n=e.call(this,t)||this,"number"==typeof t.poolSize)n.poolSize=[t.poolSize];else{if(!Array.isArray(t.poolSize)||1!==t.poolSize.length||"number"!=typeof t.poolSize[0])throw new Kr("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.poolSize));n.poolSize=t.poolSize;}if(null==t.strides)n.strides=n.poolSize;else if("number"==typeof t.strides)n.strides=[t.strides];else{if(!Array.isArray(t.strides)||1!==t.strides.length||"number"!=typeof t.strides[0])throw new Kr("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.strides));n.strides=t.strides;}return n.padding=null==t.padding?"valid":t.padding,ba(n.padding),n.inputSpec=[new Ti({ndim:3})],n;}return gu(t,e),t.prototype.computeOutputShape=function(e){var t=js((e=la(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]];},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){n.invokeCallHook(e,t),e=Xa(ca(e),2);var r=n.poolingFunction(ca(e),[n.poolSize[0],1],[n.strides[0],1],n.padding,"channelsLast");return f.lc(r,[2]);});},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t;}(_i),bu=function(e){function t(t){return e.call(this,t)||this;}return gu(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return ya(a),ba(r),yu(e,t,n,r,a,"max");},t.className="MaxPooling1D",t;}(vu);o.SerializationMap.register(bu);var wu=function(e){function t(t){return e.call(this,t)||this;}return gu(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return ya(a),ba(r),yu(e,t,n,r,a,"avg");},t.className="AveragePooling1D",t;}(vu);o.SerializationMap.register(wu);var xu=function(e){function t(t){var n=this;return null==t.poolSize&&(t.poolSize=[2,2]),(n=e.call(this,t)||this).poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],n.strides=null==t.strides?n.poolSize:t.strides,n.padding=null==t.padding?"valid":t.padding,n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,ya(n.dataFormat),ba(n.padding),n.inputSpec=[new Ti({ndim:4})],n;}return gu(t,e),t.prototype.computeOutputShape=function(e){e=la(e);var t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=js(t,this.poolSize[0],this.padding,this.strides[0]),n=js(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]];},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){return n.invokeCallHook(e,t),n.poolingFunction(ca(e),n.poolSize,n.strides,n.padding,n.dataFormat);});},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t;}(_i),ku=function(e){function t(t){return e.call(this,t)||this;}return gu(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return ya(a),ba(r),yu(e,t,n,r,a,"max");},t.className="MaxPooling2D",t;}(xu);o.SerializationMap.register(ku);var Ou=function(e){function t(t){return e.call(this,t)||this;}return gu(t,e),t.prototype.poolingFunction=function(e,t,n,r,a){return ya(a),ba(r),yu(e,t,n,r,a,"avg");},t.className="AveragePooling2D",t;}(xu);o.SerializationMap.register(Ou);var Su=function(e){function t(t){var n=e.call(this,t)||this;return n.inputSpec=[new Ti({ndim:3})],n;}return gu(t,e),t.prototype.computeOutputShape=function(e){return[e[0],e[2]];},t.prototype.call=function(e,t){throw new Xr();},t;}(_i),Nu=function(e){function t(t){return e.call(this,t)||this;}return gu(t,e),t.prototype.call=function(e,t){return Object(yr.f)(function(){var t=ca(e);return f.ab(t,1);});},t.className="GlobalAveragePooling1D",t;}(Su);o.SerializationMap.register(Nu);var Eu=function(e){function t(t){return e.call(this,t)||this;}return gu(t,e),t.prototype.call=function(e,t){return Object(yr.f)(function(){var t=ca(e);return f.Wa(t,1);});},t.className="GlobalMaxPooling1D",t;}(Su);o.SerializationMap.register(Eu);var Iu=function(e){function t(t){var n=e.call(this,t)||this;return n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,ya(n.dataFormat),n.inputSpec=[new Ti({ndim:4})],n;}return gu(t,e),t.prototype.computeOutputShape=function(e){return e=e,"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]];},t.prototype.call=function(e,t){throw new Xr();},t.prototype.getConfig=function(){var t={dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t;}(_i),Tu=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return gu(t,e),t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){var t=ca(e);return"channelsLast"===n.dataFormat?f.ab(t,[1,2]):f.ab(t,[2,3]);});},t.className="GlobalAveragePooling2D",t;}(Iu);o.SerializationMap.register(Tu);var Au=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return gu(t,e),t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){var t=ca(e);return"channelsLast"===n.dataFormat?f.Wa(t,[1,2]):f.Wa(t,[2,3]);});},t.className="GlobalMaxPooling2D",t;}(Iu);o.SerializationMap.register(Au);var Cu=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}();function Pu(e,t,n,r,a,i,o,s){void 0===r&&(r=!1),void 0===o&&(o=!1);var u=t.shape.length;if(u<3)throw new Kr("Input should be at least 3D, but is "+u+"D.");var c,l,p=[1,0].concat(_a(2,u));if(t=f.Bc(t,p),null!=a)throw new Xr("The rnn() function of the deeplearn.js backend does not support masking yet.");if(null!=i)throw new Xr("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r&&(t=f.Lb(t,0));for(var h=n,d=t.shape[0],m=0;m<d;++m){var g=Ja(t,m,1),y=e(g=g.reshape(g.shape.slice(1)),h);l=y[0],c=0===m?l.reshape([1].concat(l.shape)):$a(c,l.reshape([1].concat(l.shape))),h=y[1];}return[l,f.Bc(c,[1,0].concat(_a(2,c.shape.length))),h];}var _u=function(e){function t(t){var n,r=e.call(this,t)||this;if(null==t.cell)throw new Kr("cell property is missing for the constructor of RNN.");if(null==(n=Array.isArray(t.cell)?new Bu({cells:t.cell}):t.cell).stateSize)throw new Kr("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");return r.cell=n,r.returnSequences=null!=t.returnSequences&&t.returnSequences,r.returnState=null!=t.returnState&&t.returnState,r.goBackwards=null!=t.goBackwards&&t.goBackwards,r._stateful=null!=t.stateful&&t.stateful,r.unroll=null!=t.unroll&&t.unroll,r.supportsMasking=!0,r.inputSpec=[new Ti({ndim:3})],r.stateSpec=null,r.states=null,r.numConstants=null,r;}return Cu(t,e),t.prototype.getStates=function(){return null==this.states?_a(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map(function(e){return null;}):this.states;},t.prototype.setStates=function(e){this.states=e;},t.prototype.computeOutputShape=function(e){na(e)&&(e=e[0]),e=e;var t=this.cell.stateSize;Array.isArray(t)||(t=[t]);var n,r=t[0];if(n=this.returnSequences?[e[0],e[1],r]:[e[0],r],this.returnState){for(var a=[],i=0,o=t;i<o.length;i++){var s=o[i];a.push([e[0],s]);}return[n].concat(a);}return n;},t.prototype.computeMask=function(e,t){throw new Xr("computeMask has not been implemented for RNN yet");},t.prototype.build=function(e){if(null!=this.numConstants)throw new Xr("Constants support is not implemented in RNN yet.");na(e)&&(e=e[0]),e=e;var t=this.stateful?e[0]:null,n=e[e.length-1];this.inputSpec[0]=new Ti({shape:[t,null,n]});var r,a=[e[0]].concat(e.slice(2));if(this.cell.build(a),r=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!y.arraysEqual(this.stateSpec.map(function(e){return e.shape[e.shape.length-1];}),r))throw new Kr("An initialState was passed that is not compatible with cell.stateSize. Received stateSpec="+this.stateSpec+"; However cell.stateSize is "+this.cell.stateSize);}else this.stateSpec=r.map(function(e){return new Ti({shape:[null,e]});});if(this.stateful)throw new Xr("stateful RNN layer is not implemented yet");},t.prototype.resetStates=function(e){var t=this;Object(yr.f)(function(){if(!t.stateful)throw new qr("Cannot call resetState() on an RNN Layer that is not stateful.");var n=t.inputSpec[0].shape[0];if(null==n)throw new Kr("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==t.states)Array.isArray(t.cell.stateSize)?t.states=t.cell.stateSize.map(function(e){return f.Hc([n,e]);}):t.states=[f.Hc([n,t.cell.stateSize])];else if(null==e)Array.isArray(t.cell.stateSize)?t.states=t.cell.stateSize.map(function(e){return f.Hc([n,e]);}):t.states[0]=f.Hc([n,t.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==t.states.length)throw new Kr("Layer "+t.name+" expects "+t.states.length+" state(s), but it received "+e.length+" state value(s). Input received: "+e);for(var r=0;r<t.states.length;++r){var a=e[r],i=Array.isArray(t.cell.stateSize)?t.cell.stateSize[r]:t.cell.stateSize,o=[n,i];if(!y.arraysEqual(a.shape,o))throw new Kr("State "+r+" is incompatible with layer "+t.name+": expected shape="+o+", received shape="+a.shape);t.states[r]=a;}}});},t.prototype.standardizeArgs=function(e,t,n){if(Array.isArray(e)){if(null!=t||null!=n)throw new Kr("When inputs is an array, neither initialState or constants should be provided");null!=this.numConstants&&(n=e.slice(e.length-this.numConstants,e.length),e=e.slice(0,e.length-this.numConstants)),e.length>1&&(t=e.slice(1,e.length)),e=e[0];}function r(e){return null==e||Array.isArray(e)?e:[e];}return{inputs:e,initialState:t=r(t),constants:n=r(n)};},t.prototype.apply=function(t,n){var r=null==n?null:n.initialState,a=null==n?null:n.constants;null==n&&(n={});var i=this.standardizeArgs(t,r,a);t=i.inputs,r=i.initialState,a=i.constants;var o=[],s=[];if(null!=r){n.initialState=r,o=o.concat(r),this.stateSpec=[];for(var u=0,c=r;u<c.length;u++){var l=c[u];this.stateSpec.push(new Ti({shape:l.shape}));}s=s.concat(this.stateSpec);}if(null!=a&&(n.constants=a,o=o.concat(a),this.numConstants=a.length),o[0]instanceof ja){var f=[t].concat(o),p=this.inputSpec.concat(s),h=this.inputSpec;this.inputSpec=p;var d=e.prototype.apply.call(this,f,n);return this.inputSpec=h,d;}return e.prototype.apply.call(this,t,n);},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){var r=null==t?null:t.mask,a=null==t?null:t.training,i=null==t?null:t.initialState;if(e=ca(e),null==i){if(n.stateful)throw new Xr("stateful RNN layer is not implemented yet.");i=n.getInitialState(e);}if(null!=r)throw new Xr("Masking is not implemented for RNN yet");var o=Array.isArray(n.cell.stateSize)?n.cell.stateSize.length:1;if(i.length!==o)throw new Kr("RNN Layer has "+o+" state(s) but was passed "+i.length+" initial state(s).");e.shape[1],n.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");var s={training:a},u=Pu(function(e,t){var r=n.cell.call([e].concat(t),s);return[r[0],r.slice(1)];},e,i,n.goBackwards,null,null,n.unroll),c=u[0],l=u[1],f=u[2];if(n.stateful)throw new Xr("stateful RNN layer is not implemented yet");var p=n.returnSequences?l:c;return n.returnState?[p].concat(f):p;});},t.prototype.getInitialState=function(e){var t=this;return Object(yr.f)(function(){var n=f.Hc(e.shape);return n=Xa(n=f.rc(n,[1,2])),Array.isArray(t.cell.stateSize)?t.cell.stateSize.map(function(e){return e>1?ei(n,[1,e]):n;}):t.cell.stateSize>1?[ei(n,[1,t.cell.stateSize])]:[n];});},Object.defineProperty(t.prototype,"trainableWeights",{get:function get(){return this.trainable?this.cell.trainableWeights:[];},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function get(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights;},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);var n=this.cell.getConfig();t.cell={className:this.cell.getClassName(),config:n};var r=e.prototype.getConfig.call(this);return Object.assign(t,r),t;},t.className="RNN",t;}(_i);o.SerializationMap.register(_u);var Ru=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return Cu(t,e),function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;}([Object(qt.a)({heading:"Layers",subheading:"Classes"})],t);}(_i),Mu=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,n.activation=xs(null==t.activation?n.DEFAULT_ACTIVATION:t.activation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=is(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=is(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=is(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=Rs(t.kernelRegularizer),n.recurrentRegularizer=Rs(t.recurrentRegularizer),n.biasRegularizer=Rs(t.biasRegularizer),n.kernelConstraint=ki(t.kernelConstraint),n.recurrentConstraint=ki(t.recurrentConstraint),n.biasConstraint=ki(t.biasConstraint),n.dropout=Ca([1,Pa([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=Ca([1,Pa([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.stateSize=n.units,n;}return Cu(t,e),t.prototype.build=function(e){e=la(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0;},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){if(2!==(e=e).length)throw new Kr("SimpleRNNCell expects 2 input Tensors, got "+e.length+".");var t=e[1];if(e=e[0],0!==n.dropout||0!==n.recurrentDropout)throw new Xr("Dropout is not implemented for SimpleRNNCell yet");var r=ii(e,n.kernel.read());null!=n.bias&&(r=ui(r,n.bias.read()));var a=f.d(r,ii(t,n.recurrentKernel.read()));return null!=n.activation&&(a=n.activation.apply(a)),[a,a];});},t.prototype.getConfig=function(){var t={units:this.units,activation:bs(this.activation),useBias:this.useBias,kernelInitializer:as(this.kernelInitializer),recurrentInitializer:as(this.recurrentInitializer),biasInitializer:as(this.biasInitializer),kernelRegularizer:Ps(this.kernelRegularizer),recurrentRegularizer:Ps(this.recurrentRegularizer),biasRegularizer:Ps(this.biasRegularizer),activityRegularizer:Ps(this.activityRegularizer),kernelConstraint:wi(this.kernelConstraint),recurrentConstraint:wi(this.recurrentConstraint),biasConstraint:wi(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="SimpleRNNCell",t;}(Ru);o.SerializationMap.register(Mu);var ju=function(e){function t(t){return t.cell=new Mu(t),e.call(this,t)||this;}return Cu(t,e),t.prototype.call=function(t,n){var r=this;return Object(yr.f)(function(){var a=null==n?null:n.mask,i=null==n?null:n.training,o=null==n?null:n.initialState;return e.prototype.call.call(r,t,{mask:a,training:i,initialState:o});});},Object.defineProperty(t.prototype,"units",{get:function get(){return this.cell.units;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activation",{get:function get(){return this.cell.activation;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBias",{get:function get(){return this.cell.useBias;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelInitializer",{get:function get(){return this.cell.kernelInitializer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentInitializer",{get:function get(){return this.cell.recurrentInitializer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasInitializer",{get:function get(){return this.cell.biasInitializer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelRegularizer",{get:function get(){return this.cell.kernelRegularizer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentRegularizer",{get:function get(){return this.cell.recurrentRegularizer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasRegularizer",{get:function get(){return this.cell.biasRegularizer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelConstraint",{get:function get(){return this.cell.kernelConstraint;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentConstraint",{get:function get(){return this.cell.recurrentConstraint;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasConstraint",{get:function get(){return this.cell.biasConstraint;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dropout",{get:function get(){return this.cell.dropout;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentDropout",{get:function get(){return this.cell.recurrentDropout;},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={units:this.units,activation:bs(this.activation),useBias:this.useBias,kernelInitializer:as(this.kernelInitializer),recurrentInitializer:as(this.recurrentInitializer),biasInitializer:as(this.biasInitializer),kernelRegularizer:Ps(this.kernelRegularizer),recurrentRegularizer:Ps(this.recurrentRegularizer),biasRegularizer:Ps(this.biasRegularizer),activityRegularizer:Ps(this.activityRegularizer),kernelConstraint:wi(this.kernelConstraint),recurrentConstraint:wi(this.recurrentConstraint),biasConstraint:wi(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=e.prototype.getConfig.call(this);return delete n.cell,Object.assign(t,n),t;},t.className="SimpleRNN",t;}(_u);o.SerializationMap.register(ju);var Du=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,n.activation=xs(void 0===t.activation?n.DEFAULT_ACTIVATION:t.activation),n.recurrentActivation=xs(void 0===t.activation?n.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=is(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=is(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=is(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=Rs(t.kernelRegularizer),n.recurrentRegularizer=Rs(t.recurrentRegularizer),n.biasRegularizer=Rs(t.biasRegularizer),n.kernelConstraint=ki(t.kernelConstraint),n.recurrentConstraint=ki(t.recurrentConstraint),n.biasConstraint=ki(t.biasConstraint),n.dropout=Ca([1,Pa([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=Ca([1,Pa([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.implementation=t.implementation,n.stateSize=n.units,n;}return Cu(t,e),t.prototype.build=function(e){var t=(e=la(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0;},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){if(0!==n.dropout||0!==n.recurrentDropout)throw new Xr("Dropout is not implemented for GRUCell yet");if(2!==(e=e).length)throw new Kr("GRUCell expects 2 input Tensors (inputs, h, c), got "+e.length+".");var t,r,a,i=e[1];if(e=e[0],1===n.implementation){var o=Ya(n.kernel.read(),0,n.units),s=Ya(n.kernel.read(),n.units,n.units),u=Ya(n.kernel.read(),2*n.units,n.units),c=Ya(n.recurrentKernel.read(),0,n.units),l=Ya(n.recurrentKernel.read(),n.units,n.units),p=Ya(n.recurrentKernel.read(),2*n.units,n.units),h=e,d=e,m=ii(e,o),g=ii(h,s),y=ii(d,u);if(n.useBias){var v=Ja(n.bias.read(),0,n.units),b=Ja(n.bias.read(),n.units,n.units),w=Ja(n.bias.read(),2*n.units,n.units);m=ui(m,v),g=ui(g,b),y=ui(y,w);}var x=i,k=i,O=i;t=n.recurrentActivation.apply(f.d(m,ii(x,c))),r=n.recurrentActivation.apply(f.d(g,ii(k,l))),a=n.activation.apply(f.d(y,ii(f.ib(r,O),p)));}else{var S=ii(e,n.kernel.read());n.useBias&&(S=ui(S,n.bias.read()));var N=ii(i,Ya(n.recurrentKernel.read(),0,2*n.units)),E=(m=Ya(S,0,n.units),g=Ya(S,n.units,n.units),Ya(N,0,n.units)),I=Ya(N,n.units,n.units);t=n.recurrentActivation.apply(f.d(m,E)),r=n.recurrentActivation.apply(f.d(g,I)),y=Ya(S,2*n.units,n.units);var T=ii(f.ib(r,i),Ya(n.recurrentKernel.read(),2*n.units,n.units));a=n.activation.apply(f.d(y,T));}var A=f.d(f.ib(t,i),f.ib(ri(Ua(1),f.mb(t)),a));return[A,A];});},t.prototype.getConfig=function(){var t={units:this.units,activation:bs(this.activation),useBias:this.useBias,kernelInitializer:as(this.kernelInitializer),recurrentInitializer:as(this.recurrentInitializer),biasInitializer:as(this.biasInitializer),kernelRegularizer:Ps(this.kernelRegularizer),recurrentRegularizer:Ps(this.recurrentRegularizer),biasRegularizer:Ps(this.biasRegularizer),activityRegularizer:Ps(this.activityRegularizer),kernelConstraint:wi(this.kernelConstraint),recurrentConstraint:wi(this.recurrentConstraint),biasConstraint:wi(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="GRUCell",t;}(Ru);o.SerializationMap.register(Du);var Lu=function(e){function t(t){return 0===t.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new Du(t),e.call(this,t)||this;}return Cu(t,e),t.prototype.call=function(t,n){var r=this;return Object(yr.f)(function(){var a=null==n?null:n.mask,i=null==n?null:n.training,o=null==n?null:n.initialState;return e.prototype.call.call(r,t,{mask:a,training:i,initialState:o});});},Object.defineProperty(t.prototype,"units",{get:function get(){return this.cell.units;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activation",{get:function get(){return this.cell.activation;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBias",{get:function get(){return this.cell.useBias;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelInitializer",{get:function get(){return this.cell.kernelInitializer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentInitializer",{get:function get(){return this.cell.recurrentInitializer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasInitializer",{get:function get(){return this.cell.biasInitializer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelRegularizer",{get:function get(){return this.cell.kernelRegularizer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentRegularizer",{get:function get(){return this.cell.recurrentRegularizer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasRegularizer",{get:function get(){return this.cell.biasRegularizer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelConstraint",{get:function get(){return this.cell.kernelConstraint;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentConstraint",{get:function get(){return this.cell.recurrentConstraint;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasConstraint",{get:function get(){return this.cell.biasConstraint;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dropout",{get:function get(){return this.cell.dropout;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentDropout",{get:function get(){return this.cell.recurrentDropout;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"implementation",{get:function get(){return this.cell.implementation;},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={units:this.units,activation:bs(this.activation),useBias:this.useBias,kernelInitializer:as(this.kernelInitializer),recurrentInitializer:as(this.recurrentInitializer),biasInitializer:as(this.biasInitializer),kernelRegularizer:Ps(this.kernelRegularizer),recurrentRegularizer:Ps(this.recurrentRegularizer),biasRegularizer:Ps(this.biasRegularizer),activityRegularizer:Ps(this.activityRegularizer),kernelConstraint:wi(this.kernelConstraint),recurrentConstraint:wi(this.recurrentConstraint),biasConstraint:wi(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return delete n.cell,Object.assign(t,n),t;},t.fromConfig=function(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t);},t.className="GRU",t;}(_u);o.SerializationMap.register(Lu);var zu=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,n.activation=xs(void 0===t.activation?n.DEFAULT_ACTIVATION:t.activation),n.recurrentActivation=xs(void 0===t.activation?n.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=is(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=is(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=is(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.unitForgetBias=t.unitForgetBias,n.kernelRegularizer=Rs(t.kernelRegularizer),n.recurrentRegularizer=Rs(t.recurrentRegularizer),n.biasRegularizer=Rs(t.biasRegularizer),n.kernelConstraint=ki(t.kernelConstraint),n.recurrentConstraint=ki(t.recurrentConstraint),n.biasConstraint=ki(t.biasConstraint),n.dropout=Ca([1,Pa([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=Ca([1,Pa([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.implementation=t.implementation,n.stateSize=[n.units,n.units],n;}return Cu(t,e),t.prototype.build=function(e){var t,n,r=(e=la(e))[e.length-1];if(this.kernel=this.addWeight("kernel",[r,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){var a=this.biasInitializer,i=this.units;t=new((n=function(e){function t(){return null!==e&&e.apply(this,arguments)||this;}return Cu(t,e),t.prototype.apply=function(e,t){var n=a.apply([i]),r=new Go().apply([i]),o=a.apply([2*i]);return $a($a(n,r),o);},t;}(Uo)).className="CustomInit",n)();}else t=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,t,this.biasRegularizer,!0,this.biasConstraint);}else this.bias=null;this.built=!0;},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){if(0!==n.dropout||0!==n.recurrentDropout)throw new Xr("Dropout is not implemented for LSTMCell yet");if(3!==(e=e).length)throw new Kr("LSTMCell expects 3 input Tensors (inputs, h, c), got "+e.length+".");var t,r,a,i,o=e[1],s=e[2];if(e=e[0],1===n.implementation){var u=Ya(n.kernel.read(),0,n.units),c=Ya(n.kernel.read(),n.units,n.units),l=Ya(n.kernel.read(),2*n.units,n.units),p=Ya(n.kernel.read(),3*n.units,n.units),h=Ya(n.recurrentKernel.read(),0,n.units),d=Ya(n.recurrentKernel.read(),n.units,n.units),m=Ya(n.recurrentKernel.read(),2*n.units,n.units),g=Ya(n.recurrentKernel.read(),3*n.units,n.units),y=e,v=e,b=e,w=ii(e,u),x=ii(y,c),k=ii(v,l),O=ii(b,p);if(n.useBias){var S=Ja(n.bias.read(),0,n.units),N=Ja(n.bias.read(),n.units,n.units),E=Ja(n.bias.read(),2*n.units,n.units),I=Ja(n.bias.read(),3*n.units,n.units);w=ui(w,S),x=ui(x,N),k=ui(k,E),O=ui(O,I);}var T=o,A=o,C=o,P=o;t=n.recurrentActivation.apply(f.d(w,ii(T,h))),r=n.recurrentActivation.apply(f.d(x,ii(A,d))),a=f.d(f.ib(r,s),f.ib(t,n.activation.apply(f.d(k,ii(C,m))))),i=n.recurrentActivation.apply(f.d(O,ii(P,g)));}else{var _=ii(e,n.kernel.read());_=f.d(_,ii(o,n.recurrentKernel.read())),n.useBias&&(_=ui(_,n.bias.read()));var R=Ya(_,0,n.units),M=Ya(_,n.units,n.units),j=Ya(_,2*n.units,n.units),D=Ya(_,3*n.units,n.units);t=n.recurrentActivation.apply(R),r=n.recurrentActivation.apply(M),a=f.d(f.ib(r,s),f.ib(t,n.activation.apply(j))),i=n.recurrentActivation.apply(D);}var L=f.ib(i,n.activation.apply(a));return[L,L,a];});},t.prototype.getConfig=function(){var t={units:this.units,activation:bs(this.activation),useBias:this.useBias,kernelInitializer:as(this.kernelInitializer),recurrentInitializer:as(this.recurrentInitializer),biasInitializer:as(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Ps(this.kernelRegularizer),recurrentRegularizer:Ps(this.recurrentRegularizer),biasRegularizer:Ps(this.biasRegularizer),activityRegularizer:Ps(this.activityRegularizer),kernelConstraint:wi(this.kernelConstraint),recurrentConstraint:wi(this.recurrentConstraint),biasConstraint:wi(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.className="LSTMCell",t;}(Ru);o.SerializationMap.register(zu);var Fu=function(e){function t(t){return 0===t.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new zu(t),e.call(this,t)||this;}return Cu(t,e),t.prototype.call=function(t,n){var r=this;return Object(yr.f)(function(){var a=null==n?null:n.mask,i=null==n?null:n.training,o=null==n?null:n.initialState;return e.prototype.call.call(r,t,{mask:a,training:i,initialState:o});});},Object.defineProperty(t.prototype,"units",{get:function get(){return this.cell.units;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"activation",{get:function get(){return this.cell.activation;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"useBias",{get:function get(){return this.cell.useBias;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelInitializer",{get:function get(){return this.cell.kernelInitializer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentInitializer",{get:function get(){return this.cell.recurrentInitializer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasInitializer",{get:function get(){return this.cell.biasInitializer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"unitForgetBias",{get:function get(){return this.cell.unitForgetBias;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelRegularizer",{get:function get(){return this.cell.kernelRegularizer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentRegularizer",{get:function get(){return this.cell.recurrentRegularizer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasRegularizer",{get:function get(){return this.cell.biasRegularizer;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"kernelConstraint",{get:function get(){return this.cell.kernelConstraint;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentConstraint",{get:function get(){return this.cell.recurrentConstraint;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"biasConstraint",{get:function get(){return this.cell.biasConstraint;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"dropout",{get:function get(){return this.cell.dropout;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"recurrentDropout",{get:function get(){return this.cell.recurrentDropout;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"implementation",{get:function get(){return this.cell.implementation;},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={units:this.units,activation:bs(this.activation),useBias:this.useBias,kernelInitializer:as(this.kernelInitializer),recurrentInitializer:as(this.recurrentInitializer),biasInitializer:as(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Ps(this.kernelRegularizer),recurrentRegularizer:Ps(this.recurrentRegularizer),biasRegularizer:Ps(this.biasRegularizer),activityRegularizer:Ps(this.activityRegularizer),kernelConstraint:wi(this.kernelConstraint),recurrentConstraint:wi(this.recurrentConstraint),biasConstraint:wi(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return delete n.cell,Object.assign(t,n),t;},t.fromConfig=function(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t);},t.className="LSTM",t;}(_u);o.SerializationMap.register(Fu);var Bu=function(e){function t(t){var n=e.call(this,t)||this;return n.cells=t.cells,n;}return Cu(t,e),Object.defineProperty(t.prototype,"stateSize",{get:function get(){for(var e=[],t=0,n=this.cells.slice().reverse();t<n.length;t++){var r=n[t];Array.isArray(r.stateSize)?e.push.apply(e,r.stateSize):e.push(r.stateSize);}return e;},enumerable:!0,configurable:!0}),t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){for(var r=(e=e).slice(1),a=[],i=0,o=n.cells.slice().reverse();i<o.length;i++){var s=o[i];Array.isArray(s.stateSize)?a.push(r.splice(0,s.stateSize.length)):a.push(r.splice(0,1));}a.reverse();for(var u,c=[],l=0;l<n.cells.length;++l){s=n.cells[l],r=a[l],u=0===l?[e[0]].concat(r):[u[0]].concat(r),u=s.call(u,t),c.push(u.slice(1));}r=[];for(var f=0,p=c.slice().reverse();f<p.length;f++){var h=p[f];r.push.apply(r,h);}return[u[0]].concat(r);});},t.prototype.build=function(e){var t;na(e)&&(e=e[0]),e=e;for(var n=0,r=this.cells;n<r.length;n++){var a=r[n];a.build(e),t=Array.isArray(a.stateSize)?a.stateSize[0]:a.stateSize,e=[e[0],t];}this.built=!0;},t.prototype.getConfig=function(){for(var t=[],n=0,r=this.cells;n<r.length;n++){var a=r[n];t.push({className:this.getClassName(),config:a.getConfig()});}var i={cells:t},o=e.prototype.getConfig.call(this);return Object.assign(i,o),i;},t.fromConfig=function(e,t,n){void 0===n&&(n={});for(var r=[],a=0,i=t.cells;a<i.length;a++){var o=i[a];r.push(Oi(o,n));}return new e({cells:r});},Object.defineProperty(t.prototype,"trainableWeights",{get:function get(){if(!this.trainable)return[];for(var e=[],t=0,n=this.cells;t<n.length;t++){var r=n[t];e.push.apply(e,r.trainableWeights);}return e;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function get(){for(var e=[],t=0,n=this.cells;t<n.length;t++){var r=n[t];e.push.apply(e,r.nonTrainableWeights);}if(!this.trainable){for(var a=[],i=0,o=this.cells;i<o.length;i++){r=o[i],a.push.apply(a,r.trainableWeights);}return a.concat(e);}return e;},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){for(var e=[],t=0,n=this.cells;t<n.length;t++){var r=n[t];e.push.apply(e,r.weights);}return za(e);},t.prototype.setWeights=function(e){for(var t=[],n=0,r=this.cells;n<r.length;n++){for(var a=r[n],i=a.weights.length,o=e.splice(i),s=0;s<a.weights.length;++s){t.push([a.weights[s],o[s]]);}}Fa(t);},t.className="StackedRNNCells",t;}(Ru);o.SerializationMap.register(Bu);var Vu=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Uu=function(e){function t(t){var n=e.call(this,t)||this;return n.layer=t.layer,n;}return Vu(t,e),t.prototype.build=function(e){this.built=!0;},Object.defineProperty(t.prototype,"trainable",{get:function get(){return null!=this.layer&&this.layer.trainable;},set:function set(e){null!=this.layer&&(this.layer.trainable=e);},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function get(){return this.layer.trainableWeights;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function get(){return this.layer.nonTrainableWeights;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"updates",{get:function get(){return this.layer._updates;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function get(){return this.layer.losses;},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.layer.getWeights();},t.prototype.setWeights=function(e){this.layer.setWeights(e);},t.prototype.getConfig=function(){var t={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.fromConfig=function(e,t,n){void 0===n&&(n={});var r=Oi(t.layer,n);delete t.layer;var a={layer:r};return Object.assign(a,t),new e(a);},t;}(_i),Wu=function(e){function t(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n;}return Vu(t,e),t.prototype.build=function(t){if((t=la(t)).length<3)throw new Kr("TimeDistributed layer expects an input shape >= 3D, but received input shape "+JSON.stringify(t));this.inputSpec=[{shape:t}];var n=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(n),this.layer.built=!0),e.prototype.build.call(this,t);},t.prototype.computeOutputShape=function(e){var t=[(e=la(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),r=e[1];return[n[0],r].concat(n.slice(1));},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){return Pu(function(e,r){return[n.layer.call(e,t),[]];},e=ca(e),[],!1,null,null,!1,e.shape[1])[1];});},t.className="TimeDistributed",t;}(Uu);o.SerializationMap.register(Wu);var Gu=["sum","mul","concat","ave"],qu=function(e){function t(t){var n=e.call(this,t)||this,r=t.layer.getConfig();if(n.forwardLayer=Oi({className:t.layer.getClassName(),config:r}),r.goBackwards=!0!==r.goBackwards,n.backwardLayer=Oi({className:t.layer.getClassName(),config:r}),n.forwardLayer.name="forward_"+n.forwardLayer.name,n.backwardLayer.name="backward_"+n.backwardLayer.name,function(e){da(Gu,"BidirectionalMergeMode",e);}(t.mergeMode),n.mergeMode=t.mergeMode,t.weights)throw new Xr("weights support is not implemented for Bidirectional layer yet.");return n._stateful=t.layer.stateful,n.returnSequences=t.layer.returnSequences,n.returnState=t.layer.returnState,n.supportsMasking=!0,n._trainable=!0,n.inputSpec=t.layer.inputSpec,n;}return Vu(t,e),Object.defineProperty(t.prototype,"trainable",{get:function get(){return this._trainable;},set:function set(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e);},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights());},t.prototype.setWeights=function(e){var t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n));},t.prototype.computeOutputShape=function(e){var t,n,r,a=this.forwardLayer.computeOutputShape(e);return Array.isArray(a)&&Array.isArray(a[0])||(a=[a]),a=a,this.returnState?(r=a.slice(1),t=a[0]):t=a[0],t=t,"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[t].concat(r).concat(r.slice()):ea(n);},t.prototype.apply=function(t,n){var r=null;if(null!=n&&(r=n.initialState),Array.isArray(t)&&(r=t.slice(1),t=t[0]),null==r||0===r.length)return e.prototype.apply.call(this,t,n);throw new Xr("The support for initial states is not implemented for Bidirectional layers yet.");},t.prototype.call=function(e,t){var n=this;return Object(yr.f)(function(){if(null!=t.mask)throw new Xr("The support for masking is not implemented for Bidirectional layers yet.");if(null!=t.initialState)throw new Xr("The support for initial states is not implemented for Bidirectional layers yet.");var r,a,i=n.forwardLayer.call(e,t),o=n.backwardLayer.call(e,t);return n.returnState&&(Array.isArray(i)&&(r=i.slice(1).concat(o.slice(1))),i=i[0],o=o[0]),n.returnSequences&&(o=f.Lb(o,1)),"concat"===n.mergeMode?a=Za([i,o]):"sum"===n.mergeMode?a=f.d(i,o):"ave"===n.mergeMode?a=ni(Ua(.5),f.d(i,o)):"mul"===n.mergeMode?a=f.ib(i,o):null==n.mergeMode&&(a=[i,o]),n.returnState?null==n.mergeMode?a.concat(r):[a].concat(r):a;});},t.prototype.resetStates=function(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates();},t.prototype.build=function(e){var t=this;ci(this.forwardLayer.name,function(){t.forwardLayer.build(e);}),ci(this.backwardLayer.name,function(){t.backwardLayer.build(e);}),this.built=!0;},Object.defineProperty(t.prototype,"trainableWeights",{get:function get(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights);},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function get(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights);},enumerable:!0,configurable:!0}),t.prototype.getConfig=function(){var t={mergeMode:this.mergeMode},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t;},t.fromConfig=function(e,t){var n=Oi(t.layer);if(delete t.layer,null!=t.numConstants)throw new Xr("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");var r=t;return r.layer=n,new e(r);},t.className="Bidirectional",t;}(Uu);o.SerializationMap.register(qu);var Hu=function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t){t.hasOwnProperty(n)&&(e[n]=t[n]);}};return function(t,n){function r(){this.constructor=t;}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());};}(),Ku=function Ku(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},Xu=function Xu(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},Ju=function Ju(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}};var Yu=function(e){function t(t){var n=e.call(this,{inputs:[],outputs:[]})||this;if(t=t||{},n.trainable=!0,n._updatable=!0,n.built=!1,n.name=null!=t.name?t.name:fi("sequential_"),null!=t.layers)for(var r=0,a=t.layers;r<a.length;r++){var i=a[r];n.add(i);}return n;}return Hu(t,e),n=t,t.prototype.add=function(e){if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new Kr("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");var t=Mi({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(t);}if(1!==e.inboundNodes.length)throw new Kr("A layer added to a Sequential model must not already be connected somewhere else. Model received layer "+e.name+" which has "+e.inboundNodes.length+" pre-existing inbound connections.");if(1!==e.inboundNodes[0].outputTensors.length)throw new Kr("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=function e(t,n,r){if((null==n||null!=r&&r>0)&&(n=t.sourceLayer,r=t.nodeIndex),0===n.inboundNodes.length)return[t];var a=n.inboundNodes[r];if(0===a.inboundLayers.length)return a.inputTensors;for(var i=[],o=0;o<a.inboundLayers.length;o++){for(var s=0,u=e(a.inputTensors[o],a.inboundLayers[o],a.nodeIndices[o]);s<u.length;s++){var c=u[s];-1===i.indexOf(c)&&i.push(c);}}return i;}(this.outputs[0]),new Ci({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Qr(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(function(e){return e.shape;}),outputShapes:this.outputs[0].shape});}else{var n=e.apply(this.outputs[0]);if(Array.isArray(n))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.outputs=[n],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape];}this.layers.push(e),this.built=!1;},t.prototype.pop=function(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{var e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape];}},t.prototype.call=function(e,t){return null==this.model&&this.build(),this.model.call(e,t);},t.prototype.build=function(e){if(la(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new zo({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.model.updatable=this.updatable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0;},t.prototype.setWeights=function(e){null==this.model&&this.build(),this.model.setWeights(e);},Object.defineProperty(t.prototype,"updatable",{get:function get(){return this._updatable;},set:function set(e){this.built&&(this.model.updatable=e),this._updatable=e;},enumerable:!0,configurable:!0}),t.prototype.evaluate=function(e,t,n){if(void 0===n&&(n={}),!this.built)throw new Hr("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n);},t.prototype.predict=function(e,t){return void 0===t&&(t={}),null==this.model&&this.build(),this.model.predict(e,t);},t.prototype.predictOnBatch=function(e){return null==this.model&&this.build(),this.model.predictOnBatch(e);},t.prototype.compile=function(e){this.build(),this.model.compile(e),this.optimizer=this.model.optimizer,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames;},t.prototype.fit=function(e,t,n){return void 0===n&&(n={}),Xu(this,void 0,void 0,function(){return Ju(this,function(r){if(!this.built)throw new Hr("The model needs to be compiled before being used.");return[2,this.model.fit(e,t,n)];});});},t.fromConfig=function(e,t){var r=new e({});if(!(r instanceof n))throw new Kr("Sequential.fromConfig called on non-Sequential input: "+r);if(!(t instanceof Array))throw new Kr("Sequential.fromConfig called without an array of configs");if(null==t[0].className||"Merge"===t[0].className)throw new Kr("Legacy serialization format not supported yet.");for(var a=0,i=t;a<i.length;a++){var o=Oi(i[a]);r.add(o);}return r;},t.prototype.getConfig=function(){for(var e=[],t=0,n=this.layers;t<n.length;t++){var r=n[t];e.push({className:r.getClassName(),config:r.getConfig()});}return e;},t.className="Sequential",Ku([Object(qt.a)({heading:"Models",subheading:"Classes"})],t.prototype,"add",null),Ku([Object(qt.a)({heading:"Models",subheading:"Classes",configParamIndices:[2]})],t.prototype,"evaluate",null),Ku([Object(qt.a)({heading:"Models",subheading:"Classes",configParamIndices:[1]})],t.prototype,"predict",null),Ku([Object(qt.a)({heading:"Models",subheading:"Classes",configParamIndices:[2]})],t.prototype,"fit",null),n=Ku([Object(qt.a)({heading:"Models",subheading:"Classes"})],t);var n;}(zo);o.SerializationMap.register(Yu);var Qu=function Qu(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},Zu=function(){function e(){}return e.model=function(e){return new zo(e);},e.sequential=function(e){return new Yu(e);},e.loadModel=function(e){return function(e){return Xu(this,void 0,void 0,function(){var t;return Ju(this,function(n){if("string"==typeof e){if(0===(t=i.getLoadHandlers(e)).length)return[2,function(e){return Xu(this,void 0,void 0,function(){var t;return Ju(this,function(n){switch(n.label){case 0:return[4,fetch(e)];case 1:return[4,n.sent().json()];case 2:if(null==(t=n.sent()).modelTopology)throw new Kr('Missing field "modelTopology" from model JSON at path'+e);if(null==t.weightsManifest)throw new Kr('Missing field "weightsManifest" from model JSON at path'+e);return t.pathPrefix=e.substring(0,e.lastIndexOf("/")),[2,function(e,t){return Xu(this,void 0,void 0,function(){var t,n,r,a,o,s,u,c,l,f;return Ju(this,function(p){switch(p.label){case 0:return null!=(t=e.modelTopology).model_config&&(t=t.model_config),n=Ni(t),r=Oi(n,void 0),null==e.weightsManifest?[3,2]:[4,i.loadWeights(e.weightsManifest,e.pathPrefix,r.weights.map(function(e){return e.originalName;}))];case 1:for(a=p.sent(),o={},s=0,u=r.weights;s<u.length;s++){c=u[s],o[c.originalName]=a[c.originalName];}l=null,f=!0,r.loadWeights(o,l,f),p.label=2;case 2:return[2,r];}});});}(t)];}});});}(e)];if(t.length>1)throw new Kr("Found more than one ("+t.length+") load handlers for URL '"+e+"'");e=t[0];}return[2,function(e,t){return Xu(this,void 0,void 0,function(){var t,n,r,a;return Ju(this,function(o){switch(o.label){case 0:if(null==e.load)throw new Kr("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,e.load()];case 1:if(t=o.sent(),n=Oi(Ni(t.modelTopology),void 0),null!=t.weightData){if(null==t.weightSpecs)throw new Kr("Model artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");r=!1,a=!0,n.loadWeights(i.decodeWeights(t.weightData,t.weightSpecs),r,a);}return[2,n];}});});}(e)];});});}(e);},e.input=function(e){return Mi(e);},Qu([Object(qt.a)({heading:"Models",subheading:"Creation",configParamIndices:[0]})],e,"model",null),Qu([Object(qt.a)({heading:"Models",subheading:"Creation",configParamIndices:[0]})],e,"sequential",null),Qu([Object(qt.a)({heading:"Models",subheading:"Loading",useDocsFrom:"loadModelInternal"})],e,"loadModel",null),Qu([Object(qt.a)({heading:"Models",subheading:"Inputs",useDocsFrom:"Input",configParamIndices:[0]})],e,"input",null),e;}(),$u=function(){function e(){}return e.inputLayer=function(e){return new Ri(e);},e.elu=function(e){return new Ss(e);},e.leakyReLU=function(e){return new Os(e);},e.softmax=function(e){return new Es(e);},e.thresholdedReLU=function(e){return new Ns(e);},e.conv1d=function(e){return new Ws(e);},e.conv2d=function(e){return new Bs(e);},e.conv2dTranspose=function(e){return new Vs(e);},e.separableConv2d=function(e){return new Us(e);},e.cropping2D=function(e){return new Gs(e);},e.upSampling2d=function(e){return new qs(e);},e.depthwiseConv2d=function(e){return new Ks(e);},e.activation=function(e){return new Zs(e);},e.dense=function(e){return new Ys(e);},e.dropout=function(e){return new Js(e);},e.flatten=function(e){return new Qs(e);},e.repeatVector=function(e){return new $s(e);},e.reshape=function(e){return new eu(e);},e.embedding=function(e){return new nu(e);},e.add=function(e){return new iu(e);},e.average=function(e){return new su(e);},e.concatenate=function(e){return new lu(e);},e.maximum=function(e){return new uu(e);},e.minimum=function(e){return new cu(e);},e.multiply=function(e){return new ou(e);},e.batchNormalization=function(e){return new hu(e);},e.zeroPadding2d=function(e){return new mu(e);},e.averagePooling1d=function(e){return new wu(e);},e.avgPool1d=function(t){return e.averagePooling1d(t);},e.avgPooling1d=function(t){return e.averagePooling1d(t);},e.averagePooling2d=function(e){return new Ou(e);},e.avgPool2d=function(t){return e.averagePooling2d(t);},e.avgPooling2d=function(t){return e.averagePooling2d(t);},e.globalAveragePooling1d=function(e){return new Nu(e);},e.globalAveragePooling2d=function(e){return new Tu(e);},e.globalMaxPooling1d=function(e){return new Eu(e);},e.globalMaxPooling2d=function(e){return new Au(e);},e.maxPooling1d=function(e){return new bu(e);},e.maxPooling2d=function(e){return new ku(e);},e.gru=function(e){return new Lu(e);},e.gruCell=function(e){return new Du(e);},e.lstm=function(e){return new Fu(e);},e.lstmCell=function(e){return new zu(e);},e.simpleRNN=function(e){return new ju(e);},e.simpleRNNCell=function(e){return new Mu(e);},e.rnn=function(e){return new _u(e);},e.stackedRNNCells=function(e){return new Bu(e);},e.bidirectional=function(e){return new qu(e);},e.timeDistributed=function(e){return new Wu(e);},e.Layer=_i,e.RNN=_u,e.RNNCell=Ru,e.input=Zu.input,Qu([Object(qt.a)({heading:"Layers",subheading:"Inputs",namespace:"layers",useDocsFrom:"InputLayer",configParamIndices:[0]})],e,"inputLayer",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Advanced Activation",namespace:"layers",useDocsFrom:"ELU",configParamIndices:[0]})],e,"elu",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Advanced Activation",namespace:"layers",useDocsFrom:"LeakyReLU",configParamIndices:[0]})],e,"leakyReLU",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Advanced Activation",namespace:"layers",useDocsFrom:"Softmax",configParamIndices:[0]})],e,"softmax",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Advanced Activation",namespace:"layers",useDocsFrom:"ThresholdedReLU",configParamIndices:[0]})],e,"thresholdedReLU",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Convolutional",namespace:"layers",useDocsFrom:"Conv1D",configParamIndices:[0]})],e,"conv1d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Convolutional",namespace:"layers",useDocsFrom:"Conv2D",configParamIndices:[0]})],e,"conv2d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Convolutional",namespace:"layers",useDocsFrom:"Conv2DTranspose",configParamIndices:[0]})],e,"conv2dTranspose",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Convolutional",namespace:"layers",useDocsFrom:"SeparableConv2D",configParamIndices:[0]})],e,"separableConv2d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Convolutional",namespace:"layers",useDocsFrom:"Cropping2D",configParamIndices:[0]})],e,"cropping2D",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Convolutional",namespace:"layers",useDocsFrom:"UpSampling2D",configParamIndices:[0]})],e,"upSampling2d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Convolutional",namespace:"layers",useDocsFrom:"DepthwiseConv2D",configParamIndices:[0]})],e,"depthwiseConv2d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Basic",namespace:"layers",useDocsFrom:"Activation",configParamIndices:[0]})],e,"activation",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Basic",namespace:"layers",useDocsFrom:"Dense",configParamIndices:[0]})],e,"dense",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Basic",namespace:"layers",useDocsFrom:"Dropout",configParamIndices:[0]})],e,"dropout",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Basic",namespace:"layers",useDocsFrom:"Flatten",configParamIndices:[0]})],e,"flatten",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Basic",namespace:"layers",useDocsFrom:"RepeatVector",configParamIndices:[0]})],e,"repeatVector",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Basic",namespace:"layers",useDocsFrom:"Reshape",configParamIndices:[0]})],e,"reshape",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Basic",namespace:"layers",useDocsFrom:"Embedding",configParamIndices:[0]})],e,"embedding",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Merge",namespace:"layers",useDocsFrom:"Add",configParamIndices:[0]})],e,"add",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Merge",namespace:"layers",useDocsFrom:"Average",configParamIndices:[0]})],e,"average",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Merge",namespace:"layers",useDocsFrom:"Concatenate",configParamIndices:[0]})],e,"concatenate",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Merge",namespace:"layers",useDocsFrom:"Maximum",configParamIndices:[0]})],e,"maximum",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Merge",namespace:"layers",useDocsFrom:"Minimum",configParamIndices:[0]})],e,"minimum",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Merge",namespace:"layers",useDocsFrom:"Multiply",configParamIndices:[0]})],e,"multiply",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Normalization",namespace:"layers",useDocsFrom:"BatchNormalization",configParamIndices:[0]})],e,"batchNormalization",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Padding",namespace:"layers",useDocsFrom:"ZeroPadding2D",configParamIndices:[0]})],e,"zeroPadding2d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Pooling",namespace:"layers",useDocsFrom:"AveragePooling1D",configParamIndices:[0]})],e,"averagePooling1d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Pooling",namespace:"layers",useDocsFrom:"AveragePooling2D",configParamIndices:[0]})],e,"averagePooling2d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Pooling",namespace:"layers",useDocsFrom:"GlobalAveragePooling1D",configParamIndices:[0]})],e,"globalAveragePooling1d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Pooling",namespace:"layers",useDocsFrom:"GlobalAveragePooling2D",configParamIndices:[0]})],e,"globalAveragePooling2d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Pooling",namespace:"layers",useDocsFrom:"GlobalMaxPooling1D",configParamIndices:[0]})],e,"globalMaxPooling1d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Pooling",namespace:"layers",useDocsFrom:"GlobalMaxPooling2D",configParamIndices:[0]})],e,"globalMaxPooling2d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Pooling",namespace:"layers",useDocsFrom:"MaxPooling1D",configParamIndices:[0]})],e,"maxPooling1d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Pooling",namespace:"layers",useDocsFrom:"MaxPooling2D",configParamIndices:[0]})],e,"maxPooling2d",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Recurrent",namespace:"layers",useDocsFrom:"GRU",configParamIndices:[0]})],e,"gru",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Recurrent",namespace:"layers",useDocsFrom:"GRUCell",configParamIndices:[0]})],e,"gruCell",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Recurrent",namespace:"layers",useDocsFrom:"LSTM",configParamIndices:[0]})],e,"lstm",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Recurrent",namespace:"layers",useDocsFrom:"LSTMCell",configParamIndices:[0]})],e,"lstmCell",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Recurrent",namespace:"layers",useDocsFrom:"SimpleRNN",configParamIndices:[0]})],e,"simpleRNN",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Recurrent",namespace:"layers",useDocsFrom:"SimpleRNNCell",configParamIndices:[0]})],e,"simpleRNNCell",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Recurrent",namespace:"layers",useDocsFrom:"RNN",configParamIndices:[0]})],e,"rnn",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Recurrent",namespace:"layers",useDocsFrom:"RNN",configParamIndices:[0]})],e,"stackedRNNCells",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Wrapper",namespace:"layers",useDocsFrom:"Bidirectional",configParamIndices:[0]})],e,"bidirectional",null),Qu([Object(qt.a)({heading:"Layers",subheading:"Wrapper",namespace:"layers",useDocsFrom:"TimeDistributed",configParamIndices:[0]})],e,"timeDistributed",null),e;}(),ec=function(){function e(){}return e.maxNorm=function(e){return new mi(e);},e.unitNorm=function(e){return new gi(e);},e.nonNeg=function(){return new yi();},e.minMaxNorm=function(e){return new vi(e);},Qu([Object(qt.a)({heading:"Constraints",namespace:"constraints",useDocsFrom:"MaxNorm",configParamIndices:[0]})],e,"maxNorm",null),Qu([Object(qt.a)({heading:"Constraints",namespace:"constraints",useDocsFrom:"UnitNorm",configParamIndices:[0]})],e,"unitNorm",null),Qu([Object(qt.a)({heading:"Constraints",namespace:"constraints",useDocsFrom:"NonNeg"})],e,"nonNeg",null),Qu([Object(qt.a)({heading:"Constraints",namespace:"constraints",useDocsFrom:"MinMaxNormConfig",configParamIndices:[0]})],e,"minMaxNorm",null),e;}(),tc=function(){function e(){}return e.zeros=function(){return new Wo();},e.ones=function(){return new Go();},e.constant=function(e){return new qo(e);},e.randomUniform=function(e){return new Ho(e);},e.randomNormal=function(e){return new Ko(e);},e.truncatedNormal=function(e){return new Xo(e);},e.identity=function(e){return new Jo(e);},e.varianceScaling=function(e){return new Yo(e);},e.glorotUniform=function(e){return new Qo(e);},e.glorotNormal=function(e){return new Zo(e);},e.heNormal=function(e){return new $o(e);},e.leCunNormal=function(e){return new es(e);},e.orthogonal=function(e){return new ts(e);},Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"Zeros"})],e,"zeros",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"Ones"})],e,"ones",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"Constant",configParamIndices:[0]})],e,"constant",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"RandomUniform",configParamIndices:[0]})],e,"randomUniform",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"RandomNormal",configParamIndices:[0]})],e,"randomNormal",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"TruncatedNormal",configParamIndices:[0]})],e,"truncatedNormal",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"Identity",configParamIndices:[0]})],e,"identity",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"VarianceScaling",configParamIndices:[0]})],e,"varianceScaling",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"GlorotUniform",configParamIndices:[0]})],e,"glorotUniform",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"GlorotNormal",configParamIndices:[0]})],e,"glorotNormal",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"HeNormal",configParamIndices:[0]})],e,"heNormal",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"LeCunNormal",configParamIndices:[0]})],e,"leCunNormal",null),Qu([Object(qt.a)({heading:"Initializers",namespace:"initializers",useDocsFrom:"Orthogonal",configParamIndices:[0]})],e,"orthogonal",null),e;}(),nc=function(){function e(){}return e.binaryAccuracy=function(e,t){return co(e,t);},e.binaryCrossentropy=function(e,t){return fo(e,t);},e.categoricalAccuracy=function(e,t){return lo(e,t);},e.categoricalCrossentropy=function(e,t){return no(e,t);},e.cosineProximity=function(e,t){return so(e,t);},e.prototype.meanAbsoluteError=function(e,t){return Ji(e,t);},e.prototype.meanAbsolutePercentageError=function(e,t){return Yi(e,t);},e.prototype.MAPE=function(e,t){return Yi(e,t);},e.prototype.mape=function(e,t){return Yi(e,t);},e.meanSquaredError=function(e,t){return Xi(e,t);},e.MSE=function(e,t){return Xi(e,t);},e.mse=function(e,t){return Xi(e,t);},Qu([Object(qt.a)({heading:"Metrics",namespace:"metrics",useDocsFrom:"meanAbsoluteError"})],e.prototype,"meanAbsoluteError",null),Qu([Object(qt.a)({heading:"Metrics",namespace:"metrics",useDocsFrom:"meanAbsolutePercentageError"})],e.prototype,"meanAbsolutePercentageError",null),Qu([Object(qt.a)({heading:"Metrics",namespace:"metrics",useDocsFrom:"binaryAccuracy"})],e,"binaryAccuracy",null),Qu([Object(qt.a)({heading:"Metrics",namespace:"metrics",useDocsFrom:"binaryCrossentropy"})],e,"binaryCrossentropy",null),Qu([Object(qt.a)({heading:"Metrics",namespace:"metrics",useDocsFrom:"categoricalAccuracy"})],e,"categoricalAccuracy",null),Qu([Object(qt.a)({heading:"Metrics",namespace:"metrics",useDocsFrom:"categoricalCrossentropy"})],e,"categoricalCrossentropy",null),Qu([Object(qt.a)({heading:"Metrics",namespace:"metrics",useDocsFrom:"cosineProximity"})],e,"cosineProximity",null),Qu([Object(qt.a)({heading:"Metrics",namespace:"metrics",useDocsFrom:"meanSquaredError"})],e,"meanSquaredError",null),e;}(),rc=function(){function e(){}return e.l1l2=function(e){return new As(e);},e.l1=function(e){return function(e){return new As({l1:null!=e?e.l1:null,l2:0});}(e);},e.l2=function(e){return function(e){return new As({l2:null!=e?e.l2:null,l1:0});}(e);},Qu([Object(qt.a)({heading:"Regularizers",namespace:"regularizers",useDocsFrom:"L1L2"})],e,"l1l2",null),Qu([Object(qt.a)({heading:"Regularizers",namespace:"regularizers",useDocsFrom:"L1L2"})],e,"l1",null),Qu([Object(qt.a)({heading:"Regularizers",namespace:"regularizers",useDocsFrom:"L1L2"})],e,"l2",null),e;}(),ac=Zu.model,ic=Zu.sequential,oc=Zu.loadModel,sc=Zu.input,uc=$u,cc=ec,lc=tc,fc=nc,pc=rc,hc=n(171),dc=n(102);var mc=dc.Reader,gc=dc.util,yc=dc.roots.default||(dc.roots.default={}),vc=yc.tensorflow=function(){var e={};return e.Any=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.typeUrl="",e.prototype.value=gc.newBuffer([]),e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.Any();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.typeUrl=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&a);}}return r;},e;}(),e.DataType=function(){var e={},t=Object.create(e);return t[e[0]="DT_INVALID"]=0,t[e[1]="DT_FLOAT"]=1,t[e[2]="DT_DOUBLE"]=2,t[e[3]="DT_INT32"]=3,t[e[4]="DT_UINT8"]=4,t[e[5]="DT_INT16"]=5,t[e[6]="DT_INT8"]=6,t[e[7]="DT_STRING"]=7,t[e[8]="DT_COMPLEX64"]=8,t[e[9]="DT_INT64"]=9,t[e[10]="DT_BOOL"]=10,t[e[11]="DT_QINT8"]=11,t[e[12]="DT_QUINT8"]=12,t[e[13]="DT_QINT32"]=13,t[e[14]="DT_BFLOAT16"]=14,t[e[101]="DT_FLOAT_REF"]=101,t[e[102]="DT_DOUBLE_REF"]=102,t[e[103]="DT_INT32_REF"]=103,t[e[104]="DT_UINT8_REF"]=104,t[e[105]="DT_INT16_REF"]=105,t[e[106]="DT_INT8_REF"]=106,t[e[107]="DT_STRING_REF"]=107,t[e[108]="DT_COMPLEX64_REF"]=108,t[e[109]="DT_INT64_REF"]=109,t[e[110]="DT_BOOL_REF"]=110,t[e[111]="DT_QINT8_REF"]=111,t[e[112]="DT_QUINT8_REF"]=112,t[e[113]="DT_QINT32_REF"]=113,t[e[114]="DT_BFLOAT16_REF"]=114,t;}(),e.TensorShape=function(){function e(e){if(this.dim=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.dim=gc.emptyArray,e.prototype.unknownRank=!1,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.TensorShape();e.pos<n;){var a=e.uint32();switch(a>>>3){case 2:r.dim&&r.dim.length||(r.dim=[]),r.dim.push(yc.tensorflow.TensorShape.Dim.decode(e,e.uint32()));break;case 3:r.unknownRank=e.bool();break;default:e.skipType(7&a);}}return r;},e.Dim=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.size=gc.Long?gc.Long.fromBits(0,0,!1):0,e.prototype.name="",e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.TensorShape.Dim();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.size=e.int64();break;case 2:r.name=e.string();break;default:e.skipType(7&a);}}return r;},e;}(),e;}(),e.Tensor=function(){function e(e){if(this.floatVal=[],this.doubleVal=[],this.intVal=[],this.stringVal=[],this.scomplexVal=[],this.int64Val=[],this.boolVal=[],this.uint32Val=[],this.uint64Val=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.dtype=0,e.prototype.tensorShape=null,e.prototype.versionNumber=0,e.prototype.tensorContent=gc.newBuffer([]),e.prototype.floatVal=gc.emptyArray,e.prototype.doubleVal=gc.emptyArray,e.prototype.intVal=gc.emptyArray,e.prototype.stringVal=gc.emptyArray,e.prototype.scomplexVal=gc.emptyArray,e.prototype.int64Val=gc.emptyArray,e.prototype.boolVal=gc.emptyArray,e.prototype.uint32Val=gc.emptyArray,e.prototype.uint64Val=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.Tensor();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.dtype=e.int32();break;case 2:r.tensorShape=yc.tensorflow.TensorShape.decode(e,e.uint32());break;case 3:r.versionNumber=e.int32();break;case 4:r.tensorContent=e.bytes();break;case 5:if(r.floatVal&&r.floatVal.length||(r.floatVal=[]),2==(7&a))for(var i=e.uint32()+e.pos;e.pos<i;){r.floatVal.push(e.float());}else r.floatVal.push(e.float());break;case 6:if(r.doubleVal&&r.doubleVal.length||(r.doubleVal=[]),2==(7&a))for(i=e.uint32()+e.pos;e.pos<i;){r.doubleVal.push(e.double());}else r.doubleVal.push(e.double());break;case 7:if(r.intVal&&r.intVal.length||(r.intVal=[]),2==(7&a))for(i=e.uint32()+e.pos;e.pos<i;){r.intVal.push(e.int32());}else r.intVal.push(e.int32());break;case 8:r.stringVal&&r.stringVal.length||(r.stringVal=[]),r.stringVal.push(e.bytes());break;case 9:if(r.scomplexVal&&r.scomplexVal.length||(r.scomplexVal=[]),2==(7&a))for(i=e.uint32()+e.pos;e.pos<i;){r.scomplexVal.push(e.float());}else r.scomplexVal.push(e.float());break;case 10:if(r.int64Val&&r.int64Val.length||(r.int64Val=[]),2==(7&a))for(i=e.uint32()+e.pos;e.pos<i;){r.int64Val.push(e.int64());}else r.int64Val.push(e.int64());break;case 11:if(r.boolVal&&r.boolVal.length||(r.boolVal=[]),2==(7&a))for(i=e.uint32()+e.pos;e.pos<i;){r.boolVal.push(e.bool());}else r.boolVal.push(e.bool());break;case 16:if(r.uint32Val&&r.uint32Val.length||(r.uint32Val=[]),2==(7&a))for(i=e.uint32()+e.pos;e.pos<i;){r.uint32Val.push(e.uint32());}else r.uint32Val.push(e.uint32());break;case 17:if(r.uint64Val&&r.uint64Val.length||(r.uint64Val=[]),2==(7&a))for(i=e.uint32()+e.pos;e.pos<i;){r.uint64Val.push(e.uint64());}else r.uint64Val.push(e.uint64());break;default:e.skipType(7&a);}}return r;},e;}(),e.AttrValue=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}var t=void 0;return e.prototype.list=null,e.prototype.s=gc.newBuffer([]),e.prototype.i=gc.Long?gc.Long.fromBits(0,0,!1):0,e.prototype.f=0,e.prototype.b=!1,e.prototype.type=0,e.prototype.shape=null,e.prototype.tensor=null,e.prototype.placeholder="",e.prototype.func=null,Object.defineProperty(e.prototype,"value",{get:gc.oneOfGetter(t=["list","s","i","f","b","type","shape","tensor","placeholder","func"]),set:gc.oneOfSetter(t)}),e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.AttrValue();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.list=yc.tensorflow.AttrValue.ListValue.decode(e,e.uint32());break;case 2:r.s=e.bytes();break;case 3:r.i=e.int64();break;case 4:r.f=e.float();break;case 5:r.b=e.bool();break;case 6:r.type=e.int32();break;case 7:r.shape=yc.tensorflow.TensorShape.decode(e,e.uint32());break;case 8:r.tensor=yc.tensorflow.Tensor.decode(e,e.uint32());break;case 9:r.placeholder=e.string();break;case 10:r.func=yc.tensorflow.NameAttrList.decode(e,e.uint32());break;default:e.skipType(7&a);}}return r;},e.ListValue=function(){function e(e){if(this.s=[],this.i=[],this.f=[],this.b=[],this.type=[],this.shape=[],this.tensor=[],this.func=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.s=gc.emptyArray,e.prototype.i=gc.emptyArray,e.prototype.f=gc.emptyArray,e.prototype.b=gc.emptyArray,e.prototype.type=gc.emptyArray,e.prototype.shape=gc.emptyArray,e.prototype.tensor=gc.emptyArray,e.prototype.func=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.AttrValue.ListValue();e.pos<n;){var a=e.uint32();switch(a>>>3){case 2:r.s&&r.s.length||(r.s=[]),r.s.push(e.bytes());break;case 3:if(r.i&&r.i.length||(r.i=[]),2==(7&a))for(var i=e.uint32()+e.pos;e.pos<i;){r.i.push(e.int64());}else r.i.push(e.int64());break;case 4:if(r.f&&r.f.length||(r.f=[]),2==(7&a))for(i=e.uint32()+e.pos;e.pos<i;){r.f.push(e.float());}else r.f.push(e.float());break;case 5:if(r.b&&r.b.length||(r.b=[]),2==(7&a))for(i=e.uint32()+e.pos;e.pos<i;){r.b.push(e.bool());}else r.b.push(e.bool());break;case 6:if(r.type&&r.type.length||(r.type=[]),2==(7&a))for(i=e.uint32()+e.pos;e.pos<i;){r.type.push(e.int32());}else r.type.push(e.int32());break;case 7:r.shape&&r.shape.length||(r.shape=[]),r.shape.push(yc.tensorflow.TensorShape.decode(e,e.uint32()));break;case 8:r.tensor&&r.tensor.length||(r.tensor=[]),r.tensor.push(yc.tensorflow.Tensor.decode(e,e.uint32()));break;case 9:r.func&&r.func.length||(r.func=[]),r.func.push(yc.tensorflow.NameAttrList.decode(e,e.uint32()));break;default:e.skipType(7&a);}}return r;},e;}(),e;}(),e.NameAttrList=function(){function e(e){if(this.attr={},e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.name="",e.prototype.attr=gc.emptyObject,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n,r=void 0===t?e.len:e.pos+t,a=new yc.tensorflow.NameAttrList();e.pos<r;){var i=e.uint32();switch(i>>>3){case 1:a.name=e.string();break;case 2:e.skip().pos++,a.attr===gc.emptyObject&&(a.attr={}),n=e.string(),e.pos++,a.attr[n]=yc.tensorflow.AttrValue.decode(e,e.uint32());break;default:e.skipType(7&i);}}return a;},e;}(),e.NodeDef=function(){function e(e){if(this.input=[],this.attr={},e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.name="",e.prototype.op="",e.prototype.input=gc.emptyArray,e.prototype.device="",e.prototype.attr=gc.emptyObject,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n,r=void 0===t?e.len:e.pos+t,a=new yc.tensorflow.NodeDef();e.pos<r;){var i=e.uint32();switch(i>>>3){case 1:a.name=e.string();break;case 2:a.op=e.string();break;case 3:a.input&&a.input.length||(a.input=[]),a.input.push(e.string());break;case 4:a.device=e.string();break;case 5:e.skip().pos++,a.attr===gc.emptyObject&&(a.attr={}),n=e.string(),e.pos++,a.attr[n]=yc.tensorflow.AttrValue.decode(e,e.uint32());break;default:e.skipType(7&i);}}return a;},e;}(),e.VersionDef=function(){function e(e){if(this.badConsumers=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.producer=0,e.prototype.minConsumer=0,e.prototype.badConsumers=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.VersionDef();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.producer=e.int32();break;case 2:r.minConsumer=e.int32();break;case 3:if(r.badConsumers&&r.badConsumers.length||(r.badConsumers=[]),2==(7&a))for(var i=e.uint32()+e.pos;e.pos<i;){r.badConsumers.push(e.int32());}else r.badConsumers.push(e.int32());break;default:e.skipType(7&a);}}return r;},e;}(),e.GraphDef=function(){function e(e){if(this.node=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.node=gc.emptyArray,e.prototype.versions=null,e.prototype.library=null,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.GraphDef();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.node&&r.node.length||(r.node=[]),r.node.push(yc.tensorflow.NodeDef.decode(e,e.uint32()));break;case 4:r.versions=yc.tensorflow.VersionDef.decode(e,e.uint32());break;case 2:r.library=yc.tensorflow.FunctionDefLibrary.decode(e,e.uint32());break;default:e.skipType(7&a);}}return r;},e;}(),e.CollectionDef=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}var t=void 0;return e.prototype.nodeList=null,e.prototype.bytesList=null,e.prototype.int64List=null,e.prototype.floatList=null,e.prototype.anyList=null,Object.defineProperty(e.prototype,"kind",{get:gc.oneOfGetter(t=["nodeList","bytesList","int64List","floatList","anyList"]),set:gc.oneOfSetter(t)}),e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.CollectionDef();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.nodeList=yc.tensorflow.CollectionDef.NodeList.decode(e,e.uint32());break;case 2:r.bytesList=yc.tensorflow.CollectionDef.BytesList.decode(e,e.uint32());break;case 3:r.int64List=yc.tensorflow.CollectionDef.Int64List.decode(e,e.uint32());break;case 4:r.floatList=yc.tensorflow.CollectionDef.FloatList.decode(e,e.uint32());break;case 5:r.anyList=yc.tensorflow.CollectionDef.AnyList.decode(e,e.uint32());break;default:e.skipType(7&a);}}return r;},e.NodeList=function(){function e(e){if(this.value=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.value=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.CollectionDef.NodeList();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.value&&r.value.length||(r.value=[]),r.value.push(e.string());break;default:e.skipType(7&a);}}return r;},e;}(),e.BytesList=function(){function e(e){if(this.value=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.value=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.CollectionDef.BytesList();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.value&&r.value.length||(r.value=[]),r.value.push(e.bytes());break;default:e.skipType(7&a);}}return r;},e;}(),e.Int64List=function(){function e(e){if(this.value=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.value=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.CollectionDef.Int64List();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:if(r.value&&r.value.length||(r.value=[]),2==(7&a))for(var i=e.uint32()+e.pos;e.pos<i;){r.value.push(e.int64());}else r.value.push(e.int64());break;default:e.skipType(7&a);}}return r;},e;}(),e.FloatList=function(){function e(e){if(this.value=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.value=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.CollectionDef.FloatList();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:if(r.value&&r.value.length||(r.value=[]),2==(7&a))for(var i=e.uint32()+e.pos;e.pos<i;){r.value.push(e.float());}else r.value.push(e.float());break;default:e.skipType(7&a);}}return r;},e;}(),e.AnyList=function(){function e(e){if(this.value=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.value=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.CollectionDef.AnyList();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.value&&r.value.length||(r.value=[]),r.value.push(yc.tensorflow.Any.decode(e,e.uint32()));break;default:e.skipType(7&a);}}return r;},e;}(),e;}(),e.SaverDef=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.filenameTensorName="",e.prototype.saveTensorName="",e.prototype.restoreOpName="",e.prototype.maxToKeep=0,e.prototype.sharded=!1,e.prototype.keepCheckpointEveryNHours=0,e.prototype.version=0,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.SaverDef();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.filenameTensorName=e.string();break;case 2:r.saveTensorName=e.string();break;case 3:r.restoreOpName=e.string();break;case 4:r.maxToKeep=e.int32();break;case 5:r.sharded=e.bool();break;case 6:r.keepCheckpointEveryNHours=e.float();break;case 7:r.version=e.int32();break;default:e.skipType(7&a);}}return r;},e.CheckpointFormatVersion=function(){var e={},t=Object.create(e);return t[e[0]="LEGACY"]=0,t[e[1]="V1"]=1,t[e[2]="V2"]=2,t;}(),e;}(),e.TensorInfo=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}var t=void 0;return e.prototype.name="",e.prototype.cooSparse=null,e.prototype.dtype=0,e.prototype.tensorShape=null,Object.defineProperty(e.prototype,"encoding",{get:gc.oneOfGetter(t=["name","cooSparse"]),set:gc.oneOfSetter(t)}),e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.TensorInfo();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 4:r.cooSparse=yc.tensorflow.TensorInfo.CooSparse.decode(e,e.uint32());break;case 2:r.dtype=e.int32();break;case 3:r.tensorShape=yc.tensorflow.TensorShape.decode(e,e.uint32());break;default:e.skipType(7&a);}}return r;},e.CooSparse=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.valuesTensorName="",e.prototype.indicesTensorName="",e.prototype.denseShapeTensorName="",e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.TensorInfo.CooSparse();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.valuesTensorName=e.string();break;case 2:r.indicesTensorName=e.string();break;case 3:r.denseShapeTensorName=e.string();break;default:e.skipType(7&a);}}return r;},e;}(),e;}(),e.SignatureDef=function(){function e(e){if(this.inputs={},this.outputs={},e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.inputs=gc.emptyObject,e.prototype.outputs=gc.emptyObject,e.prototype.methodName="",e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n,r=void 0===t?e.len:e.pos+t,a=new yc.tensorflow.SignatureDef();e.pos<r;){var i=e.uint32();switch(i>>>3){case 1:e.skip().pos++,a.inputs===gc.emptyObject&&(a.inputs={}),n=e.string(),e.pos++,a.inputs[n]=yc.tensorflow.TensorInfo.decode(e,e.uint32());break;case 2:e.skip().pos++,a.outputs===gc.emptyObject&&(a.outputs={}),n=e.string(),e.pos++,a.outputs[n]=yc.tensorflow.TensorInfo.decode(e,e.uint32());break;case 3:a.methodName=e.string();break;default:e.skipType(7&i);}}return a;},e;}(),e.AssetFileDef=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.tensorInfo=null,e.prototype.filename="",e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.AssetFileDef();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.tensorInfo=yc.tensorflow.TensorInfo.decode(e,e.uint32());break;case 2:r.filename=e.string();break;default:e.skipType(7&a);}}return r;},e;}(),e.OpDef=function(){function e(e){if(this.inputArg=[],this.outputArg=[],this.attr=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.name="",e.prototype.inputArg=gc.emptyArray,e.prototype.outputArg=gc.emptyArray,e.prototype.attr=gc.emptyArray,e.prototype.deprecation=null,e.prototype.summary="",e.prototype.description="",e.prototype.isCommutative=!1,e.prototype.isAggregate=!1,e.prototype.isStateful=!1,e.prototype.allowsUninitializedInput=!1,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.OpDef();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 2:r.inputArg&&r.inputArg.length||(r.inputArg=[]),r.inputArg.push(yc.tensorflow.OpDef.ArgDef.decode(e,e.uint32()));break;case 3:r.outputArg&&r.outputArg.length||(r.outputArg=[]),r.outputArg.push(yc.tensorflow.OpDef.ArgDef.decode(e,e.uint32()));break;case 4:r.attr&&r.attr.length||(r.attr=[]),r.attr.push(yc.tensorflow.OpDef.AttrDef.decode(e,e.uint32()));break;case 8:r.deprecation=yc.tensorflow.OpDef.OpDeprecation.decode(e,e.uint32());break;case 5:r.summary=e.string();break;case 6:r.description=e.string();break;case 18:r.isCommutative=e.bool();break;case 16:r.isAggregate=e.bool();break;case 17:r.isStateful=e.bool();break;case 19:r.allowsUninitializedInput=e.bool();break;default:e.skipType(7&a);}}return r;},e.ArgDef=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.name="",e.prototype.description="",e.prototype.type=0,e.prototype.typeAttr="",e.prototype.numberAttr="",e.prototype.typeListAttr="",e.prototype.isRef=!1,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.OpDef.ArgDef();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 2:r.description=e.string();break;case 3:r.type=e.int32();break;case 4:r.typeAttr=e.string();break;case 5:r.numberAttr=e.string();break;case 6:r.typeListAttr=e.string();break;case 16:r.isRef=e.bool();break;default:e.skipType(7&a);}}return r;},e;}(),e.AttrDef=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.name="",e.prototype.type="",e.prototype.defaultValue=null,e.prototype.description="",e.prototype.hasMinimum=!1,e.prototype.minimum=gc.Long?gc.Long.fromBits(0,0,!1):0,e.prototype.allowedValues=null,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.OpDef.AttrDef();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.name=e.string();break;case 2:r.type=e.string();break;case 3:r.defaultValue=yc.tensorflow.AttrValue.decode(e,e.uint32());break;case 4:r.description=e.string();break;case 5:r.hasMinimum=e.bool();break;case 6:r.minimum=e.int64();break;case 7:r.allowedValues=yc.tensorflow.AttrValue.decode(e,e.uint32());break;default:e.skipType(7&a);}}return r;},e;}(),e.OpDeprecation=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.version=0,e.prototype.explanation="",e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.OpDef.OpDeprecation();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.version=e.int32();break;case 2:r.explanation=e.string();break;default:e.skipType(7&a);}}return r;},e;}(),e;}(),e.OpList=function(){function e(e){if(this.op=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.op=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.OpList();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.op&&r.op.length||(r.op=[]),r.op.push(yc.tensorflow.OpDef.decode(e,e.uint32()));break;default:e.skipType(7&a);}}return r;},e;}(),e.MetaGraphDef=function(){function e(e){if(this.collectionDef={},this.signatureDef={},this.assetFileDef=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.metaInfoDef=null,e.prototype.graphDef=null,e.prototype.saverDef=null,e.prototype.collectionDef=gc.emptyObject,e.prototype.signatureDef=gc.emptyObject,e.prototype.assetFileDef=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n,r=void 0===t?e.len:e.pos+t,a=new yc.tensorflow.MetaGraphDef();e.pos<r;){var i=e.uint32();switch(i>>>3){case 1:a.metaInfoDef=yc.tensorflow.MetaGraphDef.MetaInfoDef.decode(e,e.uint32());break;case 2:a.graphDef=yc.tensorflow.GraphDef.decode(e,e.uint32());break;case 3:a.saverDef=yc.tensorflow.SaverDef.decode(e,e.uint32());break;case 4:e.skip().pos++,a.collectionDef===gc.emptyObject&&(a.collectionDef={}),n=e.string(),e.pos++,a.collectionDef[n]=yc.tensorflow.CollectionDef.decode(e,e.uint32());break;case 5:e.skip().pos++,a.signatureDef===gc.emptyObject&&(a.signatureDef={}),n=e.string(),e.pos++,a.signatureDef[n]=yc.tensorflow.SignatureDef.decode(e,e.uint32());break;case 6:a.assetFileDef&&a.assetFileDef.length||(a.assetFileDef=[]),a.assetFileDef.push(yc.tensorflow.AssetFileDef.decode(e,e.uint32()));break;default:e.skipType(7&i);}}return a;},e.MetaInfoDef=function(){function e(e){if(this.tags=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.metaGraphVersion="",e.prototype.strippedOpList=null,e.prototype.anyInfo=null,e.prototype.tags=gc.emptyArray,e.prototype.tensorflowVersion="",e.prototype.tensorflowGitVersion="",e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.MetaGraphDef.MetaInfoDef();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.metaGraphVersion=e.string();break;case 2:r.strippedOpList=yc.tensorflow.OpList.decode(e,e.uint32());break;case 3:r.anyInfo=yc.tensorflow.Any.decode(e,e.uint32());break;case 4:r.tags&&r.tags.length||(r.tags=[]),r.tags.push(e.string());break;case 5:r.tensorflowVersion=e.string();break;case 6:r.tensorflowGitVersion=e.string();break;default:e.skipType(7&a);}}return r;},e;}(),e;}(),e.SavedModel=function(){function e(e){if(this.metaGraphs=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.savedModelSchemaVersion=gc.Long?gc.Long.fromBits(0,0,!1):0,e.prototype.metaGraphs=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.SavedModel();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.savedModelSchemaVersion=e.int64();break;case 2:r.metaGraphs&&r.metaGraphs.length||(r.metaGraphs=[]),r.metaGraphs.push(yc.tensorflow.MetaGraphDef.decode(e,e.uint32()));break;default:e.skipType(7&a);}}return r;},e;}(),e.FunctionDefLibrary=function(){function e(e){if(this.function=[],this.gradient=[],e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.function=gc.emptyArray,e.prototype.gradient=gc.emptyArray,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.FunctionDefLibrary();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.function&&r.function.length||(r.function=[]),r.function.push(yc.tensorflow.FunctionDef.decode(e,e.uint32()));break;case 2:r.gradient&&r.gradient.length||(r.gradient=[]),r.gradient.push(yc.tensorflow.GradientDef.decode(e,e.uint32()));break;default:e.skipType(7&a);}}return r;},e;}(),e.FunctionDef=function(){function e(e){if(this.attr={},this.nodeDef=[],this.ret={},e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.signature=null,e.prototype.attr=gc.emptyObject,e.prototype.nodeDef=gc.emptyArray,e.prototype.ret=gc.emptyObject,e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n,r=void 0===t?e.len:e.pos+t,a=new yc.tensorflow.FunctionDef();e.pos<r;){var i=e.uint32();switch(i>>>3){case 1:a.signature=yc.tensorflow.OpDef.decode(e,e.uint32());break;case 5:e.skip().pos++,a.attr===gc.emptyObject&&(a.attr={}),n=e.string(),e.pos++,a.attr[n]=yc.tensorflow.AttrValue.decode(e,e.uint32());break;case 3:a.nodeDef&&a.nodeDef.length||(a.nodeDef=[]),a.nodeDef.push(yc.tensorflow.NodeDef.decode(e,e.uint32()));break;case 4:e.skip().pos++,a.ret===gc.emptyObject&&(a.ret={}),n=e.string(),e.pos++,a.ret[n]=e.string();break;default:e.skipType(7&i);}}return a;},e;}(),e.GradientDef=function(){function e(e){if(e)for(var t=Object.keys(e),n=0;n<t.length;++n){null!=e[t[n]]&&(this[t[n]]=e[t[n]]);}}return e.prototype.functionName="",e.prototype.gradientFunc="",e.decode=function(e,t){e instanceof mc||(e=mc.create(e));for(var n=void 0===t?e.len:e.pos+t,r=new yc.tensorflow.GradientDef();e.pos<n;){var a=e.uint32();switch(a>>>3){case 1:r.functionName=e.string();break;case 2:r.gradientFunc=e.string();break;default:e.skipType(7&a);}}return r;},e;}(),e;}();function bc(e,t,n,r){var a=t.params[e];if(a&&void 0!==a.inputIndex){if("tensor"===a.type)return wc(t.inputNames[a.inputIndex],n,r);if("tensors"===a.type)return(0===a.inputIndex?0===a.inputParamLength?t.inputNames:t.inputNames.slice(a.inputIndex,-a.inputParamLength):t.inputNames.splice(a.inputIndex)).map(function(e){return wc(e,n,r);});var i=Array.prototype.slice.call(wc(t.inputNames.slice(a.inputIndex)[0],n,r).dataSync());return"number"===a.type?i[0]:i;}return a&&a.value;}function wc(e,t,n){var r=Oc(e),a=r[0],i=r[1],o=n.currentContextIds.find(function(e){return!!t[kc(a,e)];});return void 0!==o?t[kc(a,o)][i]:void 0;}function xc(e,t){var n=Oc(e),r=n[0],a=n[1];return[kc(r,t&&t.currentContextId),a];}function kc(e,t){return t?e+"-"+t:e;}function Oc(e){var t=e.lastIndexOf(":");return-1===t?[e,0]:[e.substring(0,t),Number(e.substring(t+1))];}var Sc=n(240),Nc=Object.assign({},Sc,{default:Sc}),Ec=n(239),Ic=Object.assign({},Ec,{default:Ec}),Tc=n(238),Ac=Object.assign({},Tc,{default:Tc}),Cc=n(237),Pc=Object.assign({},Cc,{default:Cc}),_c=n(236),Rc=Object.assign({},_c,{default:_c}),Mc=n(235),jc=Object.assign({},Mc,{default:Mc}),Dc=n(234),Lc=Object.assign({},Dc,{default:Dc}),zc=n(233),Fc=Object.assign({},zc,{default:zc}),Bc=n(232),Vc=Object.assign({},Bc,{default:Bc}),Uc=n(231),Wc=Object.assign({},Uc,{default:Uc}),Gc=n(230),qc=Object.assign({},Gc,{default:Gc}),Hc=n(229),Kc=Object.assign({},Hc,{default:Hc}),Xc=n(228),Jc=Object.assign({},Xc,{default:Xc}),Yc=["Switch","Merge","Enter","Exit","NextIteration"],Qc=function(){function e(){var e=[Nc,Ic,Ac,Pc,Rc,Fc,Lc,jc,Vc,Wc,qc,Kc,Jc],t=[].concat.apply([],e.map(function(e){return e.default?e.default:e;}));this.opMappers=t.reduce(function(e,t){return e[t.tfOpName]=t,e;},{});}return Object.defineProperty(e,"Instance",{get:function get(){return this._instance||(this._instance=new this());},enumerable:!0,configurable:!0}),e.prototype.isControlFlow=function(e){return Yc.some(function(t){return t===e.op;});},e.prototype.transformGraph=function(e){var t=this,n=!1,r=[],a=e.node.reduce(function(e,a){return e[a.name]=t.mapNode(a),t.isControlFlow(a)&&(n=!0),"Placeholder"===a.op&&r.push(e[a.name]),e;},{}),i=[],o=[];return Object.keys(a).forEach(function(e){var t=a[e];t.inputNames.forEach(function(e){var n=xc(e)[0];t.inputs.push(a[n]),a[n].children.push(t);}),0===t.inputs.length&&i.push(t);}),Object.keys(a).forEach(function(e){var t=a[e];0===t.children.length&&o.push(t);}),{nodes:a,inputs:i,outputs:o,placeholders:r,withControlFlow:n};},e.prototype.mapNode=function(e){var t=this,n=this.opMappers[e.op];if(void 0===n)throw new Error("Tensorflow Op is not supported: "+e.op);var r={name:e.name,op:n.dlOpName,category:n.category,inputNames:(e.input||[]).map(function(e){return e.startsWith("^")?e.substr(1):e;}),inputs:[],children:[],params:{}};return n.params&&(r.params=n.params.reduce(function(n,r){var a=r.tfInputIndex,i=r.tfInputParamLength,o=r.type,s=void 0;if(void 0===a)switch(r.type){case"string":void 0===(s=t.getStringParam(e.attr,r.tfParamName,r.defaultValue))&&r.tfParamNameDeprecated&&(s=t.getStringParam(e.attr,r.tfParamNameDeprecated,r.defaultValue));break;case"number":void 0===(s=t.getNumberParam(e.attr,r.tfParamName,r.defaultValue))&&r.tfParamNameDeprecated&&(s=t.getNumberParam(e.attr,r.tfParamNameDeprecated,r.defaultValue));break;case"number[]":void 0===(s=t.getNumericArrayParam(e.attr,r.tfParamName,r.defaultValue))&&r.tfParamNameDeprecated&&(s=t.getNumericArrayParam(e.attr,r.tfParamNameDeprecated,r.defaultValue));break;case"bool":void 0===(s=t.getBoolParam(e.attr,r.tfParamName,r.defaultValue))&&r.tfParamNameDeprecated&&(s=t.getBoolParam(e.attr,r.tfParamNameDeprecated,r.defaultValue));break;case"shape":void 0===(s=t.getTensorShapeParam(e.attr,r.tfParamName,r.defaultValue))&&r.tfParamNameDeprecated&&(s=t.getTensorShapeParam(e.attr,r.tfParamNameDeprecated,r.defaultValue));break;case"dtype":void 0===(s=t.getDtypeParam(e.attr,r.tfParamName,r.defaultValue))&&r.tfParamNameDeprecated&&(s=t.getDtypeParam(e.attr,r.tfParamNameDeprecated,r.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+r.type+" for op: "+e.op);}return n[r.dlParamName]={value:s,inputIndex:a,type:o,inputParamLength:i},n;},{})),r;},e.prototype.getStringParam=function(e,t,n,r){void 0===r&&(r=!1);var a=e[t];if(void 0!==a){var i=String.fromCharCode.apply(null,a.s);return r?i:i.toLowerCase();}return n;},e.prototype.getBoolParam=function(e,t,n){var r=e[t];return r?r.b:n;},e.prototype.getNumberParam=function(e,t,n){var r=e[t],a=r?void 0!==r.f?r.f:r.i:n;return"number"==typeof a?a:a.toInt();},e.prototype.getDtypeParam=function(e,t,n){var r=e[t];if(r&&r.type)switch(r.type){case vc.DataType.DT_FLOAT:return"float32";case vc.DataType.DT_INT32:return"int32";case vc.DataType.DT_BOOL:return"bool";default:return n;}return n;},e.prototype.getTensorShapeParam=function(e,t,n){var r=e[t];return r&&r.shape?r.shape.dim.map(function(e){return e.size;}):n;},e.prototype.getNumericArrayParam=function(e,t,n){var r=e[t];return r?(r.list.f&&r.list.f.length?r.list.f:r.list.i).map(function(e){return"number"==typeof e?e:e.toInt();}):n;},e;}(),Zc=function Zc(e,t,n){switch(e.op){case"add":return[f.d(bc("a",e,t,n),bc("b",e,t,n))];case"mod":return[f.eb(bc("a",e,t,n),bc("b",e,t,n))];case"mul":return[f.ib(bc("a",e,t,n),bc("b",e,t,n))];case"div":return[f.J(bc("a",e,t,n),bc("b",e,t,n))];case"sub":return[f.pc(bc("a",e,t,n),bc("b",e,t,n))];case"minimum":return[f.cb(bc("a",e,t,n),bc("b",e,t,n))];case"maximum":return[f.Ya(bc("a",e,t,n),bc("b",e,t,n))];case"pow":return[f.Ab(bc("a",e,t,n),bc("b",e,t,n))];case"squaredDifference":return[f.jc(bc("a",e,t,n),bc("b",e,t,n))];default:throw TypeError("Node type "+e.op+" is not implemented");}},$c=function $c(e,t,n){switch(e.op){case"abs":return[f.a(bc("x",e,t,n))];case"acos":return[f.b(bc("x",e,t,n))];case"acosh":return[f.c(bc("x",e,t,n))];case"asin":return[f.h(bc("x",e,t,n))];case"asinh":return[f.i(bc("x",e,t,n))];case"atan":return[f.j(bc("x",e,t,n))];case"atanh":return[f.l(bc("x",e,t,n))];case"ceil":return[f.u(bc("x",e,t,n))];case"cos":return[f.F(bc("x",e,t,n))];case"cosh":return[f.G(bc("x",e,t,n))];case"elu":return[f.M(bc("x",e,t,n))];case"erf":return[f.P(bc("x",e,t,n))];case"exp":return[f.Q(bc("x",e,t,n))];case"expm1":return[f.S(bc("x",e,t,n))];case"floor":return[f.V(bc("x",e,t,n))];case"log":return[f.La(bc("x",e,t,n))];case"log1p":return[f.Ma(bc("x",e,t,n))];case"neg":return[f.mb(bc("x",e,t,n))];case"reciprocal":return[f.Ib(bc("x",e,t,n))];case"relu":return[f.Jb(bc("x",e,t,n))];case"round":return[f.Qb(bc("x",e,t,n))];case"selu":return[f.Tb(bc("x",e,t,n))];case"sigmoid":return[f.Vb(bc("x",e,t,n))];case"sin":return[f.Xb(bc("x",e,t,n))];case"sign":return[f.Wb(bc("x",e,t,n))];case"sinh":return[f.Yb(bc("x",e,t,n))];case"softplus":return[f.fc(bc("x",e,t,n))];case"sqrt":return[f.hc(bc("x",e,t,n))];case"square":return[f.ic(bc("x",e,t,n))];case"tanh":return[f.tc(bc("x",e,t,n))];case"tan":return[f.sc(bc("x",e,t,n))];case"clipByValue":return[f.v(bc("x",e,t,n),bc("clipValueMin",e,t,n),bc("clipValueMax",e,t,n))];case"rsqrt":return[f.J(f.Sb(1,"float32"),f.hc(wc(e.inputNames[0],t,n)))];default:throw TypeError("Node type "+e.op+" is not implemented");}},el=function el(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},tl=function tl(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},nl=function nl(e,t,n){switch(e.op){case"conv1d":var r=bc("stride",e,t,n),a=bc("pad",e,t,n),i=bc("dataFormat",e,t,n).toUpperCase(),o=bc("dilation",e,t,n);return[f.C(bc("x",e,t,n),bc("filter",e,t,n),r,a,i,o)];case"conv2d":r=bc("strides",e,t,n),a=bc("pad",e,t,n),i=bc("dataFormat",e,t,n).toUpperCase();var s=bc("dilations",e,t,n);return[f.D(bc("x",e,t,n),bc("filter",e,t,n),[r[1],r[2]],a,i,[s[0],s[1]])];case"conv2dTranspose":var u=bc("outputShape",e,t,n);return r=bc("strides",e,t,n),a=bc("pad",e,t,n),[f.E(bc("x",e,t,n),bc("filter",e,t,n),u,[r[1],r[2]],a)];case"depthwiseConv2d":return r=bc("strides",e,t,n),a=bc("pad",e,t,n),s=bc("dilations",e,t,n),i=bc("dataFormat",e,t,n).toUpperCase(),[f.I(bc("input",e,t,n),bc("filter",e,t,n),[r[1],r[2]],a,i,[s[0],s[1]])];case"avgPool":r=bc("strides",e,t,n),a=bc("pad",e,t,n);var c=bc("kernelSize",e,t,n);return[f.m(bc("x",e,t,n),[c[1],c[2]],[r[1],r[2]],a)];case"maxPool":return r=bc("strides",e,t,n),a=bc("pad",e,t,n),c=bc("kernelSize",e,t,n),[f.Xa(bc("x",e,t,n),[c[1],c[2]],[r[1],r[2]],a)];default:throw TypeError("Node type "+e.op+" is not implemented");}},rl=function rl(e,t,n){switch(e.op){case"fill":var r=bc("shape",e,t,n),a=bc("value",e,t,n);return[f.U(r,a)];case"linspace":var i=bc("start",e,t,n),o=bc("stop",e,t,n),s=bc("num",e,t,n);return[f.Ja(i,o,s)];case"oneHot":var u=bc("indices",e,t,n),c=bc("depth",e,t,n),l=bc("onValue",e,t,n),p=bc("offValue",e,t,n);return[f.qb(u,c,l,p)];case"ones":return[f.rb(bc("shape",e,t,n),bc("dtype",e,t,n))];case"onesLike":return[f.sb(bc("x",e,t,n))];case"randomUniform":return[f.Gb(bc("shape",e,t,n),bc("minval",e,t,n),bc("maxval",e,t,n),bc("dtype",e,t,n))];case"range":i=bc("start",e,t,n);var h=bc("stop",e,t,n),d=bc("step",e,t,n);return[f.Hb(i,h,d,bc("dtype",e,t,n))];case"truncatedNormal":r=bc("shape",e,t,n);var m=bc("mean",e,t,n),g=bc("stdDev",e,t,n),y=bc("seed",e,t,n);return[f.Cc(r,m,g,bc("dtype",e,t,n),y)];case"zeros":return[f.Hc(bc("shape",e,t,n),bc("dtype",e,t,n))];case"zerosLike":return[f.Ic(bc("x",e,t,n))];default:throw TypeError("Node type "+e.op+" is not implemented");}},al=function al(e,t,n){switch(e.op){case"const":return t[e.name];case"placeholder":var r=bc("default",e,t,n);return[wc(e.name,t,n)||r];case"identity":case"stopGradient":case"fakeQuantWithMinMaxVars":return[bc("x",e,t,n)];case"snapshot":return[bc("x",e,t,n).clone()];case"shape":return[f.vc(bc("x",e,t,n).shape,"int32")];case"noop":return[];case"print":var a=bc("x",e,t,n),i=bc("data",e,t,n),o=bc("message",e,t,n),s=bc("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(var u=0;u<i.length;u++){console.log(Array.prototype.slice.call(i[0].dataSync()).slice(0,s));}return[a];default:throw TypeError("Node type "+e.op+" is not implemented");}},il=function il(e,t,n){switch(e.op){case"resizeBilinear":var r=bc("images",e,t,n),a=bc("size",e,t,n),i=bc("alignCorners",e,t,n);return[f.Ca.resizeBilinear(r,[a[0],a[1]],i)];case"resizeNearestNeighbor":return r=bc("images",e,t,n),a=bc("size",e,t,n),i=bc("alignCorners",e,t,n),[f.Ca.resizeNearestNeighbor(r,[a[0],a[1]],i)];default:throw TypeError("Node type "+e.op+" is not implemented");}},ol=function ol(e,t,n){switch(e.op){case"equal":return[f.N(bc("a",e,t,n),bc("b",e,t,n))];case"notEqual":return[f.ob(bc("a",e,t,n),bc("b",e,t,n))];case"greater":return[f.Y(bc("a",e,t,n),bc("b",e,t,n))];case"greaterEqual":return[f.Z(bc("a",e,t,n),bc("b",e,t,n))];case"less":return[f.Ea(bc("a",e,t,n),bc("b",e,t,n))];case"lessEqual":return[f.Fa(bc("a",e,t,n),bc("b",e,t,n))];case"logicalAnd":return[f.Pa(bc("a",e,t,n),bc("b",e,t,n))];case"logicalNot":return[f.Qa(bc("a",e,t,n))];case"logicalOr":return[f.Ra(bc("a",e,t,n),bc("b",e,t,n))];case"where":return[f.Gc(bc("condition",e,t,n),bc("a",e,t,n),bc("b",e,t,n))];default:throw TypeError("Node type "+e.op+" is not implemented");}},sl=function sl(e,t,n){switch(e.op){case"matMul":return[f.Ua(bc("a",e,t,n),bc("b",e,t,n),bc("transposeA",e,t,n),bc("transposeB",e,t,n))];case"transpose":return[f.Bc(bc("x",e,t,n),bc("perm",e,t,n))];default:throw TypeError("Node type "+e.op+" is not implemented");}},ul=function ul(e,t,n){switch(e.op){case"batchNormalization":return[f.o(bc("x",e,t,n),bc("mean",e,t,n),bc("variance",e,t,n),bc("epsilon",e,t,n),bc("scale",e,t,n),bc("offset",e,t,n))];case"localResponseNormalization":return[f.Ka(bc("x",e,t,n),bc("radius",e,t,n),bc("bias",e,t,n),bc("alpha",e,t,n),bc("beta",e,t,n))];case"softmax":return[f.ec(bc("x",e,t,n))];default:throw TypeError("Node type "+e.op+" is not implemented");}},cl=function cl(e,t,n){switch(e.op){case"max":var r=bc("axis",e,t,n),a=bc("keepDims",e,t,n);return[f.Wa(bc("x",e,t,n),r,a)];case"mean":return r=bc("axis",e,t,n),a=bc("keepDims",e,t,n),[f.ab(bc("x",e,t,n),r,a)];case"min":return r=bc("axis",e,t,n),a=bc("keepDims",e,t,n),[f.bb(bc("x",e,t,n),r,a)];case"sum":return r=bc("axis",e,t,n),a=bc("keepDims",e,t,n),[f.rc(bc("x",e,t,n),r,a)];case"argMax":return r=bc("axis",e,t,n),[f.f(bc("x",e,t,n),r)];case"argMin":return r=bc("axis",e,t,n),[f.g(bc("x",e,t,n),r)];default:throw TypeError("Node type "+e.op+" is not implemented");}},ll=function ll(e,t,n){switch(e.op){case"concat":var r=bc("axis",e,t,n),a=bc("tensors",e,t,n);return[f.x(a,r)];case"gather":r=bc("axis",e,t,n);var i=bc("x",e,t,n),o=bc("indices",e,t,n);return[f.X(i,o,r)];case"reverse":return r=bc("axis",e,t,n),i=bc("x",e,t,n),[f.Lb(i,r)];case"slice":var s=bc("begin",e,t,n),u=bc("size",e,t,n);return[f.Zb(bc("x",e,t,n),s,u)];case"stridedSlice":s=bc("begin",e,t,n);var c=bc("end",e,t,n),l=bc("strides",e,t,n),p=bc("beginMask",e,t,n),h=bc("endMask",e,t,n);return[f.oc(bc("x",e,t,n),s,c,l,p,h)];case"stack":return yr.f(function(){var r=bc("axis",e,t,n),a=bc("tensors",e,t,n),i=a[0].shape,o=a[0].squeeze().shape,s=a.map(function(e){var t=y.arraysEqual(e.shape,i);if(!t&&!y.arraysEqual(e.squeeze().shape,o))throw new Error("the input tensors shape does not match");return t?e:e.reshape(i);});return[f.mc(s,r)];});case"tile":var d=bc("reps",e,t,n);return[f.zc(bc("x",e,t,n),d)];case"split":r=bc("axis",e,t,n);var m=bc("numOrSizeSplits",e,t,n);return f.gc(bc("x",e,t,n),m,r);default:throw TypeError("Node type "+e.op+" is not implemented");}},fl=function fl(e,t,n){switch(e.op){case"cast":return[f.t(bc("x",e,t,n),bc("dtype",e,t,n))];case"expandDims":var r=e.params.axis.value;return[f.R(bc("x",e,t,n),r)];case"squeeze":return r=e.params.axis.value,[f.lc(bc("x",e,t,n),r)];case"reshape":return[f.Kb(bc("x",e,t,n),bc("shape",e,t,n))];case"pad":return[f.vb(bc("x",e,t,n),function(e,t){for(var n=[],r=0;r<e.length;r+=2){n.push(e.slice(r,r+2));}return n;}(bc("padding",e,t,n)),bc("constantValue",e,t,n))];default:throw TypeError("Node type "+e.op+" is not implemented");}};function pl(e,t,n){switch(e.category){case"arithmetic":return Zc(e,t,n);case"basic_math":return $c(e,t,n);case"control":return function(e,t,n){return el(this,void 0,void 0,function(){var r,a,i,o,s,u,c;return tl(this,function(l){switch(l.label){case 0:switch(e.op){case"loopCond":return[3,1];case"switch":return[3,2];case"merge":return[3,4];case"enter":return[3,5];case"exit":return[3,6];case"nextIteration":return[3,7];}return[3,8];case 1:return[2,[bc("pred",e,t,n)]];case 2:return r=bc("pred",e,t,n),a=bc("data",e,t,n),[4,r.data()];case 3:return[2,l.sent()[0]?[void 0,a]:[a,void 0]];case 4:return[2,(i=e.inputNames.find(function(e){return void 0!==wc(e,t,n);}))?[wc(i,t,n)]:void 0];case 5:return o=bc("frameName",e,t,n),s=bc("tensor",e,t,n),n.enterFrame(o),[2,[s]];case 6:return u=bc("tensor",e,t,n),n.exitFrame(),[2,[u]];case 7:return c=bc("tensor",e,t,n),n.nextIteration(),[2,[c]];case 8:throw TypeError("Node type "+e.op+" is not implemented");}});});}(e,t,n);case"convolution":return nl(e,t,n);case"creation":return rl(e,t,n);case"image":return il(e,t,n);case"graph":return al(e,t,n);case"logical":return ol(e,t,n);case"matrices":return sl(e,t,n);case"normalization":return ul(e,t,n);case"reduction":return cl(e,t,n);case"slice_join":return ll(e,t,n);case"transformation":return fl(e,t,n);default:throw TypeError("Node type "+e.op+" is not implemented");}}var hl=function(){function e(e){this.weightMap=e,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds();}return e.prototype.newFrame=function(e,t){return{id:e,frameName:t,iterationId:0};},Object.defineProperty(e.prototype,"currentContext",{get:function get(){return this.contexts;},set:function set(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds());},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentContextId",{get:function get(){return this._currentContextIds[0];},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentContextIds",{get:function get(){return this._currentContextIds;},enumerable:!0,configurable:!0}),e.prototype.generateCurrentContextIds=function(){for(var e=[],t=0;t<this.contexts.length-1;t++){var n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n));}e.push(""),this._currentContextIds=e;},e.prototype.contextIdforContexts=function(e){return e?e.map(function(e){return 0===e.id&&0===e.iterationId?"":e.frameName+"-"+e.iterationId;}).join("/"):"";},e.prototype.enterFrame=function(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)));},e.prototype.exitFrame=function(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();},e.prototype.nextIteration=function(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts));},e.prototype.getWeight=function(e){return this.weightMap[e];},e;}(),dl=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){for(var a in t=arguments[n]){Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);}}return e;},ml=function ml(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},gl=function gl(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},yl=function(){function e(e){this.graph=e,this.compiledOrder=[],this._weightMap={},this.placeholders=e.placeholders.map(function(e){return e.name;}),this.outputs=e.outputs.map(function(e){return e.name;}),this.compile();}return Object.defineProperty(e.prototype,"weightMap",{get:function get(){return this._weightMap;},set:function set(e){var t=Object.keys(e).map(function(t){return e[t].map(function(e){return e.id;});});this.weightIds=[].concat.apply([],t),this._weightMap=e;},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function get(){return this.placeholders;},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function get(){return this.outputs;},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"isControlFlowModel",{get:function get(){return this.graph.withControlFlow;},enumerable:!0,configurable:!0}),e.prototype.compile=function(){if(!this.graph.withControlFlow)for(var e=this.graph.inputs.slice(),t={};e.length>0;){var n=e.pop();t[n.name]=!0,this.compiledOrder.push(n),n.children.forEach(function(n){!t[n.name]&&n.inputNames.every(function(e){var n=xc(e)[0];return t[n];})&&e.push(n);});}},e.prototype.execute=function(e,t){var n=this;return this.checkInput(e),Object(yr.f)(function(){var r=new hl(n._weightMap),a=n.compiledOrder.reduce(function(e,t){return e[t.name]=pl(t,e,r),e;},dl({},n.weightMap,e));return n.findOutputs(a,r,t);});},e.prototype.executeAsync=function(e,t){return ml(this,void 0,void 0,function(){var n,r,a,i,o,s,u=this;return gl(this,function(c){switch(c.label){case 0:return n=new hl(this._weightMap),[4,this.executeWithControlFlow(e,n)];case 1:return r=c.sent(),a=this.findOutputs(r,n,t),i=Object.keys(a).map(function(e){return a[e].id;}),o=Object.keys(e).map(function(t){return e[t].map(function(e){return e.id;});}),s=[].concat.apply([],o),Object.keys(r).forEach(function(e){r[e].forEach(function(e){e&&-1===i.indexOf(e.id)&&-1===s.indexOf(e.id)&&-1===u.weightIds.indexOf(e.id)&&e.dispose();});}),[2,a];}});});},e.prototype.executeWithControlFlow=function(e,t){return ml(this,void 0,void 0,function(){var n,r,a,i,o,s,u,c;return gl(this,function(l){switch(l.label){case 0:n=this.graph.inputs.map(function(e){return{node:e,contexts:t.currentContext};}),r=dl({},this.weightMap,e),a={},l.label=1;case 1:return n.length>0?(i=n.pop(),t.currentContext=i.contexts,o=pl(i.node,r,t),s=xc(i.node.name,t)[0],u=r,c=s,[4,o]):[3,3];case 2:return u[c]=l.sent(),i.node.children.forEach(function(e){var i=xc(e.name,t)[0];a[i]||("merge"===e.op?e.inputNames.some(function(e){return!!wc(e,r,t);})&&(a[i]=!0,n.push({contexts:t.currentContext,node:e})):e.inputNames.every(function(e){return!!wc(e,r,t);})&&(a[i]=!0,n.push({contexts:t.currentContext,node:e})));}),[3,1];case 3:return[2,r];}});});},e.prototype.findOutputs=function(e,t,n){return!n||n instanceof Array||(n=[n]),(n||this.graph.outputs.map(function(e){return e.name;})).reduce(function(n,r){return n[r]=wc(r,e,t),n;},{});},e.prototype.dispose=function(){var e=this;Object.keys(this.weightMap).forEach(function(t){return e.weightMap[t].forEach(function(e){return e.dispose();});});},e.prototype.checkInput=function(e){var t=this,n=Object.keys(e),r=[],a=[];if(this.placeholders.forEach(function(e){-1===n.indexOf(e)&&r.push(e);}),n.forEach(function(e){-1===t.placeholders.indexOf(e)&&a.push(e);}),r.length>0)throw new Error("The dict provided in model.execute(dict) has the keys ["+n+"], but is missing the required keys: ["+r+"].");if(a.length>0)throw new Error("The dict provided in model.execute(dict) has unused keys: ["+a+"]. Please provide only the following keys: ["+this.placeholders+"].");},e;}(),vl=function vl(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},bl=function bl(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},wl=function(){function e(e,t,n){this.modelUrl=e,this.weightManifestUrl=t,this.requestOption=n,this.version="n/a",this.pathPrefix=this.getPathPrefix();}return Object.defineProperty(e.prototype,"modelVersion",{get:function get(){return this.version;},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function get(){return this.executor.inputNodes;},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function get(){return this.executor.outputNodes;},enumerable:!0,configurable:!0}),e.prototype.getPathPrefix=function(){var e=hc.parse(this.weightManifestUrl),t=e.pathname.split("/");return t.splice(-1),e.pathname=t.join("/"),hc.format(e)+"/";},e.prototype.loadRemoteProtoFile=function(){return vl(this,void 0,void 0,function(){var e,t,n,r,a;return bl(this,function(i){switch(i.label){case 0:return i.trys.push([0,3,,4]),[4,fetch(this.modelUrl,this.requestOption)];case 1:return e=i.sent(),n=(t=vc.GraphDef).decode,r=Uint8Array.bind,[4,e.arrayBuffer()];case 2:return[2,n.apply(t,[new(r.apply(Uint8Array,[void 0,i.sent()]))()])];case 3:throw a=i.sent(),new Error(this.modelUrl+" not found. "+a);case 4:return[2];}});});},e.prototype.loadWeightManifest=function(){return vl(this,void 0,void 0,function(){var e,t,n;return bl(this,function(r){switch(r.label){case 0:return r.trys.push([0,3,,4]),[4,fetch(this.weightManifestUrl,this.requestOption)];case 1:return e=r.sent(),t=this,[4,e.clone().json()];case 2:return t.weightManifest=r.sent(),[3,4];case 3:throw n=r.sent(),new Error(this.weightManifestUrl+" not found. "+n);case 4:return[2];}});});},e.prototype.load=function(){return vl(this,void 0,void 0,function(){var e,t,n,r;return bl(this,function(a){switch(a.label){case 0:return e=this.loadRemoteProtoFile(),t=this.loadWeightManifest(),[4,Promise.all([e,t])];case 1:return n=a.sent()[0],this.version=n.versions.producer+"."+n.versions.minConsumer,[4,i.loadWeights(this.weightManifest,this.pathPrefix,void 0,this.requestOption)];case 2:return r=a.sent(),this.executor=new yl(Qc.Instance.transformGraph(n)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),[2,!0];}});});},e.prototype.predict=function(e,t){return this.execute(e,this.outputNodes);},e.prototype.constructTensorMap=function(e){var t=e instanceof m.a?[e]:e;if(t.length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the frozen model has "+this.inputNodes.length+" placeholders, while there are "+t.length+" input tensors.");return this.inputNodes.reduce(function(e,n,r){return e[n]=t[r],e;},{});},e.prototype.execute=function(e,t){if(t=t||this.outputNodes,(e instanceof m.a||Array.isArray(e))&&(e=this.constructTensorMap(e)),this.executor.isControlFlowModel)throw new Error("The model contains control flow ops, please use executeAsync method");var n=this.executor.execute(this.convertTensorMapToTensorsMap(e),t),r=Object.keys(n);return Array.isArray(t)&&t.length>1?t.map(function(e){return n[e];}):n[r[0]];},e.prototype.executeAsync=function(e,t){return vl(this,void 0,void 0,function(){var n,r;return bl(this,function(a){switch(a.label){case 0:if(!this.executor.isControlFlowModel)throw new Error("The model does not contain control flow ops, please use execute method for better performance.");return t=t||this.outputNodes,(e instanceof m.a||Array.isArray(e))&&(e=this.constructTensorMap(e)),[4,this.executor.executeAsync(this.convertTensorMapToTensorsMap(e),t)];case 1:return n=a.sent(),r=Object.keys(n),[2,Array.isArray(t)&&t.length>1?t.map(function(e){return n[e];}):n[r[0]]];}});});},e.prototype.convertTensorMapToTensorsMap=function(e){return Object.keys(e).reduce(function(t,n){return t[n]=[e[n]],t;},{});},e.prototype.dispose=function(){this.executor.dispose();},e;}();function xl(e,t,n){return vl(this,void 0,void 0,function(){var r;return bl(this,function(a){switch(a.label){case 0:return[4,(r=new wl(e,t,n)).load()];case 1:return a.sent(),[2,r];}});});}n.d(t,"version",function(){return kl;}),n.d(t,"AdadeltaOptimizer",function(){return kr;}),n.d(t,"AdagradOptimizer",function(){return Sr;}),n.d(t,"AdamOptimizer",function(){return Er;}),n.d(t,"AdamaxOptimizer",function(){return Tr;}),n.d(t,"MomentumOptimizer",function(){return _r;}),n.d(t,"Optimizer",function(){return wr;}),n.d(t,"RMSPropOptimizer",function(){return Mr;}),n.d(t,"SGDOptimizer",function(){return Cr;}),n.d(t,"Tensor",function(){return m.a;}),n.d(t,"TensorBuffer",function(){return m.b;}),n.d(t,"variable",function(){return m.d;}),n.d(t,"Variable",function(){return m.c;}),n.d(t,"Rank",function(){return g.a;}),n.d(t,"Reduction",function(){return jr.b;}),n.d(t,"ENV",function(){return c.ENV;}),n.d(t,"Environment",function(){return c.Environment;}),n.d(t,"setBackend",function(){return Fr;}),n.d(t,"getBackend",function(){return Br;}),n.d(t,"disposeVariables",function(){return Vr;}),n.d(t,"memory",function(){return Ur;}),n.d(t,"version_core",function(){return"0.11.4";}),n.d(t,"doc",function(){return qt.a;}),n.d(t,"nextFrame",function(){return Wr;}),n.d(t,"environment",function(){return c;}),n.d(t,"io",function(){return i;}),n.d(t,"serialization",function(){return o;}),n.d(t,"test_util",function(){return s;}),n.d(t,"util",function(){return y;}),n.d(t,"webgl",function(){return u;}),n.d(t,"batchNormalization",function(){return f.o;}),n.d(t,"batchNormalization2d",function(){return f.p;}),n.d(t,"batchNormalization3d",function(){return f.q;}),n.d(t,"batchNormalization4d",function(){return f.r;}),n.d(t,"concat",function(){return f.x;}),n.d(t,"concat1d",function(){return f.y;}),n.d(t,"concat2d",function(){return f.z;}),n.d(t,"concat3d",function(){return f.A;}),n.d(t,"concat4d",function(){return f.B;}),n.d(t,"conv1d",function(){return f.C;}),n.d(t,"conv2d",function(){return f.D;}),n.d(t,"conv2dTranspose",function(){return f.E;}),n.d(t,"depthwiseConv2d",function(){return f.I;}),n.d(t,"separableConv2d",function(){return f.Ub;}),n.d(t,"matMul",function(){return f.Ua;}),n.d(t,"matrixTimesVector",function(){return f.Va;}),n.d(t,"outerProduct",function(){return f.ub;}),n.d(t,"vectorTimesMatrix",function(){return f.Fc;}),n.d(t,"dot",function(){return f.L;}),n.d(t,"avgPool",function(){return f.m;}),n.d(t,"maxPool",function(){return f.Xa;}),n.d(t,"transpose",function(){return f.Bc;}),n.d(t,"reverse",function(){return f.Lb;}),n.d(t,"reverse1d",function(){return f.Mb;}),n.d(t,"reverse2d",function(){return f.Nb;}),n.d(t,"reverse3d",function(){return f.Ob;}),n.d(t,"reverse4d",function(){return f.Pb;}),n.d(t,"slice",function(){return f.Zb;}),n.d(t,"slice1d",function(){return f.ac;}),n.d(t,"slice2d",function(){return f.bc;}),n.d(t,"slice3d",function(){return f.cc;}),n.d(t,"slice4d",function(){return f.dc;}),n.d(t,"stridedSlice",function(){return f.oc;}),n.d(t,"argMax",function(){return f.f;}),n.d(t,"argMin",function(){return f.g;}),n.d(t,"logSumExp",function(){return f.Oa;}),n.d(t,"max",function(){return f.Wa;}),n.d(t,"mean",function(){return f.ab;}),n.d(t,"min",function(){return f.bb;}),n.d(t,"moments",function(){return f.gb;}),n.d(t,"sum",function(){return f.rc;}),n.d(t,"unsortedSegmentSum",function(){return f.Dc;}),n.d(t,"equal",function(){return f.N;}),n.d(t,"equalStrict",function(){return f.O;}),n.d(t,"greater",function(){return f.Y;}),n.d(t,"greaterStrict",function(){return f.Ba;}),n.d(t,"greaterEqual",function(){return f.Z;}),n.d(t,"greaterEqualStrict",function(){return f.Aa;}),n.d(t,"less",function(){return f.Ea;}),n.d(t,"lessStrict",function(){return f.Ha;}),n.d(t,"lessEqual",function(){return f.Fa;}),n.d(t,"lessEqualStrict",function(){return f.Ga;}),n.d(t,"notEqual",function(){return f.ob;}),n.d(t,"notEqualStrict",function(){return f.pb;}),n.d(t,"logicalNot",function(){return f.Qa;}),n.d(t,"logicalAnd",function(){return f.Pa;}),n.d(t,"logicalOr",function(){return f.Ra;}),n.d(t,"logicalXor",function(){return f.Sa;}),n.d(t,"where",function(){return f.Gc;}),n.d(t,"abs",function(){return f.a;}),n.d(t,"acos",function(){return f.b;}),n.d(t,"acosh",function(){return f.c;}),n.d(t,"asin",function(){return f.h;}),n.d(t,"asinh",function(){return f.i;}),n.d(t,"atan",function(){return f.j;}),n.d(t,"atanh",function(){return f.l;}),n.d(t,"ceil",function(){return f.u;}),n.d(t,"clipByValue",function(){return f.v;}),n.d(t,"cos",function(){return f.F;}),n.d(t,"cosh",function(){return f.G;}),n.d(t,"elu",function(){return f.M;}),n.d(t,"exp",function(){return f.Q;}),n.d(t,"expm1",function(){return f.S;}),n.d(t,"floor",function(){return f.V;}),n.d(t,"sign",function(){return f.Wb;}),n.d(t,"leakyRelu",function(){return f.Da;}),n.d(t,"log",function(){return f.La;}),n.d(t,"log1p",function(){return f.Ma;}),n.d(t,"logSigmoid",function(){return f.Na;}),n.d(t,"neg",function(){return f.mb;}),n.d(t,"prelu",function(){return f.Cb;}),n.d(t,"relu",function(){return f.Jb;}),n.d(t,"reciprocal",function(){return f.Ib;}),n.d(t,"round",function(){return f.Qb;}),n.d(t,"selu",function(){return f.Tb;}),n.d(t,"sigmoid",function(){return f.Vb;}),n.d(t,"sin",function(){return f.Xb;}),n.d(t,"sinh",function(){return f.Yb;}),n.d(t,"softplus",function(){return f.fc;}),n.d(t,"sqrt",function(){return f.hc;}),n.d(t,"rsqrt",function(){return f.Rb;}),n.d(t,"square",function(){return f.ic;}),n.d(t,"step",function(){return f.nc;}),n.d(t,"tan",function(){return f.sc;}),n.d(t,"tanh",function(){return f.tc;}),n.d(t,"erf",function(){return f.P;}),n.d(t,"add",function(){return f.d;}),n.d(t,"addStrict",function(){return f.e;}),n.d(t,"atan2",function(){return f.k;}),n.d(t,"div",function(){return f.J;}),n.d(t,"divStrict",function(){return f.K;}),n.d(t,"maximum",function(){return f.Ya;}),n.d(t,"maximumStrict",function(){return f.Za;}),n.d(t,"minimum",function(){return f.cb;}),n.d(t,"minimumStrict",function(){return f.db;}),n.d(t,"mod",function(){return f.eb;}),n.d(t,"modStrict",function(){return f.fb;}),n.d(t,"mul",function(){return f.ib;}),n.d(t,"mulStrict",function(){return f.jb;}),n.d(t,"pow",function(){return f.Ab;}),n.d(t,"powStrict",function(){return f.Bb;}),n.d(t,"sub",function(){return f.pc;}),n.d(t,"subStrict",function(){return f.qc;}),n.d(t,"squaredDifference",function(){return f.jc;}),n.d(t,"squaredDifferenceStrict",function(){return f.kc;}),n.d(t,"norm",function(){return f.nb;}),n.d(t,"cast",function(){return f.t;}),n.d(t,"clone",function(){return f.w;}),n.d(t,"fromPixels",function(){return f.W;}),n.d(t,"toPixels",function(){return f.Ac;}),n.d(t,"ones",function(){return f.rb;}),n.d(t,"onesLike",function(){return f.sb;}),n.d(t,"zeros",function(){return f.Hc;}),n.d(t,"zerosLike",function(){return f.Ic;}),n.d(t,"eye",function(){return f.T;}),n.d(t,"rand",function(){return f.Eb;}),n.d(t,"randomNormal",function(){return f.Fb;}),n.d(t,"truncatedNormal",function(){return f.Cc;}),n.d(t,"randomUniform",function(){return f.Gb;}),n.d(t,"multinomial",function(){return f.lb;}),n.d(t,"reshape",function(){return f.Kb;}),n.d(t,"squeeze",function(){return f.lc;}),n.d(t,"tile",function(){return f.zc;}),n.d(t,"gather",function(){return f.X;}),n.d(t,"oneHot",function(){return f.qb;}),n.d(t,"linspace",function(){return f.Ja;}),n.d(t,"range",function(){return f.Hb;}),n.d(t,"buffer",function(){return f.s;}),n.d(t,"fill",function(){return f.U;}),n.d(t,"tensor",function(){return f.uc;}),n.d(t,"scalar",function(){return f.Sb;}),n.d(t,"tensor1d",function(){return f.vc;}),n.d(t,"tensor2d",function(){return f.wc;}),n.d(t,"tensor3d",function(){return f.xc;}),n.d(t,"tensor4d",function(){return f.yc;}),n.d(t,"print",function(){return f.Db;}),n.d(t,"expandDims",function(){return f.R;}),n.d(t,"stack",function(){return f.mc;}),n.d(t,"unstack",function(){return f.Ec;}),n.d(t,"split",function(){return f.gc;}),n.d(t,"cumsum",function(){return f.H;}),n.d(t,"pad",function(){return f.vb;}),n.d(t,"pad1d",function(){return f.wb;}),n.d(t,"pad2d",function(){return f.xb;}),n.d(t,"pad3d",function(){return f.yb;}),n.d(t,"pad4d",function(){return f.zb;}),n.d(t,"movingAverage",function(){return f.hb;}),n.d(t,"basicLSTMCell",function(){return f.n;}),n.d(t,"multiRNNCell",function(){return f.kb;}),n.d(t,"softmax",function(){return f.ec;}),n.d(t,"localResponseNormalization",function(){return f.Ka;}),n.d(t,"linalg",function(){return f.Ia;}),n.d(t,"operation",function(){return f.tb;}),n.d(t,"losses",function(){return f.Ta;}),n.d(t,"image",function(){return f.Ca;}),n.d(t,"train",function(){return zr;}),n.d(t,"tidy",function(){return yr.f;}),n.d(t,"keep",function(){return yr.e;}),n.d(t,"dispose",function(){return yr.b;}),n.d(t,"time",function(){return yr.g;}),n.d(t,"grad",function(){return yr.c;}),n.d(t,"valueAndGrad",function(){return yr.h;}),n.d(t,"grads",function(){return yr.d;}),n.d(t,"valueAndGrads",function(){return yr.i;}),n.d(t,"variableGrads",function(){return yr.j;}),n.d(t,"customGrad",function(){return yr.a;}),n.d(t,"Callback",function(){return Vi;}),n.d(t,"CallbackList",function(){return Ui;}),n.d(t,"CustomCallback",function(){return Hi;}),n.d(t,"Model",function(){return zo;}),n.d(t,"RNN",function(){return _u;}),n.d(t,"Sequential",function(){return Yu;}),n.d(t,"SymbolicTensor",function(){return ja;}),n.d(t,"version_layers",function(){return"0.6.4";}),n.d(t,"model",function(){return ac;}),n.d(t,"sequential",function(){return ic;}),n.d(t,"loadModel",function(){return oc;}),n.d(t,"input",function(){return sc;}),n.d(t,"layers",function(){return uc;}),n.d(t,"constraints",function(){return cc;}),n.d(t,"initializers",function(){return lc;}),n.d(t,"metrics",function(){return fc;}),n.d(t,"regularizers",function(){return pc;}),n.d(t,"FrozenModel",function(){return wl;}),n.d(t,"loadFrozenModel",function(){return xl;}),n.d(t,"version_converter",function(){return"0.4.1";});var kl={"tfjs-core":"0.11.4","tfjs-layers":"0.6.4","tfjs-converter":"0.4.1",tfjs:"0.11.4"};},function(e,t,n){"use strict";function r(e,t){for(var n=e.length,r=[],a=0;a<n;a++){var i=n-1-a,o=e[i]||1;(t[t.length-1-a]||1)>1&&1===o&&r.unshift(i);}return r;}function a(e,t){for(var n=[],r=0;r<t.length;r++){var a=e[e.length-r-1],i=t.length-r-1,o=t[i];(null==a||1===a&&o>1)&&n.unshift(i);}return n;}function i(e){for(var t=0;t<e.length;t++){if(e[t]!==t)return!1;}return!0;}function o(e,t){for(var n=[],r="Operands could not be broadcast together with shapes "+e+" and "+t+".",a=Math.max(e.length,t.length),i=0;i<a;i++){var o=e[e.length-i-1]||1,s=t[t.length-i-1]||1;if(o>1&&s>1&&o!==s)throw Error(r);n.unshift(Math.max(o,s));}return n;}n.d(t,"c",function(){return r;}),n.d(t,"d",function(){return a;}),n.d(t,"b",function(){return i;}),n.d(t,"a",function(){return o;});},function(e,t,n){var r=n(15);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e;};},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n);},function(e,t){e.exports=function(e){try{return!!e();}catch(e){return!0;}};},function(e,t){e.exports=function(e){return"object"==(typeof e==="undefined"?"undefined":_typeof(e))?null!==e:"function"==typeof e;};},function(e,t,n){var r=n(121)("wks"),a=n(78),i=n(13).Symbol,o="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=o&&i[e]||(o?i:a)("Symbol."+e));}).store=r;},function(e,t,n){var r=n(48),a=Math.min;e.exports=function(e){return e>0?a(r(e),9007199254740991):0;};},function(e,t,n){var r=n(12),a=n(226),i=n(50),o=Object.defineProperty;t.f=n(19)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),a)try{return o(e,t,n);}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e;};},function(e,t,n){e.exports=!n(14)(function(){return 7!=Object.defineProperty({},"a",{get:function get(){return 7;}}).a;});},function(e,t,n){"use strict";var r,a,i,o,s;n.d(t,"a",function(){return a;}),n.d(t,"c",function(){return c;}),n.d(t,"b",function(){return l;}),function(e){e.float32="float32",e.int32="int32",e.bool="bool";}(r||(r={})),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4";}(a||(a={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32";}(i||(i={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool";}(o||(o={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32";}(s||(s={}));var u={float32:s,int32:i,bool:o};function c(e,t){return u[e][t];}function l(e){return c(e,"int32");}},function(e,t){var n=e.exports={version:"2.5.7"};"number"==typeof __e&&(__e=n);},function(e,t,n){var r=n(49);e.exports=function(e){return Object(r(e));};},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e;};},function(e,t,n){var r=n(138)("wks"),a=n(105),i=n(25).Symbol,o="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=o&&i[e]||(o?i:a)("Symbol."+e));}).store=r;},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n);},function(e,t,n){var r=n(5),a=n(14),i=n(49),o=/"/g,s=function s(e,t,n,r){var a=String(i(e)),s="<"+t;return""!==n&&(s+=" "+n+'="'+String(r).replace(o,"&quot;")+'"'),s+">"+a+"</"+t+">";};e.exports=function(e,t){var n={};n[e]=t(s),r(r.P+r.F*a(function(){var t=""[e]('"');return t!==t.toLowerCase()||t.split('"').length>3;}),"String",n);};},function(e,t,n){var r=n(13),a=n(28),i=n(38),o=n(78)("src"),s=Function.toString,u=(""+s).split("toString");n(43).inspectSource=function(e){return s.call(e);},(e.exports=function(e,t,n,s){var c="function"==typeof n;c&&(i(n,"name")||a(n,"name",t)),e[t]!==n&&(c&&(i(n,o)||a(n,o,e[t]?""+e[t]:u.join(String(t)))),e===r?e[t]=n:s?e[t]?e[t]=n:a(e,t,n):(delete e[t],a(e,t,n)));})(Function.prototype,"toString",function(){return"function"==typeof this&&this[o]||s.call(this);});},function(e,t,n){var r=n(18),a=n(79);e.exports=n(19)?function(e,t,n){return r.f(e,t,a(1,n));}:function(e,t,n){return e[t]=n,e;};},function(e,t,n){"use strict";t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e};}(n(297));t.default=function(){function e(e,t){for(var n=0;n<t.length;n++){var a=t[n];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),(0,r.default)(e,a.key,a);}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t;};}();},function(e,t,n){"use strict";t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function");};},function(e,t,n){"use strict";t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e};}(n(64));t.default=function(e){return function(){var t=e.apply(this,arguments);return new r.default(function(e,n){return function a(i,o){try{var s=t[i](o),u=s.value;}catch(e){return void n(e);}if(!s.done)return r.default.resolve(u).then(function(e){a("next",e);},function(e){a("throw",e);});e(u);}("next");});};};},function(e,t,n){e.exports=n(316);},function(e,t){e.exports=function(){throw new Error("define cannot be used indirect");};},function(e,t,n){var r=n(25),a=n(21),i=n(85),o=n(69),s=n(68),u=function u(e,t,n){var c,l,f,p=e&u.F,h=e&u.G,d=e&u.S,m=e&u.P,g=e&u.B,y=e&u.W,v=h?a:a[t]||(a[t]={}),b=v.prototype,w=h?r:d?r[t]:(r[t]||{}).prototype;for(c in h&&(n=t),n){(l=!p&&w&&void 0!==w[c])&&s(v,c)||(f=l?w[c]:n[c],v[c]=h&&"function"!=typeof w[c]?n[c]:g&&l?i(f,r):y&&w[c]==f?function(e){var t=function t(_t2,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e();case 1:return new e(_t2);case 2:return new e(_t2,n);}return new e(_t2,n,r);}return e.apply(this,arguments);};return t.prototype=e.prototype,t;}(f):m&&"function"==typeof f?i(Function.call,f):f,m&&((v.virtual||(v.virtual={}))[c]=f,e&u.R&&b&&!b[c]&&o(b,c,f)));}};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,e.exports=u;},function(e,t,n){var r=n(38),a=n(22),i=n(168)("IE_PROTO"),o=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=a(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?o:null;};},function(e,t,n){var r=n(99),a=n(79),i=n(37),o=n(50),s=n(38),u=n(226),c=Object.getOwnPropertyDescriptor;t.f=n(19)?c:function(e,t){if(e=i(e),t=o(t,!0),u)try{return c(e,t);}catch(e){}if(s(e,t))return a(!r.f.call(e,t),e[t]);};},function(e,t,n){var r=n(100),a=n(49);e.exports=function(e){return r(a(e));};},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t);};},function(e,t,n){"use strict";n.d(t,"a",function(){return f;});var r=n(2),a=n(3),i=n(7),o=n(0),s=n(8),u=n(4),c=n(1),l=function l(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},f=function(){function e(){}return e.logSumExp=function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1),o.assertArgumentsAreTensors({x:e},"logSumExp");var r=s.g(t,e.shape),a=e.max(r,!0),i=e.sub(a).exp().sum(r).log(),u=a.reshape(i.shape).add(i);if(n){var c=s.c(u.shape,r);return u.reshape(c);}return u;},e.sum=function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1),o.assertArgumentsAreTensors({x:e},"sum"),"bool"===e.dtype&&(e=e.toInt());var r=s.g(t,e.shape);return Object(i.a)(function(e){var t=s.d(r,e.rank),i=r,o=e;null!=t&&(o=e.transpose(t),i=s.e(i.length,e.rank));var u=a.ENV.engine.runKernel(function(e){return e.sum(o,i);},{permutedX:o});if(n){var l=s.c(u.shape,r);u=u.reshape(l);}return{value:u,gradFunc:function gradFunc(t){var n=e.shape.slice();return r.forEach(function(e){n[e]=1;}),t.reshape(n).mul(c.rb(e.shape,"float32"));}};})(e);},e.mean=function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1),o.assertArgumentsAreTensors({x:e},"mean");var r=s.g(t,e.shape),a=s.b(e.shape,r)[1],u=o.sizeFromShape(a);return Object(i.a)(function(e){var a=c.Sb(u);return{value:(a.dtype===e.dtype?e:e.cast(a.dtype)).div(a).sum(t,n),gradFunc:function gradFunc(t){var n=e.shape.slice();return r.forEach(function(e){n[e]=1;}),t.reshape(n).mul(c.rb(e.shape,"float32")).div(a);}};})(e);},e.min=function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1),o.assertArgumentsAreTensors({x:e},"min");var r=s.g(t,e.shape),i=r,u=s.d(i,e.rank);null!=u&&(e=e.transpose(u),i=s.e(i.length,e.rank));var c=a.ENV.engine.runKernel(function(t){return t.min(e,i);},{x:e});if(n){var l=s.c(c.shape,r);return c.reshape(l);}return c;},e.max=function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1),o.assertArgumentsAreTensors({x:e},"max");var r=s.g(t,e.shape),i=r,u=s.d(i,e.rank);null!=u&&(e=e.transpose(u),i=s.e(i.length,e.rank));var c=a.ENV.engine.runKernel(function(t){return t.max(e,i);},{x:e});if(n){var l=s.c(c.shape,r);return c.reshape(l);}return c;},e.argMin=function(e,t){void 0===t&&(t=0),o.assertArgumentsAreTensors({x:e},"argMin"),null==t&&(t=0);var n=s.g(t,e.shape),r=s.d(n,e.rank);return null!=r&&(e=e.transpose(r),n=s.e(n.length,e.rank)),a.ENV.engine.runKernel(function(t){return t.argMin(e,n[0]);},{x:e});},e.argMax=function(e,t){void 0===t&&(t=0),o.assertArgumentsAreTensors({x:e},"argMax"),null==t&&(t=0);var n=s.g(t,e.shape),r=s.d(n,e.rank);return null!=r&&(e=e.transpose(r),n=s.e(n.length,e.rank)),a.ENV.engine.runKernel(function(t){return t.argMax(e,n[0]);},{x:e});},e.moments=function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1),o.assertArgumentsAreTensors({x:e},"moments");var r=s.g(t,e.shape),a=e.mean(r,n),i=a.shape;return n||(i=s.c(a.shape,r)),{mean:a,variance:e.toFloat().sub(a.reshape(i)).square().mean(r,n)};},e.unsortedSegmentSum=function(e,t,n,r){void 0===r&&(r=0),o.assertArgumentsAreTensors({x:e,segmentIds:t},"unsortedSegmentSum"),o.assert("int32"===t.dtype,"Segment Ids must be of dtype `int32`"),r=s.g(r,e.shape)[0];for(var a=[],i=t.shape[0],u=[],l=0;l<e.shape.length;l++){l===r?u.push(i):u.push(1);}var f=c.Kb(t,u);for(l=0;l<n;l++){var p=c.Sb(l,"int32"),h=c.N(p,f).asType("float32").mul(e).sum(r);a.push(h);}return c.mc(a,r);},l([Object(r.a)({heading:"Operations",subheading:"Reduction"}),u.a],e,"logSumExp",null),l([Object(r.a)({heading:"Operations",subheading:"Reduction"}),u.a],e,"sum",null),l([Object(r.a)({heading:"Operations",subheading:"Reduction"}),u.a],e,"mean",null),l([Object(r.a)({heading:"Operations",subheading:"Reduction"}),u.a],e,"min",null),l([Object(r.a)({heading:"Operations",subheading:"Reduction"}),u.a],e,"max",null),l([Object(r.a)({heading:"Operations",subheading:"Reduction"}),u.a],e,"argMin",null),l([Object(r.a)({heading:"Operations",subheading:"Reduction"}),u.a],e,"argMax",null),l([Object(r.a)({heading:"Operations",subheading:"Normalization"}),u.a],e,"moments",null),l([Object(r.a)({heading:"Operations",subheading:"Reduction"}),u.a],e,"unsortedSegmentSum",null),e;}();},function(e,t,n){"use strict";var r=n(14);e.exports=function(e,t){return!!e&&r(function(){t?e.call(null,function(){},1):e.call(null);});};},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1);};},function(e,t,n){var r=n(23);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n);};case 2:return function(n,r){return e.call(t,n,r);};case 3:return function(n,r,a){return e.call(t,n,r,a);};}return function(){return e.apply(t,arguments);};};},function(e,t){var n=e.exports={version:"2.5.7"};"number"==typeof __e&&(__e=n);},function(e,t,n){"use strict";n.d(t,"b",function(){return r;}),n.d(t,"a",function(){return c;});var r,a=n(2),i=n(0),o=n(4),s=n(1),u=function u(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;};!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS";}(r||(r={}));var c=function(){function e(){}return e.computeWeightedLoss=function(e,t,n){void 0===n&&(n=r.SUM_BY_NONZERO_WEIGHTS),i.assertArgumentsAreTensors({losses:e},"computeWeightedLoss"),null!=t&&i.assertArgumentsAreTensors({weights:t},"computeWeightedLoss");var a=null==t?e:e.mul(t);if(n===r.NONE)return a;if(n===r.SUM)return a.sum();if(n===r.MEAN)return null==t?a.mean():a.sum().div(t.sum());if(n===r.SUM_BY_NONZERO_WEIGHTS){if(null==t)return a.sum().div(s.Sb(e.size));var o=t.notEqual(s.Sb(0)).sum().toFloat();return a.sum().div(o);}throw Error("Unknown reduction: "+n);},e.absoluteDifference=function(t,n,a,o){void 0===o&&(o=r.SUM_BY_NONZERO_WEIGHTS),i.assertArgumentsAreTensors({labels:t,predictions:n},"absoluteDifference"),null!=a&&i.assertArgumentsAreTensors({weights:a},"absoluteDifference"),i.assertShapesMatch(t.shape,n.shape,"Error in absoluteDifference: ");var s=t.sub(n).abs();return e.computeWeightedLoss(s,a,o);},e.meanSquaredError=function(t,n,a,o){void 0===o&&(o=r.SUM_BY_NONZERO_WEIGHTS),i.assertArgumentsAreTensors({labels:t,predictions:n},"meanSquaredError"),null!=a&&i.assertArgumentsAreTensors({weights:a},"meanSquaredError"),i.assertShapesMatch(t.shape,n.shape,"Error in meanSquaredError: ");var s=t.squaredDifference(n);return e.computeWeightedLoss(s,a,o);},e.cosineDistance=function(t,n,a,o,u){void 0===u&&(u=r.SUM_BY_NONZERO_WEIGHTS),i.assertArgumentsAreTensors({labels:t,predictions:n},"cosineDistance"),null!=o&&i.assertArgumentsAreTensors({weights:o},"cosineDistance"),i.assertShapesMatch(t.shape,n.shape,"Error in cosineDistance: ");var c=s.Sb(1).sub(t.mul(n).sum(a,!0));return e.computeWeightedLoss(c,o,u);},e.hingeLoss=function(t,n,a,o){void 0===o&&(o=r.SUM_BY_NONZERO_WEIGHTS),i.assertArgumentsAreTensors({labels:t,predictions:n},"hingeLoss"),null!=a&&i.assertArgumentsAreTensors({weights:a},"hingeLoss"),i.assertShapesMatch(t.shape,n.shape,"Error in hingeLoss: ");var u=s.Sb(1);t=s.Sb(2).mul(t).sub(u);var c=u.sub(t.mul(n)).relu();return e.computeWeightedLoss(c,a,o);},e.logLoss=function(t,n,a,o,u){void 0===o&&(o=1e-7),void 0===u&&(u=r.SUM_BY_NONZERO_WEIGHTS),i.assertArgumentsAreTensors({labels:t,predictions:n},"logLoss"),null!=a&&i.assertArgumentsAreTensors({weights:a},"logLoss"),i.assertShapesMatch(t.shape,n.shape,"Error in logLoss: ");var c=s.Sb(1),l=s.Sb(o),f=t.mul(n.add(l).log()).neg().sub(c.sub(t).mul(c.sub(n).add(l).log()));return e.computeWeightedLoss(f,a,u);},e.huberLoss=function(t,n,a,o,u){void 0===o&&(o=1),void 0===u&&(u=r.SUM_BY_NONZERO_WEIGHTS),i.assertArgumentsAreTensors({labels:t,predictions:n},"huberLoss"),null!=a&&i.assertArgumentsAreTensors({weights:a},"huberLoss"),i.assertShapesMatch(t.shape,n.shape,"Error in huberLoss: ");var c=s.Sb(o),l=n.sub(t).abs(),f=s.cb(l,c),p=l.sub(f),h=s.Sb(.5).mul(f.square()).add(c.mul(p));return e.computeWeightedLoss(h,a,u);},u([Object(a.a)({heading:"Training",subheading:"Losses",namespace:"losses"}),o.a],e,"computeWeightedLoss",null),u([Object(a.a)({heading:"Training",subheading:"Losses",namespace:"losses"}),o.a],e,"absoluteDifference",null),u([Object(a.a)({heading:"Training",subheading:"Losses",namespace:"losses"}),o.a],e,"meanSquaredError",null),u([Object(a.a)({heading:"Training",subheading:"Losses",namespace:"losses"}),o.a],e,"cosineDistance",null),u([Object(a.a)({heading:"Training",subheading:"Losses",namespace:"losses"}),o.a],e,"hingeLoss",null),u([Object(a.a)({heading:"Training",subheading:"Losses",namespace:"losses"}),o.a],e,"logLoss",null),u([Object(a.a)({heading:"Training",subheading:"Losses",namespace:"losses"}),o.a],e,"huberLoss",null),e;}();},function(e,t,n){var r=n(58);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e;};},function(e,t,n){var r=n(42),a=n(100),i=n(22),o=n(17),s=n(151);e.exports=function(e,t){var n=1==e,u=2==e,c=3==e,l=4==e,f=6==e,p=5==e||f,h=t||s;return function(t,s,d){for(var m,g,y=i(t),v=a(y),b=r(s,d,3),w=o(v.length),x=0,k=n?h(t,w):u?h(t,0):void 0;w>x;x++){if((p||x in v)&&(g=b(m=v[x],x,y),e))if(n)k[x]=g;else if(g)switch(e){case 3:return!0;case 5:return m;case 6:return x;case 2:k.push(m);}else if(l)return!1;}return f?-1:c||l?l:k;};};},function(e,t,n){var r=n(5),a=n(43),i=n(14);e.exports=function(e,t){var n=(a.Object||{})[e]||Object[e],o={};o[e]=t(n),r(r.S+r.F*i(function(){n(1);}),"Object",o);};},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e);};},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e;};},function(e,t,n){var r=n(15);e.exports=function(e,t){if(!r(e))return e;var n,a;if(t&&"function"==typeof(n=e.toString)&&!r(a=n.call(e)))return a;if("function"==typeof(n=e.valueOf)&&!r(a=n.call(e)))return a;if(!t&&"function"==typeof(n=e.toString)&&!r(a=n.call(e)))return a;throw TypeError("Can't convert object to primitive value");};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return t&&e.then(function(e){return t(void 0,e),e;}).catch(function(e){return t(e),e;}),e;};},function(e,t,n){var r=n(45),a=n(192),i=n(143),o=Object.defineProperty;t.f=n(57)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),a)try{return o(e,t,n);}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e;};},function(e,t,n){var r=n(205),a=n(5),i=n(121)("metadata"),o=i.store||(i.store=new(n(202))()),s=function s(e,t,n){var a=o.get(e);if(!a){if(!n)return;o.set(e,a=new r());}var i=a.get(t);if(!i){if(!n)return;a.set(t,i=new r());}return i;};e.exports={store:o,map:s,has:function has(e,t,n){var r=s(t,n,!1);return void 0!==r&&r.has(e);},get:function get(e,t,n){var r=s(t,n,!1);return void 0===r?void 0:r.get(e);},set:function set(e,t,n,r){s(n,r,!0).set(e,t);},keys:function keys(e,t){var n=s(e,t,!1),r=[];return n&&n.forEach(function(e,t){r.push(t);}),r;},key:function key(e){return void 0===e||"symbol"==(typeof e==="undefined"?"undefined":_typeof(e))?e:String(e);},exp:function exp(e){a(a.S,"Reflect",e);}};},function(e,t,n){"use strict";if(n(19)){var r=n(60),a=n(13),i=n(14),o=n(5),s=n(110),u=n(145),c=n(42),l=n(72),f=n(79),p=n(28),h=n(70),d=n(48),m=n(17),g=n(200),y=n(76),v=n(50),b=n(38),w=n(98),x=n(15),k=n(22),O=n(154),S=n(75),N=n(35),E=n(74).f,I=n(152),T=n(78),A=n(16),C=n(46),P=n(120),_=n(113),R=n(149),M=n(87),j=n(116),D=n(73),L=n(150),z=n(210),F=n(18),B=n(36),V=F.f,U=B.f,W=a.RangeError,G=a.TypeError,q=a.Uint8Array,H=Array.prototype,K=u.ArrayBuffer,X=u.DataView,J=C(0),Y=C(2),Q=C(3),Z=C(4),$=C(5),ee=C(6),te=P(!0),ne=P(!1),re=R.values,ae=R.keys,ie=R.entries,oe=H.lastIndexOf,se=H.reduce,ue=H.reduceRight,ce=H.join,le=H.sort,fe=H.slice,pe=H.toString,he=H.toLocaleString,de=A("iterator"),me=A("toStringTag"),ge=T("typed_constructor"),ye=T("def_constructor"),ve=s.CONSTR,be=s.TYPED,we=s.VIEW,xe=C(1,function(e,t){return Ee(_(e,e[ye]),t);}),ke=i(function(){return 1===new q(new Uint16Array([1]).buffer)[0];}),Oe=!!q&&!!q.prototype.set&&i(function(){new q(1).set({});}),Se=function Se(e,t){var n=d(e);if(n<0||n%t)throw W("Wrong offset!");return n;},Ne=function Ne(e){if(x(e)&&be in e)return e;throw G(e+" is not a typed array!");},Ee=function Ee(e,t){if(!(x(e)&&ge in e))throw G("It is not a typed array constructor!");return new e(t);},Ie=function Ie(e,t){return Te(_(e,e[ye]),t);},Te=function Te(e,t){for(var n=0,r=t.length,a=Ee(e,r);r>n;){a[n]=t[n++];}return a;},Ae=function Ae(e,t,n){V(e,t,{get:function get(){return this._d[n];}});},Ce=function Ce(e){var t,n,r,a,i,o,s=k(e),u=arguments.length,l=u>1?arguments[1]:void 0,f=void 0!==l,p=I(s);if(void 0!=p&&!O(p)){for(o=p.call(s),r=[],t=0;!(i=o.next()).done;t++){r.push(i.value);}s=r;}for(f&&u>2&&(l=c(l,arguments[2],2)),t=0,n=m(s.length),a=Ee(this,n);n>t;t++){a[t]=f?l(s[t],t):s[t];}return a;},Pe=function Pe(){for(var e=0,t=arguments.length,n=Ee(this,t);t>e;){n[e]=arguments[e++];}return n;},_e=!!q&&i(function(){he.call(new q(1));}),Re=function Re(){return he.apply(_e?fe.call(Ne(this)):Ne(this),arguments);},Me={copyWithin:function copyWithin(e,t){return z.call(Ne(this),e,t,arguments.length>2?arguments[2]:void 0);},every:function every(e){return Z(Ne(this),e,arguments.length>1?arguments[1]:void 0);},fill:function fill(e){return L.apply(Ne(this),arguments);},filter:function filter(e){return Ie(this,Y(Ne(this),e,arguments.length>1?arguments[1]:void 0));},find:function find(e){return $(Ne(this),e,arguments.length>1?arguments[1]:void 0);},findIndex:function findIndex(e){return ee(Ne(this),e,arguments.length>1?arguments[1]:void 0);},forEach:function forEach(e){J(Ne(this),e,arguments.length>1?arguments[1]:void 0);},indexOf:function indexOf(e){return ne(Ne(this),e,arguments.length>1?arguments[1]:void 0);},includes:function includes(e){return te(Ne(this),e,arguments.length>1?arguments[1]:void 0);},join:function join(e){return ce.apply(Ne(this),arguments);},lastIndexOf:function lastIndexOf(e){return oe.apply(Ne(this),arguments);},map:function map(e){return xe(Ne(this),e,arguments.length>1?arguments[1]:void 0);},reduce:function reduce(e){return se.apply(Ne(this),arguments);},reduceRight:function reduceRight(e){return ue.apply(Ne(this),arguments);},reverse:function reverse(){for(var e,t=Ne(this).length,n=Math.floor(t/2),r=0;r<n;){e=this[r],this[r++]=this[--t],this[t]=e;}return this;},some:function some(e){return Q(Ne(this),e,arguments.length>1?arguments[1]:void 0);},sort:function sort(e){return le.call(Ne(this),e);},subarray:function subarray(e,t){var n=Ne(this),r=n.length,a=y(e,r);return new(_(n,n[ye]))(n.buffer,n.byteOffset+a*n.BYTES_PER_ELEMENT,m((void 0===t?r:y(t,r))-a));}},je=function je(e,t){return Ie(this,fe.call(Ne(this),e,t));},De=function De(e){Ne(this);var t=Se(arguments[1],1),n=this.length,r=k(e),a=m(r.length),i=0;if(a+t>n)throw W("Wrong length!");for(;i<a;){this[t+i]=r[i++];}},Le={entries:function entries(){return ie.call(Ne(this));},keys:function keys(){return ae.call(Ne(this));},values:function values(){return re.call(Ne(this));}},ze=function ze(e,t){return x(e)&&e[be]&&"symbol"!=(typeof t==="undefined"?"undefined":_typeof(t))&&t in e&&String(+t)==String(t);},Fe=function Fe(e,t){return ze(e,t=v(t,!0))?f(2,e[t]):U(e,t);},Be=function Be(e,t,n){return!(ze(e,t=v(t,!0))&&x(n)&&b(n,"value"))||b(n,"get")||b(n,"set")||n.configurable||b(n,"writable")&&!n.writable||b(n,"enumerable")&&!n.enumerable?V(e,t,n):(e[t]=n.value,e);};ve||(B.f=Fe,F.f=Be),o(o.S+o.F*!ve,"Object",{getOwnPropertyDescriptor:Fe,defineProperty:Be}),i(function(){pe.call({});})&&(pe=he=function he(){return ce.call(this);});var Ve=h({},Me);h(Ve,Le),p(Ve,de,Le.values),h(Ve,{slice:je,set:De,constructor:function constructor(){},toString:pe,toLocaleString:Re}),Ae(Ve,"buffer","b"),Ae(Ve,"byteOffset","o"),Ae(Ve,"byteLength","l"),Ae(Ve,"length","e"),V(Ve,me,{get:function get(){return this[be];}}),e.exports=function(e,t,n,u){var c=e+((u=!!u)?"Clamped":"")+"Array",f="get"+e,h="set"+e,d=a[c],y=d||{},v=d&&N(d),b=!d||!s.ABV,k={},O=d&&d.prototype,I=function I(e,n){V(e,n,{get:function get(){return function(e,n){var r=e._d;return r.v[f](n*t+r.o,ke);}(this,n);},set:function set(e){return function(e,n,r){var a=e._d;u&&(r=(r=Math.round(r))<0?0:r>255?255:255&r),a.v[h](n*t+a.o,r,ke);}(this,n,e);},enumerable:!0});};b?(d=n(function(e,n,r,a){l(e,d,c,"_d");var i,o,s,u,f=0,h=0;if(x(n)){if(!(n instanceof K||"ArrayBuffer"==(u=w(n))||"SharedArrayBuffer"==u))return be in n?Te(d,n):Ce.call(d,n);i=n,h=Se(r,t);var y=n.byteLength;if(void 0===a){if(y%t)throw W("Wrong length!");if((o=y-h)<0)throw W("Wrong length!");}else if((o=m(a)*t)+h>y)throw W("Wrong length!");s=o/t;}else s=g(n),i=new K(o=s*t);for(p(e,"_d",{b:i,o:h,l:o,e:s,v:new X(i)});f<s;){I(e,f++);}}),O=d.prototype=S(Ve),p(O,"constructor",d)):i(function(){d(1);})&&i(function(){new d(-1);})&&j(function(e){new d(),new d(null),new d(1.5),new d(e);},!0)||(d=n(function(e,n,r,a){var i;return l(e,d,c),x(n)?n instanceof K||"ArrayBuffer"==(i=w(n))||"SharedArrayBuffer"==i?void 0!==a?new y(n,Se(r,t),a):void 0!==r?new y(n,Se(r,t)):new y(n):be in n?Te(d,n):Ce.call(d,n):new y(g(n));}),J(v!==Function.prototype?E(y).concat(E(v)):E(y),function(e){e in d||p(d,e,y[e]);}),d.prototype=O,r||(O.constructor=d));var T=O[de],A=!!T&&("values"==T.name||void 0==T.name),C=Le.values;p(d,ge,!0),p(O,be,c),p(O,we,!0),p(O,ye,d),(u?new d(1)[me]==c:me in O)||V(O,me,{get:function get(){return c;}}),k[c]=d,o(o.G+o.W+o.F*(d!=y),k),o(o.S,c,{BYTES_PER_ELEMENT:t}),o(o.S+o.F*i(function(){y.of.call(d,1);}),c,{from:Ce,of:Pe}),"BYTES_PER_ELEMENT"in O||p(O,"BYTES_PER_ELEMENT",t),o(o.P,c,Me),D(c),o(o.P+o.F*Oe,c,{set:De}),o(o.P+o.F*!A,c,Le),r||O.toString==pe||(O.toString=pe),o(o.P+o.F*i(function(){new d(1).slice();}),c,{slice:je}),o(o.P+o.F*(i(function(){return[1,2].toLocaleString()!=new d([1,2]).toLocaleString();})||!i(function(){O.toLocaleString.call([1,2]);})),c,{toLocaleString:Re}),M[c]=A?T:C,r||A||p(O,de,C);};}else e.exports=function(){};},function(e,t,n){"use strict";n.d(t,"b",function(){return r;}),n.d(t,"a",function(){return a;});var r=1.7580993408473768,a=1.0507009873554805;},function(e,t,n){"use strict";t.__esModule=!0;var r=o(n(293)),a=o(n(291)),i="function"==typeof a.default&&"symbol"==_typeof(r.default)?function(e){return typeof e==="undefined"?"undefined":_typeof(e);}:function(e){return e&&"function"==typeof a.default&&e.constructor===a.default&&e!==a.default.prototype?"symbol":typeof e==="undefined"?"undefined":_typeof(e);};function o(e){return e&&e.__esModule?e:{default:e};}t.default="function"==typeof a.default&&"symbol"===i(r.default)?function(e){return void 0===e?"undefined":i(e);}:function(e){return e&&"function"==typeof a.default&&e.constructor===a.default&&e!==a.default.prototype?"symbol":void 0===e?"undefined":i(e);};},function(e,t,n){e.exports=!n(84)(function(){return 7!=Object.defineProperty({},"a",{get:function get(){return 7;}}).a;});},function(e,t){e.exports=function(e){return"object"==(typeof e==="undefined"?"undefined":_typeof(e))?null!==e:"function"==typeof e;};},function(e,t,n){var r=n(16)("unscopables"),a=Array.prototype;void 0==a[r]&&n(28)(a,r,{}),e.exports=function(e){a[r][e]=!0;};},function(e,t){e.exports=!1;},function(e,t,n){var r=n(78)("meta"),a=n(15),i=n(38),o=n(18).f,s=0,u=Object.isExtensible||function(){return!0;},c=!n(14)(function(){return u(Object.preventExtensions({}));}),l=function l(e){o(e,r,{value:{i:"O"+ ++s,w:{}}});},f=e.exports={KEY:r,NEED:!1,fastKey:function fastKey(e,t){if(!a(e))return"symbol"==(typeof e==="undefined"?"undefined":_typeof(e))?e:("string"==typeof e?"S":"P")+e;if(!i(e,r)){if(!u(e))return"F";if(!t)return"E";l(e);}return e[r].i;},getWeak:function getWeak(e,t){if(!i(e,r)){if(!u(e))return!0;if(!t)return!1;l(e);}return e[r].w;},onFreeze:function onFreeze(e){return c&&f.NEED&&u(e)&&!i(e,r)&&l(e),e;}};},function(e,t,n){"use strict";n.d(t,"a",function(){return a;}),n.d(t,"c",function(){return i;}),n.d(t,"b",function(){return o;});var r=n(0);function a(e,t,n){var a=e.length,i=t.length;r.assert(e.length===t.length,"Error in concat"+a+"D: rank of x1 ("+a+") and x2 ("+i+") must be the same."),r.assert(n>=0&&n<a,"Error in concat"+a+"D: axis must be between 0 and "+(a-1)+".");for(var o=0;o<a;o++){r.assert(o===n||e[o]===t[o],"Error in concat"+a+"D: Shape ("+e+") does not match ("+t+") along the non-concatenated axis "+o+".");}}function i(e,t,n){r.assert(e.length===t.length,"x1 and x2 should have the same rank.");var a=e.slice();return a[n]+=t[n],a;}function o(e,t){return{aBegin:[0,0],aSize:e,bBegin:[0,e[1]],bSize:t};}},function(e,t,n){"use strict";n.d(t,"a",function(){return c;});var r=n(2),a=n(3),i=n(0),o=n(8),s=n(62),u=n(4),c=function(){function e(){}return e.concat1d=function(t){return e.concat(t,0);},e.concat2d=function(t,n){return e.concat(t,n);},e.concat3d=function(t,n){return e.concat(t,n);},e.concat4d=function(t,n){return e.concat(t,n);},e.concat=function(e,t){void 0===t&&(t=0),i.assert(e.length>=1,"Pass at least one tensor to concat"),i.assertArgumentsAreTensors({tensors:e},"concat");var n=e[0];if(1===e.length)return n;for(var r=Object(o.g)(t,n.shape),a=1;a<e.length;++a){n=l(n,e[a],r[0]);}return n;},function(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}i>3&&o&&Object.defineProperty(t,n,o);}([Object(r.a)({heading:"Tensors",subheading:"Slicing and Joining"}),u.a],e,"concat",null),e;}();function l(e,t,n){s.a(e.shape,t.shape,n);var r=s.c(e.shape,t.shape,n),o=e.as2D(-1,i.sizeFromShape(e.shape.slice(n))),u=t.as2D(-1,i.sizeFromShape(t.shape.slice(n))),c=s.b(o.shape,u.shape),l=c.aBegin,f=c.aSize,p=c.bBegin,h=c.bSize;return a.ENV.engine.runKernel(function(e){return e.concat(o,u);},{a:o,b:u},function(e){return{a:function a(){return e.slice(l,f);},b:function b(){return e.slice(p,h);}};}).reshape(r);}},function(e,t,n){e.exports={default:n(314),__esModule:!0};},function(e,t,n){"use strict";(function(e){var r=t;function a(e,t,n){for(var r=Object.keys(t),a=0;a<r.length;++a){void 0!==e[r[a]]&&n||(e[r[a]]=t[r[a]]);}return e;}function i(e){function t(e,n){if(!(this instanceof t))return new t(e,n);Object.defineProperty(this,"message",{get:function get(){return e;}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:new Error().stack||""}),n&&a(this,n);}return(t.prototype=Object.create(Error.prototype)).constructor=t,Object.defineProperty(t.prototype,"name",{get:function get(){return e;}}),t.prototype.toString=function(){return this.name+": "+this.message;},t;}r.asPromise=n(330),r.base64=n(329),r.EventEmitter=n(328),r.float=n(327),r.inquire=n(326),r.utf8=n(325),r.pool=n(324),r.LongBits=n(323),r.emptyArray=Object.freeze?Object.freeze([]):[],r.emptyObject=Object.freeze?Object.freeze({}):{},r.isNode=Boolean(e.process&&e.process.versions&&e.process.versions.node),r.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e;},r.isString=function(e){return"string"==typeof e||e instanceof String;},r.isObject=function(e){return e&&"object"==(typeof e==="undefined"?"undefined":_typeof(e));},r.isset=r.isSet=function(e,t){var n=e[t];return!(null==n||!e.hasOwnProperty(t))&&("object"!=(typeof n==="undefined"?"undefined":_typeof(n))||(Array.isArray(n)?n.length:Object.keys(n).length)>0);},r.Buffer=function(){try{var e=r.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null;}catch(e){return null;}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(e){return"number"==typeof e?r.Buffer?r._Buffer_allocUnsafe(e):new r.Array(e):r.Buffer?r._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e);},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=e.dcodeIO&&e.dcodeIO.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(e){return e?r.LongBits.from(e).toHash():r.LongBits.zeroHash;},r.longFromHash=function(e,t){var n=r.LongBits.fromHash(e);return r.Long?r.Long.fromBits(n.lo,n.hi,t):n.toNumber(Boolean(t));},r.merge=a,r.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1);},r.newError=i,r.ProtocolError=i("ProtocolError"),r.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n){t[e[n]]=1;}return function(){for(var e=Object.keys(this),n=e.length-1;n>-1;--n){if(1===t[e[n]]&&void 0!==this[e[n]]&&null!==this[e[n]])return e[n];}};},r.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n){e[n]!==t&&delete this[e[n]];}};},r.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},r._configure=function(){var e=r.Buffer;e?(r._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,n){return new e(t,n);},r._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t);}):r._Buffer_from=r._Buffer_allocUnsafe=null;};}).call(this,n(101));},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function get(){return e.l;}}),Object.defineProperty(e,"id",{enumerable:!0,get:function get(){return e.i;}}),e.webpackPolyfill=1),e;};},function(e,t,n){var r=n(190),a=n(142);e.exports=function(e){return r(a(e));};},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t);};},function(e,t,n){var r=n(52),a=n(97);e.exports=n(57)?function(e,t,n){return r.f(e,t,a(1,n));}:function(e,t,n){return e[t]=n,e;};},function(e,t,n){var r=n(27);e.exports=function(e,t,n){for(var a in t){r(e,a,t[a],n);}return e;};},function(e,t,n){var r=n(42),a=n(212),i=n(154),o=n(12),s=n(17),u=n(152),c={},l={};(t=e.exports=function(e,t,n,f,p){var h,d,m,g,y=p?function(){return e;}:u(e),v=r(n,f,t?2:1),b=0;if("function"!=typeof y)throw TypeError(e+" is not iterable!");if(i(y)){for(h=s(e.length);h>b;b++){if((g=t?v(o(d=e[b])[0],d[1]):v(e[b]))===c||g===l)return g;}}else for(m=y.call(e);!(d=m.next()).done;){if((g=a(m,v,d.value,t))===c||g===l)return g;}}).BREAK=c,t.RETURN=l;},function(e,t){e.exports=function(e,t,n,r){if(!(e instanceof t)||void 0!==r&&r in e)throw TypeError(n+": incorrect invocation!");return e;};},function(e,t,n){"use strict";var r=n(13),a=n(18),i=n(19),o=n(16)("species");e.exports=function(e){var t=r[e];i&&t&&!t[o]&&a.f(t,o,{configurable:!0,get:function get(){return this;}});};},function(e,t,n){var r=n(224),a=n(167).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,a);};},function(e,t,n){var r=n(12),a=n(223),i=n(167),o=n(168)("IE_PROTO"),s=function s(){},_u2=function u(){var e,t=n(170)("iframe"),r=i.length;for(t.style.display="none",n(166).appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),_u2=e.F;r--;){delete _u2.prototype[i[r]];}return _u2();};e.exports=Object.create||function(e,t){var n;return null!==e?(s.prototype=r(e),n=new s(),s.prototype=null,n[o]=e):n=_u2(),void 0===t?n:a(n,t);};},function(e,t,n){var r=n(48),a=Math.max,i=Math.min;e.exports=function(e,t){return(e=r(e))<0?a(e+t,0):i(e,t);};},function(e,t,n){var r=n(224),a=n(167);e.exports=Object.keys||function(e){return r(e,a);};},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36));};},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t};};},function(e,t,n){"use strict";n.d(t,"a",function(){return s;});var r=n(2),a=n(3),i=n(0),o=function o(e,t,n,r){var a,i=arguments.length,o=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==(typeof Reflect==="undefined"?"undefined":_typeof(Reflect))&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--){(a=e[s])&&(o=(i<3?a(o):i>3?a(t,n,o):a(t,n))||o);}return i>3&&o&&Object.defineProperty(t,n,o),o;},s=function(){function e(){}return e.tidy=function(e,t,n){void 0===n&&(n=!1);var r=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e;}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");r=e;}a.ENV.engine.startScope(r,n);var i=t();return i instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),a.ENV.engine.endScope(i,n),i;},e.dispose=function(e){Object(i.extractTensorsFromAny)(e).forEach(function(e){return e.dispose();});},e.keep=function(e){return a.ENV.engine.keep(e);},e.time=function(e){return a.ENV.engine.time(e);},o([Object(r.a)({heading:"Performance",subheading:"Memory"})],e,"tidy",null),o([Object(r.a)({heading:"Performance",subheading:"Memory"})],e,"keep",null),o([Object(r.a)({heading:"Performance",subheading:"Timing"})],e,"time",null),e;}();},function(e,t){e.exports={};},function(e,t){(function(t){e.exports=t;}).call(this,{});},function(e,t,n){var r=n(191),a=n(137);e.exports=Object.keys||function(e){return r(e,a);};},function(e,t){e.exports=function(e){try{return!!e();}catch(e){return!0;}};},function(e,t,n){var r=n(106);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n);};case 2:return function(n,r){return e.call(t,n,r);};case 3:return function(n,r,a){return e.call(t,n,r,a);};}return function(){return e.apply(t,arguments);};};},function(e,t,n){var r=n(15);e.exports=function(e,t){if(!r(e)||e._t!==t)throw TypeError("Incompatible receiver, "+t+" required!");return e;};},function(e,t){e.exports={};},function(e,t,n){var r=n(5),a=n(49),i=n(14),o=n(164),s="["+o+"]",u=RegExp("^"+s+s+"*"),c=RegExp(s+s+"*$"),l=function l(e,t,n){var a={},s=i(function(){return!!o[e]()||"​…"!="​…"[e]();}),u=a[e]=s?t(f):o[e];n&&(a[n]=u),r(r.P+r.F*s,"String",a);},f=l.trim=function(e,t){return e=String(a(e)),1&t&&(e=e.replace(u,"")),2&t&&(e=e.replace(c,"")),e;};e.exports=l;},function(e,t,n){var r=n(18).f,a=n(38),i=n(16)("toStringTag");e.exports=function(e,t,n){e&&!a(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t});};},function(e,t,n){"use strict";n.d(t,"a",function(){return a;}),n.d(t,"b",function(){return i;});var r=n(0);function a(e,t,n){r.assert(e.rank===t.length,"Error in slice"+e.rank+"D: Length of begin "+t+" must match the rank of the array ("+e.rank+")."),r.assert(e.rank===n.length,"Error in slice"+e.rank+"D: Length of size "+n+" must match the rank of the array ("+e.rank+").");for(var a=0;a<e.rank;++a){r.assert(t[a]+n[a]<=e.shape[a],"Error in slice"+e.rank+"D: begin["+a+"] + size["+a+"] ("+(t[a]+n[a])+") would overflow input.shape["+a+"] ("+e.shape[a]+")");}}function i(e,t,n,r,a,i){void 0===a&&(a=0),void 0===i&&(i=0);for(var u=[],c=[],l=0;l<e.length;l++){u[l]=o(a,t,r,e,l),c[l]=s(i,n,r,e,l);}var f=new Array(e.length).fill(0);return f=f.map(function(e,t){for(var n=0,a=u[t];!(r[t]>0?a>=c[t]:a<=c[t]);a+=r[t]){n+=1;}return n;}),[u,f];}function o(e,t,n,a,i){var o=t[i];e&1<<i&&(o=n[i]>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=a[i];return o<0&&(o+=s),r.clamp(0,o,s-1);}function s(e,t,n,a,i){var o=t[i];e&1<<i&&(o=n[i]>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=a[i];return o<0&&(o+=s),n[i]>0?r.clamp(0,o,s):r.clamp(-1,o,s-1);}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.imgToTensor=t.cropImage=t.processVideo=t.array3DToImage=void 0;var r=function(e){return e&&e.__esModule?e:{default:e};}(n(128)),a=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}(n(10)),i=function i(e){var t=Math.min(e.shape[0],e.shape[1]),n=e.shape[0]/2-t/2,r=e.shape[1]/2-t/2;return e.slice([n,r,0],[t,t,3]);};t.array3DToImage=function(e){var t=(0,r.default)(e.shape,2),n=t[0],a=t[1],i=e.dataSync(),o=document.createElement("canvas");o.width=n,o.height=a;for(var s=o.getContext("2d"),u=s.getImageData(0,0,o.width,o.height),c=0;c<n*a;c+=1){var l=4*c,f=3*c;u.data[l+0]=Math.floor(256*i[f+0]),u.data[l+1]=Math.floor(256*i[f+1]),u.data[l+2]=Math.floor(256*i[f+2]),u.data[l+3]=255;}s.putImageData(u,0,0);var p=o.toDataURL(),h=document.createElement("img");return h.src=p,h.style.width=n,h.style.height=a,h;},t.processVideo=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){},r=e,a=document.createElement("video");return r.onplay=function(){var e=r.captureStream();a.srcObject=e,a.width=t,a.height=t,a.autoplay=!0,a.playsinline=!0,a.muted=!0,n();},a;},t.cropImage=i,t.imgToTensor=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return a.tidy(function(){var n=a.fromPixels(e);return t&&(n=a.image.resizeBilinear(n,t)),i(n).expandDims(0).toFloat().div(a.scalar(127)).sub(a.scalar(1));});};},function(e,t,n){"use strict";var r=n(313)(!0);n(186)(String,"String",function(e){this._t=String(e),this._i=0;},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1});});},function(e,t,n){var r=n(142);e.exports=function(e){return Object(r(e));};},function(e,t){t.f={}.propertyIsEnumerable;},function(e,t){e.exports=!0;},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1);};},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t};};},function(e,t,n){var r=n(41),a=n(16)("toStringTag"),i="Arguments"==r(function(){return arguments;}());e.exports=function(e){var t,n,o;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t];}catch(e){}}(t=Object(e),a))?n:i?r(t):"Object"==(o=r(t))&&"function"==typeof t.callee?"Arguments":o;};},function(e,t){t.f={}.propertyIsEnumerable;},function(e,t,n){var r=n(41);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e);};},function(e,t){var n;n=function(){return this;}();try{n=n||Function("return this")()||(0,eval)("this");}catch(e){"object"==(typeof window==="undefined"?"undefined":_typeof(window))&&(n=window);}e.exports=n;},function(e,t,n){"use strict";e.exports=n(331);},function(e,t,n){n(310);for(var r=n(25),a=n(69),i=n(81),o=n(24)("toStringTag"),s="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(","),u=0;u<s.length;u++){var c=s[u],l=r[c],f=l&&l.prototype;f&&!f[o]&&a(f,o,c),i[c]=i.Array;}},function(e,t,n){var r=n(52).f,a=n(68),i=n(24)("toStringTag");e.exports=function(e,t,n){e&&!a(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t});};},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36));};},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e;};},function(e,t,n){"use strict";var r=n(5),a=n(23),i=n(42),o=n(71);e.exports=function(e){r(r.S,e,{from:function from(e){var t,n,r,s,u=arguments[1];return a(this),(t=void 0!==u)&&a(u),void 0==e?new this():(n=[],t?(r=0,s=i(u,arguments[2],2),o(e,!1,function(e){n.push(s(e,r++));})):o(e,!1,n.push,n),new this(n));}});};},function(e,t,n){"use strict";var r=n(5);e.exports=function(e){r(r.S,e,{of:function of(){for(var e=arguments.length,t=new Array(e);e--;){t[e]=arguments[e];}return new this(t);}});};},function(e,t,n){"use strict";e.exports=n(60)||!n(14)(function(){var e=Math.random();__defineSetter__.call(null,e,function(){}),delete n(13)[e];});},function(e,t,n){for(var r,a=n(13),i=n(28),o=n(78),s=o("typed_array"),u=o("view"),c=!(!a.ArrayBuffer||!a.DataView),l=c,f=0,p="Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array".split(",");f<9;){(r=a[p[f++]])?(i(r.prototype,s,!0),i(r.prototype,u,!0)):l=!1;}e.exports={ABV:c,CONSTR:l,TYPED:s,VIEW:u};},function(e,t,n){"use strict";var r=n(13),a=n(5),i=n(27),o=n(70),s=n(61),u=n(71),c=n(72),l=n(15),f=n(14),p=n(116),h=n(89),d=n(163);e.exports=function(e,t,n,m,g,y){var v=r[e],b=v,w=g?"set":"add",x=b&&b.prototype,k={},O=function O(e){var t=x[e];i(x,e,"delete"==e?function(e){return!(y&&!l(e))&&t.call(this,0===e?0:e);}:"has"==e?function(e){return!(y&&!l(e))&&t.call(this,0===e?0:e);}:"get"==e?function(e){return y&&!l(e)?void 0:t.call(this,0===e?0:e);}:"add"==e?function(e){return t.call(this,0===e?0:e),this;}:function(e,n){return t.call(this,0===e?0:e,n),this;});};if("function"==typeof b&&(y||x.forEach&&!f(function(){new b().entries().next();}))){var S=new b(),N=S[w](y?{}:-0,1)!=S,E=f(function(){S.has(1);}),I=p(function(e){new b(e);}),T=!y&&f(function(){for(var e=new b(),t=5;t--;){e[w](t,t);}return!e.has(-0);});I||((b=t(function(t,n){c(t,b,e);var r=d(new v(),t,b);return void 0!=n&&u(n,g,r[w],r),r;})).prototype=x,x.constructor=b),(E||T)&&(O("delete"),O("has"),g&&O("get")),(T||N)&&O(w),y&&x.clear&&delete x.clear;}else b=m.getConstructor(t,e,g,w),o(b.prototype,n),s.NEED=!0;return h(b,e),k[e]=b,a(a.G+a.W+a.F*(b!=v),k),y||m.setStrong(b,e,g),b;};},function(e,t,n){var r=n(13).navigator;e.exports=r&&r.userAgent||"";},function(e,t,n){var r=n(12),a=n(23),i=n(16)("species");e.exports=function(e,t){var n,o=r(e).constructor;return void 0===o||void 0==(n=r(o)[i])?t:a(n);};},function(e,t,n){"use strict";var r=n(28),a=n(27),i=n(14),o=n(49),s=n(16);e.exports=function(e,t,n){var u=s(e),c=n(o,u,""[e]),l=c[0],f=c[1];i(function(){var t={};return t[u]=function(){return 7;},7!=""[e](t);})&&(a(String.prototype,e,l),r(RegExp.prototype,u,2==t?function(e,t){return f.call(e,this,t);}:function(e){return f.call(e,this);}));};},function(e,t,n){"use strict";var r=n(12);e.exports=function(){var e=r(this),t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.unicode&&(t+="u"),e.sticky&&(t+="y"),t;};},function(e,t,n){var r=n(16)("iterator"),a=!1;try{var i=[7][r]();i.return=function(){a=!0;},Array.from(i,function(){throw 2;});}catch(e){}e.exports=function(e,t){if(!t&&!a)return!1;var n=!1;try{var i=[7],o=i[r]();o.next=function(){return{done:n=!0};},i[r]=function(){return o;},e(i);}catch(e){}return n;};},function(e,t,n){var r=n(15),a=n(41),i=n(16)("match");e.exports=function(e){var t;return r(e)&&(void 0!==(t=e[i])?!!t:"RegExp"==a(e));};},function(e,t,n){var r=n(41);e.exports=Array.isArray||function(e){return"Array"==r(e);};},function(e,t){t.f=Object.getOwnPropertySymbols;},function(e,t,n){var r=n(37),a=n(17),i=n(76);e.exports=function(e){return function(t,n,o){var s,u=r(t),c=a(u.length),l=i(o,c);if(e&&n!=n){for(;c>l;){if((s=u[l++])!=s)return!0;}}else for(;c>l;l++){if((e||l in u)&&u[l]===n)return e||l||0;}return!e&&-1;};};},function(e,t,n){var r=n(43),a=n(13),i=a["__core-js_shared__"]||(a["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{});})("versions",[]).push({version:r.version,mode:n(60)?"pure":"global",copyright:"© 2018 Denis Pushkarev (zloirock.ru)"});},function(e,t,n){var r=n(344),a=n(343),i=n(342),o=n(341),s=n(340),u=n(339),c=n(338);c.alea=r,c.xor128=a,c.xorwow=i,c.xorshift7=o,c.xor4096=s,c.tychei=u,e.exports=c;},function(e,t,n){"use strict";n.d(t,"a",function(){return s;});var r=n(0),a=20,i=3,o=7;function s(e,t){var n=e.dataSync(),r=function(e){var t=e.dataSync(),n=e.size,r=e.strides[e.strides.length-1],a=new Array(r).fill(0);if(e.rank>1)for(var i=0;i<n/r;i++){for(var o=i*r,s=0;s<r;s++){a[s]=Math.max(a[s],u(t[o+s],0).length);}}return a;}(e),o=function e(t,n,r,o,s){void 0===s&&(s=!0);var c=n[0],l=n.length;if(0===l)return[t[0].toString()];if(1===l){if(c>a){var f=Array.from(t.subarray(0,i)),p=Array.from(t.subarray(c-i,c));return["["+f.map(function(e,t){return u(e,o[t]);}).join(", ")+", ..., "+p.map(function(e,t){return u(e,o[c-i+t]);}).join(", ")+"]"];}return["["+Array.from(t).map(function(e,t){return u(e,o[t]);}).join(", ")+"]"];}var h=n.slice(1),d=r.slice(1),m=r[0],g=[];if(c>a){for(var y=0;y<i;y++){var v=(b=y*m)+m;g.push.apply(g,e(t.subarray(b,v),h,d,o,!1));}g.push("...");for(y=c-i;y<c;y++){v=(b=y*m)+m;g.push.apply(g,e(t.subarray(b,v),h,d,o,y===c-1));}}else for(y=0;y<c;y++){var b;v=(b=y*m)+m;g.push.apply(g,e(t.subarray(b,v),h,d,o,y===c-1));}var w=2===l?",":"";g[0]="["+g[0]+w;for(y=1;y<g.length-1;y++){g[y]=" "+g[y]+w;}var x=",\n";for(y=2;y<l;y++){x+="\n";}return g[g.length-1]=" "+g[g.length-1]+"]"+(s?"":x),g;}(n,e.shape,e.strides,r),s=["Tensor"];return t&&(s.push(" dtype: "+e.dtype),s.push(" rank: "+e.rank),s.push(" shape: ["+e.shape+"]"),s.push(" values:")),s.push(o.map(function(e){return" "+e;}).join("\n")),s.join("\n");}function u(e,t){return r.rightPad(parseFloat(e.toFixed(o)).toString(),t);}},function(e,t,n){"use strict";t.__esModule=!0;var r=o(n(263)),a=o(n(259)),i=o(n(56));function o(e){return e&&e.__esModule?e:{default:e};}t.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,i.default)(t)));e.prototype=(0,a.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(r.default?(0,r.default)(e,t):e.__proto__=t);};},function(e,t,n){"use strict";t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e};}(n(56));t.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":(0,r.default)(t))&&"function"!=typeof t?e:t;};},function(e,t,n){e.exports={default:n(265),__esModule:!0};},function(e,t,n){e.exports={default:n(268),__esModule:!0};},function(e,t,n){"use strict";t.__esModule=!0;var r=i(n(279)),a=i(n(276));function i(e){return e&&e.__esModule?e:{default:e};}t.default=function(e,t){if(Array.isArray(e))return e;if((0,r.default)(Object(e)))return function(e,t){var n=[],r=!0,i=!1,o=void 0;try{for(var s,u=(0,a.default)(e);!(r=(s=u.next()).done)&&(n.push(s.value),!t||n.length!==t);r=!0){}}catch(e){i=!0,o=e;}finally{try{!r&&u.return&&u.return();}finally{if(i)throw o;}}return n;}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance");};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=c(n(32)),a=c(n(64)),i=c(n(31)),o=c(n(56)),s=c(n(30)),u=c(n(29));function c(e){return e&&e.__esModule?e:{default:e};}var l=function(){function e(t,n){(0,s.default)(this,e),this.videoElt=null,this.size=n,this.videoReady=!1,t instanceof HTMLVideoElement?this.videoElt=t:null!==t&&"object"===(void 0===t?"undefined":(0,o.default)(t))&&t.elt instanceof HTMLVideoElement&&(this.videoElt=t.elt);}return(0,u.default)(e,[{key:"loadVideo",value:function(){var e=(0,i.default)(r.default.mark(function e(){var t=this;return r.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.abrupt("return",new a.default(function(e){t.video=document.createElement("video");var n=t.videoElt.captureStream();t.video.srcObject=n,t.video.width=t.size,t.video.height=t.size,t.video.autoplay=!0,t.video.playsinline=!0,t.video.muted=!0;var r=t.video.play();void 0!==r&&r.then(function(){e(t.video);});}));case 1:case"end":return e.stop();}}},e,this);}));return function(){return e.apply(this,arguments);};}()}]),e;}();t.default=l;},function(e,t,n){var r=n(25),a=n(21),i=n(95),o=n(131),s=n(52).f;e.exports=function(e){var t=a.Symbol||(a.Symbol=i?{}:r.Symbol||{});"_"==e.charAt(0)||e in t||s(t,e,{value:o.f(e)});};},function(e,t,n){t.f=n(24);},function(e,t,n){"use strict";var r=n(106);e.exports.f=function(e){return new function(e){var t,n;this.promise=new e(function(e,r){if(void 0!==t||void 0!==n)throw TypeError("Bad Promise constructor");t=e,n=r;}),this.resolve=r(t),this.reject=r(n);}(e);};},function(e,t,n){var r=n(134),a=n(24)("iterator"),i=n(81);e.exports=n(21).getIteratorMethod=function(e){if(void 0!=e)return e[a]||e["@@iterator"]||i[r(e)];};},function(e,t,n){var r=n(96),a=n(24)("toStringTag"),i="Arguments"==r(function(){return arguments;}());e.exports=function(e){var t,n,o;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t];}catch(e){}}(t=Object(e),a))?n:i?r(t):"Object"==(o=r(t))&&"function"==typeof t.callee?"Arguments":o;};},function(e,t,n){var r=n(45),a=n(311),i=n(137),o=n(139)("IE_PROTO"),s=function s(){},_u3=function u(){var e,t=n(144)("iframe"),r=i.length;for(t.style.display="none",n(184).appendChild(t),t.src="javascript:",(e=t.contentWindow.document).open(),e.write("<script>document.F=Object<\/script>"),e.close(),_u3=e.F;r--;){delete _u3.prototype[i[r]];}return _u3();};e.exports=Object.create||function(e,t){var n;return null!==e?(s.prototype=r(e),n=new s(),s.prototype=null,n[o]=e):n=_u3(),void 0===t?n:a(n,t);};},function(e,t){t.f=Object.getOwnPropertySymbols;},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",");},function(e,t,n){var r=n(21),a=n(25),i=a["__core-js_shared__"]||(a["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{});})("versions",[]).push({version:r.version,mode:n(95)?"pure":"global",copyright:"© 2018 Denis Pushkarev (zloirock.ru)"});},function(e,t,n){var r=n(138)("keys"),a=n(105);e.exports=function(e){return r[e]||(r[e]=a(e));};},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e);};},function(e,t,n){var r=n(140),a=Math.min;e.exports=function(e){return e>0?a(r(e),9007199254740991):0;};},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e;};},function(e,t,n){var r=n(58);e.exports=function(e,t){if(!r(e))return e;var n,a;if(t&&"function"==typeof(n=e.toString)&&!r(a=n.call(e)))return a;if("function"==typeof(n=e.valueOf)&&!r(a=n.call(e)))return a;if(!t&&"function"==typeof(n=e.toString)&&!r(a=n.call(e)))return a;throw TypeError("Can't convert object to primitive value");};},function(e,t,n){var r=n(58),a=n(25).document,i=r(a)&&r(a.createElement);e.exports=function(e){return i?a.createElement(e):{};};},function(e,t,n){"use strict";var r=n(13),a=n(19),i=n(60),o=n(110),s=n(28),u=n(70),c=n(14),l=n(72),f=n(48),p=n(17),h=n(200),d=n(74).f,m=n(18).f,g=n(150),y=n(89),v="prototype",b="Wrong index!",_w2=r.ArrayBuffer,_x=r.DataView,k=r.Math,O=r.RangeError,S=r.Infinity,N=_w2,E=k.abs,I=k.pow,T=k.floor,A=k.log,C=k.LN2,P=a?"_b":"buffer",_=a?"_l":"byteLength",R=a?"_o":"byteOffset";function M(e,t,n){var r,a,i,o=new Array(n),s=8*n-t-1,u=(1<<s)-1,c=u>>1,l=23===t?I(2,-24)-I(2,-77):0,f=0,p=e<0||0===e&&1/e<0?1:0;for((e=E(e))!=e||e===S?(a=e!=e?1:0,r=u):(r=T(A(e)/C),e*(i=I(2,-r))<1&&(r--,i*=2),(e+=r+c>=1?l/i:l*I(2,1-c))*i>=2&&(r++,i/=2),r+c>=u?(a=0,r=u):r+c>=1?(a=(e*i-1)*I(2,t),r+=c):(a=e*I(2,c-1)*I(2,t),r=0));t>=8;o[f++]=255&a,a/=256,t-=8){}for(r=r<<t|a,s+=t;s>0;o[f++]=255&r,r/=256,s-=8){}return o[--f]|=128*p,o;}function j(e,t,n){var r,a=8*n-t-1,i=(1<<a)-1,o=i>>1,s=a-7,u=n-1,c=e[u--],l=127&c;for(c>>=7;s>0;l=256*l+e[u],u--,s-=8){}for(r=l&(1<<-s)-1,l>>=-s,s+=t;s>0;r=256*r+e[u],u--,s-=8){}if(0===l)l=1-o;else{if(l===i)return r?NaN:c?-S:S;r+=I(2,t),l-=o;}return(c?-1:1)*r*I(2,l-t);}function D(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0];}function L(e){return[255&e];}function z(e){return[255&e,e>>8&255];}function F(e){return[255&e,e>>8&255,e>>16&255,e>>24&255];}function B(e){return M(e,52,8);}function V(e){return M(e,23,4);}function U(e,t,n){m(e[v],t,{get:function get(){return this[n];}});}function W(e,t,n,r){var a=h(+n);if(a+t>e[_])throw O(b);var i=e[P]._b,o=a+e[R],s=i.slice(o,o+t);return r?s:s.reverse();}function G(e,t,n,r,a,i){var o=h(+n);if(o+t>e[_])throw O(b);for(var s=e[P]._b,u=o+e[R],c=r(+a),l=0;l<t;l++){s[u+l]=c[i?l:t-l-1];}}if(o.ABV){if(!c(function(){_w2(1);})||!c(function(){new _w2(-1);})||c(function(){return new _w2(),new _w2(1.5),new _w2(NaN),"ArrayBuffer"!=_w2.name;})){for(var q,H=(_w2=function w(e){return l(this,_w2),new N(h(e));})[v]=N[v],K=d(N),X=0;K.length>X;){(q=K[X++])in _w2||s(_w2,q,N[q]);}i||(H.constructor=_w2);}var J=new _x(new _w2(2)),Y=_x[v].setInt8;J.setInt8(0,2147483648),J.setInt8(1,2147483649),!J.getInt8(0)&&J.getInt8(1)||u(_x[v],{setInt8:function setInt8(e,t){Y.call(this,e,t<<24>>24);},setUint8:function setUint8(e,t){Y.call(this,e,t<<24>>24);}},!0);}else _w2=function _w(e){l(this,_w2,"ArrayBuffer");var t=h(e);this._b=g.call(new Array(t),0),this[_]=t;},_x=function x(e,t,n){l(this,_x,"DataView"),l(e,_w2,"DataView");var r=e[_],a=f(t);if(a<0||a>r)throw O("Wrong offset!");if(a+(n=void 0===n?r-a:p(n))>r)throw O("Wrong length!");this[P]=e,this[R]=a,this[_]=n;},a&&(U(_w2,"byteLength","_l"),U(_x,"buffer","_b"),U(_x,"byteLength","_l"),U(_x,"byteOffset","_o")),u(_x[v],{getInt8:function getInt8(e){return W(this,1,e)[0]<<24>>24;},getUint8:function getUint8(e){return W(this,1,e)[0];},getInt16:function getInt16(e){var t=W(this,2,e,arguments[1]);return(t[1]<<8|t[0])<<16>>16;},getUint16:function getUint16(e){var t=W(this,2,e,arguments[1]);return t[1]<<8|t[0];},getInt32:function getInt32(e){return D(W(this,4,e,arguments[1]));},getUint32:function getUint32(e){return D(W(this,4,e,arguments[1]))>>>0;},getFloat32:function getFloat32(e){return j(W(this,4,e,arguments[1]),23,4);},getFloat64:function getFloat64(e){return j(W(this,8,e,arguments[1]),52,8);},setInt8:function setInt8(e,t){G(this,1,e,L,t);},setUint8:function setUint8(e,t){G(this,1,e,L,t);},setInt16:function setInt16(e,t){G(this,2,e,z,t,arguments[2]);},setUint16:function setUint16(e,t){G(this,2,e,z,t,arguments[2]);},setInt32:function setInt32(e,t){G(this,4,e,F,t,arguments[2]);},setUint32:function setUint32(e,t){G(this,4,e,F,t,arguments[2]);},setFloat32:function setFloat32(e,t){G(this,4,e,V,t,arguments[2]);},setFloat64:function setFloat64(e,t){G(this,8,e,B,t,arguments[2]);}});y(_w2,"ArrayBuffer"),y(_x,"DataView"),s(_x[v],o.VIEW,!0),t.ArrayBuffer=_w2,t.DataView=_x;},function(e,t,n){"use strict";var r=n(23);e.exports.f=function(e){return new function(e){var t,n;this.promise=new e(function(e,r){if(void 0!==t||void 0!==n)throw TypeError("Bad Promise constructor");t=e,n=r;}),this.resolve=r(t),this.reject=r(n);}(e);};},function(e,t,n){var r=n(13),a=n(148).set,i=r.MutationObserver||r.WebKitMutationObserver,o=r.process,s=r.Promise,u="process"==n(41)(o);e.exports=function(){var e,t,n,c=function c(){var r,a;for(u&&(r=o.domain)&&r.exit();e;){a=e.fn,e=e.next;try{a();}catch(r){throw e?n():t=void 0,r;}}t=void 0,r&&r.enter();};if(u)n=function n(){o.nextTick(c);};else if(!i||r.navigator&&r.navigator.standalone){if(s&&s.resolve){var l=s.resolve(void 0);n=function n(){l.then(c);};}else n=function n(){a.call(r,c);};}else{var f=!0,p=document.createTextNode("");new i(c).observe(p,{characterData:!0}),n=function n(){p.data=f=!f;};}return function(r){var a={fn:r,next:void 0};t&&(t.next=a),e||(e=a,n()),t=a;};};},function(e,t,n){var r,a,i,o=n(42),s=n(219),u=n(166),c=n(170),l=n(13),f=l.process,p=l.setImmediate,h=l.clearImmediate,d=l.MessageChannel,m=l.Dispatch,g=0,y={},v=function v(){var e=+this;if(y.hasOwnProperty(e)){var t=y[e];delete y[e],t();}},b=function b(e){v.call(e.data);};p&&h||(p=function p(e){for(var t=[],n=1;arguments.length>n;){t.push(arguments[n++]);}return y[++g]=function(){s("function"==typeof e?e:Function(e),t);},r(g),g;},h=function h(e){delete y[e];},"process"==n(41)(f)?r=function r(e){f.nextTick(o(v,e,1));}:m&&m.now?r=function r(e){m.now(o(v,e,1));}:d?(i=(a=new d()).port2,a.port1.onmessage=b,r=o(i.postMessage,i,1)):l.addEventListener&&"function"==typeof postMessage&&!l.importScripts?(r=function r(e){l.postMessage(e+"","*");},l.addEventListener("message",b,!1)):r="onreadystatechange"in c("script")?function(e){u.appendChild(c("script")).onreadystatechange=function(){u.removeChild(this),v.call(e);};}:function(e){setTimeout(o(v,e,1),0);}),e.exports={set:p,clear:h};},function(e,t,n){"use strict";var r=n(59),a=n(209),i=n(87),o=n(37);e.exports=n(158)(Array,"Array",function(e,t){this._t=o(e),this._i=0,this._k=t;},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,a(1)):a(0,"keys"==t?n:"values"==t?e[n]:[n,e[n]]);},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries");},function(e,t,n){"use strict";var r=n(22),a=n(76),i=n(17);e.exports=function(e){for(var t=r(this),n=i(t.length),o=arguments.length,s=a(o>1?arguments[1]:void 0,n),u=o>2?arguments[2]:void 0,c=void 0===u?n:a(u,n);c>s;){t[s++]=e;}return t;};},function(e,t,n){var r=n(462);e.exports=function(e,t){return new(r(e))(t);};},function(e,t,n){var r=n(98),a=n(16)("iterator"),i=n(87);e.exports=n(43).getIteratorMethod=function(e){if(void 0!=e)return e[a]||e["@@iterator"]||i[r(e)];};},function(e,t,n){"use strict";var r=n(18),a=n(79);e.exports=function(e,t,n){t in e?r.f(e,t,a(0,n)):e[t]=n;};},function(e,t,n){var r=n(87),a=n(16)("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||i[a]===e);};},function(e,t,n){var r=n(16)("match");e.exports=function(e){var t=/./;try{"/./"[e](t);}catch(n){try{return t[r]=!1,!"/./"[e](t);}catch(e){}}return!0;};},function(e,t,n){var r=n(117),a=n(49);e.exports=function(e,t,n){if(r(t))throw TypeError("String#"+n+" doesn't accept regex!");return String(a(e));};},function(e,t,n){"use strict";var r=n(75),a=n(79),i=n(89),o={};n(28)(o,n(16)("iterator"),function(){return this;}),e.exports=function(e,t,n){e.prototype=r(o,{next:a(1,n)}),i(e,t+" Iterator");};},function(e,t,n){"use strict";var r=n(60),a=n(5),i=n(27),o=n(28),s=n(87),u=n(157),c=n(89),l=n(35),f=n(16)("iterator"),p=!([].keys&&"next"in[].keys()),h=function h(){return this;};e.exports=function(e,t,n,d,m,g,y){u(n,t,d);var v,b,w,x=function x(e){if(!p&&e in N)return N[e];switch(e){case"keys":case"values":return function(){return new n(this,e);};}return function(){return new n(this,e);};},k=t+" Iterator",O="values"==m,S=!1,N=e.prototype,E=N[f]||N["@@iterator"]||m&&N[m],I=E||x(m),T=m?O?x("entries"):I:void 0,A="Array"==t&&N.entries||E;if(A&&(w=l(A.call(new e())))!==Object.prototype&&w.next&&(c(w,k,!0),r||"function"==typeof w[f]||o(w,f,h)),O&&E&&"values"!==E.name&&(S=!0,I=function I(){return E.call(this);}),r&&!y||!p&&!S&&N[f]||o(N,f,I),s[t]=I,s[k]=h,m)if(v={values:O?I:x("values"),keys:g?I:x("keys"),entries:T},y)for(b in v){b in N||i(N,b,v[b]);}else a(a.P+a.F*(p||S),t,v);return v;};},function(e,t,n){var r=n(48),a=n(49);e.exports=function(e){return function(t,n){var i,o,s=String(a(t)),u=r(n),c=s.length;return u<0||u>=c?e?"":void 0:(i=s.charCodeAt(u))<55296||i>56319||u+1===c||(o=s.charCodeAt(u+1))<56320||o>57343?e?s.charAt(u):i:e?s.slice(u,u+2):o-56320+(i-55296<<10)+65536;};};},function(e,t){var n=Math.expm1;e.exports=!n||n(10)>22025.465794806718||n(10)<22025.465794806718||-2e-17!=n(-2e-17)?function(e){return 0==(e=+e)?e:e>-1e-6&&e<1e-6?e+e*e/2:Math.exp(e)-1;}:n;},function(e,t){e.exports=Math.sign||function(e){return 0==(e=+e)||e!=e?e:e<0?-1:1;};},function(e,t,n){"use strict";var r=n(48),a=n(49);e.exports=function(e){var t=String(a(this)),n="",i=r(e);if(i<0||i==1/0)throw RangeError("Count can't be negative");for(;i>0;(i>>>=1)&&(t+=t)){1&i&&(n+=t);}return n;};},function(e,t,n){var r=n(15),a=n(165).set;e.exports=function(e,t,n){var i,o=t.constructor;return o!==n&&"function"==typeof o&&(i=o.prototype)!==n.prototype&&r(i)&&a&&a(e,i),e;};},function(e,t){e.exports="\t\n\x0B\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF";},function(e,t,n){var r=n(15),a=n(12),i=function i(e,t){if(a(e),!r(t)&&null!==t)throw TypeError(t+": can't set as prototype!");};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{(r=n(42)(Function.call,n(36).f(Object.prototype,"__proto__").set,2))(e,[]),t=!(e instanceof Array);}catch(e){t=!0;}return function(e,n){return i(e,n),t?e.__proto__=n:r(e,n),e;};}({},!1):void 0),check:i};},function(e,t,n){var r=n(13).document;e.exports=r&&r.documentElement;},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",");},function(e,t,n){var r=n(121)("keys"),a=n(78);e.exports=function(e){return r[e]||(r[e]=a(e));};},function(e,t,n){var r=n(13),a=n(43),i=n(60),o=n(225),s=n(18).f;e.exports=function(e){var t=a.Symbol||(a.Symbol=i?{}:r.Symbol||{});"_"==e.charAt(0)||e in t||s(t,e,{value:o.f(e)});};},function(e,t,n){var r=n(15),a=n(13).document,i=r(a)&&r(a.createElement);e.exports=function(e){return i?a.createElement(e):{};};},function(e,t,n){"use strict";var r=n(336),a=n(335);function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null;}t.parse=b,t.resolve=function(e,t){return b(e,!1,!0).resolve(t);},t.resolveObject=function(e,t){return e?b(e,!1,!0).resolveObject(t):t;},t.format=function(e){return a.isString(e)&&(e=b(e)),e instanceof i?e.format():i.prototype.format.call(e);},t.Url=i;var o=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,u=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,c=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),l=["'"].concat(c),f=["%","/","?",";","#"].concat(l),p=["/","?","#"],h=/^[+a-z0-9A-Z_-]{0,63}$/,d=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},g={javascript:!0,"javascript:":!0},y={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=n(334);function b(e,t,n){if(e&&a.isObject(e)&&e instanceof i)return e;var r=new i();return r.parse(e,t,n),r;}i.prototype.parse=function(e,t,n){if(!a.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+(typeof e==="undefined"?"undefined":_typeof(e)));var i=e.indexOf("?"),s=-1!==i&&i<e.indexOf("#")?"?":"#",c=e.split(s);c[0]=c[0].replace(/\\/g,"/");var b=e=c.join(s);if(b=b.trim(),!n&&1===e.split("#").length){var w=u.exec(b);if(w)return this.path=b,this.href=b,this.pathname=w[1],w[2]?(this.search=w[2],this.query=t?v.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this;}var x=o.exec(b);if(x){var k=(x=x[0]).toLowerCase();this.protocol=k,b=b.substr(x.length);}if(n||x||b.match(/^\/\/[^@\/]+@[^@\/]+/)){var O="//"===b.substr(0,2);!O||x&&g[x]||(b=b.substr(2),this.slashes=!0);}if(!g[x]&&(O||x&&!y[x])){for(var S,N,E=-1,I=0;I<p.length;I++){-1!==(T=b.indexOf(p[I]))&&(-1===E||T<E)&&(E=T);}for(-1!==(N=-1===E?b.lastIndexOf("@"):b.lastIndexOf("@",E))&&(S=b.slice(0,N),b=b.slice(N+1),this.auth=decodeURIComponent(S)),E=-1,I=0;I<f.length;I++){var T;-1!==(T=b.indexOf(f[I]))&&(-1===E||T<E)&&(E=T);}-1===E&&(E=b.length),this.host=b.slice(0,E),b=b.slice(E),this.parseHost(),this.hostname=this.hostname||"";var A="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!A)for(var C=this.hostname.split(/\./),P=(I=0,C.length);I<P;I++){var _=C[I];if(_&&!_.match(h)){for(var R="",M=0,j=_.length;M<j;M++){_.charCodeAt(M)>127?R+="x":R+=_[M];}if(!R.match(h)){var D=C.slice(0,I),L=C.slice(I+1),z=_.match(d);z&&(D.push(z[1]),L.unshift(z[2])),L.length&&(b="/"+L.join(".")+b),this.hostname=D.join(".");break;}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),A||(this.hostname=r.toASCII(this.hostname));var F=this.port?":"+this.port:"",B=this.hostname||"";this.host=B+F,this.href+=this.host,A&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==b[0]&&(b="/"+b));}if(!m[k])for(I=0,P=l.length;I<P;I++){var V=l[I];if(-1!==b.indexOf(V)){var U=encodeURIComponent(V);U===V&&(U=escape(V)),b=b.split(V).join(U);}}var W=b.indexOf("#");-1!==W&&(this.hash=b.substr(W),b=b.slice(0,W));var G=b.indexOf("?");if(-1!==G?(this.search=b.substr(G),this.query=b.substr(G+1),t&&(this.query=v.parse(this.query)),b=b.slice(0,G)):t&&(this.search="",this.query={}),b&&(this.pathname=b),y[k]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){F=this.pathname||"";var q=this.search||"";this.path=F+q;}return this.href=this.format(),this;},i.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",i=!1,o="";this.host?i=e+this.host:this.hostname&&(i=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(i+=":"+this.port)),this.query&&a.isObject(this.query)&&Object.keys(this.query).length&&(o=v.stringify(this.query));var s=this.search||o&&"?"+o||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||y[t])&&!1!==i?(i="//"+(i||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):i||(i=""),r&&"#"!==r.charAt(0)&&(r="#"+r),s&&"?"!==s.charAt(0)&&(s="?"+s),t+i+(n=n.replace(/[?#]/g,function(e){return encodeURIComponent(e);}))+(s=s.replace("#","%23"))+r;},i.prototype.resolve=function(e){return this.resolveObject(b(e,!1,!0)).format();},i.prototype.resolveObject=function(e){if(a.isString(e)){var t=new i();t.parse(e,!1,!0),e=t;}for(var n=new i(),r=Object.keys(this),o=0;o<r.length;o++){var s=r[o];n[s]=this[s];}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var u=Object.keys(e),c=0;c<u.length;c++){var l=u[c];"protocol"!==l&&(n[l]=e[l]);}return y[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n;}if(e.protocol&&e.protocol!==n.protocol){if(!y[e.protocol]){for(var f=Object.keys(e),p=0;p<f.length;p++){var h=f[p];n[h]=e[h];}return n.href=n.format(),n;}if(n.protocol=e.protocol,e.host||g[e.protocol])n.pathname=e.pathname;else{for(var d=(e.pathname||"").split("/");d.length&&!(e.host=d.shift());){}e.host||(e.host=""),e.hostname||(e.hostname=""),""!==d[0]&&d.unshift(""),d.length<2&&d.unshift(""),n.pathname=d.join("/");}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var m=n.pathname||"",v=n.search||"";n.path=m+v;}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n;}var b=n.pathname&&"/"===n.pathname.charAt(0),w=e.host||e.pathname&&"/"===e.pathname.charAt(0),x=w||b||n.host&&e.pathname,k=x,O=n.pathname&&n.pathname.split("/")||[],S=(d=e.pathname&&e.pathname.split("/")||[],n.protocol&&!y[n.protocol]);if(S&&(n.hostname="",n.port=null,n.host&&(""===O[0]?O[0]=n.host:O.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===d[0]?d[0]=e.host:d.unshift(e.host)),e.host=null),x=x&&(""===d[0]||""===O[0])),w)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,O=d;else if(d.length)O||(O=[]),O.pop(),O=O.concat(d),n.search=e.search,n.query=e.query;else if(!a.isNullOrUndefined(e.search))return S&&(n.hostname=n.host=O.shift(),(A=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=A.shift(),n.host=n.hostname=A.shift())),n.search=e.search,n.query=e.query,a.isNull(n.pathname)&&a.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!O.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var N=O.slice(-1)[0],E=(n.host||e.host||O.length>1)&&("."===N||".."===N)||""===N,I=0,T=O.length;T>=0;T--){"."===(N=O[T])?O.splice(T,1):".."===N?(O.splice(T,1),I++):I&&(O.splice(T,1),I--);}if(!x&&!k)for(;I--;I){O.unshift("..");}!x||""===O[0]||O[0]&&"/"===O[0].charAt(0)||O.unshift(""),E&&"/"!==O.join("/").substr(-1)&&O.push("");var A,C=""===O[0]||O[0]&&"/"===O[0].charAt(0);return S&&(n.hostname=n.host=C?"":O.length?O.shift():"",(A=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=A.shift(),n.host=n.hostname=A.shift())),(x=x||n.host&&O.length)&&!C&&O.unshift(""),O.length?n.pathname=O.join("/"):(n.pathname=null,n.path=null),a.isNull(n.pathname)&&a.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n;},i.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e);};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=l(n(127)),a=l(n(32)),i=l(n(64)),o=l(n(31)),s=l(n(30)),u=l(n(29)),c=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}(n(10));function l(e){return e&&e.__esModule?e:{default:e};}var f=function(){function e(t){(0,s.default)(this,e),this.urlPath=t,"/"!==this.urlPath.charAt(this.urlPath.length-1)&&(this.urlPath+="/");}return(0,u.default)(e,[{key:"loadManifest",value:function(){var e=(0,o.default)(a.default.mark(function e(){var t=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.abrupt("return",new i.default(function(e,n){var r=new XMLHttpRequest();r.open("GET",t.urlPath+"manifest.json"),r.onload=function(){t.checkpointManifest=JSON.parse(r.responseText),e();},r.onerror=function(e){throw n(),new Error("manifest.json not found at "+t.urlPath+". "+e);},r.send();}));case 1:case"end":return e.stop();}}},e,this);}));return function(){return e.apply(this,arguments);};}()},{key:"getCheckpointManifest",value:function(){var e=(0,o.default)(a.default.mark(function e(){return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:if(null!=this.checkpointManifest){e.next=3;break;}return e.next=3,this.loadManifest();case 3:return e.abrupt("return",this.checkpointManifest);case 4:case"end":return e.stop();}}},e,this);}));return function(){return e.apply(this,arguments);};}()},{key:"getAllVariables",value:function(){var e=(0,o.default)(a.default.mark(function e(){var t,n,o=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:if(null==this.variables){e.next=2;break;}return e.abrupt("return",i.default.resolve(this.variables));case 2:return e.next=4,this.getCheckpointManifest();case 4:return t=(0,r.default)(this.checkpointManifest),n=t.map(function(e){return o.getVariable(e);}),e.abrupt("return",i.default.all(n).then(function(e){o.variables={};for(var n=0;n<e.length;n+=1){o.variables[t[n]]=e[n];}return o.variables;}));case 7:case"end":return e.stop();}}},e,this);}));return function(){return e.apply(this,arguments);};}()},{key:"getVariable",value:function value(e){var t=this;if(!(e in this.checkpointManifest))throw new Error("Cannot load non-existent variable "+e);var n=function n(_n10){var r=new XMLHttpRequest();r.responseType="arraybuffer";var a=t.checkpointManifest[e].filename;r.open("GET",t.urlPath+a),r.onload=function(){if(404===r.status)throw new Error("Not found variable "+e);var a=new Float32Array(r.response),i=c.Tensor.make(t.checkpointManifest[e].shape,{values:a});_n10(i);},r.onerror=function(t){throw new Error("Could not fetch variable "+e+": "+t);},r.send();};return null==this.checkpointManifest?new i.default(function(e){t.loadManifest().then(function(){new i.default(n).then(e);});}):new i.default(n);}}]),e;}();t.default=f;},function(e,t,n){var r=n(34),a=n(21),i=n(84);e.exports=function(e,t){var n=(a.Object||{})[e]||Object[e],o={};o[e]=t(n),r(r.S+r.F*i(function(){n(1);}),"Object",o);};},function(e,t,n){var r=n(94),a=n(97),i=n(67),o=n(143),s=n(68),u=n(192),c=Object.getOwnPropertyDescriptor;t.f=n(57)?c:function(e,t){if(e=i(e),t=o(t,!0),u)try{return c(e,t);}catch(e){}if(s(e,t))return a(!r.f.call(e,t),e[t]);};},function(e,t,n){var r=n(191),a=n(137).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,a);};},function(e,t,n){var r=n(24)("iterator"),a=!1;try{var i=[7][r]();i.return=function(){a=!0;},Array.from(i,function(){throw 2;});}catch(e){}e.exports=function(e,t){if(!t&&!a)return!1;var n=!1;try{var i=[7],o=i[r]();o.next=function(){return{done:n=!0};},i[r]=function(){return o;},e(i);}catch(e){}return n;};},function(e,t,n){var r=n(45),a=n(58),i=n(132);e.exports=function(e,t){if(r(e),a(t)&&t.constructor===e)return t;var n=i.f(e);return(0,n.resolve)(t),n.promise;};},function(e,t){e.exports=function(e){try{return{e:!1,v:e()};}catch(e){return{e:!0,v:e};}};},function(e,t,n){var r,a,i,o=n(85),s=n(304),u=n(184),c=n(144),l=n(25),f=l.process,p=l.setImmediate,h=l.clearImmediate,d=l.MessageChannel,m=l.Dispatch,g=0,y={},v=function v(){var e=+this;if(y.hasOwnProperty(e)){var t=y[e];delete y[e],t();}},b=function b(e){v.call(e.data);};p&&h||(p=function p(e){for(var t=[],n=1;arguments.length>n;){t.push(arguments[n++]);}return y[++g]=function(){s("function"==typeof e?e:Function(e),t);},r(g),g;},h=function h(e){delete y[e];},"process"==n(96)(f)?r=function r(e){f.nextTick(o(v,e,1));}:m&&m.now?r=function r(e){m.now(o(v,e,1));}:d?(i=(a=new d()).port2,a.port1.onmessage=b,r=o(i.postMessage,i,1)):l.addEventListener&&"function"==typeof postMessage&&!l.importScripts?(r=function r(e){l.postMessage(e+"","*");},l.addEventListener("message",b,!1)):r="onreadystatechange"in c("script")?function(e){u.appendChild(c("script")).onreadystatechange=function(){u.removeChild(this),v.call(e);};}:function(e){setTimeout(o(v,e,1),0);}),e.exports={set:p,clear:h};},function(e,t,n){var r=n(45),a=n(106),i=n(24)("species");e.exports=function(e,t){var n,o=r(e).constructor;return void 0===o||void 0==(n=r(o)[i])?t:a(n);};},function(e,t,n){var r=n(81),a=n(24)("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||i[a]===e);};},function(e,t,n){var r=n(45);e.exports=function(e,t,n,a){try{return a?t(r(n)[0],n[1]):t(n);}catch(t){var i=e.return;throw void 0!==i&&r(i.call(e)),t;}};},function(e,t,n){var r=n(68),a=n(93),i=n(139)("IE_PROTO"),o=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=a(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?o:null;};},function(e,t,n){var r=n(25).document;e.exports=r&&r.documentElement;},function(e,t,n){e.exports=n(69);},function(e,t,n){"use strict";var r=n(95),a=n(34),i=n(185),o=n(69),s=n(81),u=n(312),c=n(104),l=n(183),f=n(24)("iterator"),p=!([].keys&&"next"in[].keys()),h=function h(){return this;};e.exports=function(e,t,n,d,m,g,y){u(n,t,d);var v,b,w,x=function x(e){if(!p&&e in N)return N[e];switch(e){case"keys":case"values":return function(){return new n(this,e);};}return function(){return new n(this,e);};},k=t+" Iterator",O="values"==m,S=!1,N=e.prototype,E=N[f]||N["@@iterator"]||m&&N[m],I=E||x(m),T=m?O?x("entries"):I:void 0,A="Array"==t&&N.entries||E;if(A&&(w=l(A.call(new e())))!==Object.prototype&&w.next&&(c(w,k,!0),r||"function"==typeof w[f]||o(w,f,h)),O&&E&&"values"!==E.name&&(S=!0,I=function I(){return E.call(this);}),r&&!y||!p&&!S&&N[f]||o(N,f,I),s[t]=I,s[k]=h,m)if(v={values:O?I:x("values"),keys:g?I:x("keys"),entries:T},y)for(b in v){b in N||i(N,b,v[b]);}else a(a.P+a.F*(p||S),t,v);return v;};},function(e,t){},function(e,t,n){"use strict";e.exports=u;var r,a=n(65),i=a.LongBits,o=a.utf8;function s(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len);}function u(e){this.buf=e,this.pos=0,this.len=e.length;}var c="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new u(e);throw Error("illegal buffer");}:function(e){if(Array.isArray(e))return new u(e);throw Error("illegal buffer");};function l(){var e=new i(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw s(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e;}for(;t<4;++t){if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;}if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t){if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e;}}else for(;t<5;++t){if(this.pos>=this.len)throw s(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e;}throw Error("invalid varint encoding");}function f(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0;}function p(){if(this.pos+8>this.len)throw s(this,8);return new i(f(this.buf,this.pos+=4),f(this.buf,this.pos+=4));}u.create=a.Buffer?function(e){return(u.create=function(e){return a.Buffer.isBuffer(e)?new r(e):c(e);})(e);}:c,u.prototype._slice=a.Array.prototype.subarray||a.Array.prototype.slice,u.prototype.uint32=function(){var e=4294967295;return function(){if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,s(this,10);return e;};}(),u.prototype.int32=function(){return 0|this.uint32();},u.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0;},u.prototype.bool=function(){return 0!==this.uint32();},u.prototype.fixed32=function(){if(this.pos+4>this.len)throw s(this,4);return f(this.buf,this.pos+=4);},u.prototype.sfixed32=function(){if(this.pos+4>this.len)throw s(this,4);return 0|f(this.buf,this.pos+=4);},u.prototype.float=function(){if(this.pos+4>this.len)throw s(this,4);var e=a.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e;},u.prototype.double=function(){if(this.pos+8>this.len)throw s(this,4);var e=a.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e;},u.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw s(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,n):t===n?new this.buf.constructor(0):this._slice.call(this.buf,t,n);},u.prototype.string=function(){var e=this.bytes();return o.read(e,0,e.length);},u.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw s(this,e);this.pos+=e;}else do{if(this.pos>=this.len)throw s(this);}while(128&this.buf[this.pos++]);return this;},u.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());){this.skipType(e);}break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos);}return this;},u._configure=function(e){r=e;var t=a.Long?"toLong":"toNumber";a.merge(u.prototype,{int64:function int64(){return l.call(this)[t](!1);},uint64:function uint64(){return l.call(this)[t](!0);},sint64:function sint64(){return l.call(this).zzDecode()[t](!1);},fixed64:function fixed64(){return p.call(this)[t](!0);},sfixed64:function sfixed64(){return p.call(this)[t](!1);}});};},function(e,t,n){"use strict";e.exports=l;var r,a=n(65),i=a.LongBits,o=a.base64,s=a.utf8;function u(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n;}function c(){}function l(){this.len=0,this.head=new u(c,0,0),this.tail=this.head,this.states=null;}function f(e,t,n){t[n]=255&e;}function p(e,t){this.len=e,this.next=void 0,this.val=t;}function h(e,t,n){for(;e.hi;){t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;}for(;e.lo>127;){t[n++]=127&e.lo|128,e.lo=e.lo>>>7;}t[n++]=e.lo;}function d(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24;}l.create=a.Buffer?function(){return(l.create=function(){return new r();})();}:function(){return new l();},l.alloc=function(e){return new a.Array(e);},a.Array!==Array&&(l.alloc=a.pool(l.alloc,a.Array.prototype.subarray)),l.prototype._push=function(e,t,n){return this.tail=this.tail.next=new u(e,t,n),this.len+=t,this;},p.prototype=Object.create(u.prototype),p.prototype.fn=function(e,t,n){for(;e>127;){t[n++]=127&e|128,e>>>=7;}t[n]=e;},l.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new p((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this;},l.prototype.int32=function(e){return e<0?this._push(h,10,i.fromNumber(e)):this.uint32(e);},l.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0);},l.prototype.uint64=function(e){var t=i.from(e);return this._push(h,t.length(),t);},l.prototype.int64=l.prototype.uint64,l.prototype.sint64=function(e){var t=i.from(e).zzEncode();return this._push(h,t.length(),t);},l.prototype.bool=function(e){return this._push(f,1,e?1:0);},l.prototype.fixed32=function(e){return this._push(d,4,e>>>0);},l.prototype.sfixed32=l.prototype.fixed32,l.prototype.fixed64=function(e){var t=i.from(e);return this._push(d,4,t.lo)._push(d,4,t.hi);},l.prototype.sfixed64=l.prototype.fixed64,l.prototype.float=function(e){return this._push(a.float.writeFloatLE,4,e);},l.prototype.double=function(e){return this._push(a.float.writeDoubleLE,8,e);};var m=a.Array.prototype.set?function(e,t,n){t.set(e,n);}:function(e,t,n){for(var r=0;r<e.length;++r){t[n+r]=e[r];}};l.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(f,1,0);if(a.isString(e)){var n=l.alloc(t=o.length(e));o.decode(e,n,0),e=n;}return this.uint32(t)._push(m,t,e);},l.prototype.string=function(e){var t=s.length(e);return t?this.uint32(t)._push(s.write,t,e):this._push(f,1,0);},l.prototype.fork=function(){return this.states=new function(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states;}(this),this.head=this.tail=new u(c,0,0),this.len=0,this;},l.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new u(c,0,0),this.len=0),this;},l.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this;},l.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;){e.fn(e.val,t,n),n+=e.len,e=e.next;}return t;},l._configure=function(e){r=e;};},function(e,t,n){var r=n(96);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e);};},function(e,t,n){var r=n(68),a=n(67),i=n(346)(!1),o=n(139)("IE_PROTO");e.exports=function(e,t){var n,s=a(e),u=0,c=[];for(n in s){n!=o&&r(s,n)&&c.push(n);}for(;t.length>u;){r(s,n=t[u++])&&(~i(c,n)||c.push(n));}return c;};},function(e,t,n){e.exports=!n(57)&&!n(84)(function(){return 7!=Object.defineProperty(n(144)("div"),"a",{get:function get(){return 7;}}).a;});},function(e,t){e.exports=Math.scale||function(e,t,n,r,a){return 0===arguments.length||e!=e||t!=t||n!=n||r!=r||a!=a?NaN:e===1/0||e===-1/0?e:(e-t)*(a-r)/(n-t)+r;};},function(e,t,n){var r=n(71);e.exports=function(e,t){var n=[];return r(e,!1,n.push,n,t),n;};},function(e,t,n){var r=n(98),a=n(194);e.exports=function(e){return function(){if(r(this)!=e)throw TypeError(e+"#toJSON isn't generic");return a(this);};};},function(e,t,n){var r=n(77),a=n(37),i=n(99).f;e.exports=function(e){return function(t){for(var n,o=a(t),s=r(o),u=s.length,c=0,l=[];u>c;){i.call(o,n=s[c++])&&l.push(e?[n,o[n]]:o[n]);}return l;};};},function(e,t,n){var r=n(17),a=n(162),i=n(49);e.exports=function(e,t,n,o){var s=String(i(e)),u=s.length,c=void 0===n?" ":String(n),l=r(t);if(l<=u||""==c)return s;var f=l-u,p=a.call(c,Math.ceil(f/c.length));return p.length>f&&(p=p.slice(0,f)),o?p+s:s+p;};},function(e,t,n){"use strict";var r=n(118),a=n(15),i=n(17),o=n(42),s=n(16)("isConcatSpreadable");e.exports=function e(t,n,u,c,l,f,p,h){for(var d,m,g=l,y=0,v=!!p&&o(p,h,3);y<c;){if(y in u){if(d=v?v(u[y],y,n):u[y],m=!1,a(d)&&(m=void 0!==(m=d[s])?!!m:r(d)),m&&f>0)g=e(t,n,d,i(d.length),g,f-1)-1;else{if(g>=9007199254740991)throw TypeError();t[g]=d;}g++;}y++;}return g;};},function(e,t,n){var r=n(74),a=n(119),i=n(12),o=n(13).Reflect;e.exports=o&&o.ownKeys||function(e){var t=r.f(i(e)),n=a.f;return n?t.concat(n(e)):t;};},function(e,t,n){var r=n(48),a=n(17);e.exports=function(e){if(void 0===e)return 0;var t=r(e),n=a(t);if(t!==n)throw RangeError("Wrong length!");return n;};},function(e,t,n){"use strict";var r=n(70),a=n(61).getWeak,i=n(12),o=n(15),s=n(72),u=n(71),c=n(46),l=n(38),f=n(86),p=c(5),h=c(6),d=0,m=function m(e){return e._l||(e._l=new g());},g=function g(){this.a=[];},y=function y(e,t){return p(e.a,function(e){return e[0]===t;});};g.prototype={get:function get(e){var t=y(this,e);if(t)return t[1];},has:function has(e){return!!y(this,e);},set:function set(e,t){var n=y(this,e);n?n[1]=t:this.a.push([e,t]);},delete:function _delete(e){var t=h(this.a,function(t){return t[0]===e;});return~t&&this.a.splice(t,1),!!~t;}},e.exports={getConstructor:function getConstructor(e,t,n,i){var c=e(function(e,r){s(e,c,t,"_i"),e._t=t,e._i=d++,e._l=void 0,void 0!=r&&u(r,n,e[i],e);});return r(c.prototype,{delete:function _delete(e){if(!o(e))return!1;var n=a(e);return!0===n?m(f(this,t)).delete(e):n&&l(n,this._i)&&delete n[this._i];},has:function has(e){if(!o(e))return!1;var n=a(e);return!0===n?m(f(this,t)).has(e):n&&l(n,this._i);}}),c;},def:function def(e,t,n){var r=a(i(t),!0);return!0===r?m(e).set(t,n):r[e._i]=n,e;},ufstore:m};},function(e,t,n){"use strict";var r,a=n(46)(0),i=n(27),o=n(61),s=n(221),u=n(201),c=n(15),l=n(14),f=n(86),p=o.getWeak,h=Object.isExtensible,d=u.ufstore,m={},g=function g(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0);};},y={get:function get(e){if(c(e)){var t=p(e);return!0===t?d(f(this,"WeakMap")).get(e):t?t[this._i]:void 0;}},set:function set(e,t){return u.def(f(this,"WeakMap"),e,t);}},v=e.exports=n(111)("WeakMap",g,y,u,!0,!0);l(function(){return 7!=new v().set((Object.freeze||Object)(m),7).get(m);})&&(s((r=u.getConstructor(g,"WeakMap")).prototype,y),o.NEED=!0,a(["delete","has","get","set"],function(e){var t=v.prototype,n=t[e];i(t,e,function(t,a){if(c(t)&&!h(t)){this._f||(this._f=new r());var i=this._f[e](t,a);return"set"==e?this:i;}return n.call(this,t,a);});}));},function(e,t,n){"use strict";var r=n(204),a=n(86);e.exports=n(111)("Set",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0);};},{add:function add(e){return r.def(a(this,"Set"),e=0===e?0:e,e);}},r);},function(e,t,n){"use strict";var r=n(18).f,a=n(75),i=n(70),o=n(42),s=n(72),u=n(71),c=n(158),l=n(209),f=n(73),p=n(19),h=n(61).fastKey,d=n(86),m=p?"_s":"size",g=function g(e,t){var n,r=h(t);if("F"!==r)return e._i[r];for(n=e._f;n;n=n.n){if(n.k==t)return n;}};e.exports={getConstructor:function getConstructor(e,t,n,c){var l=e(function(e,r){s(e,l,t,"_i"),e._t=t,e._i=a(null),e._f=void 0,e._l=void 0,e[m]=0,void 0!=r&&u(r,n,e[c],e);});return i(l.prototype,{clear:function clear(){for(var e=d(this,t),n=e._i,r=e._f;r;r=r.n){r.r=!0,r.p&&(r.p=r.p.n=void 0),delete n[r.i];}e._f=e._l=void 0,e[m]=0;},delete:function _delete(e){var n=d(this,t),r=g(n,e);if(r){var a=r.n,i=r.p;delete n._i[r.i],r.r=!0,i&&(i.n=a),a&&(a.p=i),n._f==r&&(n._f=a),n._l==r&&(n._l=i),n[m]--;}return!!r;},forEach:function forEach(e){d(this,t);for(var n,r=o(e,arguments.length>1?arguments[1]:void 0,3);n=n?n.n:this._f;){for(r(n.v,n.k,this);n&&n.r;){n=n.p;}}},has:function has(e){return!!g(d(this,t),e);}}),p&&r(l.prototype,"size",{get:function get(){return d(this,t)[m];}}),l;},def:function def(e,t,n){var r,a,i=g(e,t);return i?i.v=n:(e._l=i={i:a=h(t,!0),k:t,v:n,p:r=e._l,n:void 0,r:!1},e._f||(e._f=i),r&&(r.n=i),e[m]++,"F"!==a&&(e._i[a]=i)),e;},getEntry:g,setStrong:function setStrong(e,t,n){c(e,t,function(e,n){this._t=d(e,t),this._k=n,this._l=void 0;},function(){for(var e=this._k,t=this._l;t&&t.r;){t=t.p;}return this._t&&(this._l=t=t?t.n:this._t._f)?l(0,"keys"==e?t.k:"values"==e?t.v:[t.k,t.v]):(this._t=void 0,l(1));},n?"entries":"values",!n,!0),f(t);}};},function(e,t,n){"use strict";var r=n(204),a=n(86);e.exports=n(111)("Map",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0);};},{get:function get(e){var t=r.getEntry(a(this,"Map"),e);return t&&t.v;},set:function set(e,t){return r.def(a(this,"Map"),0===e?0:e,t);}},r,!0);},function(e,t,n){var r=n(12),a=n(15),i=n(146);e.exports=function(e,t){if(r(e),a(t)&&t.constructor===e)return t;var n=i.f(e);return(0,n.resolve)(t),n.promise;};},function(e,t){e.exports=function(e){try{return{e:!1,v:e()};}catch(e){return{e:!0,v:e};}};},function(e,t,n){n(19)&&"g"!=/./g.flags&&n(18).f(RegExp.prototype,"flags",{configurable:!0,get:n(115)});},function(e,t){e.exports=function(e,t){return{value:t,done:!!e};};},function(e,t,n){"use strict";var r=n(22),a=n(76),i=n(17);e.exports=[].copyWithin||function(e,t){var n=r(this),o=i(n.length),s=a(e,o),u=a(t,o),c=arguments.length>2?arguments[2]:void 0,l=Math.min((void 0===c?o:a(c,o))-u,o-s),f=1;for(u<s&&s<u+l&&(f=-1,u+=l-1,s+=l-1);l-->0;){u in n?n[s]=n[u]:delete n[s],s+=f,u+=f;}return n;};},function(e,t,n){var r=n(23),a=n(22),i=n(100),o=n(17);e.exports=function(e,t,n,s,u){r(t);var c=a(e),l=i(c),f=o(c.length),p=u?f-1:0,h=u?-1:1;if(n<2)for(;;){if(p in l){s=l[p],p+=h;break;}if(p+=h,u?p<0:f<=p)throw TypeError("Reduce of empty array with no initial value");}for(;u?p>=0:f>p;p+=h){p in l&&(s=t(s,l[p],p,c));}return s;};},function(e,t,n){var r=n(12);e.exports=function(e,t,n,a){try{return a?t(r(n)[0],n[1]):t(n);}catch(t){var i=e.return;throw void 0!==i&&r(i.call(e)),t;}};},function(e,t,n){var r=n(161),a=Math.pow,i=a(2,-52),o=a(2,-23),s=a(2,127)*(2-o),u=a(2,-126);e.exports=Math.fround||function(e){var t,n,a=Math.abs(e),c=r(e);return a<u?c*(a/u/o+1/i-1/i)*u*o:(n=(t=(1+o/i)*a)-(t-a))>s||n!=n?c*(1/0):c*n;};},function(e,t){e.exports=Math.log1p||function(e){return(e=+e)>-1e-8&&e<1e-8?e-e*e/2:Math.log(1+e);};},function(e,t,n){var r=n(15),a=Math.floor;e.exports=function(e){return!r(e)&&isFinite(e)&&a(e)===e;};},function(e,t,n){var r=n(41);e.exports=function(e,t){if("number"!=typeof e&&"Number"!=r(e))throw TypeError(t);return+e;};},function(e,t,n){var r=n(13).parseFloat,a=n(88).trim;e.exports=1/r(n(164)+"-0")!=-1/0?function(e){var t=a(String(e),3),n=r(t);return 0===n&&"-"==t.charAt(0)?-0:n;}:r;},function(e,t,n){var r=n(13).parseInt,a=n(88).trim,i=n(164),o=/^[-+]?0[xX]/;e.exports=8!==r(i+"08")||22!==r(i+"0x16")?function(e,t){var n=a(String(e),3);return r(n,t>>>0||(o.test(n)?16:10));}:r;},function(e,t){e.exports=function(e,t,n){var r=void 0===n;switch(t.length){case 0:return r?e():e.call(n);case 1:return r?e(t[0]):e.call(n,t[0]);case 2:return r?e(t[0],t[1]):e.call(n,t[0],t[1]);case 3:return r?e(t[0],t[1],t[2]):e.call(n,t[0],t[1],t[2]);case 4:return r?e(t[0],t[1],t[2],t[3]):e.call(n,t[0],t[1],t[2],t[3]);}return e.apply(n,t);};},function(e,t,n){"use strict";var r=n(23),a=n(15),i=n(219),o=[].slice,s={};e.exports=Function.bind||function(e){var t=r(this),n=o.call(arguments,1),u=function u(){var r=n.concat(o.call(arguments));return this instanceof u?function(e,t,n){if(!(t in s)){for(var r=[],a=0;a<t;a++){r[a]="a["+a+"]";}s[t]=Function("F,a","return new F("+r.join(",")+")");}return s[t](e,n);}(t,r.length,r):i(t,r,e);};return a(t.prototype)&&(u.prototype=t.prototype),u;};},function(e,t,n){"use strict";var r=n(77),a=n(119),i=n(99),o=n(22),s=n(100),u=Object.assign;e.exports=!u||n(14)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e;}),7!=u({},e)[n]||Object.keys(u({},t)).join("")!=r;})?function(e,t){for(var n=o(e),u=arguments.length,c=1,l=a.f,f=i.f;u>c;){for(var p,h=s(arguments[c++]),d=l?r(h).concat(l(h)):r(h),m=d.length,g=0;m>g;){f.call(h,p=d[g++])&&(n[p]=h[p]);}}return n;}:u;},function(e,t,n){var r=n(37),a=n(74).f,i={}.toString,o="object"==(typeof window==="undefined"?"undefined":_typeof(window))&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];e.exports.f=function(e){return o&&"[object Window]"==i.call(e)?function(e){try{return a(e);}catch(e){return o.slice();}}(e):a(r(e));};},function(e,t,n){var r=n(18),a=n(12),i=n(77);e.exports=n(19)?Object.defineProperties:function(e,t){a(e);for(var n,o=i(t),s=o.length,u=0;s>u;){r.f(e,n=o[u++],t[n]);}return e;};},function(e,t,n){var r=n(38),a=n(37),i=n(120)(!1),o=n(168)("IE_PROTO");e.exports=function(e,t){var n,s=a(e),u=0,c=[];for(n in s){n!=o&&r(s,n)&&c.push(n);}for(;t.length>u;){r(s,n=t[u++])&&(~i(c,n)||c.push(n));}return c;};},function(e,t,n){t.f=n(16);},function(e,t,n){e.exports=!n(19)&&!n(14)(function(){return 7!=Object.defineProperty(n(170)("div"),"a",{get:function get(){return 7;}}).a;});},function(e,t,n){"use strict";var r=n(3),a=n(7),i=n(1),o=n(0),s=function(){function e(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new u());}return e.prototype.profileKernel=function(e,t){var n,r=this,a=this.backendTimer.time(function(){n=t();}),i=n.dataSync();return o.checkForNaN(i,n.dtype,e),a.then(function(t){r.logger.logKernelProfile(e,n,i,t.kernelMs);}),n;},e;}(),u=function(){function e(){}return e.prototype.logKernelProfile=function(e,t,n,r){var a=o.rightPad(r+"ms",9),i=o.rightPad(e,25),s=t.rank,u=t.size,c=o.rightPad(t.shape.toString(),14);console.log("%c"+i+"\t%c"+a+"\t%c"+s+"D "+c+"\t%c"+u,"font-weight:bold","color:red","color:blue","color: orange");},e;}(),c=n(6);n.d(t,"a",function(){return l;});var l=function(){function e(e,t){this.backend=e,this.safeMode=t,this.registeredVariables={},this.refCounter=new WeakMap(),this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numDataBuffers=0,this.gradientScopeCount=0,this.customGradientDepth=0,this.activeScope={keep:[],track:[]},this.scopeStack=[this.activeScope],this.profiler=new s(e);}return e.prototype.runKernel=function(e,t,n){var a,i=this,o=[],s=function s(e){return o.push(e),e;},u=this.activeScope.name;if(this.customGradientDepth++,a=r.ENV.get("DEBUG")?this.profiler.profileKernel(u,function(){return e(i.backend,s);}):e(this.backend,s),this.customGradientDepth--,this.shouldRecord()){var c={id:this.nextTapeNodeId++,name:u,inputs:t,output:a};null!=n&&(c.gradient=function(e){return n(e,o);}),this.activeTape.push(c);}return a;},e.prototype.registerTensor=function(e){var t=this.refCounter.has(e.dataId)?this.refCounter.get(e.dataId):0;this.numTensors++,0===t&&(this.numDataBuffers++,this.numBytes+=o.sizeFromShape(e.shape)*o.bytesPerElement(e.dtype),this.backend.register(e.dataId,e.shape,e.dtype)),this.refCounter.set(e.dataId,t+1),e instanceof c.c||this.track(e);},e.prototype.registerVariable=function(e){if(null!=this.registeredVariables[e.name])throw new Error("Variable with name "+e.name+" was already registered");this.registeredVariables[e.name]=e;},e.prototype.disposeTensor=function(e){if(this.refCounter.has(e.dataId)){this.numTensors--;var t=this.refCounter.get(e.dataId);t<=1?(this.refCounter.delete(e.dataId),this.backend.disposeData(e.dataId),this.numDataBuffers--,this.numBytes-=o.sizeFromShape(e.shape)*o.bytesPerElement(e.dtype)):this.refCounter.set(e.dataId,t-1);}},e.prototype.disposeVariables=function(){for(var e in this.registeredVariables){var t=this.registeredVariables[e];this.disposeTensor(t),delete this.registeredVariables[e];}},e.prototype.memory=function(){var e=this.backend.memory();return e.numTensors=this.numTensors,e.numDataBuffers=this.numDataBuffers,e.numBytes=this.numBytes,e;},e.prototype.shouldRecord=function(){return null!=this.activeTape&&0===this.customGradientDepth;},e.prototype.addTapeNode=function(e,t,n){var r={};e.forEach(function(e,t){r[t]=e;});var a={id:this.nextTapeNodeId++,name:this.activeScope.name,inputs:r,output:t,gradient:function gradient(e){var t={};return n(e).forEach(function(e,n){t[n]=function(){return e;};}),t;}};this.activeTape.push(a);},e.prototype.keep=function(e){if(1===this.scopeStack.length&&r.ENV.engine.safeMode)throw new Error("Safe mode is ON. Enclose all tensor operations inside tf.tidy(): tf.tidy(() => {...}) to avoid memory leaks.");return this.activeScope.keep.push(e),e;},e.prototype.startScope=function(e,t){void 0===t&&(t=!1),t&&0===this.gradientScopeCount&&(this.activeTape=[]),t&&this.gradientScopeCount++;var n={keep:[],track:[]};e&&(n.name=e),this.scopeStack.push(n),this.activeScope=n;},e.prototype.endScope=function(e,t){var n=this;void 0===t&&(t=!1),t&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var r=this.activeScope.keep,a=o.extractTensorsFromContainer(e);r=r.concat(a);for(var i=0;i<this.activeScope.track.length;i++){var s=this.activeScope.track[i];o.isTensorInList(s,r)||(null!=this.activeTape?a.push(s):s.dispose());}this.scopeStack.pop(),this.activeScope=0===this.scopeStack.length?{keep:[],track:[]}:this.scopeStack[this.scopeStack.length-1],a.forEach(function(e){o.isTensorInList(e,n.activeScope.keep)||n.track(e);});},e.prototype.dispose=function(){},e.prototype.gradients=function(e,t,n,r){var s=this;return void 0===r&&(r=!1),o.assert(t.length>0,"gradients() received an empty list of xs."),Object(a.f)("gradients",function(){var a=e();o.assert(a instanceof c.a,"The result y returned by f() must be a tensor.");var u=function(e,t,n){for(var r={},a={},i=0;i<t.length;i++){r[t[i].id]=!0;}for(i=0;i<e.length;i++){var o=(m=e[i]).inputs;for(var s in o){for(var u=o[s],c=!1,l=0;l<t.length;l++){if(r[u.id]){r[m.output.id]=!0,c=!0,a[m.id]=!0;break;}}if(c)break;}}var f={};f[n.id]=!0;var p={};for(i=e.length-1;i>=0;i--){o=(m=e[i]).inputs;var h=[];for(h.push(m.output),l=0;l<h.length;l++){if(f[h[l].id]){for(var s in o){f[o[s].id]=!0,p[m.id]=!0;}break;}}}var d=[];for(i=0;i<e.length;i++){var m;if(a[(m=e[i]).id]&&p[m.id]){var g={};for(var s in m.inputs){var y=m.inputs[s];r[y.id]&&(g[s]=y);}var v=Object.assign({},m);v.inputs=g,v.output=m.output,d.push(v);}}return d;}(s.activeTape,t,a);if(!r&&0===u.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");var l={};return l[a.id]=null==n?i.rb(a.shape):n,function(e,t){for(var n=t.length-1;n>=0;n--){var r=t[n],a=e[r.output.id];if(null==r.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+r.name+".");var i=r.gradient(a);for(var s in r.inputs){if(!(s in i))throw new Error("Cannot backprop through input "+s+". Available gradients found: "+Object.keys(i)+".");var u=i[s](),c=r.inputs[s];if(!o.arraysEqual(u.shape,c.shape))throw new Error("Error in gradient for op "+r.name+". The gradient of input '"+s+"' has shape '"+u.shape+"', which does not match the shape of the input '"+c.shape+"'");if(null==e[c.id])e[c.id]=u;else{var l=e[c.id];e[c.id]=l.add(u),l.dispose();}}}}(l,u),{value:a,grads:t.map(function(e){return l[e.id];})};},!0);},e.prototype.customGrad=function(e){var t=this;return o.assert(o.isFunction(e),"The f passed in customGrad(f) must be a function."),function(){for(var n,r=[],i=0;i<arguments.length;i++){r[i]=arguments[i];}o.assert(r.every(function(e){return e instanceof c.a;}),"The args passed in customGrad(f)(x1, x2,...) must all be tensors"),t.customGradientDepth++;var s=Object(a.f)(e.name,function(){var t=e.apply(void 0,r),a=t.value,i=t.gradFunc;return o.assert(a instanceof c.a,"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),o.assert(o.isFunction(i),"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n=i,a;},!0);return t.customGradientDepth--,t.shouldRecord()&&t.addTapeNode(r,s,function(e){var t=n(e),a=Array.isArray(t)?t:[t];return o.assert(a.length===r.length,"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),o.assert(a.every(function(e){return e instanceof c.a;}),"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."),a;}),s;};},e.prototype.write=function(e,t){this.backend.write(e,t);},e.prototype.readSync=function(e){return this.backend.readSync(e);},e.prototype.read=function(e){return this.backend.read(e);},e.prototype.fromPixels=function(e,t){return this.backend.fromPixels(e,t);},e.prototype.time=function(e){return function(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});}(this,void 0,void 0,function(){var t,n;return function(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}}(this,function(r){switch(r.label){case 0:return t=performance.now(),[4,this.backend.time(e)];case 1:return(n=r.sent()).wallMs=performance.now()-t,[2,n];}});});},e.prototype.track=function(e){if(1===this.scopeStack.length&&this.safeMode)throw new Error("Safe mode is ON. Enclose all tensor operations inside tf.tidy(): tf.tidy(() => {op();...}); to avoid memory leaks.");return this.activeScope.track.push(e),e;},e;}();},function(e){e.exports=[{tfOpName:"Cast",dlOpName:"cast",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"SrcT",dlParamName:"sdtype",type:"dtype",notSupported:!0},{tfParamName:"DstT",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",dlOpName:"expandDims",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,tfParamNameDeprecated:"dim",dlParamName:"axis",type:"number"}]},{tfOpName:"Pad",dlOpName:"pad",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"padding",type:"number[]"},{tfParamName:"constant_value",dlParamName:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",dlOpName:"pad",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"padding",type:"number[]"},{tfInputIndex:2,dlParamName:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",dlOpName:"reshape",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"shape",type:"number[]"}]},{tfOpName:"Squeeze",dlOpName:"squeeze",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"axis",tfParamNameDeprecated:"squeeze_dims",dlParamName:"axis",type:"number[]"}]}];},function(e){e.exports=[{tfOpName:"ConcatV2",dlOpName:"concat",category:"slice_join",params:[{tfInputIndex:0,tfInputParamLength:1,dlParamName:"tensors",type:"tensors"},{tfInputIndex:-1,dlParamName:"axis",type:"number"}]},{tfOpName:"Concat",dlOpName:"concat",category:"slice_join",params:[{tfInputIndex:1,tfInputParamLength:1,dlParamName:"tensors",type:"tensors"},{tfInputIndex:0,dlParamName:"axis",type:"number"}]},{tfOpName:"GatherV2",dlOpName:"gather",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"indices",type:"tensor"},{tfParamName:"axis",dlParamName:"axis",type:"number",defaultValue:0}]},{tfOpName:"Gather",dlOpName:"gather",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"indices",type:"tensor"},{tfParamName:"axis",dlParamName:"axis",type:"number",defaultValue:0},{tfParamName:"validate_indices",dlParamName:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",dlOpName:"reverse",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number"}]},{tfOpName:"ReverseV2",dlOpName:"reverse",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number"}]},{tfOpName:"Slice",dlOpName:"slice",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"begin",type:"number[]"},{tfInputIndex:2,dlParamName:"size",type:"number[]"}]},{tfOpName:"StridedSlice",dlOpName:"stridedSlice",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"begin",type:"number[]"},{tfInputIndex:2,dlParamName:"end",type:"number[]"},{tfInputIndex:3,dlParamName:"strides",type:"number[]"},{tfParamName:"begin_mask",dlParamName:"beginMask",type:"number",defaultValue:0},{tfParamName:"end_mask",dlParamName:"endMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",dlOpName:"stack",category:"slice_join",params:[{tfInputIndex:0,tfInputParamLength:0,dlParamName:"tensors",type:"tensors"},{tfParamName:"axis",dlParamName:"axis",type:"number",defaultValue:0}]},{tfOpName:"Tile",dlOpName:"tile",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"reps",type:"number[]"}]},{tfOpName:"Split",dlOpName:"split",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"axis",type:"number",defaultValue:0},{tfInputIndex:1,dlParamName:"x",type:"tensor"},{tfParamName:"num_split",dlParamName:"numOrSizeSplits",type:"number",defaultValue:1}]}];},function(e){e.exports=[{tfOpName:"Max",dlOpName:"max",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool"}]},{tfOpName:"Mean",dlOpName:"mean",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool"}]},{tfOpName:"Min",dlOpName:"min",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool"}]},{tfOpName:"Sum",dlOpName:"sum",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",dlOpName:"argMax",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number"}]},{tfOpName:"ArgMin",dlOpName:"argMin",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number"}]}];},function(e){e.exports=[{tfOpName:"FusedBatchNorm",dlOpName:"batchNormalization",category:"normalization",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"scale",type:"tensor"},{tfInputIndex:2,dlParamName:"offset",type:"tensor"},{tfInputIndex:3,dlParamName:"mean",type:"tensor"},{tfInputIndex:4,dlParamName:"variance",type:"tensor"},{tfParamName:"epsilon",dlParamName:"epsilon",type:"number",defaultValue:.001},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",dlOpName:"batchNormalization",category:"normalization",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"scale",type:"tensor"},{tfInputIndex:2,dlParamName:"offset",type:"tensor"},{tfInputIndex:3,dlParamName:"mean",type:"tensor"},{tfInputIndex:4,dlParamName:"variance",type:"tensor"},{tfParamName:"epsilon",dlParamName:"epsilon",type:"number",defaultValue:.001},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",dlOpName:"localResponseNormalization",category:"normalization",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"depth_radius",dlParamName:"radius",type:"number",defaultValue:5},{tfParamName:"bias",dlParamName:"bias",type:"number",defaultValue:1},{tfParamName:"alpha",dlParamName:"alpha",type:"number",defaultValue:1},{tfParamName:"beta",dlParamName:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",dlOpName:"softmax",category:"normalization",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]}];},function(e){e.exports=[{tfOpName:"MatMul",dlOpName:"matMul",category:"matrices",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"transpose_a",dlParamName:"transposeA",type:"bool",defaultValue:!1},{tfParamName:"transpose_b",dlParamName:"transposeB",type:"bool",defaultValue:!1},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",dlOpName:"transpose",category:"matrices",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"perm",dlParamName:"perm",type:"number[]"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]}];},function(e){e.exports=[{tfOpName:"Equal",dlOpName:"equal",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",dlOpName:"notEqual",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",dlOpName:"greater",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",dlOpName:"greaterEqual",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",dlOpName:"less",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",dlOpName:"lessEqual",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",dlOpName:"logicalAnd",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",dlOpName:"logicalNot",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",dlOpName:"logicalOr",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",dlOpName:"where",category:"logical",params:[{tfInputIndex:0,dlParamName:"condition",type:"tensor"},{tfInputIndex:1,dlParamName:"a",type:"tensor"},{tfInputIndex:2,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]}];},function(e){e.exports=[{tfOpName:"ResizeBilinear",dlOpName:"resizeBilinear",category:"image",params:[{tfInputIndex:0,dlParamName:"images",type:"tensor"},{tfInputIndex:1,dlParamName:"size",type:"number[]"},{tfParamName:"align_corners",dlParamName:"alignCorners",type:"bool"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",dlOpName:"resizeNearestNeighbor",category:"image",params:[{tfInputIndex:0,dlParamName:"images",type:"tensor"},{tfInputIndex:1,dlParamName:"size",type:"number[]"},{tfParamName:"align_corners",dlParamName:"alignCorners",type:"bool"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]}];},function(e){e.exports=[{tfOpName:"PlaceholderWithDefault",dlOpName:"placeholder",category:"graph",params:[{tfInputIndex:0,dlParamName:"default",type:"tensor"}]},{tfOpName:"Placeholder",dlOpName:"placeholder",category:"graph"},{tfOpName:"Const",dlOpName:"const",category:"graph"},{tfOpName:"Identity",dlOpName:"identity",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"Snapshot",dlOpName:"snapshot",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"Shape",dlOpName:"shape",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"Print",dlOpName:"print",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,tfInputParamLength:1,dlParamName:"data",type:"tensors"},{tfParamName:"message",dlParamName:"message",type:"string"},{tfParamName:"first_n",dlParamName:"firstN",type:"number",notSupprted:!0},{tfParamName:"summarize",dlParamName:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",dlOpName:"noop",category:"graph",params:[]},{tfOpName:"StopGradient",dlOpName:"stopGradient",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",dlOpName:"fakeQuantWithMinMaxVars",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"min",dlParamName:"min",type:"number"},{tfParamName:"max",dlParamName:"max",type:"number"}]}];},function(e){e.exports=[{tfOpName:"Fill",dlOpName:"fill",category:"creation",params:[{tfInputIndex:0,dlParamName:"shape",type:"number[]"},{tfInputIndex:1,dlParamName:"value",type:"number"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LinSpace",dlOpName:"linspace",category:"creation",params:[{tfInputIndex:0,dlParamName:"start",type:"number"},{tfInputIndex:1,dlParamName:"stop",type:"number"},{tfInputIndex:2,dlParamName:"num",type:"number"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",dlOpName:"oneHot",category:"creation",params:[{tfInputIndex:0,dlParamName:"indices",type:"tensor"},{tfInputIndex:1,dlParamName:"depth",type:"number"},{tfInputIndex:2,dlParamName:"onValue",type:"number",defaultValue:1},{tfInputIndex:3,dlParamName:"offValue",type:"number",defaultValue:0},{tfParamName:"axis",dlParamName:"axis",type:"number",notSupported:!0},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",dlOpName:"ones",category:"creation",params:[{tfInputIndex:0,dlParamName:"shape",type:"number[]"},{tfParamName:"T",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",dlOpName:"onesLike",category:"creation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",dlOpName:"randomUniform",category:"creation",params:[{tfInputIndex:0,dlParamName:"shape",type:"number[]"},{tfParamName:"minval",dlParamName:"minval",type:"number",defaultValue:0},{tfParamName:"maxval",dlParamName:"maxval",type:"number",defaultValue:1},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype"},{tfParamName:"seed",dlParamName:"seed",type:"number",defaultValue:0},{tfParamName:"seed2",dlParamName:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfParamName:"T",dlParamName:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",dlOpName:"range",category:"creation",params:[{tfInputIndex:0,dlParamName:"start",type:"number"},{tfInputIndex:1,dlParamName:"stop",type:"number"},{tfInputIndex:2,dlParamName:"step",type:"number",defaultValue:0},{tfParamName:"Tidx",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"truncatedNormal",dlOpName:"truncatedNormal",category:"creation",params:[{tfInputIndex:0,dlParamName:"shape",type:"number[]"},{tfParamName:"means",dlParamName:"mean",type:"number",defaultValue:0},{tfParamName:"stddev",dlParamName:"stdDev",type:"number",defaultValue:1},{tfParamName:"seed",dlParamName:"seed",type:"number"},{tfParamName:"seed2",dlParamName:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype"},{tfParamName:"T",dlParamName:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",dlOpName:"zeros",category:"creation",params:[{tfInputIndex:0,dlParamName:"shape",type:"number[]"},{tfParamName:"T",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",dlOpName:"zerosLike",category:"creation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype"}]}];},function(e){e.exports=[{tfOpName:"AvgPool",dlOpName:"avgPool",category:"convolution",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",notSupported:!0},{tfParamName:"ksize",dlParamName:"kernelSize",type:"number[]"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",dlOpName:"maxPool",category:"convolution",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",notSupported:!0},{tfParamName:"ksize",dlParamName:"kernelSize",type:"number[]"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",dlOpName:"conv1d",category:"convolution",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"filter",type:"tensor"},{tfParamName:"stride",dlParamName:"stride",type:"number"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",defaultValue:"NWC"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0},{tfParamName:"dilation",dlParamName:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",dlOpName:"conv2d",category:"convolution",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"filter",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"useCudnnOnGpu",dlParamName:"useCudnnOnGpu",type:"bool"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",defaultValue:"NHWC"},{tfParamName:"dilations",dlParamName:"dilations",type:"number[]"}]},{tfOpName:"Conv2DBackpropInput",dlOpName:"conv2dTranspose",category:"convolution",params:[{tfInputIndex:2,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"filter",type:"tensor"},{tfInputIndex:0,dlParamName:"outputShape",type:"number[]"},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",dlOpName:"depthwiseConv2d",category:"convolution",params:[{tfInputIndex:0,dlParamName:"input",type:"tensor"},{tfInputIndex:1,dlParamName:"filter",type:"tensor"},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",defaultValue:"NHWC"},{tfParamName:"dilations",dlParamName:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",dlOpName:"depthwiseConv2d",category:"convolution",params:[{tfInputIndex:0,dlParamName:"input",type:"tensor"},{tfInputIndex:1,dlParamName:"filter",type:"tensor"},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",defaultValue:"NHWC"},{tfParamName:"dilations",dlParamName:"dilations",type:"number[]"}]}];},function(e){e.exports=[{tfOpName:"LoopCond",dlOpName:"loopCond",category:"control",params:[{tfInputIndex:0,dlParamName:"pred",type:"tensor"}]},{tfOpName:"Switch",dlOpName:"switch",category:"control",params:[{tfInputIndex:0,dlParamName:"data",type:"tensor"},{tfInputIndex:1,dlParamName:"pred",type:"tensor"}]},{tfOpName:"Merge",dlOpName:"merge",category:"control",params:[{tfInputIndex:0,tfInputParamLength:0,dlParamName:"tensors",type:"tensors"}]},{tfOpName:"Enter",dlOpName:"enter",category:"control",params:[{tfInputIndex:0,dlParamName:"tensor",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0},{tfParamName:"frame_name",dlParamName:"frameName",type:"string"},{tfParamName:"is_constant",dlParamName:"isConstant",type:"bool"}]},{tfOpName:"Exit",dlOpName:"exit",category:"control",params:[{tfInputIndex:0,dlParamName:"tensor",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",dlOpName:"nextIteration",category:"control",params:[{tfInputIndex:0,dlParamName:"tensor",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]}];},function(e){e.exports=[{tfOpName:"Abs",dlOpName:"abs",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",dlOpName:"acos",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",dlOpName:"asin",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"atan",dlOpName:"atan",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",dlOpName:"ceil",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",dlOpName:"clipByValue",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"clip_value_min",dlParamName:"clipValueMin",type:"number"},{tfParamName:"clip_value_max",dlParamName:"clipValueMax",type:"number"}]},{tfOpName:"Cos",dlOpName:"cos",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",dlOpName:"cosh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",dlOpName:"elu",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",dlOpName:"exp",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",dlOpName:"floor",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",dlOpName:"log",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",dlOpName:"neg",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",dlOpName:"relu",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",dlOpName:"clipByValue",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0},{dlParamName:"clipValueMin",type:"number",defaultValue:0},{dlParamName:"clipValueMax",type:"number",defaultValue:6}]},{tfOpName:"Selu",dlOpName:"selu",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",dlOpName:"sigmoid",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",dlOpName:"sin",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",dlOpName:"sinh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",dlOpName:"sqrt",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",dlOpName:"rsqrt",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",dlOpName:"square",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",dlOpName:"tan",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",dlOpName:"tanh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",dlOpName:"sign",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",dlOpName:"round",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",dlOpName:"expm1",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",dlOpName:"log1p",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",dlOpName:"reciprocal",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",dlOpName:"reciprocal",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",dlOpName:"softplus",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",dlOpName:"asinh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",dlOpName:"acosh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",dlOpName:"atanh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",dlOpName:"erf",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]}];},function(e){e.exports=[{tfOpName:"Add",dlOpName:"add",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BiasAdd",dlOpName:"add",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sub",dlOpName:"sub",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",dlOpName:"div",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",dlOpName:"div",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",dlOpName:"mul",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",dlOpName:"maximum",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"}]},{tfOpName:"Minimum",dlOpName:"minimum",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"}]},{tfOpName:"Pow",dlOpName:"pow",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",dlOpName:"squaredDifference",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",dlOpName:"mod",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]}];},function(e,t,n){"use strict";function r(){var e=navigator.userAgent||navigator.vendor||window.opera;return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4));}n.d(t,"a",function(){return r;});},function(e,t,n){"use strict";n.r(t);var r=n(10),a={0:"tench, Tinca tinca",1:"goldfish, Carassius auratus",2:"great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",3:"tiger shark, Galeocerdo cuvieri",4:"hammerhead, hammerhead shark",5:"electric ray, crampfish, numbfish, torpedo",6:"stingray",7:"cock",8:"hen",9:"ostrich, Struthio camelus",10:"brambling, Fringilla montifringilla",11:"goldfinch, Carduelis carduelis",12:"house finch, linnet, Carpodacus mexicanus",13:"junco, snowbird",14:"indigo bunting, indigo finch, indigo bird, Passerina cyanea",15:"robin, American robin, Turdus migratorius",16:"bulbul",17:"jay",18:"magpie",19:"chickadee",20:"water ouzel, dipper",21:"kite",22:"bald eagle, American eagle, Haliaeetus leucocephalus",23:"vulture",24:"great grey owl, great gray owl, Strix nebulosa",25:"European fire salamander, Salamandra salamandra",26:"common newt, Triturus vulgaris",27:"eft",28:"spotted salamander, Ambystoma maculatum",29:"axolotl, mud puppy, Ambystoma mexicanum",30:"bullfrog, Rana catesbeiana",31:"tree frog, tree-frog",32:"tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",33:"loggerhead, loggerhead turtle, Caretta caretta",34:"leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",35:"mud turtle",36:"terrapin",37:"box turtle, box tortoise",38:"banded gecko",39:"common iguana, iguana, Iguana iguana",40:"American chameleon, anole, Anolis carolinensis",41:"whiptail, whiptail lizard",42:"agama",43:"frilled lizard, Chlamydosaurus kingi",44:"alligator lizard",45:"Gila monster, Heloderma suspectum",46:"green lizard, Lacerta viridis",47:"African chameleon, Chamaeleo chamaeleon",48:"Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",49:"African crocodile, Nile crocodile, Crocodylus niloticus",50:"American alligator, Alligator mississipiensis",51:"triceratops",52:"thunder snake, worm snake, Carphophis amoenus",53:"ringneck snake, ring-necked snake, ring snake",54:"hognose snake, puff adder, sand viper",55:"green snake, grass snake",56:"king snake, kingsnake",57:"garter snake, grass snake",58:"water snake",59:"vine snake",60:"night snake, Hypsiglena torquata",61:"boa constrictor, Constrictor constrictor",62:"rock python, rock snake, Python sebae",63:"Indian cobra, Naja naja",64:"green mamba",65:"sea snake",66:"horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",67:"diamondback, diamondback rattlesnake, Crotalus adamanteus",68:"sidewinder, horned rattlesnake, Crotalus cerastes",69:"trilobite",70:"harvestman, daddy longlegs, Phalangium opilio",71:"scorpion",72:"black and gold garden spider, Argiope aurantia",73:"barn spider, Araneus cavaticus",74:"garden spider, Aranea diademata",75:"black widow, Latrodectus mactans",76:"tarantula",77:"wolf spider, hunting spider",78:"tick",79:"centipede",80:"black grouse",81:"ptarmigan",82:"ruffed grouse, partridge, Bonasa umbellus",83:"prairie chicken, prairie grouse, prairie fowl",84:"peacock",85:"quail",86:"partridge",87:"African grey, African gray, Psittacus erithacus",88:"macaw",89:"sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",90:"lorikeet",91:"coucal",92:"bee eater",93:"hornbill",94:"hummingbird",95:"jacamar",96:"toucan",97:"drake",98:"red-breasted merganser, Mergus serrator",99:"goose",100:"black swan, Cygnus atratus",101:"tusker",102:"echidna, spiny anteater, anteater",103:"platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",104:"wallaby, brush kangaroo",105:"koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",106:"wombat",107:"jelly fish",108:"sea anemone, anemone",109:"brain coral",110:"flatworm, platyhelminth",111:"nematode, nematode worm, roundworm",112:"conch",113:"snail",114:"slug",115:"sea slug, nudibranch",116:"chiton, coat-of-mail shell, sea cradle, polyplacophore",117:"chambered nautilus, pearly nautilus, nautilus",118:"Dungeness crab, Cancer magister",119:"rock crab, Cancer irroratus",120:"fiddler crab",121:"king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",122:"American lobster, Northern lobster, Maine lobster, Homarus americanus",123:"spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",124:"crayfish, crawfish, crawdad, crawdaddy",125:"hermit crab",126:"isopod",127:"white stork, Ciconia ciconia",128:"black stork, Ciconia nigra",129:"spoonbill",130:"flamingo",131:"little blue heron, Egretta caerulea",132:"American egret, great white heron, Egretta albus",133:"bittern",134:"crane",135:"limpkin, Aramus pictus",136:"European gallinule, Porphyrio porphyrio",137:"American coot, marsh hen, mud hen, water hen, Fulica americana",138:"bustard",139:"ruddy turnstone, Arenaria interpres",140:"red-backed sandpiper, dunlin, Erolia alpina",141:"redshank, Tringa totanus",142:"dowitcher",143:"oystercatcher, oyster catcher",144:"pelican",145:"king penguin, Aptenodytes patagonica",146:"albatross, mollymawk",147:"grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",148:"killer whale, killer, orca, grampus, sea wolf, Orcinus orca",149:"dugong, Dugong dugon",150:"sea lion",151:"Chihuahua",152:"Japanese spaniel",153:"Maltese dog, Maltese terrier, Maltese",154:"Pekinese, Pekingese, Peke",155:"Shih-Tzu",156:"Blenheim spaniel",157:"papillon",158:"toy terrier",159:"Rhodesian ridgeback",160:"Afghan hound, Afghan",161:"basset, basset hound",162:"beagle",163:"bloodhound, sleuthhound",164:"bluetick",165:"black-and-tan coonhound",166:"Walker hound, Walker foxhound",167:"English foxhound",168:"redbone",169:"borzoi, Russian wolfhound",170:"Irish wolfhound",171:"Italian greyhound",172:"whippet",173:"Ibizan hound, Ibizan Podenco",174:"Norwegian elkhound, elkhound",175:"otterhound, otter hound",176:"Saluki, gazelle hound",177:"Scottish deerhound, deerhound",178:"Weimaraner",179:"Staffordshire bullterrier, Staffordshire bull terrier",180:"American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",181:"Bedlington terrier",182:"Border terrier",183:"Kerry blue terrier",184:"Irish terrier",185:"Norfolk terrier",186:"Norwich terrier",187:"Yorkshire terrier",188:"wire-haired fox terrier",189:"Lakeland terrier",190:"Sealyham terrier, Sealyham",191:"Airedale, Airedale terrier",192:"cairn, cairn terrier",193:"Australian terrier",194:"Dandie Dinmont, Dandie Dinmont terrier",195:"Boston bull, Boston terrier",196:"miniature schnauzer",197:"giant schnauzer",198:"standard schnauzer",199:"Scotch terrier, Scottish terrier, Scottie",200:"Tibetan terrier, chrysanthemum dog",201:"silky terrier, Sydney silky",202:"soft-coated wheaten terrier",203:"West Highland white terrier",204:"Lhasa, Lhasa apso",205:"flat-coated retriever",206:"curly-coated retriever",207:"golden retriever",208:"Labrador retriever",209:"Chesapeake Bay retriever",210:"German short-haired pointer",211:"vizsla, Hungarian pointer",212:"English setter",213:"Irish setter, red setter",214:"Gordon setter",215:"Brittany spaniel",216:"clumber, clumber spaniel",217:"English springer, English springer spaniel",218:"Welsh springer spaniel",219:"cocker spaniel, English cocker spaniel, cocker",220:"Sussex spaniel",221:"Irish water spaniel",222:"kuvasz",223:"schipperke",224:"groenendael",225:"malinois",226:"briard",227:"kelpie",228:"komondor",229:"Old English sheepdog, bobtail",230:"Shetland sheepdog, Shetland sheep dog, Shetland",231:"collie",232:"Border collie",233:"Bouvier des Flandres, Bouviers des Flandres",234:"Rottweiler",235:"German shepherd, German shepherd dog, German police dog, alsatian",236:"Doberman, Doberman pinscher",237:"miniature pinscher",238:"Greater Swiss Mountain dog",239:"Bernese mountain dog",240:"Appenzeller",241:"EntleBucher",242:"boxer",243:"bull mastiff",244:"Tibetan mastiff",245:"French bulldog",246:"Great Dane",247:"Saint Bernard, St Bernard",248:"Eskimo dog, husky",249:"malamute, malemute, Alaskan malamute",250:"Siberian husky",251:"dalmatian, coach dog, carriage dog",252:"affenpinscher, monkey pinscher, monkey dog",253:"basenji",254:"pug, pug-dog",255:"Leonberg",256:"Newfoundland, Newfoundland dog",257:"Great Pyrenees",258:"Samoyed, Samoyede",259:"Pomeranian",260:"chow, chow chow",261:"keeshond",262:"Brabancon griffon",263:"Pembroke, Pembroke Welsh corgi",264:"Cardigan, Cardigan Welsh corgi",265:"toy poodle",266:"miniature poodle",267:"standard poodle",268:"Mexican hairless",269:"timber wolf, grey wolf, gray wolf, Canis lupus",270:"white wolf, Arctic wolf, Canis lupus tundrarum",271:"red wolf, maned wolf, Canis rufus, Canis niger",272:"coyote, prairie wolf, brush wolf, Canis latrans",273:"dingo, warrigal, warragal, Canis dingo",274:"dhole, Cuon alpinus",275:"African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",276:"hyena, hyaena",277:"red fox, Vulpes vulpes",278:"kit fox, Vulpes macrotis",279:"Arctic fox, white fox, Alopex lagopus",280:"grey fox, gray fox, Urocyon cinereoargenteus",281:"tabby, tabby cat",282:"tiger cat",283:"Persian cat",284:"Siamese cat, Siamese",285:"Egyptian cat",286:"cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",287:"lynx, catamount",288:"leopard, Panthera pardus",289:"snow leopard, ounce, Panthera uncia",290:"jaguar, panther, Panthera onca, Felis onca",291:"lion, king of beasts, Panthera leo",292:"tiger, Panthera tigris",293:"cheetah, chetah, Acinonyx jubatus",294:"brown bear, bruin, Ursus arctos",295:"American black bear, black bear, Ursus americanus, Euarctos americanus",296:"ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",297:"sloth bear, Melursus ursinus, Ursus ursinus",298:"mongoose",299:"meerkat, mierkat",300:"tiger beetle",301:"ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",302:"ground beetle, carabid beetle",303:"long-horned beetle, longicorn, longicorn beetle",304:"leaf beetle, chrysomelid",305:"dung beetle",306:"rhinoceros beetle",307:"weevil",308:"fly",309:"bee",310:"ant, emmet, pismire",311:"grasshopper, hopper",312:"cricket",313:"walking stick, walkingstick, stick insect",314:"cockroach, roach",315:"mantis, mantid",316:"cicada, cicala",317:"leafhopper",318:"lacewing, lacewing fly",319:"dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",320:"damselfly",321:"admiral",322:"ringlet, ringlet butterfly",323:"monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",324:"cabbage butterfly",325:"sulphur butterfly, sulfur butterfly",326:"lycaenid, lycaenid butterfly",327:"starfish, sea star",328:"sea urchin",329:"sea cucumber, holothurian",330:"wood rabbit, cottontail, cottontail rabbit",331:"hare",332:"Angora, Angora rabbit",333:"hamster",334:"porcupine, hedgehog",335:"fox squirrel, eastern fox squirrel, Sciurus niger",336:"marmot",337:"beaver",338:"guinea pig, Cavia cobaya",339:"sorrel",340:"zebra",341:"hog, pig, grunter, squealer, Sus scrofa",342:"wild boar, boar, Sus scrofa",343:"warthog",344:"hippopotamus, hippo, river horse, Hippopotamus amphibius",345:"ox",346:"water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",347:"bison",348:"ram, tup",349:"bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",350:"ibex, Capra ibex",351:"hartebeest",352:"impala, Aepyceros melampus",353:"gazelle",354:"Arabian camel, dromedary, Camelus dromedarius",355:"llama",356:"weasel",357:"mink",358:"polecat, fitch, foulmart, foumart, Mustela putorius",359:"black-footed ferret, ferret, Mustela nigripes",360:"otter",361:"skunk, polecat, wood pussy",362:"badger",363:"armadillo",364:"three-toed sloth, ai, Bradypus tridactylus",365:"orangutan, orang, orangutang, Pongo pygmaeus",366:"gorilla, Gorilla gorilla",367:"chimpanzee, chimp, Pan troglodytes",368:"gibbon, Hylobates lar",369:"siamang, Hylobates syndactylus, Symphalangus syndactylus",370:"guenon, guenon monkey",371:"patas, hussar monkey, Erythrocebus patas",372:"baboon",373:"macaque",374:"langur",375:"colobus, colobus monkey",376:"proboscis monkey, Nasalis larvatus",377:"marmoset",378:"capuchin, ringtail, Cebus capucinus",379:"howler monkey, howler",380:"titi, titi monkey",381:"spider monkey, Ateles geoffroyi",382:"squirrel monkey, Saimiri sciureus",383:"Madagascar cat, ring-tailed lemur, Lemur catta",384:"indri, indris, Indri indri, Indri brevicaudatus",385:"Indian elephant, Elephas maximus",386:"African elephant, Loxodonta africana",387:"lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",388:"giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",389:"barracouta, snoek",390:"eel",391:"coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",392:"rock beauty, Holocanthus tricolor",393:"anemone fish",394:"sturgeon",395:"gar, garfish, garpike, billfish, Lepisosteus osseus",396:"lionfish",397:"puffer, pufferfish, blowfish, globefish",398:"abacus",399:"abaya",400:"academic gown, academic robe, judge's robe",401:"accordion, piano accordion, squeeze box",402:"acoustic guitar",403:"aircraft carrier, carrier, flattop, attack aircraft carrier",404:"airliner",405:"airship, dirigible",406:"altar",407:"ambulance",408:"amphibian, amphibious vehicle",409:"analog clock",410:"apiary, bee house",411:"apron",412:"ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",413:"assault rifle, assault gun",414:"backpack, back pack, knapsack, packsack, rucksack, haversack",415:"bakery, bakeshop, bakehouse",416:"balance beam, beam",417:"balloon",418:"ballpoint, ballpoint pen, ballpen, Biro",419:"Band Aid",420:"banjo",421:"bannister, banister, balustrade, balusters, handrail",422:"barbell",423:"barber chair",424:"barbershop",425:"barn",426:"barometer",427:"barrel, cask",428:"barrow, garden cart, lawn cart, wheelbarrow",429:"baseball",430:"basketball",431:"bassinet",432:"bassoon",433:"bathing cap, swimming cap",434:"bath towel",435:"bathtub, bathing tub, bath, tub",436:"beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",437:"beacon, lighthouse, beacon light, pharos",438:"beaker",439:"bearskin, busby, shako",440:"beer bottle",441:"beer glass",442:"bell cote, bell cot",443:"bib",444:"bicycle-built-for-two, tandem bicycle, tandem",445:"bikini, two-piece",446:"binder, ring-binder",447:"binoculars, field glasses, opera glasses",448:"birdhouse",449:"boathouse",450:"bobsled, bobsleigh, bob",451:"bolo tie, bolo, bola tie, bola",452:"bonnet, poke bonnet",453:"bookcase",454:"bookshop, bookstore, bookstall",455:"bottlecap",456:"bow",457:"bow tie, bow-tie, bowtie",458:"brass, memorial tablet, plaque",459:"brassiere, bra, bandeau",460:"breakwater, groin, groyne, mole, bulwark, seawall, jetty",461:"breastplate, aegis, egis",462:"broom",463:"bucket, pail",464:"buckle",465:"bulletproof vest",466:"bullet train, bullet",467:"butcher shop, meat market",468:"cab, hack, taxi, taxicab",469:"caldron, cauldron",470:"candle, taper, wax light",471:"cannon",472:"canoe",473:"can opener, tin opener",474:"cardigan",475:"car mirror",476:"carousel, carrousel, merry-go-round, roundabout, whirligig",477:"carpenter's kit, tool kit",478:"carton",479:"car wheel",480:"cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",481:"cassette",482:"cassette player",483:"castle",484:"catamaran",485:"CD player",486:"cello, violoncello",487:"cellular telephone, cellular phone, cellphone, cell, mobile phone",488:"chain",489:"chainlink fence",490:"chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",491:"chain saw, chainsaw",492:"chest",493:"chiffonier, commode",494:"chime, bell, gong",495:"china cabinet, china closet",496:"Christmas stocking",497:"church, church building",498:"cinema, movie theater, movie theatre, movie house, picture palace",499:"cleaver, meat cleaver, chopper",500:"cliff dwelling",501:"cloak",502:"clog, geta, patten, sabot",503:"cocktail shaker",504:"coffee mug",505:"coffeepot",506:"coil, spiral, volute, whorl, helix",507:"combination lock",508:"computer keyboard, keypad",509:"confectionery, confectionary, candy store",510:"container ship, containership, container vessel",511:"convertible",512:"corkscrew, bottle screw",513:"cornet, horn, trumpet, trump",514:"cowboy boot",515:"cowboy hat, ten-gallon hat",516:"cradle",517:"crane",518:"crash helmet",519:"crate",520:"crib, cot",521:"Crock Pot",522:"croquet ball",523:"crutch",524:"cuirass",525:"dam, dike, dyke",526:"desk",527:"desktop computer",528:"dial telephone, dial phone",529:"diaper, nappy, napkin",530:"digital clock",531:"digital watch",532:"dining table, board",533:"dishrag, dishcloth",534:"dishwasher, dish washer, dishwashing machine",535:"disk brake, disc brake",536:"dock, dockage, docking facility",537:"dogsled, dog sled, dog sleigh",538:"dome",539:"doormat, welcome mat",540:"drilling platform, offshore rig",541:"drum, membranophone, tympan",542:"drumstick",543:"dumbbell",544:"Dutch oven",545:"electric fan, blower",546:"electric guitar",547:"electric locomotive",548:"entertainment center",549:"envelope",550:"espresso maker",551:"face powder",552:"feather boa, boa",553:"file, file cabinet, filing cabinet",554:"fireboat",555:"fire engine, fire truck",556:"fire screen, fireguard",557:"flagpole, flagstaff",558:"flute, transverse flute",559:"folding chair",560:"football helmet",561:"forklift",562:"fountain",563:"fountain pen",564:"four-poster",565:"freight car",566:"French horn, horn",567:"frying pan, frypan, skillet",568:"fur coat",569:"garbage truck, dustcart",570:"gasmask, respirator, gas helmet",571:"gas pump, gasoline pump, petrol pump, island dispenser",572:"goblet",573:"go-kart",574:"golf ball",575:"golfcart, golf cart",576:"gondola",577:"gong, tam-tam",578:"gown",579:"grand piano, grand",580:"greenhouse, nursery, glasshouse",581:"grille, radiator grille",582:"grocery store, grocery, food market, market",583:"guillotine",584:"hair slide",585:"hair spray",586:"half track",587:"hammer",588:"hamper",589:"hand blower, blow dryer, blow drier, hair dryer, hair drier",590:"hand-held computer, hand-held microcomputer",591:"handkerchief, hankie, hanky, hankey",592:"hard disc, hard disk, fixed disk",593:"harmonica, mouth organ, harp, mouth harp",594:"harp",595:"harvester, reaper",596:"hatchet",597:"holster",598:"home theater, home theatre",599:"honeycomb",600:"hook, claw",601:"hoopskirt, crinoline",602:"horizontal bar, high bar",603:"horse cart, horse-cart",604:"hourglass",605:"iPod",606:"iron, smoothing iron",607:"jack-o'-lantern",608:"jean, blue jean, denim",609:"jeep, landrover",610:"jersey, T-shirt, tee shirt",611:"jigsaw puzzle",612:"jinrikisha, ricksha, rickshaw",613:"joystick",614:"kimono",615:"knee pad",616:"knot",617:"lab coat, laboratory coat",618:"ladle",619:"lampshade, lamp shade",620:"laptop, laptop computer",621:"lawn mower, mower",622:"lens cap, lens cover",623:"letter opener, paper knife, paperknife",624:"library",625:"lifeboat",626:"lighter, light, igniter, ignitor",627:"limousine, limo",628:"liner, ocean liner",629:"lipstick, lip rouge",630:"Loafer",631:"lotion",632:"loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",633:"loupe, jeweler's loupe",634:"lumbermill, sawmill",635:"magnetic compass",636:"mailbag, postbag",637:"mailbox, letter box",638:"maillot",639:"maillot, tank suit",640:"manhole cover",641:"maraca",642:"marimba, xylophone",643:"mask",644:"matchstick",645:"maypole",646:"maze, labyrinth",647:"measuring cup",648:"medicine chest, medicine cabinet",649:"megalith, megalithic structure",650:"microphone, mike",651:"microwave, microwave oven",652:"military uniform",653:"milk can",654:"minibus",655:"miniskirt, mini",656:"minivan",657:"missile",658:"mitten",659:"mixing bowl",660:"mobile home, manufactured home",661:"Model T",662:"modem",663:"monastery",664:"monitor",665:"moped",666:"mortar",667:"mortarboard",668:"mosque",669:"mosquito net",670:"motor scooter, scooter",671:"mountain bike, all-terrain bike, off-roader",672:"mountain tent",673:"mouse, computer mouse",674:"mousetrap",675:"moving van",676:"muzzle",677:"nail",678:"neck brace",679:"necklace",680:"nipple",681:"notebook, notebook computer",682:"obelisk",683:"oboe, hautboy, hautbois",684:"ocarina, sweet potato",685:"odometer, hodometer, mileometer, milometer",686:"oil filter",687:"organ, pipe organ",688:"oscilloscope, scope, cathode-ray oscilloscope, CRO",689:"overskirt",690:"oxcart",691:"oxygen mask",692:"packet",693:"paddle, boat paddle",694:"paddlewheel, paddle wheel",695:"padlock",696:"paintbrush",697:"pajama, pyjama, pj's, jammies",698:"palace",699:"panpipe, pandean pipe, syrinx",700:"paper towel",701:"parachute, chute",702:"parallel bars, bars",703:"park bench",704:"parking meter",705:"passenger car, coach, carriage",706:"patio, terrace",707:"pay-phone, pay-station",708:"pedestal, plinth, footstall",709:"pencil box, pencil case",710:"pencil sharpener",711:"perfume, essence",712:"Petri dish",713:"photocopier",714:"pick, plectrum, plectron",715:"pickelhaube",716:"picket fence, paling",717:"pickup, pickup truck",718:"pier",719:"piggy bank, penny bank",720:"pill bottle",721:"pillow",722:"ping-pong ball",723:"pinwheel",724:"pirate, pirate ship",725:"pitcher, ewer",726:"plane, carpenter's plane, woodworking plane",727:"planetarium",728:"plastic bag",729:"plate rack",730:"plow, plough",731:"plunger, plumber's helper",732:"Polaroid camera, Polaroid Land camera",733:"pole",734:"police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",735:"poncho",736:"pool table, billiard table, snooker table",737:"pop bottle, soda bottle",738:"pot, flowerpot",739:"potter's wheel",740:"power drill",741:"prayer rug, prayer mat",742:"printer",743:"prison, prison house",744:"projectile, missile",745:"projector",746:"puck, hockey puck",747:"punching bag, punch bag, punching ball, punchball",748:"purse",749:"quill, quill pen",750:"quilt, comforter, comfort, puff",751:"racer, race car, racing car",752:"racket, racquet",753:"radiator",754:"radio, wireless",755:"radio telescope, radio reflector",756:"rain barrel",757:"recreational vehicle, RV, R.V.",758:"reel",759:"reflex camera",760:"refrigerator, icebox",761:"remote control, remote",762:"restaurant, eating house, eating place, eatery",763:"revolver, six-gun, six-shooter",764:"rifle",765:"rocking chair, rocker",766:"rotisserie",767:"rubber eraser, rubber, pencil eraser",768:"rugby ball",769:"rule, ruler",770:"running shoe",771:"safe",772:"safety pin",773:"saltshaker, salt shaker",774:"sandal",775:"sarong",776:"sax, saxophone",777:"scabbard",778:"scale, weighing machine",779:"school bus",780:"schooner",781:"scoreboard",782:"screen, CRT screen",783:"screw",784:"screwdriver",785:"seat belt, seatbelt",786:"sewing machine",787:"shield, buckler",788:"shoe shop, shoe-shop, shoe store",789:"shoji",790:"shopping basket",791:"shopping cart",792:"shovel",793:"shower cap",794:"shower curtain",795:"ski",796:"ski mask",797:"sleeping bag",798:"slide rule, slipstick",799:"sliding door",800:"slot, one-armed bandit",801:"snorkel",802:"snowmobile",803:"snowplow, snowplough",804:"soap dispenser",805:"soccer ball",806:"sock",807:"solar dish, solar collector, solar furnace",808:"sombrero",809:"soup bowl",810:"space bar",811:"space heater",812:"space shuttle",813:"spatula",814:"speedboat",815:"spider web, spider's web",816:"spindle",817:"sports car, sport car",818:"spotlight, spot",819:"stage",820:"steam locomotive",821:"steel arch bridge",822:"steel drum",823:"stethoscope",824:"stole",825:"stone wall",826:"stopwatch, stop watch",827:"stove",828:"strainer",829:"streetcar, tram, tramcar, trolley, trolley car",830:"stretcher",831:"studio couch, day bed",832:"stupa, tope",833:"submarine, pigboat, sub, U-boat",834:"suit, suit of clothes",835:"sundial",836:"sunglass",837:"sunglasses, dark glasses, shades",838:"sunscreen, sunblock, sun blocker",839:"suspension bridge",840:"swab, swob, mop",841:"sweatshirt",842:"swimming trunks, bathing trunks",843:"swing",844:"switch, electric switch, electrical switch",845:"syringe",846:"table lamp",847:"tank, army tank, armored combat vehicle, armoured combat vehicle",848:"tape player",849:"teapot",850:"teddy, teddy bear",851:"television, television system",852:"tennis ball",853:"thatch, thatched roof",854:"theater curtain, theatre curtain",855:"thimble",856:"thresher, thrasher, threshing machine",857:"throne",858:"tile roof",859:"toaster",860:"tobacco shop, tobacconist shop, tobacconist",861:"toilet seat",862:"torch",863:"totem pole",864:"tow truck, tow car, wrecker",865:"toyshop",866:"tractor",867:"trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",868:"tray",869:"trench coat",870:"tricycle, trike, velocipede",871:"trimaran",872:"tripod",873:"triumphal arch",874:"trolleybus, trolley coach, trackless trolley",875:"trombone",876:"tub, vat",877:"turnstile",878:"typewriter keyboard",879:"umbrella",880:"unicycle, monocycle",881:"upright, upright piano",882:"vacuum, vacuum cleaner",883:"vase",884:"vault",885:"velvet",886:"vending machine",887:"vestment",888:"viaduct",889:"violin, fiddle",890:"volleyball",891:"waffle iron",892:"wall clock",893:"wallet, billfold, notecase, pocketbook",894:"wardrobe, closet, press",895:"warplane, military plane",896:"washbasin, handbasin, washbowl, lavabo, wash-hand basin",897:"washer, automatic washer, washing machine",898:"water bottle",899:"water jug",900:"water tower",901:"whiskey jug",902:"whistle",903:"wig",904:"window screen",905:"window shade",906:"Windsor tie",907:"wine bottle",908:"wing",909:"wok",910:"wooden spoon",911:"wool, woolen, woollen",912:"worm fence, snake fence, snake-rail fence, Virginia fence",913:"wreck",914:"yawl",915:"yurt",916:"web site, website, internet site, site",917:"comic book",918:"crossword puzzle, crossword",919:"street sign",920:"traffic light, traffic signal, stoplight",921:"book jacket, dust cover, dust jacket, dust wrapper",922:"menu",923:"plate",924:"guacamole",925:"consomme",926:"hot pot, hotpot",927:"trifle",928:"ice cream, icecream",929:"ice lolly, lolly, lollipop, popsicle",930:"French loaf",931:"bagel, beigel",932:"pretzel",933:"cheeseburger",934:"hotdog, hot dog, red hot",935:"mashed potato",936:"head cabbage",937:"broccoli",938:"cauliflower",939:"zucchini, courgette",940:"spaghetti squash",941:"acorn squash",942:"butternut squash",943:"cucumber, cuke",944:"artichoke, globe artichoke",945:"bell pepper",946:"cardoon",947:"mushroom",948:"Granny Smith",949:"strawberry",950:"orange",951:"lemon",952:"fig",953:"pineapple, ananas",954:"banana",955:"jackfruit, jak, jack",956:"custard apple",957:"pomegranate",958:"hay",959:"carbonara",960:"chocolate sauce, chocolate syrup",961:"dough",962:"meat loaf, meatloaf",963:"pizza, pizza pie",964:"potpie",965:"burrito",966:"red wine",967:"espresso",968:"cup",969:"eggnog",970:"alp",971:"bubble",972:"cliff, drop, drop-off",973:"coral reef",974:"geyser",975:"lakeside, lakeshore",976:"promontory, headland, head, foreland",977:"sandbar, sand bar",978:"seashore, coast, seacoast, sea-coast",979:"valley, vale",980:"volcano",981:"ballplayer, baseball player",982:"groom, bridegroom",983:"scuba diver",984:"rapeseed",985:"daisy",986:"yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",987:"corn",988:"acorn",989:"hip, rose hip, rosehip",990:"buckeye, horse chestnut, conker",991:"coral fungus",992:"agaric",993:"gyromitra",994:"stinkhorn, carrion fungus",995:"earthstar",996:"hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",997:"bolete",998:"ear, spike, capitulum",999:"toilet tissue, toilet paper, bathroom tissue"};n.d(t,"load",function(){return c;}),n.d(t,"MobileNet",function(){return l;});var i=function i(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});},o=function o(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=r[2&i[0]?"return":i[0]?"throw":"next"])&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[0,a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}},s="https://storage.googleapis.com/tfjs-models/tfjs/",u=224;function c(e,t){return void 0===e&&(e=1),void 0===t&&(t=1),i(this,void 0,void 0,function(){var n;return o(this,function(a){switch(a.label){case 0:if(null==r)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this model.");if(1!==e)throw new Error("Currently only MobileNet V1 is supported. Got version "+e+".");if(-1===[.25,.5,.75,1].indexOf(t))throw new Error("MobileNet constructed with invalid alpha "+t+". Valid multipliers are 0.25, 0.50, 0.75, and 1.0.");return[4,(n=new l(e,t)).load()];case 1:return a.sent(),[2,n];}});});}var l=function(){function e(e,t){this.intermediateModels={};var n={.25:"0.25",.5:"0.50",.75:"0.75",1:"1.0"}[t];this.path=s+"mobilenet_v"+e+"_"+n+"_"+u+"/model.json",this.normalizationOffset=r.scalar(127.5);}return e.prototype.load=function(){return i(this,void 0,void 0,function(){var e,t;return o(this,function(n){switch(n.label){case 0:return e=this,[4,r.loadModel(this.path)];case 1:return e.model=n.sent(),this.endpoints=this.model.layers.map(function(e){return e.name;}),[4,(t=this.model.predict(r.zeros([1,u,u,3]))).data()];case 2:return n.sent(),t.dispose(),[2];}});});},e.prototype.infer=function(e,t){var n=this;if(null!=t&&-1===this.endpoints.indexOf(t))throw new Error("Unknown endpoint "+t+". Available endpoints: "+this.endpoints+".");return r.tidy(function(){e instanceof r.Tensor||(e=r.fromPixels(e));var a=e.toFloat().sub(n.normalizationOffset).div(n.normalizationOffset),i=a;e.shape[0]===u&&e.shape[1]===u||(i=r.image.resizeBilinear(a,[u,u],!0));var o,s=i.reshape([1,u,u,3]);if(null==t)o=n.model;else{if(null==n.intermediateModels[t]){var c=n.model.layers.find(function(e){return e.name===t;});n.intermediateModels[t]=r.model({inputs:n.model.inputs,outputs:c.output});}o=n.intermediateModels[t];}return o.predict(s);});},e.prototype.classify=function(e,t){return void 0===t&&(t=3),i(this,void 0,void 0,function(){var n,r;return o(this,function(s){switch(s.label){case 0:return[4,function(e,t){return i(this,void 0,void 0,function(){var n,r,i,s,u,c;return o(this,function(o){switch(o.label){case 0:return[4,e.data()];case 1:for(n=o.sent(),r=[],c=0;c<n.length;c++){r.push({value:n[c],index:c});}for(r.sort(function(e,t){return t.value-e.value;}),i=new Float32Array(t),s=new Int32Array(t),c=0;c<t;c++){i[c]=r[c].value,s[c]=r[c].index;}for(u=[],c=0;c<s.length;c++){u.push({className:a[s[c]],probability:i[c]});}return[2,u];}});});}(n=this.infer(e),t)];case 1:return r=s.sent(),n.dispose(),[2,r];}});});},e;}();},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=s(n(64)),a=s(n(30)),i=s(n(29)),o=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}(n(10));function s(e){return e&&e.__esModule?e:{default:e};}var u=function(){function e(t){(0,a.default)(this,e),this.urlPath=t;}return(0,i.default)(e,[{key:"getAllVariables",value:function value(){var e=this;return new r.default(function(t,n){var r={};if(e.urlPath in r)t(r[e.urlPath]);else{var a=new XMLHttpRequest();a.open("GET",e.urlPath,!0),a.responseType="arraybuffer",a.onload=function(){if(200===a.status){var i=a.response;if(i){for(var s=[],u=0;u<i.byteLength;){var c=new Uint8Array(i.slice(u,u+4));u+=4;var l=(c[0]<<24)+(c[1]<<16)+(c[2]<<8)+c[3];s.push(i.slice(u,u+l)),u+=l;}for(var f=JSON.parse(new TextDecoder("utf8").decode(s[0])),p=new Float32Array(s[1]),h=new Uint8Array(s[2]),d=new Float32Array(h.length),m=0;m<d.length;m+=1){d[m]=p[h[m]];}var g={};u=0;for(var y=0;y<f.length;y+=1){var v=f[y].shape,b=v.reduce(function(e,t){return e*t;}),w=d.slice(u,u+b),x=o.tensor1d(w,"float32");g[f[y].name]=x.reshape(v),u+=b;}r[e.urlPath]=g,t(g);}else n(new Error("invalid arraybuffer"));}else n(new Error("missing model"));},a.send(null);}});}}]),e;}();t.default=u;},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=f(n(32)),a=f(n(31)),i=f(n(30)),o=f(n(29)),s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}(n(10)),u=f(n(243)),c=n(91),l=f(n(51));function f(e){return e&&e.__esModule?e:{default:e};}var p=function(){function e(t,n){(0,i.default)(this,e),this.ready=(0,l.default)(this.loadCheckpoints(t),n);}return(0,o.default)(e,[{key:"loadCheckpoints",value:function(){var e=(0,a.default)(r.default.mark(function e(t){var n;return r.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return n=new u.default(t),e.next=3,n.getAllVariables();case 3:return this.variables=e.sent,e.abrupt("return",this);case 5:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()},{key:"transfer",value:function(){var e=(0,a.default)(r.default.mark(function e(t,n){return r.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.abrupt("return",(0,l.default)(this.transferInternal(t),n));case 1:case"end":return e.stop();}}},e,this);}));return function(t,n){return e.apply(this,arguments);};}()},{key:"transferInternal",value:function(){var t=(0,a.default)(r.default.mark(function t(n){var a,i,o,u,l,f=this;return r.default.wrap(function(t){for(;;){switch(t.prev=t.next){case 0:return a=s.fromPixels(n),i=a.dataSync(),o=s.tensor3d(i,a.shape),u=s.div(o,s.scalar(255)),l=(0,c.array3DToImage)(s.tidy(function(){var t=e.preprocess(u),n=[],r=f.variables["generator/encoder_1/conv2d/kernel"],a=f.variables["generator/encoder_1/conv2d/bias"],i=e.conv2d(t,r,a);n.push(i);for(var o=2;o<=8;o+=1){var c="generator/encoder_"+o.toString();r=f.variables[c+"/conv2d/kernel"];var l=f.variables[c+"/conv2d/bias"],p=n[n.length-1],h=s.leakyRelu(p,.2);i=e.conv2d(h,r,l);var d=f.variables[c+"/batch_normalization/gamma"],m=f.variables[c+"/batch_normalization/beta"],g=e.batchnorm(i,d,m);n.push(g);}for(var y=8;y>=2;y-=1){var v=void 0;if(8===y)v=n[n.length-1];else{var b=y-1;v=s.concat([n[n.length-1],n[b]],2);}var w=s.relu(v),x="generator/decoder_"+y.toString();r=f.variables[x+"/conv2d_transpose/kernel"],a=f.variables[x+"/conv2d_transpose/bias"],i=e.deconv2d(w,r,a);var k=f.variables[x+"/batch_normalization/gamma"],O=f.variables[x+"/batch_normalization/beta"],S=e.batchnorm(i,k,O);n.push(S);}var N=s.concat([n[n.length-1],n[0]],2),E=s.relu(N);r=f.variables["generator/decoder_1/conv2d_transpose/kernel"];var I=f.variables["generator/decoder_1/conv2d_transpose/bias"];i=e.deconv2d(E,r,I),E=s.tanh(i),n.push(E);var T=n[n.length-1];return e.deprocess(T);})),t.next=7,s.nextFrame();case 7:return t.abrupt("return",l);case 8:case"end":return t.stop();}}},t,this);}));return function(e){return t.apply(this,arguments);};}()}],[{key:"preprocess",value:function value(e){return s.sub(s.mul(e,s.scalar(2)),s.scalar(1));}},{key:"deprocess",value:function value(e){return s.div(s.add(e,s.scalar(1)),s.scalar(2));}},{key:"batchnorm",value:function value(e,t,n){var r=s.moments(e,[0,1]);return s.batchNormalization(e,r.mean,r.variance,1e-5,t,n);}},{key:"conv2d",value:function value(e,t){return s.conv2d(e,t,[2,2],"same");}},{key:"deconv2d",value:function value(e,t,n){var r=s.conv2dTranspose(e,t,[2*e.shape[0],2*e.shape[1],t.shape[2]],[2,2],"same");return s.add(r,n);}}]),e;}();t.default=function(e,t){var n=new p(e,t);return t?n:n.ready;};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){for(var t=Math.random(),n=0,r=void 0,a=0;a<e.length;a+=1){if(t<(n+=e[a])){r=a;break;}}return r;};},function(e,t,n){"use strict";var r=n(52),a=n(97);e.exports=function(e,t,n){t in e?r.f(e,t,a(0,n)):e[t]=n;};},function(e,t,n){"use strict";var r=n(85),a=n(34),i=n(93),o=n(182),s=n(181),u=n(141),c=n(246),l=n(133);a(a.S+a.F*!n(176)(function(e){Array.from(e);}),"Array",{from:function from(e){var t,n,a,f,p=i(e),h="function"==typeof this?this:Array,d=arguments.length,m=d>1?arguments[1]:void 0,g=void 0!==m,y=0,v=l(p);if(g&&(m=r(m,d>2?arguments[2]:void 0,2)),void 0==v||h==Array&&s(v))for(n=new h(t=u(p.length));t>y;y++){c(n,y,g?m(p[y],y):p[y]);}else for(f=v.call(p),n=new h();!(a=f.next()).done;y++){c(n,y,g?o(f,m,[a.value,y],!0):a.value);}return n.length=y,n;}});},function(e,t,n){n(92),n(247),e.exports=n(21).Array.from;},function(e,t,n){e.exports={default:n(248),__esModule:!0};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=h(n(249)),a=h(n(32)),i=h(n(127)),o=h(n(31)),s=h(n(30)),u=h(n(29)),c=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}(n(10)),l=h(n(245)),f=h(n(172)),p=h(n(51));function h(e){return e&&e.__esModule?e:{default:e};}var d=/cell_[0-9]|lstm_[0-9]/gi,m=/weights|weight|kernel|kernels|w/gi,g=/softmax/gi,y=function(){function e(t,n){(0,s.default)(this,e),this.ready=!1,this.model={},this.cellsAmount=0,this.vocab={},this.vocabSize=0,this.defaults={seed:"a",length:20,temperature:.5},this.ready=(0,p.default)(this.loadCheckpoints(t),n);}return(0,u.default)(e,[{key:"loadCheckpoints",value:function(){var e=(0,o.default)(a.default.mark(function e(t){var n,r,o=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return n=new f.default(t),e.next=3,n.getAllVariables();case 3:return r=e.sent,(0,i.default)(r).forEach(function(e){e.match(d)?e.match(m)?(o.model["Kernel_"+e.match(/[0-9]/)[0]]=r[e],o.cellsAmount+=1):o.model["Bias_"+e.match(/[0-9]/)[0]]=r[e]:e.match(g)?e.match(m)?o.model.fullyConnectedWeights=r[e]:o.model.fullyConnectedBiases=r[e]:o.model[e]=r[e];}),e.next=7,this.loadVocab(t);case 7:return e.abrupt("return",this);case 8:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()},{key:"loadVocab",value:function(){var e=(0,o.default)(a.default.mark(function e(t){var n;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,fetch(t+"/vocab.json").then(function(e){return e.json();}).catch(function(e){return console.error(e);});case 2:n=e.sent,this.vocab=n,this.vocabSize=(0,i.default)(n).length;case 5:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()},{key:"generateInternal",value:function(){var e=(0,o.default)(a.default.mark(function e(t){var n,o,s,u,f,p,h,d,m,g,y,v,b,w,x,k,O,S,N,E,I,T,A,C,P,_,R,M=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return n=t.seed||this.defaults.seed,o=+t.length||this.defaults.length,s=+t.temperature||this.defaults.temperature,u=[],e.next=6,this.ready;case 6:for(f=c.tensor(1),p=[],h=[],d=[],m=function m(e){return function(t,n,r){return c.basicLSTMCell(f,M.model["Kernel_"+e],M.model["Bias_"+e],t,n,r);};},g=0;g<this.cellsAmount;g+=1){h.push(c.zeros([1,this.model["Bias_"+g].shape[0]/4])),d.push(c.zeros([1,this.model["Bias_"+g].shape[0]/4])),p.push(m(g));}y=(0,r.default)(n),v=[],y.forEach(function(e,t){t<100&&v.push(M.vocab[e]);}),w=v[b=0],x=0;case 18:if(!(x<y.length+o)){e.next=39;break;}return(k=c.buffer([1,this.vocabSize])).set(1,0,w),O=k.toTensor(),S=void 0,this.model.embedding?(N=c.matMul(O,this.model.embedding),S=c.multiRNNCell(p,N,h,d)):S=c.multiRNNCell(p,O,h,d),h=S[0],d=S[1],E=d[1],I=c.matMul(E,this.model.fullyConnectedWeights),T=c.add(I,this.model.fullyConnectedBiases),A=c.div(T,c.tensor(s)),C=c.exp(A),e.next=33,c.div(C,c.sum(C)).data();case 33:P=e.sent,_=(0,l.default)(P),y.length>b?(w=v[b],b+=1):(w=_,u.push(_));case 36:x+=1,e.next=18;break;case 39:return R="",u.forEach(function(e){var t=(0,i.default)(M.vocab).find(function(t){return M.vocab[t]===e;});t&&(R+=t);}),e.abrupt("return",R);case 42:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()},{key:"generate",value:function(){var e=(0,o.default)(a.default.mark(function e(t,n){return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.abrupt("return",(0,p.default)(this.generateInternal(t),n));case 1:case"end":return e.stop();}}},e,this);}));return function(t,n){return e.apply(this,arguments);};}()}]),e;}();t.default=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"./",t=arguments[1];return new y(e,t);};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=y(n(56)),a=y(n(128)),i=y(n(32)),o=y(n(31)),s=y(n(126)),u=y(n(30)),c=y(n(29)),l=y(n(125)),f=y(n(124)),p=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}(n(10)),h=y(n(129)),d=y(n(172)),m=n(91),g=y(n(51));function y(e){return e&&e.__esModule?e:{default:e};}var v=200,b=function(e){function t(e,n,r){(0,u.default)(this,t);var a=(0,l.default)(this,(t.__proto__||(0,s.default)(t)).call(this,n,v));return a.ready=!1,a.variableDictionary={},a.timesScalar=p.scalar(150),a.plusScalar=p.scalar(127.5),a.epsilonScalar=p.scalar(.001),a.video=null,a.ready=(0,g.default)(a.load(e),r),a;}return(0,f.default)(t,e),(0,c.default)(t,[{key:"load",value:function(){var e=(0,o.default)(i.default.mark(function e(t){return i.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:if(!this.videoElt){e.next=4;break;}return e.next=3,this.loadVideo();case 3:this.videoReady=!0;case 4:return e.next=6,this.loadCheckpoints(t);case 6:return e.abrupt("return",this);case 7:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()},{key:"loadCheckpoints",value:function(){var e=(0,o.default)(i.default.mark(function e(t){var n;return i.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return n=new d.default(t),e.next=3,n.getAllVariables();case 3:this.variables=e.sent;case 4:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()},{key:"instanceNorm",value:function value(e,n){var r=(0,a.default)(e.shape,3),i=r[0],o=r[1],s=r[2],u=p.moments(e,[0,1]),c=u.mean,l=u.variance,f=this.variables[t.getVariableName(n)],h=this.variables[t.getVariableName(n+1)],d=this.epsilonScalar,m=p.div(p.sub(e.asType("float32"),c),p.sqrt(p.add(l,d)));return p.add(p.mul(h,m),f).as3D(i,o,s);}},{key:"convLayer",value:function value(e,n,r,a){var i=p.conv2d(e,this.variables[t.getVariableName(a)],[n,n],"same"),o=this.instanceNorm(i,a+1);return r?p.relu(o):o;}},{key:"residualBlock",value:function value(e,t){var n=this.convLayer(e,1,!0,t),r=this.convLayer(n,1,!1,t+3);return p.add(r,e);}},{key:"convTransposeLayer",value:function value(e,n,r,i){var o=(0,a.default)(e.shape,2),s=[o[0]*r,o[1]*r,n],u=p.conv2dTranspose(e,this.variables[t.getVariableName(i)],s,[r,r],"same"),c=this.instanceNorm(u,i+1);return p.relu(c);}},{key:"transfer",value:function(){var e=(0,o.default)(i.default.mark(function e(t,n){var a,o;return i.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return a=void 0,o=n,t instanceof HTMLVideoElement||t instanceof HTMLImageElement?a=t:"object"===(void 0===t?"undefined":(0,r.default)(t))&&(t.elt instanceof HTMLVideoElement||t.elt instanceof HTMLImageElement)?a=t.elt:"function"==typeof t&&(a=this.video,o=t),e.abrupt("return",(0,g.default)(this.transferInternal(a),o));case 4:case"end":return e.stop();}}},e,this);}));return function(t,n){return e.apply(this,arguments);};}()},{key:"transferInternal",value:function(){var e=(0,o.default)(i.default.mark(function e(t){var n,r,a=this;return i.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return n=p.fromPixels(t),r=(0,m.array3DToImage)(p.tidy(function(){var e=a.convLayer(n,1,!0,0),t=a.convLayer(e,2,!0,3),r=a.convLayer(t,2,!0,6),i=a.residualBlock(r,9),o=a.residualBlock(i,15),s=a.residualBlock(o,21),u=a.residualBlock(s,27),c=a.residualBlock(u,33),l=a.convTransposeLayer(c,64,2,39),f=a.convTransposeLayer(l,32,2,42),h=a.convLayer(f,1,!1,45),d=p.tanh(h),m=p.mul(a.timesScalar,d),g=p.add(a.plusScalar,m),y=p.clipByValue(g,0,255);return p.div(y,p.scalar(255));})),e.next=4,p.nextFrame();case 4:return e.abrupt("return",r);case 5:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()}],[{key:"getVariableName",value:function value(e){return 0===e?"Variable":"Variable_"+e;}}]),t;}(h.default);t.default=function(e,t,n){var r=n;"function"==typeof t&&(r=t);var a=new b(e,t,r);return r?a:a.ready;};},function(e,t,n){"use strict";n.r(t),n.d(t,"decodeMultiplePoses",function(){return j;}),n.d(t,"decodeSinglePose",function(){return K;}),n.d(t,"load",function(){return Y;}),n.d(t,"PoseNet",function(){return J;}),n.d(t,"checkpoints",function(){return W;}),n.d(t,"partIds",function(){return u;}),n.d(t,"partNames",function(){return o;}),n.d(t,"poseChain",function(){return c;}),n.d(t,"getAdjacentKeyPoints",function(){return f;}),n.d(t,"getBoundingBox",function(){return d;}),n.d(t,"getBoundingBoxPoints",function(){return m;});var r=n(10);function a(e,t,n,r){return new(n||(n=Promise))(function(a,i){function o(e){try{u(r.next(e));}catch(e){i(e);}}function s(e){try{u(r.throw(e));}catch(e){i(e);}}function u(e){e.done?a(e.value):new n(function(t){t(e.value);}).then(o,s);}u((r=r.apply(e,t||[])).next());});}function i(e,t){var n,r,a,i,o={label:0,sent:function sent(){if(1&a[0])throw a[1];return a[1];},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this;}),i;function s(i){return function(s){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;o;){try{if(n=1,r&&(a=2&i[0]?r.return:i[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!(a=(a=o.trys).length>0&&a[a.length-1])&&(6===i[0]||2===i[0])){o=0;continue;}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break;}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break;}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break;}a[2]&&o.ops.pop(),o.trys.pop();continue;}i=t.call(e,o);}catch(e){i=[6,e],r=0;}finally{n=a=0;}}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0};}([i,s]);};}}var o=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],s=o.length,u=o.reduce(function(e,t,n){return e[t]=n,e;},{}),c=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]],l=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]].map(function(e){var t=e[0],n=e[1];return[u[t],u[n]];});function f(e,t){return l.reduce(function(n,r){var a=r[0],i=r[1];return function(e,t,n){return e<n||t<n;}(e[a].score,e[i].score,t)?n:(n.push([e[a],e[i]]),n);},[]);}var p=Number.NEGATIVE_INFINITY,h=Number.POSITIVE_INFINITY;function d(e){return e.reduce(function(e,t){var n=e.maxX,r=e.maxY,a=e.minX,i=e.minY,o=t.position,s=o.x,u=o.y;return{maxX:Math.max(n,s),maxY:Math.max(r,u),minX:Math.min(a,s),minY:Math.min(i,u)};},{maxX:p,maxY:p,minX:h,minY:h});}function m(e){var t=d(e),n=t.minX,r=t.minY,a=t.maxX,i=t.maxY;return[{x:n,y:r},{x:a,y:r},{x:a,y:i},{x:n,y:i}];}function g(e,t){return void 0===t&&(t="float32"),a(this,void 0,void 0,function(){var n;return i(this,function(a){switch(a.label){case 0:return[4,e.data()];case 1:return n=a.sent(),[2,new r.TensorBuffer(e.shape,t,n)];}});});}function y(e,t,n){return{score:e.score,keypoints:e.keypoints.map(function(e){var r=e.score,a=e.part,i=e.position;return{score:r,part:a,position:{x:i.x*t,y:i.y*n}};})};}function v(e,t,n){var r=t*e-1;return r-r%n+1;}function b(e){return Math.floor(e/2);}var w=function(){function e(e,t){this.priorityQueue=new Array(e),this.numberOfElements=-1,this.getElementValue=t;}return e.prototype.enqueue=function(e){this.priorityQueue[++this.numberOfElements]=e,this.swim(this.numberOfElements);},e.prototype.dequeue=function(){var e=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,e;},e.prototype.empty=function(){return-1===this.numberOfElements;},e.prototype.size=function(){return this.numberOfElements+1;},e.prototype.all=function(){return this.priorityQueue.slice(0,this.numberOfElements+1);},e.prototype.max=function(){return this.priorityQueue[0];},e.prototype.swim=function(e){for(;e>0&&this.less(b(e),e);){this.exchange(e,b(e)),e=b(e);}},e.prototype.sink=function(e){for(;2*e<=this.numberOfElements;){var t=2*e;if(t<this.numberOfElements&&this.less(t,t+1)&&t++,!this.less(e,t))break;this.exchange(e,t),e=t;}},e.prototype.getValueAt=function(e){return this.getElementValue(this.priorityQueue[e]);},e.prototype.less=function(e,t){return this.getValueAt(e)<this.getValueAt(t);},e.prototype.exchange=function(e,t){var n=this.priorityQueue[e];this.priorityQueue[e]=this.priorityQueue[t],this.priorityQueue[t]=n;},e;}();function x(e,t,n,r,a,i){for(var o=i.shape,s=o[0],u=o[1],c=!0,l=Math.max(n-a,0),f=Math.min(n+a+1,s),p=l;p<f;++p){for(var h=Math.max(r-a,0),d=Math.min(r+a+1,u),m=h;m<d;++m){if(i.get(p,m,e)>t){c=!1;break;}}if(!c)break;}return c;}function k(e,t,n,r){return{y:r.get(e,t,n),x:r.get(e,t,n+s)};}function O(e,t,n){var r=k(e.heatmapY,e.heatmapX,e.id,n),a=r.y,i=r.x;return{x:e.heatmapX*t+i,y:e.heatmapY*t+a};}function S(e,t,n){return e<t?t:e>n?n:e;}function N(e,t){return{x:e.x+t.x,y:e.y+t.y};}var E=c.map(function(e){var t=e[0],n=e[1];return[u[t],u[n]];}),I=E.map(function(e){return e[1];}),T=E.map(function(e){return e[0];});function A(e,t,n,r){return{y:S(Math.round(e.y/t),0,n-1),x:S(Math.round(e.x/t),0,r-1)};}function C(e,t,n,r,a,i,s){var u=r.shape,c=u[0],l=u[1],f=function(e,t,n){var r=n.shape[2]/2;return{y:n.get(t.y,t.x,e),x:n.get(t.y,t.x,r+e)};}(e,A(t.position,i,c,l),s),p=A(N(t.position,f),i,c,l),h=k(p.y,p.x,n,a),d=r.get(p.y,p.x,n);return{position:N({x:p.x*i,y:p.y*i},{x:h.x,y:h.y}),part:o[n],score:d};}function P(e,t,n,r,a,i){var s=t.shape[2],u=I.length,c=new Array(s),l=e.part,f=e.score,p=O(l,r,n);c[l.id]={score:f,part:o[l.id],position:p};for(var h=u-1;h>=0;--h){var d=I[h],m=T[h];c[d]&&!c[m]&&(c[m]=C(h,c[d],m,t,n,r,i));}for(h=0;h<u;++h){d=T[h],m=I[h],c[d]&&!c[m]&&(c[m]=C(h,c[d],m,t,n,r,a));}return c;}function _(e,t,n,r){var a=n.x,i=n.y;return e.some(function(e){var n=e.keypoints[r].position;return function(e,t,n,r){var a=n-e,i=r-t;return a*a+i*i;}(i,a,n.y,n.x)<=t;});}function R(e,t,n){return n.reduce(function(n,r,a){var i=r.position,o=r.score;return _(e,t,i,a)||(n+=o),n;},0)/n.length;}var M=1;function j(e,t,n,r,o,s,u,c){return void 0===u&&(u=.5),void 0===c&&(c=20),a(this,void 0,void 0,function(){var l,f,p,h,d,m,y,v,b,k,S,N;return i(this,function(E){switch(E.label){case 0:return l=[],[4,function(e){return a(this,void 0,void 0,function(){return i(this,function(t){return[2,Promise.all(e.map(function(e){return g(e,"float32");}))];});});}([e,t,n,r])];case 1:for(f=E.sent(),p=f[0],h=f[1],d=f[2],m=f[3],y=function(e,t,n){for(var r=n.shape,a=r[0],i=r[1],o=r[2],s=new w(a*i*o,function(e){return e.score;}),u=0;u<a;++u){for(var c=0;c<i;++c){for(var l=0;l<o;++l){var f=n.get(u,c,l);f<e||x(l,f,u,c,t,n)&&s.enqueue({score:f,part:{heatmapY:u,heatmapX:c,id:l}});}}}return s;}(u,M,p),v=c*c;l.length<s&&!y.empty();){b=y.dequeue(),k=O(b.part,o,h),_(l,v,k,b.part.id)||(S=P(b,p,h,o,d,m),N=R(l,v,S),l.push({keypoints:S,score:N}));}return[2,l];}});});}var D=function(){function e(e){this.urlPath=e,"/"!==this.urlPath.charAt(this.urlPath.length-1)&&(this.urlPath+="/");}return e.prototype.loadManifest=function(){var e=this;return new Promise(function(t,n){var r=new XMLHttpRequest();r.open("GET",e.urlPath+"manifest.json"),r.onload=function(){e.checkpointManifest=JSON.parse(r.responseText),t();},r.onerror=function(t){throw new Error("manifest.json not found at "+e.urlPath+". "+t);},r.send();});},e.prototype.getCheckpointManifest=function(){var e=this;return null==this.checkpointManifest?new Promise(function(t,n){e.loadManifest().then(function(){t(e.checkpointManifest);});}):new Promise(function(t,n){t(e.checkpointManifest);});},e.prototype.getAllVariables=function(){var e=this;return null!=this.variables?new Promise(function(t,n){t(e.variables);}):new Promise(function(t,n){e.getCheckpointManifest().then(function(n){for(var r=Object.keys(e.checkpointManifest),a=[],i=0;i<r.length;i++){a.push(e.getVariable(r[i]));}Promise.all(a).then(function(n){e.variables={};for(var a=0;a<n.length;a++){e.variables[r[a]]=n[a];}t(e.variables);});});});},e.prototype.getVariable=function(e){var t=this;if(!(e in this.checkpointManifest))throw new Error("Cannot load non-existant variable "+e);var n=function n(_n11,a){var i=new XMLHttpRequest();i.responseType="arraybuffer";var o=t.checkpointManifest[e].filename;i.open("GET",t.urlPath+o),i.onload=function(){if(404===i.status)throw new Error("Not found variable "+e);var a=new Float32Array(i.response),o=r.Tensor.make(t.checkpointManifest[e].shape,{values:a});_n11(o);},i.onerror=function(t){throw new Error("Could not fetch variable "+e+": "+t);},i.send();};return null==this.checkpointManifest?new Promise(function(e,r){t.loadManifest().then(function(){new Promise(n).then(e);});}):new Promise(n);},e;}(),L=[8,16,32];function z(e){r.util.assert("number"==typeof e,"outputStride is not a number"),r.util.assert(L.indexOf(e)>=0,"outputStride of "+e+" is invalid. It must be either 8, 16, or 32");}function F(e){r.util.assert("number"==typeof e,"imageScaleFactor is not a number"),r.util.assert(e>=.2&&e<=1,"imageScaleFactor must be between 0.2 and 1.0");}var B={100:[["conv2d",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",2],["separableConv",1]],75:[["conv2d",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1]],50:[["conv2d",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",2],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1],["separableConv",1]]},V=function(){function e(e,t){this.PREPROCESS_DIVISOR=Object(r.scalar)(127.5),this.ONE=Object(r.scalar)(1),this.variables=e,this.convolutionDefinitions=t;}return e.prototype.predict=function(e,t){var n=this,a=Object(r.cast)(e,"float32").div(this.PREPROCESS_DIVISOR).sub(this.ONE);return function(e,t){var n=1,r=1;return e.map(function(e,a){var i,o,s=e[0],u=e[1];return n===t?(i=1,o=r,r*=u):(i=u,o=1,n*=u),{blockId:a,convType:s,stride:i,rate:o,outputStride:n};});}(this.convolutionDefinitions,t).reduce(function(e,t){var r=t.blockId,a=t.stride,i=t.convType,o=t.rate;if("conv2d"===i)return n.conv(e,a,r);if("separableConv"===i)return n.separableConv(e,a,r,o);throw Error("Unknown conv type of "+i);},a);},e.prototype.convToOutput=function(e,t){return e.conv2d(this.weights(t),1,"same").add(this.biases(t));},e.prototype.conv=function(e,t,n){return e.conv2d(this.weights("Conv2d_"+String(n)),t,"same").add(this.biases("Conv2d_"+String(n))).clipByValue(0,6);},e.prototype.separableConv=function(e,t,n,r){void 0===r&&(r=1);var a="Conv2d_"+String(n)+"_depthwise",i="Conv2d_"+String(n)+"_pointwise";return e.depthwiseConv2D(this.depthwiseWeights(a),t,"same","NHWC",r).add(this.biases(a)).clipByValue(0,6).conv2d(this.weights(i),[1,1],"same").add(this.biases(i)).clipByValue(0,6);},e.prototype.weights=function(e){return this.variables["MobilenetV1/"+e+"/weights"];},e.prototype.biases=function(e){return this.variables["MobilenetV1/"+e+"/biases"];},e.prototype.depthwiseWeights=function(e){return this.variables["MobilenetV1/"+e+"/depthwise_weights"];},e.prototype.dispose=function(){for(var e in this.variables){this.variables[e].dispose();}},e;}(),U="https://storage.googleapis.com/tfjs-models/weights/posenet/",W={1.01:{url:U+"mobilenet_v1_101/",architecture:B[100]},1:{url:U+"mobilenet_v1_100/",architecture:B[100]},.75:{url:U+"mobilenet_v1_075/",architecture:B[75]},.5:{url:U+"mobilenet_v1_050/",architecture:B[50]}};function G(e){var t=e.shape,n=t[0],a=t[1],i=t[2];return Object(r.tidy)(function(){var t=e.reshape([n*a,i]).argMax(0),o=t.div(Object(r.scalar)(a,"int32")).expandDims(1),s=function(e,t){return Object(r.tidy)(function(){var n=e.div(Object(r.scalar)(t,"int32"));return e.sub(n.mul(Object(r.scalar)(t,"int32")));});}(t,a).expandDims(1);return Object(r.concat)([o,s],1);});}function q(e,t,n,r){return{y:r.get(e,t,n),x:r.get(e,t,n+s)};}function H(e,t,n){return Object(r.tidy)(function(){var a=function(e,t){for(var n=[],a=0;a<s;a++){var i=q(e.get(a,0).valueOf(),e.get(a,1).valueOf(),a,t),o=i.x,u=i.y;n.push(u),n.push(o);}return Object(r.tensor2d)(n,[s,2]);}(e,n);return e.toTensor().mul(Object(r.scalar)(t,"int32")).toFloat().add(a);});}function K(e,t,n){return a(this,void 0,void 0,function(){var r,a,s,u,c,l,f,p,h,d;return i(this,function(i){switch(i.label){case 0:return r=0,a=G(e),[4,Promise.all([g(e),g(t),g(a,"int32")])];case 1:return s=i.sent(),u=s[0],c=s[1],l=s[2],[4,g(f=H(l,n,c))];case 2:return p=i.sent(),h=Array.from(function(e,t){for(var n=t.shape[0],r=new Float32Array(n),a=0;a<n;a++){var i=t.get(a,0),o=t.get(a,1);r[a]=e.get(i,o,a);}return r;}(u,l)),d=h.map(function(e,t){return r+=e,{position:{y:p.get(t,0),x:p.get(t,1)},part:o[t],score:e};}),a.dispose(),f.dispose(),[2,{keypoints:d,score:r/d.length}];}});});}function X(e,t,n,a){var i=e instanceof r.Tensor?e:Object(r.fromPixels)(e);return a?i.reverse(1).resizeBilinear([t,n]):i.resizeBilinear([t,n]);}var J=function(){function e(e){this.mobileNet=e;}return e.prototype.predictForSinglePose=function(e,t){var n=this;return void 0===t&&(t=16),z(t),Object(r.tidy)(function(){var r=n.mobileNet.predict(e,t),a=n.mobileNet.convToOutput(r,"heatmap_2"),i=n.mobileNet.convToOutput(r,"offset_2");return{heatmapScores:a.sigmoid(),offsets:i};});},e.prototype.predictForMultiPose=function(e,t){var n=this;return void 0===t&&(t=16),Object(r.tidy)(function(){var r=n.mobileNet.predict(e,t),a=n.mobileNet.convToOutput(r,"heatmap_2"),i=n.mobileNet.convToOutput(r,"offset_2"),o=n.mobileNet.convToOutput(r,"displacement_fwd_2"),s=n.mobileNet.convToOutput(r,"displacement_bwd_2");return{heatmapScores:a.sigmoid(),offsets:i,displacementFwd:o,displacementBwd:s};});},e.prototype.estimateSinglePose=function(e,t,n,o){return void 0===t&&(t=.5),void 0===n&&(n=!1),void 0===o&&(o=16),a(this,void 0,void 0,function(){var a,s,u,c,l,f,p,h,d,m=this;return i(this,function(i){switch(i.label){case 0:return z(o),F(t),a=e instanceof r.Tensor?[e.shape[0],e.shape[1]]:[e.height,e.width],s=a[0],u=a[1],c=v(t,s,o),l=v(t,u,o),f=Object(r.tidy)(function(){var t=X(e,c,l,n);return m.predictForSinglePose(t,o);}),p=f.heatmapScores,h=f.offsets,[4,K(p,h,o)];case 1:return d=i.sent(),p.dispose(),h.dispose(),[2,y(d,s/c,u/l)];}});});},e.prototype.estimateMultiplePoses=function(e,t,n,o,s,u,c){return void 0===t&&(t=.5),void 0===n&&(n=!1),void 0===o&&(o=16),void 0===s&&(s=5),void 0===u&&(u=.5),void 0===c&&(c=20),a(this,void 0,void 0,function(){var a,l,f,p,h,d,m,g,b,w,x,k=this;return i(this,function(i){switch(i.label){case 0:return z(o),F(t),a=e instanceof r.Tensor?[e.shape[0],e.shape[1]]:[e.height,e.width],l=a[0],f=a[1],p=v(t,l,o),h=v(t,f,o),d=Object(r.tidy)(function(){var t=X(e,p,h,n);return k.predictForMultiPose(t,o);}),m=d.heatmapScores,g=d.offsets,b=d.displacementFwd,w=d.displacementBwd,[4,j(m,g,b,w,o,s,u,c)];case 1:return x=i.sent(),m.dispose(),g.dispose(),b.dispose(),w.dispose(),[2,function(e,t,n){return 1===n&&1===t?x:x.map(function(e){return y(e,n,t);});}(0,l/p,f/h)];}});});},e.prototype.dispose=function(){this.mobileNet.dispose();},e;}();function Y(e){return void 0===e&&(e=1.01),a(this,void 0,void 0,function(){var t,n;return i(this,function(a){switch(a.label){case 0:if(null==r)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this model.");return t=Object.keys(W),r.util.assert("number"==typeof e,"got multiplier type of "+(typeof e==="undefined"?"undefined":_typeof(e))+" when it should be a number."),r.util.assert(t.indexOf(e.toString())>=0,"invalid multiplier value of "+e+". No checkpoint exists for that multiplier. Must be one of "+t.join(",")+"."),[4,Q.load(e)];case 1:return n=a.sent(),[2,new J(n)];}});});}var Q={load:function load(e){return a(void 0,void 0,void 0,function(){var t,n;return i(this,function(r){switch(r.label){case 0:return t=W[e],[4,new D(t.url).getAllVariables()];case 1:return n=r.sent(),[2,new V(n,t.architecture)];}});});}};},function(e,t){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0;}function r(e){return"function"==typeof e;}function a(e){return"object"==(typeof e==="undefined"?"undefined":_typeof(e))&&null!==e;}function i(e){return void 0===e;}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(e){if(!function(e){return"number"==typeof e;}(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this;},n.prototype.emit=function(e){var t,n,o,s,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l;}if(i(n=this._events[e]))return!1;if(r(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:s=Array.prototype.slice.call(arguments,1),n.apply(this,s);}else if(a(n))for(s=Array.prototype.slice.call(arguments,1),o=(c=n.slice()).length,u=0;u<o;u++){c[u].apply(this,s);}return!0;},n.prototype.addListener=function(e,t){var o;if(!r(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,r(t.listener)?t.listener:t),this._events[e]?a(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,a(this._events[e])&&!this._events[e].warned&&(o=i(this._maxListeners)?n.defaultMaxListeners:this._maxListeners)&&o>0&&this._events[e].length>o&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this;},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){if(!r(t))throw TypeError("listener must be a function");var n=!1;function a(){this.removeListener(e,a),n||(n=!0,t.apply(this,arguments));}return a.listener=t,this.on(e,a),this;},n.prototype.removeListener=function(e,t){var n,i,o,s;if(!r(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(o=(n=this._events[e]).length,i=-1,n===t||r(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(n)){for(s=o;s-->0;){if(n[s]===t||n[s].listener&&n[s].listener===t){i=s;break;}}if(i<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(i,1),this._events.removeListener&&this.emit("removeListener",e,t);}return this;},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events){"removeListener"!==t&&this.removeAllListeners(t);}return this.removeAllListeners("removeListener"),this._events={},this;}if(r(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;){this.removeListener(e,n[n.length-1]);}return delete this._events[e],this;},n.prototype.listeners=function(e){return this._events&&this._events[e]?r(this._events[e])?[this._events[e]]:this._events[e].slice():[];},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(r(t))return 1;if(t)return t.length;}return 0;},n.listenerCount=function(e,t){return e.listenerCount(t);};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=y(n(56)),a=y(n(32)),i=y(n(64)),o=y(n(31)),s=y(n(126)),u=y(n(30)),c=y(n(29)),l=y(n(125)),f=y(n(124)),p=y(n(253)),h=g(n(10)),d=g(n(252)),m=y(n(51));function g(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}function y(e){return e&&e.__esModule?e:{default:e};}var v={imageScaleFactor:.3,outputStride:16,flipHorizontal:!1,minConfidence:.5,maxPoseDetections:5,scoreThreshold:.5,nmsRadius:20,detectionType:"multiple",multiplier:.75},b=function(e){function t(e,n,r,a){(0,u.default)(this,t);var i=(0,l.default)(this,(t.__proto__||(0,s.default)(t)).call(this));return i.video=e,i.detectionType=r||v.detectionType,i.imageScaleFactor=n.imageScaleFactor||v.imageScaleFactor,i.outputStride=n.outputStride||v.outputStride,i.flipHorizontal=n.flipHorizontal||v.flipHorizontal,i.minConfidence=n.minConfidence||v.minConfidence,i.multiplier=n.multiplier||v.multiplier,i.ready=(0,m.default)(i.load(),a),i;}return(0,f.default)(t,e),(0,c.default)(t,[{key:"load",value:function(){var e=(0,o.default)(a.default.mark(function e(){var t=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,d.load(this.multiplier);case 2:if(this.net=e.sent,!this.video){e.next=9;break;}if(0!==this.video.readyState){e.next=7;break;}return e.next=7,new i.default(function(e){t.video.onloadeddata=function(){return e();};});case 7:"single"===this.detectionType&&this.singlePose(),this.multiPose();case 9:return e.abrupt("return",this);case 10:case"end":return e.stop();}}},e,this);}));return function(){return e.apply(this,arguments);};}()},{key:"skeleton",value:function value(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.minConfidence;return d.getAdjacentKeyPoints(e,t);}},{key:"singlePose",value:function(){var e=(0,o.default)(a.default.mark(function e(t){var n,i,o,s=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return n=void 0,n=t instanceof HTMLImageElement||t instanceof HTMLVideoElement?t:"object"===(void 0===t?"undefined":(0,r.default)(t))&&(t.elt instanceof HTMLImageElement||t.elt instanceof HTMLVideoElement)?t.elt:this.video,e.next=4,this.net.estimateSinglePose(n,this.imageScaleFactor,this.flipHorizontal,this.outputStride);case 4:if(i=e.sent,o=[{pose:i,skeleton:this.skeleton(i.keypoints)}],this.emit("pose",o),!this.video){e.next=9;break;}return e.abrupt("return",h.nextFrame().then(function(){return s.singlePose();}));case 9:return e.abrupt("return",o);case 10:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()},{key:"multiPose",value:function(){var e=(0,o.default)(a.default.mark(function e(t){var n,i,o,s=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return n=void 0,n=t instanceof HTMLImageElement||t instanceof HTMLVideoElement?t:"object"===(void 0===t?"undefined":(0,r.default)(t))&&(t.elt instanceof HTMLImageElement||t.elt instanceof HTMLVideoElement)?t.elt:this.video,e.next=4,this.net.estimateMultiplePoses(n,this.imageScaleFactor,this.flipHorizontal,this.outputStride);case 4:if(i=e.sent,o=i.map(function(e){return{pose:e,skeleton:s.skeleton(e.keypoints)};}),this.emit("pose",o),!this.video){e.next=9;break;}return e.abrupt("return",h.nextFrame().then(function(){return s.multiPose();}));case 9:return e.abrupt("return",o);case 10:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()}]),t;}(p.default);t.default=function(e,t,n){var a=void 0,i={},o=n,s=null;return e instanceof HTMLVideoElement?a=e:"object"===(void 0===e?"undefined":(0,r.default)(e))&&e.elt instanceof HTMLVideoElement?a=e.elt:"object"===(void 0===e?"undefined":(0,r.default)(e))?i=e:"function"==typeof e&&(o=e),"object"===(void 0===t?"undefined":(0,r.default)(t))?i=t:"function"==typeof t?o=t:"string"==typeof t&&(s=t),new b(a,i,s,o);};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.nonMaxSuppression=t.boxesToCorners=t.filterBoxes=t.boxIOU=t.boxUnion=t.boxIntersection=t.ANCHORS=void 0;var r=o(n(32)),a=o(n(31));t.filterBoxes=function(){var e=(0,a.default)(r.default.mark(function e(t,n,a,o){var s,u,c,l,f,p,h,d;return r.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return s=i.mul(n,a),u=i.argMax(s,-1),c=i.max(s,-1),l=i.greaterEqual(c,i.scalar(o)),e.next=6,l.data();case 6:for(f=e.sent,p=[],h=0;h<f.length;h+=1){f[h]&&p.push(h);}if(0!==p.length){e.next=11;break;}return e.abrupt("return",[null,null,null]);case 11:return d=i.tensor1d(p,"int32"),e.abrupt("return",[i.gather(t.reshape([f.length,4]),d),i.gather(c.flatten(),d),i.gather(u.flatten(),d)]);case 13:case"end":return e.stop();}}},e,this);}));return function(t,n,r,a){return e.apply(this,arguments);};}(),t.head=function(e,t,n){var r=t.shape[0],a=i.reshape(t,[1,1,r,2]),o=e.shape.slice(1,3),s=o[0],u=o[1],c=i.range(0,o[0]),l=i.range(0,o[1]);c=i.tile(c,[o[1]]),l=i.tile(i.expandDims(l,0),[o[0],1]),l=i.transpose(l).flatten();var f=i.transpose(i.stack([c,l]));f=i.reshape(f,[o[0],o[1],1,2]),f=i.cast(f,e.dtype),e=i.reshape(e,[o[0],o[1],r,n+5]),o=i.cast(i.reshape(i.tensor1d(o),[1,1,1,2]),e.dtype);var p=i.sigmoid(e.slice([0,0,0,0],[s,u,r,2])),h=i.exp(e.slice([0,0,0,2],[s,u,r,2])),d=i.sigmoid(e.slice([0,0,0,4],[s,u,r,1])),m=i.softmax(e.slice([0,0,0,5],[s,u,r,n]));return[p=i.div(i.add(p,f),o),h=i.div(i.mul(h,a),o),d,m];};var i=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}(n(10));function o(e){return e&&e.__esModule?e:{default:e};}t.ANCHORS=i.tensor2d([[.57273,.677385],[1.87446,2.06253],[3.33843,5.47434],[7.88282,3.52778],[9.77052,9.16828]]);var s=t.boxIntersection=function(e,t){var n=Math.min(e[3],t[3])-Math.max(e[1],t[1]),r=Math.min(e[2],t[2])-Math.max(e[0],t[0]);return n<0||r<0?0:n*r;},u=t.boxUnion=function(e,t){var n=s(e,t);return(e[3]-e[1])*(e[2]-e[0])+(t[3]-t[1])*(t[2]-t[0])-n;},c=t.boxIOU=function(e,t){return s(e,t)/u(e,t);};t.boxesToCorners=function(e,t){var n=i.tensor1d([2]),r=i.sub(e,i.div(t,n)),a=i.add(e,i.div(t,n)),o=[r.shape[0],r.shape[1],r.shape[2],1];return i.concat([r.slice([0,0,0,1],o),r.slice([0,0,0,0],o),a.slice([0,0,0,1],o),a.slice([0,0,0,0],o)],3);},t.nonMaxSuppression=function(e,t,n){for(var r=[],a=0;a<t.length;a+=1){r.push([t[a],[e[4*a],e[4*a+1],e[4*a+2],e[4*a+3]],a]);}var i=[];return r.sort(function(e,t){return t[0]-e[0];}).forEach(function(e){for(var t=!0,r=0;r<i.length;r+=1){if(c(e[1],i[r][1])>n){t=!1;break;}}t&&i.push(e);}),[i.map(function(e){return e[2];}),i.map(function(e){return e[1];}),i.map(function(e){return e[0];})];};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=["person","bicycle","car","motorbike","aeroplane","bus","train","truck","boat","traffic light","fire hydrant","stop sign","parking meter","bench","bird","cat","dog","horse","sheep","cow","elephant","bear","zebra","giraffe","backpack","umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sports ball","kite","baseball bat","baseball glove","skateboard","surfboard","tennis racket","bottle","wine glass","cup","fork","knife","spoon","bowl","banana","apple","sandwich","orange","broccoli","carrot","hot dog","pizza","donut","cake","chair","sofa","pottedplant","bed","diningtable","toilet","tvmonitor","laptop","mouse","remote","keyboard","cell phone","microwave","oven","toaster","sink","refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"];},function(e,t,n){var r=n(34);r(r.S,"Object",{create:n(135)});},function(e,t,n){n(257);var r=n(21).Object;e.exports=function(e,t){return r.create(e,t);};},function(e,t,n){e.exports={default:n(258),__esModule:!0};},function(e,t,n){var r=n(58),a=n(45),i=function i(e,t){if(a(e),!r(t)&&null!==t)throw TypeError(t+": can't set as prototype!");};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{(r=n(85)(Function.call,n(174).f(Object.prototype,"__proto__").set,2))(e,[]),t=!(e instanceof Array);}catch(e){t=!0;}return function(e,n){return i(e,n),t?e.__proto__=n:r(e,n),e;};}({},!1):void 0),check:i};},function(e,t,n){var r=n(34);r(r.S,"Object",{setPrototypeOf:n(260).set});},function(e,t,n){n(261),e.exports=n(21).Object.setPrototypeOf;},function(e,t,n){e.exports={default:n(262),__esModule:!0};},function(e,t,n){var r=n(93),a=n(183);n(173)("getPrototypeOf",function(){return function(e){return a(r(e));};});},function(e,t,n){n(264),e.exports=n(21).Object.getPrototypeOf;},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=b(n(64)),a=b(n(128)),i=b(n(56)),o=b(n(32)),s=b(n(31)),u=b(n(126)),c=b(n(30)),l=b(n(29)),f=b(n(125)),p=b(n(124)),h=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}(n(10)),d=b(n(129)),m=n(91),g=b(n(51)),y=b(n(256)),v=n(255);function b(e){return e&&e.__esModule?e:{default:e};}var w={filterBoxesThreshold:.01,IOUThreshold:.4,classProbThreshold:.4},x=416,k=function(e){function t(e,n,r){(0,c.default)(this,t);var a=(0,f.default)(this,(t.__proto__||(0,u.default)(t)).call(this,e,x));return a.filterBoxesThreshold=n.filterBoxesThreshold||w.filterBoxesThreshold,a.IOUThreshold=n.IOUThreshold||w.IOUThreshold,a.classProbThreshold=n.classProbThreshold||w.classProbThreshold,a.modelReady=!1,a.isPredicting=!1,a.ready=(0,g.default)(a.loadModel(),r),a;}return(0,p.default)(t,e),(0,l.default)(t,[{key:"loadModel",value:function(){var e=(0,s.default)(o.default.mark(function e(){return o.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:if(!this.videoElt||this.video){e.next=4;break;}return e.next=3,this.loadVideo();case 3:this.video=e.sent;case 4:return e.next=6,h.loadModel("https://raw.githubusercontent.com/ml5js/ml5-data-and-training/master/models/YOLO/model.json");case 6:return this.model=e.sent,this.modelReady=!0,e.abrupt("return",this);case 9:case"end":return e.stop();}}},e,this);}));return function(){return e.apply(this,arguments);};}()},{key:"detect",value:function(){var e=(0,s.default)(o.default.mark(function e(t,n){var r,a;return o.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,this.ready;case 2:return r=void 0,a=n,t instanceof HTMLImageElement||t instanceof HTMLVideoElement?r=t:"object"===(void 0===t?"undefined":(0,i.default)(t))&&(t.elt instanceof HTMLImageElement||t.elt instanceof HTMLVideoElement)?r=t.elt:"function"==typeof t&&(r=this.video,a=t),e.abrupt("return",(0,g.default)(this.detectInternal(r),a));case 6:case"end":return e.stop();}}},e,this);}));return function(t,n){return e.apply(this,arguments);};}()},{key:"detectInternal",value:function(){var e=(0,s.default)(o.default.mark(function e(t){var n,i,s,u,c,l,f,p,d,g,b,w,k,O,S,N,E,I,T,A,C,P,_,R,M,j=this;return o.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,this.ready;case 2:return e.next=4,h.nextFrame();case 4:return this.isPredicting=!0,n=h.tidy(function(){var e=(0,m.imgToTensor)(t,[x,x]),n=j.model.predict(e),r=(0,v.head)(n,v.ANCHORS,80),i=(0,a.default)(r,4),o=i[0],s=i[1],u=i[2],c=i[3];return[(0,v.boxesToCorners)(o,s),u,c];}),i=(0,a.default)(n,3),s=i[0],u=i[1],c=i[2],e.next=8,(0,v.filterBoxes)(s,u,c,this.filterBoxesThreshold);case 8:if(l=e.sent,f=(0,a.default)(l,3),p=f[0],d=f[1],g=f[2],null!=p){e.next=15;break;}return e.abrupt("return",[]);case 15:return b=h.scalar(x),w=h.scalar(x),k=h.stack([w,b,w,b]).reshape([1,4]),O=h.mul(p,k),e.next=21,r.default.all([O.data(),d.data()]);case 21:return S=e.sent,N=(0,a.default)(S,2),E=N[0],I=N[1],T=(0,v.nonMaxSuppression)(E,I,this.IOUThreshold),A=(0,a.default)(T,3),C=A[0],P=A[1],_=A[2],e.next=28,g.gather(h.tensor1d(C,"int32")).data();case 28:return R=e.sent,M=[],R.forEach(function(e,t){var n=_[t];if(!(n<j.classProbThreshold)){var r=y.default[e],i=(0,a.default)(P[t],4),o=i[0],s=i[1],u=i[2],c=i[3];o=Math.max(0,o),s=Math.max(0,s),u=Math.min(x,u)-o,c=Math.min(x,c)-s;var l={className:r,classProb:n,x:s/x,y:o/x,w:c/x,h:u/x};M.push(l);}}),this.isPredicting=!1,e.abrupt("return",M);case 33:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()}]),t;}(d.default);t.default=function(e,t,n){var r=null,a={},o=n;return e instanceof HTMLVideoElement?r=e:"object"===(void 0===e?"undefined":(0,i.default)(e))&&e.elt instanceof HTMLVideoElement?r=e.elt:"function"==typeof e?o=e:"object"===(void 0===e?"undefined":(0,i.default)(e))&&(a=e),"object"===(void 0===t?"undefined":(0,i.default)(t))?a=t:"function"==typeof t&&(o=t),new k(r,a,o);};},function(e,t,n){var r=n(93),a=n(83);n(173)("keys",function(){return function(e){return a(r(e));};});},function(e,t,n){n(267),e.exports=n(21).Object.keys;},function(e,t,n){var r=n(83),a=n(67),i=n(94).f;e.exports=function(e){return function(t){for(var n,o=a(t),s=r(o),u=s.length,c=0,l=[];u>c;){i.call(o,n=s[c++])&&l.push(e?[n,o[n]]:o[n]);}return l;};};},function(e,t,n){var r=n(34),a=n(269)(!1);r(r.S,"Object",{values:function values(e){return a(e);}});},function(e,t,n){n(270),e.exports=n(21).Object.values;},function(e,t,n){e.exports={default:n(271),__esModule:!0};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=f(n(272)),a=f(n(32)),i=f(n(127)),o=f(n(31)),s=f(n(30)),u=f(n(29)),c=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}(n(10)),l=f(n(51));function f(e){return e&&e.__esModule?e:{default:e};}var p=function(){function e(t,n){(0,s.default)(this,e),this.model={},this.modelPath=t,this.modelSize=0,this.modelLoaded=!1,this.ready=(0,l.default)(this.loadModel(),n);}return(0,u.default)(e,[{key:"loadModel",value:function(){var e=(0,o.default)(a.default.mark(function e(){var t,n=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,fetch(this.modelPath).then(function(e){return e.json();});case 2:return t=e.sent,(0,i.default)(t.vectors).forEach(function(e){n.model[e]=c.tensor1d(t.vectors[e]);}),this.modelSize=(0,i.default)(this.model).length,this.modelLoaded=!0,e.abrupt("return",this);case 7:case"end":return e.stop();}}},e,this);}));return function(){return e.apply(this,arguments);};}()},{key:"dispose",value:function value(e){(0,r.default)(this.model).forEach(function(e){return e.dispose();}),e&&e();}},{key:"add",value:function(){var t=(0,o.default)(a.default.mark(function t(n,r,i){var o,s,u,l=this;return a.default.wrap(function(t){for(;;){switch(t.prev=t.next){case 0:return o=e.parser(r,i,10),s=o.max,u=o.callback,t.next=3,this.ready;case 3:return t.abrupt("return",c.tidy(function(){var t=e.addOrSubtract(l.model,n,"ADD"),r=e.nearest(l.model,t,n.length,n.length+s);return u&&u(void 0,r),r;}));case 4:case"end":return t.stop();}}},t,this);}));return function(e,n,r){return t.apply(this,arguments);};}()},{key:"subtract",value:function(){var t=(0,o.default)(a.default.mark(function t(n,r,i){var o,s,u,l=this;return a.default.wrap(function(t){for(;;){switch(t.prev=t.next){case 0:return o=e.parser(r,i,10),s=o.max,u=o.callback,t.next=3,this.ready;case 3:return t.abrupt("return",c.tidy(function(){var t=e.addOrSubtract(l.model,n,"SUBTRACT"),r=e.nearest(l.model,t,n.length,n.length+s);return u&&u(void 0,r),r;}));case 4:case"end":return t.stop();}}},t,this);}));return function(e,n,r){return t.apply(this,arguments);};}()},{key:"average",value:function(){var t=(0,o.default)(a.default.mark(function t(n,r,i){var o,s,u,l=this;return a.default.wrap(function(t){for(;;){switch(t.prev=t.next){case 0:return o=e.parser(r,i,10),s=o.max,u=o.callback,t.next=3,this.ready;case 3:return t.abrupt("return",c.tidy(function(){var t=e.addOrSubtract(l.model,n,"ADD"),r=c.div(t,c.tensor(n.length)),a=e.nearest(l.model,r,n.length,n.length+s);return u&&u(void 0,a),a;}));case 4:case"end":return t.stop();}}},t,this);}));return function(e,n,r){return t.apply(this,arguments);};}()},{key:"nearest",value:function(){var t=(0,o.default)(a.default.mark(function t(n,r,i){var o,s,u,c,l;return a.default.wrap(function(t){for(;;){switch(t.prev=t.next){case 0:return o=e.parser(r,i,10),s=o.max,u=o.callback,t.next=3,this.ready;case 3:return c=this.model[n],l=void 0,l=c?e.nearest(this.model,c,1,s+1):null,u&&u(void 0,l),t.abrupt("return",l);case 8:case"end":return t.stop();}}},t,this);}));return function(e,n,r){return t.apply(this,arguments);};}()},{key:"getRandomWord",value:function(){var e=(0,o.default)(a.default.mark(function e(t){var n,r;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,this.ready;case 2:return n=(0,i.default)(this.model),r=n[Math.floor(Math.random()*n.length)],t&&t(void 0,r),e.abrupt("return",r);case 6:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()}],[{key:"parser",value:function value(e,t,n){var r=n,a=t;return"function"==typeof e?a=e:"number"==typeof e&&(r=e),{max:r,callback:a};}},{key:"addOrSubtract",value:function value(e,t,n){return c.tidy(function(){var r=[],a=[];if(t.length<2)throw new Error("Invalid input, must be passed more than 1 value");if(t.forEach(function(t){var n=e[t];n?r.push(n):a.push(t);}),a.length>0)throw new Error("Invalid input, vector not found for: "+a.toString());var i=r[0];if("ADD"===n)for(var o=1;o<r.length;o+=1){i=c.add(i,r[o]);}else for(var s=1;s<r.length;s+=1){i=c.sub(i,r[s]);}return i;});}},{key:"nearest",value:function value(e,t,n,r){var a=[];return(0,i.default)(e).forEach(function(n){var r=c.util.distSquared(t.dataSync(),e[n].dataSync());a.push({word:n,distance:r});}),a.sort(function(e,t){return e.distance-t.distance;}),a.slice(n,r);}}]),e;}();t.default=function(e,t){return new p(e,t);};},function(e,t,n){var r=n(45),a=n(133);e.exports=n(21).getIterator=function(e){var t=a(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return r(t.call(e));};},function(e,t,n){n(103),n(92),e.exports=n(274);},function(e,t,n){e.exports={default:n(275),__esModule:!0};},function(e,t,n){var r=n(134),a=n(24)("iterator"),i=n(81);e.exports=n(21).isIterable=function(e){var t=Object(e);return void 0!==t[a]||"@@iterator"in t||i.hasOwnProperty(r(t));};},function(e,t,n){n(103),n(92),e.exports=n(277);},function(e,t,n){e.exports={default:n(278),__esModule:!0};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.IMAGENET_CLASSES={0:"tench, Tinca tinca",1:"goldfish, Carassius auratus",2:"great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",3:"tiger shark, Galeocerdo cuvieri",4:"hammerhead, hammerhead shark",5:"electric ray, crampfish, numbfish, torpedo",6:"stingray",7:"cock",8:"hen",9:"ostrich, Struthio camelus",10:"brambling, Fringilla montifringilla",11:"goldfinch, Carduelis carduelis",12:"house finch, linnet, Carpodacus mexicanus",13:"junco, snowbird",14:"indigo bunting, indigo finch, indigo bird, Passerina cyanea",15:"robin, American robin, Turdus migratorius",16:"bulbul",17:"jay",18:"magpie",19:"chickadee",20:"water ouzel, dipper",21:"kite",22:"bald eagle, American eagle, Haliaeetus leucocephalus",23:"vulture",24:"great grey owl, great gray owl, Strix nebulosa",25:"European fire salamander, Salamandra salamandra",26:"common newt, Triturus vulgaris",27:"eft",28:"spotted salamander, Ambystoma maculatum",29:"axolotl, mud puppy, Ambystoma mexicanum",30:"bullfrog, Rana catesbeiana",31:"tree frog, tree-frog",32:"tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",33:"loggerhead, loggerhead turtle, Caretta caretta",34:"leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",35:"mud turtle",36:"terrapin",37:"box turtle, box tortoise",38:"banded gecko",39:"common iguana, iguana, Iguana iguana",40:"American chameleon, anole, Anolis carolinensis",41:"whiptail, whiptail lizard",42:"agama",43:"frilled lizard, Chlamydosaurus kingi",44:"alligator lizard",45:"Gila monster, Heloderma suspectum",46:"green lizard, Lacerta viridis",47:"African chameleon, Chamaeleo chamaeleon",48:"Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",49:"African crocodile, Nile crocodile, Crocodylus niloticus",50:"American alligator, Alligator mississipiensis",51:"triceratops",52:"thunder snake, worm snake, Carphophis amoenus",53:"ringneck snake, ring-necked snake, ring snake",54:"hognose snake, puff adder, sand viper",55:"green snake, grass snake",56:"king snake, kingsnake",57:"garter snake, grass snake",58:"water snake",59:"vine snake",60:"night snake, Hypsiglena torquata",61:"boa constrictor, Constrictor constrictor",62:"rock python, rock snake, Python sebae",63:"Indian cobra, Naja naja",64:"green mamba",65:"sea snake",66:"horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",67:"diamondback, diamondback rattlesnake, Crotalus adamanteus",68:"sidewinder, horned rattlesnake, Crotalus cerastes",69:"trilobite",70:"harvestman, daddy longlegs, Phalangium opilio",71:"scorpion",72:"black and gold garden spider, Argiope aurantia",73:"barn spider, Araneus cavaticus",74:"garden spider, Aranea diademata",75:"black widow, Latrodectus mactans",76:"tarantula",77:"wolf spider, hunting spider",78:"tick",79:"centipede",80:"black grouse",81:"ptarmigan",82:"ruffed grouse, partridge, Bonasa umbellus",83:"prairie chicken, prairie grouse, prairie fowl",84:"peacock",85:"quail",86:"partridge",87:"African grey, African gray, Psittacus erithacus",88:"macaw",89:"sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",90:"lorikeet",91:"coucal",92:"bee eater",93:"hornbill",94:"hummingbird",95:"jacamar",96:"toucan",97:"drake",98:"red-breasted merganser, Mergus serrator",99:"goose",100:"black swan, Cygnus atratus",101:"tusker",102:"echidna, spiny anteater, anteater",103:"platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",104:"wallaby, brush kangaroo",105:"koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",106:"wombat",107:"jelly fish",108:"sea anemone, anemone",109:"brain coral",110:"flatworm, platyhelminth",111:"nematode, nematode worm, roundworm",112:"conch",113:"snail",114:"slug",115:"sea slug, nudibranch",116:"chiton, coat-of-mail shell, sea cradle, polyplacophore",117:"chambered nautilus, pearly nautilus, nautilus",118:"Dungeness crab, Cancer magister",119:"rock crab, Cancer irroratus",120:"fiddler crab",121:"king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",122:"American lobster, Northern lobster, Maine lobster, Homarus americanus",123:"spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",124:"crayfish, crawfish, crawdad, crawdaddy",125:"hermit crab",126:"isopod",127:"white stork, Ciconia ciconia",128:"black stork, Ciconia nigra",129:"spoonbill",130:"flamingo",131:"little blue heron, Egretta caerulea",132:"American egret, great white heron, Egretta albus",133:"bittern",134:"crane",135:"limpkin, Aramus pictus",136:"European gallinule, Porphyrio porphyrio",137:"American coot, marsh hen, mud hen, water hen, Fulica americana",138:"bustard",139:"ruddy turnstone, Arenaria interpres",140:"red-backed sandpiper, dunlin, Erolia alpina",141:"redshank, Tringa totanus",142:"dowitcher",143:"oystercatcher, oyster catcher",144:"pelican",145:"king penguin, Aptenodytes patagonica",146:"albatross, mollymawk",147:"grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",148:"killer whale, killer, orca, grampus, sea wolf, Orcinus orca",149:"dugong, Dugong dugon",150:"sea lion",151:"Chihuahua",152:"Japanese spaniel",153:"Maltese dog, Maltese terrier, Maltese",154:"Pekinese, Pekingese, Peke",155:"Shih-Tzu",156:"Blenheim spaniel",157:"papillon",158:"toy terrier",159:"Rhodesian ridgeback",160:"Afghan hound, Afghan",161:"basset, basset hound",162:"beagle",163:"bloodhound, sleuthhound",164:"bluetick",165:"black-and-tan coonhound",166:"Walker hound, Walker foxhound",167:"English foxhound",168:"redbone",169:"borzoi, Russian wolfhound",170:"Irish wolfhound",171:"Italian greyhound",172:"whippet",173:"Ibizan hound, Ibizan Podenco",174:"Norwegian elkhound, elkhound",175:"otterhound, otter hound",176:"Saluki, gazelle hound",177:"Scottish deerhound, deerhound",178:"Weimaraner",179:"Staffordshire bullterrier, Staffordshire bull terrier",180:"American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",181:"Bedlington terrier",182:"Border terrier",183:"Kerry blue terrier",184:"Irish terrier",185:"Norfolk terrier",186:"Norwich terrier",187:"Yorkshire terrier",188:"wire-haired fox terrier",189:"Lakeland terrier",190:"Sealyham terrier, Sealyham",191:"Airedale, Airedale terrier",192:"cairn, cairn terrier",193:"Australian terrier",194:"Dandie Dinmont, Dandie Dinmont terrier",195:"Boston bull, Boston terrier",196:"miniature schnauzer",197:"giant schnauzer",198:"standard schnauzer",199:"Scotch terrier, Scottish terrier, Scottie",200:"Tibetan terrier, chrysanthemum dog",201:"silky terrier, Sydney silky",202:"soft-coated wheaten terrier",203:"West Highland white terrier",204:"Lhasa, Lhasa apso",205:"flat-coated retriever",206:"curly-coated retriever",207:"golden retriever",208:"Labrador retriever",209:"Chesapeake Bay retriever",210:"German short-haired pointer",211:"vizsla, Hungarian pointer",212:"English setter",213:"Irish setter, red setter",214:"Gordon setter",215:"Brittany spaniel",216:"clumber, clumber spaniel",217:"English springer, English springer spaniel",218:"Welsh springer spaniel",219:"cocker spaniel, English cocker spaniel, cocker",220:"Sussex spaniel",221:"Irish water spaniel",222:"kuvasz",223:"schipperke",224:"groenendael",225:"malinois",226:"briard",227:"kelpie",228:"komondor",229:"Old English sheepdog, bobtail",230:"Shetland sheepdog, Shetland sheep dog, Shetland",231:"collie",232:"Border collie",233:"Bouvier des Flandres, Bouviers des Flandres",234:"Rottweiler",235:"German shepherd, German shepherd dog, German police dog, alsatian",236:"Doberman, Doberman pinscher",237:"miniature pinscher",238:"Greater Swiss Mountain dog",239:"Bernese mountain dog",240:"Appenzeller",241:"EntleBucher",242:"boxer",243:"bull mastiff",244:"Tibetan mastiff",245:"French bulldog",246:"Great Dane",247:"Saint Bernard, St Bernard",248:"Eskimo dog, husky",249:"malamute, malemute, Alaskan malamute",250:"Siberian husky",251:"dalmatian, coach dog, carriage dog",252:"affenpinscher, monkey pinscher, monkey dog",253:"basenji",254:"pug, pug-dog",255:"Leonberg",256:"Newfoundland, Newfoundland dog",257:"Great Pyrenees",258:"Samoyed, Samoyede",259:"Pomeranian",260:"chow, chow chow",261:"keeshond",262:"Brabancon griffon",263:"Pembroke, Pembroke Welsh corgi",264:"Cardigan, Cardigan Welsh corgi",265:"toy poodle",266:"miniature poodle",267:"standard poodle",268:"Mexican hairless",269:"timber wolf, grey wolf, gray wolf, Canis lupus",270:"white wolf, Arctic wolf, Canis lupus tundrarum",271:"red wolf, maned wolf, Canis rufus, Canis niger",272:"coyote, prairie wolf, brush wolf, Canis latrans",273:"dingo, warrigal, warragal, Canis dingo",274:"dhole, Cuon alpinus",275:"African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",276:"hyena, hyaena",277:"red fox, Vulpes vulpes",278:"kit fox, Vulpes macrotis",279:"Arctic fox, white fox, Alopex lagopus",280:"grey fox, gray fox, Urocyon cinereoargenteus",281:"tabby, tabby cat",282:"tiger cat",283:"Persian cat",284:"Siamese cat, Siamese",285:"Egyptian cat",286:"cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",287:"lynx, catamount",288:"leopard, Panthera pardus",289:"snow leopard, ounce, Panthera uncia",290:"jaguar, panther, Panthera onca, Felis onca",291:"lion, king of beasts, Panthera leo",292:"tiger, Panthera tigris",293:"cheetah, chetah, Acinonyx jubatus",294:"brown bear, bruin, Ursus arctos",295:"American black bear, black bear, Ursus americanus, Euarctos americanus",296:"ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",297:"sloth bear, Melursus ursinus, Ursus ursinus",298:"mongoose",299:"meerkat, mierkat",300:"tiger beetle",301:"ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",302:"ground beetle, carabid beetle",303:"long-horned beetle, longicorn, longicorn beetle",304:"leaf beetle, chrysomelid",305:"dung beetle",306:"rhinoceros beetle",307:"weevil",308:"fly",309:"bee",310:"ant, emmet, pismire",311:"grasshopper, hopper",312:"cricket",313:"walking stick, walkingstick, stick insect",314:"cockroach, roach",315:"mantis, mantid",316:"cicada, cicala",317:"leafhopper",318:"lacewing, lacewing fly",319:"dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",320:"damselfly",321:"admiral",322:"ringlet, ringlet butterfly",323:"monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",324:"cabbage butterfly",325:"sulphur butterfly, sulfur butterfly",326:"lycaenid, lycaenid butterfly",327:"starfish, sea star",328:"sea urchin",329:"sea cucumber, holothurian",330:"wood rabbit, cottontail, cottontail rabbit",331:"hare",332:"Angora, Angora rabbit",333:"hamster",334:"porcupine, hedgehog",335:"fox squirrel, eastern fox squirrel, Sciurus niger",336:"marmot",337:"beaver",338:"guinea pig, Cavia cobaya",339:"sorrel",340:"zebra",341:"hog, pig, grunter, squealer, Sus scrofa",342:"wild boar, boar, Sus scrofa",343:"warthog",344:"hippopotamus, hippo, river horse, Hippopotamus amphibius",345:"ox",346:"water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",347:"bison",348:"ram, tup",349:"bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",350:"ibex, Capra ibex",351:"hartebeest",352:"impala, Aepyceros melampus",353:"gazelle",354:"Arabian camel, dromedary, Camelus dromedarius",355:"llama",356:"weasel",357:"mink",358:"polecat, fitch, foulmart, foumart, Mustela putorius",359:"black-footed ferret, ferret, Mustela nigripes",360:"otter",361:"skunk, polecat, wood pussy",362:"badger",363:"armadillo",364:"three-toed sloth, ai, Bradypus tridactylus",365:"orangutan, orang, orangutang, Pongo pygmaeus",366:"gorilla, Gorilla gorilla",367:"chimpanzee, chimp, Pan troglodytes",368:"gibbon, Hylobates lar",369:"siamang, Hylobates syndactylus, Symphalangus syndactylus",370:"guenon, guenon monkey",371:"patas, hussar monkey, Erythrocebus patas",372:"baboon",373:"macaque",374:"langur",375:"colobus, colobus monkey",376:"proboscis monkey, Nasalis larvatus",377:"marmoset",378:"capuchin, ringtail, Cebus capucinus",379:"howler monkey, howler",380:"titi, titi monkey",381:"spider monkey, Ateles geoffroyi",382:"squirrel monkey, Saimiri sciureus",383:"Madagascar cat, ring-tailed lemur, Lemur catta",384:"indri, indris, Indri indri, Indri brevicaudatus",385:"Indian elephant, Elephas maximus",386:"African elephant, Loxodonta africana",387:"lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",388:"giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",389:"barracouta, snoek",390:"eel",391:"coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",392:"rock beauty, Holocanthus tricolor",393:"anemone fish",394:"sturgeon",395:"gar, garfish, garpike, billfish, Lepisosteus osseus",396:"lionfish",397:"puffer, pufferfish, blowfish, globefish",398:"abacus",399:"abaya",400:"academic gown, academic robe, judge's robe",401:"accordion, piano accordion, squeeze box",402:"acoustic guitar",403:"aircraft carrier, carrier, flattop, attack aircraft carrier",404:"airliner",405:"airship, dirigible",406:"altar",407:"ambulance",408:"amphibian, amphibious vehicle",409:"analog clock",410:"apiary, bee house",411:"apron",412:"ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",413:"assault rifle, assault gun",414:"backpack, back pack, knapsack, packsack, rucksack, haversack",415:"bakery, bakeshop, bakehouse",416:"balance beam, beam",417:"balloon",418:"ballpoint, ballpoint pen, ballpen, Biro",419:"Band Aid",420:"banjo",421:"bannister, banister, balustrade, balusters, handrail",422:"barbell",423:"barber chair",424:"barbershop",425:"barn",426:"barometer",427:"barrel, cask",428:"barrow, garden cart, lawn cart, wheelbarrow",429:"baseball",430:"basketball",431:"bassinet",432:"bassoon",433:"bathing cap, swimming cap",434:"bath towel",435:"bathtub, bathing tub, bath, tub",436:"beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",437:"beacon, lighthouse, beacon light, pharos",438:"beaker",439:"bearskin, busby, shako",440:"beer bottle",441:"beer glass",442:"bell cote, bell cot",443:"bib",444:"bicycle-built-for-two, tandem bicycle, tandem",445:"bikini, two-piece",446:"binder, ring-binder",447:"binoculars, field glasses, opera glasses",448:"birdhouse",449:"boathouse",450:"bobsled, bobsleigh, bob",451:"bolo tie, bolo, bola tie, bola",452:"bonnet, poke bonnet",453:"bookcase",454:"bookshop, bookstore, bookstall",455:"bottlecap",456:"bow",457:"bow tie, bow-tie, bowtie",458:"brass, memorial tablet, plaque",459:"brassiere, bra, bandeau",460:"breakwater, groin, groyne, mole, bulwark, seawall, jetty",461:"breastplate, aegis, egis",462:"broom",463:"bucket, pail",464:"buckle",465:"bulletproof vest",466:"bullet train, bullet",467:"butcher shop, meat market",468:"cab, hack, taxi, taxicab",469:"caldron, cauldron",470:"candle, taper, wax light",471:"cannon",472:"canoe",473:"can opener, tin opener",474:"cardigan",475:"car mirror",476:"carousel, carrousel, merry-go-round, roundabout, whirligig",477:"carpenter's kit, tool kit",478:"carton",479:"car wheel",480:"cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",481:"cassette",482:"cassette player",483:"castle",484:"catamaran",485:"CD player",486:"cello, violoncello",487:"cellular telephone, cellular phone, cellphone, cell, mobile phone",488:"chain",489:"chainlink fence",490:"chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",491:"chain saw, chainsaw",492:"chest",493:"chiffonier, commode",494:"chime, bell, gong",495:"china cabinet, china closet",496:"Christmas stocking",497:"church, church building",498:"cinema, movie theater, movie theatre, movie house, picture palace",499:"cleaver, meat cleaver, chopper",500:"cliff dwelling",501:"cloak",502:"clog, geta, patten, sabot",503:"cocktail shaker",504:"coffee mug",505:"coffeepot",506:"coil, spiral, volute, whorl, helix",507:"combination lock",508:"computer keyboard, keypad",509:"confectionery, confectionary, candy store",510:"container ship, containership, container vessel",511:"convertible",512:"corkscrew, bottle screw",513:"cornet, horn, trumpet, trump",514:"cowboy boot",515:"cowboy hat, ten-gallon hat",516:"cradle",517:"crane",518:"crash helmet",519:"crate",520:"crib, cot",521:"Crock Pot",522:"croquet ball",523:"crutch",524:"cuirass",525:"dam, dike, dyke",526:"desk",527:"desktop computer",528:"dial telephone, dial phone",529:"diaper, nappy, napkin",530:"digital clock",531:"digital watch",532:"dining table, board",533:"dishrag, dishcloth",534:"dishwasher, dish washer, dishwashing machine",535:"disk brake, disc brake",536:"dock, dockage, docking facility",537:"dogsled, dog sled, dog sleigh",538:"dome",539:"doormat, welcome mat",540:"drilling platform, offshore rig",541:"drum, membranophone, tympan",542:"drumstick",543:"dumbbell",544:"Dutch oven",545:"electric fan, blower",546:"electric guitar",547:"electric locomotive",548:"entertainment center",549:"envelope",550:"espresso maker",551:"face powder",552:"feather boa, boa",553:"file, file cabinet, filing cabinet",554:"fireboat",555:"fire engine, fire truck",556:"fire screen, fireguard",557:"flagpole, flagstaff",558:"flute, transverse flute",559:"folding chair",560:"football helmet",561:"forklift",562:"fountain",563:"fountain pen",564:"four-poster",565:"freight car",566:"French horn, horn",567:"frying pan, frypan, skillet",568:"fur coat",569:"garbage truck, dustcart",570:"gasmask, respirator, gas helmet",571:"gas pump, gasoline pump, petrol pump, island dispenser",572:"goblet",573:"go-kart",574:"golf ball",575:"golfcart, golf cart",576:"gondola",577:"gong, tam-tam",578:"gown",579:"grand piano, grand",580:"greenhouse, nursery, glasshouse",581:"grille, radiator grille",582:"grocery store, grocery, food market, market",583:"guillotine",584:"hair slide",585:"hair spray",586:"half track",587:"hammer",588:"hamper",589:"hand blower, blow dryer, blow drier, hair dryer, hair drier",590:"hand-held computer, hand-held microcomputer",591:"handkerchief, hankie, hanky, hankey",592:"hard disc, hard disk, fixed disk",593:"harmonica, mouth organ, harp, mouth harp",594:"harp",595:"harvester, reaper",596:"hatchet",597:"holster",598:"home theater, home theatre",599:"honeycomb",600:"hook, claw",601:"hoopskirt, crinoline",602:"horizontal bar, high bar",603:"horse cart, horse-cart",604:"hourglass",605:"iPod",606:"iron, smoothing iron",607:"jack-o'-lantern",608:"jean, blue jean, denim",609:"jeep, landrover",610:"jersey, T-shirt, tee shirt",611:"jigsaw puzzle",612:"jinrikisha, ricksha, rickshaw",613:"joystick",614:"kimono",615:"knee pad",616:"knot",617:"lab coat, laboratory coat",618:"ladle",619:"lampshade, lamp shade",620:"laptop, laptop computer",621:"lawn mower, mower",622:"lens cap, lens cover",623:"letter opener, paper knife, paperknife",624:"library",625:"lifeboat",626:"lighter, light, igniter, ignitor",627:"limousine, limo",628:"liner, ocean liner",629:"lipstick, lip rouge",630:"Loafer",631:"lotion",632:"loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",633:"loupe, jeweler's loupe",634:"lumbermill, sawmill",635:"magnetic compass",636:"mailbag, postbag",637:"mailbox, letter box",638:"maillot",639:"maillot, tank suit",640:"manhole cover",641:"maraca",642:"marimba, xylophone",643:"mask",644:"matchstick",645:"maypole",646:"maze, labyrinth",647:"measuring cup",648:"medicine chest, medicine cabinet",649:"megalith, megalithic structure",650:"microphone, mike",651:"microwave, microwave oven",652:"military uniform",653:"milk can",654:"minibus",655:"miniskirt, mini",656:"minivan",657:"missile",658:"mitten",659:"mixing bowl",660:"mobile home, manufactured home",661:"Model T",662:"modem",663:"monastery",664:"monitor",665:"moped",666:"mortar",667:"mortarboard",668:"mosque",669:"mosquito net",670:"motor scooter, scooter",671:"mountain bike, all-terrain bike, off-roader",672:"mountain tent",673:"mouse, computer mouse",674:"mousetrap",675:"moving van",676:"muzzle",677:"nail",678:"neck brace",679:"necklace",680:"nipple",681:"notebook, notebook computer",682:"obelisk",683:"oboe, hautboy, hautbois",684:"ocarina, sweet potato",685:"odometer, hodometer, mileometer, milometer",686:"oil filter",687:"organ, pipe organ",688:"oscilloscope, scope, cathode-ray oscilloscope, CRO",689:"overskirt",690:"oxcart",691:"oxygen mask",692:"packet",693:"paddle, boat paddle",694:"paddlewheel, paddle wheel",695:"padlock",696:"paintbrush",697:"pajama, pyjama, pj's, jammies",698:"palace",699:"panpipe, pandean pipe, syrinx",700:"paper towel",701:"parachute, chute",702:"parallel bars, bars",703:"park bench",704:"parking meter",705:"passenger car, coach, carriage",706:"patio, terrace",707:"pay-phone, pay-station",708:"pedestal, plinth, footstall",709:"pencil box, pencil case",710:"pencil sharpener",711:"perfume, essence",712:"Petri dish",713:"photocopier",714:"pick, plectrum, plectron",715:"pickelhaube",716:"picket fence, paling",717:"pickup, pickup truck",718:"pier",719:"piggy bank, penny bank",720:"pill bottle",721:"pillow",722:"ping-pong ball",723:"pinwheel",724:"pirate, pirate ship",725:"pitcher, ewer",726:"plane, carpenter's plane, woodworking plane",727:"planetarium",728:"plastic bag",729:"plate rack",730:"plow, plough",731:"plunger, plumber's helper",732:"Polaroid camera, Polaroid Land camera",733:"pole",734:"police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",735:"poncho",736:"pool table, billiard table, snooker table",737:"pop bottle, soda bottle",738:"pot, flowerpot",739:"potter's wheel",740:"power drill",741:"prayer rug, prayer mat",742:"printer",743:"prison, prison house",744:"projectile, missile",745:"projector",746:"puck, hockey puck",747:"punching bag, punch bag, punching ball, punchball",748:"purse",749:"quill, quill pen",750:"quilt, comforter, comfort, puff",751:"racer, race car, racing car",752:"racket, racquet",753:"radiator",754:"radio, wireless",755:"radio telescope, radio reflector",756:"rain barrel",757:"recreational vehicle, RV, R.V.",758:"reel",759:"reflex camera",760:"refrigerator, icebox",761:"remote control, remote",762:"restaurant, eating house, eating place, eatery",763:"revolver, six-gun, six-shooter",764:"rifle",765:"rocking chair, rocker",766:"rotisserie",767:"rubber eraser, rubber, pencil eraser",768:"rugby ball",769:"rule, ruler",770:"running shoe",771:"safe",772:"safety pin",773:"saltshaker, salt shaker",774:"sandal",775:"sarong",776:"sax, saxophone",777:"scabbard",778:"scale, weighing machine",779:"school bus",780:"schooner",781:"scoreboard",782:"screen, CRT screen",783:"screw",784:"screwdriver",785:"seat belt, seatbelt",786:"sewing machine",787:"shield, buckler",788:"shoe shop, shoe-shop, shoe store",789:"shoji",790:"shopping basket",791:"shopping cart",792:"shovel",793:"shower cap",794:"shower curtain",795:"ski",796:"ski mask",797:"sleeping bag",798:"slide rule, slipstick",799:"sliding door",800:"slot, one-armed bandit",801:"snorkel",802:"snowmobile",803:"snowplow, snowplough",804:"soap dispenser",805:"soccer ball",806:"sock",807:"solar dish, solar collector, solar furnace",808:"sombrero",809:"soup bowl",810:"space bar",811:"space heater",812:"space shuttle",813:"spatula",814:"speedboat",815:"spider web, spider's web",816:"spindle",817:"sports car, sport car",818:"spotlight, spot",819:"stage",820:"steam locomotive",821:"steel arch bridge",822:"steel drum",823:"stethoscope",824:"stole",825:"stone wall",826:"stopwatch, stop watch",827:"stove",828:"strainer",829:"streetcar, tram, tramcar, trolley, trolley car",830:"stretcher",831:"studio couch, day bed",832:"stupa, tope",833:"submarine, pigboat, sub, U-boat",834:"suit, suit of clothes",835:"sundial",836:"sunglass",837:"sunglasses, dark glasses, shades",838:"sunscreen, sunblock, sun blocker",839:"suspension bridge",840:"swab, swob, mop",841:"sweatshirt",842:"swimming trunks, bathing trunks",843:"swing",844:"switch, electric switch, electrical switch",845:"syringe",846:"table lamp",847:"tank, army tank, armored combat vehicle, armoured combat vehicle",848:"tape player",849:"teapot",850:"teddy, teddy bear",851:"television, television system",852:"tennis ball",853:"thatch, thatched roof",854:"theater curtain, theatre curtain",855:"thimble",856:"thresher, thrasher, threshing machine",857:"throne",858:"tile roof",859:"toaster",860:"tobacco shop, tobacconist shop, tobacconist",861:"toilet seat",862:"torch",863:"totem pole",864:"tow truck, tow car, wrecker",865:"toyshop",866:"tractor",867:"trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",868:"tray",869:"trench coat",870:"tricycle, trike, velocipede",871:"trimaran",872:"tripod",873:"triumphal arch",874:"trolleybus, trolley coach, trackless trolley",875:"trombone",876:"tub, vat",877:"turnstile",878:"typewriter keyboard",879:"umbrella",880:"unicycle, monocycle",881:"upright, upright piano",882:"vacuum, vacuum cleaner",883:"vase",884:"vault",885:"velvet",886:"vending machine",887:"vestment",888:"viaduct",889:"violin, fiddle",890:"volleyball",891:"waffle iron",892:"wall clock",893:"wallet, billfold, notecase, pocketbook",894:"wardrobe, closet, press",895:"warplane, military plane",896:"washbasin, handbasin, washbowl, lavabo, wash-hand basin",897:"washer, automatic washer, washing machine",898:"water bottle",899:"water jug",900:"water tower",901:"whiskey jug",902:"whistle",903:"wig",904:"window screen",905:"window shade",906:"Windsor tie",907:"wine bottle",908:"wing",909:"wok",910:"wooden spoon",911:"wool, woolen, woollen",912:"worm fence, snake fence, snake-rail fence, Virginia fence",913:"wreck",914:"yawl",915:"yurt",916:"web site, website, internet site, site",917:"comic book",918:"crossword puzzle, crossword",919:"street sign",920:"traffic light, traffic signal, stoplight",921:"book jacket, dust cover, dust jacket, dust wrapper",922:"menu",923:"plate",924:"guacamole",925:"consomme",926:"hot pot, hotpot",927:"trifle",928:"ice cream, icecream",929:"ice lolly, lolly, lollipop, popsicle",930:"French loaf",931:"bagel, beigel",932:"pretzel",933:"cheeseburger",934:"hotdog, hot dog, red hot",935:"mashed potato",936:"head cabbage",937:"broccoli",938:"cauliflower",939:"zucchini, courgette",940:"spaghetti squash",941:"acorn squash",942:"butternut squash",943:"cucumber, cuke",944:"artichoke, globe artichoke",945:"bell pepper",946:"cardoon",947:"mushroom",948:"Granny Smith",949:"strawberry",950:"orange",951:"lemon",952:"fig",953:"pineapple, ananas",954:"banana",955:"jackfruit, jak, jack",956:"custard apple",957:"pomegranate",958:"hay",959:"carbonara",960:"chocolate sauce, chocolate syrup",961:"dough",962:"meat loaf, meatloaf",963:"pizza, pizza pie",964:"potpie",965:"burrito",966:"red wine",967:"espresso",968:"cup",969:"eggnog",970:"alp",971:"bubble",972:"cliff, drop, drop-off",973:"coral reef",974:"geyser",975:"lakeside, lakeshore",976:"promontory, headland, head, foreland",977:"sandbar, sand bar",978:"seashore, coast, seacoast, sea-coast",979:"valley, vale",980:"volcano",981:"ballplayer, baseball player",982:"groom, bridegroom",983:"scuba diver",984:"rapeseed",985:"daisy",986:"yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",987:"corn",988:"acorn",989:"hip, rose hip, rosehip",990:"buckeye, horse chestnut, conker",991:"coral fungus",992:"agaric",993:"gyromitra",994:"stinkhorn, carrion fungus",995:"earthstar",996:"hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",997:"bolete",998:"ear, spike, capitulum",999:"toilet tissue, toilet paper, bathroom tissue"};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=h(n(56)),a=h(n(32)),i=h(n(31)),o=h(n(30)),s=h(n(29)),u=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}(n(10)),c=h(n(129)),l=n(280),f=n(91),p=h(n(51));function h(e){return e&&e.__esModule?e:{default:e};}var d={version:1,alpha:1,topk:3,learningRate:1e-4,hiddenUnits:100,epochs:20,numClasses:2,batchSize:.4},m=function(){function e(t,n){(0,o.default)(this,e),this.mobilenet=null,this.modelPath="https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1_0.25_224/model.json",this.topKPredictions=10,this.hasAnyTrainedClass=!1,this.customModel=null,this.epochs=t.epochs||d.epochs,this.hiddenUnits=t.hiddenUnits||d.hiddenUnits,this.numClasses=t.numClasses||d.numClasses,this.learningRate=t.learningRate||d.learningRate,this.batchSize=t.batchSize||d.batchSize,this.isPredicting=!1,this.mapStringToIndex=[],this.usageType=null,this.ready=(0,p.default)(this.loadModel(),n);}return(0,s.default)(e,[{key:"loadModel",value:function(){var e=(0,i.default)(a.default.mark(function e(){var t,n=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,u.loadModel(this.modelPath);case 2:return this.mobilenet=e.sent,t=this.mobilenet.getLayer("conv_pw_13_relu"),this.video&&u.tidy(function(){return n.mobilenet.predict((0,f.imgToTensor)(n.video));}),e.next=7,u.model({inputs:this.mobilenet.inputs,outputs:t.output});case 7:return this.mobilenetFeatures=e.sent,e.abrupt("return",this);case 9:case"end":return e.stop();}}},e,this);}));return function(){return e.apply(this,arguments);};}()},{key:"classification",value:function value(e,t){return this.usageType="classifier",e&&(0,p.default)(this.loadVideo(e),t),this;}},{key:"regression",value:function value(e,t){return this.usageType="regressor",e&&(0,p.default)(this.loadVideo(e),t),this;}},{key:"loadVideo",value:function(){var e=(0,i.default)(a.default.mark(function e(t){var n,i;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:if(n=null,t instanceof HTMLVideoElement?n=t:"object"===(void 0===t?"undefined":(0,r.default)(t))&&t.elt instanceof HTMLVideoElement&&(n=t.elt),!n){e.next=7;break;}return i=new c.default(n,224),e.next=6,i.loadVideo();case 6:this.video=e.sent;case 7:return e.abrupt("return",this);case 8:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()},{key:"addImage",value:function(){var e=(0,i.default)(a.default.mark(function e(t,n,i){var o,s,u;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return o=void 0,s=void 0,u=i,t instanceof HTMLImageElement||t instanceof HTMLVideoElement?o=t:"object"===(void 0===t?"undefined":(0,r.default)(t))&&(t.elt instanceof HTMLImageElement||t.elt instanceof HTMLVideoElement)?o=t:"string"!=typeof t&&"number"!=typeof t||(o=this.video,s=t),"string"==typeof n||"number"==typeof n?s=n:"function"==typeof n&&(u=n),"string"==typeof s&&(s=this.mapStringToIndex.includes(s)?this.mapStringToIndex.indexOf(s):this.mapStringToIndex.push(s)-1),e.abrupt("return",(0,p.default)(this.addImageInternal(o,s),u));case 7:case"end":return e.stop();}}},e,this);}));return function(t,n,r){return e.apply(this,arguments);};}()},{key:"addImageInternal",value:function(){var e=(0,i.default)(a.default.mark(function e(t,n){var r=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,this.ready;case 2:return u.tidy(function(){var e=(0,f.imgToTensor)(t),a=r.mobilenetFeatures.predict(e),i=void 0;if("classifier"===r.usageType?i=u.tidy(function(){return u.oneHot(u.tensor1d([n],"int32"),r.numClasses);}):"regressor"===r.usageType&&(i=u.tensor2d([[n]])),null==r.xs)r.xs=u.keep(a),r.ys=u.keep(i),r.hasAnyTrainedClass=!0;else{var o=r.xs;r.xs=u.keep(o.concat(a,0));var s=r.ys;r.ys=u.keep(s.concat(i,0)),o.dispose(),s.dispose(),i.dispose();}}),e.abrupt("return",this);case 4:case"end":return e.stop();}}},e,this);}));return function(t,n){return e.apply(this,arguments);};}()},{key:"train",value:function(){var e=(0,i.default)(a.default.mark(function e(t){var n,r,o=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:if(this.hasAnyTrainedClass){e.next=2;break;}throw new Error("Add some examples before training!");case 2:if(this.isPredicting=!1,"classifier"===this.usageType?(this.loss="categoricalCrossentropy",this.customModel=u.sequential({layers:[u.layers.flatten({inputShape:[7,7,256]}),u.layers.dense({units:this.hiddenUnits,activation:"relu",kernelInitializer:"varianceScaling",useBias:!0}),u.layers.dense({units:this.numClasses,kernelInitializer:"varianceScaling",useBias:!1,activation:"softmax"})]})):"regressor"===this.usageType&&(this.loss="meanSquaredError",this.customModel=u.sequential({layers:[u.layers.flatten({inputShape:[7,7,256]}),u.layers.dense({units:this.hiddenUnits,activation:"relu",kernelInitializer:"varianceScaling",useBias:!0}),u.layers.dense({units:1,useBias:!1,kernelInitializer:"Zeros",activation:"linear"})]})),n=u.train.adam(this.learningRate),this.customModel.compile({optimizer:n,loss:this.loss}),(r=Math.floor(this.xs.shape[0]*this.batchSize))>0){e.next=9;break;}throw new Error("Batch size is 0 or NaN. Please choose a non-zero fraction.");case 9:return e.abrupt("return",this.customModel.fit(this.xs,this.ys,{batchSize:r,epochs:this.epochs,callbacks:{onBatchEnd:function(){var e=(0,i.default)(a.default.mark(function e(n,r){return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return t(r.loss.toFixed(5)),e.next=3,u.nextFrame();case 3:case"end":return e.stop();}}},e,o);}));return function(t,n){return e.apply(this,arguments);};}(),onTrainEnd:function onTrainEnd(){return t(null);}}}));case 10:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()},{key:"classify",value:function(){var e=(0,i.default)(a.default.mark(function e(t,n){var i,o;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return i=void 0,o=void 0,t instanceof HTMLImageElement||t instanceof HTMLVideoElement?i=t:"object"===(void 0===t?"undefined":(0,r.default)(t))&&(t.elt instanceof HTMLImageElement||t.elt instanceof HTMLVideoElement)?i=t.elt:"function"==typeof t&&(i=this.video,o=t),"function"==typeof n&&(o=n),e.abrupt("return",(0,p.default)(this.classifyInternal(i),o));case 5:case"end":return e.stop();}}},e,this);}));return function(t,n){return e.apply(this,arguments);};}()},{key:"classifyInternal",value:function(){var e=(0,i.default)(a.default.mark(function e(t){var n,r,i=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:if("classifier"===this.usageType){e.next=2;break;}throw new Error("Mobilenet Feature Extraction has not been set to be a classifier.");case 2:return e.next=4,u.nextFrame();case 4:return this.isPredicting=!0,n=u.tidy(function(){var e=(0,f.imgToTensor)(t),n=i.mobilenetFeatures.predict(e);return i.customModel.predict(n).as1D().argMax();}),e.next=8,n.data();case 8:return r=e.sent[0],this.mapStringToIndex.length>0&&(r=this.mapStringToIndex[r]),e.abrupt("return",r);case 11:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()},{key:"predict",value:function(){var e=(0,i.default)(a.default.mark(function e(t,n){var i,o;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return i=void 0,o=void 0,t instanceof HTMLImageElement||t instanceof HTMLVideoElement?i=t:"object"===(void 0===t?"undefined":(0,r.default)(t))&&(t.elt instanceof HTMLImageElement||t.elt instanceof HTMLVideoElement)?i=t.elt:"function"==typeof t&&(i=this.video,o=t),"function"==typeof n&&(o=n),e.abrupt("return",(0,p.default)(this.predictInternal(i),o));case 5:case"end":return e.stop();}}},e,this);}));return function(t,n){return e.apply(this,arguments);};}()},{key:"predictInternal",value:function(){var e=(0,i.default)(a.default.mark(function e(t){var n,r,i=this;return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:if("regressor"===this.usageType){e.next=2;break;}throw new Error("Mobilenet Feature Extraction has not been set to be a regressor.");case 2:return e.next=4,u.nextFrame();case 4:return this.isPredicting=!0,n=u.tidy(function(){var e=(0,f.imgToTensor)(t),n=i.mobilenetFeatures.predict(e);return i.customModel.predict(n).as1D();}),e.next=8,n.data();case 8:return r=e.sent,n.dispose(),e.abrupt("return",r[0]);case 11:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()}],[{key:"getTopKClasses",value:function(){var e=(0,i.default)(a.default.mark(function e(t,n){var r,i,o,s,c,f,p,h,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){};return a.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,t.data();case 2:for(r=e.sent,i=[],o=0;o<r.length;o+=1){i.push({value:r[o],index:o});}for(i.sort(function(e,t){return t.value-e.value;}),s=new Float32Array(n),c=new Int32Array(n),f=0;f<n;f+=1){s[f]=i[f].value,c[f]=i[f].index;}for(p=[],h=0;h<c.length;h+=1){p.push({className:l.IMAGENET_CLASSES[c[h]],probability:s[h]});}return e.next=13,u.nextFrame();case 13:return d(void 0,p),e.abrupt("return",p);case 15:case"end":return e.stop();}}},e,this);}));return function(t,n){return e.apply(this,arguments);};}()}]),e;}();t.default=m;},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(e){return e&&e.__esModule?e:{default:e};}(n(281));t.default=function(e,t,n){var a;if("string"!=typeof e)throw new Error('Please specify a model to use. E.g: "MobileNet"');a=e.toLowerCase();var i={},o=n;if("object"===t?i=t:"function"==typeof t&&(o=t),"mobilenet"===a)return new r.default(i,o);throw new Error(a+" is not a valid model.");};},function(e,t,n){n(130)("observable");},function(e,t,n){n(130)("asyncIterator");},function(e,t,n){var r=n(67),a=n(175).f,i={}.toString,o="object"==(typeof window==="undefined"?"undefined":_typeof(window))&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];e.exports.f=function(e){return o&&"[object Window]"==i.call(e)?function(e){try{return a(e);}catch(e){return o.slice();}}(e):a(r(e));};},function(e,t,n){var r=n(96);e.exports=Array.isArray||function(e){return"Array"==r(e);};},function(e,t,n){var r=n(83),a=n(136),i=n(94);e.exports=function(e){var t=r(e),n=a.f;if(n)for(var o,s=n(e),u=i.f,c=0;s.length>c;){u.call(e,o=s[c++])&&t.push(o);}return t;};},function(e,t,n){var r=n(105)("meta"),a=n(58),i=n(68),o=n(52).f,s=0,u=Object.isExtensible||function(){return!0;},c=!n(84)(function(){return u(Object.preventExtensions({}));}),l=function l(e){o(e,r,{value:{i:"O"+ ++s,w:{}}});},f=e.exports={KEY:r,NEED:!1,fastKey:function fastKey(e,t){if(!a(e))return"symbol"==(typeof e==="undefined"?"undefined":_typeof(e))?e:("string"==typeof e?"S":"P")+e;if(!i(e,r)){if(!u(e))return"F";if(!t)return"E";l(e);}return e[r].i;},getWeak:function getWeak(e,t){if(!i(e,r)){if(!u(e))return!0;if(!t)return!1;l(e);}return e[r].w;},onFreeze:function onFreeze(e){return c&&f.NEED&&u(e)&&!i(e,r)&&l(e),e;}};},function(e,t,n){"use strict";var r=n(25),a=n(68),i=n(57),o=n(34),s=n(185),u=n(288).KEY,c=n(84),l=n(138),f=n(104),p=n(105),h=n(24),d=n(131),m=n(130),g=n(287),y=n(286),v=n(45),b=n(58),w=n(67),x=n(143),k=n(97),O=n(135),S=n(285),N=n(174),E=n(52),I=n(83),T=N.f,A=E.f,C=S.f,_P=r.Symbol,_=r.JSON,R=_&&_.stringify,M=h("_hidden"),j=h("toPrimitive"),D={}.propertyIsEnumerable,L=l("symbol-registry"),z=l("symbols"),F=l("op-symbols"),B=Object.prototype,V="function"==typeof _P,U=r.QObject,W=!U||!U.prototype||!U.prototype.findChild,G=i&&c(function(){return 7!=O(A({},"a",{get:function get(){return A(this,"a",{value:7}).a;}})).a;})?function(e,t,n){var r=T(B,t);r&&delete B[t],A(e,t,n),r&&e!==B&&A(B,t,r);}:A,q=function q(e){var t=z[e]=O(_P.prototype);return t._k=e,t;},H=V&&"symbol"==_typeof(_P.iterator)?function(e){return"symbol"==(typeof e==="undefined"?"undefined":_typeof(e));}:function(e){return e instanceof _P;},K=function K(e,t,n){return e===B&&K(F,t,n),v(e),t=x(t,!0),v(n),a(z,t)?(n.enumerable?(a(e,M)&&e[M][t]&&(e[M][t]=!1),n=O(n,{enumerable:k(0,!1)})):(a(e,M)||A(e,M,k(1,{})),e[M][t]=!0),G(e,t,n)):A(e,t,n);},X=function X(e,t){v(e);for(var n,r=g(t=w(t)),a=0,i=r.length;i>a;){K(e,n=r[a++],t[n]);}return e;},J=function J(e){var t=D.call(this,e=x(e,!0));return!(this===B&&a(z,e)&&!a(F,e))&&(!(t||!a(this,e)||!a(z,e)||a(this,M)&&this[M][e])||t);},Y=function Y(e,t){if(e=w(e),t=x(t,!0),e!==B||!a(z,t)||a(F,t)){var n=T(e,t);return!n||!a(z,t)||a(e,M)&&e[M][t]||(n.enumerable=!0),n;}},Q=function Q(e){for(var t,n=C(w(e)),r=[],i=0;n.length>i;){a(z,t=n[i++])||t==M||t==u||r.push(t);}return r;},Z=function Z(e){for(var t,n=e===B,r=C(n?F:w(e)),i=[],o=0;r.length>o;){!a(z,t=r[o++])||n&&!a(B,t)||i.push(z[t]);}return i;};V||(s((_P=function P(){if(this instanceof _P)throw TypeError("Symbol is not a constructor!");var e=p(arguments.length>0?arguments[0]:void 0),t=function t(n){this===B&&t.call(F,n),a(this,M)&&a(this[M],e)&&(this[M][e]=!1),G(this,e,k(1,n));};return i&&W&&G(B,e,{configurable:!0,set:t}),q(e);}).prototype,"toString",function(){return this._k;}),N.f=Y,E.f=K,n(175).f=S.f=Q,n(94).f=J,n(136).f=Z,i&&!n(95)&&s(B,"propertyIsEnumerable",J,!0),d.f=function(e){return q(h(e));}),o(o.G+o.W+o.F*!V,{Symbol:_P});for(var $="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ee=0;$.length>ee;){h($[ee++]);}for(var te=I(h.store),ne=0;te.length>ne;){m(te[ne++]);}o(o.S+o.F*!V,"Symbol",{for:function _for(e){return a(L,e+="")?L[e]:L[e]=_P(e);},keyFor:function keyFor(e){if(!H(e))throw TypeError(e+" is not a symbol!");for(var t in L){if(L[t]===e)return t;}},useSetter:function useSetter(){W=!0;},useSimple:function useSimple(){W=!1;}}),o(o.S+o.F*!V,"Object",{create:function create(e,t){return void 0===t?O(e):X(O(e),t);},defineProperty:K,defineProperties:X,getOwnPropertyDescriptor:Y,getOwnPropertyNames:Q,getOwnPropertySymbols:Z}),_&&o(o.S+o.F*(!V||c(function(){var e=_P();return"[null]"!=R([e])||"{}"!=R({a:e})||"{}"!=R(Object(e));})),"JSON",{stringify:function stringify(e){for(var t,n,r=[e],a=1;arguments.length>a;){r.push(arguments[a++]);}if(n=t=r[1],(b(t)||void 0!==e)&&!H(e))return y(t)||(t=function t(e,_t3){if("function"==typeof n&&(_t3=n.call(this,e,_t3)),!H(_t3))return _t3;}),r[1]=t,R.apply(_,r);}}),_P.prototype[j]||n(69)(_P.prototype,j,_P.prototype.valueOf),f(_P,"Symbol"),f(Math,"Math",!0),f(r.JSON,"JSON",!0);},function(e,t,n){n(289),n(187),n(284),n(283),e.exports=n(21).Symbol;},function(e,t,n){e.exports={default:n(290),__esModule:!0};},function(e,t,n){n(92),n(103),e.exports=n(131).f("iterator");},function(e,t,n){e.exports={default:n(292),__esModule:!0};},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=h(n(56)),a=h(n(64)),i=h(n(32)),o=h(n(31)),s=h(n(30)),u=h(n(29)),c=p(n(10)),l=p(n(242)),f=h(n(51));function p(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}function h(e){return e&&e.__esModule?e:{default:e};}var d={mobilenet:{version:1,alpha:1,topk:3}},m=function(){function e(t,n,r,a){(0,s.default)(this,e),this.modelName=t,this.video=n,this.version=r.version||d[this.modelName].version,this.alpha=r.alpha||d[this.modelName].alpha,this.topk=r.topk||d[this.modelName].topk,this.model=null,"mobilenet"===this.modelName?this.modelToUse=l:this.modelToUse=null,this.ready=(0,f.default)(this.loadModel(),a);}return(0,u.default)(e,[{key:"loadModel",value:function(){var e=(0,o.default)(i.default.mark(function e(){return i.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,this.modelToUse.load(this.version,this.alpha);case 2:return this.model=e.sent,e.abrupt("return",this);case 4:case"end":return e.stop();}}},e,this);}));return function(){return e.apply(this,arguments);};}()},{key:"predictInternal",value:function(){var e=(0,o.default)(i.default.mark(function e(t,n){var r=this;return i.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,this.ready;case 2:return e.next=4,c.nextFrame();case 4:if(!this.video||0!==this.video.readyState){e.next=7;break;}return e.next=7,new a.default(function(e){r.video.onloadeddata=function(){return e();};});case 7:return e.abrupt("return",this.model.classify(t,n));case 8:case"end":return e.stop();}}},e,this);}));return function(t,n){return e.apply(this,arguments);};}()},{key:"predict",value:function(){var e=(0,o.default)(i.default.mark(function e(t){var n,a,o,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,u=arguments[2];return i.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return n=this.video,a=this.topk,o=void 0,"function"==typeof t?(n=this.video,o=t):"number"==typeof t?(n=this.video,a=t):t instanceof HTMLImageElement?n=t:"object"===(void 0===t?"undefined":(0,r.default)(t))&&t.elt instanceof HTMLImageElement&&(n=t.elt),"number"==typeof s?a=s:"function"==typeof s&&(o=s),"function"==typeof u&&(o=u),e.abrupt("return",(0,f.default)(this.predictInternal(n,a),o));case 7:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()}]),e;}();t.default=function(e,t,n,a){var i,o=void 0,s={},u=a;if("string"!=typeof e)throw new Error('Please specify a model to use. E.g: "MobileNet"');i=e.toLowerCase(),t instanceof HTMLVideoElement?o=t:"object"===(void 0===t?"undefined":(0,r.default)(t))&&t.elt instanceof HTMLVideoElement?o=t.elt:"object"===(void 0===t?"undefined":(0,r.default)(t))?s=t:"function"==typeof t&&(u=t),"object"===(void 0===n?"undefined":(0,r.default)(n))?s=n:"function"==typeof n&&(u=n);var c=new m(i,o,s,u);return u?c:c.ready;};},function(e,t,n){var r=n(34);r(r.S+r.F*!n(57),"Object",{defineProperty:n(52).f});},function(e,t,n){n(295);var r=n(21).Object;e.exports=function(e,t,n){return r.defineProperty(e,t,n);};},function(e,t,n){e.exports={default:n(296),__esModule:!0};},function(e,t,n){"use strict";var r=n(34),a=n(132),i=n(178);r(r.S,"Promise",{try:function _try(e){var t=a.f(this),n=i(e);return(n.e?t.reject:t.resolve)(n.v),t.promise;}});},function(e,t,n){"use strict";var r=n(34),a=n(21),i=n(25),o=n(180),s=n(177);r(r.P+r.R,"Promise",{finally:function _finally(e){var t=o(this,a.Promise||i.Promise),n="function"==typeof e;return this.then(n?function(n){return s(t,e()).then(function(){return n;});}:e,n?function(n){return s(t,e()).then(function(){throw n;});}:e);}});},function(e,t,n){"use strict";var r=n(25),a=n(21),i=n(52),o=n(57),s=n(24)("species");e.exports=function(e){var t="function"==typeof a[e]?a[e]:r[e];o&&t&&!t[s]&&i.f(t,s,{configurable:!0,get:function get(){return this;}});};},function(e,t,n){var r=n(69);e.exports=function(e,t,n){for(var a in t){n&&e[a]?e[a]=t[a]:r(e,a,t[a]);}return e;};},function(e,t,n){var r=n(25).navigator;e.exports=r&&r.userAgent||"";},function(e,t,n){var r=n(25),a=n(179).set,i=r.MutationObserver||r.WebKitMutationObserver,o=r.process,s=r.Promise,u="process"==n(96)(o);e.exports=function(){var e,t,n,c=function c(){var r,a;for(u&&(r=o.domain)&&r.exit();e;){a=e.fn,e=e.next;try{a();}catch(r){throw e?n():t=void 0,r;}}t=void 0,r&&r.enter();};if(u)n=function n(){o.nextTick(c);};else if(!i||r.navigator&&r.navigator.standalone){if(s&&s.resolve){var l=s.resolve(void 0);n=function n(){l.then(c);};}else n=function n(){a.call(r,c);};}else{var f=!0,p=document.createTextNode("");new i(c).observe(p,{characterData:!0}),n=function n(){p.data=f=!f;};}return function(r){var a={fn:r,next:void 0};t&&(t.next=a),e||(e=a,n()),t=a;};};},function(e,t){e.exports=function(e,t,n){var r=void 0===n;switch(t.length){case 0:return r?e():e.call(n);case 1:return r?e(t[0]):e.call(n,t[0]);case 2:return r?e(t[0],t[1]):e.call(n,t[0],t[1]);case 3:return r?e(t[0],t[1],t[2]):e.call(n,t[0],t[1],t[2]);case 4:return r?e(t[0],t[1],t[2],t[3]):e.call(n,t[0],t[1],t[2],t[3]);}return e.apply(n,t);};},function(e,t,n){var r=n(85),a=n(182),i=n(181),o=n(45),s=n(141),u=n(133),c={},l={};(t=e.exports=function(e,t,n,f,p){var h,d,m,g,y=p?function(){return e;}:u(e),v=r(n,f,t?2:1),b=0;if("function"!=typeof y)throw TypeError(e+" is not iterable!");if(i(y)){for(h=s(e.length);h>b;b++){if((g=t?v(o(d=e[b])[0],d[1]):v(e[b]))===c||g===l)return g;}}else for(m=y.call(e);!(d=m.next()).done;){if((g=a(m,v,d.value,t))===c||g===l)return g;}}).BREAK=c,t.RETURN=l;},function(e,t){e.exports=function(e,t,n,r){if(!(e instanceof t)||void 0!==r&&r in e)throw TypeError(n+": incorrect invocation!");return e;};},function(e,t,n){"use strict";var r,a,i,o,s=n(95),u=n(25),c=n(85),l=n(134),f=n(34),p=n(58),h=n(106),d=n(306),m=n(305),g=n(180),y=n(179).set,v=n(303)(),b=n(132),w=n(178),x=n(302),k=n(177),O=u.TypeError,S=u.process,N=S&&S.versions,E=N&&N.v8||"",_I=u.Promise,T="process"==l(S),A=function A(){},C=a=b.f,P=!!function(){try{var e=_I.resolve(1),t=(e.constructor={})[n(24)("species")]=function(e){e(A,A);};return(T||"function"==typeof PromiseRejectionEvent)&&e.then(A)instanceof t&&0!==E.indexOf("6.6")&&-1===x.indexOf("Chrome/66");}catch(e){}}(),_=function _(e){var t;return!(!p(e)||"function"!=typeof(t=e.then))&&t;},R=function R(e,t){if(!e._n){e._n=!0;var n=e._c;v(function(){for(var r=e._v,a=1==e._s,i=0,o=function o(t){var n,i,o,s=a?t.ok:t.fail,u=t.resolve,c=t.reject,l=t.domain;try{s?(a||(2==e._h&&D(e),e._h=1),!0===s?n=r:(l&&l.enter(),n=s(r),l&&(l.exit(),o=!0)),n===t.promise?c(O("Promise-chain cycle")):(i=_(n))?i.call(n,u,c):u(n)):c(r);}catch(e){l&&!o&&l.exit(),c(e);}};n.length>i;){o(n[i++]);}e._c=[],e._n=!1,t&&!e._h&&M(e);});}},M=function M(e){y.call(u,function(){var t,n,r,a=e._v,i=j(e);if(i&&(t=w(function(){T?S.emit("unhandledRejection",a,e):(n=u.onunhandledrejection)?n({promise:e,reason:a}):(r=u.console)&&r.error&&r.error("Unhandled promise rejection",a);}),e._h=T||j(e)?2:1),e._a=void 0,i&&t.e)throw t.v;});},j=function j(e){return 1!==e._h&&0===(e._a||e._c).length;},D=function D(e){y.call(u,function(){var t;T?S.emit("rejectionHandled",e):(t=u.onrejectionhandled)&&t({promise:e,reason:e._v});});},L=function L(e){var t=this;t._d||(t._d=!0,(t=t._w||t)._v=e,t._s=2,t._a||(t._a=t._c.slice()),R(t,!0));},z=function z(e){var t,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===e)throw O("Promise can't be resolved itself");(t=_(e))?v(function(){var r={_w:n,_d:!1};try{t.call(e,c(z,r,1),c(L,r,1));}catch(e){L.call(r,e);}}):(n._v=e,n._s=1,R(n,!1));}catch(e){L.call({_w:n,_d:!1},e);}}};P||(_I=function I(e){d(this,_I,"Promise","_h"),h(e),r.call(this);try{e(c(z,this,1),c(L,this,1));}catch(e){L.call(this,e);}},(r=function r(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1;}).prototype=n(301)(_I.prototype,{then:function then(e,t){var n=C(g(this,_I));return n.ok="function"!=typeof e||e,n.fail="function"==typeof t&&t,n.domain=T?S.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&R(this,!1),n.promise;},catch:function _catch(e){return this.then(void 0,e);}}),i=function i(){var e=new r();this.promise=e,this.resolve=c(z,e,1),this.reject=c(L,e,1);},b.f=C=function C(e){return e===_I||e===o?new i(e):a(e);}),f(f.G+f.W+f.F*!P,{Promise:_I}),n(104)(_I,"Promise"),n(300)("Promise"),o=n(21).Promise,f(f.S+f.F*!P,"Promise",{reject:function reject(e){var t=C(this);return(0,t.reject)(e),t.promise;}}),f(f.S+f.F*(s||!P),"Promise",{resolve:function resolve(e){return k(s&&this===o?_I:this,e);}}),f(f.S+f.F*!(P&&n(176)(function(e){_I.all(e).catch(A);})),"Promise",{all:function all(e){var t=this,n=C(t),r=n.resolve,a=n.reject,i=w(function(){var n=[],i=0,o=1;m(e,!1,function(e){var s=i++,u=!1;n.push(void 0),o++,t.resolve(e).then(function(e){u||(u=!0,n[s]=e,--o||r(n));},a);}),--o||r(n);});return i.e&&a(i.v),n.promise;},race:function race(e){var t=this,n=C(t),r=n.reject,a=w(function(){m(e,!1,function(e){t.resolve(e).then(n.resolve,r);});});return a.e&&r(a.v),n.promise;}});},function(e,t){e.exports=function(e,t){return{value:t,done:!!e};};},function(e,t){e.exports=function(){};},function(e,t,n){"use strict";var r=n(309),a=n(308),i=n(81),o=n(67);e.exports=n(186)(Array,"Array",function(e,t){this._t=o(e),this._i=0,this._k=t;},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,a(1)):a(0,"keys"==t?n:"values"==t?e[n]:[n,e[n]]);},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries");},function(e,t,n){var r=n(52),a=n(45),i=n(83);e.exports=n(57)?Object.defineProperties:function(e,t){a(e);for(var n,o=i(t),s=o.length,u=0;s>u;){r.f(e,n=o[u++],t[n]);}return e;};},function(e,t,n){"use strict";var r=n(135),a=n(97),i=n(104),o={};n(69)(o,n(24)("iterator"),function(){return this;}),e.exports=function(e,t,n){e.prototype=r(o,{next:a(1,n)}),i(e,t+" Iterator");};},function(e,t,n){var r=n(140),a=n(142);e.exports=function(e){return function(t,n){var i,o,s=String(a(t)),u=r(n),c=s.length;return u<0||u>=c?e?"":void 0:(i=s.charCodeAt(u))<55296||i>56319||u+1===c||(o=s.charCodeAt(u+1))<56320||o>57343?e?s.charAt(u):i:e?s.slice(u,u+2):o-56320+(i-55296<<10)+65536;};};},function(e,t,n){n(187),n(92),n(103),n(307),n(299),n(298),e.exports=n(21).Promise;},function(e,t){!function(t){"use strict";var n,r=Object.prototype,a=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag",c="object"==(typeof e==="undefined"?"undefined":_typeof(e)),l=t.regeneratorRuntime;if(l)c&&(e.exports=l);else{(l=t.regeneratorRuntime=c?e.exports:{}).wrap=w;var f="suspendedStart",p="suspendedYield",h="executing",d="completed",m={},g={};g[o]=function(){return this;};var y=Object.getPrototypeOf,v=y&&y(y(P([])));v&&v!==r&&a.call(v,o)&&(g=v);var b=S.prototype=k.prototype=Object.create(g);O.prototype=b.constructor=S,S.constructor=O,S[u]=O.displayName="GeneratorFunction",l.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===O||"GeneratorFunction"===(t.displayName||t.name));},l.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,S):(e.__proto__=S,u in e||(e[u]="GeneratorFunction")),e.prototype=Object.create(b),e;},l.awrap=function(e){return{__await:e};},N(E.prototype),E.prototype[s]=function(){return this;},l.AsyncIterator=E,l.async=function(e,t,n,r){var a=new E(w(e,t,n,r));return l.isGeneratorFunction(t)?a:a.next().then(function(e){return e.done?e.value:a.next();});},N(b),b[u]="Generator",b[o]=function(){return this;},b.toString=function(){return"[object Generator]";},l.keys=function(e){var t=[];for(var n in e){t.push(n);}return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n;}return n.done=!0,n;};},l.values=P,C.prototype={constructor:C,reset:function reset(e){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(A),!e)for(var t in this){"t"===t.charAt(0)&&a.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=n);}},stop:function stop(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval;},dispatchException:function dispatchException(e){if(this.done)throw e;var t=this;function r(r,a){return s.type="throw",s.arg=e,t.next=r,a&&(t.method="next",t.arg=n),!!a;}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],s=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var u=a.call(o,"catchLoc"),c=a.call(o,"finallyLoc");if(u&&c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc);}else if(u){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc);}}}},abrupt:function abrupt(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&a.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break;}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?(this.method="next",this.next=i.finallyLoc,m):this.complete(o);},complete:function complete(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),m;},finish:function finish(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),A(n),m;}},catch:function _catch(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;A(n);}return a;}}throw new Error("illegal catch attempt");},delegateYield:function delegateYield(e,t,r){return this.delegate={iterator:P(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=n),m;}};}function w(e,t,n,r){var a=t&&t.prototype instanceof k?t:k,i=Object.create(a.prototype),o=new C(r||[]);return i._invoke=function(e,t,n){var r=f;return function(a,i){if(r===h)throw new Error("Generator is already running");if(r===d){if("throw"===a)throw i;return _();}for(n.method=a,n.arg=i;;){var o=n.delegate;if(o){var s=I(o,n);if(s){if(s===m)continue;return s;}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===f)throw r=d,n.arg;n.dispatchException(n.arg);}else"return"===n.method&&n.abrupt("return",n.arg);r=h;var u=x(e,t,n);if("normal"===u.type){if(r=n.done?d:p,u.arg===m)continue;return{value:u.arg,done:n.done};}"throw"===u.type&&(r=d,n.method="throw",n.arg=u.arg);}};}(e,n,o),i;}function x(e,t,n){try{return{type:"normal",arg:e.call(t,n)};}catch(e){return{type:"throw",arg:e};}}function k(){}function O(){}function S(){}function N(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e);};});}function E(e){var t;this._invoke=function(n,r){function i(){return new Promise(function(t,i){!function t(n,r,i,o){var s=x(e[n],e,r);if("throw"!==s.type){var u=s.arg,c=u.value;return c&&"object"==(typeof c==="undefined"?"undefined":_typeof(c))&&a.call(c,"__await")?Promise.resolve(c.__await).then(function(e){t("next",e,i,o);},function(e){t("throw",e,i,o);}):Promise.resolve(c).then(function(e){u.value=e,i(u);},o);}o(s.arg);}(n,r,t,i);});}return t=t?t.then(i,i):i();};}function I(e,t){var r=e.iterator[t.method];if(r===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=n,I(e,t),"throw"===t.method))return m;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method");}return m;}var a=x(r,e.iterator,t.arg);if("throw"===a.type)return t.method="throw",t.arg=a.arg,t.delegate=null,m;var i=a.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=n),t.delegate=null,m):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,m);}function T(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t);}function A(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t;}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0);}function P(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r<e.length;){if(a.call(e,r))return t.value=e[r],t.done=!1,t;}return t.value=n,t.done=!0,t;};return i.next=i;}}return{next:_};}function _(){return{value:n,done:!0};}}(function(){return this;}()||Function("return this")());},function(e,t,n){var r=function(){return this;}()||Function("return this")(),a=r.regeneratorRuntime&&Object.getOwnPropertyNames(r).indexOf("regeneratorRuntime")>=0,i=a&&r.regeneratorRuntime;if(r.regeneratorRuntime=void 0,e.exports=n(315),a)r.regeneratorRuntime=i;else try{delete r.regeneratorRuntime;}catch(e){r.regeneratorRuntime=void 0;}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=c(n(32)),a=c(n(31)),i=c(n(30)),o=c(n(29)),s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}(n(10)),u=c(n(51));function c(e){return e&&e.__esModule?e:{default:e};}var l=function(){function e(t,n,r,a){(0,i.default)(this,e),this.model=t,this.audioContext=n,this.stream=r,this.frequency=null,this.ready=(0,u.default)(this.loadModel(t),a);}return(0,o.default)(e,[{key:"loadModel",value:function(){var e=(0,a.default)(r.default.mark(function e(t){return r.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,s.loadModel(t+"/model.json");case 2:if(this.model=e.sent,!this.audioContext){e.next=8;break;}return e.next=6,this.processStream();case 6:e.next=9;break;case 8:throw new Error("Could not access microphone - getUserMedia not available");case 9:return e.abrupt("return",this);case 10:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()},{key:"processStream",value:function(){var e=(0,a.default)(r.default.mark(function e(){var t,n,a,i,o;return r.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,s.nextFrame();case 2:for(t=this.audioContext.createMediaStreamSource(this.stream),n=this.audioContext.sampleRate/16e3*1024,a=4;a<n;){a*=2;}(i=this.audioContext.createScriptProcessor(a,1,1)).onaudioprocess=this.processMicrophoneBuffer.bind(this),(o=this.audioContext.createGain()).gain.setValueAtTime(0,this.audioContext.currentTime),t.connect(i),i.connect(o),o.connect(this.audioContext.destination),"running"!==this.audioContext.state&&console.warn("User gesture needed to start AudioContext, please click");case 14:case"end":return e.stop();}}},e,this);}));return function(){return e.apply(this,arguments);};}()},{key:"processMicrophoneBuffer",value:function(){var t=(0,a.default)(r.default.mark(function t(n){var a,i=this;return r.default.wrap(function(t){for(;;){switch(t.prev=t.next){case 0:return t.next=2,s.nextFrame();case 2:this.results={},a=s.add(s.linspace(0,7180,360),s.tensor(1997.379408437619)),e.resample(n.inputBuffer,function(e){s.tidy(function(){i.running=!0;var t=s.tensor(e.slice(0,1024)),n=s.sub(t,s.mean(t)),r=s.tensor(s.norm(n).dataSync()/Math.sqrt(1024)),o=s.div(n,r).reshape([1,1024]),u=i.model.predict([o]).reshape([360]),c=u.max().dataSync()[0],l=u.argMax().dataSync()[0];i.results.confidence=c.toFixed(3);var f=Math.max(0,l-4),p=Math.min(360,l+5),h=u.slice([f],[p-f]),d=a.slice([f],[p-f]),m=s.mul(h,d).dataSync().reduce(function(e,t){return e+t;},0)/h.dataSync().reduce(function(e,t){return e+t;},0),g=10*Math.pow(m/1200,2),y=c>.5?g:null;i.frequency=y;});});case 5:case"end":return t.stop();}}},t,this);}));return function(e){return t.apply(this,arguments);};}()},{key:"getPitch",value:function(){var e=(0,a.default)(r.default.mark(function e(t){var n;return r.default.wrap(function(e){for(;;){switch(e.prev=e.next){case 0:return e.next=2,this.ready;case 2:return e.next=4,s.nextFrame();case 4:return n=this.frequency,t&&t(void 0,n),e.abrupt("return",n);case 7:case"end":return e.stop();}}},e,this);}));return function(t){return e.apply(this,arguments);};}()}],[{key:"resample",value:function value(e,t){for(var n=e.sampleRate%16e3!=0,r=e.sampleRate/16e3,a=e.getChannelData(0),i=new Float32Array(1024),o=0;o<1024;o+=1){if(n){var s=Math.floor(o*r),u=s+1,c=o*r-s;i[o]=(1-c)*a[s]+c*a[u];}else i[o]=a[o*r];}t(i);}}]),e;}();t.default=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"./",t=arguments[1],n=arguments[2],r=arguments[3];return new l(e,t,n,r);};},function(e,t,n){"use strict";e.exports={};},function(e,t,n){"use strict";e.exports=a;var r=n(65);function a(e,t,n){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(n);}(a.prototype=Object.create(r.EventEmitter.prototype)).constructor=a,a.prototype.rpcCall=function e(t,n,a,i,o){if(!i)throw TypeError("request must be specified");var s=this;if(!o)return r.asPromise(e,s,t,n,a,i);if(s.rpcImpl)try{return s.rpcImpl(t,n[s.requestDelimited?"encodeDelimited":"encode"](i).finish(),function(e,n){if(e)return s.emit("error",e,t),o(e);if(null!==n){if(!(n instanceof a))try{n=a[s.responseDelimited?"decodeDelimited":"decode"](n);}catch(e){return s.emit("error",e,t),o(e);}return s.emit("data",n,t),o(null,n);}s.end(!0);});}catch(e){return s.emit("error",e,t),void setTimeout(function(){o(e);},0);}else setTimeout(function(){o(Error("already ended"));},0);},a.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this;};},function(e,t,n){"use strict";t.Service=n(319);},function(e,t,n){"use strict";e.exports=i;var r=n(188);(i.prototype=Object.create(r.prototype)).constructor=i;var a=n(65);function i(e){r.call(this,e);}a.Buffer&&(i.prototype._slice=a.Buffer.prototype.slice),i.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len));};},function(e,t,n){"use strict";e.exports=o;var r=n(189);(o.prototype=Object.create(r.prototype)).constructor=o;var a=n(65),i=a.Buffer;function o(){r.call(this);}o.alloc=function(e){return(o.alloc=a._Buffer_allocUnsafe)(e);};var s=i&&i.prototype instanceof Uint8Array&&"set"===i.prototype.set.name?function(e,t,n){t.set(e,n);}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var r=0;r<e.length;){t[n++]=e[r++];}};function u(e,t,n){e.length<40?a.utf8.write(e,t,n):t.utf8Write(e,n);}o.prototype.bytes=function(e){a.isString(e)&&(e=a._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(s,t,e),this;},o.prototype.string=function(e){var t=i.byteLength(e);return this.uint32(t),t&&this._push(u,t,e),this;};},function(e,t,n){"use strict";e.exports=a;var r=n(65);function a(e,t){this.lo=e>>>0,this.hi=t>>>0;}var i=a.zero=new a(0,0);i.toNumber=function(){return 0;},i.zzEncode=i.zzDecode=function(){return this;},i.length=function(){return 1;};var o=a.zeroHash="\0\0\0\0\0\0\0\0";a.fromNumber=function(e){if(0===e)return i;var t=e<0;t&&(e=-e);var n=e>>>0,r=(e-n)/4294967296>>>0;return t&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new a(n,r);},a.from=function(e){if("number"==typeof e)return a.fromNumber(e);if(r.isString(e)){if(!r.Long)return a.fromNumber(parseInt(e,10));e=r.Long.fromString(e);}return e.low||e.high?new a(e.low>>>0,e.high>>>0):i;},a.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+4294967296*n);}return this.lo+4294967296*this.hi;},a.prototype.toLong=function(e){return r.Long?new r.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)};};var s=String.prototype.charCodeAt;a.fromHash=function(e){return e===o?i:new a((s.call(e,0)|s.call(e,1)<<8|s.call(e,2)<<16|s.call(e,3)<<24)>>>0,(s.call(e,4)|s.call(e,5)<<8|s.call(e,6)<<16|s.call(e,7)<<24)>>>0);},a.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24);},a.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this;},a.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this;},a.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10;};},function(e,t,n){"use strict";e.exports=function(e,t,n){var r=n||8192,a=r>>>1,i=null,o=r;return function(n){if(n<1||n>a)return e(n);o+n>r&&(i=e(r),o=0);var s=t.call(i,o,o+=n);return 7&o&&(o=1+(7|o)),s;};};},function(e,t,n){"use strict";var r=t;r.length=function(e){for(var t=0,n=0,r=0;r<e.length;++r){(n=e.charCodeAt(r))<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(r+1))?(++r,t+=4):t+=3;}return t;},r.read=function(e,t,n){if(n-t<1)return"";for(var r,a=null,i=[],o=0;t<n;){(r=e[t++])<128?i[o++]=r:r>191&&r<224?i[o++]=(31&r)<<6|63&e[t++]:r>239&&r<365?(r=((7&r)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[o++]=55296+(r>>10),i[o++]=56320+(1023&r)):i[o++]=(15&r)<<12|(63&e[t++])<<6|63&e[t++],o>8191&&((a||(a=[])).push(String.fromCharCode.apply(String,i)),o=0);}return a?(o&&a.push(String.fromCharCode.apply(String,i.slice(0,o))),a.join("")):String.fromCharCode.apply(String,i.slice(0,o));},r.write=function(e,t,n){for(var r,a,i=n,o=0;o<e.length;++o){(r=e.charCodeAt(o))<128?t[n++]=r:r<2048?(t[n++]=r>>6|192,t[n++]=63&r|128):55296==(64512&r)&&56320==(64512&(a=e.charCodeAt(o+1)))?(r=65536+((1023&r)<<10)+(1023&a),++o,t[n++]=r>>18|240,t[n++]=r>>12&63|128,t[n++]=r>>6&63|128,t[n++]=63&r|128):(t[n++]=r>>12|224,t[n++]=r>>6&63|128,t[n++]=63&r|128);}return n-i;};},function(module,exports,__webpack_require__){"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod;}catch(e){}return null;}module.exports=inquire;},function(e,t,n){"use strict";function r(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),n=new Uint8Array(t.buffer),r=128===n[3];function a(e,r,a){t[0]=e,r[a]=n[0],r[a+1]=n[1],r[a+2]=n[2],r[a+3]=n[3];}function i(e,r,a){t[0]=e,r[a]=n[3],r[a+1]=n[2],r[a+2]=n[1],r[a+3]=n[0];}function o(e,r){return n[0]=e[r],n[1]=e[r+1],n[2]=e[r+2],n[3]=e[r+3],t[0];}function s(e,r){return n[3]=e[r],n[2]=e[r+1],n[1]=e[r+2],n[0]=e[r+3],t[0];}e.writeFloatLE=r?a:i,e.writeFloatBE=r?i:a,e.readFloatLE=r?o:s,e.readFloatBE=r?s:o;}():function(){function t(e,t,n,r){var a=t<0?1:0;if(a&&(t=-t),0===t)e(1/t>0?0:2147483648,n,r);else if(isNaN(t))e(2143289344,n,r);else if(t>3.4028234663852886e38)e((a<<31|2139095040)>>>0,n,r);else if(t<1.1754943508222875e-38)e((a<<31|Math.round(t/1.401298464324817e-45))>>>0,n,r);else{var i=Math.floor(Math.log(t)/Math.LN2);e((a<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,n,r);}}function n(e,t,n){var r=e(t,n),a=2*(r>>31)+1,i=r>>>23&255,o=8388607&r;return 255===i?o?NaN:a*(1/0):0===i?1.401298464324817e-45*a*o:a*Math.pow(2,i-150)*(o+8388608);}e.writeFloatLE=t.bind(null,a),e.writeFloatBE=t.bind(null,i),e.readFloatLE=n.bind(null,o),e.readFloatBE=n.bind(null,s);}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),n=new Uint8Array(t.buffer),r=128===n[7];function a(e,r,a){t[0]=e,r[a]=n[0],r[a+1]=n[1],r[a+2]=n[2],r[a+3]=n[3],r[a+4]=n[4],r[a+5]=n[5],r[a+6]=n[6],r[a+7]=n[7];}function i(e,r,a){t[0]=e,r[a]=n[7],r[a+1]=n[6],r[a+2]=n[5],r[a+3]=n[4],r[a+4]=n[3],r[a+5]=n[2],r[a+6]=n[1],r[a+7]=n[0];}function o(e,r){return n[0]=e[r],n[1]=e[r+1],n[2]=e[r+2],n[3]=e[r+3],n[4]=e[r+4],n[5]=e[r+5],n[6]=e[r+6],n[7]=e[r+7],t[0];}function s(e,r){return n[7]=e[r],n[6]=e[r+1],n[5]=e[r+2],n[4]=e[r+3],n[3]=e[r+4],n[2]=e[r+5],n[1]=e[r+6],n[0]=e[r+7],t[0];}e.writeDoubleLE=r?a:i,e.writeDoubleBE=r?i:a,e.readDoubleLE=r?o:s,e.readDoubleBE=r?s:o;}():function(){function t(e,t,n,r,a,i){var o=r<0?1:0;if(o&&(r=-r),0===r)e(0,a,i+t),e(1/r>0?0:2147483648,a,i+n);else if(isNaN(r))e(0,a,i+t),e(2146959360,a,i+n);else if(r>1.7976931348623157e308)e(0,a,i+t),e((o<<31|2146435072)>>>0,a,i+n);else{var s;if(r<2.2250738585072014e-308)e((s=r/5e-324)>>>0,a,i+t),e((o<<31|s/4294967296)>>>0,a,i+n);else{var u=Math.floor(Math.log(r)/Math.LN2);1024===u&&(u=1023),e(4503599627370496*(s=r*Math.pow(2,-u))>>>0,a,i+t),e((o<<31|u+1023<<20|1048576*s&1048575)>>>0,a,i+n);}}}function n(e,t,n,r,a){var i=e(r,a+t),o=e(r,a+n),s=2*(o>>31)+1,u=o>>>20&2047,c=4294967296*(1048575&o)+i;return 2047===u?c?NaN:s*(1/0):0===u?5e-324*s*c:s*Math.pow(2,u-1075)*(c+4503599627370496);}e.writeDoubleLE=t.bind(null,a,0,4),e.writeDoubleBE=t.bind(null,i,4,0),e.readDoubleLE=n.bind(null,o,0,4),e.readDoubleBE=n.bind(null,s,4,0);}(),e;}function a(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24;}function i(e,t,n){t[n]=e>>>24,t[n+1]=e>>>16&255,t[n+2]=e>>>8&255,t[n+3]=255&e;}function o(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0;}function s(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0;}e.exports=r(r);},function(e,t,n){"use strict";function r(){this._listeners={};}e.exports=r,r.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this;},r.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var n=this._listeners[e],r=0;r<n.length;){n[r].fn===t?n.splice(r,1):++r;}return this;},r.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],r=1;r<arguments.length;){n.push(arguments[r++]);}for(r=0;r<t.length;){t[r].fn.apply(t[r++].ctx,n);}}return this;};},function(e,t,n){"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&"="===e.charAt(t);){++n;}return Math.ceil(3*e.length)/4-n;};for(var a=new Array(64),i=new Array(123),o=0;o<64;){i[a[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;}r.encode=function(e,t,n){for(var r,i=null,o=[],s=0,u=0;t<n;){var c=e[t++];switch(u){case 0:o[s++]=a[c>>2],r=(3&c)<<4,u=1;break;case 1:o[s++]=a[r|c>>4],r=(15&c)<<2,u=2;break;case 2:o[s++]=a[r|c>>6],o[s++]=a[63&c],u=0;}s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0);}return u&&(o[s++]=a[r],o[s++]=61,1===u&&(o[s++]=61)),i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s));},r.decode=function(e,t,n){for(var r,a=n,o=0,s=0;s<e.length;){var u=e.charCodeAt(s++);if(61===u&&o>1)break;if(void 0===(u=i[u]))throw Error("invalid encoding");switch(o){case 0:r=u,o=1;break;case 1:t[n++]=r<<2|(48&u)>>4,r=u,o=2;break;case 2:t[n++]=(15&r)<<4|(60&u)>>2,r=u,o=3;break;case 3:t[n++]=(3&r)<<6|u,o=0;}}if(1===o)throw Error("invalid encoding");return n-a;},r.test=function(e){return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e);};},function(e,t,n){"use strict";e.exports=function(e,t){for(var n=new Array(arguments.length-1),r=0,a=2,i=!0;a<arguments.length;){n[r++]=arguments[a++];}return new Promise(function(a,o){n[r]=function(e){if(i)if(i=!1,e)o(e);else{for(var t=new Array(arguments.length-1),n=0;n<t.length;){t[n++]=arguments[n];}a.apply(null,t);}};try{e.apply(t||null,n);}catch(e){i&&(i=!1,o(e));}});};},function(e,t,n){"use strict";var r=t;function a(){r.Reader._configure(r.BufferReader),r.util._configure();}r.build="minimal",r.Writer=n(189),r.BufferWriter=n(322),r.Reader=n(188),r.BufferReader=n(321),r.util=n(65),r.rpc=n(320),r.roots=n(318),r.configure=a,r.Writer._configure(r.BufferWriter),a();},function(e,t,n){"use strict";var r=function r(e){switch(typeof e==="undefined"?"undefined":_typeof(e)){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return"";}};e.exports=function(e,t,n,s){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==(typeof e==="undefined"?"undefined":_typeof(e))?i(o(e),function(o){var s=encodeURIComponent(r(o))+n;return a(e[o])?i(e[o],function(e){return s+encodeURIComponent(r(e));}).join(t):s+encodeURIComponent(r(e[o]));}).join(t):s?encodeURIComponent(r(s))+n+encodeURIComponent(r(e)):"";};var a=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e);};function i(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++){n.push(t(e[r],r));}return n;}var o=Object.keys||function(e){var t=[];for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);}return t;};},function(e,t,n){"use strict";function r(e,t){return Object.prototype.hasOwnProperty.call(e,t);}e.exports=function(e,t,n,i){t=t||"&",n=n||"=";var o={};if("string"!=typeof e||0===e.length)return o;var s=/\+/g;e=e.split(t);var u=1e3;i&&"number"==typeof i.maxKeys&&(u=i.maxKeys);var c=e.length;u>0&&c>u&&(c=u);for(var l=0;l<c;++l){var f,p,h,d,m=e[l].replace(s,"%20"),g=m.indexOf(n);g>=0?(f=m.substr(0,g),p=m.substr(g+1)):(f=m,p=""),h=decodeURIComponent(f),d=decodeURIComponent(p),r(o,h)?a(o[h])?o[h].push(d):o[h]=[o[h],d]:o[h]=d;}return o;};var a=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e);};},function(e,t,n){"use strict";t.decode=t.parse=n(333),t.encode=t.stringify=n(332);},function(e,t,n){"use strict";e.exports={isString:function isString(e){return"string"==typeof e;},isObject:function isObject(e){return"object"==(typeof e==="undefined"?"undefined":_typeof(e))&&null!==e;},isNull:function isNull(e){return null===e;},isNullOrUndefined:function isNullOrUndefined(e){return null==e;}};},function(e,t,n){(function(e,r){var a;/*! https://mths.be/punycode v1.3.2 by @mathias */!function(i){"object"==(typeof t==="undefined"?"undefined":_typeof(t))&&t&&t.nodeType,"object"==(typeof e==="undefined"?"undefined":_typeof(e))&&e&&e.nodeType;var o="object"==(typeof r==="undefined"?"undefined":_typeof(r))&&r;o.global!==o&&o.window!==o&&o.self;var s,u=2147483647,c=36,l=1,f=26,p=38,h=700,d=72,m=128,g="-",y=/^xn--/,v=/[^\x20-\x7E]/,b=/[\x2E\u3002\uFF0E\uFF61]/g,w={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},x=c-l,k=Math.floor,O=String.fromCharCode;function S(e){throw RangeError(w[e]);}function N(e,t){for(var n=e.length,r=[];n--;){r[n]=t(e[n]);}return r;}function E(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+N((e=e.replace(b,".")).split("."),t).join(".");}function I(e){for(var t,n,r=[],a=0,i=e.length;a<i;){(t=e.charCodeAt(a++))>=55296&&t<=56319&&a<i?56320==(64512&(n=e.charCodeAt(a++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),a--):r.push(t);}return r;}function T(e){return N(e,function(e){var t="";return e>65535&&(t+=O((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+O(e);}).join("");}function A(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:c;}function C(e,t){return e+22+75*(e<26)-((0!=t)<<5);}function P(e,t,n){var r=0;for(e=n?k(e/h):e>>1,e+=k(e/t);e>x*f>>1;r+=c){e=k(e/x);}return k(r+(x+1)*e/(e+p));}function _(e){var t,n,r,a,i,o,s,p,h,y,v=[],b=e.length,w=0,x=m,O=d;for((n=e.lastIndexOf(g))<0&&(n=0),r=0;r<n;++r){e.charCodeAt(r)>=128&&S("not-basic"),v.push(e.charCodeAt(r));}for(a=n>0?n+1:0;a<b;){for(i=w,o=1,s=c;a>=b&&S("invalid-input"),((p=A(e.charCodeAt(a++)))>=c||p>k((u-w)/o))&&S("overflow"),w+=p*o,!(p<(h=s<=O?l:s>=O+f?f:s-O));s+=c){o>k(u/(y=c-h))&&S("overflow"),o*=y;}O=P(w-i,t=v.length+1,0==i),k(w/t)>u-x&&S("overflow"),x+=k(w/t),w%=t,v.splice(w++,0,x);}return T(v);}function R(e){var t,n,r,a,i,o,s,p,h,y,v,b,w,x,N,E=[];for(b=(e=I(e)).length,t=m,n=0,i=d,o=0;o<b;++o){(v=e[o])<128&&E.push(O(v));}for(r=a=E.length,a&&E.push(g);r<b;){for(s=u,o=0;o<b;++o){(v=e[o])>=t&&v<s&&(s=v);}for(s-t>k((u-n)/(w=r+1))&&S("overflow"),n+=(s-t)*w,t=s,o=0;o<b;++o){if((v=e[o])<t&&++n>u&&S("overflow"),v==t){for(p=n,h=c;!(p<(y=h<=i?l:h>=i+f?f:h-i));h+=c){N=p-y,x=c-y,E.push(O(C(y+N%x,0))),p=k(N/x);}E.push(O(C(p,0))),i=P(n,w,r==a),n=0,++r;}}++n,++t;}return E.join("");}s={version:"1.3.2",ucs2:{decode:I,encode:T},decode:_,encode:R,toASCII:function toASCII(e){return E(e,function(e){return v.test(e)?"xn--"+R(e):e;});},toUnicode:function toUnicode(e){return E(e,function(e){return y.test(e)?_(e.slice(4).toLowerCase()):e;});}},void 0===(a=function(){return s;}.call(t,n,t,e))||(e.exports=a);}();}).call(this,n(66)(e),n(101));},function(e,t){},function(e,t,n){var r;!function(a,i){var o,s=this,u=256,c=6,l="random",f=i.pow(u,c),p=i.pow(2,52),h=2*p,d=u-1;function m(e,t,n){var r=[],m=y(function e(t,n){var r,a=[],i=typeof t==="undefined"?"undefined":_typeof(t);if(n&&"object"==i)for(r in t){try{a.push(e(t[r],n-1));}catch(e){}}return a.length?a:"string"==i?t:t+"\0";}((t=1==t?{entropy:!0}:t||{}).entropy?[e,v(a)]:null==e?function(){try{var e;return o&&(e=o.randomBytes)?e=e(u):(e=new Uint8Array(u),(s.crypto||s.msCrypto).getRandomValues(e)),v(e);}catch(e){var t=s.navigator,n=t&&t.plugins;return[+new Date(),s,n,s.screen,v(a)];}}():e,3),r),b=new function(e){var t,n=e.length,r=this,a=0,i=r.i=r.j=0,o=r.S=[];for(n||(e=[n++]);a<u;){o[a]=a++;}for(a=0;a<u;a++){o[a]=o[i=d&i+e[a%n]+(t=o[a])],o[i]=t;}(r.g=function(e){for(var t,n=0,a=r.i,i=r.j,o=r.S;e--;){t=o[a=d&a+1],n=n*u+o[d&(o[a]=o[i=d&i+t])+(o[i]=t)];}return r.i=a,r.j=i,n;})(u);}(r),w=function w(){for(var e=b.g(c),t=f,n=0;e<p;){e=(e+n)*u,t*=u,n=b.g(1);}for(;e>=h;){e/=2,t/=2,n>>>=1;}return(e+n)/t;};return w.int32=function(){return 0|b.g(4);},w.quick=function(){return b.g(4)/4294967296;},w.double=w,y(v(b.S),a),(t.pass||n||function(e,t,n,r){return r&&(r.S&&g(r,b),e.state=function(){return g(b,{});}),n?(i[l]=e,t):e;})(w,m,"global"in t?t.global:this==i,t.state);}function g(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t;}function y(e,t){for(var n,r=e+"",a=0;a<r.length;){t[d&a]=d&(n^=19*t[d&a])+r.charCodeAt(a++);}return v(t);}function v(e){return String.fromCharCode.apply(0,e);}if(i["seed"+l]=m,y(i.random(),a),"object"==(typeof e==="undefined"?"undefined":_typeof(e))&&e.exports){e.exports=m;try{o=n(337);}catch(e){}}else void 0===(r=function(){return m;}.call(t,n,t,e))||(e.exports=r);}([],Math);},function(e,t,n){(function(e){var r;!function(e,a,i){function o(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t;}function s(e,t){var n=new function(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-e|0;},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r<n.length+20;r++){t.b^=0|n.charCodeAt(r),t.next();}}(e),r=t&&t.state,a=function a(){return(n.next()>>>0)/4294967296;};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===e);return e;},a.int32=n.next,a.quick=a,r&&("object"==(typeof r==="undefined"?"undefined":_typeof(r))&&o(r,n),a.state=function(){return o(n,{});}),a;}a&&a.exports?a.exports=s:n(33)&&n(82)?void 0===(r=function(){return s;}.call(t,n,t,a))||(a.exports=r):this.tychei=s;}(0,"object"==(typeof e==="undefined"?"undefined":_typeof(e))&&e,n(33));}).call(this,n(66)(e));},function(e,t,n){(function(e){var r;!function(e,a,i){function o(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t;}function s(e,t){null==e&&(e=+new Date());var n=new function(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,i=t.i;return t.w=r=r+1640531527|0,n=a[i+34&127],e=a[i=i+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[i]=n^e,t.i=i,n+(r^r>>>16)|0;},function(e,t){var n,r,a,i,o,s=[],u=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,u=Math.max(u,t.length)),a=0,i=-32;i<u;++i){t&&(r^=t.charCodeAt((i+32)%t.length)),0===i&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,i>=0&&(o=o+1640531527|0,a=0==(n=s[127&i]^=r+o)?a+1:0);}for(a>=128&&(s[127&(t&&t.length||0)]=-1),a=127,i=512;i>0;--i){r=s[a+34&127],n=s[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[a]=r^n;}e.w=o,e.X=s,e.i=a;}(t,e);}(e),r=t&&t.state,a=function a(){return(n.next()>>>0)/4294967296;};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===e);return e;},a.int32=n.next,a.quick=a,r&&(r.X&&o(r,n),a.state=function(){return o(n,{});}),a;}a&&a.exports?a.exports=s:n(33)&&n(82)?void 0===(r=function(){return s;}.call(t,n,t,a))||(a.exports=r):this.xor4096=s;}(0,"object"==(typeof e==="undefined"?"undefined":_typeof(e))&&e,n(33));}).call(this,n(66)(e));},function(e,t,n){(function(e){var r;!function(e,a,i){function o(e,t){return t.x=e.x.slice(),t.i=e.i,t;}function s(e,t){null==e&&(e=+new Date());var n=new function(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n;},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n<t.length;++n){r[7&n]=r[7&n]<<15^t.charCodeAt(n)+r[n+1&7]<<13;}for(;r.length<8;){r.push(0);}for(n=0;n<8&&0===r[n];++n){}for(8==n?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n){e.next();}}(t,e);}(e),r=t&&t.state,a=function a(){return(n.next()>>>0)/4294967296;};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===e);return e;},a.int32=n.next,a.quick=a,r&&(r.x&&o(r,n),a.state=function(){return o(n,{});}),a;}a&&a.exports?a.exports=s:n(33)&&n(82)?void 0===(r=function(){return s;}.call(t,n,t,a))||(a.exports=r):this.xorshift7=s;}(0,"object"==(typeof e==="undefined"?"undefined":_typeof(e))&&e,n(33));}).call(this,n(66)(e));},function(e,t,n){(function(e){var r;!function(e,a,i){function o(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t;}function s(e,t){var n=new function(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0;},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++){t.x^=0|n.charCodeAt(r),r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next();}}(e),r=t&&t.state,a=function a(){return(n.next()>>>0)/4294967296;};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===e);return e;},a.int32=n.next,a.quick=a,r&&("object"==(typeof r==="undefined"?"undefined":_typeof(r))&&o(r,n),a.state=function(){return o(n,{});}),a;}a&&a.exports?a.exports=s:n(33)&&n(82)?void 0===(r=function(){return s;}.call(t,n,t,a))||(a.exports=r):this.xorwow=s;}(0,"object"==(typeof e==="undefined"?"undefined":_typeof(e))&&e,n(33));}).call(this,n(66)(e));},function(e,t,n){(function(e){var r;!function(e,a,i){function o(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t;}function s(e,t){var n=new function(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8;},e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++){t.x^=0|n.charCodeAt(r),t.next();}}(e),r=t&&t.state,a=function a(){return(n.next()>>>0)/4294967296;};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===e);return e;},a.int32=n.next,a.quick=a,r&&("object"==(typeof r==="undefined"?"undefined":_typeof(r))&&o(r,n),a.state=function(){return o(n,{});}),a;}a&&a.exports?a.exports=s:n(33)&&n(82)?void 0===(r=function(){return s;}.call(t,n,t,a))||(a.exports=r):this.xor128=s;}(0,"object"==(typeof e==="undefined"?"undefined":_typeof(e))&&e,n(33));}).call(this,n(66)(e));},function(e,t,n){(function(e){var r;!function(e,a,i){function o(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t;}function s(e,t){var n=new function(e){var t=this,n=function(){var e=4022871197;return function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e);}return 2.3283064365386963e-10*(e>>>0);};}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e);},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null;}(e),r=t&&t.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0;},a.double=function(){return a()+1.1102230246251565e-16*(2097152*a()|0);},a.quick=a,r&&("object"==(typeof r==="undefined"?"undefined":_typeof(r))&&o(r,n),a.state=function(){return o(n,{});}),a;}a&&a.exports?a.exports=s:n(33)&&n(82)?void 0===(r=function(){return s;}.call(t,n,t,a))||(a.exports=r):this.alea=s;}(0,"object"==(typeof e==="undefined"?"undefined":_typeof(e))&&e,n(33));}).call(this,n(66)(e));},function(e,t,n){var r=n(140),a=Math.max,i=Math.min;e.exports=function(e,t){return(e=r(e))<0?a(e+t,0):i(e,t);};},function(e,t,n){var r=n(67),a=n(141),i=n(345);e.exports=function(e){return function(t,n,o){var s,u=r(t),c=a(u.length),l=i(o,c);if(e&&n!=n){for(;c>l;){if((s=u[l++])!=s)return!0;}}else for(;c>l;l++){if((e||l in u)&&u[l]===n)return e||l||0;}return!e&&-1;};};},function(e,t,n){"use strict";var r=n(83),a=n(136),i=n(94),o=n(93),s=n(190),u=Object.assign;e.exports=!u||n(84)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e;}),7!=u({},e)[n]||Object.keys(u({},t)).join("")!=r;})?function(e,t){for(var n=o(e),u=arguments.length,c=1,l=a.f,f=i.f;u>c;){for(var p,h=s(arguments[c++]),d=l?r(h).concat(l(h)):r(h),m=d.length,g=0;m>g;){f.call(h,p=d[g++])&&(n[p]=h[p]);}}return n;}:u;},function(e,t,n){var r=n(34);r(r.S+r.F,"Object",{assign:n(347)});},function(e,t,n){n(348),e.exports=n(21).Object.assign;},function(e,t,n){e.exports={default:n(349),__esModule:!0};},function(e,t,n){"use strict";t.__esModule=!0;var r=function(e){return e&&e.__esModule?e:{default:e};}(n(350));t.default=r.default||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n){Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r]);}}return e;};},function(e,t,n){"use strict";var r=g(n(351)),a=m(n(10)),i=g(n(317)),o=g(n(294)),s=g(n(282)),u=g(n(273)),c=g(n(266)),l=g(n(254)),f=m(n(91)),p=g(n(251)),h=g(n(250)),d=g(n(244));function m(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);}return t.default=e,t;}function g(e){return e&&e.__esModule?e:{default:e};}e.exports=(0,r.default)({imageClassifier:o.default,featureExtractor:s.default,pitchDetection:i.default,YOLO:c.default,word2vec:u.default,styleTransfer:p.default,poseNet:l.default,LSTMGenerator:h.default,pix2pix:d.default},f,{tf:a});},function(e,t){e.exports=function(e,t){var n=t===Object(t)?function(e){return t[e];}:t;return function(t){return String(t).replace(e,n);};};},function(e,t,n){var r=n(5),a=n(353)(/[\\^$*+?.()|[\]{}]/g,"\\$&");r(r.S,"RegExp",{escape:function escape(e){return a(e);}});},function(e,t,n){n(354),e.exports=n(43).RegExp.escape;},function(e,t,n){(function(t){!function(t){"use strict";var n,r=Object.prototype,a=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",s=i.asyncIterator||"@@asyncIterator",u=i.toStringTag||"@@toStringTag",c="object"==(typeof e==="undefined"?"undefined":_typeof(e)),l=t.regeneratorRuntime;if(l)c&&(e.exports=l);else{(l=t.regeneratorRuntime=c?e.exports:{}).wrap=w;var f="suspendedStart",p="suspendedYield",h="executing",d="completed",m={},g={};g[o]=function(){return this;};var y=Object.getPrototypeOf,v=y&&y(y(P([])));v&&v!==r&&a.call(v,o)&&(g=v);var b=S.prototype=k.prototype=Object.create(g);O.prototype=b.constructor=S,S.constructor=O,S[u]=O.displayName="GeneratorFunction",l.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===O||"GeneratorFunction"===(t.displayName||t.name));},l.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,S):(e.__proto__=S,u in e||(e[u]="GeneratorFunction")),e.prototype=Object.create(b),e;},l.awrap=function(e){return{__await:e};},N(E.prototype),E.prototype[s]=function(){return this;},l.AsyncIterator=E,l.async=function(e,t,n,r){var a=new E(w(e,t,n,r));return l.isGeneratorFunction(t)?a:a.next().then(function(e){return e.done?e.value:a.next();});},N(b),b[u]="Generator",b[o]=function(){return this;},b.toString=function(){return"[object Generator]";},l.keys=function(e){var t=[];for(var n in e){t.push(n);}return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n;}return n.done=!0,n;};},l.values=P,C.prototype={constructor:C,reset:function reset(e){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(A),!e)for(var t in this){"t"===t.charAt(0)&&a.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=n);}},stop:function stop(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval;},dispatchException:function dispatchException(e){if(this.done)throw e;var t=this;function r(r,a){return s.type="throw",s.arg=e,t.next=r,a&&(t.method="next",t.arg=n),!!a;}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],s=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var u=a.call(o,"catchLoc"),c=a.call(o,"finallyLoc");if(u&&c){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc);}else if(u){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc);}}}},abrupt:function abrupt(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&a.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break;}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=e,o.arg=t,i?(this.method="next",this.next=i.finallyLoc,m):this.complete(o);},complete:function complete(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),m;},finish:function finish(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),A(n),m;}},catch:function _catch(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var a=r.arg;A(n);}return a;}}throw new Error("illegal catch attempt");},delegateYield:function delegateYield(e,t,r){return this.delegate={iterator:P(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=n),m;}};}function w(e,t,n,r){var a=t&&t.prototype instanceof k?t:k,i=Object.create(a.prototype),o=new C(r||[]);return i._invoke=function(e,t,n){var r=f;return function(a,i){if(r===h)throw new Error("Generator is already running");if(r===d){if("throw"===a)throw i;return _();}for(n.method=a,n.arg=i;;){var o=n.delegate;if(o){var s=I(o,n);if(s){if(s===m)continue;return s;}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===f)throw r=d,n.arg;n.dispatchException(n.arg);}else"return"===n.method&&n.abrupt("return",n.arg);r=h;var u=x(e,t,n);if("normal"===u.type){if(r=n.done?d:p,u.arg===m)continue;return{value:u.arg,done:n.done};}"throw"===u.type&&(r=d,n.method="throw",n.arg=u.arg);}};}(e,n,o),i;}function x(e,t,n){try{return{type:"normal",arg:e.call(t,n)};}catch(e){return{type:"throw",arg:e};}}function k(){}function O(){}function S(){}function N(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e);};});}function E(e){function n(t,r,i,o){var s=x(e[t],e,r);if("throw"!==s.type){var u=s.arg,c=u.value;return c&&"object"==(typeof c==="undefined"?"undefined":_typeof(c))&&a.call(c,"__await")?Promise.resolve(c.__await).then(function(e){n("next",e,i,o);},function(e){n("throw",e,i,o);}):Promise.resolve(c).then(function(e){u.value=e,i(u);},o);}o(s.arg);}var r;"object"==_typeof(t.process)&&t.process.domain&&(n=t.process.domain.bind(n)),this._invoke=function(e,t){function a(){return new Promise(function(r,a){n(e,t,r,a);});}return r=r?r.then(a,a):a();};}function I(e,t){var r=e.iterator[t.method];if(r===n){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=n,I(e,t),"throw"===t.method))return m;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method");}return m;}var a=x(r,e.iterator,t.arg);if("throw"===a.type)return t.method="throw",t.arg=a.arg,t.delegate=null,m;var i=a.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=n),t.delegate=null,m):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,m);}function T(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t);}function A(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t;}function C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(T,this),this.reset(!0);}function P(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,i=function t(){for(;++r<e.length;){if(a.call(e,r))return t.value=e[r],t.done=!1,t;}return t.value=n,t.done=!0,t;};return i.next=i;}}return{next:_};}function _(){return{value:n,done:!0};}}("object"==(typeof t==="undefined"?"undefined":_typeof(t))?t:"object"==(typeof window==="undefined"?"undefined":_typeof(window))?window:"object"==(typeof self==="undefined"?"undefined":_typeof(self))?self:this);}).call(this,n(101));},function(e,t,n){for(var r=n(149),a=n(77),i=n(27),o=n(13),s=n(28),u=n(87),c=n(16),l=c("iterator"),f=c("toStringTag"),p=u.Array,h={CSSRuleList:!0,CSSStyleDeclaration:!1,CSSValueList:!1,ClientRectList:!1,DOMRectList:!1,DOMStringList:!1,DOMTokenList:!0,DataTransferItemList:!1,FileList:!1,HTMLAllCollection:!1,HTMLCollection:!1,HTMLFormElement:!1,HTMLSelectElement:!1,MediaList:!0,MimeTypeArray:!1,NamedNodeMap:!1,NodeList:!0,PaintRequestList:!1,Plugin:!1,PluginArray:!1,SVGLengthList:!1,SVGNumberList:!1,SVGPathSegList:!1,SVGPointList:!1,SVGStringList:!1,SVGTransformList:!1,SourceBufferList:!1,StyleSheetList:!0,TextTrackCueList:!1,TextTrackList:!1,TouchList:!1},d=a(h),m=0;m<d.length;m++){var g,y=d[m],v=h[y],b=o[y],w=b&&b.prototype;if(w&&(w[l]||s(w,l,p),w[f]||s(w,f,y),u[y]=p,v))for(g in r){w[g]||i(w,g,r[g],!0);}}},function(e,t,n){var r=n(5),a=n(148);r(r.G+r.B,{setImmediate:a.set,clearImmediate:a.clear});},function(e,t,n){var r=n(13),a=n(5),i=n(112),o=[].slice,s=/MSIE .\./.test(i),u=function u(e){return function(t,n){var r=arguments.length>2,a=!!r&&o.call(arguments,2);return e(r?function(){("function"==typeof t?t:Function(t)).apply(this,a);}:t,n);};};a(a.G+a.B+a.F*s,{setTimeout:u(r.setTimeout),setInterval:u(r.setInterval)});},function(e,t,n){"use strict";var r=n(5),a=n(13),i=n(43),o=n(147)(),s=n(16)("observable"),u=n(23),c=n(12),l=n(72),f=n(70),p=n(28),h=n(71),d=h.RETURN,m=function m(e){return null==e?void 0:u(e);},g=function g(e){var t=e._c;t&&(e._c=void 0,t());},y=function y(e){return void 0===e._o;},v=function v(e){y(e)||(e._o=void 0,g(e));},b=function b(e,t){c(e),this._c=void 0,this._o=e,e=new w(this);try{var n=t(e),r=n;null!=n&&("function"==typeof n.unsubscribe?n=function n(){r.unsubscribe();}:u(n),this._c=n);}catch(t){return void e.error(t);}y(this)&&g(this);};b.prototype=f({},{unsubscribe:function unsubscribe(){v(this);}});var w=function w(e){this._s=e;};w.prototype=f({},{next:function next(e){var t=this._s;if(!y(t)){var n=t._o;try{var r=m(n.next);if(r)return r.call(n,e);}catch(e){try{v(t);}finally{throw e;}}}},error:function error(e){var t=this._s;if(y(t))throw e;var n=t._o;t._o=void 0;try{var r=m(n.error);if(!r)throw e;e=r.call(n,e);}catch(e){try{g(t);}finally{throw e;}}return g(t),e;},complete:function complete(e){var t=this._s;if(!y(t)){var n=t._o;t._o=void 0;try{var r=m(n.complete);e=r?r.call(n,e):void 0;}catch(e){try{g(t);}finally{throw e;}}return g(t),e;}}});var x=function x(e){l(this,x,"Observable","_f")._f=u(e);};f(x.prototype,{subscribe:function subscribe(e){return new b(e,this._f);},forEach:function forEach(e){var t=this;return new(i.Promise||a.Promise)(function(n,r){u(e);var a=t.subscribe({next:function next(t){try{return e(t);}catch(e){r(e),a.unsubscribe();}},error:r,complete:n});});}}),f(x,{from:function from(e){var t="function"==typeof this?this:x,n=m(c(e)[s]);if(n){var r=c(n.call(e));return r.constructor===t?r:new t(function(e){return r.subscribe(e);});}return new t(function(t){var n=!1;return o(function(){if(!n){try{if(h(e,!1,function(e){if(t.next(e),n)return d;})===d)return;}catch(e){if(n)throw e;return void t.error(e);}t.complete();}}),function(){n=!0;};});},of:function of(){for(var e=0,t=arguments.length,n=new Array(t);e<t;){n[e]=arguments[e++];}return new("function"==typeof this?this:x)(function(e){var t=!1;return o(function(){if(!t){for(var r=0;r<n.length;++r){if(e.next(n[r]),t)return;}e.complete();}}),function(){t=!0;};});}}),p(x.prototype,s,function(){return this;}),r(r.G,{Observable:x}),n(73)("Observable");},function(e,t,n){var r=n(5),a=n(147)(),i=n(13).process,o="process"==n(41)(i);r(r.G,{asap:function asap(e){var t=o&&i.domain;a(t?t.bind(e):e);}});},function(e,t,n){var r=n(53),a=n(12),i=n(23),o=r.key,s=r.set;r.exp({metadata:function metadata(e,t){return function(n,r){s(e,t,(void 0!==r?a:i)(n),o(r));};}});},function(e,t,n){var r=n(53),a=n(12),i=r.has,o=r.key;r.exp({hasOwnMetadata:function hasOwnMetadata(e,t){return i(e,a(t),arguments.length<3?void 0:o(arguments[2]));}});},function(e,t,n){var r=n(53),a=n(12),i=n(35),o=r.has,s=r.key,u=function u(e,t,n){if(o(e,t,n))return!0;var r=i(t);return null!==r&&u(e,r,n);};r.exp({hasMetadata:function hasMetadata(e,t){return u(e,a(t),arguments.length<3?void 0:s(arguments[2]));}});},function(e,t,n){var r=n(53),a=n(12),i=r.keys,o=r.key;r.exp({getOwnMetadataKeys:function getOwnMetadataKeys(e){return i(a(e),arguments.length<2?void 0:o(arguments[1]));}});},function(e,t,n){var r=n(53),a=n(12),i=r.get,o=r.key;r.exp({getOwnMetadata:function getOwnMetadata(e,t){return i(e,a(t),arguments.length<3?void 0:o(arguments[2]));}});},function(e,t,n){var r=n(203),a=n(194),i=n(53),o=n(12),s=n(35),u=i.keys,c=i.key,l=function l(e,t){var n=u(e,t),i=s(e);if(null===i)return n;var o=l(i,t);return o.length?n.length?a(new r(n.concat(o))):o:n;};i.exp({getMetadataKeys:function getMetadataKeys(e){return l(o(e),arguments.length<2?void 0:c(arguments[1]));}});},function(e,t,n){var r=n(53),a=n(12),i=n(35),o=r.has,s=r.get,u=r.key,c=function c(e,t,n){if(o(e,t,n))return s(e,t,n);var r=i(t);return null!==r?c(e,r,n):void 0;};r.exp({getMetadata:function getMetadata(e,t){return c(e,a(t),arguments.length<3?void 0:u(arguments[2]));}});},function(e,t,n){var r=n(53),a=n(12),i=r.key,o=r.map,s=r.store;r.exp({deleteMetadata:function deleteMetadata(e,t){var n=arguments.length<3?void 0:i(arguments[2]),r=o(a(t),n,!1);if(void 0===r||!r.delete(e))return!1;if(r.size)return!0;var u=s.get(t);return u.delete(n),!!u.size||s.delete(t);}});},function(e,t,n){var r=n(53),a=n(12),i=r.key,o=r.set;r.exp({defineMetadata:function defineMetadata(e,t,n,r){o(e,t,a(n),i(r));}});},function(e,t,n){"use strict";var r=n(5),a=n(146),i=n(207);r(r.S,"Promise",{try:function _try(e){var t=a.f(this),n=i(e);return(n.e?t.reject:t.resolve)(n.v),t.promise;}});},function(e,t,n){"use strict";var r=n(5),a=n(43),i=n(13),o=n(113),s=n(206);r(r.P+r.R,"Promise",{finally:function _finally(e){var t=o(this,a.Promise||i.Promise),n="function"==typeof e;return this.then(n?function(n){return s(t,e()).then(function(){return n;});}:e,n?function(n){return s(t,e()).then(function(){throw n;});}:e);}});},function(e,t,n){var r=n(5);r(r.S,"Math",{signbit:function signbit(e){return(e=+e)!=e?e:0==e?1/e==1/0:e>0;}});},function(e,t,n){var r=n(5);r(r.S,"Math",{umulh:function umulh(e,t){var n=+e,r=+t,a=65535&n,i=65535&r,o=n>>>16,s=r>>>16,u=(o*i>>>0)+(a*i>>>16);return o*s+(u>>>16)+((a*s>>>0)+(65535&u)>>>16);}});},function(e,t,n){var r=n(5);r(r.S,"Math",{scale:n(193)});},function(e,t,n){var r=n(5),a=Math.PI/180;r(r.S,"Math",{radians:function radians(e){return e*a;}});},function(e,t,n){var r=n(5);r(r.S,"Math",{RAD_PER_DEG:180/Math.PI});},function(e,t,n){var r=n(5);r(r.S,"Math",{imulh:function imulh(e,t){var n=+e,r=+t,a=65535&n,i=65535&r,o=n>>16,s=r>>16,u=(o*i>>>0)+(a*i>>>16);return o*s+(u>>16)+((a*s>>>0)+(65535&u)>>16);}});},function(e,t,n){var r=n(5);r(r.S,"Math",{isubh:function isubh(e,t,n,r){var a=e>>>0,i=n>>>0;return(t>>>0)-(r>>>0)-((~a&i|~(a^i)&a-i>>>0)>>>31)|0;}});},function(e,t,n){var r=n(5);r(r.S,"Math",{iaddh:function iaddh(e,t,n,r){var a=e>>>0,i=n>>>0;return(t>>>0)+(r>>>0)+((a&i|(a|i)&~(a+i>>>0))>>>31)|0;}});},function(e,t,n){var r=n(5),a=n(193),i=n(213);r(r.S,"Math",{fscale:function fscale(e,t,n,r,o){return i(a(e,t,n,r,o));}});},function(e,t,n){var r=n(5),a=180/Math.PI;r(r.S,"Math",{degrees:function degrees(e){return e*a;}});},function(e,t,n){var r=n(5);r(r.S,"Math",{DEG_PER_RAD:Math.PI/180});},function(e,t,n){var r=n(5);r(r.S,"Math",{clamp:function clamp(e,t,n){return Math.min(n,Math.max(t,e));}});},function(e,t,n){var r=n(5),a=n(41);r(r.S,"Error",{isError:function isError(e){return"Error"===a(e);}});},function(e,t,n){var r=n(5);r(r.S,"System",{global:n(13)});},function(e,t,n){var r=n(5);r(r.G,{global:n(13)});},function(e,t,n){n(107)("WeakSet");},function(e,t,n){n(107)("WeakMap");},function(e,t,n){n(107)("Set");},function(e,t,n){n(107)("Map");},function(e,t,n){n(108)("WeakSet");},function(e,t,n){n(108)("WeakMap");},function(e,t,n){n(108)("Set");},function(e,t,n){n(108)("Map");},function(e,t,n){var r=n(5);r(r.P+r.R,"Set",{toJSON:n(195)("Set")});},function(e,t,n){var r=n(5);r(r.P+r.R,"Map",{toJSON:n(195)("Map")});},function(e,t,n){"use strict";var r=n(5),a=n(22),i=n(50),o=n(35),s=n(36).f;n(19)&&r(r.P+n(109),"Object",{__lookupSetter__:function __lookupSetter__(e){var t,n=a(this),r=i(e,!0);do{if(t=s(n,r))return t.set;}while(n=o(n));}});},function(e,t,n){"use strict";var r=n(5),a=n(22),i=n(50),o=n(35),s=n(36).f;n(19)&&r(r.P+n(109),"Object",{__lookupGetter__:function __lookupGetter__(e){var t,n=a(this),r=i(e,!0);do{if(t=s(n,r))return t.get;}while(n=o(n));}});},function(e,t,n){"use strict";var r=n(5),a=n(22),i=n(23),o=n(18);n(19)&&r(r.P+n(109),"Object",{__defineSetter__:function __defineSetter__(e,t){o.f(a(this),e,{set:i(t),enumerable:!0,configurable:!0});}});},function(e,t,n){"use strict";var r=n(5),a=n(22),i=n(23),o=n(18);n(19)&&r(r.P+n(109),"Object",{__defineGetter__:function __defineGetter__(e,t){o.f(a(this),e,{get:i(t),enumerable:!0,configurable:!0});}});},function(e,t,n){var r=n(5),a=n(196)(!0);r(r.S,"Object",{entries:function entries(e){return a(e);}});},function(e,t,n){var r=n(5),a=n(196)(!1);r(r.S,"Object",{values:function values(e){return a(e);}});},function(e,t,n){var r=n(5),a=n(199),i=n(37),o=n(36),s=n(153);r(r.S,"Object",{getOwnPropertyDescriptors:function getOwnPropertyDescriptors(e){for(var t,n,r=i(e),u=o.f,c=a(r),l={},f=0;c.length>f;){void 0!==(n=u(r,t=c[f++]))&&s(l,t,n);}return l;}});},function(e,t,n){n(169)("observable");},function(e,t,n){n(169)("asyncIterator");},function(e,t,n){"use strict";var r=n(5),a=n(49),i=n(17),o=n(117),s=n(115),u=RegExp.prototype,c=function c(e,t){this._r=e,this._s=t;};n(157)(c,"RegExp String",function(){var e=this._r.exec(this._s);return{value:e,done:null===e};}),r(r.P,"String",{matchAll:function matchAll(e){if(a(this),!o(e))throw TypeError(e+" is not a regexp!");var t=String(this),n="flags"in u?String(e.flags):s.call(e),r=new RegExp(e.source,~n.indexOf("g")?n:"g"+n);return r.lastIndex=i(e.lastIndex),new c(r,t);}});},function(e,t,n){"use strict";n(88)("trimRight",function(e){return function(){return e(this,2);};},"trimEnd");},function(e,t,n){"use strict";n(88)("trimLeft",function(e){return function(){return e(this,1);};},"trimStart");},function(e,t,n){"use strict";var r=n(5),a=n(197),i=n(112);r(r.P+r.F*/Version\/10\.\d+(\.\d+)? Safari\//.test(i),"String",{padEnd:function padEnd(e){return a(this,e,arguments.length>1?arguments[1]:void 0,!1);}});},function(e,t,n){"use strict";var r=n(5),a=n(197),i=n(112);r(r.P+r.F*/Version\/10\.\d+(\.\d+)? Safari\//.test(i),"String",{padStart:function padStart(e){return a(this,e,arguments.length>1?arguments[1]:void 0,!0);}});},function(e,t,n){"use strict";var r=n(5),a=n(159)(!0);r(r.P,"String",{at:function at(e){return a(this,e);}});},function(e,t,n){"use strict";var r=n(5),a=n(198),i=n(22),o=n(17),s=n(48),u=n(151);r(r.P,"Array",{flatten:function flatten(){var e=arguments[0],t=i(this),n=o(t.length),r=u(t,0);return a(r,t,t,n,0,void 0===e?1:s(e)),r;}}),n(59)("flatten");},function(e,t,n){"use strict";var r=n(5),a=n(198),i=n(22),o=n(17),s=n(23),u=n(151);r(r.P,"Array",{flatMap:function flatMap(e){var t,n,r=i(this);return s(e),t=o(r.length),n=u(r,0),a(n,r,r,t,0,1,e,arguments[1]),n;}}),n(59)("flatMap");},function(e,t,n){"use strict";var r=n(5),a=n(120)(!0);r(r.P,"Array",{includes:function includes(e){return a(this,e,arguments.length>1?arguments[1]:void 0);}}),n(59)("includes");},function(e,t,n){var r=n(5),a=n(165);a&&r(r.S,"Reflect",{setPrototypeOf:function setPrototypeOf(e,t){a.check(e,t);try{return a.set(e,t),!0;}catch(e){return!1;}}});},function(e,t,n){var r=n(18),a=n(36),i=n(35),o=n(38),s=n(5),u=n(79),c=n(12),l=n(15);s(s.S,"Reflect",{set:function e(t,n,s){var f,p,h=arguments.length<4?t:arguments[3],d=a.f(c(t),n);if(!d){if(l(p=i(t)))return e(p,n,s,h);d=u(0);}if(o(d,"value")){if(!1===d.writable||!l(h))return!1;if(f=a.f(h,n)){if(f.get||f.set||!1===f.writable)return!1;f.value=s,r.f(h,n,f);}else r.f(h,n,u(0,s));return!0;}return void 0!==d.set&&(d.set.call(h,s),!0);}});},function(e,t,n){var r=n(5),a=n(12),i=Object.preventExtensions;r(r.S,"Reflect",{preventExtensions:function preventExtensions(e){a(e);try{return i&&i(e),!0;}catch(e){return!1;}}});},function(e,t,n){var r=n(5);r(r.S,"Reflect",{ownKeys:n(199)});},function(e,t,n){var r=n(5),a=n(12),i=Object.isExtensible;r(r.S,"Reflect",{isExtensible:function isExtensible(e){return a(e),!i||i(e);}});},function(e,t,n){var r=n(5);r(r.S,"Reflect",{has:function has(e,t){return t in e;}});},function(e,t,n){var r=n(5),a=n(35),i=n(12);r(r.S,"Reflect",{getPrototypeOf:function getPrototypeOf(e){return a(i(e));}});},function(e,t,n){var r=n(36),a=n(5),i=n(12);a(a.S,"Reflect",{getOwnPropertyDescriptor:function getOwnPropertyDescriptor(e,t){return r.f(i(e),t);}});},function(e,t,n){var r=n(36),a=n(35),i=n(38),o=n(5),s=n(15),u=n(12);o(o.S,"Reflect",{get:function e(t,n){var o,c,l=arguments.length<3?t:arguments[2];return u(t)===l?t[n]:(o=r.f(t,n))?i(o,"value")?o.value:void 0!==o.get?o.get.call(l):void 0:s(c=a(t))?e(c,n,l):void 0;}});},function(e,t,n){"use strict";var r=n(5),a=n(12),i=function i(e){this._t=a(e),this._i=0;var t,n=this._k=[];for(t in e){n.push(t);}};n(157)(i,"Object",function(){var e,t=this._k;do{if(this._i>=t.length)return{value:void 0,done:!0};}while(!((e=t[this._i++])in this._t));return{value:e,done:!1};}),r(r.S,"Reflect",{enumerate:function enumerate(e){return new i(e);}});},function(e,t,n){var r=n(5),a=n(36).f,i=n(12);r(r.S,"Reflect",{deleteProperty:function deleteProperty(e,t){var n=a(i(e),t);return!(n&&!n.configurable)&&delete e[t];}});},function(e,t,n){var r=n(18),a=n(5),i=n(12),o=n(50);a(a.S+a.F*n(14)(function(){Reflect.defineProperty(r.f({},1,{value:1}),1,{value:2});}),"Reflect",{defineProperty:function defineProperty(e,t,n){i(e),t=o(t,!0),i(n);try{return r.f(e,t,n),!0;}catch(e){return!1;}}});},function(e,t,n){var r=n(5),a=n(75),i=n(23),o=n(12),s=n(15),u=n(14),c=n(220),l=(n(13).Reflect||{}).construct,f=u(function(){function e(){}return!(l(function(){},[],e)instanceof e);}),p=!u(function(){l(function(){});});r(r.S+r.F*(f||p),"Reflect",{construct:function construct(e,t){i(e),o(t);var n=arguments.length<3?e:i(arguments[2]);if(p&&!f)return l(e,t,n);if(e==n){switch(t.length){case 0:return new e();case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);}var r=[null];return r.push.apply(r,t),new(c.apply(e,r))();}var u=n.prototype,h=a(s(u)?u:Object.prototype),d=Function.apply.call(e,h,t);return s(d)?d:h;}});},function(e,t,n){var r=n(5),a=n(23),i=n(12),o=(n(13).Reflect||{}).apply,s=Function.apply;r(r.S+r.F*!n(14)(function(){o(function(){});}),"Reflect",{apply:function apply(e,t,n){var r=a(e),u=i(n);return o?o(r,t,u):s.call(r,t,u);}});},function(e,t,n){n(54)("Float64",8,function(e){return function(t,n,r){return e(this,t,n,r);};});},function(e,t,n){n(54)("Float32",4,function(e){return function(t,n,r){return e(this,t,n,r);};});},function(e,t,n){n(54)("Uint32",4,function(e){return function(t,n,r){return e(this,t,n,r);};});},function(e,t,n){n(54)("Int32",4,function(e){return function(t,n,r){return e(this,t,n,r);};});},function(e,t,n){n(54)("Uint16",2,function(e){return function(t,n,r){return e(this,t,n,r);};});},function(e,t,n){n(54)("Int16",2,function(e){return function(t,n,r){return e(this,t,n,r);};});},function(e,t,n){n(54)("Uint8",1,function(e){return function(t,n,r){return e(this,t,n,r);};},!0);},function(e,t,n){n(54)("Uint8",1,function(e){return function(t,n,r){return e(this,t,n,r);};});},function(e,t,n){n(54)("Int8",1,function(e){return function(t,n,r){return e(this,t,n,r);};});},function(e,t,n){var r=n(5);r(r.G+r.W+r.F*!n(110).ABV,{DataView:n(145).DataView});},function(e,t,n){"use strict";var r=n(5),a=n(110),i=n(145),o=n(12),s=n(76),u=n(17),c=n(15),l=n(13).ArrayBuffer,f=n(113),p=i.ArrayBuffer,h=i.DataView,d=a.ABV&&l.isView,m=p.prototype.slice,g=a.VIEW;r(r.G+r.W+r.F*(l!==p),{ArrayBuffer:p}),r(r.S+r.F*!a.CONSTR,"ArrayBuffer",{isView:function isView(e){return d&&d(e)||c(e)&&g in e;}}),r(r.P+r.U+r.F*n(14)(function(){return!new p(2).slice(1,void 0).byteLength;}),"ArrayBuffer",{slice:function slice(e,t){if(void 0!==m&&void 0===t)return m.call(o(this),e);for(var n=o(this).byteLength,r=s(e,n),a=s(void 0===t?n:t,n),i=new(f(this,p))(u(a-r)),c=new h(this),l=new h(i),d=0;r<a;){l.setUint8(d++,c.getUint8(r++));}return i;}}),n(73)("ArrayBuffer");},function(e,t,n){"use strict";var r=n(201),a=n(86);n(111)("WeakSet",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0);};},{add:function add(e){return r.def(a(this,"WeakSet"),e,!0);}},r,!1,!0);},function(e,t,n){"use strict";var r,a,i,o,s=n(60),u=n(13),c=n(42),l=n(98),f=n(5),p=n(15),h=n(23),d=n(72),m=n(71),g=n(113),y=n(148).set,v=n(147)(),b=n(146),w=n(207),x=n(112),k=n(206),O=u.TypeError,S=u.process,N=S&&S.versions,E=N&&N.v8||"",_I2=u.Promise,T="process"==l(S),A=function A(){},C=a=b.f,P=!!function(){try{var e=_I2.resolve(1),t=(e.constructor={})[n(16)("species")]=function(e){e(A,A);};return(T||"function"==typeof PromiseRejectionEvent)&&e.then(A)instanceof t&&0!==E.indexOf("6.6")&&-1===x.indexOf("Chrome/66");}catch(e){}}(),_=function _(e){var t;return!(!p(e)||"function"!=typeof(t=e.then))&&t;},R=function R(e,t){if(!e._n){e._n=!0;var n=e._c;v(function(){for(var r=e._v,a=1==e._s,i=0,o=function o(t){var n,i,o,s=a?t.ok:t.fail,u=t.resolve,c=t.reject,l=t.domain;try{s?(a||(2==e._h&&D(e),e._h=1),!0===s?n=r:(l&&l.enter(),n=s(r),l&&(l.exit(),o=!0)),n===t.promise?c(O("Promise-chain cycle")):(i=_(n))?i.call(n,u,c):u(n)):c(r);}catch(e){l&&!o&&l.exit(),c(e);}};n.length>i;){o(n[i++]);}e._c=[],e._n=!1,t&&!e._h&&M(e);});}},M=function M(e){y.call(u,function(){var t,n,r,a=e._v,i=j(e);if(i&&(t=w(function(){T?S.emit("unhandledRejection",a,e):(n=u.onunhandledrejection)?n({promise:e,reason:a}):(r=u.console)&&r.error&&r.error("Unhandled promise rejection",a);}),e._h=T||j(e)?2:1),e._a=void 0,i&&t.e)throw t.v;});},j=function j(e){return 1!==e._h&&0===(e._a||e._c).length;},D=function D(e){y.call(u,function(){var t;T?S.emit("rejectionHandled",e):(t=u.onrejectionhandled)&&t({promise:e,reason:e._v});});},L=function L(e){var t=this;t._d||(t._d=!0,(t=t._w||t)._v=e,t._s=2,t._a||(t._a=t._c.slice()),R(t,!0));},z=function z(e){var t,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===e)throw O("Promise can't be resolved itself");(t=_(e))?v(function(){var r={_w:n,_d:!1};try{t.call(e,c(z,r,1),c(L,r,1));}catch(e){L.call(r,e);}}):(n._v=e,n._s=1,R(n,!1));}catch(e){L.call({_w:n,_d:!1},e);}}};P||(_I2=function I(e){d(this,_I2,"Promise","_h"),h(e),r.call(this);try{e(c(z,this,1),c(L,this,1));}catch(e){L.call(this,e);}},(r=function r(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1;}).prototype=n(70)(_I2.prototype,{then:function then(e,t){var n=C(g(this,_I2));return n.ok="function"!=typeof e||e,n.fail="function"==typeof t&&t,n.domain=T?S.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&R(this,!1),n.promise;},catch:function _catch(e){return this.then(void 0,e);}}),i=function i(){var e=new r();this.promise=e,this.resolve=c(z,e,1),this.reject=c(L,e,1);},b.f=C=function C(e){return e===_I2||e===o?new i(e):a(e);}),f(f.G+f.W+f.F*!P,{Promise:_I2}),n(89)(_I2,"Promise"),n(73)("Promise"),o=n(43).Promise,f(f.S+f.F*!P,"Promise",{reject:function reject(e){var t=C(this);return(0,t.reject)(e),t.promise;}}),f(f.S+f.F*(s||!P),"Promise",{resolve:function resolve(e){return k(s&&this===o?_I2:this,e);}}),f(f.S+f.F*!(P&&n(116)(function(e){_I2.all(e).catch(A);})),"Promise",{all:function all(e){var t=this,n=C(t),r=n.resolve,a=n.reject,i=w(function(){var n=[],i=0,o=1;m(e,!1,function(e){var s=i++,u=!1;n.push(void 0),o++,t.resolve(e).then(function(e){u||(u=!0,n[s]=e,--o||r(n));},a);}),--o||r(n);});return i.e&&a(i.v),n.promise;},race:function race(e){var t=this,n=C(t),r=n.reject,a=w(function(){m(e,!1,function(e){t.resolve(e).then(n.resolve,r);});});return a.e&&r(a.v),n.promise;}});},function(e,t,n){n(114)("split",2,function(e,t,r){"use strict";var a=n(117),i=r,o=[].push;if("c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length){var s=void 0===/()??/.exec("")[1];r=function r(e,t){var n=String(this);if(void 0===e&&0===t)return[];if(!a(e))return i.call(n,e,t);var r,u,c,l,f,p=[],h=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")+(e.sticky?"y":""),d=0,m=void 0===t?4294967295:t>>>0,g=new RegExp(e.source,h+"g");for(s||(r=new RegExp("^"+g.source+"$(?!\\s)",h));(u=g.exec(n))&&!((c=u.index+u[0].length)>d&&(p.push(n.slice(d,u.index)),!s&&u.length>1&&u[0].replace(r,function(){for(f=1;f<arguments.length-2;f++){void 0===arguments[f]&&(u[f]=void 0);}}),u.length>1&&u.index<n.length&&o.apply(p,u.slice(1)),l=u[0].length,d=c,p.length>=m));){g.lastIndex===u.index&&g.lastIndex++;}return d===n.length?!l&&g.test("")||p.push(""):p.push(n.slice(d)),p.length>m?p.slice(0,m):p;};}else"0".split(void 0,0).length&&(r=function r(e,t){return void 0===e&&0===t?[]:i.call(this,e,t);});return[function(n,a){var i=e(this),o=void 0==n?void 0:n[t];return void 0!==o?o.call(n,i,a):r.call(String(i),n,a);},r];});},function(e,t,n){n(114)("search",1,function(e,t,n){return[function(n){"use strict";var r=e(this),a=void 0==n?void 0:n[t];return void 0!==a?a.call(n,r):new RegExp(n)[t](String(r));},n];});},function(e,t,n){n(114)("replace",2,function(e,t,n){return[function(r,a){"use strict";var i=e(this),o=void 0==r?void 0:r[t];return void 0!==o?o.call(r,i,a):n.call(String(i),r,a);},n];});},function(e,t,n){n(114)("match",1,function(e,t,n){return[function(n){"use strict";var r=e(this),a=void 0==n?void 0:n[t];return void 0!==a?a.call(n,r):new RegExp(n)[t](String(r));},n];});},function(e,t,n){"use strict";n(208);var r=n(12),a=n(115),i=n(19),o=/./.toString,s=function s(e){n(27)(RegExp.prototype,"toString",e,!0);};n(14)(function(){return"/a/b"!=o.call({source:"a",flags:"b"});})?s(function(){var e=r(this);return"/".concat(e.source,"/","flags"in e?e.flags:!i&&e instanceof RegExp?a.call(e):void 0);}):"toString"!=o.name&&s(function(){return o.call(this);});},function(e,t,n){var r=n(13),a=n(163),i=n(18).f,o=n(74).f,s=n(117),u=n(115),_c2=r.RegExp,l=_c2,f=_c2.prototype,p=/a/g,h=/a/g,d=new _c2(p)!==p;if(n(19)&&(!d||n(14)(function(){return h[n(16)("match")]=!1,_c2(p)!=p||_c2(h)==h||"/a/i"!=_c2(p,"i");}))){_c2=function c(e,t){var n=this instanceof _c2,r=s(e),i=void 0===t;return!n&&r&&e.constructor===_c2&&i?e:a(d?new l(r&&!i?e.source:e,t):l((r=e instanceof _c2)?e.source:e,r&&i?u.call(e):t),n?this:f,_c2);};for(var m=function m(e){(e in _c2)||i(_c2,e,{configurable:!0,get:function get(){return l[e];},set:function set(t){l[e]=t;}});},g=o(l),y=0;g.length>y;){m(g[y++]);}f.constructor=_c2,_c2.prototype=f,n(27)(r,"RegExp",_c2);}n(73)("RegExp");},function(e,t,n){n(73)("Array");},function(e,t,n){"use strict";var r=n(5),a=n(46)(6),i="findIndex",o=!0;i in[]&&Array(1)[i](function(){o=!1;}),r(r.P+r.F*o,"Array",{findIndex:function findIndex(e){return a(this,e,arguments.length>1?arguments[1]:void 0);}}),n(59)(i);},function(e,t,n){"use strict";var r=n(5),a=n(46)(5),i=!0;"find"in[]&&Array(1).find(function(){i=!1;}),r(r.P+r.F*i,"Array",{find:function find(e){return a(this,e,arguments.length>1?arguments[1]:void 0);}}),n(59)("find");},function(e,t,n){var r=n(5);r(r.P,"Array",{fill:n(150)}),n(59)("fill");},function(e,t,n){var r=n(5);r(r.P,"Array",{copyWithin:n(210)}),n(59)("copyWithin");},function(e,t,n){"use strict";var r=n(5),a=n(37),i=n(48),o=n(17),s=[].lastIndexOf,u=!!s&&1/[1].lastIndexOf(1,-0)<0;r(r.P+r.F*(u||!n(40)(s)),"Array",{lastIndexOf:function lastIndexOf(e){if(u)return s.apply(this,arguments)||0;var t=a(this),n=o(t.length),r=n-1;for(arguments.length>1&&(r=Math.min(r,i(arguments[1]))),r<0&&(r=n+r);r>=0;r--){if(r in t&&t[r]===e)return r||0;}return-1;}});},function(e,t,n){"use strict";var r=n(5),a=n(120)(!1),i=[].indexOf,o=!!i&&1/[1].indexOf(1,-0)<0;r(r.P+r.F*(o||!n(40)(i)),"Array",{indexOf:function indexOf(e){return o?i.apply(this,arguments)||0:a(this,e,arguments[1]);}});},function(e,t,n){"use strict";var r=n(5),a=n(211);r(r.P+r.F*!n(40)([].reduceRight,!0),"Array",{reduceRight:function reduceRight(e){return a(this,e,arguments.length,arguments[1],!0);}});},function(e,t,n){"use strict";var r=n(5),a=n(211);r(r.P+r.F*!n(40)([].reduce,!0),"Array",{reduce:function reduce(e){return a(this,e,arguments.length,arguments[1],!1);}});},function(e,t,n){"use strict";var r=n(5),a=n(46)(4);r(r.P+r.F*!n(40)([].every,!0),"Array",{every:function every(e){return a(this,e,arguments[1]);}});},function(e,t,n){"use strict";var r=n(5),a=n(46)(3);r(r.P+r.F*!n(40)([].some,!0),"Array",{some:function some(e){return a(this,e,arguments[1]);}});},function(e,t,n){"use strict";var r=n(5),a=n(46)(2);r(r.P+r.F*!n(40)([].filter,!0),"Array",{filter:function filter(e){return a(this,e,arguments[1]);}});},function(e,t,n){"use strict";var r=n(5),a=n(46)(1);r(r.P+r.F*!n(40)([].map,!0),"Array",{map:function map(e){return a(this,e,arguments[1]);}});},function(e,t,n){var r=n(15),a=n(118),i=n(16)("species");e.exports=function(e){var t;return a(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!a(t.prototype)||(t=void 0),r(t)&&null===(t=t[i])&&(t=void 0)),void 0===t?Array:t;};},function(e,t,n){"use strict";var r=n(5),a=n(46)(0),i=n(40)([].forEach,!0);r(r.P+r.F*!i,"Array",{forEach:function forEach(e){return a(this,e,arguments[1]);}});},function(e,t,n){"use strict";var r=n(5),a=n(23),i=n(22),o=n(14),s=[].sort,u=[1,2,3];r(r.P+r.F*(o(function(){u.sort(void 0);})||!o(function(){u.sort(null);})||!n(40)(s)),"Array",{sort:function sort(e){return void 0===e?s.call(i(this)):s.call(i(this),a(e));}});},function(e,t,n){"use strict";var r=n(5),a=n(166),i=n(41),o=n(76),s=n(17),u=[].slice;r(r.P+r.F*n(14)(function(){a&&u.call(a);}),"Array",{slice:function slice(e,t){var n=s(this.length),r=i(this);if(t=void 0===t?n:t,"Array"==r)return u.call(this,e,t);for(var a=o(e,n),c=o(t,n),l=s(c-a),f=new Array(l),p=0;p<l;p++){f[p]="String"==r?this.charAt(a+p):this[a+p];}return f;}});},function(e,t,n){"use strict";var r=n(5),a=n(37),i=[].join;r(r.P+r.F*(n(100)!=Object||!n(40)(i)),"Array",{join:function join(e){return i.call(a(this),void 0===e?",":e);}});},function(e,t,n){"use strict";var r=n(5),a=n(153);r(r.S+r.F*n(14)(function(){function e(){}return!(Array.of.call(e)instanceof e);}),"Array",{of:function of(){for(var e=0,t=arguments.length,n=new("function"==typeof this?this:Array)(t);t>e;){a(n,e,arguments[e++]);}return n.length=t,n;}});},function(e,t,n){"use strict";var r=n(42),a=n(5),i=n(22),o=n(212),s=n(154),u=n(17),c=n(153),l=n(152);a(a.S+a.F*!n(116)(function(e){Array.from(e);}),"Array",{from:function from(e){var t,n,a,f,p=i(e),h="function"==typeof this?this:Array,d=arguments.length,m=d>1?arguments[1]:void 0,g=void 0!==m,y=0,v=l(p);if(g&&(m=r(m,d>2?arguments[2]:void 0,2)),void 0==v||h==Array&&s(v))for(n=new h(t=u(p.length));t>y;y++){c(n,y,g?m(p[y],y):p[y]);}else for(f=v.call(p),n=new h();!(a=f.next()).done;y++){c(n,y,g?o(f,m,[a.value,y],!0):a.value);}return n.length=y,n;}});},function(e,t,n){var r=n(5);r(r.S,"Array",{isArray:n(118)});},function(e,t,n){"use strict";var r=n(12),a=n(50);e.exports=function(e){if("string"!==e&&"number"!==e&&"default"!==e)throw TypeError("Incorrect hint");return a(r(this),"number"!=e);};},function(e,t,n){var r=n(16)("toPrimitive"),a=Date.prototype;r in a||n(28)(a,r,n(470));},function(e,t,n){var r=Date.prototype,a=r.toString,i=r.getTime;new Date(NaN)+""!="Invalid Date"&&n(27)(r,"toString",function(){var e=i.call(this);return e==e?a.call(this):"Invalid Date";});},function(e,t,n){"use strict";var r=n(14),a=Date.prototype.getTime,i=Date.prototype.toISOString,o=function o(e){return e>9?e:"0"+e;};e.exports=r(function(){return"0385-07-25T07:06:39.999Z"!=i.call(new Date(-5e13-1));})||!r(function(){i.call(new Date(NaN));})?function(){if(!isFinite(a.call(this)))throw RangeError("Invalid time value");var e=this,t=e.getUTCFullYear(),n=e.getUTCMilliseconds(),r=t<0?"-":t>9999?"+":"";return r+("00000"+Math.abs(t)).slice(r?-6:-4)+"-"+o(e.getUTCMonth()+1)+"-"+o(e.getUTCDate())+"T"+o(e.getUTCHours())+":"+o(e.getUTCMinutes())+":"+o(e.getUTCSeconds())+"."+(n>99?n:"0"+o(n))+"Z";}:i;},function(e,t,n){var r=n(5),a=n(473);r(r.P+r.F*(Date.prototype.toISOString!==a),"Date",{toISOString:a});},function(e,t,n){"use strict";var r=n(5),a=n(22),i=n(50);r(r.P+r.F*n(14)(function(){return null!==new Date(NaN).toJSON()||1!==Date.prototype.toJSON.call({toISOString:function toISOString(){return 1;}});}),"Date",{toJSON:function toJSON(e){var t=a(this),n=i(t);return"number"!=typeof n||isFinite(n)?t.toISOString():null;}});},function(e,t,n){var r=n(5);r(r.S,"Date",{now:function now(){return new Date().getTime();}});},function(e,t,n){"use strict";n(26)("sup",function(e){return function(){return e(this,"sup","","");};});},function(e,t,n){"use strict";n(26)("sub",function(e){return function(){return e(this,"sub","","");};});},function(e,t,n){"use strict";n(26)("strike",function(e){return function(){return e(this,"strike","","");};});},function(e,t,n){"use strict";n(26)("small",function(e){return function(){return e(this,"small","","");};});},function(e,t,n){"use strict";n(26)("link",function(e){return function(t){return e(this,"a","href",t);};});},function(e,t,n){"use strict";n(26)("italics",function(e){return function(){return e(this,"i","","");};});},function(e,t,n){"use strict";n(26)("fontsize",function(e){return function(t){return e(this,"font","size",t);};});},function(e,t,n){"use strict";n(26)("fontcolor",function(e){return function(t){return e(this,"font","color",t);};});},function(e,t,n){"use strict";n(26)("fixed",function(e){return function(){return e(this,"tt","","");};});},function(e,t,n){"use strict";n(26)("bold",function(e){return function(){return e(this,"b","","");};});},function(e,t,n){"use strict";n(26)("blink",function(e){return function(){return e(this,"blink","","");};});},function(e,t,n){"use strict";n(26)("big",function(e){return function(){return e(this,"big","","");};});},function(e,t,n){"use strict";n(26)("anchor",function(e){return function(t){return e(this,"a","name",t);};});},function(e,t,n){"use strict";var r=n(5),a=n(17),i=n(156),o="".startsWith;r(r.P+r.F*n(155)("startsWith"),"String",{startsWith:function startsWith(e){var t=i(this,e,"startsWith"),n=a(Math.min(arguments.length>1?arguments[1]:void 0,t.length)),r=String(e);return o?o.call(t,r,n):t.slice(n,n+r.length)===r;}});},function(e,t,n){var r=n(5);r(r.P,"String",{repeat:n(162)});},function(e,t,n){"use strict";var r=n(5),a=n(156);r(r.P+r.F*n(155)("includes"),"String",{includes:function includes(e){return!!~a(this,e,"includes").indexOf(e,arguments.length>1?arguments[1]:void 0);}});},function(e,t,n){"use strict";var r=n(5),a=n(17),i=n(156),o="".endsWith;r(r.P+r.F*n(155)("endsWith"),"String",{endsWith:function endsWith(e){var t=i(this,e,"endsWith"),n=arguments.length>1?arguments[1]:void 0,r=a(t.length),s=void 0===n?r:Math.min(a(n),r),u=String(e);return o?o.call(t,u,s):t.slice(s-u.length,s)===u;}});},function(e,t,n){"use strict";var r=n(5),a=n(159)(!1);r(r.P,"String",{codePointAt:function codePointAt(e){return a(this,e);}});},function(e,t,n){"use strict";var r=n(159)(!0);n(158)(String,"String",function(e){this._t=String(e),this._i=0;},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1});});},function(e,t,n){"use strict";n(88)("trim",function(e){return function(){return e(this,3);};});},function(e,t,n){var r=n(5),a=n(37),i=n(17);r(r.S,"String",{raw:function raw(e){for(var t=a(e.raw),n=i(t.length),r=arguments.length,o=[],s=0;n>s;){o.push(String(t[s++])),s<r&&o.push(String(arguments[s]));}return o.join("");}});},function(e,t,n){var r=n(5),a=n(76),i=String.fromCharCode,o=String.fromCodePoint;r(r.S+r.F*(!!o&&1!=o.length),"String",{fromCodePoint:function fromCodePoint(e){for(var t,n=[],r=arguments.length,o=0;r>o;){if(t=+arguments[o++],a(t,1114111)!==t)throw RangeError(t+" is not a valid code point");n.push(t<65536?i(t):i(55296+((t-=65536)>>10),t%1024+56320));}return n.join("");}});},function(e,t,n){var r=n(5);r(r.S,"Math",{trunc:function trunc(e){return(e>0?Math.floor:Math.ceil)(e);}});},function(e,t,n){var r=n(5),a=n(160),i=Math.exp;r(r.S,"Math",{tanh:function tanh(e){var t=a(e=+e),n=a(-e);return t==1/0?1:n==1/0?-1:(t-n)/(i(e)+i(-e));}});},function(e,t,n){var r=n(5),a=n(160),i=Math.exp;r(r.S+r.F*n(14)(function(){return-2e-17!=!Math.sinh(-2e-17);}),"Math",{sinh:function sinh(e){return Math.abs(e=+e)<1?(a(e)-a(-e))/2:(i(e-1)-i(-e-1))*(Math.E/2);}});},function(e,t,n){var r=n(5);r(r.S,"Math",{sign:n(161)});},function(e,t,n){var r=n(5);r(r.S,"Math",{log2:function log2(e){return Math.log(e)/Math.LN2;}});},function(e,t,n){var r=n(5);r(r.S,"Math",{log1p:n(214)});},function(e,t,n){var r=n(5);r(r.S,"Math",{log10:function log10(e){return Math.log(e)*Math.LOG10E;}});},function(e,t,n){var r=n(5),a=Math.imul;r(r.S+r.F*n(14)(function(){return-5!=a(4294967295,5)||2!=a.length;}),"Math",{imul:function imul(e,t){var n=+e,r=+t,a=65535&n,i=65535&r;return 0|a*i+((65535&n>>>16)*i+a*(65535&r>>>16)<<16>>>0);}});},function(e,t,n){var r=n(5),a=Math.abs;r(r.S,"Math",{hypot:function hypot(e,t){for(var n,r,i=0,o=0,s=arguments.length,u=0;o<s;){u<(n=a(arguments[o++]))?(i=i*(r=u/n)*r+1,u=n):i+=n>0?(r=n/u)*r:n;}return u===1/0?1/0:u*Math.sqrt(i);}});},function(e,t,n){var r=n(5);r(r.S,"Math",{fround:n(213)});},function(e,t,n){var r=n(5),a=n(160);r(r.S+r.F*(a!=Math.expm1),"Math",{expm1:a});},function(e,t,n){var r=n(5),a=Math.exp;r(r.S,"Math",{cosh:function cosh(e){return(a(e=+e)+a(-e))/2;}});},function(e,t,n){var r=n(5);r(r.S,"Math",{clz32:function clz32(e){return(e>>>=0)?31-Math.floor(Math.log(e+.5)*Math.LOG2E):32;}});},function(e,t,n){var r=n(5),a=n(161);r(r.S,"Math",{cbrt:function cbrt(e){return a(e=+e)*Math.pow(Math.abs(e),1/3);}});},function(e,t,n){var r=n(5),a=Math.atanh;r(r.S+r.F*!(a&&1/a(-0)<0),"Math",{atanh:function atanh(e){return 0==(e=+e)?e:Math.log((1+e)/(1-e))/2;}});},function(e,t,n){var r=n(5),a=Math.asinh;r(r.S+r.F*!(a&&1/a(0)>0),"Math",{asinh:function e(t){return isFinite(t=+t)&&0!=t?t<0?-e(-t):Math.log(t+Math.sqrt(t*t+1)):t;}});},function(e,t,n){var r=n(5),a=n(214),i=Math.sqrt,o=Math.acosh;r(r.S+r.F*!(o&&710==Math.floor(o(Number.MAX_VALUE))&&o(1/0)==1/0),"Math",{acosh:function acosh(e){return(e=+e)<1?NaN:e>94906265.62425156?Math.log(e)+Math.LN2:a(e-1+i(e-1)*i(e+1));}});},function(e,t,n){var r=n(5),a=n(218);r(r.S+r.F*(Number.parseInt!=a),"Number",{parseInt:a});},function(e,t,n){var r=n(5),a=n(217);r(r.S+r.F*(Number.parseFloat!=a),"Number",{parseFloat:a});},function(e,t,n){var r=n(5);r(r.S,"Number",{MIN_SAFE_INTEGER:-9007199254740991});},function(e,t,n){var r=n(5);r(r.S,"Number",{MAX_SAFE_INTEGER:9007199254740991});},function(e,t,n){var r=n(5),a=n(215),i=Math.abs;r(r.S,"Number",{isSafeInteger:function isSafeInteger(e){return a(e)&&i(e)<=9007199254740991;}});},function(e,t,n){var r=n(5);r(r.S,"Number",{isNaN:function isNaN(e){return e!=e;}});},function(e,t,n){var r=n(5);r(r.S,"Number",{isInteger:n(215)});},function(e,t,n){var r=n(5),a=n(13).isFinite;r(r.S,"Number",{isFinite:function isFinite(e){return"number"==typeof e&&a(e);}});},function(e,t,n){var r=n(5);r(r.S,"Number",{EPSILON:Math.pow(2,-52)});},function(e,t,n){"use strict";var r=n(5),a=n(14),i=n(216),o=1..toPrecision;r(r.P+r.F*(a(function(){return"1"!==o.call(1,void 0);})||!a(function(){o.call({});})),"Number",{toPrecision:function toPrecision(e){var t=i(this,"Number#toPrecision: incorrect invocation!");return void 0===e?o.call(t):o.call(t,e);}});},function(e,t,n){"use strict";var r=n(5),a=n(48),i=n(216),o=n(162),s=1..toFixed,u=Math.floor,c=[0,0,0,0,0,0],l="Number.toFixed: incorrect invocation!",f=function f(e,t){for(var n=-1,r=t;++n<6;){r+=e*c[n],c[n]=r%1e7,r=u(r/1e7);}},p=function p(e){for(var t=6,n=0;--t>=0;){n+=c[t],c[t]=u(n/e),n=n%e*1e7;}},h=function h(){for(var e=6,t="";--e>=0;){if(""!==t||0===e||0!==c[e]){var n=String(c[e]);t=""===t?n:t+o.call("0",7-n.length)+n;}}return t;},d=function d(e,t,n){return 0===t?n:t%2==1?d(e,t-1,n*e):d(e*e,t/2,n);};r(r.P+r.F*(!!s&&("0.000"!==8e-5.toFixed(3)||"1"!==.9.toFixed(0)||"1.25"!==1.255.toFixed(2)||"1000000000000000128"!==0xde0b6b3a7640080.toFixed(0))||!n(14)(function(){s.call({});})),"Number",{toFixed:function toFixed(e){var t,n,r,s,u=i(this,l),c=a(e),m="",g="0";if(c<0||c>20)throw RangeError(l);if(u!=u)return"NaN";if(u<=-1e21||u>=1e21)return String(u);if(u<0&&(m="-",u=-u),u>1e-21)if(n=(t=function(e){for(var t=0,n=u*d(2,69,1);n>=4096;){t+=12,n/=4096;}for(;n>=2;){t+=1,n/=2;}return t;}()-69)<0?u*d(2,-t,1):u/d(2,t,1),n*=4503599627370496,(t=52-t)>0){for(f(0,n),r=c;r>=7;){f(1e7,0),r-=7;}for(f(d(10,r,1),0),r=t-1;r>=23;){p(1<<23),r-=23;}p(1<<r),f(1,1),p(2),g=h();}else f(0,n),f(1<<-t,0),g=h()+o.call("0",c);return c>0?m+((s=g.length)<=c?"0."+o.call("0",c-s)+g:g.slice(0,s-c)+"."+g.slice(s-c)):m+g;}});},function(e,t,n){"use strict";var r=n(13),a=n(38),i=n(41),o=n(163),s=n(50),u=n(14),c=n(74).f,l=n(36).f,f=n(18).f,p=n(88).trim,_h=r.Number,d=_h,m=_h.prototype,g="Number"==i(n(75)(m)),y="trim"in String.prototype,v=function v(e){var t=s(e,!1);if("string"==typeof t&&t.length>2){var n,r,a,i=(t=y?t.trim():p(t,3)).charCodeAt(0);if(43===i||45===i){if(88===(n=t.charCodeAt(2))||120===n)return NaN;}else if(48===i){switch(t.charCodeAt(1)){case 66:case 98:r=2,a=49;break;case 79:case 111:r=8,a=55;break;default:return+t;}for(var o,u=t.slice(2),c=0,l=u.length;c<l;c++){if((o=u.charCodeAt(c))<48||o>a)return NaN;}return parseInt(u,r);}}return+t;};if(!_h(" 0o1")||!_h("0b1")||_h("+0x1")){_h=function h(e){var t=arguments.length<1?0:e,n=this;return n instanceof _h&&(g?u(function(){m.valueOf.call(n);}):"Number"!=i(n))?o(new d(v(t)),n,_h):v(t);};for(var b,w=n(19)?c(d):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),x=0;w.length>x;x++){a(d,b=w[x])&&!a(_h,b)&&f(_h,b,l(d,b));}_h.prototype=m,m.constructor=_h,n(27)(r,"Number",_h);}},function(e,t,n){var r=n(5),a=n(217);r(r.G+r.F*(parseFloat!=a),{parseFloat:a});},function(e,t,n){var r=n(5),a=n(218);r(r.G+r.F*(parseInt!=a),{parseInt:a});},function(e,t,n){"use strict";var r=n(15),a=n(35),i=n(16)("hasInstance"),o=Function.prototype;i in o||n(18).f(o,i,{value:function value(e){if("function"!=typeof this||!r(e))return!1;if(!r(this.prototype))return e instanceof this;for(;e=a(e);){if(this.prototype===e)return!0;}return!1;}});},function(e,t,n){var r=n(18).f,a=Function.prototype,i=/^\s*function ([^ (]*)/;"name"in a||n(19)&&r(a,"name",{configurable:!0,get:function get(){try{return(""+this).match(i)[1];}catch(e){return"";}}});},function(e,t,n){var r=n(5);r(r.P,"Function",{bind:n(220)});},function(e,t,n){"use strict";var r=n(98),a={};a[n(16)("toStringTag")]="z",a+""!="[object z]"&&n(27)(Object.prototype,"toString",function(){return"[object "+r(this)+"]";},!0);},function(e,t,n){var r=n(5);r(r.S,"Object",{setPrototypeOf:n(165).set});},function(e,t){e.exports=Object.is||function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t;};},function(e,t,n){var r=n(5);r(r.S,"Object",{is:n(535)});},function(e,t,n){var r=n(5);r(r.S+r.F,"Object",{assign:n(221)});},function(e,t,n){var r=n(15);n(47)("isExtensible",function(e){return function(t){return!!r(t)&&(!e||e(t));};});},function(e,t,n){var r=n(15);n(47)("isSealed",function(e){return function(t){return!r(t)||!!e&&e(t);};});},function(e,t,n){var r=n(15);n(47)("isFrozen",function(e){return function(t){return!r(t)||!!e&&e(t);};});},function(e,t,n){var r=n(15),a=n(61).onFreeze;n(47)("preventExtensions",function(e){return function(t){return e&&r(t)?e(a(t)):t;};});},function(e,t,n){var r=n(15),a=n(61).onFreeze;n(47)("seal",function(e){return function(t){return e&&r(t)?e(a(t)):t;};});},function(e,t,n){var r=n(15),a=n(61).onFreeze;n(47)("freeze",function(e){return function(t){return e&&r(t)?e(a(t)):t;};});},function(e,t,n){n(47)("getOwnPropertyNames",function(){return n(222).f;});},function(e,t,n){var r=n(22),a=n(77);n(47)("keys",function(){return function(e){return a(r(e));};});},function(e,t,n){var r=n(22),a=n(35);n(47)("getPrototypeOf",function(){return function(e){return a(r(e));};});},function(e,t,n){var r=n(37),a=n(36).f;n(47)("getOwnPropertyDescriptor",function(){return function(e,t){return a(r(e),t);};});},function(e,t,n){var r=n(5);r(r.S+r.F*!n(19),"Object",{defineProperties:n(223)});},function(e,t,n){var r=n(5);r(r.S+r.F*!n(19),"Object",{defineProperty:n(18).f});},function(e,t,n){var r=n(5);r(r.S,"Object",{create:n(75)});},function(e,t,n){var r=n(77),a=n(119),i=n(99);e.exports=function(e){var t=r(e),n=a.f;if(n)for(var o,s=n(e),u=i.f,c=0;s.length>c;){u.call(e,o=s[c++])&&t.push(o);}return t;};},function(e,t,n){"use strict";var r=n(13),a=n(38),i=n(19),o=n(5),s=n(27),u=n(61).KEY,c=n(14),l=n(121),f=n(89),p=n(78),h=n(16),d=n(225),m=n(169),g=n(551),y=n(118),v=n(12),b=n(15),w=n(37),x=n(50),k=n(79),O=n(75),S=n(222),N=n(36),E=n(18),I=n(77),T=N.f,A=E.f,C=S.f,_P2=r.Symbol,_=r.JSON,R=_&&_.stringify,M=h("_hidden"),j=h("toPrimitive"),D={}.propertyIsEnumerable,L=l("symbol-registry"),z=l("symbols"),F=l("op-symbols"),B=Object.prototype,V="function"==typeof _P2,U=r.QObject,W=!U||!U.prototype||!U.prototype.findChild,G=i&&c(function(){return 7!=O(A({},"a",{get:function get(){return A(this,"a",{value:7}).a;}})).a;})?function(e,t,n){var r=T(B,t);r&&delete B[t],A(e,t,n),r&&e!==B&&A(B,t,r);}:A,q=function q(e){var t=z[e]=O(_P2.prototype);return t._k=e,t;},H=V&&"symbol"==_typeof(_P2.iterator)?function(e){return"symbol"==(typeof e==="undefined"?"undefined":_typeof(e));}:function(e){return e instanceof _P2;},K=function K(e,t,n){return e===B&&K(F,t,n),v(e),t=x(t,!0),v(n),a(z,t)?(n.enumerable?(a(e,M)&&e[M][t]&&(e[M][t]=!1),n=O(n,{enumerable:k(0,!1)})):(a(e,M)||A(e,M,k(1,{})),e[M][t]=!0),G(e,t,n)):A(e,t,n);},X=function X(e,t){v(e);for(var n,r=g(t=w(t)),a=0,i=r.length;i>a;){K(e,n=r[a++],t[n]);}return e;},J=function J(e){var t=D.call(this,e=x(e,!0));return!(this===B&&a(z,e)&&!a(F,e))&&(!(t||!a(this,e)||!a(z,e)||a(this,M)&&this[M][e])||t);},Y=function Y(e,t){if(e=w(e),t=x(t,!0),e!==B||!a(z,t)||a(F,t)){var n=T(e,t);return!n||!a(z,t)||a(e,M)&&e[M][t]||(n.enumerable=!0),n;}},Q=function Q(e){for(var t,n=C(w(e)),r=[],i=0;n.length>i;){a(z,t=n[i++])||t==M||t==u||r.push(t);}return r;},Z=function Z(e){for(var t,n=e===B,r=C(n?F:w(e)),i=[],o=0;r.length>o;){!a(z,t=r[o++])||n&&!a(B,t)||i.push(z[t]);}return i;};V||(s((_P2=function P(){if(this instanceof _P2)throw TypeError("Symbol is not a constructor!");var e=p(arguments.length>0?arguments[0]:void 0),t=function t(n){this===B&&t.call(F,n),a(this,M)&&a(this[M],e)&&(this[M][e]=!1),G(this,e,k(1,n));};return i&&W&&G(B,e,{configurable:!0,set:t}),q(e);}).prototype,"toString",function(){return this._k;}),N.f=Y,E.f=K,n(74).f=S.f=Q,n(99).f=J,n(119).f=Z,i&&!n(60)&&s(B,"propertyIsEnumerable",J,!0),d.f=function(e){return q(h(e));}),o(o.G+o.W+o.F*!V,{Symbol:_P2});for(var $="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ee=0;$.length>ee;){h($[ee++]);}for(var te=I(h.store),ne=0;te.length>ne;){m(te[ne++]);}o(o.S+o.F*!V,"Symbol",{for:function _for(e){return a(L,e+="")?L[e]:L[e]=_P2(e);},keyFor:function keyFor(e){if(!H(e))throw TypeError(e+" is not a symbol!");for(var t in L){if(L[t]===e)return t;}},useSetter:function useSetter(){W=!0;},useSimple:function useSimple(){W=!1;}}),o(o.S+o.F*!V,"Object",{create:function create(e,t){return void 0===t?O(e):X(O(e),t);},defineProperty:K,defineProperties:X,getOwnPropertyDescriptor:Y,getOwnPropertyNames:Q,getOwnPropertySymbols:Z}),_&&o(o.S+o.F*(!V||c(function(){var e=_P2();return"[null]"!=R([e])||"{}"!=R({a:e})||"{}"!=R(Object(e));})),"JSON",{stringify:function stringify(e){for(var t,n,r=[e],a=1;arguments.length>a;){r.push(arguments[a++]);}if(n=t=r[1],(b(t)||void 0!==e)&&!H(e))return y(t)||(t=function t(e,_t4){if("function"==typeof n&&(_t4=n.call(this,e,_t4)),!H(_t4))return _t4;}),r[1]=t,R.apply(_,r);}}),_P2.prototype[j]||n(28)(_P2.prototype,j,_P2.prototype.valueOf),f(_P2,"Symbol"),f(Math,"Math",!0),f(r.JSON,"JSON",!0);},function(e,t,n){n(552),n(550),n(549),n(548),n(547),n(546),n(545),n(544),n(543),n(542),n(541),n(540),n(539),n(538),n(537),n(536),n(534),n(533),n(532),n(531),n(530),n(529),n(528),n(527),n(526),n(525),n(524),n(523),n(522),n(521),n(520),n(519),n(518),n(517),n(516),n(515),n(514),n(513),n(512),n(511),n(510),n(509),n(508),n(507),n(506),n(505),n(504),n(503),n(502),n(501),n(500),n(499),n(498),n(497),n(496),n(495),n(494),n(493),n(492),n(491),n(490),n(489),n(488),n(487),n(486),n(485),n(484),n(483),n(482),n(481),n(480),n(479),n(478),n(477),n(476),n(475),n(474),n(472),n(471),n(469),n(468),n(467),n(466),n(465),n(464),n(463),n(461),n(460),n(459),n(458),n(457),n(456),n(455),n(454),n(453),n(452),n(451),n(450),n(449),n(149),n(448),n(447),n(208),n(446),n(445),n(444),n(443),n(442),n(205),n(203),n(202),n(441),n(440),n(439),n(438),n(437),n(436),n(435),n(434),n(433),n(432),n(431),n(430),n(429),n(428),n(427),n(426),n(425),n(424),n(423),n(422),n(421),n(420),n(419),n(418),n(417),n(416),n(415),n(414),n(413),n(412),n(411),n(410),n(409),n(408),n(407),n(406),n(405),n(404),n(403),n(402),n(401),n(400),n(399),n(398),n(397),n(396),n(395),n(394),n(393),n(392),n(391),n(390),n(389),n(388),n(387),n(386),n(385),n(384),n(383),n(382),n(381),n(380),n(379),n(378),n(377),n(376),n(375),n(374),n(373),n(372),n(371),n(370),n(369),n(368),n(367),n(366),n(365),n(364),n(363),n(362),n(361),n(360),n(359),n(358),n(357),e.exports=n(43);},function(e,t,n){"use strict";(function(e){if(n(553),n(356),n(355),e._babelPolyfill)throw new Error("only one instance of babel-polyfill is allowed");e._babelPolyfill=!0;var t="defineProperty";function r(e,n,r){e[n]||Object[t](e,n,{writable:!0,configurable:!0,value:r});}r(String.prototype,"padLeft","".padStart),r(String.prototype,"padRight","".padEnd),"pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function(e){[][e]&&r(Array,e,Function.call.bind([][e]));});}).call(this,n(101));},function(e,t,n){n(554),e.exports=n(352);}]);});//# sourceMappingURL=ml5.min.js.map /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5)(module))) /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; 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 get() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function get() { return module.i; } }); module.webpackPolyfill = 1; } return module; }; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _ml = __webpack_require__(4); var ML5 = _interopRequireWildcard(_ml); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } // TODO: Try to use npm if I can use the minified file var SIZE = 256; // import * as P5Dom from '../../vendor/js/p5.dom.min'; var sketch = function sketch(p5) { // The pre-trained Edges2Pikachu model is trained on 256x256 images // So the input images can only be 256x256 or 512x512, or multiple of 256 var inputImg = void 0; // let inputCanvas; var outputContainer = void 0; var statusMsg = void 0; var pix2pix = void 0; var clearBtn = void 0; var transferBtn = void 0; var modelReady = false; var isTransfering = false; // Draw the input image to the canvas var drawImage = function drawImage() { p5.image(inputImg, 0, 0); }; // Clear the canvas var clearCanvas = function clearCanvas() { p5.background(255); }; // Create image tag and add to #output div var createImage = function createImage(src) { var output = document.querySelector('#output'); var img = document.createElement('img'); img.src = src; output.appendChild(img); }; var transfer = function transfer() { // Set isTransfering to true isTransfering = true; // Update status message statusMsg.innerHTML = 'Applying Style Transfer...!'; // Select canvas DOM element var canvasElement = document.querySelector('canvas'); // .elt; // Apply pix2pix transformation pix2pix.transfer(canvasElement, function (err, result) { if (err) { console.log('err:', err); console.log('exit because error.'); return; } if (result && result.src) { // Set isTransfering back to false isTransfering = false; // Clear output container outputContainer.innerHTML = ''; // Create an image based result // I have no idea what this original commented out function was calling // createImg(result.src).class('border-box').parent('output'); createImage(result.src); // Show 'Done!' message statusMsg.innerHTML = 'Done!'; } }); }; // A function to be called when the models have loaded var modelLoaded = function modelLoaded() { console.log('model loaded'); // Show 'Model Loaded!' message statusMsg.innerHTML = 'Model Loaded!'; // Set modelReady to true modelReady = true; // Call transfer function after the model is loaded transfer(); // Attach a click event to the transfer button transferBtn.addEventListener('click', function () { transfer(); }); }; // When mouse is released, transfer the current image if the model is loaded and it's not in the process of another transformation p5.mouseReleased = function () { if (modelReady && !isTransfering) { transfer(); } }; // // Setup and Draw functions // p5.setup = function () { // Create a canvas var inputCanvas = p5.createCanvas(SIZE, SIZE); inputCanvas.class('border-box').parent('canvasContainer'); // Display initial input image inputImg = p5.loadImage('images/pikachu.png', drawImage); // Selcect output div container outputContainer = document.querySelector('#output'); statusMsg = document.querySelector('#status'); // Select 'transfer' button html element transferBtn = document.querySelector('#transferBtn'); // Select 'clear' button html element then assign click event. clearBtn = document.querySelector('#clearBtn'); clearBtn.addEventListener('click', function () { console.log('clear'); clearCanvas(); }); // Set stroke to black p5.stroke(0); p5.pixelDensity(1); // Create a pix2pix method with a pre-trained model pix2pix = ML5.pix2pix('https://rawgit.com/ml5js/pix2pix_models/master/edges2pikachu_AtoB.pict', modelLoaded); }; // Draw on the canvas when mouse is pressed p5.draw = function () { if (p5.mouseIsPressed) { p5.line(p5.mouseX, p5.mouseY, p5.pmouseX, p5.pmouseY); } }; }; exports.default = sketch; /***/ }) /******/ ]); //# sourceMappingURL=index.js.map
JavaScript
CL
83538cbb749f3edd751d9fd53f12471428a7151c28c540599582d9716f2e7597
import csv from 'csvtojson'; // polyfills for older browsers // keep an eye on these tickets // https://github.com/github/fetch/issues/357 // https://github.com/github/fetch/issues/275 import 'whatwg-fetch'; import Promise from 'promise-polyfill'; if (!window.Promise) { window.Promise = Promise; } /* My custom lib so if we stop using fetch and use axios or something else we dont have multiple points in the code to edit */ function fetchWrapper(url, method, options){ var request = new Request(url, {method}); return fetch(request) .catch(err=>{ alert('Connection failed, check your internet'); }) .then(response => { // django or whatever server sent client an error code if (!response.ok && response.headers) { var errObj = { serverError: true, status: response.status, statusText: response.statusText, } throw Error(JSON.stringify(errObj)); } return response; }) // added for .csv and the tartari test .then(response => { let textString = response.text(); return textString; }) // added for .csv and the tartari test .then(CSVdata => { // we are done with the fetch promise chain // so rotate to the promise from csv return csv().fromString(CSVdata); }); } export default fetchWrapper;
JavaScript
CL
a81ac3814d62477ea463c53d9987d6aa05ce59094633bad587391d401dcba9b2
import React from 'react'; import {Button} from 'reactstrap'; import {GenericSystemConfig} from './Generic'; import gql from 'graphql-tag'; import { graphql } from 'react-apollo'; import { Input, FormGroup, Label } from 'reactstrap'; const ops = { addSystem: gql`mutation AddSystemToSimulator($id: ID!, $params: String = "{}") { addSystemToSimulator(simulatorId: $id, className: "Reactor", params: $params) }`, removeSystem: gql`mutation RemoveSystem($id: ID) { removeSystemFromSimulator(systemId: $id) }`, updateOutput: gql`mutation UpdateReactorOutput($id: ID!, $output: Int!) { reactorChangeOutput(id: $id, output: $output) }` } const Reactor = ({data, client, simulatorId, type}) => { const addReactor = (model) => { const mutation = ops.addSystem; const variables = { id: simulatorId, params: JSON.stringify({model}) } client.mutate({ mutation, variables, refetchQueries: ['Reactor'] }) } const removeReactor = (id) => { const mutation = ops.removeSystem; const variables = { id, } client.mutate({ mutation, variables, refetchQueries: ['Reactor'] }) } const updateOutput = ({id}, value) => { const mutation = ops.updateOutput; const variables = { id, output: value } client.mutate({ mutation, variables, refetchQueries: ['Reactor'] }) } if (data.loading) return null; const {reactors} = data; return <div className="reactor scroll"> {reactors.map(e => <div key={e.id}> <GenericSystemConfig client={client} simulatorId={simulatorId} type={type} data={{systems: [e]}}> <div> <p>Model: {e.model}</p> { e.model === 'reactor' && <FormGroup> <Label>Reactor Output <Input type="number" value={e.powerOutput} onChange={(evt) => {updateOutput(e, evt.target.value)}} /> </Label> </FormGroup> } <Button color="danger" onClick={() => {removeReactor(e.id)}}>Remove Reactor</Button> </div> </GenericSystemConfig> </div>)} <Input color="primary" type="select" value="label" onChange={(e) => addReactor(e.target.value)}> <option value="label" disabled>Add Reactor</option> <option value="battery">Battery</option> <option value="reactor">Reactor</option> </Input> </div> } const SYSTEM_QUERY = gql` query Reactor($id: ID) { reactors(simulatorId: $id) { id name displayName type power { power powerLevels } model powerOutput } }`; export default graphql(SYSTEM_QUERY, { options: (ownProps) => ({ variables: { id: ownProps.simulatorId, } }) })(Reactor);
JavaScript
CL
eaa1a4c430fabb742148fce5c52492f097ca45e17a9f7822a869d637c870f4c8
/** * # nodeGame-db * Copyright(c) 2014 Stefano Balietti * MIT Licensed * * Abstract DB interface for nodeGame * * http://www.nodegame.org * * --- */ module.exports.Database = require('./lib/Database.js');
JavaScript
CL
ef6a8f727c55f7961a4cb0798b418af44b576b98c7952ef3a11624d4a6d7b3fa
/** @preserve Twitter Bootstrap Alert Overlay 0.1.1 * Available under the MIT license. * See https://github.com/Fincallorca/twbs-alert-overlay/ for more information. */ /** * * @property {Object} _options - properties of SelectableTable * @property {string} _options.overlay - all elements which can be selected * @property {boolean} _options.overlayAuto - all elements which can be selected * @property {Array.<Object>} _options.messages - all elements which can be selected */ class TwbsAlertOverlay { /** * * @param {string} type - one of the bootstrap classes `success`, `info`, `warning` or `danger` * @param {string} content - the text/html content of the alert element * @returns {object} * @private */ static _GetAlertElement(type, content) { return $("<div class=\"alert alert-" + type + "\" role=\"alert\">" + content + "</div>"); }; /** * * @param {Object} options - initial options */ constructor(options) { this._options = $.extend({}, TwbsAlertOverlay.DEFAULTS, options || {}); if ( this._options.messages.length === 0 ) { return; } this.$_overlay = null; TwbsAlertOverlay._scrollPosition = { top: null, left: null }; this._initializeOverlay(); } /** * @returns {object} returns the created jQuery object * @private */ _createOverlay() { let selector_parts = this._options.overlay.split(" "); let last_selector = selector_parts[ selector_parts.length - 1 ]; let tag = "div"; let id = ""; let classes = ""; if ( last_selector.search(/^[^#\.]+/g) > -1 ) { tag = last_selector.match(/^[^#\.]+/g); } let $overlay = $(document.createElement(tag)); if ( last_selector.search(/#[^#\.\s]+/g) > -1 ) { let ids = last_selector.match(/#[^#\.\s]+/g).map(function (_id) { return _id.substring(1); }); if ( ids.length > 1 ) { throw new Error("Multiple ids in option overlay: " + this._options.overlay); } $overlay.attr("id", ids[ 0 ]); } if ( last_selector.search(/\.[^#\.\s]+/g) > -1 ) { classes = last_selector.match(/\.[^#\.\s]+/g).map(function (_id) { return _id.substring(1); }); $overlay.attr("class", classes.join(" ")); } $overlay.css("display", "none"); $overlay.append($(document.createElement("div"))); return $overlay; }; /** * * @private */ _appendOverlay() { let selector_parts = this._options.overlay.split(" "); selector_parts.pop(); let selector = selector_parts.join(" "); if ( selector === "" ) { selector = "body"; } let $append_to = $(selector); if ( $append_to.length < 1 ) { throw new Error("No element found to append overlay: " + this._options.overlay); } this.$_overlay.appendTo($append_to); }; /** * * @private */ _initializeOverlay() { // jQuery Selctor mit der ID füllen this.$_overlay = $(this._options.overlay); // globales Overlay initalisiern (falls es verwendet werden soll und noch nicht existiert) if ( this.$_overlay.length === 0 ) { if ( !this._options.overlayAuto && window.console && console.warn ) { console.warn("Overlay '" + this._options.overlay + "' for twbsAlertOverlay could not be found!"); } else { this.$_overlay = this._createOverlay(); this._appendOverlay(); } } this.$_overlay.click(this._destroy.bind(this)); this._showOverlay(); }; /** * * @private */ _destroy() { this._hideOverlay(); }; /** * * @private */ _getAlertsElement() { let $element = $("<div class=\"container\"></div>"); this._options.messages.forEach(function (_message) { TwbsAlertOverlay._GetAlertElement(_message.type, _message.content).appendTo($element); }.bind(this)); return $element; }; /** * * @private */ _showOverlay() { TwbsAlertOverlay._scrollPosition.top = $(document).scrollY; TwbsAlertOverlay._scrollPosition.left = $(document).scrollX; let $body = $("body"); if ( document.body.scrollHeight > document.documentElement.clientHeight ) { $body.css("overflow-y", "scroll"); } if ( document.body.scrollWidth > document.documentElement.clientWidth ) { $body.css("overflow-x", "scroll"); } $body.addClass("alert-overlay-open"); this.$_overlay.html(this._getAlertsElement()).show(); }; /** * * @private */ _hideOverlay() { $("body").removeClass("alert-overlay-open"); this.$_overlay.hide(); }; } /** * * @type {{overlay: string, overlayAuto: boolean, messages: Array}} */ TwbsAlertOverlay.DEFAULTS = { overlay: "#alert-overlay", overlayAuto: true, messages: [] }; $(document).on("scroll", function () { if ( $("body").hasClass("alert-overlay-open") ) { window.scrollTo(TwbsAlertOverlay._scrollPosition.left, TwbsAlertOverlay._scrollPosition.top); } });
JavaScript
CL
6fa6d51c3c2dd362793b8e6ffc899f9ba4f87fb4d42529833f255ae3730eaea4
/** * This software or document includes material copied from or derived from the * [JSON <=> URI selector converter](http://w3c.github.io/web-annotation/selector-note/converter/) * built for demoing the * [Selectors and States](http://w3c.github.io/web-annotation/selector-note/index-respec.html#media_selector) * Note. Copyright © 2017 W3C® (MIT, ERCIM, Keio, Beihang). **/ import { parse } from './fragment.js' export { parse } export function uriToSpecificResource(uri) { const [source, fragmentIdentifier] = uri.split('#') const specificResource = { source } if (fragmentIdentifier) { try { Object.assign(specificResource, parse(fragmentIdentifier)) } catch (err) { // Apparently, the fragment identifier was not a serialised selector or state object. // We convert the fragment identifier string to its equivalent selector object. // (https://www.w3.org/TR/2017/NOTE-selectors-states-20170223/#FragmentSelector_def) specificResource.selector = { type: 'FragmentSelector', value: fragmentIdentifier, // According to the spec, we _should_ specify a 'conformsTo' link, but we cannot // know the semantics of this fragmentIdentifier, so we have to omit this relation. } } } return specificResource } export function specificResourceToUri(specificResource) { const uri = specificResource.source const selectorOrState = specificResource.selector || specificResource.state const fragmentIdentifier = selectorOrState && `#${stringify(selectorOrState)}` return (uri || '') + (fragmentIdentifier || '') } // Turn a selector or state object into a fragment identifier. export function stringify(selectorOrState) { const parameters = Object.entries(selectorOrState) .map(([key, value]) => { if ( key === 'refinedBy' || key === 'startSelector' || key === 'endSelector' ) { return `${encode(key)}=${stringify(value)}` } else { return `${encode(key)}=${encode(value)}` } }) const type = (/State$/.test(selectorOrState.type)) ? 'state' : 'selector' return `${type}(${parameters.join(',')})` } function encode(string) { // Besides required percent-encoding of required characters, also encode parentheses, because // parsers like our own can choke on them. Note that for our parser, only encoding any closing // parenthesis at the end of a value — i.e. /\)$/ — would have sufficed. return encodeURI(string) .replace(/#/g,'%23') .replace(/,/g,'%2C') .replace(/=/g,'%3D') .replace(/\(/g,'%28') .replace(/\)/g,'%29') }
JavaScript
CL
f07342c1600be27b62bc179b87ec58ab007c097033cbd3357e860363bebaad60
/** * Actual worker to load database models into global.app.db + global.db * This is seperated into its own un-oppinionated module so that it can be used by 'dumb' scripts without the need for the Doop framework load process * * @example * // Access the database via a dumb module: * var db = require(config.paths.root + '/units/core.db/loader')(function(db) { // db is now the modules loaded // }) * * @exmaple * // Access the database via an emitter * require(config.paths.root + '/units/core.db/loader')() * .on('end', (models) => { // Models is now the modules loaded // }); */ var _ = require('lodash'); var async = require('async-chainable'); var glob = require('glob'); var events = require('events'); var monoxide = require('monoxide'); /** * Load the database and all models * @param {function} callback Optional callback to fire on exit. Called as (err, models) * @return {EventEmitter} */ module.exports = function databaseLoader(callback) { var self = new events.EventEmitter(); // Queue the actual work for the next execute cycle so we can return immediately (otherwise we cant return an emitter); setTimeout(function() { if (!app.config) throw new Error('Attempted to load database before app.config was provided!'); self.emit('start'); monoxide.connect(app.config.mongo.uri) .on('error', err => self.emit('error', err)); self.emit('connected'); glob(app.config.paths.root + '/units/**/*.schm.js', function(err, files) { if (err) return next(err); files.forEach(path => { self.emit('model', path); require(path); }); self.emit('end', monoxide.models); if (_.isFunction(callback)) callback(null, monoxide.models); }); }); return self; };
JavaScript
CL
1d07c96e6ddc003d55ceebe20dc81a12a034b07d7881c258cc0adef61cab6955
import React from "react"; import Book from "../components/bookingForm"; import Map from "../components/Map"; import RequestModal from "../drivercomponents/RequestModal"; import { View, HeaderBarItem, StatusBar, AsyncStorage, ToastAndroid } from "react-native"; import { Container, Text, Button, Content, Input, Item } from "native-base"; import MapSearch from "../components/mapSearch"; import io from "socket.io-client"; console.ignoredYellowBox = ["Remote debugger"]; const localip = "192.168.0.105"; import { YellowBox } from "react-native"; YellowBox.ignoreWarnings([ "Unrecognized WebSocket connection option(s) `agent`, `perMessageDeflate`, `pfx`, `key`, `passphrase`, `cert`, `ca`, `ciphers`, `rejectUnauthorized`. Did you mean to put these under `headers`?" ]); export default class HomeScreen extends React.Component { constructor() { super(); this.activeSocket = false; this.state = { requestModal: false, bookInfo: [], currentReqId: "0", tempBookInfo: null }; } async processResponse(action) { this.setState({ ...this.state, requestModal: false }); console.log("processing response"); const data = { decision: action.toString() }; let token = await AsyncStorage.getItem("jwt"); // Serialize and post the data const json = JSON.stringify(data); fetch( `http://${localip}:3000/driver/${this.state.currentReqId}/decision `, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: `JWT ${token}` }, body: json } ) .then(response => response.json()) .then(res => { console.log(res); ToastAndroid.show(res.message, ToastAndroid.LONG); this.setState({ ...this.state, bookInfo: [...this.state.bookInfo, this.state.tempBookInfo], tempBookInfo: null }); }) .catch(error => { console.log(error); }) .done(); } async sendUserId() { let token = await AsyncStorage.getItem("jwt"); fetch(`http://${localip}:3000/driver/getuser`, { method: "GET", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: `JWT ${token}` } }) .then(res => {}) .catch(() => alert("Cannot send ID")); } async updateSocketId(socketId) { let token = await AsyncStorage.getItem("jwt"); try { let response = await fetch(`http://${localip}:3000/driver/updateSocket`, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", Authorization: `JWT ${token}` }, body: JSON.stringify({ driverSocketId: socketId }) }); let responseJson = await response.json(); console.log(responseJson.message); return responseJson.message; } catch (error) { console.error(error); } } connectSocket() { this.socket = io(`http://${localip}:3000`); this.socket.on("connect", () => { this.activeSocket = true; console.log( "Connected with id: " + this.socket.id + " sending fetch to /updateSocket" ); this.updateSocketId(this.socket.id); this.socket.on("new-booking", data => { console.log("new booking data: ", data); this.setState({ ...this.state, requestModal: true, currentReqId: data.bookingData._id, tempBookInfo: data.bookingData }); }); }); this.socket.on("server", data => { this.socket.emit("client", "Hi"); console.log(data); }); this.socket.on("disconnect", function() { this.activeSocket = false; console.log("driver disconnected"); }); } render() { if (!this.activeSocket) { this.sendUserId(); this.connectSocket(); console.log("Connectng from render"); } return ( <View style={{ flex: 1 }}> <StatusBar backgroundColor="red" /> <Map socket={this.socket} /> {this.state.requestModal ? ( <RequestModal onResponse={action => { console.log("on response recived action " + action); this.processResponse(action); }} requestId={this.state.currentReqId} /> ) : null} </View> ); } }
JavaScript
CL
73bc25d1f326014b7f272cf185a92b608bbd8c14f0bc3c15153641b634714e33
import React from 'react'; import {Card, CardText, CardTitle} from 'react-md/lib/Cards/index'; import {Chart} from 'react-google-charts'; const opts = { hAxis: { title: 'Regression methods', minValue: 0, }, vAxis: { title: 'Time in seconds', }, chartArea: {width: '60%'}, isStacked: false, }; const columns2 = [ {type: 'string', label: 'Regression method'}, {type: 'number', label: 'Method time'}, {type: 'string', role: 'annotation'}, ]; const dataReg = [ columns2, ['Linear', 0.09, '0.09'], ['Lasso', 0.15, '0.15'], ['Random forest', 0.35, '0.35'], // TODO: add XGBoost? add DeepLearning? ]; export const RegressionMethodsCard = () => { return <Card className="md-cell md-cell--6 md-cell--8-tablet"> <CardTitle title="Regression method comparison" subtitle="Tested version 1.0.0" expander/> <CardText expandable> <p>How long does it take to run various regression methods? This is the answer.</p> <p> The regression tests were run with the configuration: encoding type boolean, no padding, prefix length 20, prediction label remaining time, no clustering and default classification method parameters. </p> The logs for this test are: <ul> <li><a href="https://data.4tu.nl/repository/uuid:5f3067df-f10b-45da-b98b-86ae4c7a310b">BPI challenge 2017</a> about a loan application process. It contains 31,509 traces and 1,202,267 events </li> </ul> The time for any regression method takes up an insignificant percentage of the total task time. <Chart chartType="BarChart" data={dataReg} options={opts} graph_id="reg-methods" width="100%" /> </CardText> </Card>; };
JavaScript
CL
e3a27b835a9ade25637267a022d438d1fa7328365935e090c3c8cde7a575962a
/* Instructions: (1) Wrap an XHR in a Promise in the get() function below. See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest (a) Resolve on load and reject on error. (2) If the XHR resolves, use addSearchHeader to add the search header to the page. (3) If the XHR fails, console.log the error and pass 'unknown' to addSearchHeader */ // Inline configuration for jshint below. Prevents `gulp jshint` from failing with quiz starter code. /* jshint unused: false */ (function(document) { "use strict"; var home = null; /** * Helper function to show the search query. * @param {String} response - The unparsed JSON response from get. */ function addSearchHeader(response) { try { response = JSON.parse(response).query; // you'll be moving this line out of here in the next quiz! } catch (e) { // it's 'unknown', so leave it alone } home.innerHTML = '<h2 class="page-title">query: ' + response + "</h2>"; } /** * XHR wrapped in a promise. * @param {String} url - The URL to fetch. * @return {Promise} - A Promise that resolves when the XHR succeeds and fails otherwise. */ function get(url) { return fetch(url, { method: "GET" }); } function getJSON(url) { console.log("sent : " + url); return get(url).then(response => { if (url === "data/planets/kepler-62f.json") { return new Promise(resolve => { setTimeout(() => { console.log("recieved : " + url); resolve(response.json()); }, 1000); }); } else { console.log("recieved : " + url); return response.json(); } }); } function createPlanetThumb(data) { return new Promise(resolve => { let planet = document.createElement("planet-thumb"); for (let content in data) { planet[content] = data[content]; } home.appendChild(planet); console.log(data.pl_name); resolve(); }); } window.addEventListener("WebComponentsReady", function() { home = document.querySelector('section[data-route="home"]'); /* Uncomment the next line you're ready to start chaining and testing! You'll need to add a .then and a .catch. Pass the response to addSearchHeader on resolve or pass 'unknown' to addSearchHeader if it rejects. */ /** This is a three step process: BONUS EXCERCISE Create an array of network requests that are executing in parallel. Attach a Promisified version of createPlanetThumb to each request in order to render thumbnails. Create a sequence of Promises, each of which is a request and thumbnail rendering. I imagine it like this (each '-->' is a .then): [ (request --> render) --> (request --> render) --> (request --> render) --> ... ] .map takes care of the parallel requests part and .forEach chains the requests into a sequence. */ // get("../data/earth-like-results.json"); getJSON("../data/earth-like-results.json") .then(response => { console.log(response.results); addSearchHeader(response.query); return response; }) .then(response => { let sequence = Promise.resolve(); let arrayOfExecutingPromises = response.results.map(result => { return getJSON(result); }); arrayOfExecutingPromises.forEach(request => { sequence = sequence.then(() => { return request.then(data => { createPlanetThumb(data); }); }); }); // return Promise.all(arrayOfExecutingPromises).then(data => { // sequence = sequence.then(() => { // createPlanetThumb(data); // }); // }); }); }); })(document);
JavaScript
CL
39b8486680c4e3986d0a1964b1625202490412f6fd1298129c230430143f1ea3
var ffdb = require('flat-file-db'); var events = require('events'); var util = require('util'); var File = require('../utils/File'); var path = require('path'); function Database(config) { var self = this; /** db instance */ this.db; /** * connect to db * @param table */ this.connect = function(table) { db = new ffdb( config.dbLocation + path.sep + table + '.db' ); db.on('open', function(){ self.emit(Database.prototype.CONNECTED); }); }; /** * connect to db (sync) * @param table */ this.connectSync = function(table) { db = new ffdb.sync( config.dbLocation + path.sep + table + '.db' ); }; /** * insert doc into DB * @param key * @param value * @param callback */ this.insert = function(key, val, cb) { db.put(key, val, function(err) { if (cb) { cb(err); } }); }; /** * get keys * @returns {*} */ this.keys = function() { return db.keys(); }; /** * find doc * @param query * @returns {*} */ this.find = function(query) { return db.get(query); }; /** * get all tables * @param {String} optional dir in db location to narrow down location */ this.getAllTables = function(dir) { var dbdir = config.dbLocation; if (dir) { dbdir += path.sep + dir; } var files = File.prototype.getAllFiles(dbdir, { map: function(fullpath, filename, dir) { var table = fullpath.split(config.dbLocation + path.sep)[1]; var db = File.prototype.removeExtension(table); return db; } }); return files; }; } util.inherits(Database, events.EventEmitter); Database.prototype.CONNECTED = "connected"; Database.prototype.CONNECTIONERROR = "connectionerror"; exports = module.exports = Database;
JavaScript
CL
9dd1f2a9fb54d9b9cb0ec41268ff392c42f7ebe07d42c4bd2ea6261e623ef5a3
import cd from './cd'; import controller from './controller'; import settings from './settings'; import { areObjectsEqual } from './utils'; import { confirmCloseDialog, createCheckboxField, createNumberField, createRadioField, createTextField, handleDialogError, isDialogUnsaved, tweakUserOoUiClass, } from './ooui'; import { saveGlobalOption, saveLocalOption } from './apiWrappers'; /** * Class used to create a settings dialog. * * @augments external:OO.ui.ProcessDialog */ class SettingsDialog extends OO.ui.ProcessDialog { static name = 'settingsDialog'; static title = cd.s('sd-title'); static actions = [ { action: 'close', modes: ['settings', 'reload', 'dataRemoved'], flags: ['safe', 'close'], disabled: true, }, { action: 'save', modes: ['settings'], label: cd.s('sd-save'), flags: ['primary', 'progressive'], disabled: true, }, { action: 'reset', modes: ['settings'], label: cd.s('sd-reset'), flags: ['destructive'], disabled: true, }, { action: 'reload', modes: ['reload'], label: cd.s('sd-reload'), flags: ['primary', 'progressive'], }, ]; static size = 'large'; /** * Create a settings dialog. * * @param {string} [initialPageName] */ constructor(initialPageName) { super({ classes: ['cd-dialog-settings'] }); this.initialPageName = initialPageName; } /** * OOUI native method to get the height of the window body. * * @returns {number} * @see * https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/OO.ui.Window-method-getBodyHeight * @private */ getBodyHeight() { return 600; } /** * OOUI native method that initializes window contents. * * @param {...*} [args] * @see * https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/OO.ui.ProcessDialog-method-initialize * @see https://www.mediawiki.org/wiki/OOUI/Windows#Window_lifecycle * @private */ initialize(...args) { super.initialize(...args); this.pushPending(); this.preparatoryRequests = [ settings.load({ omitLocal: true }), ]; this.loadingPanel = new OO.ui.PanelLayout({ padded: true, expanded: false, }); this.loadingPanel.$element.append($('<div>').text(cd.s('loading-ellipsis'))); this.settingsPanel = new OO.ui.PanelLayout({ padded: false, expanded: true, }); const $settingsSaved = $('<p>').text(cd.s('sd-saved')); this.reloadPanel = new OO.ui.PanelLayout({ padded: true, expanded: false, }); this.reloadPanel.$element.append($settingsSaved); const $dataRemoved = $('<p>').text(cd.s('sd-dataremoved')); this.dataRemovedPanel = new OO.ui.PanelLayout({ padded: true, expanded: false, }); this.dataRemovedPanel.$element.append($dataRemoved); this.stackLayout = new OO.ui.StackLayout({ items: [this.loadingPanel, this.settingsPanel, this.reloadPanel, this.dataRemovedPanel], }); this.$body.append(this.stackLayout.$element); } /** * OOUI native method that returns a "setup" process which is used to set up a window for use in a * particular context, based on the `data` argument. * * @param {object} [data] Dialog opening data * @returns {external:OO.ui.Process} * @see * https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/OO.ui.Dialog-method-getSetupProcess * @see https://www.mediawiki.org/wiki/OOUI/Windows#Window_lifecycle * @private */ getSetupProcess(data) { return super.getSetupProcess(data).next(() => { this.stackLayout.setItem(this.loadingPanel); this.actions.setMode('settings'); }); } /** * OOUI native method that returns a "ready" process which is used to ready a window for use in a * particular context, based on the `data` argument. * * @param {object} data Window opening data * @returns {external:OO.ui.Process} * @see * https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/OO.ui.Window-method-getReadyProcess * @see https://www.mediawiki.org/wiki/OOUI/Windows#Window_lifecycle * @private */ getReadyProcess(data) { return super.getReadyProcess(data).next(async () => { try { [this.settings] = await Promise.all(this.preparatoryRequests); } catch (e) { handleDialogError(this, e, 'error-settings-load', false); return; } // `this.settings` can be empty after removing the data using the relevant functionality in // UI. if (!Object.keys(this.settings).length) { this.settings = settings.get(); } this.renderControls(this.settings); this.stackLayout.setItem(this.settingsPanel); this.bookletLayout.setPage(this.initialPageName || settings.scheme.ui[0].name); this.actions.setAbilities({ close: true }); this.popPending(); controller.addPreventUnloadCondition('dialog', () => isDialogUnsaved(this)); }); } /** * OOUI native method that returns a process for taking action. * * @param {string} action Symbolic name of the action. * @returns {external:OO.ui.Process} * @see * https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/OO.ui.Dialog-method-getActionProcess * @private */ getActionProcess(action) { if (action === 'save') { return new OO.ui.Process(async () => { this.pushPending(); try { await settings.save(this.collectSettings()); } catch (e) { handleDialogError(this, e, 'error-settings-save', true); return; } controller.removePreventUnloadCondition('dialog'); this.stackLayout.setItem(this.reloadPanel); this.actions.setMode('reload'); this.popPending(); }); } else if (action === 'reload') { return new OO.ui.Process(() => { this.close(); location.reload(); }); } else if (action === 'close') { return new OO.ui.Process(() => { confirmCloseDialog(this, 'sd'); }); } else if (action === 'reset') { return new OO.ui.Process(() => { if (confirm(cd.s('sd-reset-confirm'))) { const currentPageName = this.bookletLayout.getCurrentPageName(); this.renderControls(settings.scheme.default); this.bookletLayout.setPage(currentPageName); } }); } return super.getActionProcess(action); } /** * Create widget fields with states of controls set according to setting values. * * @param {object} settingValues Values of settings according to which to set the states of * controls. * @returns {object} * @private */ createPages(settingValues) { const controls = {}; const pages = settings.scheme.ui.map((pageData) => { const $fields = pageData.controls.map((data) => { const name = data.name; switch (data.type) { case 'checkbox': controls[name] = createCheckboxField({ value: name, selected: settingValues[name], label: data.label, help: data.help, classes: data.classes, }); controls[name].input.connect(this, { change: 'updateStates' }); break; case 'radio': controls[name] = createRadioField({ options: data.options, selected: settingValues[name], label: data.label, help: data.help, }); controls[name].select.connect(this, { select: 'updateStates' }); break; case 'text': controls[name] = createTextField({ value: settingValues[name], maxLength: 100, label: data.label, help: data.help, }); controls[name].input.connect(this, { change: 'updateStates' }); break; case 'number': controls[name] = createNumberField({ value: settingValues[name], min: data.min, max: data.max, buttonStep: data.buttonStep, label: data.label, help: data.help, classes: data.classes, }); controls[name].input.connect(this, { change: 'updateStates' }); break; case 'multicheckbox': controls[name] = {}; controls[name].multiselect = new OO.ui.CheckboxMultiselectWidget({ items: data.options.map((option) => ( new OO.ui.CheckboxMultioptionWidget({ data: option.data, selected: settingValues[name].includes(option.data), label: option.label, }) )), classes: data.classes, }); controls[name].multiselect.connect(this, { select: 'updateStates' }); controls[name].field = new OO.ui.FieldLayout(controls[name].multiselect, { label: data.label, align: 'top', }); break; case 'multitag': controls[name] = {}; controls[name].multiselect = new OO.ui.TagMultiselectWidget({ placeholder: data.placeholder, allowArbitrary: true, inputPosition: 'outline', tagLimit: data.tagLimit, selected: (data.dataToUi || ((val) => val)).call(null, settingValues[name]), }); controls[name].multiselect.connect(this, { change: 'updateStates' }); controls[name].field = new OO.ui.FieldLayout(controls[name].multiselect, { label: data.label, align: 'top', help: data.help, helpInline: true, }); break; case 'button': controls[name] = {}; controls[name].button = new OO.ui.ButtonWidget({ label: data.label, flags: data.flags, }); controls[name].field = new OO.ui.FieldLayout(controls[name].button, { label: data.fieldLabel, align: 'top', help: data.help, helpInline: true, }); break; } return controls[name].field.$element; }); // eslint-disable-next-line jsdoc/require-jsdoc const PageLayout = class extends OO.ui.PageLayout { // eslint-disable-next-line jsdoc/require-jsdoc constructor() { super(pageData.name); this.$element.append($fields); } // eslint-disable-next-line jsdoc/require-jsdoc setupOutlineItem() { this.outlineItem.setLabel(pageData.label); } }; tweakUserOoUiClass(PageLayout, OO.ui.PageLayout); const page = new PageLayout(this); return page; }); controls.removeData.button.connect(this, { click: 'removeData' }); controls.desktopNotifications.select.connect(this, { choose: 'onDesktopNotificationsSelectChange', }); this.controls = controls; return pages; } /** * Render control widgets. * * @param {object} settingValues Values of settings according to which to set the states of * controls. * @private */ renderControls(settingValues) { settings.initUi(); this.bookletLayout = new OO.ui.BookletLayout({ outlined: true, }); this.bookletLayout.addPages(this.createPages(settingValues)); this.settingsPanel.$element.empty().append(this.bookletLayout.$element); this.updateStates(); } /** * Get an object with settings related to states (see {@link module:settings.scheme}). * * @returns {object} * @private */ getStatesSettings() { return settings.scheme.states.reduce((obj, state) => { obj[state] = this.settings[state]; return obj; }, {}); } /** * Get setting values from controls. * * @returns {object} * @private */ collectSettings() { const collectedSettings = {}; const controls = this.controls; settings.scheme.ui.forEach((pageData) => { pageData.controls.forEach((data) => { const name = data.name; switch (data.type) { case 'checkbox': collectedSettings[name] = controls[name].input.isSelected(); break; case 'radio': collectedSettings[name] = ( controls[name].select.findSelectedItem()?.getData() || settings.scheme.default[name] ); break; case 'text': collectedSettings[name] = controls[name].input.getValue(); break; case 'number': collectedSettings[name] = Number(controls[name].input.getValue()); break; case 'multicheckbox': collectedSettings[name] = controls[name].multiselect.findSelectedItemsData(); break; case 'multitag': collectedSettings[name] = (data.uiToData || ((val) => val)).call( null, controls[name].multiselect.getValue() ); break; } }); }); return Object.assign( {}, settings.scheme.default, collectedSettings, this.getStatesSettings(), { 'insertButtons-altered': ( JSON.stringify(collectedSettings.insertButtons) !== JSON.stringify(settings.scheme.default.insertButtons) ), }, ); } /** * Update the control states. * * @private */ async updateStates() { const controls = this.controls; controls.collapseThreadsLevel.input.setDisabled(!controls.enableThreads.input.isSelected()); controls.hideTimezone.input.setDisabled( controls.timestampFormat.select.findSelectedItem()?.getData() === 'relative' ); controls.notifyCollapsedThreads.input.setDisabled( controls.desktopNotifications.select.findSelectedItem()?.getData() === 'none' && controls.notifications.select.findSelectedItem()?.getData() === 'none' ); controls.showContribsLink.input.setDisabled(!controls.reformatComments.input.isSelected()); controls.useTemplateData.input.setDisabled( !controls.autocompleteTypes.multiselect.findItemFromData('templates').isSelected() ); let areInputsValid = true; const numberSettingNames = [].concat(...settings.scheme.ui.map((pageData) => ( pageData.controls .filter((data) => data.type === 'number') .map((data) => data.name) ))); await Promise.all(numberSettingNames.map((name) => controls[name].input.getValidity())) .catch(() => { areInputsValid = false; }); const collectedSettings = this.collectSettings(); this.actions.setAbilities({ save: !areObjectsEqual(collectedSettings, this.settings) && areInputsValid, reset: !areObjectsEqual( Object.assign({}, collectedSettings), Object.assign( {}, settings.scheme.default, settings.scheme.resetsTo, this.getStatesSettings(), ) ), }); } /** * Handler of the event of change of the desktop notifications radio select. * * @param {external:OO.ui.RadioOptionWidget} option * @private */ onDesktopNotificationsSelectChange(option) { if (typeof Notification === 'undefined') return; if (option.data !== 'none' && Notification.permission !== 'granted') { OO.ui.alert(cd.s('dn-grantpermission')); Notification.requestPermission((permission) => { if (permission !== 'granted') { this.controls.desktopNotifications.select.selectItemByData('none'); } }); } } /** * Remove script data as requested by the user after confirmation. * * @private */ async removeData() { if (confirm(cd.s('sd-removedata-confirm'))) { this.pushPending(); try { await Promise.all([ saveLocalOption(cd.g.localSettingsOptionName, null), saveLocalOption(cd.g.visitsOptionName, null), saveLocalOption(cd.g.subscriptionsOptionName, null), saveGlobalOption(cd.g.settingsOptionName, null), ]); } catch (e) { handleDialogError(this, e, 'sd-error-removedata', false); return; } mw.storage.remove('convenientDiscussions-commentForms'); mw.storage.remove('convenientDiscussions-thanks'); mw.storage.remove('convenientDiscussions-seenRenderedChanges'); mw.storage.remove('convenientDiscussions-collapsedThreads'); mw.storage.remove('convenientDiscussions-mutedUsers'); this.stackLayout.setItem(this.dataRemovedPanel); this.actions.setMode('dataRemoved'); this.popPending(); } } } tweakUserOoUiClass(SettingsDialog, OO.ui.ProcessDialog); export default SettingsDialog;
JavaScript
CL
e6b7b5115a15567e506e0f6a36645a51b7c55ad61b2939c90530743aaba6b26b
/** * 初始化接口请求 * @param {object} types 要分发的 Action type 集合,结构 {start:'',success:'',failure:''} * @param {string} api 接口地址 * @param {string} callType 请求类型,暂时只提供 get 和 post * @param {object} meta 要分发的 Action meta 信息 * @param {object} body 要传递给后台的数据 * @param {function} shouldCallAPI 决定是否真实调用接口的函数,传入的参数为整个应用的 State。 * @returns {{typeCollection: *, api: *, callType: *, meta, body: {}, shouldCallAPI: (function(*): boolean)}} */ export function initAPI (types, api, callType, { meta, body = {}, shouldCallAPI = (state) => true } = {}) { return { types, api, callType, meta, body, shouldCallAPI } } export default initAPI
JavaScript
CL
690b49771403c9172699798b987186a9b3363f90c1532a7e952782a142eabe36
import React from 'react'; import PropTypes from 'prop-types'; import { TouchableHighlight, View, FlatList, StyleSheet, } from 'react-native'; import { RkStyleSheet, RkTheme, RkText, } from 'react-native-ui-kitten'; import NavigationType from '../../config/navigation/propTypes'; export class CategoryMenu extends React.Component { static propTypes = { navigation: NavigationType.isRequired, items: PropTypes.arrayOf(PropTypes.shape({ title: PropTypes.string.isRequired, })).isRequired, }; onItemPressed = (item) => { const url = item.action || item.id; this.props.navigation.navigate(url); }; extractItemKey = (item) => item.id; renderItem = ({ item }) => ( <TouchableHighlight style={styles.item} underlayColor={RkTheme.current.colors.button.underlay} activeOpacity={1} onPress={() => this.onItemPressed(item)}> <View> <RkText>{item.title}</RkText> </View> </TouchableHighlight> ); renderPlaceholder = () => ( <View style={styles.emptyContainer}> <RkText rkType='light subtitle'>Coming Soon...</RkText> </View> ); renderList = () => ( <FlatList style={styles.list} data={this.props.items} keyExtractor={this.extractItemKey} renderItem={this.renderItem} /> ); render = () => (this.props.items.length === 0 ? this.renderPlaceholder() : this.renderList()); } const styles = RkStyleSheet.create(theme => ({ item: { paddingVertical: 32.5, paddingHorizontal: 16.5, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: theme.colors.border.base, }, list: { backgroundColor: theme.colors.screen.base, }, emptyContainer: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: theme.colors.screen.base, }, }));
JavaScript
CL
2f27ebcb48c07615708d5142ad6a3ec37114fcaf92ac29ad7ec8da57d4deab49
/* * Copyright 2016 Nicolas Lochet 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. */ 'use strict' describe("more advanced pattern grammar test:", function() { var build_parser = require(__dirname+'/../lib/parser') , fs = require('fs') , yaml = require('js-yaml') var parser = build_parser(yaml.safeLoad(fs.readFileSync(__dirname+'/grammar_for_test.yml'))) it("no change rule", function() { expect(parser('moon.ABS')).toEqual('aleh') }) it("complex phonetic system tranformation", function() { expect(parser('moon.GEN')).toEqual('alehih') expect(parser('moon.PL.ABS')).toEqual('alecuh') expect(parser('moon.PL.GEN')).toEqual('alecuhih') }) it("tranform via simple derivation", function() { expect(parser('moon-MS')).toEqual('aler') expect(parser('moon-MS.ABS')).toEqual('aler') expect(parser('moon-MS.GEN')).toEqual('alerih') expect(parser('moon-MS.PL.ABS')).toEqual('alerruh') expect(parser('moon-MS.PL.GEN')).toEqual('alerruhih') }) it("tranform via complex derivation", function() { expect(function() { parser('moon-NMZa') }).toThrowError('No matching derivation for "nominal.GEN>nominal, nominal.PL.GEN>nominal, verbal.ATTR>nominal" in "aleh"') expect(function() { parser('moon.ABS-NMZa') }).toThrowError('No matching derivation for "nominal.GEN>nominal, nominal.PL.GEN>nominal, verbal.ATTR>nominal" in "aleh.ABS"') expect(parser('moon.GEN-NMZa')).toEqual('alehihfah') expect(parser('moon.PL.GEN-NMZa')).toEqual('alecuhihfah') }) it("default tranformation", function() { expect(parser('not_a_real_verb')).toEqual('plop') expect(parser('not_a_real_verb.PFV')).toEqual('plopil') expect(parser('not_a_real_verb.OPTA.NEG')).toEqual('ploras') }) it("paradigm extension", function() { expect(parser('act.IPFV')).toEqual('hesan') expect(parser('say.IPFV')).toEqual('fahun') }) })
JavaScript
CL
0d6dcc9db5bafa778e69ecc170e5b90b57ceeac714b4af24a6d9d15f0cb17902
const EventEmitter = require('events'); const logger = require('winston'); const Notifications = require('./notifications'); const internal = require('./internal/code-gen/statistics-api'); class Statistics extends EventEmitter { /** * Create a new Statistics object. * @param {String} apiKey The API key used to access the statistics api. * @param {String} baseUrl The URL of the statistics service. */ constructor(apiKey, baseUrl) { super(); const apiUrl = `${baseUrl}/statistics/v3`; this.SERVICE_CHANGE_EVENT = "ServiceChange"; this.UPDATES_EVENT = "Updates"; this.apiKey = apiKey; this.apiUrl = apiUrl; const client = new internal.ApiClient(); client.enableCookies = true; client.basePath = apiUrl; this.client = client; this.api = new internal.StatisticsApi(client); this.cookieJar = client.agent.jar; this.notifications = new Notifications(apiKey, `${apiUrl}/notifications`); } /** * Initialize the Statistics client library. * * @param {string} token The authorization token you received during authentication by following the Authorization Code Grant flow. * @param {object} cometdConfiguration * @returns {Promise} */ initialize(token, cometdConfiguration = {}) { logger.debug(`Initializing: ${token}`); this.client.defaultHeaders = { 'x-api-key': this.apiKey, Authorization: `Bearer ${token}` }; const serviceChannel = "/statistics/v3/service"; const updatesChannel = "/statistics/v3/updates"; const channels = [ serviceChannel, updatesChannel ]; // emit events, to subscribe them use events.on(EVENT_NAME, (data) => {}); this.notifications.on(serviceChannel, data => this.emit(this.SERVICE_CHANGE_EVENT, data)); this.notifications.on(updatesChannel, data => this.emit(this.UPDATES_EVENT, data)); return this.notifications.initialize(token, channels, this.cookieJar, cometdConfiguration).then(() => this); } /** * Delete the specified subscription by closing all its statistics. * * @param {string} id The ID of the subscription to delete. * @returns {Promise} */ deleteSubscription(id) { return this.api.deleteSubscription(id); } /** * Open a subscription for the specified set of statistics. * * @param {string} operationId A unique string (we recommend using a UUID/GUID) that the Statistics API uses as the subscriptionId. * @param {object[]} descriptors Definitions of the statistics to be monitored. * @param {boolean} verbose Specifies whether the Statistics API should return additional information about opened statistics in the response. * @returns {Promise} */ createSubscription(operationId, descriptors = [], verbose = true) { const statistics = { operationId: operationId, data: { statistics: descriptors } }; const opts = { verbose: verbose ? 'INFO' : 'OFF' }; return this.api.createSubscription(statistics, opts); } /** * Get the value of a set of statistics that was opened with a subscription. * * @param {string} id The ID of the subscription. * @param {string[]} statisticIds A list of statistic IDs that belong to the specified subscription. If omitted, the Statistics API returns the current values of all statistics opened within the subscription. If specified, the Statistics API returns values for the statistics with the specified IDs. * @param {boolean} verbose * @returns {Promise} */ peekSubscriptionStats(id, statisticIds = [], verbose = true) { const opts = { statisticIds: statisticIds, verbose: verbose ? 'INFO' : 'OFF' }; return this.api.peekSubscriptionStats(id, opts); } /** * Get the current value of a statistic from Stat Server. * * @param {string} name The name of the pre-configured statistic to retrieve. * @param {string} objectId The ID of the object. * @param {string} objectType The type of object the statistic is for. * @returns {Promise} */ getStatValue(name, objectId, objectType) { return this.api.getStatValue(objectId, objectType, name); } /** * Get the current value of predefined statistics from Stat Server without a subscription. * * @param {object[]} infos The set of statistics you want to get the values for from Stat Server. * @returns {Promise} */ getStatValues(infos = []) { const statistics = { data: { statistics: infos } }; return this.api.getStatValues(statistics); } destroy() { this.notifications.finalize(); } } module.exports = Statistics;
JavaScript
CL
ce2076689508587613b65d25c1eed2838e55e5021c93a15613f7a98dc6784fd6
import { useEffect, useState } from "react"; import twitterLogo from "./assets/twitter-logo.svg"; import "./App.css"; import { Connection, PublicKey, clusterApiUrl } from "@solana/web3.js"; import { Program, Provider, web3 } from "@project-serum/anchor"; import kp from "./keypair.json"; import idl from "./idl.json"; // SystemProgram is a reference to the Solana runtime! const { SystemProgram, Keypair } = web3; // Create a keypair for the account that will hold the GIF data. const arr = Object.values(kp._keypair.secretKey); const secret = new Uint8Array(arr); const baseAccount = web3.Keypair.fromSecretKey(secret); // Get our program's id form the IDL file. const programID = new PublicKey(idl.metadata.address); // Set our network to devent. const network = clusterApiUrl("devnet"); // Control's how we want to acknowledge when a trasnaction is "done". const opts = { preflightCommitment: "processed", }; // Change this up to be your Twitter if you want. const TWITTER_HANDLE = "_buildspace"; const TWITTER_LINK = `https://twitter.com/${TWITTER_HANDLE}`; const App = () => { // useeffect /////////////////////////////////////////// // for checkifwalletconnected function const [walletAddress, setWalletAddress] = useState(null); // for input link const [inputValue, setInputValue] = useState(""); // for the gif list const [gifList, setGifList] = useState([ "https://media.giphy.com/media/slVWEctHZKvWU/giphy.gif", "https://media.giphy.com/media/ukpwkOzk6kafXwfwbH/giphy.gif", "https://media.giphy.com/media/HtqFbL7el09oY/giphy.gif", "https://media.giphy.com/media/rAm0u2k17rM3e/giphy.gif", ]); /* * This function holds the logic for deciding if a Phantom Wallet is * connected or not */ const checkIfWalletIsConnected = async () => { try { const { solana } = window; if (solana) { if (solana.isPhantom) { console.log("Phantom wallet found!"); // Something like logging in // solana object gives us a function that will allow us to connect directly with the user's wallet! const response = await solana.connect({ onlyIfTrusted: true }); console.log( "Connected with public key:", response.publicKey.toString() ); // set user publickey in state for later use setWalletAddress(response.publicKey.toString()); } } else { alert("Solana object not found! Get a Phantom Wallet 👻"); } } catch (error) { console.error(error); } }; /* * Let's define this method so our code doesn't break. */ const connectWallet = async () => { const { solana } = window; if (solana) { const response = await solana.connect(); console.log("Connected with public key:", response.publicKey.toString()); // set user publickey in state for later use setWalletAddress(response.publicKey.toString()); } }; // handle function for the input link const onInputChange = (event) => { const { value } = event.target; setInputValue(value); }; // creating a provider which is an authenticated connection to Solana const getProvider = () => { const connection = new Connection(network, opts.preflightCommitment); const provider = new Provider( connection, window.solana, opts.preflightCommitment ); return provider; }; const createGifAccount = async () => { try { const provider = getProvider(); const program = new Program(idl, programID, provider); console.log("ping"); await program.rpc.startStuffOff({ accounts: { baseAccount: baseAccount.publicKey, user: provider.wallet.publicKey, systemProgram: SystemProgram.programId, }, signers: [baseAccount], }); console.log( "Created a new BaseAccount w/ address:", baseAccount.publicKey.toString() ); await getGifList(); } catch (error) { console.log("Error creating BaseAccount account:", error); } }; // for the submit button const sendGif = async () => { if (inputValue.length === 0) { console.log("No gif link given!"); return; } console.log("Gif link:", inputValue); try { const provider = getProvider(); const program = new Program(idl, programID, provider); await program.rpc.addGif(inputValue, { accounts: { baseAccount: baseAccount.publicKey, }, }); console.log("GIF sucesfully sent to program", inputValue); await getGifList(); } catch (error) { console.log("Error sending GIF:", error); } }; /* * We want to render this UI when the user hasn't connected * their wallet to our app yet. */ const renderNotConnectedContainer = () => ( <> <button className="cta-button connect-wallet-button" onClick={connectWallet} > Connect to Wallet </button> <p>Hi there! This is a decentralised app (dapp) that retrieves a GIF based on the link provided.</p> <p>This is my very first dapp and for visitors who have no idea what it is, let me try to explain. (Even though I'm really new to it too, so don't take my words at face value.)</p> <p>Normal internet as we know it is known as web 2. This dapp here would be considered web 3.</p> <p>Web 3 screams blockchain.</p> <p>Some of Web 3's features includes privacy + reduced censorship. Read more <a href="https://ethereum.org/en/developers/docs/web2-vs-web3/" target="_blank">here.</a></p> <p>Since this is hosted on blockchain, you would need a <a href="https://phantom.app/" target="_blank">phantom wallet</a> to make full use of this website.</p> <p>The currency being used is Solana. I'll be honest, I've never heard of it before starting this project.</p> <p>Once you connect your wallet, you'll have access to the page where you can enter the GIF link.</p> <p>When you click "GET GIF", you'll have to approve the transaction with a network fee cost.</p> <p>Once it's approved, you'll see the gif appear in the website.</p> <p>I've done it, to save you the hassle of setting up. Image below.</p> <img src="https://i.imgur.com/6ZqPwof.jpg" alt="pokegif" width="700px" height="500px"/> <p>Added 4 gifs below so visitors without wallet can at least look at some gifs...</p> <div className="gif-grid"> {/* We use index as the key instead, also, the src is now item.gifLink */} {gifList.map((item, index) => ( <div className="gif-item" key={index}> <img src={item} alt="" /> </div> ))} </div> </> ); const renderConnectedContainer = () => { // If we hit this, it means the program account hasn't be initialized. if (gifList === null) { return ( <div className="connected-container"> <button className="cta-button submit-gif-button" onClick={createGifAccount} > Do One-Time Initialization For GIF Program Account </button> </div> ); } // Otherwise, we're good! Account exists. User can submit GIFs. else { return ( <div className="connected-container"> <input type="text" placeholder="Please enter gif link!" value={inputValue} onChange={onInputChange} /> <button className="cta-button submit-gif-button" onClick={sendGif}> GET GIF </button> <div className="gif-grid"> <div className="gif-item" > <img src="https://media.giphy.com/media/HtqFbL7el09oY/giphy.gif" alt="" /> </div> {/* We use index as the key instead, also, the src is now item.gifLink */} {gifList.map((item, index) => ( <div className="gif-item" key={index}> <img src={item.gifLink} alt="" /> </div> ))} </div> </div> ); } }; // useeffects/////////////////////////////////////////////////////////////// /* * When our component first mounts, let's check to see if we have a connected * Phantom Wallet */ useEffect(() => { window.addEventListener("load", async (event) => { await checkIfWalletIsConnected(); }); }, []); const getGifList = async () => { try { const provider = getProvider(); const program = new Program(idl, programID, provider); const account = await program.account.baseAccount.fetch( baseAccount.publicKey ); console.log("Got the account", account); setGifList(account.gifList); } catch (error) { console.log("Error in getGifs: ", error); setGifList(null); } }; // whenever there is a change in walletaddress useEffect(() => { if (walletAddress) { console.log("Fetching GIF list..."); getGifList(); } }, [walletAddress]); return ( <div className="App"> <div className="container"> <div className="header-container"> <p className="header">🖼 PokeGIF</p> <p className="sub-text">PokeGIF collection in the metaverse ✨</p> {/* Add the condition to show this only if we don't have a wallet address */} {!walletAddress && renderNotConnectedContainer()} {/* if walletaddress exists, show connected container */} {walletAddress && renderConnectedContainer()} </div> <div > <img alt="Twitter Logo" className="twitter-logo" src={twitterLogo} /> <a href={TWITTER_LINK} target="_blank" rel="noreferrer" >{`built on @${TWITTER_HANDLE}`}</a> </div> <a className="footer" href="https://github.com/zyteo/gif-portal-starter" target="_blank" rel="noreferrer" >ZY signing off - ty buildspace for helping with my very first dapp!</a> </div> </div> ); }; export default App;
JavaScript
CL
839df3abafba8e3ab9112d7f7a145949b2ff0aed925e69c4a69c06fc530e8ead
import React from 'react'; import ReactMarkdown from 'react-markdown'; import { t } from 'ttag'; import ExternalLink from '../../../../../ExternalLink/ExternalLink'; import logoCopernicus from './images/logo-tooltips-copernicus.png'; const getMarkdown = () => t` **Sentinel-2** provides high-resolution images in the visible and infrared wavelengths, to monitor vegetation, soil and water cover, inland waterways and coastal areas. . **Spatial resolution:** 10m, 20m, and 60m, depending on the wavelength (that is, only details bigger than 10m, 20m, and 60m can be seen). More info [here](https://sentinel.esa.int/web/sentinel/user-guides/sentinel-2-msi/resolutions/spatial). **Revisit time:** maximum 5 days to revisit the same area, using both satellites. **Data availability:** Since June 2015. Full global coverage since March 2017. **Common usage:** Land-cover maps, land-change detection maps, vegetation monitoring, monitoring of burnt areas. `; const S2L2AMarkdown = () => t` Level 2A data are high quality data where the effects of the atmosphere on the light being reflected off of the surface of the Earth and reaching the sensor are excluded. Data are available globally since March 2017. More info about atmospheric correction [here](https://www.sentinel-hub.com/develop/api/ogc/custom-parameters/atmospheric-correction/).`; const S2L1CMarkdown = () => t` Level 1C data are data of sufficient quality for most investigations, where all image corrections were done except for the atmospheric correction. Data are available globally since June 2015 onwards.`; const Sentinel2Tooltip = () => { return ( <div> <div className="data-source-group-tooltip-description"> <ReactMarkdown source={getMarkdown()} linkTarget="_blank" /> </div> <div className="data-source-group-tooltip-credits"> <div>{t`Credits:`}</div> <div> <ExternalLink href="http://copernicus.eu/main/sentinels"> <img src={logoCopernicus} alt="Copernicus" className="data-source-group-tooltip-logo" /> </ExternalLink> </div> </div> </div> ); }; const S2L2ATooltip = () => <ReactMarkdown source={S2L2AMarkdown()} linkTarget="_blank" />; const S2L1CTooltip = () => <ReactMarkdown source={S2L1CMarkdown()} />; export { Sentinel2Tooltip, S2L1CTooltip, S2L2ATooltip };
JavaScript
CL
7de43d8cead1317cbf8ce59f4b58bd4ddd220e5e182b0dd227306b6671c33981
"use strict";var _a;Object.defineProperty(exports,"__esModule",{value:!0}),exports.BucketWebsiteTarget=void 0;const jsiiDeprecationWarnings=require("../../.warnings.jsii.js"),JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti"),core_1=require("../../core"),region_info_1=require("../../region-info");class BucketWebsiteTarget{constructor(bucket){this.bucket=bucket,jsiiDeprecationWarnings.aws_cdk_lib_aws_s3_IBucket(bucket)}bind(_record,_zone){jsiiDeprecationWarnings.aws_cdk_lib_aws_route53_IRecordSet(_record),jsiiDeprecationWarnings.aws_cdk_lib_aws_route53_IHostedZone(_zone);const{region}=core_1.Stack.of(this.bucket.stack);if(core_1.Token.isUnresolved(region))throw new Error(["Cannot use an S3 record alias in region-agnostic stacks.","You must specify a specific region when you define the stack","(see https://docs.aws.amazon.com/cdk/latest/guide/environments.html)"].join(" "));const{s3StaticWebsiteHostedZoneId:hostedZoneId,s3StaticWebsiteEndpoint:dnsName}=region_info_1.RegionInfo.get(region);if(!hostedZoneId||!dnsName)throw new Error(`Bucket website target is not supported for the "${region}" region`);return{hostedZoneId,dnsName}}}exports.BucketWebsiteTarget=BucketWebsiteTarget,_a=JSII_RTTI_SYMBOL_1,BucketWebsiteTarget[_a]={fqn:"aws-cdk-lib.aws_route53_targets.BucketWebsiteTarget",version:"2.15.0"}; //# sourceMappingURL=bucket-website-target.js.map
JavaScript
CL
b46af13e64ef0c24947b0753a60f3fa0c0a22069e3f03edd2be2d5dd0aa8ad18
var EventEmitter = require('eventemitter2').EventEmitter2 || require('eventemitter2'); var safeDeepClone = require('./safeDeepClone'); var Promise = require("promise"); var _ = require("lodash"); var createActionFunction = function(actionName, factory) { var fn = function() { var args = safeDeepClone('[Circular]', [], Array.prototype.slice.call(arguments, 0)); if (!fn._events) { throw new Error('You are triggering the action: ' + fn.handlerName + ', and nobody is listening to it yet. Remember to load up the store first'); } if (_.isFunction(factory)) { return factory.apply({}, args).then(function() { try { var newArgs = ['trigger'].concat(safeDeepClone('[Circular]', [], Array.prototype.slice.call(arguments, 0))); fn.emit.apply(fn, newArgs); } catch (e) { console.log(e); } }); } else { fn.emit.apply(fn, ['trigger'].concat(args)); return new Promise(function(resolve, reject) { resolve(); }); } }; var emitter = new EventEmitter(); // It is possible to listen to the function and to achieve that we // have to manually inherit methods from EventEmitter for (var prop in EventEmitter.prototype) { if (EventEmitter.prototype.hasOwnProperty(prop)) { fn[prop] = EventEmitter.prototype[prop]; } } // Add handlerName fn.handlerName = actionName; return fn; }; module.exports = createActionFunction;
JavaScript
CL
be140eb986dc688aff712a396c93fc455f00ff11ab20ba11c2abc02a4acaec83
/* * Copyright (c) 2009-2011 Takashi Kitao * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ function testMath() { var i, x; /* floor */ assertEquals(1.0, b9.Math.floor(1.234)); assertEquals(-2.0, b9.Math.floor(-1.234)); /* abs */ assertEquals(1.234, b9.Math.abs(1.234)); assertEquals(1.234, b9.Math.abs(-1.234)); /* min */ assertEquals(1.0, b9.Math.min(1.0, 2.0)); assertEquals(1.0, b9.Math.min(2.0, 1.0)); /* max */ assertEquals(2.0, b9.Math.max(1.0, 2.0)); assertEquals(2.0, b9.Math.max(2.0, 1.0)); /* clamp */ assertEquals(1.0, b9.Math.clamp(0.0, 1.0, 2.0)); assertEquals(1.5, b9.Math.clamp(1.5, 1.0, 2.0)); assertEquals(2.0, b9.Math.clamp(3.0, 1.0, 2.0)); /* sqrt */ assertEquals_float(0.0, b9.Math.sqrt(0.0)); assertEquals_float(2.0, b9.Math.sqrt(4.0)); /* sin_float */ assertEquals_float(0.0, b9.Math.sin_float(0.0)); assertEquals_float(1.0, b9.Math.sin_float(90.0)); assertEquals_float(-1.0, b9.Math.sin_float(630.0)); assertEquals_float(-1.0, b9.Math.sin_float(-90.0)); assertEquals_float(1.0, b9.Math.sin_float(-630.0)); /* cos_float */ assertEquals_float(0.0, b9.Math.cos_float(90.0)); assertEquals_float(-1.0, b9.Math.cos_float(180.0)); assertEquals_float(1.0, b9.Math.cos_float(720.0)); assertEquals_float(-1.0, b9.Math.cos_float(-180.0)); assertEquals_float(1.0, b9.Math.cos_float(-720.0)); /* sin_int */ assertEquals_float(0.0, b9.Math.sin_int(0.0)); assertEquals_float(1.0, b9.Math.sin_int(90.0)); assertEquals_float(-1.0, b9.Math.sin_int(630.0)); assertEquals_float(-1.0, b9.Math.sin_int(-90.0)); assertEquals_float(1.0, b9.Math.sin_int(-630.0)); /* cos_int */ assertEquals_float(0.0, b9.Math.cos_int(90.0)); assertEquals_float(-1.0, b9.Math.cos_int(180.0)); assertEquals_float(1.0, b9.Math.cos_int(720.0)); assertEquals_float(-1.0, b9.Math.cos_int(-180.0)); assertEquals_float(1.0, b9.Math.cos_int(-720.0)); /* asin */ assertEquals_float(0.0, b9.Math.asin(0.0)); assertEquals_float(90.0, b9.Math.asin(1.0)); assertEquals_float(-90.0, b9.Math.asin(-1.0)); /* acos */ assertEquals_float(90.0, b9.Math.acos(0.0)); assertEquals_float(0.0, b9.Math.acos(1.0)); assertEquals_float(180.0, b9.Math.acos(-1.0)); /* atan2 */ assertEquals_float(0.0, b9.Math.atan2(0.0, 1.0)); assertEquals_float(90.0, b9.Math.atan2(2.0, 0.0)); assertEquals_float(180.0, b9.Math.atan2(0.0, -3.0)); assertEquals_float(-90.0, b9.Math.atan2(-4.0, 0.0)); /* random_int */ for (i = 0; i < 10; i++) { x = b9.Math.random_int(-1, 1); assertTrue(x === -1 || x === 0 || x === 1); } for (i = 0; i < 10; i++) { x = b9.Math.random_int(3, 5); assertTrue(x === 3 || x === 4 || x === 5); } for (i = 0; i < 10; i++) { x = b9.Math.random_int(-3, -5); assertTrue(x === -3 || x === -4 || x === -5); } /* random_float */ for (i = 0; i < 10; i++) { x = b9.Math.random_float(-0.5, 0.5, 0.5); assertTrue(x === -0.5 || x === 0.0 || x === 0.5); } for (i = 0; i < 10; i++) { x = b9.Math.random_float(3.5, 4.5, 0.5); assertTrue(x === 3.5 || x === 4.0 || x === 4.5); } for (i = 0; i < 10; i++) { x = b9.Math.random_float(-3.5, -4.5, -0.5); assertTrue(x === -3.5 || x === -4.0 || x === -4.5); } /* lerp */ assertEquals_float(0.0, b9.Math.lerp(0.0, 2.0, -1.0)); assertEquals_float(1.0, b9.Math.lerp(0.0, 2.0, 0.5)); assertEquals_float(2.0, b9.Math.lerp(0.0, 2.0, 2.0)); /* equals_float */ assertTrue(b9.Math.equals_float(1.0, 1.0 + b9.Math.EPSILON * 0.99)); assertTrue(b9.Math.equals_float(1.0, 1.0 - b9.Math.EPSILON * 0.99)); assertFalse(b9.Math.equals_float(1.1, 2.0)); assertFalse(b9.Math.equals_float(1.0, 2.1)); /* EPSILON */ assertEquals(0.0001, b9.Math.EPSILON); /* PI */ assertEquals_float(3.14159265358979, b9.Math.PI); /* DEG_TO_RAD */ assertEquals_float(b9.Math.PI / 180.0, b9.Math.DEG_TO_RAD); /* RAD_TO_DEG */ assertEquals_float(180.0 / b9.Math.PI, b9.Math.RAD_TO_DEG); }
JavaScript
CL
998dc96971b0a55386c2196b9c8a19a51b68cabf0a078001622a2d94a5895452
const assert = require('assert'); const moment = require('moment'); const request = require('supertest'); const app = require('../../src/app'); const models = require('../../src/models'); const { createUserToken } = require('../../src/routes/auth'); const TestUtil = require('../util'); describe('API update', () => { let trip; let user; beforeEach(async () => { trip = await TestUtil.createDummyTrip(); user = await TestUtil.createDummyUser(trip.orgId); await trip.update({ values: { existing: true, outer: { one: 2 } } }); }); describe('PATCH /api/trips/:id', () => { it('updates values with shallow merge', () => { return request(app) .patch(`/api/trips/${trip.id}`) .set('Authorization', `Bearer ${createUserToken(user, 10)}`) .set('Accept', 'application/json') .send({ values: { outer: { inner: 'value' } } }) .expect(200) .then(async (res) => { // Test set in DB await trip.reload(); assert.deepStrictEqual(trip.values, { existing: true, outer: { inner: 'value' } }); // Test updated in response assert.deepStrictEqual(res.body.data.trip.values, { existing: true, outer: { inner: 'value' } }); }); }); it('updates values with shallow merge on non-matching type', async () => { await trip.update({ values: { outer: 'string' } }); return request(app) .patch(`/api/trips/${trip.id}`) .set('Authorization', `Bearer ${createUserToken(user, 10)}`) .set('Accept', 'application/json') .send({ values: { outer: { inner: 'value' } } }) .expect(200) .then(async (res) => { assert.deepStrictEqual(res.body.data.trip.values, { outer: { inner: 'value' } }); }); }); }); describe('PATCH /api/messages/:id', () => { let message; beforeEach(async () => { message = await models.Message.create({ orgId: trip.orgId, tripId: trip.id, fromRoleName: 'from', toRoleName: 'to', createdAt: moment.utc(), name: 'hi', medium: 'text', content: 'hi there', isInGallery: false, isArchived: false }); }); it('allows change to permitted fields', () => { const now = moment.utc(); const permittedFields = [ ['isInGallery', true, true], ['isArchived', true, true], ['replyReceivedAt', now, now.toISOString()] ]; return Promise.all(permittedFields.map(([fieldName, val, valResp]) => { return request(app) .put(`/api/messages/${message.id}`) .set('Authorization', `Bearer ${createUserToken(user, 10)}`) .set('Accept', 'application/json') .send({ [fieldName]: val }) .expect(200) .then(async (res) => { assert.strictEqual(res.body.data.message[fieldName], valResp); }); })); }); it('forbids changes to any other field', () => { const forbiddenFields = [ 'fromRoleName', 'toRoleName', 'name', 'medium', 'content' ]; return Promise.all(forbiddenFields.map(fieldName => { return request(app) .put(`/api/messages/${message.id}`) .set('Authorization', `Bearer ${createUserToken(user, 10)}`) .set('Accept', 'application/json') .send({ [fieldName]: 'does not matter' }) .expect(403) .then((res) => { assert.deepStrictEqual(res.body.error, { type: 'ForbiddenError', message: `Action 'update' on field '${fieldName}' of record ` + `'message #${message.id}' by 'test@test.com' denied.` }); }); })); }); }); });
JavaScript
CL
e0ca8f0af71303ff6f18b1e12eace60d401e18a6d07e46168f81d443eab06ddb
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ let ErrorParser = { getMessage (errorXML) { let errors = []; errors = Array.prototype.slice.call(errorXML.getElementsByTagName('error')) .map(error => { return { code: error.getElementsByTagName('code')[0].textContent, message: error.getElementsByTagName('message')[0].textContent }; }) .sort((a, b) => { return parseInt(a.code, 10) - parseInt(b.code, 10); }) // removes duplicate error messages .filter((item, pos, array) => { return !pos || (item.code != (array[pos - 1] && array[pos - 1].code)); }) // removes not so helpful `Internal Server Error` .filter(error => { return error.code != 1001; }); if (errors && errors.length == 0) { errors[0] = {}; errors[0].code = 500; errors[0].message = 'Oh snap! Something went wrong. Please try again later.'; } return errors; } }; export default ErrorParser;
JavaScript
CL
080443a2a39956376ab1b0f8c744632626ce2deaa11193229e9d01c101c4e90b
//Call lineChart function to draw charts lineChart("linechart-2-container", "linechart-2", "linechart2-data.csv", "number of consumers"); lineChart("linechart-3-container", "linechart-3", "linechart3-data.csv", "total balances ($b)", "dollar"); /** * Creates a d3.js Line Chart * @param {String} containerID - ID of container div * @param {String} chartID - ID of chart dic * @param {String} dataLoc - Filename of csv data file (extension included) * @param {String} yLabel - Y axis label * @param {String} yFormat (optional) - Specifies the y axis format **/ function lineChart(containerID, chartID, dataLoc, yLabel, yFormat) { //Initialize Variables var lineContainerWidth, lineContainerHeight, lineMargin, lineWidth, lineHeight; //Assign chart specific variables var chartSelector = d3.select("#"+chartID); var dataLocation = dataLoc; //Find width of chart container and update dimensions lineContainerMargin = $("#"+chartID).offset().left; lineContainerWidth = $("#"+containerID).width(); // lineChartHeight = $("#"+chartID).height(); // console.log("lineChartHeight is: "+lineChartHeight); updateDimensions(lineContainerWidth); //Formats var parseTime = d3.timeParse("%y"); var percentage = d3.format(".0%"); var dollar = d3.format("$,.0f"); var thousand = d3.format(",.0f"); //Returns value in our array of data that corresponds to the horizontal position of the mouse pointer var bisectPoint = d3.bisector(function(d) { return d.year; }).left; //Set the scales with ranges - possible area to render chart in pixels var x = d3.scaleLinear().range([0, lineWidth]); var y = d3.scaleLinear().range([lineHeight, 0]); //Define the line generator var lineGen = d3.line() .x(function(d) { return x(d.year); }) .y(function(d) { return y(d.value); }); // append the svg obgect to the body of the page // appends a 'group' element to 'svg' // moves the 'group' element to the top left margin // var svg = chartSelector.append("svg") // .attr("width", lineWidth + lineMargin.left + lineMargin.right) // .attr("height", lineHeight + lineMargin.top + lineMargin.bottom) // .style("background-color", "#fff") // .append("g") // .attr("transform", // "translate(" + lineMargin.left + "," + lineMargin.top + ")"); /////////////////////////////////////////////////////////////////// // CURRENTLY IN DEVELOPMENT: modification to make svg responsive // /////////////////////////////////////////////////////////////////// var svg = chartSelector.append("div") .classed("svg-container", true) //container class to make it responsive .append("svg") .style("background-color", "#fff") //responsive SVG needs these 2 attributes and no width and height attr .attr("preserveAspectRatio", "xMinYMin meet") .attr("viewBox", "0 0 " + (lineWidth + lineMargin.left + lineMargin.right) + " " + (lineHeight + lineMargin.top + lineMargin.bottom)) //class to make it responsive .classed("svg-content-responsive", true) .append("g") .attr("transform", "translate(" + lineMargin.left + "," + lineMargin.top + ")"); // Get the data and loop through each data point d3.csv("data/"+dataLocation, function(error, data) { //Format the data // data.forEach(function(d) { // d.value = +d.value; // d.year = +d.year; // d.label = +d.label; // }); //Scale the domains - minimum and maximum values of axes x.domain([2011,2016]); y.domain([0, d3.max(data, function(d) { return Math.max(d.value)*1.15; })]); //Draw x axis and labels svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + lineHeight + ")") .call( d3.axisBottom(x) .ticks(5) .tickFormat(d3.format("d")) ) .selectAll("text") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", "rotate(-65)"); //Draw y axis var yAxis = svg.append("g") .attr("class", "y axis") .call( d3.axisLeft(y) .ticks(5) ); //Format y axis is yFormat is included if (yFormat === "dollar") { yAxis.call( d3.axisLeft(y) .ticks(5) .tickFormat(dollar) ); } //Draw y axis label svg.append("text") .attr("class", "y-label") .attr("text-anchor", "end") .attr("y", 6) .attr("dy", ".75em") .attr("transform", "rotate(-90)") .text(yLabel); //Draw vertical grid svg.append("g") .attr("class", "grid vert-grid") .attr("transform", "translate(0," + lineHeight + ")") .call( d3.axisBottom(x) .ticks(5) .tickSize(-lineHeight, 0, 0) .tickFormat(d3.format("d")) ); //Draw horizontal grid svg.append("g") .attr("class", "grid hor-grid") .attr("id", chartID+"-y-grid") .call( d3.axisLeft(y) .tickSize(-lineWidth, 0, 0) .tickFormat("") ); //Use lineGen to draw line 1 var line1 = svg.append("path") .data([data]) .attr("class", "line") .attr("id", chartID+"-line") .attr("d", lineGen); //Find length of line 1 var totalLength = line1.node().getTotalLength(); //Hide line by default using offset line1 .attr("stroke-dasharray", totalLength + " " + totalLength) .attr("stroke-dashoffset", totalLength) //Initialize hidden tooltip var lineTooltip = chartSelector.append("div") .attr("class", "tooltip") .style("display", "none"); //// //Transition events to fire when chart element is visible - uses Waypoints.js //// var waypoint = new Waypoint({ element: document.getElementById(chartID), handler: function() { //Transition for line to appear line1.transition() .duration(2000) .attr("stroke-dashoffset", 0); //Transition for line points to appear linePoints.transition() .duration(2000) .style("opacity","1"); }, offset: 'bottom-in-view' }); //Draw line points var linePoints = svg.selectAll("dot") .data(data) .enter().append("circle") .attr("class", "line-point") // .style("opacity", "0") .attr("r", 5) .attr("cx", function(d) { return x(d.year); }) .attr("cy", function(d) { return y(d.value); }) .on("mouseover", function(d, event) { lineTooltip.transition() .duration(100) .style("display", "inline") .style("opacity", .9); //Change tooltip content based on chart if(chartID === "linechart-2") { lineTooltip.html("<strong>Q3 "+d.year+"</strong><br>"+thousand(d.value)+" consumers") .style("left", x(d.year) + "px") .style("top", y(d.value) + "px"); } else if (chartID === "linechart-3") { lineTooltip.html("<strong>Q3 "+d.year+"</strong><br>"+dollar(d.value)+" billion") .style("left", (x(d.year)) + "px") .style("top", (y(d.value)) + "px"); } }) .on("mouseout", function(d) { lineTooltip.transition() .duration(500) .style("opacity", 0); }) .on("mouseleave", function() { lineTooltip.transition() .duration(500) .style("opacity", 0); }); ////////////////////////////////////// // REMOVED AREA CAPTURE FOR Q3 2016 // ////////////////////////////////////// // //Append the area to capture mouse hover // svg.append("rect") // .attr("class", "hover-area") // .attr("width", lineWidth) // .attr("height", lineHeight) // .style("fill", "none") // .style("pointer-events", "all") // .on("mouseover", function() { focus.style("display", null); }) // .on("mouseout", function() { focus.style("display", "none"); }) // .on("mousemove", mousemove); // //Initialize tooltip focus 1 // var focus = svg.append("g") // .attr("class", "lineCircle") // .style("display", "none"); // //Mousemove function // function mousemove() { // //Variables for tooltip circle 1 // var x0 = x.invert(d3.mouse(this)[0]), // i = bisectPoint(data, x0, 1), // d0 = data[i - 1], // d1 = data[i], // d = x0 - d0.year > d1.year - x0 ? d1 : d0; // focus.select("circle.y") // .attr("transform","translate(" + x(d.year) + "," + y(d.value) + ")"); // } //end mousemove // //append circle 1 at the intersection // focus.append("circle") // // .data(data) // .attr("class", "y") // .style("fill", "#fff") // .style("stroke", "#00A6CA") // .attr("r", 6) // //Circle Tooltip Events // .on("mouseover", function(d) { // //fixes bug that flickers circle // focus.style("display", "inline"); // lineTooltip.transition() // // .style("opacity", 0.9) // .style("display", "inline"); // }) //Draw dotted line on 15 million line **Tick Hack** if(chartID === "linechart-2") { $("#"+chartID+" g.y.axis g.tick:nth-child(5) line").attr("x2", lineWidth).attr("stroke-dasharray","5, 5").attr("opacity","0.3"); } //Draw dotted line on $100 billion line **Tick Hack** if (chartID === "linechart-3") { $("#"+chartID+"-y-grid g.tick:nth-child(12)").attr("class", "tick zero-axis dotted"); } }); //end data function updateDimensions(contWidth) { //Declare margins and height of svg container lineMargin = {top: 10, right: 50, bottom: 80, left: 125}, lineWidth = contWidth - lineMargin.left - lineMargin.right, lineHeight = contWidth - lineMargin.top - lineMargin.bottom; } } // })(window,d3); //end linechart 2 //Document Ready $(document).ready(function() { })
JavaScript
CL
d6b3be83d6109fe6253891fceb7cb115f9079affd7d9aeccb0380953733a3135
import React from "react"; class ThinktankSection1 extends React.Component { render() { return ( <section id="section-2-113" className="ct-section" style={{ background: "#eff4f7" }} > <div className="ct-section-inner-wrap"> <div id="fancy_icon-3-113" className="ct-fancy-icon"> <svg id="svg-fancy_icon-3-113"> <use xlinkHref="#Lineariconsicon-heart-pulse" /> </svg> </div> <h1 id="headline-4-113" className="ct-headline atomic-primary-heading" > Think Tank </h1> <div id="text_block-5-113" className="ct-text-block atomic-subheading" > Nutritank stemming from –<i>a Nutritional think tank</i>. Set up by medical students with grassroot research and action. <br /> </div> <div id="div_block-17-113" className="ct-div-block"> <div id="div_block-21-113" className="ct-div-block" /> <nav id="_nav_menu-397-113" className="oxy-nav-menu oxy-nav-menu-dropdowns oxy-nav-menu-dropdown-arrow oxy-nav-menu-vertical" > <div className="oxy-menu-toggle"> <div className="oxy-nav-menu-hamburger-wrap"> <div className="oxy-nav-menu-hamburger"> <div className="oxy-nav-menu-hamburger-line" /> <div className="oxy-nav-menu-hamburger-line" /> <div className="oxy-nav-menu-hamburger-line" /> </div> </div> </div> <div className="menu-think-tank-container"> <ul id="menu-think-tank" className="oxy-nav-menu-list"> <li id="menu-item-181" className="menu-item menu-item-type-custom menu-item-object-custom menu-item-181" > <a href="#aim" data-ps2id-api="true"> Current Aim </a> </li> <li id="menu-item-182" className="menu-item menu-item-type-custom menu-item-object-custom menu-item-182" > <a href="#film" data-ps2id-api="true"> Describing our Work </a> </li> <li id="menu-item-183" className="menu-item menu-item-type-custom menu-item-object-custom menu-item-183" > <a href="#ourwork" data-ps2id-api="true"> Our Work  </a> </li> <li id="menu-item-184" className="menu-item menu-item-type-custom menu-item-object-custom menu-item-184" > <a href="#panel" data-ps2id-api="true"> Think Tank Panel </a> </li> <li id="menu-item-185" className="menu-item menu-item-type-custom menu-item-object-custom menu-item-185" > <a href="#experts" data-ps2id-api="true"> Supporting Experts </a> </li> <li id="menu-item-186" className="menu-item menu-item-type-custom menu-item-object-custom menu-item-186" > <a href="#orgs" data-ps2id-api="true" style={{ textAlign: "left" }} > Organisations who Share our Vision </a> </li> <li id="menu-item-187" className="menu-item menu-item-type-custom menu-item-object-custom menu-item-187" > <a href="#faq" data-ps2id-api="true"> FAQ </a> </li> <li id="menu-item-188" className="menu-item menu-item-type-custom menu-item-object-custom menu-item-188" > <a href="#archive" data-ps2id-api="true"> Archive </a> </li> </ul> </div> </nav> </div> </div> </section> ); } } export default ThinktankSection1;
JavaScript
CL
37f700cf792ad25701cb791352cfa43a57a8bd3e07949cb61399dc0764896c15
/* jshint node: true */ 'use strict'; var util = require('util'), EventEmitter = require('events').EventEmitter, WebSocket = require('ws'), _ = require('busyman'), RPC = require('freebird-constants').RPC; var TIMEOUT_RSP_CODE = 8, REQ_TIMEOUT_SEC = 10; function Client (addr, options, nativeWs) { var self = this, transId = 0; if (arguments.length === 1 || _.isNil(options)) options = {}; if (!_.isString(addr)) throw new Error('addr must ba a string'); if (!_.isObject(options)) throw new Error('options must ba an object'); if (nativeWs) { WebSocket = nativeWs; this._wsClient = new WebSocket(addr, 'my-custom-protocol', options); } else { this._wsClient = new WebSocket(addr, options); } this._connected = false; this._wsClient.onopen = function () { self._connected = true; self.emit('open'); }; this._wsClient.onclose = function (event) { self._connected = false; self.emit('close', event.code, event.reason); }; this._wsClient.onerror = function (event) { self.emit('error', event); }; this._wsClient.onmessage = function (event) { var msg, type, evt; try { msg = JSON.parse(event.data); } catch (e) { return; // ignore bad message } if (msg.__intf === 'RSP') { evt = msg.subsys + '_' + msg.cmd + ':' + msg.seq; self.emit(evt, msg.status, msg.data); } else if (msg.__intf === 'IND') { var subsys = msg.subsys; delete msg.__intf; if (subsys === 'net' || subsys === RPC.Subsys.net) msg.subsys = 'net'; else if (subsys === 'dev' || subsys === RPC.Subsys.dev) msg.subsys = 'dev'; else if (subsys === 'gad' || subsys === RPC.Subsys.gad) msg.subsys = 'gad'; self.emit('ind', msg); } }; this._nextTransId = function () { if (transId > 255) transId = 0; return transId++; }; } util.inherits(Client, EventEmitter); Client.prototype.send = function (subsys, cmd, args, callback) { var self = this, evt, reqMsg = { __intf: 'REQ', subsys: subsys, seq: self._nextTransId(), id: (args.id) ? args.id : null, cmd: cmd, args: args }, timeoutCntl, rspListener; if (!_.isString(subsys)) throw new TypeError('subsys must ba a string'); if (!_.isString(cmd)) throw new TypeError('cmd must ba a string'); if (!_.isPlainObject(args)) throw new TypeError('args must ba an object'); if (!_.isFunction(callback)) throw new TypeError('callback must ba a function'); if (!this._connected) { setImmediate(callback, new Error('wsClient connection is closed.')); } else { evt = subsys + '_' + cmd + ':' + reqMsg.seq; rspListener = function (status, data) { callback(null, { status: status, data: data }); }; // [TODO] timeout seconds? how to define a reasonable time timeoutCntl = setTimeout(function () { self.emit(evt, TIMEOUT_RSP_CODE, {}); // { status: 'timeout', data: {} } }, REQ_TIMEOUT_SEC * 1000); this.once(evt, rspListener); this._wsClient.send(JSON.stringify(reqMsg)); } }; module.exports = Client;
JavaScript
CL
7ab4ea4838c1c45f07424606ec449c2d57b6fc1c7c2aee88b42260d8a9a8b022
/** * * Update on 12-DEC-2019 Unlike some other modes like CBC, GCM mode does not require the IV to be unpredictable. The only requirement is that the IV has to be unique for each invocation with a given key. If it repeats once for a given key, security can be compromised. An easy way to achieve this is to use a random IV from a strong pseudo random number generator as shown below. Using a sequence or timestamp as IV is also possible, but it may not be as trivial as it may sound. For example, if the system does not correctly keep track of the sequences already used as IV in a persistent store, an invocation may repeat an IV after a system reboot. Likewise, there is no perfect clock. Computer clocks readjusts etc. Also, the key should be rotated after every 2^32 invocations. For further details on the IV requirement, refer to this answer and the NIST recommendations. Update on 30-JUL-2019 As the answer is getting more views and votes, I think it is worth mentioning that the code below has used a *Sync method - crypto.scryptSync. Now that is fine if the encryption or decryption is done during application initialization. Otherwise, consider using the asynchronous version of the function to avoid blocking the event loop. (A promise library like bluebird is useful). Update on 23-JAN-2019 The bug in decryption logic has been fixed. Thanks @AlexisWilke for rightly pointing it out. The accepted answer is 7 years old and doesn't look secured today. Hence, I'm answering it: Encryption Algorithm: Block cipher AES with 256 bits key is considered secure enough. To encrypt a complete message, a mode needs to be selected. Authenticated encryption (which provides both confidentiality and integrity) is recommended. GCM, CCM and EAX are most commonly used authenticated encryption modes. GCM is usually preferred and it performs well in Intel architectures which provide dedicated instructions for GCM. All these three modes are CTR-based (counter-based) modes and therefore they do not need padding. As a result they are not vulnerable to padding related attacks An initialization Vector (IV) is required for GCM. The IV is not a secret. The only requirement being it has to be random or unpredictable. In NodeJs, crypto.randomBytes() is meant to produce cryptographically strong pseudo random numbers. NIST recommends 96 bit IV for GCM to promote interoperability, efficiency, and simplicity of design The recipient needs to know the IV to be able to decrypt the cipher text. Therefore the IV needs to be transferred along with the cipher text. Some implementations send the IV as AD (Associated Data) which means that the authentication tag will be calculated on both the cipher text and the IV. However, that is not required. The IV can be simply pre-pended with the cipher text because if the IV is changed during transmission due to a deliberate attack or network/file system error, the authentication tag validation will fail anyway Strings should not be used to hold the clear text message, password or the key as Strings are immutable which means we cannot clear the strings after use and they will linger in the memory. Thus a memory dump can reveal the sensitive information. For the same reason, the client calling these encryption or decryption methods should clear all the Buffer holding the message, key or the password after they are no longer needed using bufferVal.fill(0). Finally for transmission over network or storage, the cipher text should be encoded using Base64 encoding. buffer.toString('base64'); can be used to convert the Buffer into Base64 encoded string. Note that the key derivation scrypt (crypto.scryptSync()) has been used to derive a key from a password. However, this function is available only in Node 10.* and later versions The code goes here: */ const crypto = require('crypto'); var exports = module.exports = {}; const ALGORITHM = { /** * GCM is an authenticated encryption mode that * not only provides confidentiality but also * provides integrity in a secured way * */ BLOCK_CIPHER: 'aes-256-gcm', /** * 128 bit auth tag is recommended for GCM */ AUTH_TAG_BYTE_LEN: 16, /** * NIST recommends 96 bits or 12 bytes IV for GCM * to promote interoperability, efficiency, and * simplicity of design */ IV_BYTE_LEN: 12, /** * Note: 256 (in algorithm name) is key size. * Block size for AES is always 128 */ KEY_BYTE_LEN: 32, /** * To prevent rainbow table attacks * */ SALT_BYTE_LEN: 16 } const getIV = () => crypto.randomBytes(ALGORITHM.IV_BYTE_LEN); exports.getRandomKey = getRandomKey = () => crypto.randomBytes(ALGORITHM.KEY_BYTE_LEN); /** * To prevent rainbow table attacks * */ exports.getSalt = getSalt = () => crypto.randomBytes(ALGORITHM.SALT_BYTE_LEN); /** * * @param {Buffer} password - The password to be used for generating key * * To be used when key needs to be generated based on password. * The caller of this function has the responsibility to clear * the Buffer after the key generation to prevent the password * from lingering in the memory */ exports.getKeyFromPassword = getKeyFromPassword = (password, salt) => { return crypto.scryptSync(password, salt, ALGORITHM.KEY_BYTE_LEN); } /** * * @param {Buffer} messagetext - The clear text message to be encrypted * @param {Buffer} key - The key to be used for encryption * * The caller of this function has the responsibility to clear * the Buffer after the encryption to prevent the message text * and the key from lingering in the memory */ exports.encrypt = encrypt = (messagetext, key) => { const iv = getIV(); const cipher = crypto.createCipheriv( ALGORITHM.BLOCK_CIPHER, key, iv, { 'authTagLength': ALGORITHM.AUTH_TAG_BYTE_LEN }); let encryptedMessage = cipher.update(messagetext); encryptedMessage = Buffer.concat([encryptedMessage, cipher.final()]); return Buffer.concat([iv, encryptedMessage, cipher.getAuthTag()]); } /** * * @param {Buffer} ciphertext - Cipher text * @param {Buffer} key - The key to be used for decryption * * The caller of this function has the responsibility to clear * the Buffer after the decryption to prevent the message text * and the key from lingering in the memory */ exports.decrypt = decrypt = (ciphertext, key) => { const authTag = ciphertext.slice(-16); const iv = ciphertext.slice(0, 12); const encryptedMessage = ciphertext.slice(12, -16); const decipher = crypto.createDecipheriv( ALGORITHM.BLOCK_CIPHER, key, iv, { 'authTagLength': ALGORITHM.AUTH_TAG_BYTE_LEN }); decipher.setAuthTag(authTag); let messagetext = decipher.update(encryptedMessage); messagetext = Buffer.concat([messagetext, decipher.final()]); return messagetext; } /** * And the unit tests are also provided below: */ const assert = require('assert'); const cryptoUtils = require('../lib/crypto_utils'); describe('CryptoUtils', function() { describe('decrypt()', function() { it('should return the same mesage text after decryption of text encrypted with a randomly generated key', function() { let plaintext = 'my message text'; let key = cryptoUtils.getRandomKey(); let ciphertext = cryptoUtils.encrypt(plaintext, key); let decryptOutput = cryptoUtils.decrypt(ciphertext, key); assert.equal(decryptOutput.toString('utf8'), plaintext); }); it('should return the same mesage text after decryption of text excrypted with a key generated from a password', function() { let plaintext = 'my message text'; /** * Ideally the password would be read from a file and will be in a Buffer */ let key = cryptoUtils.getKeyFromPassword(Buffer.from('mysecretpassword'), cryptoUtils.getSalt()); let ciphertext = cryptoUtils.encrypt(plaintext, key); let decryptOutput = cryptoUtils.decrypt(ciphertext, key); assert.equal(decryptOutput.toString('utf8'), plaintext); }); }); }); import crypto from 'crypto'; var algorithm = "aes-192-cbc"; //algorithm to use const key = crypto.scryptSync(secretKey, 'salt', 24); //create key 24 export function encryptFx(info) { const iv = crypto.randomBytes(12); // generate different ciphertext everytime 16 const cipher = crypto.createCipheriv(algorithm, key, iv); var encrypted = cipher.update(JSON.stringify(info), 'utf8', 'hex') + cipher.final('hex'); // encrypted text return `${iv.toString('hex')}+${encrypted}`; } export function decryptFx(enc) { const _tb = enc.split('+'); console.log("info : ",_tb) let [iv,encrypted] = _tb; console.log("info : ",iv) const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(iv)); var decrypted = decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8'); //deciphered text return JSON.parse(decrypted); }
JavaScript
CL
09d844c92b591022c6a5519e4efbc145f4174e1ab6ff65322511c09155928455
/** * Electron 共用函式 * * Usage: * 1.Main Process: * const myElectron = require('./modules/myElectron'); * * 2.Renderer Process: * const {remote} = require('electron'); * const myElectron = remote.require('./modules/myElectron'); * * Created by 阿友 on 2021/02/23 */ let consoleTitle = '[/app/common/myElectron.js]'; const {BrowserWindow, Notification, dialog, screen, shell, clipboard} = require('electron'); //const si = require('systeminformation'); //第三方套件可以取得系統相關資訊 const {browserWindows, isEnableDevTools} = require('./myConfig'); //region browserWindow /** * 建立視窗 * * @param opts * @param opts.winName 視窗名稱 * @param opts.url 視窗載入檔的路徑,eg: file://${appFolderPath()}/form_map_list.html * @param [opts.frame=true] 視窗邊框 * @param [opts.show=true] 視窗顯示 * @param [opts.winTitle=null] 視窗標題 * @param [opts.width=750] 視窗寬 * @param [opts.height=500] 視窗高 * @param [opts.minWidth=750] 視窗最小寬 * @param [opts.minHeight=500] 視窗最小高 * @param [opts.parent] 父層BrowserWindow * @param [opts.hideMenu=false] 隱藏主選單 * @param [opts.resizable=true] 視窗縮放大小 * @param [opts.minimizable=false] 視窗最小化 * @param [opts.maximizable=false] 視窗最大化 * @param [opts.alwaysOnTop=false] 視窗顯示於最上層 * @param [opts.modal] 視窗設為Modal * @param [opts.backgroundColor=#ffffff] 視窗背景色 * @param [opts.isEnableDevTools=false] 開啟DevTools功能 * @param [opts.openDevTools=false] 開啟DevTools視窗 * * @param [opts.onLoad] 回呼-頁面載入時 * @param [opts.onClose] 回呼-頁面關閉時 * */ let createBrowserWindows = async (opts) => { let consoleTitle2 = consoleTitle + '[createBrowserWindows]'; let width = opts.width || 750; let height = opts.height || 500; let minWidth = opts.minWidth || width; let minHeight = opts.minHeight || height; let onLoad = typeof opts.onLoad === 'function' ? opts.onLoad : (evt) => { }; let onClose = typeof opts.onClose === 'function' ? opts.onClose : () => { this.win = null; }; //過濾變數值並返回 let getValue = (obj, defValue) => typeof obj === "undefined" ? defValue : obj; let frame = getValue(opts.frame, true); let show = getValue(opts.show, true); let resizable = getValue(opts.resizable, true); let minimizable = getValue(opts.minimizable, false); let maximizable = getValue(opts.maximizable, true); let alwaysOnTop = getValue(opts.alwaysOnTop, false); let isEnableDevTools = getValue(opts.isEnableDevTools, false); let openDevTools = getValue(opts.openDevTools, false); let hideMenu = getValue(opts.hideMenu, false); let modal = getValue(opts.modal, false); let win = new BrowserWindow({ backgroundColor: opts.backgroundColor || '#ffffff', //背景色 width: width, height: height, minWidth: minWidth, //最小寬 minHeight: minHeight, //最小高 frame: frame, //有邊框 show: show, //先隱藏 resizable: resizable, minimizable: minimizable, maximizable: maximizable, alwaysOnTop: alwaysOnTop, //將視窗顯示在最上層 (PS: 不可設否則 Win10 Explorer會被蓋在下面) parent: opts.parent || null, //父層 modal: modal, //Modal模式 webPreferences: { devTools: isEnableDevTools, //關閉開發工具 contextIsolation: false, nodeIntegration: true, enableRemoteModule: true //開啟 Renderer 可以使用 remote 方法 } }); if (hideMenu) win.setMenu(null); //PS: 隱藏選單 (macOS 不會消失,win10會消失) if (openDevTools) win.openDevTools(); //開啟 DevTools (Mac - Alt+Command+I) //PS: 註冊視窗 const winid = win.webContents.id; const winName = opts.winName; browserWindows.add(winName, winid); //console.log(consoleTitle2, 'webContents.id:', winid, ',global.BrowserWindows:', browserWindows.list()); //console.log(consoleTitle2, 'webContents.id:', winid, ',global.BrowserWindows:', browserWindows.find(opts.winName)); consoleTitle2 += `[${winName}]`; //.................................................................................... //region 註冊事件 onLoad = onLoad.bind({win}); onClose = onClose.bind({win}); //攔截html的視窗標題異動 win.on('page-title-updated', function (e) { let constTitle3 = consoleTitle2 + '[win.on][page-title-updated]'; e.preventDefault(); }); if (opts.winTitle) win.setTitle(opts.winTitle); //變更視窗標題 //一個框架中的文字載入完成後觸發該事件 win.webContents.on('did-finish-load', onLoad); //視窗關閉中 win.on('close', onClose); //視窗已關閉(win已被催毀) win.on('closed', () => { console.log(consoleTitle2, '[closed]'); }) //endregion //.................................................................................... //PS: 載入頁面 await win.loadURL(opts.url); //console.log(consoleTitle2, 'done'); return win; } //endregion //region clipboard /** * 複制文字放到剪貼板 * * @param text */ let copyTextToClipboard = function (text) { clipboard.writeText(text); } //endregion //region Shell /** * shell - Browser 開啟網址 - ok * * @param url 網址 * @return {Promise<void>} */ let shellOpenExternal = async (url) => { await shell.openExternal(url); } /** * shell - 將 目錄/檔案 丟到垃圾桶 - ok * * @param itemPath 完整目錄/檔案位置 */ let shellMoveItemToTrash = async function (itemPath) { let consoleTitle2 = consoleTitle + '[shellMoveItemToTrash]'; console.log(consoleTitle2, itemPath); //`${app.getAppPath()}/server/8/world` await shell.trashItem(itemPath); } let shellOpenUrl = function (url) { let consoleTitle2 = consoleTitle + '[shellOpenUrl]'; console.log(consoleTitle2, url); shell.openExternal(url); //PS: 開啟網頁 } /** * shell - 檔案總管 開啟 目錄 - ok * * @param folderPath 完整目錄/檔案位置 */ let shellOpenFolderPath = async function (folderPath) { let consoleTitle2 = consoleTitle + '[shellOpenFolderPath]'; console.log(consoleTitle2, folderPath); //`${app.getAppPath()}/server/8/world` //await shell.openPath(folderPath); await shell.showItemInFolder(folderPath); } //endregion /** * 取 [螢幕] 相關資訊 * * @return {Promise<{curScreenPoint: Electron.Point, curDisplay: Electron.Display, externalDisplay: T[], displays: Electron.Display[]}>} */ let getDisplays = async function () { let consoleTitle2 = consoleTitle + '[getDisplayScreens]'; //全部螢幕清單 const displays = screen.getAllDisplays(); //Array //console.log(consoleTitle2, 'displays:', displays); //取 [主要螢幕] const primaryDisplay = screen.getPrimaryDisplay(); //Object //console.log(consoleTitle2, 'primaryDisplay:', primaryDisplay); //取 [外接螢幕] 清單 const externalDisplay = displays.filter((display) => { return display.bounds.x !== 0 || display.bounds.y !== 0 }) //console.log(consoleTitle2, 'externalDisplay:', externalDisplay); //Mouse 目前所在 Point x,y let curScreenPoint = screen.getCursorScreenPoint(); //Object //console.log(consoleTitle2, 'curScreenPoint:', curScreenPoint); //將 Mouse 目前所在Point 轉成 screen let curMousePointAtScreen = screen.getDisplayMatching({ x: curScreenPoint.x, y: curScreenPoint.y, width: 10, height: 10 }); //console.log(constTitle2, 'curDisplay:', curDisplay); //PS: 使用第三方套件可以取得 螢幕Model,但是無法對應 Electron screen 清單. //let graphs = await si.graphics(); //console.log(consoleTitle2, 'graphs:', graphs); //回傳 return {displays, primaryDisplay, externalDisplay, curMousePointAtScreen}; } /** * 顯示系統通知訊息 - ok * * @param title * @param message */ let showNotification = function (title, message) { const notification = { title: title, body: message } new Notification(notification).show(); } /** * 顯示Dialog訊息 - ok * * @param title * @param message */ let showDialogMessage = function (title, message) { dialog.showMessageBox(null, {title: title, message: message}); } /** * 顯示Dialog選擇儲存到本地的檔案路徑 - ok * * @param filename 檔案名稱,eg: xxx.xls * @return {Promise<Electron.SaveDialogReturnValue>} */ let showSaveDialog = async function (filename) { return await dialog.showSaveDialog(null, {defaultPath: filename}); } /** * 顯示Dialog確認視窗 - ok * * @param {object} options * @param {string} options.type Dialog型式: "none", "info", "error", "question" or "warning" * @param {string} options.title 標題 * @param {string} options.message 訊息 * @param {string[]} options.buttons 按鈕集合 * @return {number} * * Usage: * //詢問是否確定刪除 * let btnClickIdx = myElectron.showConfirmDialog({type: 'warning', title: '移除', message: '確定要移除店家資料?', buttons: ["確定","取消"]}); * //btnClickIdx = 0 = 確定 * //btnClickIdx = 1 = 取消 */ let showConfirmDialog = function (options) { let _type = options.type || 'warning'; let _title = options.title || '標題'; let _message = options.message || '訊息...'; let _buttons = options.buttons || ["確定", "取消"]; let btnClickIdx = dialog.showMessageBoxSync({type: _type, title: _title, message: _message, buttons: _buttons}); //console.log(consoleTitle, 'btnClickIdx:', btnClickIdx); return btnClickIdx; //返回點擊的 Button 索引位置 } module.exports = { createBrowserWindows, getDisplays, showNotification, showDialogMessage, showSaveDialog, showConfirmDialog, shellOpenUrl, shellOpenFolderPath, shellMoveItemToTrash, copyTextToClipboard };
JavaScript
CL
4894367b5ef63aa41e34b40353c110f44be7cd8057453243f7e54f3ca9b4e5e3
import React from 'react'; import classes from './AboutMe.module.css'; class AboutMe extends React.Component { aboutMeRef = null; constructor(props) { super(props); this.aboutMeRef = React.createRef(); } scrollToMyRef = () => { window.scroll({ top: this.aboutMeRef.current.offsetTop, left: 0, behavior: 'smooth', }); }; render() { const technologies = [ 'JavaScript', 'Python', 'Java', 'Kotline', 'Dart', 'Swift', 'React & NextJS', 'Amazon Web Services', 'Design Patterns', 'Software Principles', 'Agile', 'Git + CI/CD', 'Linux', 'SCRUM & Kanban', ]; const technologiesList = technologies.map((el) => ( <li key={el} className={classes.GridListItem}> {el} </li> )); return ( <div className={classes.AboutMe} ref={this.aboutMeRef}> <h2 className={classes.Heading}>About Me</h2> <p className={classes.Description}> Hello, World, Linda Mucassi here. A software engineer from South Africa. </p> <p className={classes.Description}> I am a software engineer, passionate about tech and life and how the two share the social space, and yes coffee comes first because that is the bits of making awesome code. I am always open to learning new concepts. One of the things I enjoy doing is to solve common daily problems, through technology. </p> <p className={classes.Description}> I am always looking to secure and expand a responsible position in an IT organization, where I can bring immediate and strategic value and develop current skillset further and beyond the actual status quo. I love working with cutting-edge technology and playing with the latest gadgets. </p> <p> Some selected technologies and methodologies I worked with recently: </p> <ul className={classes.GridList}>{technologiesList}</ul> </div> ); } } export default AboutMe;
JavaScript
CL
5b85aa76e687730570f5cecbd4d2bb42512780ee769562d2feceae93f85d5634
const baseConfig = require('./webpack.config.base.js') const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const webpack = require('webpack') const dotenv = require('dotenv').config({ path: path.resolve(__dirname, '.env') }); const isDev = process.env.NODE_ENV !== 'production' module.exports = { ...baseConfig, entry: { index: "./src/client/js/entry" }, output: { path: path.resolve(__dirname, "../build"), filename: isDev ? "[name].bundle.js" : "[name]-[hash].bundle.js", chunkFilename: "[name]-[chunkhash].chunk.js", publicPath: '/' }, target: "web", plugins: [ new HtmlWebpackPlugin({ title: 'Loading...', filename: 'index.html', template: './src/client/template/index.html', inject: true }), new MiniCssExtractPlugin({ filename: isDev ? '[name].css' : '[name].[hash].css', chunkFilename: isDev ? '[id].css' : '[id].[hash].css' }), new webpack.DefinePlugin({ 'process.env': JSON.stringify(dotenv.parsed), 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }), ], devServer: { historyApiFallback: { disableDotRule: true }, host: '0.0.0.0', contentBase: path.resolve(__dirname, "build"), port: 3100, open: true, compress: true, https: false } }
JavaScript
CL
24794f19b4bec7c667a30f7c3c65a02118da670fffcd86762b91a5dde842dd26
/* eslint-env mocha */ import LinkedHeading from '../src/js/linked-heading'; import * as assert from 'proclaim'; import sinon from 'sinon/pkg/sinon'; sinon.assert.expose(assert, { includeFail: false, prefix: '' }); describe('LinkedHeading', () => { let testArea; beforeEach(() => { document.body.innerHTML = `<div id="test-area"></div>`; testArea = document.querySelector('#test-area'); }); afterEach(() => { document.body.innerHTML = ''; }); describe('new LinkedHeading(element)', () => { let headingElement; let instance; let originalConstructLinkElement; beforeEach(() => { originalConstructLinkElement = LinkedHeading.prototype.constructLinkElement; sinon.stub(LinkedHeading.prototype, 'constructLinkElement').returns('mock-link-element'); testArea.innerHTML = '<h2 id="mock-id">Mock Content</h2>'; headingElement = testArea.querySelector('h2'); instance = new LinkedHeading(headingElement); }); afterEach(() => { LinkedHeading.prototype.constructLinkElement.restore(); }); it('has a `headingElement` property set to the passed in element', () => { assert.strictEqual(instance.headingElement, headingElement); }); it('has an `id` property set to the heading element ID', () => { assert.strictEqual(instance.id, 'mock-id'); }); it('has an `options` property set to the default options', () => { assert.deepEqual(instance.options, { baseClass: 'o-layout__linked-heading', content: '¶', title: 'Link directly to this section of the page' }); }); it('has a `linkElement` property set to a constructed link element', () => { assert.calledOnce(LinkedHeading.prototype.constructLinkElement); assert.calledWithExactly(LinkedHeading.prototype.constructLinkElement); assert.strictEqual(instance.linkElement, 'mock-link-element'); }); describe('.constructLinkElement()', () => { let returnValue; beforeEach(() => { instance.options.baseClass = 'mock-base-class-option'; instance.options.content = 'mock-content-option'; instance.options.title = 'mock-title-option'; returnValue = originalConstructLinkElement.call(instance); }); it('sets the heading element HTML', () => { const actualHtml = headingElement.outerHTML.trim().replace(/\s+/g, ' '); const expectedHtml = ` <h2 id="mock-id" class="mock-base-class-option"> <a href="#mock-id" title="mock-title-option" class="mock-base-class-option__link"> <span class="mock-base-class-option__content">Mock Content</span> <span class="mock-base-class-option__label">mock-content-option</span> </a> </h2> `.trim().replace(/\s+/g, ' '); assert.strictEqual(actualHtml, expectedHtml); }); it('returns the created link element', () => { assert.strictEqual(returnValue, headingElement.querySelector('a')); }); describe('when the heading does not have an ID', () => { beforeEach(() => { delete instance.id; returnValue = originalConstructLinkElement.call(instance); }); it('returns `null`', () => { assert.isNull(returnValue); }); }); }); }); describe('new LinkedHeading(element, options)', () => { let headingElement; let instance; let options; beforeEach(() => { sinon.stub(LinkedHeading.prototype, 'constructLinkElement').returns('mock-link-element'); testArea.innerHTML = '<h2 id="mock-id">Mock Content</h2>'; headingElement = testArea.querySelector('h2'); options = { baseClass: 'mock-base-class-option', content: 'mock-content-option', title: 'mock-title-option' }; instance = new LinkedHeading(headingElement, options); }); afterEach(() => { LinkedHeading.prototype.constructLinkElement.restore(); }); it('has an `options` property set to the given options', () => { assert.deepEqual(instance.options, options); assert.notStrictEqual(instance.options, options); }); }); });
JavaScript
CL
0262951d4fc062528ccda42269d4b1b5e257e78f2d5f9fdecb3c94c80bc53c5c
// @flow import React from 'react'; import Point from './Point'; type Props = { startingPoint: Point, startingAnchor: AnchorPositionType, endingPoint: Point, endingAnchor: AnchorPositionType, strokeColor: string, arrowLength: number, strokeWidth: number, arrowLabel?: ?React$Node, arrowMarkerId: string, }; function computeEndingArrowDirectionVector(endingAnchor) { switch (endingAnchor) { case 'left': return { arrowX: -1, arrowY: 0 }; case 'right': return { arrowX: 1, arrowY: 0 }; case 'top': return { arrowX: 0, arrowY: -1 }; case 'bottom': return { arrowX: 0, arrowY: 1 }; default: return { arrowX: 0, arrowY: 0 }; } } export function computeEndingPointAccordingToArrow( xEnd: number, yEnd: number, arrowLength: number, strokeWidth: number, endingAnchor: AnchorPositionType, ) { const { arrowX, arrowY } = computeEndingArrowDirectionVector(endingAnchor); const xe = xEnd + (arrowX * arrowLength * strokeWidth) / 2; const ye = yEnd + (arrowY * arrowLength * strokeWidth) / 2; return { xe, ye }; } export function computeStartingAnchorPosition( xs: number, ys: number, xe: number, ye: number, startingAnchor: AnchorPositionType, ): { xa1: number, ya1: number } { if (startingAnchor === 'top' || startingAnchor === 'bottom') { return { xa1: xs, ya1: ys + (ye - ys) / 2, }; } if (startingAnchor === 'left' || startingAnchor === 'right') { return { xa1: xs + (xe - xs) / 2, ya1: ys, }; } return { xa1: xs, ya1: ys }; } export function computeEndingAnchorPosition( xs: number, ys: number, xe: number, ye: number, endingAnchor: AnchorPositionType, ): { xa2: number, ya2: number } { if (endingAnchor === 'top' || endingAnchor === 'bottom') { return { xa2: xe, ya2: ye - (ye - ys) / 2, }; } if (endingAnchor === 'left' || endingAnchor === 'right') { return { xa2: xe - (xe - xs) / 2, ya2: ye, }; } return { xa2: xe, ya2: ye }; } export function computeLabelDimensions( xs: number, ys: number, xe: number, ye: number, ): { xl: number, yl: number, wl: number, hl: number } { const wl = Math.abs(xe - xs); const hl = Math.abs(ye - ys); const xl = xe > xs ? xs : xe; const yl = ye > ys ? ys : ye; return { xl, yl, wl, hl, }; } const SvgArrow = ({ startingPoint, startingAnchor, endingPoint, endingAnchor, strokeColor, arrowLength, strokeWidth, arrowLabel, arrowMarkerId, }: Props) => { const actualArrowLength = arrowLength * 2; const xs = startingPoint.x; const ys = startingPoint.y; const { xe, ye } = computeEndingPointAccordingToArrow( endingPoint.x, endingPoint.y, actualArrowLength, strokeWidth, endingAnchor, ); const { xa1, ya1 } = computeStartingAnchorPosition( xs, ys, xe, ye, startingAnchor, ); const { xa2, ya2 } = computeEndingAnchorPosition( xs, ys, xe, ye, endingAnchor, ); const pathString = `M${xs},${ys} ` + `C${xa1},${ya1} ${xa2},${ya2} ` + `${xe},${ye}`; const { xl, yl, wl, hl } = computeLabelDimensions(xs, ys, xe, ye); return ( <g> <path d={pathString} style={{ fill: 'none', stroke: strokeColor, strokeWidth }} markerEnd={`url(${location.href}#${arrowMarkerId})`} /> {arrowLabel && ( <foreignObject x={xl} y={yl} width={wl} height={hl}> <div style={{ width: wl, height: hl, display: 'flex', alignItems: 'center', justifyContent: 'center', }} > <div>{arrowLabel}</div> </div> </foreignObject> )} </g> ); }; export default SvgArrow;
JavaScript
CL
61299920a3f1e3743adfba645c8ae09fc28b236102e780ae612a53e57b8a2452
var game = {}; game.score = 0; var scoreDisplay = document.querySelector('.info-score'); scoreDisplay.innerHTML = game.score; // Global variable for hitbox visibility. Set by checkbox on game board. var hitboxCheckbox = document.getElementById("hitbox"); var showHitbox = hitboxCheckbox.checked; // Listen for a change in the hitbox checkbox and toggle hitbox visibility hitboxCheckbox.addEventListener('click', function() { showHitbox = hitboxCheckbox.checked; }); // Global variable for difficulty. Set by dropdown on game board. var difficultyDropdown = document.getElementById("difficulty"); // Difficulty range is 1 to 10 with 1 being the easiest. Raises or lowers the chance of generating new enemies each loop. var difficulty = difficultyDropdown.value; // Listen for a change in the difficulty dropdown and adjust difficulty difficultyDropdown.addEventListener('change', function () { difficulty = difficultyDropdown.value; //Blur dropdown so that when arrow keys are used to move player after difficulty selection, the dropdown value doesn't change this.blur(); }); // Enemies our player must avoid var Enemy = function() { // Variables applied to each of our instances go here, // we've provided one for you to get started // The image/sprite for our enemies, this uses // a helper we've provided to easily load images this.sprite = 'images/enemy-bug.png'; // Create hitbox parameters this.hitbox = { xOffset: 2, yOffset: 78, width: 97, height: 65 }; // Lanes are the rows that enemies can traverse (count starts at 0, skipping water lane) const lanes = [1, 2, 4, 5]; // Randomize lanes and select one for the enemy to spawn on const spawnLane = (lanes[Math.floor(Math.random() * lanes.length)]) - 1; this.x = -101; this.y = 50 + (spawnLane * 83); this.speed = Math.floor(Math.random() * 300) + 70; }; // Update the enemy's position, required method for game // Parameter: dt, a time delta between ticks Enemy.prototype.update = function(dt) { // You should multiply any movement by the dt parameter // which will ensure the game runs at the same speed for // all computers. this.x += (this.speed) * dt; }; // Draw the enemy on the screen, required method for game Enemy.prototype.render = function(ele, ind, arr) { // Check enemy position, and if it's offscreen, delete from array if (this.x > 707) { delete arr[ind]; } else { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); } // If hitbox display is enabled, draw hitbox if (showHitbox) { drawHitbox(this); } this.checkCollision(); }; Enemy.prototype.checkCollision = function () { // Generate hitbox using defined parameters from enemy and player objects var enemyHitbox = { x: this.x + this.hitbox.xOffset, y: this.y + this.hitbox.yOffset, width: this.hitbox.width, height: this.hitbox.height }; var playerHitbox = { x: player.x + player.hitbox.xOffset, y: player.y + player.hitbox.yOffset, width: player.hitbox.width, height: player.hitbox.height }; // Check if any edge of the enemy overlaps any edge of the player if (enemyHitbox.x < playerHitbox.x + playerHitbox.width && enemyHitbox.x + enemyHitbox.width > playerHitbox.x && enemyHitbox.y < playerHitbox.y + playerHitbox.height && enemyHitbox.height + enemyHitbox.y > playerHitbox.y) { // Collision detected! Send player back to spawn. player.x = 303; player.y = 465; // Deduct half of the expected victory points (can't go below a score of zero) if(game.score > 0) { game.score -= 50 * difficulty; // If deduction causes score to go below zero, set score to zero if(game.score < 0) { game.score = 0; } } scoreDisplay.innerHTML = game.score; } } // Player class var Player = function(x, y) { // The image/sprite for our character this.sprite = 'images/char-boy.png'; this.x = x; this.y = y; // Creat hitbox parameters for our character this.hitbox = { xOffset: 34, yOffset: 114, width: 35, height: 25 }; } Player.prototype.update = function(dt) { this.checkWin(); } // Check if player sprite has made it to the water lane Player.prototype.checkWin = function() { if (this.y === -33) { // Send back to starting tile this.x = 303; this.y = 465; // Update score game.score += 100 * difficulty; scoreDisplay.innerHTML = game.score; } } Player.prototype.render = function() { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); // If hitbox display is enabled, draw hitbox if (showHitbox) { drawHitbox(this); } } // Take player inputs and translate to sprite movement Player.prototype.handleInput = function(kc) { switch (kc) { case 'w': case 'up': { // Don't allow movement up out of playable area if(this.y > -33){ this.y -= 83; } break; } case 's': case 'down': { // Don't allow movement down out of playable area if(this.y < 465){ this.y += 83; } break; } case 'a': case 'left': { // Don't allow movement left out of playable area if(this.x > 0){ this.x -= 101; } break; } case 'd': case 'right': { // Don't allow movement right out of playable area if(this.x < 606){ this.x += 101; } break; } } } function drawHitbox(ele) { // Style the hitbox ctx.strokeStyle = "#FF0000"; // Draw the hitbox around the sprite ctx.strokeRect(ele.x + ele.hitbox.xOffset, ele.y + ele.hitbox.yOffset, ele.hitbox.width, ele.hitbox.height); } // Instantiate enemy objects function generateInitialEnemies(num) { var enemies = []; const enemyCount = num; for(var i = 0; i < enemyCount; i++){ enemies.push(new Enemy()); } return enemies; } // Create initial set of enemies var allEnemies = generateInitialEnemies(4); // Create player and place on starting tile var player = new Player(303,465); // This listens for key presses and sends the keys to your // Player.handleInput() method. You don't need to modify this. document.addEventListener('keydown', function(e) { var allowedKeys = { 37: 'left', 38: 'up', 39: 'right', 40: 'down', 65: 'a', // Left w/ WASD 87: 'w', // Up w/ WASD 68: 'd', // Right w/ WASD 83: 's' // Down w/ WASD }; player.handleInput(allowedKeys[e.keyCode]); });
JavaScript
CL
9bbca178cbe6f88a805bbc659ad1e3e24a4074c55ee769a675fe74d438b7ed02
import React from "react"; import styled from "styled-components"; import { graphql } from "gatsby"; import { GatsbyImage } from "gatsby-plugin-image"; import { Layout, Container, MarkdownRenderer, Icon } from "../components"; import { capitalizeString, getImageWithTracedSVG } from "../utils"; import { useDarkMode } from "../context/darkMode"; const HeaderContainer = styled.div` display: grid; grid-template-columns: 1fr 2fr; grid-template-rows: auto; @media (max-width: ${({ theme }) => theme.bp.sm}) { grid-template-columns: 1fr; } `; const ImageContainer = styled.div` @media (max-width: ${({ theme }) => theme.bp.sm}) { height: 20rem; overflow: hidden; } `; const SocialContainer = styled.div` display: flex; flex-direction: row; flex-wrap: wrap; `; const SocialLink = styled.a` display: flex; flex-direction: row; justify-content: center; align-items: center; padding: 0.5rem; border: solid ${({ theme }) => theme.color.grey} 1px; font-size: 12px; font-weight: 200; border-radius: 4px; margin-right: 1rem; margin-bottom: 1rem; color: ${({ theme }) => theme.color.greyDark}; &:hover { color: ${({ theme }) => theme.color.primary}; border-color: ${({ theme }) => theme.color.primary}; } `; const EmailLink = styled.a` display: inline-flex; align-items: center; font-weight: 200; margin-left: 1px; margin-bottom: 1rem; color: ${({ theme }) => theme.color.greyDark}; &:hover { color: ${({ theme }) => theme.color.primary}; } `; const Social = ({ title, link }) => ( <SocialLink href={link} rel="noopener noreferrer" target="_blank"> <Icon name={title} /> {capitalizeString(title)} </SocialLink> ); const AboutPage = ({ data, location }) => { const { isDarkMode } = useDarkMode(); const { name, tagLine, emailAddress, twitterHandle, gitHubAccount, linkedInProfile, profilePhoto, biography } = data.contentfulAuthor; const profileImage = getImageWithTracedSVG(profilePhoto, isDarkMode); return ( <Layout white page={location.pathname}> <> <HeaderContainer> <ImageContainer> <GatsbyImage image={profileImage} title={name} alt={`Profile picture for ${name}`} imgStyle={{ verticalAlign: "middle", filter: isDarkMode ? "brightness(80%) sepia(10%)" : "none" }} /> </ImageContainer> <Container> <h1>{name}</h1> <p>{tagLine}</p> <EmailLink href={`mailto:${emailAddress}`}> <Icon name="mail" /> {emailAddress} </EmailLink> <SocialContainer> <Social title="gitHub" link={gitHubAccount} /> <Social title="instagram" link={`http://instagram.com/${twitterHandle}`} /> <Social title="linkedIn" link={linkedInProfile} /> </SocialContainer> </Container> </HeaderContainer> <Container content> <MarkdownRenderer source={biography.childMarkdownRemark.rawMarkdownBody} /> </Container> </> </Layout> ); }; export default AboutPage; export const query = graphql` { contentfulAuthor(name: { eq: "Vish Patel" }) { name tagLine emailAddress twitterHandle gitHubAccount linkedInProfile profilePhoto { gatsbyImageData(layout: FULL_WIDTH, placeholder: TRACED_SVG) } biography { childMarkdownRemark { rawMarkdownBody } } } } `;
JavaScript
CL
eb45d4329b746767d146f9943a43384fae163b53b0d43ffb6502d854255989fb
import { createStore, applyMiddleware, compose } from 'redux'; import createSagaMiddleware from 'redux-saga'; import rootSaga from './../utils/CombineSagas'; import reducers from './reducers/rootReducer'; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const sagaMiddleware = createSagaMiddleware(); const enhancer = composeEnhancers( applyMiddleware(sagaMiddleware) ); const initialSate = {}; export const store = (() => { const store = createStore(reducers, initialSate, enhancer); store.runSagaTask = () => { store.sagaTask = sagaMiddleware.run(rootSaga); }; store.runSagaTask(); return store; })();
JavaScript
CL
67f76c298abd98cb6d6ccdde46ca1432ea1c0012d444bcfa9df6ace8671605b4
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[4],{ /***/ "./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/index.vue?vue&type=script&lang=js&": /*!*****************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/baseComponents/base_upload/index.vue?vue&type=script&lang=js& ***! \*****************************************************************************************************************************************************************************************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _typeOne_vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typeOne.vue */ \"./src/components/baseComponents/base_upload/typeOne.vue\");\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n\n/* harmony default export */ __webpack_exports__[\"default\"] = ({\n name: 'base_upload',\n components: {\n typeOne: _typeOne_vue__WEBPACK_IMPORTED_MODULE_0__[\"default\"]\n },\n props: {\n type: {\n type: String,\n default: '1'\n } //组件类型\n\n },\n computed: {\n renderIs() {\n return ['typeOne'][this.type - 1];\n }\n\n }\n});\n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/index.vue?./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options"); /***/ }), /***/ "./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=script&lang=js&": /*!*******************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=script&lang=js& ***! \*******************************************************************************************************************************************************************************************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var vant_es_toast_style__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vant/es/toast/style */ \"./node_modules/vant/es/toast/style/index.js\");\n/* harmony import */ var vant_es_toast__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! vant/es/toast */ \"./node_modules/vant/es/toast/index.js\");\n/* harmony import */ var vant_es_image_preview_style__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! vant/es/image-preview/style */ \"./node_modules/vant/es/image-preview/style/index.js\");\n/* harmony import */ var vant_es_image_preview__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! vant/es/image-preview */ \"./node_modules/vant/es/image-preview/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var vue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! vue */ \"./node_modules/vue/dist/vue.runtime.esm.js\");\n\n\n\n\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n\n\nvue__WEBPACK_IMPORTED_MODULE_5__[\"default\"].use(vant_es_toast__WEBPACK_IMPORTED_MODULE_1__[\"default\"]).use(vant_es_image_preview__WEBPACK_IMPORTED_MODULE_3__[\"default\"]);\n/* harmony default export */ __webpack_exports__[\"default\"] = ({\n name: \"baseUpload\",\n\n data() {\n return {\n render: {\n showTitle: true,\n //是否显示标题\n uploadLeftIcon: __webpack_require__(/*! @images/baseComponentsImg/bitian.png */ \"./src/static/images/baseComponentsImg/bitian.png\"),\n //左侧是否必填图标\n title: \"上传图片\",\n //标题\n fileList: [{\n name: \"1\",\n src: __webpack_require__(/*! @images/baseComponentsImg/bgCard_01.png */ \"./src/static/images/baseComponentsImg/bgCard_01.png\")\n }],\n //上次文件列表\n maxNumber: 5,\n //最大上传文件数限制\n uploadType: 1 //上传组件类型(1:上传文件2:纯回显)\n\n },\n uploadProgress: 0 //进度条进度\n\n };\n },\n\n props: {\n value: {\n type: Object,\n default: () => {}\n },\n //出参————用于更改数据\n entryParam: {\n type: Object,\n default: () => {}\n },\n //入参————用于获取数据\n differentParam: {\n type: Object,\n default: () => {}\n } //入参————用于更改页面细微差距\n\n },\n\n created() {\n this.render = Object.assign(this.render, this.entryParam, this.differentParam);\n },\n\n methods: {\n //上传文件\n uploadFile(e) {\n let currentList = e.target.files;\n let arr = [];\n let {\n render: {\n fileList,\n maxNumber\n }\n } = this;\n\n if (currentList.length + fileList.length > maxNumber) {\n Object(vant_es_toast__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(\"文件最多只能上传5个\");\n\n return;\n }\n\n for (let i = 0; i < currentList.length; i++) {\n let imgSize = currentList[i].size;\n\n if (imgSize > 500 * 1024 * 1) {\n Object(vant_es_toast__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(\"文件大小不能超过500kb\");\n\n return;\n }\n\n let obj = {};\n obj.name = currentList[i].name;\n obj.src = this.getObjectUrl(currentList[i]);\n arr.push(obj);\n } //表单提交\n\n\n let formData = new FormData();\n formData.append(\"file\", e.target.files[0]);\n let headerConfig = {\n headers: {\n \"Content-Type\": \"mutipart/form-data\"\n }\n }; // axios.post('',formData,headerConfig).then(res=>{\n // console.log(res)\n // })\n\n let timer = null;\n timer = setInterval(() => {\n this.uploadProgress++;\n\n if (this.uploadProgress >= 120) {\n clearInterval(timer);\n this.uploadProgress = 0;\n this.render.fileList = this.render.fileList.concat(arr);\n this.$emit(\"click\", this.render.fileList);\n }\n }, 100);\n },\n\n //上传成功后预览图片\n getObjectUrl(item) {\n let url = null;\n\n if (!window.createObjectURL) {\n url = window.webkitURL.createObjectURL(item);\n }\n\n return url;\n },\n\n //点击放大图片\n preview() {\n let imgList = [];\n this.render.fileList.forEach(item => {\n imgList.push(item.src);\n });\n\n Object(vant_es_image_preview__WEBPACK_IMPORTED_MODULE_3__[\"default\"])({\n images: imgList,\n closeable: true\n });\n },\n\n //删除图片\n delImg(index) {\n this.render.fileList.splice(index, 1);\n this.$emit(\"click\", this.render.fileList);\n }\n\n }\n});\n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/typeOne.vue?./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options"); /***/ }), /***/ "./node_modules/cache-loader/dist/cjs.js?{\"cacheDirectory\":\"node_modules/.cache/vue-loader\",\"cacheIdentifier\":\"7b323dac-vue-loader-template\"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/index.vue?vue&type=template&id=2a7849ba&": /*!*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"7b323dac-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/baseComponents/base_upload/index.vue?vue&type=template&id=2a7849ba& ***! \*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return render; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return staticRenderFns; });\nvar render = function() {\n var this$1 = this\n var _vm = this\n var _h = _vm.$createElement\n var _c = _vm._self._c || _h\n return _c(\n \"div\",\n {\n on: {\n click: function($event) {\n $event.stopPropagation()\n }\n }\n },\n [\n _c(\n _vm.renderIs,\n _vm._b(\n {\n tag: \"component\",\n on: {\n click: function(param) {\n return this$1.$emit(\"click\", param)\n }\n }\n },\n \"component\",\n _vm.$attrs,\n false\n )\n )\n ],\n 1\n )\n}\nvar staticRenderFns = []\nrender._withStripped = true\n\n\n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/index.vue?./node_modules/cache-loader/dist/cjs.js?%7B%22cacheDirectory%22:%22node_modules/.cache/vue-loader%22,%22cacheIdentifier%22:%227b323dac-vue-loader-template%22%7D!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options"); /***/ }), /***/ "./node_modules/cache-loader/dist/cjs.js?{\"cacheDirectory\":\"node_modules/.cache/vue-loader\",\"cacheIdentifier\":\"7b323dac-vue-loader-template\"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=template&id=3904a4b4&scoped=true&": /*!***************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"7b323dac-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=template&id=3904a4b4&scoped=true& ***! \***************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return render; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return staticRenderFns; });\nvar render = function() {\n var _vm = this\n var _h = _vm.$createElement\n var _c = _vm._self._c || _h\n return _c(\"div\", { staticClass: \"upload-box\" }, [\n _vm.render.uploadType == \"1\"\n ? _c(\"div\", [\n _vm.render.showTitle\n ? _c(\"div\", { staticClass: \"upload-header\" }, [\n _c(\"div\", { staticClass: \"upload-header-icon\" }, [\n _c(\"img\", {\n attrs: { src: _vm.render.uploadLeftIcon, alt: \"\" }\n }),\n _c(\"span\", [_vm._v(_vm._s(_vm.render.title))])\n ])\n ])\n : _vm._e(),\n _c(\n \"div\",\n { staticClass: \"upload-img-list\" },\n [\n _vm.uploadProgress > 0\n ? _c(\"div\", { staticClass: \"upload-progress\" }, [\n _c(\"div\", { staticClass: \"upload-progress-bg\" }, [\n _c(\n \"span\",\n {\n staticClass: \"upload-progress-percent\",\n style: { width: _vm.uploadProgress + \"px\" }\n },\n [\n _c(\n \"span\",\n { staticClass: \"upload-progress-portion\" },\n [\n _vm._v(\n _vm._s(\n ((_vm.uploadProgress * 100) / 120).toFixed(0)\n ) + \"%\"\n )\n ]\n )\n ]\n )\n ])\n ])\n : _vm._e(),\n _vm._l(_vm.render.fileList, function(item, index) {\n return _c(\n \"div\",\n { key: index, staticClass: \"upload-img-item\" },\n [\n _c(\"img\", {\n attrs: { src: item.src, alt: item.name },\n on: { click: _vm.preview }\n }),\n _c(\"i\", {\n staticClass: \"upload-close\",\n on: {\n click: function($event) {\n return _vm.delImg(index)\n }\n }\n })\n ]\n )\n }),\n _vm.render.fileList.length < _vm.render.maxNumber\n ? _c(\"div\", { staticClass: \"upload-wrapper\" }, [\n _c(\"i\", { staticClass: \"upload-bg\" }),\n _c(\"input\", {\n staticClass: \"upload-input\",\n attrs: { type: \"file\", value: \"上传\", multiple: \"\" },\n on: { change: _vm.uploadFile }\n })\n ])\n : _vm._e()\n ],\n 2\n )\n ])\n : _c(\n \"div\",\n { staticClass: \"upload-img-list\" },\n _vm._l(_vm.render.fileList, function(item, index) {\n return _c(\"div\", { key: index, staticClass: \"upload-img-item\" }, [\n _c(\"img\", {\n attrs: { src: item.src, alt: item.name },\n on: { click: _vm.preview }\n })\n ])\n }),\n 0\n )\n ])\n}\nvar staticRenderFns = []\nrender._withStripped = true\n\n\n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/typeOne.vue?./node_modules/cache-loader/dist/cjs.js?%7B%22cacheDirectory%22:%22node_modules/.cache/vue-loader%22,%22cacheIdentifier%22:%227b323dac-vue-loader-template%22%7D!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options"); /***/ }), /***/ "./node_modules/css-loader/dist/cjs.js?!./node_modules/postcss-loader/src/index.js?!./node_modules/vant/es/image-preview/index.css": /*!******************************************************************************************************************************************************************!*\ !*** ./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??ref--6-oneOf-3-2!./node_modules/vant/es/image-preview/index.css ***! \******************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("// Imports\nvar ___CSS_LOADER_API_IMPORT___ = __webpack_require__(/*! ../../../css-loader/dist/runtime/api.js */ \"./node_modules/css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.i, \".van-image-preview{position:fixed;top:0;left:0;width:100%;height:100%}.van-image-preview__swipe{height:100%}.van-image-preview__swipe-item{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;overflow:hidden}.van-image-preview__cover{position:absolute;top:0;left:0}.van-image-preview__image{width:100%;-webkit-transition-property:-webkit-transform;transition-property:-webkit-transform;transition-property:transform;transition-property:transform,-webkit-transform}.van-image-preview__image--vertical{width:auto;height:100%}.van-image-preview__image img{-webkit-user-drag:none}.van-image-preview__image .van-image__error{top:30%;height:40%}.van-image-preview__image .van-image__error-icon{font-size:0.64286rem}.van-image-preview__image .van-image__loading{background-color:transparent}.van-image-preview__index{position:absolute;top:0.28571rem;left:50%;color:#fff;font-size:0.25rem;line-height:0.39286rem;text-shadow:0 0.01786rem 0.01786rem #323233;-webkit-transform:translate(-50%,0);transform:translate(-50%,0)}.van-image-preview__overlay{background-color:rgba(0,0,0,.9)}.van-image-preview__close-icon{position:absolute;z-index:1;color:#c8c9cc;font-size:0.39286rem;cursor:pointer}.van-image-preview__close-icon:active{color:#969799}.van-image-preview__close-icon--top-left{top:0.28571rem;left:0.28571rem}.van-image-preview__close-icon--top-right{top:0.28571rem;right:0.28571rem}.van-image-preview__close-icon--bottom-left{bottom:0.28571rem;left:0.28571rem}.van-image-preview__close-icon--bottom-right{right:0.28571rem;bottom:0.28571rem}\", \"\"]);\n// Exports\nmodule.exports = exports;\n\n\n//# sourceURL=webpack:///./node_modules/vant/es/image-preview/index.css?./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??ref--6-oneOf-3-2"); /***/ }), /***/ "./node_modules/css-loader/dist/cjs.js?!./node_modules/postcss-loader/src/index.js?!./node_modules/vant/es/image/index.css": /*!**********************************************************************************************************************************************************!*\ !*** ./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??ref--6-oneOf-3-2!./node_modules/vant/es/image/index.css ***! \**********************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("// Imports\nvar ___CSS_LOADER_API_IMPORT___ = __webpack_require__(/*! ../../../css-loader/dist/runtime/api.js */ \"./node_modules/css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.i, \".van-image{position:relative;display:inline-block}.van-image--round{overflow:hidden;border-radius:50%}.van-image--round img{border-radius:inherit}.van-image__error,.van-image__img,.van-image__loading{display:block;width:100%;height:100%}.van-image__error,.van-image__loading{position:absolute;top:0;left:0;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;color:#969799;font-size:0.25rem;background-color:#f7f8fa}.van-image__loading-icon{font-size:0.39286rem}.van-image__error-icon{font-size:0.39286rem}\", \"\"]);\n// Exports\nmodule.exports = exports;\n\n\n//# sourceURL=webpack:///./node_modules/vant/es/image/index.css?./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??ref--6-oneOf-3-2"); /***/ }), /***/ "./node_modules/css-loader/dist/cjs.js?!./node_modules/postcss-loader/src/index.js?!./node_modules/vant/es/swipe-item/index.css": /*!***************************************************************************************************************************************************************!*\ !*** ./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??ref--6-oneOf-3-2!./node_modules/vant/es/swipe-item/index.css ***! \***************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("// Imports\nvar ___CSS_LOADER_API_IMPORT___ = __webpack_require__(/*! ../../../css-loader/dist/runtime/api.js */ \"./node_modules/css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.i, \".van-swipe-item{position:relative;-webkit-flex-shrink:0;flex-shrink:0;width:100%;height:100%}\", \"\"]);\n// Exports\nmodule.exports = exports;\n\n\n//# sourceURL=webpack:///./node_modules/vant/es/swipe-item/index.css?./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??ref--6-oneOf-3-2"); /***/ }), /***/ "./node_modules/css-loader/dist/cjs.js?!./node_modules/postcss-loader/src/index.js?!./node_modules/vant/es/swipe/index.css": /*!**********************************************************************************************************************************************************!*\ !*** ./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??ref--6-oneOf-3-2!./node_modules/vant/es/swipe/index.css ***! \**********************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("// Imports\nvar ___CSS_LOADER_API_IMPORT___ = __webpack_require__(/*! ../../../css-loader/dist/runtime/api.js */ \"./node_modules/css-loader/dist/runtime/api.js\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\n// Module\nexports.push([module.i, \".van-swipe{position:relative;overflow:hidden;cursor:grab;-webkit-user-select:none;user-select:none}.van-swipe__track{display:-webkit-box;display:-webkit-flex;display:flex;height:100%}.van-swipe__track--vertical{-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column}.van-swipe__indicators{position:absolute;bottom:0.21429rem;left:50%;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-transform:translateX(-50%);transform:translateX(-50%)}.van-swipe__indicators--vertical{top:50%;bottom:auto;left:0.21429rem;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column;-webkit-transform:translateY(-50%);transform:translateY(-50%)}.van-swipe__indicators--vertical .van-swipe__indicator:not(:last-child){margin-bottom:0.10714rem}.van-swipe__indicator{width:0.10714rem;height:0.10714rem;background-color:#ebedf0;border-radius:100%;opacity:.3;-webkit-transition:opacity .2s;transition:opacity .2s}.van-swipe__indicator:not(:last-child){margin-right:0.10714rem}.van-swipe__indicator--active{background-color:#1989fa;opacity:1}\", \"\"]);\n// Exports\nmodule.exports = exports;\n\n\n//# sourceURL=webpack:///./node_modules/vant/es/swipe/index.css?./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??ref--6-oneOf-3-2"); /***/ }), /***/ "./node_modules/css-loader/dist/cjs.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true&": /*!***********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--8-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-1-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true& ***! \***********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("// Imports\nvar ___CSS_LOADER_API_IMPORT___ = __webpack_require__(/*! ../../../../node_modules/css-loader/dist/runtime/api.js */ \"./node_modules/css-loader/dist/runtime/api.js\");\nvar ___CSS_LOADER_GET_URL_IMPORT___ = __webpack_require__(/*! ../../../../node_modules/css-loader/dist/runtime/getUrl.js */ \"./node_modules/css-loader/dist/runtime/getUrl.js\");\nvar ___CSS_LOADER_URL_IMPORT_0___ = __webpack_require__(/*! @images/baseComponentsImg/closed.png */ \"./src/static/images/baseComponentsImg/closed.png\");\nvar ___CSS_LOADER_URL_IMPORT_1___ = __webpack_require__(/*! @images/baseComponentsImg/upload.png */ \"./src/static/images/baseComponentsImg/upload.png\");\nexports = ___CSS_LOADER_API_IMPORT___(false);\nvar ___CSS_LOADER_URL_REPLACEMENT_0___ = ___CSS_LOADER_GET_URL_IMPORT___(___CSS_LOADER_URL_IMPORT_0___);\nvar ___CSS_LOADER_URL_REPLACEMENT_1___ = ___CSS_LOADER_GET_URL_IMPORT___(___CSS_LOADER_URL_IMPORT_1___);\n// Module\nexports.push([module.i, \"@charset \\\"UTF-8\\\";\\n/**********************************************\\n * @description 混合宏\\n * @define @mixin name($param){}\\n * @callback @include name(param, param)\\n * 注意点: 混合宏的传参得严格按照 形参的顺序传值\\n */\\n/**********************************************\\n * @description 设置宽高\\n * @param $w 宽度 @default 100%\\n * @param $h 高度 @default 100%\\n */\\n/**********************************************\\n * @description flex布局\\n * @param $direction 方向默认水平 row=水平 column=垂直\\n * @param $alignItems 根据方向 来决定 横轴 或 竖轴的位置 option: flex-start center flex-end\\n * @param $justifyContent 根据方向 来决定 横轴 或 竖轴的位置 option: flex-start center flex-end\\n */\\n/**********************************************\\n * @description 设置背景\\n * @param $url 图片地址\\n * @param $width 背景占容器的宽度 默认100%\\n * @param $height 背景占容器的高度 默认100%\\n * @param $color 背景颜色 默认为 ''\\n */\\n/**\\n * @description 占位符\\n * @define %name{css style}\\n * @callback @extend %name\\n*/\\n.upload-box[data-v-3904a4b4] {\\n padding: 0.3rem;\\n}\\n.upload-box .upload-header[data-v-3904a4b4] {\\n margin-bottom: 0.15rem;\\n}\\n.upload-box .upload-img-list[data-v-3904a4b4] {\\n display: flex;\\n flex-wrap: wrap;\\n}\\n.upload-box .upload-img-list .upload-progress[data-v-3904a4b4] {\\n width: 1.5rem;\\n height: 1.5rem;\\n background: #fff;\\n display: flex;\\n align-items: center;\\n justify-content: center;\\n}\\n.upload-box .upload-img-list .upload-progress .upload-progress-bg[data-v-3904a4b4] {\\n width: 1.2rem;\\n height: 0.15rem;\\n background: #bbb;\\n border-radius: 0.1rem;\\n position: relative;\\n}\\n.upload-box .upload-img-list .upload-progress .upload-progress-bg .upload-progress-percent[data-v-3904a4b4] {\\n width: 0;\\n height: 0.15rem;\\n background: #3379ff;\\n position: absolute;\\n border-radius: 0.1rem;\\n}\\n.upload-box .upload-img-list .upload-progress .upload-progress-bg .upload-progress-percent .upload-progress-portion[data-v-3904a4b4] {\\n position: absolute;\\n top: 0.15rem;\\n font-size: 0.24rem;\\n color: #000;\\n}\\n.upload-box .upload-img-list .upload-img-item[data-v-3904a4b4] {\\n width: 1.5rem;\\n height: 1.5rem;\\n display: flex;\\n margin-bottom: 0.5rem;\\n box-shadow: 0 0 0.02rem #aaa;\\n border-radius: 0.05rem;\\n margin-right: 0.15rem;\\n position: relative;\\n}\\n.upload-box .upload-img-list .upload-img-item > img[data-v-3904a4b4] {\\n width: 1.5rem;\\n height: 1.5rem;\\n object-fit: scale-down;\\n}\\n.upload-box .upload-img-list .upload-img-item .upload-close[data-v-3904a4b4] {\\n width: 0.25rem;\\n height: 0.25rem;\\n position: absolute;\\n top: -0.15rem;\\n right: -0.1rem;\\n background: url(\" + ___CSS_LOADER_URL_REPLACEMENT_0___ + \") no-repeat center;\\n background-size: 100% 100%;\\n}\\n.upload-box .upload-wrapper[data-v-3904a4b4] {\\n width: 1.5rem;\\n height: 1.5rem;\\n border-radius: 0.1rem;\\n background: #f7f8fa;\\n position: relative;\\n}\\n.upload-box .upload-wrapper .upload-bg[data-v-3904a4b4] {\\n width: 1rem;\\n height: 1rem;\\n display: block;\\n position: absolute;\\n top: 50%;\\n left: 50%;\\n transform: translate(-50%, -50%);\\n background-size: 100% 100%;\\n background: url(\" + ___CSS_LOADER_URL_REPLACEMENT_1___ + \") no-repeat center;\\n}\\n.upload-box .upload-wrapper .upload-input[data-v-3904a4b4] {\\n width: 1.5rem;\\n height: 1.5rem;\\n opacity: 0;\\n}\", \"\"]);\n// Exports\nmodule.exports = exports;\n\n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/typeOne.vue?./node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--8-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-1-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options"); /***/ }), /***/ "./node_modules/vant/es/image-preview/ImagePreview.js": /*!************************************************************!*\ !*** ./node_modules/vant/es/image-preview/ImagePreview.js ***! \************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ \"./node_modules/vant/es/utils/index.js\");\n/* harmony import */ var _shared__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shared */ \"./node_modules/vant/es/image-preview/shared.js\");\n/* harmony import */ var _mixins_popup__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../mixins/popup */ \"./node_modules/vant/es/mixins/popup/index.js\");\n/* harmony import */ var _mixins_touch__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../mixins/touch */ \"./node_modules/vant/es/mixins/touch.js\");\n/* harmony import */ var _mixins_bind_event__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../mixins/bind-event */ \"./node_modules/vant/es/mixins/bind-event.js\");\n/* harmony import */ var _icon__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../icon */ \"./node_modules/vant/es/icon/index.js\");\n/* harmony import */ var _swipe__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../swipe */ \"./node_modules/vant/es/swipe/index.js\");\n/* harmony import */ var _ImagePreviewItem__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./ImagePreviewItem */ \"./node_modules/vant/es/image-preview/ImagePreviewItem.js\");\n// Utils\n\n // Mixins\n\n\n\n // Components\n\n\n\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (Object(_shared__WEBPACK_IMPORTED_MODULE_1__[\"createComponent\"])({\n mixins: [_mixins_touch__WEBPACK_IMPORTED_MODULE_3__[\"TouchMixin\"], Object(_mixins_popup__WEBPACK_IMPORTED_MODULE_2__[\"PopupMixin\"])({\n skipToggleEvent: true\n }), Object(_mixins_bind_event__WEBPACK_IMPORTED_MODULE_4__[\"BindEventMixin\"])(function (bind) {\n bind(window, 'resize', this.resize, true);\n })],\n props: {\n className: null,\n closeable: Boolean,\n asyncClose: Boolean,\n showIndicators: Boolean,\n images: {\n type: Array,\n default: function _default() {\n return [];\n }\n },\n loop: {\n type: Boolean,\n default: true\n },\n swipeDuration: {\n type: [Number, String],\n default: 500\n },\n overlay: {\n type: Boolean,\n default: true\n },\n showIndex: {\n type: Boolean,\n default: true\n },\n startPosition: {\n type: [Number, String],\n default: 0\n },\n minZoom: {\n type: [Number, String],\n default: 1 / 3\n },\n maxZoom: {\n type: [Number, String],\n default: 3\n },\n overlayClass: {\n type: String,\n default: Object(_shared__WEBPACK_IMPORTED_MODULE_1__[\"bem\"])('overlay')\n },\n closeIcon: {\n type: String,\n default: 'clear'\n },\n closeIconPosition: {\n type: String,\n default: 'top-right'\n }\n },\n data: function data() {\n return {\n active: 0,\n windowWidth: 0,\n windowHeight: 0,\n doubleClickTimer: null\n };\n },\n created: function created() {\n this.resize();\n },\n watch: {\n startPosition: 'setActive',\n value: function value(val) {\n var _this = this;\n\n if (val) {\n this.setActive(+this.startPosition);\n this.$nextTick(function () {\n _this.$refs.swipe.swipeTo(+_this.startPosition, {\n immediate: true\n });\n });\n } else {\n this.$emit('close', {\n index: this.active,\n url: this.images[this.active]\n });\n }\n }\n },\n methods: {\n resize: function resize() {\n if (_utils__WEBPACK_IMPORTED_MODULE_0__[\"inBrowser\"]) {\n this.windowWidth = window.innerWidth;\n this.windowHeight = window.innerHeight;\n }\n },\n emitClose: function emitClose() {\n if (!this.asyncClose) {\n this.$emit('input', false);\n }\n },\n emitScale: function emitScale(args) {\n this.$emit('scale', args);\n },\n setActive: function setActive(active) {\n if (active !== this.active) {\n this.active = active;\n this.$emit('change', active);\n }\n },\n genIndex: function genIndex() {\n var h = this.$createElement;\n\n if (this.showIndex) {\n return h(\"div\", {\n \"class\": Object(_shared__WEBPACK_IMPORTED_MODULE_1__[\"bem\"])('index')\n }, [this.slots('index') || this.active + 1 + \" / \" + this.images.length]);\n }\n },\n genCover: function genCover() {\n var h = this.$createElement;\n var cover = this.slots('cover');\n\n if (cover) {\n return h(\"div\", {\n \"class\": Object(_shared__WEBPACK_IMPORTED_MODULE_1__[\"bem\"])('cover')\n }, [cover]);\n }\n },\n genImages: function genImages() {\n var _this2 = this;\n\n var h = this.$createElement;\n return h(_swipe__WEBPACK_IMPORTED_MODULE_6__[\"default\"], {\n \"ref\": \"swipe\",\n \"attrs\": {\n \"lazyRender\": true,\n \"loop\": this.loop,\n \"duration\": this.swipeDuration,\n \"initialSwipe\": this.startPosition,\n \"showIndicators\": this.showIndicators,\n \"indicatorColor\": \"white\"\n },\n \"class\": Object(_shared__WEBPACK_IMPORTED_MODULE_1__[\"bem\"])('swipe'),\n \"on\": {\n \"change\": this.setActive\n }\n }, [this.images.map(function (image) {\n return h(_ImagePreviewItem__WEBPACK_IMPORTED_MODULE_7__[\"default\"], {\n \"attrs\": {\n \"src\": image,\n \"show\": _this2.value,\n \"active\": _this2.active,\n \"maxZoom\": _this2.maxZoom,\n \"minZoom\": _this2.minZoom,\n \"windowWidth\": _this2.windowWidth,\n \"windowHeight\": _this2.windowHeight\n },\n \"on\": {\n \"scale\": _this2.emitScale,\n \"close\": _this2.emitClose\n }\n });\n })]);\n },\n genClose: function genClose() {\n var h = this.$createElement;\n\n if (this.closeable) {\n return h(_icon__WEBPACK_IMPORTED_MODULE_5__[\"default\"], {\n \"attrs\": {\n \"role\": \"button\",\n \"name\": this.closeIcon\n },\n \"class\": Object(_shared__WEBPACK_IMPORTED_MODULE_1__[\"bem\"])('close-icon', this.closeIconPosition),\n \"on\": {\n \"click\": this.emitClose\n }\n });\n }\n },\n onClosed: function onClosed() {\n this.$emit('closed');\n },\n // @exposed-api\n swipeTo: function swipeTo(index, options) {\n if (this.$refs.swipe) {\n this.$refs.swipe.swipeTo(index, options);\n }\n }\n },\n render: function render() {\n var h = arguments[0];\n\n if (!this.shouldRender) {\n return;\n }\n\n return h(\"transition\", {\n \"attrs\": {\n \"name\": \"van-fade\"\n },\n \"on\": {\n \"afterLeave\": this.onClosed\n }\n }, [h(\"div\", {\n \"directives\": [{\n name: \"show\",\n value: this.value\n }],\n \"class\": [Object(_shared__WEBPACK_IMPORTED_MODULE_1__[\"bem\"])(), this.className]\n }, [this.genClose(), this.genImages(), this.genIndex(), this.genCover()])]);\n }\n}));\n\n//# sourceURL=webpack:///./node_modules/vant/es/image-preview/ImagePreview.js?"); /***/ }), /***/ "./node_modules/vant/es/image-preview/ImagePreviewItem.js": /*!****************************************************************!*\ !*** ./node_modules/vant/es/image-preview/ImagePreviewItem.js ***! \****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _shared__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./shared */ \"./node_modules/vant/es/image-preview/shared.js\");\n/* harmony import */ var _utils_format_number__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/format/number */ \"./node_modules/vant/es/utils/format/number.js\");\n/* harmony import */ var _utils_dom_event__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/dom/event */ \"./node_modules/vant/es/utils/dom/event.js\");\n/* harmony import */ var _mixins_touch__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../mixins/touch */ \"./node_modules/vant/es/mixins/touch.js\");\n/* harmony import */ var _image__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../image */ \"./node_modules/vant/es/image/index.js\");\n/* harmony import */ var _loading__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../loading */ \"./node_modules/vant/es/loading/index.js\");\n/* harmony import */ var _swipe_item__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../swipe-item */ \"./node_modules/vant/es/swipe-item/index.js\");\n// Utils\n\n\n // Mixins\n\n // Component\n\n\n\n\n\nfunction getDistance(touches) {\n return Math.sqrt(Math.pow(touches[0].clientX - touches[1].clientX, 2) + Math.pow(touches[0].clientY - touches[1].clientY, 2));\n}\n\n/* harmony default export */ __webpack_exports__[\"default\"] = ({\n mixins: [_mixins_touch__WEBPACK_IMPORTED_MODULE_3__[\"TouchMixin\"]],\n props: {\n src: String,\n show: Boolean,\n active: Number,\n minZoom: [Number, String],\n maxZoom: [Number, String],\n windowWidth: Number,\n windowHeight: Number\n },\n data: function data() {\n return {\n scale: 1,\n moveX: 0,\n moveY: 0,\n moving: false,\n zooming: false,\n imageRatio: 0,\n displayWidth: 0,\n displayHeight: 0\n };\n },\n computed: {\n vertical: function vertical() {\n var windowWidth = this.windowWidth,\n windowHeight = this.windowHeight;\n var windowRatio = windowHeight / windowWidth;\n return this.imageRatio > windowRatio;\n },\n imageStyle: function imageStyle() {\n var scale = this.scale;\n var style = {\n transitionDuration: this.zooming || this.moving ? '0s' : '.3s'\n };\n\n if (scale !== 1) {\n var offsetX = this.moveX / scale;\n var offsetY = this.moveY / scale;\n style.transform = \"scale(\" + scale + \", \" + scale + \") translate(\" + offsetX + \"px, \" + offsetY + \"px)\";\n }\n\n return style;\n },\n maxMoveX: function maxMoveX() {\n if (this.imageRatio) {\n var displayWidth = this.vertical ? this.windowHeight / this.imageRatio : this.windowWidth;\n return Math.max(0, (this.scale * displayWidth - this.windowWidth) / 2);\n }\n\n return 0;\n },\n maxMoveY: function maxMoveY() {\n if (this.imageRatio) {\n var displayHeight = this.vertical ? this.windowHeight : this.windowWidth * this.imageRatio;\n return Math.max(0, (this.scale * displayHeight - this.windowHeight) / 2);\n }\n\n return 0;\n }\n },\n watch: {\n show: function show(val) {\n if (!val) {\n this.resetScale();\n }\n }\n },\n mounted: function mounted() {\n this.bindTouchEvent(this.$el);\n },\n methods: {\n resetScale: function resetScale() {\n this.setScale(1);\n this.moveX = 0;\n this.moveY = 0;\n },\n setScale: function setScale(scale) {\n this.scale = Object(_utils_format_number__WEBPACK_IMPORTED_MODULE_1__[\"range\"])(scale, +this.minZoom, +this.maxZoom);\n this.$emit('scale', {\n scale: this.scale,\n index: this.active\n });\n },\n toggleScale: function toggleScale() {\n var scale = this.scale > 1 ? 1 : 2;\n this.setScale(scale);\n this.moveX = 0;\n this.moveY = 0;\n },\n onTouchStart: function onTouchStart(event) {\n var touches = event.touches;\n var _this$offsetX = this.offsetX,\n offsetX = _this$offsetX === void 0 ? 0 : _this$offsetX;\n this.touchStart(event);\n this.touchStartTime = new Date();\n this.startMoveX = this.moveX;\n this.startMoveY = this.moveY;\n this.moving = touches.length === 1 && this.scale !== 1;\n this.zooming = touches.length === 2 && !offsetX;\n\n if (this.zooming) {\n this.startScale = this.scale;\n this.startDistance = getDistance(event.touches);\n }\n },\n onTouchMove: function onTouchMove(event) {\n var touches = event.touches;\n this.touchMove(event);\n\n if (this.moving || this.zooming) {\n Object(_utils_dom_event__WEBPACK_IMPORTED_MODULE_2__[\"preventDefault\"])(event, true);\n }\n\n if (this.moving) {\n var moveX = this.deltaX + this.startMoveX;\n var moveY = this.deltaY + this.startMoveY;\n this.moveX = Object(_utils_format_number__WEBPACK_IMPORTED_MODULE_1__[\"range\"])(moveX, -this.maxMoveX, this.maxMoveX);\n this.moveY = Object(_utils_format_number__WEBPACK_IMPORTED_MODULE_1__[\"range\"])(moveY, -this.maxMoveY, this.maxMoveY);\n }\n\n if (this.zooming && touches.length === 2) {\n var distance = getDistance(touches);\n var scale = this.startScale * distance / this.startDistance;\n this.setScale(scale);\n }\n },\n onTouchEnd: function onTouchEnd(event) {\n var stopPropagation = false;\n /* istanbul ignore else */\n\n if (this.moving || this.zooming) {\n stopPropagation = true;\n\n if (this.moving && this.startMoveX === this.moveX && this.startMoveY === this.moveY) {\n stopPropagation = false;\n }\n\n if (!event.touches.length) {\n if (this.zooming) {\n this.moveX = Object(_utils_format_number__WEBPACK_IMPORTED_MODULE_1__[\"range\"])(this.moveX, -this.maxMoveX, this.maxMoveX);\n this.moveY = Object(_utils_format_number__WEBPACK_IMPORTED_MODULE_1__[\"range\"])(this.moveY, -this.maxMoveY, this.maxMoveY);\n this.zooming = false;\n }\n\n this.moving = false;\n this.startMoveX = 0;\n this.startMoveY = 0;\n this.startScale = 1;\n\n if (this.scale < 1) {\n this.resetScale();\n }\n }\n } // eliminate tap delay on safari\n\n\n Object(_utils_dom_event__WEBPACK_IMPORTED_MODULE_2__[\"preventDefault\"])(event, stopPropagation);\n this.checkTap();\n this.resetTouchStatus();\n },\n checkTap: function checkTap() {\n var _this = this;\n\n var _this$offsetX2 = this.offsetX,\n offsetX = _this$offsetX2 === void 0 ? 0 : _this$offsetX2,\n _this$offsetY = this.offsetY,\n offsetY = _this$offsetY === void 0 ? 0 : _this$offsetY;\n var deltaTime = new Date() - this.touchStartTime;\n var TAP_TIME = 250;\n var TAP_OFFSET = 10;\n\n if (offsetX < TAP_OFFSET && offsetY < TAP_OFFSET && deltaTime < TAP_TIME) {\n if (this.doubleTapTimer) {\n clearTimeout(this.doubleTapTimer);\n this.doubleTapTimer = null;\n this.toggleScale();\n } else {\n this.doubleTapTimer = setTimeout(function () {\n _this.$emit('close');\n\n _this.doubleTapTimer = null;\n }, TAP_TIME);\n }\n }\n },\n onLoad: function onLoad(event) {\n var _event$target = event.target,\n naturalWidth = _event$target.naturalWidth,\n naturalHeight = _event$target.naturalHeight;\n this.imageRatio = naturalHeight / naturalWidth;\n }\n },\n render: function render() {\n var h = arguments[0];\n var imageSlots = {\n loading: function loading() {\n return h(_loading__WEBPACK_IMPORTED_MODULE_5__[\"default\"], {\n \"attrs\": {\n \"type\": \"spinner\"\n }\n });\n }\n };\n return h(_swipe_item__WEBPACK_IMPORTED_MODULE_6__[\"default\"], {\n \"class\": Object(_shared__WEBPACK_IMPORTED_MODULE_0__[\"bem\"])('swipe-item')\n }, [h(_image__WEBPACK_IMPORTED_MODULE_4__[\"default\"], {\n \"attrs\": {\n \"src\": this.src,\n \"fit\": \"contain\"\n },\n \"class\": Object(_shared__WEBPACK_IMPORTED_MODULE_0__[\"bem\"])('image', {\n vertical: this.vertical\n }),\n \"style\": this.imageStyle,\n \"scopedSlots\": imageSlots,\n \"on\": {\n \"load\": this.onLoad\n }\n })]);\n }\n});\n\n//# sourceURL=webpack:///./node_modules/vant/es/image-preview/ImagePreviewItem.js?"); /***/ }), /***/ "./node_modules/vant/es/image-preview/index.css": /*!******************************************************!*\ !*** ./node_modules/vant/es/image-preview/index.css ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = __webpack_require__(/*! !../../../css-loader/dist/cjs.js??ref--6-oneOf-3-1!../../../postcss-loader/src??ref--6-oneOf-3-2!./index.css */ \"./node_modules/css-loader/dist/cjs.js?!./node_modules/postcss-loader/src/index.js?!./node_modules/vant/es/image-preview/index.css\");\nif(typeof content === 'string') content = [[module.i, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = __webpack_require__(/*! ../../../vue-style-loader/lib/addStylesClient.js */ \"./node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"6f02f7c9\", content, false, {\"sourceMap\":false,\"shadowMode\":false});\n// Hot Module Replacement\nif(false) {}\n\n//# sourceURL=webpack:///./node_modules/vant/es/image-preview/index.css?"); /***/ }), /***/ "./node_modules/vant/es/image-preview/index.js": /*!*****************************************************!*\ !*** ./node_modules/vant/es/image-preview/index.js ***! \*****************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ \"./node_modules/@babel/runtime/helpers/esm/extends.js\");\n/* harmony import */ var vue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! vue */ \"./node_modules/vue/dist/vue.runtime.esm.js\");\n/* harmony import */ var _ImagePreview__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ImagePreview */ \"./node_modules/vant/es/image-preview/ImagePreview.js\");\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils */ \"./node_modules/vant/es/utils/index.js\");\n\n\n\n\nvar instance;\nvar defaultConfig = {\n loop: true,\n images: [],\n value: true,\n minZoom: 1 / 3,\n maxZoom: 3,\n className: '',\n onClose: null,\n onChange: null,\n showIndex: true,\n closeable: false,\n closeIcon: 'clear',\n asyncClose: false,\n startPosition: 0,\n swipeDuration: 500,\n showIndicators: false,\n closeOnPopstate: false,\n closeIconPosition: 'top-right',\n getContainer: 'body'\n};\n\nvar initInstance = function initInstance() {\n instance = new (vue__WEBPACK_IMPORTED_MODULE_1__[\"default\"].extend(_ImagePreview__WEBPACK_IMPORTED_MODULE_2__[\"default\"]))({\n el: document.createElement('div')\n });\n document.body.appendChild(instance.$el);\n instance.$on('change', function (index) {\n if (instance.onChange) {\n instance.onChange(index);\n }\n });\n instance.$on('scale', function (data) {\n if (instance.onScale) {\n instance.onScale(data);\n }\n });\n};\n\nvar ImagePreview = function ImagePreview(images, startPosition) {\n if (startPosition === void 0) {\n startPosition = 0;\n }\n\n /* istanbul ignore if */\n if (_utils__WEBPACK_IMPORTED_MODULE_3__[\"isServer\"]) {\n return;\n }\n\n if (!instance) {\n initInstance();\n }\n\n var options = Array.isArray(images) ? {\n images: images,\n startPosition: startPosition\n } : images;\n\n Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(instance, defaultConfig, options);\n\n instance.$once('input', function (show) {\n instance.value = show;\n });\n instance.$once('closed', function () {\n instance.images = [];\n });\n\n if (options.onClose) {\n instance.$off('close');\n instance.$once('close', options.onClose);\n }\n\n return instance;\n};\n\nImagePreview.Component = _ImagePreview__WEBPACK_IMPORTED_MODULE_2__[\"default\"];\n\nImagePreview.install = function () {\n vue__WEBPACK_IMPORTED_MODULE_1__[\"default\"].use(_ImagePreview__WEBPACK_IMPORTED_MODULE_2__[\"default\"]);\n};\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (ImagePreview);\n\n//# sourceURL=webpack:///./node_modules/vant/es/image-preview/index.js?"); /***/ }), /***/ "./node_modules/vant/es/image-preview/shared.js": /*!******************************************************!*\ !*** ./node_modules/vant/es/image-preview/shared.js ***! \******************************************************/ /*! exports provided: createComponent, bem */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"createComponent\", function() { return createComponent; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"bem\", function() { return bem; });\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ \"./node_modules/vant/es/utils/index.js\");\n\n\nvar _createNamespace = Object(_utils__WEBPACK_IMPORTED_MODULE_0__[\"createNamespace\"])('image-preview'),\n createComponent = _createNamespace[0],\n bem = _createNamespace[1];\n\n\n\n//# sourceURL=webpack:///./node_modules/vant/es/image-preview/shared.js?"); /***/ }), /***/ "./node_modules/vant/es/image-preview/style/index.js": /*!***********************************************************!*\ !*** ./node_modules/vant/es/image-preview/style/index.js ***! \***********************************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _style_base_css__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../style/base.css */ \"./node_modules/vant/es/style/base.css\");\n/* harmony import */ var _style_base_css__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_base_css__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _overlay_index_css__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../overlay/index.css */ \"./node_modules/vant/es/overlay/index.css\");\n/* harmony import */ var _overlay_index_css__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_overlay_index_css__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var _info_index_css__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../info/index.css */ \"./node_modules/vant/es/info/index.css\");\n/* harmony import */ var _info_index_css__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_info_index_css__WEBPACK_IMPORTED_MODULE_2__);\n/* harmony import */ var _icon_index_css__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../icon/index.css */ \"./node_modules/vant/es/icon/index.css\");\n/* harmony import */ var _icon_index_css__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_icon_index_css__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var _image_index_css__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../image/index.css */ \"./node_modules/vant/es/image/index.css\");\n/* harmony import */ var _image_index_css__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_image_index_css__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var _popup_index_css__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../popup/index.css */ \"./node_modules/vant/es/popup/index.css\");\n/* harmony import */ var _popup_index_css__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_popup_index_css__WEBPACK_IMPORTED_MODULE_5__);\n/* harmony import */ var _loading_index_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../loading/index.css */ \"./node_modules/vant/es/loading/index.css\");\n/* harmony import */ var _loading_index_css__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_loading_index_css__WEBPACK_IMPORTED_MODULE_6__);\n/* harmony import */ var _swipe_index_css__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../swipe/index.css */ \"./node_modules/vant/es/swipe/index.css\");\n/* harmony import */ var _swipe_index_css__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_swipe_index_css__WEBPACK_IMPORTED_MODULE_7__);\n/* harmony import */ var _swipe_item_index_css__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../swipe-item/index.css */ \"./node_modules/vant/es/swipe-item/index.css\");\n/* harmony import */ var _swipe_item_index_css__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_swipe_item_index_css__WEBPACK_IMPORTED_MODULE_8__);\n/* harmony import */ var _index_css__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../index.css */ \"./node_modules/vant/es/image-preview/index.css\");\n/* harmony import */ var _index_css__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_index_css__WEBPACK_IMPORTED_MODULE_9__);\n\n\n\n\n\n\n\n\n\n\n\n//# sourceURL=webpack:///./node_modules/vant/es/image-preview/style/index.js?"); /***/ }), /***/ "./node_modules/vant/es/image/index.css": /*!**********************************************!*\ !*** ./node_modules/vant/es/image/index.css ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = __webpack_require__(/*! !../../../css-loader/dist/cjs.js??ref--6-oneOf-3-1!../../../postcss-loader/src??ref--6-oneOf-3-2!./index.css */ \"./node_modules/css-loader/dist/cjs.js?!./node_modules/postcss-loader/src/index.js?!./node_modules/vant/es/image/index.css\");\nif(typeof content === 'string') content = [[module.i, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = __webpack_require__(/*! ../../../vue-style-loader/lib/addStylesClient.js */ \"./node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"09cac48e\", content, false, {\"sourceMap\":false,\"shadowMode\":false});\n// Hot Module Replacement\nif(false) {}\n\n//# sourceURL=webpack:///./node_modules/vant/es/image/index.css?"); /***/ }), /***/ "./node_modules/vant/es/image/index.js": /*!*********************************************!*\ !*** ./node_modules/vant/es/image/index.js ***! \*********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _vue_babel_helper_vue_jsx_merge_props__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @vue/babel-helper-vue-jsx-merge-props */ \"./node_modules/@vue/babel-helper-vue-jsx-merge-props/dist/helper.js\");\n/* harmony import */ var _vue_babel_helper_vue_jsx_merge_props__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_vue_babel_helper_vue_jsx_merge_props__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ \"./node_modules/vant/es/utils/index.js\");\n/* harmony import */ var _icon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../icon */ \"./node_modules/vant/es/icon/index.js\");\n\n\n\n\n\nvar _createNamespace = Object(_utils__WEBPACK_IMPORTED_MODULE_1__[\"createNamespace\"])('image'),\n createComponent = _createNamespace[0],\n bem = _createNamespace[1];\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (createComponent({\n props: {\n src: String,\n fit: String,\n alt: String,\n round: Boolean,\n width: [Number, String],\n height: [Number, String],\n radius: [Number, String],\n lazyLoad: Boolean,\n showError: {\n type: Boolean,\n default: true\n },\n showLoading: {\n type: Boolean,\n default: true\n },\n errorIcon: {\n type: String,\n default: 'warning-o'\n },\n loadingIcon: {\n type: String,\n default: 'photo-o'\n }\n },\n data: function data() {\n return {\n loading: true,\n error: false\n };\n },\n watch: {\n src: function src() {\n this.loading = true;\n this.error = false;\n }\n },\n computed: {\n style: function style() {\n var style = {};\n\n if (Object(_utils__WEBPACK_IMPORTED_MODULE_1__[\"isDef\"])(this.width)) {\n style.width = Object(_utils__WEBPACK_IMPORTED_MODULE_1__[\"addUnit\"])(this.width);\n }\n\n if (Object(_utils__WEBPACK_IMPORTED_MODULE_1__[\"isDef\"])(this.height)) {\n style.height = Object(_utils__WEBPACK_IMPORTED_MODULE_1__[\"addUnit\"])(this.height);\n }\n\n if (Object(_utils__WEBPACK_IMPORTED_MODULE_1__[\"isDef\"])(this.radius)) {\n style.overflow = 'hidden';\n style.borderRadius = Object(_utils__WEBPACK_IMPORTED_MODULE_1__[\"addUnit\"])(this.radius);\n }\n\n return style;\n }\n },\n created: function created() {\n var $Lazyload = this.$Lazyload;\n\n if ($Lazyload && _utils__WEBPACK_IMPORTED_MODULE_1__[\"inBrowser\"]) {\n $Lazyload.$on('loaded', this.onLazyLoaded);\n $Lazyload.$on('error', this.onLazyLoadError);\n }\n },\n beforeDestroy: function beforeDestroy() {\n var $Lazyload = this.$Lazyload;\n\n if ($Lazyload) {\n $Lazyload.$off('loaded', this.onLazyLoaded);\n $Lazyload.$off('error', this.onLazyLoadError);\n }\n },\n methods: {\n onLoad: function onLoad(event) {\n this.loading = false;\n this.$emit('load', event);\n },\n onLazyLoaded: function onLazyLoaded(_ref) {\n var el = _ref.el;\n\n if (el === this.$refs.image && this.loading) {\n this.onLoad();\n }\n },\n onLazyLoadError: function onLazyLoadError(_ref2) {\n var el = _ref2.el;\n\n if (el === this.$refs.image && !this.error) {\n this.onError();\n }\n },\n onError: function onError(event) {\n this.error = true;\n this.loading = false;\n this.$emit('error', event);\n },\n onClick: function onClick(event) {\n this.$emit('click', event);\n },\n genPlaceholder: function genPlaceholder() {\n var h = this.$createElement;\n\n if (this.loading && this.showLoading) {\n return h(\"div\", {\n \"class\": bem('loading')\n }, [this.slots('loading') || h(_icon__WEBPACK_IMPORTED_MODULE_2__[\"default\"], {\n \"attrs\": {\n \"name\": this.loadingIcon\n },\n \"class\": bem('loading-icon')\n })]);\n }\n\n if (this.error && this.showError) {\n return h(\"div\", {\n \"class\": bem('error')\n }, [this.slots('error') || h(_icon__WEBPACK_IMPORTED_MODULE_2__[\"default\"], {\n \"attrs\": {\n \"name\": this.errorIcon\n },\n \"class\": bem('error-icon')\n })]);\n }\n },\n genImage: function genImage() {\n var h = this.$createElement;\n var imgData = {\n class: bem('img'),\n attrs: {\n alt: this.alt\n },\n style: {\n objectFit: this.fit\n }\n };\n\n if (this.error) {\n return;\n }\n\n if (this.lazyLoad) {\n return h(\"img\", _vue_babel_helper_vue_jsx_merge_props__WEBPACK_IMPORTED_MODULE_0___default()([{\n \"ref\": \"image\",\n \"directives\": [{\n name: \"lazy\",\n value: this.src\n }]\n }, imgData]));\n }\n\n return h(\"img\", _vue_babel_helper_vue_jsx_merge_props__WEBPACK_IMPORTED_MODULE_0___default()([{\n \"attrs\": {\n \"src\": this.src\n },\n \"on\": {\n \"load\": this.onLoad,\n \"error\": this.onError\n }\n }, imgData]));\n }\n },\n render: function render() {\n var h = arguments[0];\n return h(\"div\", {\n \"class\": bem({\n round: this.round\n }),\n \"style\": this.style,\n \"on\": {\n \"click\": this.onClick\n }\n }, [this.genImage(), this.genPlaceholder(), this.slots()]);\n }\n}));\n\n//# sourceURL=webpack:///./node_modules/vant/es/image/index.js?"); /***/ }), /***/ "./node_modules/vant/es/mixins/relation.js": /*!*************************************************!*\ !*** ./node_modules/vant/es/mixins/relation.js ***! \*************************************************/ /*! exports provided: ChildrenMixin, ParentMixin */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ChildrenMixin\", function() { return ChildrenMixin; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ParentMixin\", function() { return ParentMixin; });\n/* harmony import */ var _utils_vnodes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/vnodes */ \"./node_modules/vant/es/utils/vnodes.js\");\n\nfunction ChildrenMixin(_parent, options) {\n var _inject, _computed;\n\n if (options === void 0) {\n options = {};\n }\n\n var indexKey = options.indexKey || 'index';\n return {\n inject: (_inject = {}, _inject[_parent] = {\n default: null\n }, _inject),\n computed: (_computed = {\n parent: function parent() {\n if (this.disableBindRelation) {\n return null;\n }\n\n return this[_parent];\n }\n }, _computed[indexKey] = function () {\n this.bindRelation();\n\n if (this.parent) {\n return this.parent.children.indexOf(this);\n }\n\n return null;\n }, _computed),\n watch: {\n disableBindRelation: function disableBindRelation(val) {\n if (!val) {\n this.bindRelation();\n }\n }\n },\n mounted: function mounted() {\n this.bindRelation();\n },\n beforeDestroy: function beforeDestroy() {\n var _this = this;\n\n if (this.parent) {\n this.parent.children = this.parent.children.filter(function (item) {\n return item !== _this;\n });\n }\n },\n methods: {\n bindRelation: function bindRelation() {\n if (!this.parent || this.parent.children.indexOf(this) !== -1) {\n return;\n }\n\n var children = [].concat(this.parent.children, [this]);\n Object(_utils_vnodes__WEBPACK_IMPORTED_MODULE_0__[\"sortChildren\"])(children, this.parent);\n this.parent.children = children;\n }\n }\n };\n}\nfunction ParentMixin(parent) {\n return {\n provide: function provide() {\n var _ref;\n\n return _ref = {}, _ref[parent] = this, _ref;\n },\n data: function data() {\n return {\n children: []\n };\n }\n };\n}\n\n//# sourceURL=webpack:///./node_modules/vant/es/mixins/relation.js?"); /***/ }), /***/ "./node_modules/vant/es/swipe-item/index.css": /*!***************************************************!*\ !*** ./node_modules/vant/es/swipe-item/index.css ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = __webpack_require__(/*! !../../../css-loader/dist/cjs.js??ref--6-oneOf-3-1!../../../postcss-loader/src??ref--6-oneOf-3-2!./index.css */ \"./node_modules/css-loader/dist/cjs.js?!./node_modules/postcss-loader/src/index.js?!./node_modules/vant/es/swipe-item/index.css\");\nif(typeof content === 'string') content = [[module.i, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = __webpack_require__(/*! ../../../vue-style-loader/lib/addStylesClient.js */ \"./node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"5d25e163\", content, false, {\"sourceMap\":false,\"shadowMode\":false});\n// Hot Module Replacement\nif(false) {}\n\n//# sourceURL=webpack:///./node_modules/vant/es/swipe-item/index.css?"); /***/ }), /***/ "./node_modules/vant/es/swipe-item/index.js": /*!**************************************************!*\ !*** ./node_modules/vant/es/swipe-item/index.js ***! \**************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ \"./node_modules/@babel/runtime/helpers/esm/extends.js\");\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ \"./node_modules/vant/es/utils/index.js\");\n/* harmony import */ var _mixins_relation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../mixins/relation */ \"./node_modules/vant/es/mixins/relation.js\");\n\n\n\n\nvar _createNamespace = Object(_utils__WEBPACK_IMPORTED_MODULE_1__[\"createNamespace\"])('swipe-item'),\n createComponent = _createNamespace[0],\n bem = _createNamespace[1];\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (createComponent({\n mixins: [Object(_mixins_relation__WEBPACK_IMPORTED_MODULE_2__[\"ChildrenMixin\"])('vanSwipe')],\n data: function data() {\n return {\n offset: 0,\n mounted: false\n };\n },\n mounted: function mounted() {\n var _this = this;\n\n this.$nextTick(function () {\n _this.mounted = true;\n });\n },\n computed: {\n style: function style() {\n var style = {};\n var _this$parent = this.parent,\n size = _this$parent.size,\n vertical = _this$parent.vertical;\n style[vertical ? 'height' : 'width'] = size + \"px\";\n\n if (this.offset) {\n style.transform = \"translate\" + (vertical ? 'Y' : 'X') + \"(\" + this.offset + \"px)\";\n }\n\n return style;\n },\n shouldRender: function shouldRender() {\n var index = this.index,\n parent = this.parent,\n mounted = this.mounted;\n\n if (!parent.lazyRender) {\n return true;\n } // wait for all item to mount, so we can get the exact count\n\n\n if (!mounted) {\n return false;\n }\n\n var active = parent.activeIndicator;\n var maxActive = parent.count - 1;\n var prevActive = active === 0 ? maxActive : active - 1;\n var nextActive = active === maxActive ? 0 : active + 1;\n return index === active || index === prevActive || index === nextActive;\n }\n },\n render: function render() {\n var h = arguments[0];\n return h(\"div\", {\n \"class\": bem(),\n \"style\": this.style,\n \"on\": Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[\"default\"])({}, this.$listeners)\n }, [this.shouldRender && this.slots()]);\n }\n}));\n\n//# sourceURL=webpack:///./node_modules/vant/es/swipe-item/index.js?"); /***/ }), /***/ "./node_modules/vant/es/swipe/index.css": /*!**********************************************!*\ !*** ./node_modules/vant/es/swipe/index.css ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = __webpack_require__(/*! !../../../css-loader/dist/cjs.js??ref--6-oneOf-3-1!../../../postcss-loader/src??ref--6-oneOf-3-2!./index.css */ \"./node_modules/css-loader/dist/cjs.js?!./node_modules/postcss-loader/src/index.js?!./node_modules/vant/es/swipe/index.css\");\nif(typeof content === 'string') content = [[module.i, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = __webpack_require__(/*! ../../../vue-style-loader/lib/addStylesClient.js */ \"./node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"185dcfad\", content, false, {\"sourceMap\":false,\"shadowMode\":false});\n// Hot Module Replacement\nif(false) {}\n\n//# sourceURL=webpack:///./node_modules/vant/es/swipe/index.css?"); /***/ }), /***/ "./node_modules/vant/es/swipe/index.js": /*!*********************************************!*\ !*** ./node_modules/vant/es/swipe/index.js ***! \*********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ \"./node_modules/vant/es/utils/index.js\");\n/* harmony import */ var _utils_dom_style__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/dom/style */ \"./node_modules/vant/es/utils/dom/style.js\");\n/* harmony import */ var _utils_dom_event__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/dom/event */ \"./node_modules/vant/es/utils/dom/event.js\");\n/* harmony import */ var _utils_dom_raf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/dom/raf */ \"./node_modules/vant/es/utils/dom/raf.js\");\n/* harmony import */ var _utils_format_number__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/format/number */ \"./node_modules/vant/es/utils/format/number.js\");\n/* harmony import */ var _mixins_touch__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../mixins/touch */ \"./node_modules/vant/es/mixins/touch.js\");\n/* harmony import */ var _mixins_relation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../mixins/relation */ \"./node_modules/vant/es/mixins/relation.js\");\n/* harmony import */ var _mixins_bind_event__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../mixins/bind-event */ \"./node_modules/vant/es/mixins/bind-event.js\");\n// Utils\n\n\n\n\n // Mixins\n\n\n\n\n\nvar _createNamespace = Object(_utils__WEBPACK_IMPORTED_MODULE_0__[\"createNamespace\"])('swipe'),\n createComponent = _createNamespace[0],\n bem = _createNamespace[1];\n\n/* harmony default export */ __webpack_exports__[\"default\"] = (createComponent({\n mixins: [_mixins_touch__WEBPACK_IMPORTED_MODULE_5__[\"TouchMixin\"], Object(_mixins_relation__WEBPACK_IMPORTED_MODULE_6__[\"ParentMixin\"])('vanSwipe'), Object(_mixins_bind_event__WEBPACK_IMPORTED_MODULE_7__[\"BindEventMixin\"])(function (bind, isBind) {\n bind(window, 'resize', this.resize, true);\n bind(window, 'visibilitychange', this.onVisibilityChange);\n\n if (isBind) {\n this.initialize();\n } else {\n this.clear();\n }\n })],\n props: {\n width: [Number, String],\n height: [Number, String],\n autoplay: [Number, String],\n vertical: Boolean,\n lazyRender: Boolean,\n indicatorColor: String,\n loop: {\n type: Boolean,\n default: true\n },\n duration: {\n type: [Number, String],\n default: 500\n },\n touchable: {\n type: Boolean,\n default: true\n },\n initialSwipe: {\n type: [Number, String],\n default: 0\n },\n showIndicators: {\n type: Boolean,\n default: true\n },\n stopPropagation: {\n type: Boolean,\n default: true\n }\n },\n data: function data() {\n return {\n rect: null,\n offset: 0,\n active: 0,\n deltaX: 0,\n deltaY: 0,\n swiping: false,\n computedWidth: 0,\n computedHeight: 0\n };\n },\n watch: {\n children: function children() {\n this.initialize();\n },\n initialSwipe: function initialSwipe() {\n this.initialize();\n },\n autoplay: function autoplay(_autoplay) {\n if (_autoplay > 0) {\n this.autoPlay();\n } else {\n this.clear();\n }\n }\n },\n computed: {\n count: function count() {\n return this.children.length;\n },\n maxCount: function maxCount() {\n return Math.ceil(Math.abs(this.minOffset) / this.size);\n },\n delta: function delta() {\n return this.vertical ? this.deltaY : this.deltaX;\n },\n size: function size() {\n return this[this.vertical ? 'computedHeight' : 'computedWidth'];\n },\n trackSize: function trackSize() {\n return this.count * this.size;\n },\n activeIndicator: function activeIndicator() {\n return (this.active + this.count) % this.count;\n },\n isCorrectDirection: function isCorrectDirection() {\n var expect = this.vertical ? 'vertical' : 'horizontal';\n return this.direction === expect;\n },\n trackStyle: function trackStyle() {\n var _ref;\n\n var mainAxis = this.vertical ? 'height' : 'width';\n var crossAxis = this.vertical ? 'width' : 'height';\n return _ref = {}, _ref[mainAxis] = this.trackSize + \"px\", _ref[crossAxis] = this[crossAxis] ? this[crossAxis] + \"px\" : '', _ref.transitionDuration = (this.swiping ? 0 : this.duration) + \"ms\", _ref.transform = \"translate\" + (this.vertical ? 'Y' : 'X') + \"(\" + this.offset + \"px)\", _ref;\n },\n indicatorStyle: function indicatorStyle() {\n return {\n backgroundColor: this.indicatorColor\n };\n },\n minOffset: function minOffset() {\n return (this.vertical ? this.rect.height : this.rect.width) - this.size * this.count;\n }\n },\n mounted: function mounted() {\n this.bindTouchEvent(this.$refs.track);\n },\n methods: {\n // initialize swipe position\n initialize: function initialize(active) {\n if (active === void 0) {\n active = +this.initialSwipe;\n }\n\n if (!this.$el || Object(_utils_dom_style__WEBPACK_IMPORTED_MODULE_1__[\"isHidden\"])(this.$el)) {\n return;\n }\n\n clearTimeout(this.timer);\n var rect = this.$el.getBoundingClientRect();\n this.rect = rect;\n this.swiping = true;\n this.active = active;\n this.computedWidth = Math.round(+this.width || rect.width);\n this.computedHeight = Math.round(+this.height || rect.height);\n this.offset = this.getTargetOffset(active);\n this.children.forEach(function (swipe) {\n swipe.offset = 0;\n });\n this.autoPlay();\n },\n // @exposed-api\n resize: function resize() {\n this.initialize(this.activeIndicator);\n },\n onVisibilityChange: function onVisibilityChange() {\n if (document.hidden) {\n this.clear();\n } else {\n this.autoPlay();\n }\n },\n onTouchStart: function onTouchStart(event) {\n if (!this.touchable) return;\n this.clear();\n this.touchStartTime = Date.now();\n this.touchStart(event);\n this.correctPosition();\n },\n onTouchMove: function onTouchMove(event) {\n if (!this.touchable || !this.swiping) return;\n this.touchMove(event);\n\n if (this.isCorrectDirection) {\n Object(_utils_dom_event__WEBPACK_IMPORTED_MODULE_2__[\"preventDefault\"])(event, this.stopPropagation);\n this.move({\n offset: this.delta\n });\n }\n },\n onTouchEnd: function onTouchEnd() {\n if (!this.touchable || !this.swiping) return;\n var size = this.size,\n delta = this.delta;\n var duration = Date.now() - this.touchStartTime;\n var speed = delta / duration;\n var shouldSwipe = Math.abs(speed) > 0.25 || Math.abs(delta) > size / 2;\n\n if (shouldSwipe && this.isCorrectDirection) {\n var offset = this.vertical ? this.offsetY : this.offsetX;\n var pace = 0;\n\n if (this.loop) {\n pace = offset > 0 ? delta > 0 ? -1 : 1 : 0;\n } else {\n pace = -Math[delta > 0 ? 'ceil' : 'floor'](delta / size);\n }\n\n this.move({\n pace: pace,\n emitChange: true\n });\n } else if (delta) {\n this.move({\n pace: 0\n });\n }\n\n this.swiping = false;\n this.autoPlay();\n },\n getTargetActive: function getTargetActive(pace) {\n var active = this.active,\n count = this.count,\n maxCount = this.maxCount;\n\n if (pace) {\n if (this.loop) {\n return Object(_utils_format_number__WEBPACK_IMPORTED_MODULE_4__[\"range\"])(active + pace, -1, count);\n }\n\n return Object(_utils_format_number__WEBPACK_IMPORTED_MODULE_4__[\"range\"])(active + pace, 0, maxCount);\n }\n\n return active;\n },\n getTargetOffset: function getTargetOffset(targetActive, offset) {\n if (offset === void 0) {\n offset = 0;\n }\n\n var currentPosition = targetActive * this.size;\n\n if (!this.loop) {\n currentPosition = Math.min(currentPosition, -this.minOffset);\n }\n\n var targetOffset = Math.round(offset - currentPosition);\n\n if (!this.loop) {\n targetOffset = Object(_utils_format_number__WEBPACK_IMPORTED_MODULE_4__[\"range\"])(targetOffset, this.minOffset, 0);\n }\n\n return targetOffset;\n },\n move: function move(_ref2) {\n var _ref2$pace = _ref2.pace,\n pace = _ref2$pace === void 0 ? 0 : _ref2$pace,\n _ref2$offset = _ref2.offset,\n offset = _ref2$offset === void 0 ? 0 : _ref2$offset,\n emitChange = _ref2.emitChange;\n var loop = this.loop,\n count = this.count,\n active = this.active,\n children = this.children,\n trackSize = this.trackSize,\n minOffset = this.minOffset;\n\n if (count <= 1) {\n return;\n }\n\n var targetActive = this.getTargetActive(pace);\n var targetOffset = this.getTargetOffset(targetActive, offset); // auto move first and last swipe in loop mode\n\n if (loop) {\n if (children[0] && targetOffset !== minOffset) {\n var outRightBound = targetOffset < minOffset;\n children[0].offset = outRightBound ? trackSize : 0;\n }\n\n if (children[count - 1] && targetOffset !== 0) {\n var outLeftBound = targetOffset > 0;\n children[count - 1].offset = outLeftBound ? -trackSize : 0;\n }\n }\n\n this.active = targetActive;\n this.offset = targetOffset;\n\n if (emitChange && targetActive !== active) {\n this.$emit('change', this.activeIndicator);\n }\n },\n // @exposed-api\n prev: function prev() {\n var _this = this;\n\n this.correctPosition();\n this.resetTouchStatus();\n Object(_utils_dom_raf__WEBPACK_IMPORTED_MODULE_3__[\"doubleRaf\"])(function () {\n _this.swiping = false;\n\n _this.move({\n pace: -1,\n emitChange: true\n });\n });\n },\n // @exposed-api\n next: function next() {\n var _this2 = this;\n\n this.correctPosition();\n this.resetTouchStatus();\n Object(_utils_dom_raf__WEBPACK_IMPORTED_MODULE_3__[\"doubleRaf\"])(function () {\n _this2.swiping = false;\n\n _this2.move({\n pace: 1,\n emitChange: true\n });\n });\n },\n // @exposed-api\n swipeTo: function swipeTo(index, options) {\n var _this3 = this;\n\n if (options === void 0) {\n options = {};\n }\n\n this.correctPosition();\n this.resetTouchStatus();\n Object(_utils_dom_raf__WEBPACK_IMPORTED_MODULE_3__[\"doubleRaf\"])(function () {\n var targetIndex;\n\n if (_this3.loop && index === _this3.count) {\n targetIndex = _this3.active === 0 ? 0 : index;\n } else {\n targetIndex = index % _this3.count;\n }\n\n if (options.immediate) {\n Object(_utils_dom_raf__WEBPACK_IMPORTED_MODULE_3__[\"doubleRaf\"])(function () {\n _this3.swiping = false;\n });\n } else {\n _this3.swiping = false;\n }\n\n _this3.move({\n pace: targetIndex - _this3.active,\n emitChange: true\n });\n });\n },\n correctPosition: function correctPosition() {\n this.swiping = true;\n\n if (this.active <= -1) {\n this.move({\n pace: this.count\n });\n }\n\n if (this.active >= this.count) {\n this.move({\n pace: -this.count\n });\n }\n },\n clear: function clear() {\n clearTimeout(this.timer);\n },\n autoPlay: function autoPlay() {\n var _this4 = this;\n\n var autoplay = this.autoplay;\n\n if (autoplay > 0 && this.count > 1) {\n this.clear();\n this.timer = setTimeout(function () {\n _this4.next();\n\n _this4.autoPlay();\n }, autoplay);\n }\n },\n genIndicator: function genIndicator() {\n var _this5 = this;\n\n var h = this.$createElement;\n var count = this.count,\n activeIndicator = this.activeIndicator;\n var slot = this.slots('indicator');\n\n if (slot) {\n return slot;\n }\n\n if (this.showIndicators && count > 1) {\n return h(\"div\", {\n \"class\": bem('indicators', {\n vertical: this.vertical\n })\n }, [Array.apply(void 0, Array(count)).map(function (empty, index) {\n return h(\"i\", {\n \"class\": bem('indicator', {\n active: index === activeIndicator\n }),\n \"style\": index === activeIndicator ? _this5.indicatorStyle : null\n });\n })]);\n }\n }\n },\n render: function render() {\n var h = arguments[0];\n return h(\"div\", {\n \"class\": bem()\n }, [h(\"div\", {\n \"ref\": \"track\",\n \"style\": this.trackStyle,\n \"class\": bem('track', {\n vertical: this.vertical\n })\n }, [this.slots()]), this.genIndicator()]);\n }\n}));\n\n//# sourceURL=webpack:///./node_modules/vant/es/swipe/index.js?"); /***/ }), /***/ "./node_modules/vant/es/utils/dom/raf.js": /*!***********************************************!*\ !*** ./node_modules/vant/es/utils/dom/raf.js ***! \***********************************************/ /*! exports provided: raf, doubleRaf, cancelRaf */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"raf\", function() { return raf; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"doubleRaf\", function() { return doubleRaf; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"cancelRaf\", function() { return cancelRaf; });\n/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! .. */ \"./node_modules/vant/es/utils/index.js\");\n/**\n * requestAnimationFrame polyfill\n */\n\nvar prev = Date.now();\n/* istanbul ignore next */\n\nfunction fallback(fn) {\n var curr = Date.now();\n var ms = Math.max(0, 16 - (curr - prev));\n var id = setTimeout(fn, ms);\n prev = curr + ms;\n return id;\n}\n/* istanbul ignore next */\n\n\nvar root = ___WEBPACK_IMPORTED_MODULE_0__[\"isServer\"] ? global : window;\n/* istanbul ignore next */\n\nvar iRaf = root.requestAnimationFrame || fallback;\n/* istanbul ignore next */\n\nvar iCancel = root.cancelAnimationFrame || root.clearTimeout;\nfunction raf(fn) {\n return iRaf.call(root, fn);\n} // double raf for animation\n\nfunction doubleRaf(fn) {\n raf(function () {\n raf(fn);\n });\n}\nfunction cancelRaf(id) {\n iCancel.call(root, id);\n}\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))\n\n//# sourceURL=webpack:///./node_modules/vant/es/utils/dom/raf.js?"); /***/ }), /***/ "./node_modules/vant/es/utils/dom/style.js": /*!*************************************************!*\ !*** ./node_modules/vant/es/utils/dom/style.js ***! \*************************************************/ /*! exports provided: isHidden */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isHidden\", function() { return isHidden; });\nfunction isHidden(el) {\n var style = window.getComputedStyle(el);\n var hidden = style.display === 'none'; // offsetParent returns null in the following situations:\n // 1. The element or its parent element has the display property set to none.\n // 2. The element has the position property set to fixed\n\n var parentHidden = el.offsetParent === null && style.position !== 'fixed';\n return hidden || parentHidden;\n}\n\n//# sourceURL=webpack:///./node_modules/vant/es/utils/dom/style.js?"); /***/ }), /***/ "./node_modules/vant/es/utils/vnodes.js": /*!**********************************************!*\ !*** ./node_modules/vant/es/utils/vnodes.js ***! \**********************************************/ /*! exports provided: sortChildren */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"sortChildren\", function() { return sortChildren; });\nfunction flattenVNodes(vnodes) {\n var result = [];\n\n function traverse(vnodes) {\n vnodes.forEach(function (vnode) {\n result.push(vnode);\n\n if (vnode.componentInstance) {\n traverse(vnode.componentInstance.$children.map(function (item) {\n return item.$vnode;\n }));\n }\n\n if (vnode.children) {\n traverse(vnode.children);\n }\n });\n }\n\n traverse(vnodes);\n return result;\n} // sort children instances by vnodes order\n\n\nfunction sortChildren(children, parent) {\n var componentOptions = parent.$vnode.componentOptions;\n\n if (!componentOptions || !componentOptions.children) {\n return;\n }\n\n var vnodes = flattenVNodes(componentOptions.children);\n children.sort(function (a, b) {\n return vnodes.indexOf(a.$vnode) - vnodes.indexOf(b.$vnode);\n });\n}\n\n//# sourceURL=webpack:///./node_modules/vant/es/utils/vnodes.js?"); /***/ }), /***/ "./node_modules/vue-style-loader/index.js?!./node_modules/css-loader/dist/cjs.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true&": /*!*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/vue-style-loader??ref--8-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--8-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-1-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true& ***! \*************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("// style-loader: Adds some css to the DOM by adding a <style> tag\n\n// load the styles\nvar content = __webpack_require__(/*! !../../../../node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../node_modules/postcss-loader/src??ref--8-oneOf-1-2!../../../../node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-1-3!../../../../node_modules/cache-loader/dist/cjs.js??ref--0-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true& */ \"./node_modules/css-loader/dist/cjs.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true&\");\nif(typeof content === 'string') content = [[module.i, content, '']];\nif(content.locals) module.exports = content.locals;\n// add the styles to the DOM\nvar add = __webpack_require__(/*! ../../../../node_modules/vue-style-loader/lib/addStylesClient.js */ \"./node_modules/vue-style-loader/lib/addStylesClient.js\").default\nvar update = add(\"52ca70d8\", content, false, {\"sourceMap\":false,\"shadowMode\":false});\n// Hot Module Replacement\nif(false) {}\n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/typeOne.vue?./node_modules/vue-style-loader??ref--8-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--8-oneOf-1-2!./node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-1-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options"); /***/ }), /***/ "./src/components/baseComponents/base_upload/index.vue": /*!*************************************************************!*\ !*** ./src/components/baseComponents/base_upload/index.vue ***! \*************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _index_vue_vue_type_template_id_2a7849ba___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./index.vue?vue&type=template&id=2a7849ba& */ \"./src/components/baseComponents/base_upload/index.vue?vue&type=template&id=2a7849ba&\");\n/* harmony import */ var _index_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./index.vue?vue&type=script&lang=js& */ \"./src/components/baseComponents/base_upload/index.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ \"./node_modules/vue-loader/lib/runtime/componentNormalizer.js\");\n\n\n\n\n\n/* normalize component */\n\nvar component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(\n _index_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[\"default\"],\n _index_vue_vue_type_template_id_2a7849ba___WEBPACK_IMPORTED_MODULE_0__[\"render\"],\n _index_vue_vue_type_template_id_2a7849ba___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"],\n false,\n null,\n null,\n null\n \n)\n\n/* hot reload */\nif (false) { var api; }\ncomponent.options.__file = \"src/components/baseComponents/base_upload/index.vue\"\n/* harmony default export */ __webpack_exports__[\"default\"] = (component.exports);\n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/index.vue?"); /***/ }), /***/ "./src/components/baseComponents/base_upload/index.vue?vue&type=script&lang=js&": /*!**************************************************************************************!*\ !*** ./src/components/baseComponents/base_upload/index.vue?vue&type=script&lang=js& ***! \**************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_cache_loader_dist_cjs_js_ref_12_0_node_modules_babel_loader_lib_index_js_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_index_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/cache-loader/dist/cjs.js??ref--12-0!../../../../node_modules/babel-loader/lib!../../../../node_modules/cache-loader/dist/cjs.js??ref--0-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./index.vue?vue&type=script&lang=js& */ \"./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/index.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__[\"default\"] = (_node_modules_cache_loader_dist_cjs_js_ref_12_0_node_modules_babel_loader_lib_index_js_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_index_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[\"default\"]); \n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/index.vue?"); /***/ }), /***/ "./src/components/baseComponents/base_upload/index.vue?vue&type=template&id=2a7849ba&": /*!********************************************************************************************!*\ !*** ./src/components/baseComponents/base_upload/index.vue?vue&type=template&id=2a7849ba& ***! \********************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_cache_loader_dist_cjs_js_cacheDirectory_node_modules_cache_vue_loader_cacheIdentifier_7b323dac_vue_loader_template_node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_index_vue_vue_type_template_id_2a7849ba___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/cache-loader/dist/cjs.js?{\"cacheDirectory\":\"node_modules/.cache/vue-loader\",\"cacheIdentifier\":\"7b323dac-vue-loader-template\"}!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/cache-loader/dist/cjs.js??ref--0-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./index.vue?vue&type=template&id=2a7849ba& */ \"./node_modules/cache-loader/dist/cjs.js?{\\\"cacheDirectory\\\":\\\"node_modules/.cache/vue-loader\\\",\\\"cacheIdentifier\\\":\\\"7b323dac-vue-loader-template\\\"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/index.vue?vue&type=template&id=2a7849ba&\");\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return _node_modules_cache_loader_dist_cjs_js_cacheDirectory_node_modules_cache_vue_loader_cacheIdentifier_7b323dac_vue_loader_template_node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_index_vue_vue_type_template_id_2a7849ba___WEBPACK_IMPORTED_MODULE_0__[\"render\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return _node_modules_cache_loader_dist_cjs_js_cacheDirectory_node_modules_cache_vue_loader_cacheIdentifier_7b323dac_vue_loader_template_node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_index_vue_vue_type_template_id_2a7849ba___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"]; });\n\n\n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/index.vue?"); /***/ }), /***/ "./src/components/baseComponents/base_upload/typeOne.vue": /*!***************************************************************!*\ !*** ./src/components/baseComponents/base_upload/typeOne.vue ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _typeOne_vue_vue_type_template_id_3904a4b4_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typeOne.vue?vue&type=template&id=3904a4b4&scoped=true& */ \"./src/components/baseComponents/base_upload/typeOne.vue?vue&type=template&id=3904a4b4&scoped=true&\");\n/* harmony import */ var _typeOne_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./typeOne.vue?vue&type=script&lang=js& */ \"./src/components/baseComponents/base_upload/typeOne.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport *//* harmony import */ var _typeOne_vue_vue_type_style_index_0_id_3904a4b4_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true& */ \"./src/components/baseComponents/base_upload/typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true&\");\n/* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ \"./node_modules/vue-loader/lib/runtime/componentNormalizer.js\");\n\n\n\n\n\n\n/* normalize component */\n\nvar component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(\n _typeOne_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[\"default\"],\n _typeOne_vue_vue_type_template_id_3904a4b4_scoped_true___WEBPACK_IMPORTED_MODULE_0__[\"render\"],\n _typeOne_vue_vue_type_template_id_3904a4b4_scoped_true___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"],\n false,\n null,\n \"3904a4b4\",\n null\n \n)\n\n/* hot reload */\nif (false) { var api; }\ncomponent.options.__file = \"src/components/baseComponents/base_upload/typeOne.vue\"\n/* harmony default export */ __webpack_exports__[\"default\"] = (component.exports);\n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/typeOne.vue?"); /***/ }), /***/ "./src/components/baseComponents/base_upload/typeOne.vue?vue&type=script&lang=js&": /*!****************************************************************************************!*\ !*** ./src/components/baseComponents/base_upload/typeOne.vue?vue&type=script&lang=js& ***! \****************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_cache_loader_dist_cjs_js_ref_12_0_node_modules_babel_loader_lib_index_js_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_typeOne_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/cache-loader/dist/cjs.js??ref--12-0!../../../../node_modules/babel-loader/lib!../../../../node_modules/cache-loader/dist/cjs.js??ref--0-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./typeOne.vue?vue&type=script&lang=js& */ \"./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__[\"default\"] = (_node_modules_cache_loader_dist_cjs_js_ref_12_0_node_modules_babel_loader_lib_index_js_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_typeOne_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[\"default\"]); \n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/typeOne.vue?"); /***/ }), /***/ "./src/components/baseComponents/base_upload/typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true&": /*!*************************************************************************************************************************!*\ !*** ./src/components/baseComponents/base_upload/typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true& ***! \*************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_typeOne_vue_vue_type_style_index_0_id_3904a4b4_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-style-loader??ref--8-oneOf-1-0!../../../../node_modules/css-loader/dist/cjs.js??ref--8-oneOf-1-1!../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../node_modules/postcss-loader/src??ref--8-oneOf-1-2!../../../../node_modules/sass-loader/dist/cjs.js??ref--8-oneOf-1-3!../../../../node_modules/cache-loader/dist/cjs.js??ref--0-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true& */ \"./node_modules/vue-style-loader/index.js?!./node_modules/css-loader/dist/cjs.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/sass-loader/dist/cjs.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=style&index=0&id=3904a4b4&lang=scss&scoped=true&\");\n/* harmony import */ var _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_typeOne_vue_vue_type_style_index_0_id_3904a4b4_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_typeOne_vue_vue_type_style_index_0_id_3904a4b4_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0__);\n/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_typeOne_vue_vue_type_style_index_0_id_3904a4b4_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_typeOne_vue_vue_type_style_index_0_id_3904a4b4_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));\n /* harmony default export */ __webpack_exports__[\"default\"] = (_node_modules_vue_style_loader_index_js_ref_8_oneOf_1_0_node_modules_css_loader_dist_cjs_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_typeOne_vue_vue_type_style_index_0_id_3904a4b4_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default.a); \n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/typeOne.vue?"); /***/ }), /***/ "./src/components/baseComponents/base_upload/typeOne.vue?vue&type=template&id=3904a4b4&scoped=true&": /*!**********************************************************************************************************!*\ !*** ./src/components/baseComponents/base_upload/typeOne.vue?vue&type=template&id=3904a4b4&scoped=true& ***! \**********************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_cache_loader_dist_cjs_js_cacheDirectory_node_modules_cache_vue_loader_cacheIdentifier_7b323dac_vue_loader_template_node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_typeOne_vue_vue_type_template_id_3904a4b4_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/cache-loader/dist/cjs.js?{\"cacheDirectory\":\"node_modules/.cache/vue-loader\",\"cacheIdentifier\":\"7b323dac-vue-loader-template\"}!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/cache-loader/dist/cjs.js??ref--0-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./typeOne.vue?vue&type=template&id=3904a4b4&scoped=true& */ \"./node_modules/cache-loader/dist/cjs.js?{\\\"cacheDirectory\\\":\\\"node_modules/.cache/vue-loader\\\",\\\"cacheIdentifier\\\":\\\"7b323dac-vue-loader-template\\\"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/baseComponents/base_upload/typeOne.vue?vue&type=template&id=3904a4b4&scoped=true&\");\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return _node_modules_cache_loader_dist_cjs_js_cacheDirectory_node_modules_cache_vue_loader_cacheIdentifier_7b323dac_vue_loader_template_node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_typeOne_vue_vue_type_template_id_3904a4b4_scoped_true___WEBPACK_IMPORTED_MODULE_0__[\"render\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return _node_modules_cache_loader_dist_cjs_js_cacheDirectory_node_modules_cache_vue_loader_cacheIdentifier_7b323dac_vue_loader_template_node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_typeOne_vue_vue_type_template_id_3904a4b4_scoped_true___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"]; });\n\n\n\n//# sourceURL=webpack:///./src/components/baseComponents/base_upload/typeOne.vue?"); /***/ }), /***/ "./src/static/images/baseComponentsImg/bgCard_01.png": /*!***********************************************************!*\ !*** ./src/static/images/baseComponentsImg/bgCard_01.png ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("module.exports = __webpack_require__.p + \"img/bgCard_01.32e55fdf.png\";\n\n//# sourceURL=webpack:///./src/static/images/baseComponentsImg/bgCard_01.png?"); /***/ }), /***/ "./src/static/images/baseComponentsImg/bitian.png": /*!********************************************************!*\ !*** ./src/static/images/baseComponentsImg/bitian.png ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("module.exports = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTExIDc5LjE1ODMyNSwgMjAxNS8wOS8xMC0wMToxMDoyMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTUgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjlFMDc5OTlFRDI1RjExRUFCODJFOTdBRkNGMkQ0OTg3IiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjlFMDc5OTlGRDI1RjExRUFCODJFOTdBRkNGMkQ0OTg3Ij4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6OUUwNzk5OUNEMjVGMTFFQUI4MkU5N0FGQ0YyRDQ5ODciIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6OUUwNzk5OUREMjVGMTFFQUI4MkU5N0FGQ0YyRDQ5ODciLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5YiZqPAAABkklEQVR42mL87x7AQACIA3EaEJsDsShU7BUQnwLiWQw71r/Ep5kRjwWhQNwNxPIEHPAQiEuBFq0m1gI+ID4IxAYMpIELQGwPtOgTPgtkgfgqEPMykAc+A7E20JLHMAEmNJdTYjgDVO9VBo9APmwWHCTS8LdADPL2bjyWHES3IJSEMF8AxBuhluACBkBfhCJb0E1CMICSbCEQHyagrhsWyaB0/oIEC/6hBS0+IMEEdREx4Cs0KJmBeDmxvmWC5lBC4AMQPwLin1D+fiItMGNCyv74ACjzaCAZHE6kBWLEhqUcED8B4i9QviWxEcYELbiIARuhtCkQcxGp5xUTtFQkBnRB6WISUtwpYpPpOyAWhrLfILGJSqYvoUUuPrAXqTAEGX6UCMMfguoKWCSXElC8FkpLAfFSaDwQAqXoxfV5POXRfSDOB2JbKM1GsG7Ysd4QxGBBErSHJkVsJaoiEG8ioU6wx1ZcfwJXFhAF5AJYhfMJmwUgAKqJZKDVH6ngAlgvUm02YJU+rmaLGahsIbXZAhBgADaTaP+feiglAAAAAElFTkSuQmCC\"\n\n//# sourceURL=webpack:///./src/static/images/baseComponentsImg/bitian.png?"); /***/ }), /***/ "./src/static/images/baseComponentsImg/closed.png": /*!********************************************************!*\ !*** ./src/static/images/baseComponentsImg/closed.png ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("module.exports = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAaCAYAAACpSkzOAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyFpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTQyIDc5LjE2MDkyNCwgMjAxNy8wNy8xMy0wMTowNjozOSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChXaW5kb3dzKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpBMkY2NUJDMURBRDExMUVBOEM0OUQzQUQwODJBMDhBRSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpBMkY2NUJDMkRBRDExMUVBOEM0OUQzQUQwODJBMDhBRSI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkEyRjY1QkJGREFEMTExRUE4QzQ5RDNBRDA4MkEwOEFFIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkEyRjY1QkMwREFEMTExRUE4QzQ5RDNBRDA4MkEwOEFFIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+vo1hIgAAAa5JREFUeNrMljFLw0AUx1/DYbVSu/kZOknEoQiRTkXQsYuDRadO+gGkOhY/gFs2ccmSUUHUQQk4idKpnyFbLSi46HvtO73S3CWxifiHxzX3jvfr5e69lwLEaO3ocx2HJpqDVkWrsGuA1kcL0Pyn08KjKU7BANjCoYtmQzK9oHUQeJUIhIAyDi7aDvxOHlobgUMtCCHLONygrcBs6qE1EBZOgXgnQQYQFebInVmKw80QAhzLndgRH/wl5KNtuiByR13dqqWF+EjleaN7FNviPLF1kNtjgMNNfZQD9N2dGP+QTQyLkzFSr+8AFw8Ae/VoGM3t18draK1BTcEZr9XZ9XgkmPpMEJo7v/+ZM8gRXFYgDUz+TgghVYVSu1LBUkBIFQv+SIKrcOyu1DOJOrMYDQSX+lpSiBo4BawvuL7VTHkSBdHdRo0COiNf510sArQ29AdPc+TbxTWlohHky1r3bKoOMckIpTmAtw99Q8RatypvXcdUHeJkgHzHHoG4/Xo53GpPtnY1j9rcrLJSj2PCBIg7YSMjmGzlwykQw0IusrO8Ro9bePg/Prfy+oD8EmAAWfOcB4yqxRAAAAAASUVORK5CYII=\"\n\n//# sourceURL=webpack:///./src/static/images/baseComponentsImg/closed.png?"); /***/ }), /***/ "./src/static/images/baseComponentsImg/upload.png": /*!********************************************************!*\ !*** ./src/static/images/baseComponentsImg/upload.png ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("module.exports = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACMAAAAgCAYAAACYTcH3AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTM4IDc5LjE1OTgyNCwgMjAxNi8wOS8xNC0wMTowOTowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTcgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjdEMkU1MjQyRDNENTExRUFBRTk3OTAzNTNFQzNBRDBBIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjdEMkU1MjQzRDNENTExRUFBRTk3OTAzNTNFQzNBRDBBIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6N0QyRTUyNDBEM0Q1MTFFQUFFOTc5MDM1M0VDM0FEMEEiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6N0QyRTUyNDFEM0Q1MTFFQUFFOTc5MDM1M0VDM0FEMEEiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz6GSsF9AAAGCUlEQVR42rSXW2hcVRSGz5k5uU1uTu6JMdpaG4oWQUQtFtpqgoQ+VPCCLaVSfVJELOKTYJGKUCh9KhXEy4NGRKu+tNZGqClYDKLSJr7YNE0bTWia22QmyWSSyYzfPzln2Jk0YzKSDWvOObPPXutfa/1r7X3s8fFxy7Zta2FhwfJGMpm0YrHYc9PT08fj8Xijtcrh9/snAoHA8aKiove4t4qLi70p39zcXOPMzEwN97bP54uVlJRcwc6sud7mBYtJa35+Pv0nwB4bHBz8WfqttY9EQ0PDCwUFBV+7unSpHxoauoxjwZRRnK+oqHinrKzsGI9pw04aOoB4WbcFkUhk36Kj/jBKP+L+DxQsZAFgs3Yzcgjj5UT7rdra2h9YE1GEGA1EId+wF8f56qmpqfzbgtEIh8MKbXB2dvYRZQsgl8rLy9/lOUyYV0SSl5cnT4MTExOPYqANQ/eQ5g2kuRsdVn5+/p+k71Wc3CzgAIxg50vuZ0hpmhpLwAg9nrUg9yrceHYTgA/9V16U4snJSR/rB1gzl0gkynDgaa4V0WjUkjCGADDkcmsOgBHeTyplmZzxAWDr8PDwESKwnfs7FlNrzyLza+CLHwBF7tooEl/hvYXCwsKeYDB4lOs5pU2RsQmlvHh2bGzsMB42eS+Db8W8pBYaHq1lsNZB8lyeRqqrqw8TsY/FEgcgraOjo+9Dvlomp5nowLvLLBhZDzDYKCFND8Kf3dgpx/bb6IvBnZMOfx4ESA0vTVVVVb0MGc+Q4ygETKxYOjkC0RBhkSIAPYntk2TjLvj2CnY7fdh9XPrJ3WnHcU5zPy3yZlMI+Szet0pLSy23WiyaWEr0/ypGFOPnyMIXCjSANuD8Dh+hElktSu9HyDuTJbwpw+obMghwgcjnuViC8kLE1v/oSpW71mSJ7jx6zqp/gaGYVG1KlzaGrnopkKcgTadExqVcXHEbY4CK20WYW3Cg1i3vMOt+AoCqIyTgXmd3S3uJY7LB6EKnFDroCzoG0nQZyjtadUqRQGSMEnrPJ7SEPW5XNb19CTp0cn2elIW8hiiRLrWRkZGRlLhDHifTGLNsesuAYLyRyLTTDp5RefLOJB72I33cj8kPDLbyTifzzZldmsrNXmnZJpUiU0jdXkK+W1NEoIst4LXGxsbtTU1N2yorKw/ClQ51YMYDGH7dXhzp9XV1dVnBONki425y3ijFgCLiA8hvVMKL8OKaGqT7/hlS2wMZPwRwq/oXz1uJSPeqe1C28s2QSncDtQHyGSTs9YB4Rwf+u065t+uB6GyClNtEflNyisxtdumNAuKmr1+VpbOKKkUp0DNRUYR6jWNFDXryzGNCzmnKGBGDjAE1OFWFdyhTKdPBVTEBo4Rj6En87zTJ0wy5AYh/Uu0zGm0BREHmGgheQKU95R1BkW4dCNRXPMkJjEdgQ0Jw5bxwhkKh/ewnB7gv9lLHKOT/3fy/X+/Aj0tUV5dSZ0pOaVIH9k5hHo1IRbs2OLhyJ6e6Exjcw/+pciZaO1nTxlwZz2HmPiUSIVOBml5OYDyCmtzBSCfPb3A9Cjk3qudw34Ik3EOVuvdNLkcAcsrUp22EQ3luYDTUMb29yc23SuwU5O1n7k0M7NSeot4DyFuU/6/IMXhzIV3vpMbbm+rr65eVd19f33IwCq+pQPuTFyEp07OR898h8wE4tAWO1It73N8C0F/omTadMb/HvPOyEe06nFRY5XTMcRuXXw0NTnRgWAfxNBgzzNpfOCamwGm35b0eFPd4O7HW6cpnimV8My09yLCWyEmPzt9tOoZKPfYGHABcgXhb+MTYy+LPUXhtNac14+iR04kPe3WA2icwOHkdOe8jh1/poMNoBvX3TD6sY4LsrJOoKTYD5juy8YSOLnDwG3B0Ofx8q88TJnYJEOm4AAmvch2w1mHoW4pM3K8vT1UhUb7Ih+IHoqetD38RHaQnCFubV6LrPQAyQ0TOcgw5BF/+Tn1xuGA0KcT6PN1B/u7mObBeILBzAyAXycovABlLRUVnHgOM2G/DmzyYfp923PUAg3E+XId72Sri0CHplbns/yvAAB55fjwY+jGKAAAAAElFTkSuQmCC\"\n\n//# sourceURL=webpack:///./src/static/images/baseComponentsImg/upload.png?"); /***/ }) }]);
JavaScript
CL
75e3f7f4d589c71ebbdbeb508b89db5da7f641ff99cc0100604ff0478db5b5b9
import React, { useState, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useHistory } from "react-router-dom"; // Redux import { emailSignInStart, googleSignInStart } from "../../redux/User/user.actions"; // Material-ui import Avatar from "@material-ui/core/Avatar"; import Button from "@material-ui/core/Button"; import TextField from "@material-ui/core/TextField"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import Checkbox from "@material-ui/core/Checkbox"; import Link from "@material-ui/core/Link"; import Grid from "@material-ui/core/Grid"; import Box from "@material-ui/core/Box"; import Container from "@material-ui/core/Container"; import Typography from "@material-ui/core/Typography"; import InputAdornment from "@material-ui/core/InputAdornment"; import IconButton from "@material-ui/core/IconButton"; import OutlinedInput from "@material-ui/core/OutlinedInput"; import InputLabel from "@material-ui/core/InputLabel"; import FormControl from "@material-ui/core/FormControl"; // Material-ui Icons import LockOutlinedIcon from "@material-ui/icons/LockOutlined"; import Visibility from "@material-ui/icons/Visibility"; import VisibilityOff from "@material-ui/icons/VisibilityOff"; import ErrorIcon from "@material-ui/icons/Error"; // Material-ui Styles import { makeStyles } from "@material-ui/core/styles"; const mapState = ({ user }) => ({ currentUser: user.currentUser, userErr: user.userErr, }); const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: "flex", flexDirection: "column", alignItems: "center", }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: "100%", // Fix IE 11 issue. marginTop: theme.spacing(1), }, signin: { margin: theme.spacing(3, 0, 1), }, signingoogle: { margin: theme.spacing(0, 0, 2), }, withoutLabel: { marginTop: theme.spacing(3), }, error: { fontSize: 12, }, })); const SignIn = (props) => { const classes = useStyles(); const history = useHistory(); const dispatch = useDispatch(); const { currentUser, userErr } = useSelector(mapState); const [values, setValues] = useState({ email: "", password: "", showPassword: false, }); useEffect(() => { if (currentUser) { resetForm(); history.push("/"); } }, [currentUser, history]); const resetForm = () => { setValues({ email: "", password: "", showPassword: false, }); }; const handleSubmit = (event) => { const email = values.email; const password = values.password; event.preventDefault(); dispatch(emailSignInStart({ email, password })); }; const handleGoogleSignIn = () => { dispatch(googleSignInStart()); }; const handleChange = (prop) => (event) => { setValues({ ...values, [prop]: event.target.value }); }; const handleClickShowPassword = () => { setValues({ ...values, showPassword: !values.showPassword }); }; const handleMouseDownPassword = (event) => { event.preventDefault(); }; return ( <Container component="main" maxWidth="xs"> <div className={classes.paper}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Member Sign in </Typography> {!Array.isArray(userErr) && ( <Grid container justifyContent="center" alignItems="center" spacing={0}> <Grid item xs={1}> <ErrorIcon color="error" /> </Grid> <Grid item xs={11}> <Typography className={classes.error} color="error"> {userErr} </Typography> </Grid> </Grid> )} <form className={classes.form} noValidate onSubmit={handleSubmit}> <TextField variant="outlined" margin="normal" required fullWidth id="email" label="Email Address" type="email" name="email" autoComplete="email" autoFocus onChange={handleChange("email")} value={values.email} /> <FormControl fullWidth variant="outlined"> <InputLabel htmlFor="outlined-adornment-password">Password *</InputLabel> <OutlinedInput id="outlined-adornment-password" type={values.showPassword ? "text" : "password"} value={values.password} onChange={handleChange("password")} required autoComplete="current-password" endAdornment={ <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={handleClickShowPassword} onMouseDown={handleMouseDownPassword} edge="end" > {values.showPassword ? <Visibility /> : <VisibilityOff />} </IconButton> </InputAdornment> } labelWidth={70} /> </FormControl> <FormControlLabel control={<Checkbox value="remember" color="primary" />} label="Remember me" /> <Button type="submit" fullWidth variant="contained" color="primary" className={classes.signin}> Sign In </Button> <Button onClick={handleGoogleSignIn} fullWidth variant="contained" color="primary" className={classes.signingoogle}> Sign In With Google </Button> <Grid container> <Grid item xs> <Link href="/recovery" variant="body2"> Forgot password? </Link> </Grid> <Grid item> <Link href="/registration" variant="body2"> {"Don't have an account? Sign Up"} </Link> </Grid> </Grid> </form> </div> <Box mt={8}></Box> </Container> ); }; export default SignIn;
JavaScript
CL
a77b67314e82e53fa6b845b6c87956637740e1ae8dc99ed93880c565a4475726
'use strict' const IPLDBlock = require('ipld-block') const CID = require('cids') const { getName } = require('multicodec') // @ts-ignore const vd = require('varint-decoder') const multihashing = require('multihashing-async') const { isMapEqual } = require('../../utils') const { Message } = require('./message') const Entry = require('./entry') class BitswapMessage { /** * @param {boolean} full */ constructor (full) { this.full = full /** @type {Map<string, Entry>} */ this.wantlist = new Map() /** @type {Map<string, import('ipld-block')>} */ this.blocks = new Map() /** @type {Map<string, import('./message').Message.BlockPresenceType>} */ this.blockPresences = new Map() this.pendingBytes = 0 } get empty () { return this.blocks.size === 0 && this.wantlist.size === 0 && this.blockPresences.size === 0 } /** * * @param {CID} cid * @param {number} priority * @param {import('./message').Message.Wantlist.WantType | null} [wantType] * @param {boolean} [cancel] * @param {boolean} [sendDontHave] * @returns {void} */ addEntry (cid, priority, wantType, cancel, sendDontHave) { if (wantType == null) { wantType = BitswapMessage.WantType.Block } const cidStr = cid.toString('base58btc') const entry = this.wantlist.get(cidStr) if (entry) { // Only change priority if want is of the same type if (entry.wantType === wantType) { entry.priority = priority } // Only change from "dont cancel" to "do cancel" if (cancel) { entry.cancel = Boolean(cancel) } // Only change from "dont send" to "do send" DONT_HAVE if (sendDontHave) { entry.sendDontHave = Boolean(sendDontHave) } // want-block overrides existing want-have if (wantType === BitswapMessage.WantType.Block && entry.wantType === BitswapMessage.WantType.Have) { entry.wantType = wantType } } else { this.wantlist.set(cidStr, new Entry(cid, priority, wantType, cancel, sendDontHave)) } } /** * @param {import('ipld-block')} block * @returns {void} */ addBlock (block) { const cidStr = block.cid.toString('base58btc') this.blocks.set(cidStr, block) } /** * @param {CID} cid */ addHave (cid) { const cidStr = cid.toString('base58btc') if (!this.blockPresences.has(cidStr)) { this.blockPresences.set(cidStr, BitswapMessage.BlockPresenceType.Have) } } /** * @param {CID} cid */ addDontHave (cid) { const cidStr = cid.toString('base58btc') if (!this.blockPresences.has(cidStr)) { this.blockPresences.set(cidStr, BitswapMessage.BlockPresenceType.DontHave) } } /** * @param {CID} cid */ cancel (cid) { const cidStr = cid.toString('base58btc') this.wantlist.delete(cidStr) this.addEntry(cid, 0, BitswapMessage.WantType.Block, true, false) } /** * @param {number} size */ setPendingBytes (size) { this.pendingBytes = size } /** * Serializes to Bitswap Message protobuf of * version 1.0.0 * * @returns {Uint8Array} */ serializeToBitswap100 () { const msg = { wantlist: { entries: Array.from(this.wantlist.values()).map((entry) => { return { block: entry.cid.bytes, // cid priority: Number(entry.priority), cancel: Boolean(entry.cancel) } }), full: this.full ? true : undefined }, blocks: Array.from(this.blocks.values()) .map((block) => block.data) } return Message.encode(msg).finish() } /** * Serializes to Bitswap Message protobuf of * version 1.1.0 * * @returns {Uint8Array} */ serializeToBitswap110 () { const msg = { wantlist: { entries: Array.from(this.wantlist.values()).map((entry) => { return { block: entry.cid.bytes, // cid priority: Number(entry.priority), wantType: entry.wantType, cancel: Boolean(entry.cancel), sendDontHave: Boolean(entry.sendDontHave) } }), full: this.full ? true : undefined }, /** @type {import('./message').Message.BlockPresence[]} */ blockPresences: [], /** @type {{ prefix: Uint8Array, data: Uint8Array }[]} */ payload: [], pendingBytes: this.pendingBytes } this.blocks.forEach((block) => { msg.payload.push( new Message.Block({ prefix: block.cid.prefix, data: block.data }) ) }) for (const [cidStr, bpType] of this.blockPresences) { msg.blockPresences.push(new Message.BlockPresence({ cid: new CID(cidStr).bytes, type: bpType })) } if (this.pendingBytes > 0) { msg.pendingBytes = this.pendingBytes } return Message.encode(msg).finish() } /** * @param {BitswapMessage} other * @returns {boolean} */ equals (other) { if (this.full !== other.full || this.pendingBytes !== other.pendingBytes || !isMapEqual(this.wantlist, other.wantlist) || !isMapEqual(this.blocks, other.blocks) || // @TODO - Is this a bug ? // @ts-expect-error - isMap equals map values to be objects not numbers !isMapEqual(this.blockPresences, other.blockPresences) ) { return false } return true } get [Symbol.toStringTag] () { const list = Array.from(this.wantlist.keys()) const blocks = Array.from(this.blocks.keys()) return `BitswapMessage <full: ${this.full}, list: ${list}, blocks: ${blocks}>` } } /** * @param {Uint8Array} raw */ BitswapMessage.deserialize = async (raw) => { const decoded = Message.decode(raw) const isFull = (decoded.wantlist && decoded.wantlist.full) || false const msg = new BitswapMessage(isFull) if (decoded.wantlist && decoded.wantlist.entries) { decoded.wantlist.entries.forEach((entry) => { if (!entry.block) { return } // note: entry.block is the CID here const cid = new CID(entry.block) msg.addEntry(cid, entry.priority || 0, entry.wantType, Boolean(entry.cancel), Boolean(entry.sendDontHave)) }) } if (decoded.blockPresences) { decoded.blockPresences.forEach((blockPresence) => { if (!blockPresence.cid) { return } const cid = new CID(blockPresence.cid) if (blockPresence.type === BitswapMessage.BlockPresenceType.Have) { msg.addHave(cid) } else { msg.addDontHave(cid) } }) } // Bitswap 1.0.0 // decoded.blocks are just the byte arrays if (decoded.blocks.length > 0) { await Promise.all(decoded.blocks.map(async (b) => { const hash = await multihashing(b, 'sha2-256') const cid = new CID(hash) msg.addBlock(new IPLDBlock(b, cid)) })) return msg } // Bitswap 1.1.0 if (decoded.payload.length > 0) { await Promise.all(decoded.payload.map(async (p) => { if (!p.prefix || !p.data) { return } const values = vd(p.prefix) const cidVersion = values[0] const multicodec = values[1] const hashAlg = values[2] // const hashLen = values[3] // We haven't need to use this so far const hash = await multihashing(p.data, hashAlg) const cid = new CID(cidVersion, getName(multicodec), hash) msg.addBlock(new IPLDBlock(p.data, cid)) })) msg.setPendingBytes(decoded.pendingBytes) return msg } return msg } /** * @param {CID} cid */ BitswapMessage.blockPresenceSize = (cid) => { // It's ok if this is not exactly right: it's used to estimate the size of // the HAVE / DONT_HAVE on the wire, but when doing that calculation we leave // plenty of padding under the maximum message size. // (It's more important for this to be fast). return cid.bytes.length + 1 } BitswapMessage.Entry = Entry BitswapMessage.WantType = { Block: Message.Wantlist.WantType.Block, Have: Message.Wantlist.WantType.Have } BitswapMessage.BlockPresenceType = { Have: Message.BlockPresenceType.Have, DontHave: Message.BlockPresenceType.DontHave } module.exports = BitswapMessage
JavaScript
CL
a6989bd14e2cee34b1686b73b3c18f2b37b247e70afdf573c2622f261843718f
'use strict'; import { parseStatus, parseSetups, formatSetups } from './QT60240.mjs'; const KEY_NAMES = [ // TODO: why are the bytes backwards? Because I swapped the line numbers in the schematic.. 'c#', 'd#', 'f', 'g', 'a', 'b', 'k1', 'k3', 'c', 'd', 'e', 'f#', 'g#', 'a#', 'c2', 'k2' ]; let setups; // readSetups to load this let port; let reader; let inputDone; let outputDone; let inputStream; let outputStream; async function connect () { port = await navigator.serial.requestPort(); await port.open({ baudRate: 57600 }); document.body.classList.add('connected'); const decoder = new TextDecoderStream(); inputDone = port.readable.pipeTo(decoder.writable); inputStream = decoder.readable.pipeThrough(new TransformStream(new LineBreakTransformer())); const encoder = new TextEncoderStream(); outputDone = encoder.readable.pipeTo(port.writable); outputStream = encoder.writable; reader = inputStream.getReader(); readLoop(); // NOTE: deliberately not awaiting this } async function readLoop () { while (true) { try { var { value, done } = await reader.read(); } catch (err) { // not sure if there's a better way to disconnect so we don't get this error if (err.message.includes('This readable stream reader has been released and cannot be used to read from its previous owner stream')) { console.log('Disconnected.'); return; } throw err; } if (value) { handleLine(value); } if (done) { console.log('DONE'); reader.releaseLock(); } } } async function disconnect () { document.body.classList.remove('connected'); if (reader) { await reader.cancel(); await inputDone.catch(() => {}); reader = null; inputDone = null; } if (outputStream) { await outputStream.getWriter().close(); await outputDone; outputStream = null; outputDone = null; } await port.close(); port = null; } function readStatus () { const writer = outputStream.getWriter(); writer.write('RSTATUS\r'); writer.releaseLock(); } function readSetups () { const writer = outputStream.getWriter(); writer.write('RSETUPS\r'); writer.releaseLock(); } function writeSetups () { if (!setups) { console.log('no setups yet :('); return; } // modify setups to make the modifications we want for (let i = 0; i < 24; ++i) { setups.AKS[i] = 0; // default 0 setups.burstLength[i] = 0; // default 2 setups.negThreshold[i] = 15; // recommended 3 to 8, default 6. can do 0 to 15 } setups.driftHoldTimeout = 10; // the default is 10 meaning 1 second const writer = outputStream.getWriter(); writer.write('WSETUPS\r'); writer.write(`${formatSetups(setups)}\r`); writer.releaseLock(); }; function handleLine (line) { console.log(line); if (line.startsWith('KEYS ')) { console.log(JSON.stringify(pressedKeys(parseKeys(line.slice(5))))); return; } if (line.startsWith('STATUS ')) { console.log(parseStatus(line.slice(7))); return; } if (line.startsWith('SETUPS ')) { setups = parseSetups(line.slice(7)); console.log(setups); return; } } function parseKeys (text) { const parts = text.split(' '); const keys = {}; for (let i = 0; i < 2; ++i) { for (let j = 0; j < 8; ++j) { const index = i * 8 + j; const number = parseInt(parts[i], 10); keys[KEY_NAMES[index]] = !!(number & 1 << j) ? 1 : 0 } } return keys; } function pressedKeys (keys) { const pressed = []; for (const [k, v] of Object.entries(keys)) { if (v) { pressed.push(k); } } return pressed; } class LineBreakTransformer { constructor() { // A container for holding stream data until a new line. this.container = ''; } transform(chunk, controller) { this.container += chunk; const lines = this.container.split('\r\n'); this.container = lines.pop(); lines.forEach(line => controller.enqueue(line)); } flush(controller) { controller.enqueue(this.container); } } window.addEventListener('DOMContentLoaded', (event) => { document.querySelector('#connect').addEventListener('click', connect); document.querySelector('#disconnect').addEventListener('click', disconnect); document.querySelector('#readStatus').addEventListener('click', readStatus); document.querySelector('#readSetups').addEventListener('click', readSetups); document.querySelector('#writeSetups').addEventListener('click', writeSetups); });
JavaScript
CL
7ba3146bbfc866abc066b7c8f72ea0ab3f4fe411ca17824e500ba0af421bdced
// const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); const PurgecssPlugin = require('purgecss-webpack-plugin'); const TerserPlugin = require('terser-webpack-plugin'); const { merge } = require('webpack-merge'); const os = require('os'); const glob = require('glob'); const paths = require('./paths.js'); const common = require('./webpack.common.js'); // eslint-disable-next-line no-console console.table({ 'Environment mode': process.env.NODE_ENV, 'Webpack Threads': os.cpus().length, }); module.exports = merge(common, { mode: 'production', entry: `${paths.src._}/index.js`, devtool: false, output: { path: paths.dist, publicPath: '/', filename: 'js/[name].[contenthash].bundle.js', }, plugins: [ new MiniCssExtractPlugin({ filename: 'styles/[name].[contenthash].css', chunkFilename: '[id].css', }), new PurgecssPlugin({ paths: [ paths.src.html, ...glob.sync(`${paths.src._}/**/*`, { nodir: true }), ], }), // new BundleAnalyzerPlugin(), ], optimization: { minimize: true, minimizer: [ new CssMinimizerPlugin(), new TerserPlugin({ parallel: true, }), ], splitChunks: { chunks: 'all', }, usedExports: true, }, performance: { hints: 'warning', }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: [ { loader: 'thread-loader', options: { workers: os.cpus().length, }, }, 'babel-loader', ], }, { test: /\.scss$/, use: [ { loader: MiniCssExtractPlugin.loader, }, { loader: 'css-loader', options: { importLoaders: 2, sourceMap: false, modules: { localIdentName: '[name]__[local]___[hash:base64:5]', }, }, }, { loader: 'postcss-loader', options: { postcssOptions: { plugins: [ ['autoprefixer'], ], sourceMap: false, }, }, }, { loader: 'sass-loader', }, ], }, { test: /\.css$/, use: [ { loader: MiniCssExtractPlugin.loader, }, { loader: 'css-loader', }, { loader: 'postcss-loader', options: { postcssOptions: { plugins: [ ['autoprefixer'], ], sourceMap: false, }, }, }, ], }, { test: /\.(?:ico|gif|png|jpg|jpeg)$/i, type: 'asset/resource', }, { test: /\.ttf$/, type: 'asset/inline', }, ], }, });
JavaScript
CL
2edc0815cbf8e1b90970b680161ab983d0a27472885a9f1b5e6fb05fdfa80c56
import React, { useState } from "react"; import { Paper, Grid, TextField, Typography, Button, IconButton, Select, InputLabel, MenuItem, FormControl } from "@material-ui/core"; import MonetizationOnIcon from "@material-ui/icons/MonetizationOn"; import useStyles from "../styles/StylesSheet"; import {axiosWithAuth} from "../helpers/axiosWithAuth"; import { connect } from "react-redux"; const defaultValues = { name: "", price: "", rentalPeriod: "", rentalPeriodMin: 0, rentalPeriodMax: 0, category: "", description: "" }; const defaultErrors = { name: "", price: "", rentalPeriodMin: 0, rentalPeriodMax: 0, category: "", description: "" }; const AddItem = (state) => { const classes = useStyles(); const [values, setValues] = useState(defaultValues); const [helperText, setHelperText] = useState(defaultErrors); const priceValidate = values.price.match(/^\w{1,10}$/g); const onChange = (evt) => { const { name, value } = evt.target; setValues({ ...values, [name]: value }); }; const onSubmit = (evt) => { evt.preventDefault(); const newItem = { tech_item_title: values.name, tech_item_price: parseInt(values.price), min_rental_period: parseInt(values.rentalPeriodMin), max_rental_period: parseInt(values.rentalPeriodMax), tech_item_description: values.description, category_name: values.category }; if ( true ) { axiosWithAuth() .post(`https://use-my-tech-stuff-backend-1.herokuapp.com/api/tech_items`, newItem) .then(res =>{ console.log(state) console.log(res); // push("/owner") }) .catch(err => {console.log(err.response) console.log(newItem)} ) } else { setHelperText({ name: "Please enter a name between 2 and 15 characters long", price: "Please enter a price between 1 and 10 characters long", rentalPeriod: "Please enter a rental period between 2 and 15 characters long", category: "Please choose a category", description: "Please enter a description between 2 and 30 characters long" }); } }; return ( <> <Grid container className={classes.root}> <Paper className={classes.paper}> <Grid container> <Typography variant="h3" className={`${classes.topText} ${classes.paperItem}`} > Create New Item </Typography> </Grid> <form onSubmit={onSubmit}> <Grid container className={classes.formGrid}> <TextField variant="filled" className={classes.paperItem} fullWidth required type="text" label="Name" name="name" value={values.name} onChange={onChange} autoComplete="off" InputLabelProps={{ style: { color: "#fff" } }} /> <TextField variant="filled" className={`${classes.paperItem}`} fullWidth required helperText={priceValidate ? "" : helperText.price} type="text" label="Price" name="price" value={values.price} onChange={onChange} autoComplete="off" InputProps={{ endAdornment: ( <IconButton> <MonetizationOnIcon /> </IconButton> ) }} InputLabelProps={{ style: { color: "#fff" } }} /> <TextField variant="filled" className={`${classes.paperItem}`} fullWidth required type="text" label="Rental Period Min" name="rentalPeriodMin" value={values.rentalPeriodMin} onChange={onChange} autoComplete="off" InputLabelProps={{ style: { color: "#fff" } }} /> <TextField variant="filled" className={`${classes.paperItem}`} fullWidth required type="text" label="Rental Period Max" name="rentalPeriodMax" value={values.rentalPeriodMax} onChange={onChange} autoComplete="off" InputLabelProps={{ style: { color: "#fff" } }} /> <FormControl fullWidth className={classes.paperItem}> <InputLabel id="Category" className={classes.paperItem}> Category </InputLabel> <Select variant="filled" fullWidth labelId="Category" value={values.category} className={classes.paperItem} onChange={onChange} name="category" > <MenuItem value="camera">Camera</MenuItem> <MenuItem value="sound">Sound</MenuItem> <MenuItem value="visual">Visual</MenuItem> <MenuItem value="gaming">Gaming</MenuItem> <MenuItem value="computer">Computer</MenuItem> <MenuItem value="misc">Misc</MenuItem> </Select> </FormControl> <TextField variant="filled" className={`${classes.paperItem}`} fullWidth required type="text" label="Description" name="description" value={values.description} onChange={onChange} autoComplete="off" InputLabelProps={{ style: { color: "#fff" } }} /> <Button className={`${classes.submit}`} size="large" variant="contained" type="submit" > Submit </Button> </Grid> </form> </Paper> </Grid> </> ); } const mapStateToProps = state =>{ return({ username:state.username, userId:state.userId }) } export default connect(mapStateToProps)(AddItem);
JavaScript
CL
791bc636be069300c44b2757ce760f82252e110809233cdfd5fc1f5c8bc786ec
// @ts-check import React from 'react'; import { Provider } from 'react-redux'; import { io } from 'socket.io-client'; import { initReactI18next, I18nextProvider } from 'react-i18next'; import i18n from 'i18next'; import App from './components/App.jsx'; import store from './store/store.js'; import { SocketContext, RollbarContext } from './context.js'; import { addMessage } from './store/messages.js'; import { addChannel, removeChannel, renameChannel } from './store/channels.js'; import AuthProvider from './components/AuthProvider.jsx'; import translationRu from './locales/ru.json'; const init = async (socketClient, rollbarInstance) => { const i18nInstance = i18n.createInstance(); await i18nInstance .use(initReactI18next) .init({ resources: { ru: translationRu, }, lng: 'ru', debug: false, fallbackLng: 'ru', interpolation: { escapeValue: false, }, }); // console.log(socketClient); const socket = socketClient !== undefined ? socketClient : io(); socket.on('newMessage', (msg) => { store.dispatch(addMessage(msg)); }); socket.on('newChannel', (channel) => { store.dispatch(addChannel(channel)); }); socket.on('removeChannel', ({ id }) => { store.dispatch(removeChannel(id)); }); socket.on('renameChannel', (channel) => { store.dispatch(renameChannel(channel)); }); return ( <RollbarContext.Provider value={rollbarInstance}> <I18nextProvider i18n={i18nInstance}> <SocketContext.Provider value={socket}> <AuthProvider> <Provider store={store}> <App /> </Provider> </AuthProvider> </SocketContext.Provider> </I18nextProvider> </RollbarContext.Provider> ); }; export default init;
JavaScript
CL
0995591dc055f3de880cf672f2c4beb127898db127c6ae9f7b95c3c401b6bf88
import * as R from 'ramda' import { lazy } from '~/utils' import getFiniteMovableTiles from './getFiniteMovableTiles' import getNextMovable from './getNextMovable' import getMovableAxis from './getMovableAxis' import { getSide, reduceSnapshotBySide, parseCode, getSpecial } from '../helpers' function createReduceCb ({ checkTo, checkBy, turn, side, timeline }) { const awaitGetFiniteMovableTiles = getFiniteMovableTiles(checkTo, checkBy) return (acc, code) => { const { piece, tile } = parseCode(code) const special = getSpecial(piece) const preMovableAxis = getMovableAxis(tile, turn, piece) const preMovableTiles = R.compose( awaitGetFiniteMovableTiles(piece), getNextMovable('tiles'), lazy )({ checkBy, timeline, turn, side, tile, special, movableAxis: preMovableAxis }) return { ...acc, [code]: preMovableTiles } } } /** * Get finite movable tiles group * TODO: code works but only King return movable tiles not properly * @param {String} turn * @param {String} checkTo * @param {String} checkBy * @param {Array} timeline * @return {Object} */ function getFiniteMovableTilesGroup (turn, checkTo, checkBy, timeline) { const side = getSide(turn) const reduceCb = createReduceCb({ checkTo, checkBy, turn, side, timeline }) return R.compose( R.reduce(reduceCb, {}), reduceSnapshotBySide(side), R.nth(0) )(timeline) } export default R.curry(getFiniteMovableTilesGroup)
JavaScript
CL
9cc83414c5239ad6e350255bfea2c3627d5d5e6fc0e0e62dee30e0380b4becff
import config from 'textup-frontend/config/environment'; import Ember from 'ember'; import Location from 'textup-frontend/models/location'; import PropTypesMixin, { PropTypes } from 'ember-prop-types'; import { buildPreviewUrl } from 'textup-frontend/utils/location'; const { computed, tryInvoke, run, typeOf, getWithDefault } = Ember; export default Ember.Component.extend(PropTypesMixin, { propTypes: { location: PropTypes.instanceOf(Location).isRequired, onSuccess: PropTypes.func, onFailure: PropTypes.func, loadingMessage: PropTypes.string, errorMessage: PropTypes.string, }, getDefaultProps() { return { loadingMessage: 'Loading', errorMessage: 'Could not load preview' }; }, classNames: ['location-preview'], classNameBindings: [ '_isShowingAddress:location-preview--overlay', '_isLoading:location-preview--overlay', '_isError:location-preview--overlay', ], didInsertElement() { this._super(...arguments); // wait until after render so that client height and width will not be null run.scheduleOnce('afterRender', () => { if (this.get('isDestroying') || this.get('isDestroyed')) { return; } this.set('_shouldLoad', true); }); }, click() { if (this.get('location.address')) { this.toggleProperty('_isShowingAddress'); } else { this.set('_isShowingAddress', false); } }, // Internal properties // ------------------- _previewAlt: computed('location.address', function() { return `Previewing location with address ${this.get('location.address')}`; }), _previewUrl: computed('location.latLng.{lat,lng}', function() { const latLng = this.get('location.latLng'); if (typeOf(latLng) !== 'object' || !latLng.lat || !latLng.lng) { return; } const { lat, lng } = latLng; // schedule this method call so we don't try to modify classes multiple times in a single render run.scheduleOnce('actions', this._startLoadProps.bind(this)); return [{ source: buildPreviewUrl(lat, lng, this._getLargestDimension()) }]; }), _shouldLoad: false, _isLoading: false, _isError: false, _isShowingAddress: false, // Internal handlers // ----------------- _onSuccess() { run(() => this._finishLoadProps(true)); tryInvoke(this, 'onSuccess', [...arguments]); }, _onFailure() { run(() => this._finishLoadProps(false)); tryInvoke(this, 'onFailure', [...arguments]); }, _startLoadProps() { if (this.get('isDestroying') || this.get('isDestroyed')) { return; } this.setProperties({ _isLoading: true, _isError: false }); }, _finishLoadProps(isSuccess) { if (this.get('isDestroying') || this.get('isDestroyed')) { return; } this.setProperties({ _isLoading: false, _isError: !isSuccess }); }, _getLargestDimension() { const { maxHeight, maxWidth } = config.locationPreview, // may be null if haven't rendered component yet clientHeight = getWithDefault(this, 'element.clientHeight', maxHeight), clientWidth = getWithDefault(this, 'element.clientWidth', maxWidth); return Math.max(Math.min(clientHeight, maxHeight), Math.min(clientWidth, maxWidth)); }, });
JavaScript
CL
58e039033e204fe029f25c9d520191633205d0b851148e729988014149ae18eb
import React from "react"; import { StyleSheet, Platform, StatusBar, SafeAreaView, View, Text, } from "react-native"; import AllAccountsComponent from "./app/components/AllAccountsComponent"; import colors from "./app/config/colors"; import NavbarComponent from "./app/components/NavbarComponent"; import CashComponent from "./app/components/CashComponent"; import { NavigationContainer } from '@react-navigation/native'; import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs"; function DetailsScreen() { return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Text>Details Screen</Text> </View> ); } const Tab = createMaterialTopTabNavigator(); export default function App() { return ( <NavigationContainer> <View style={styles.app}> <SafeAreaView style={styles.container}> </SafeAreaView> <Tab.Navigator initialRouteName="Monthly" tabBar={props => <NavbarComponent {...props} />}> <Tab.Screen name="Home" options={{ title: 'Daily' }} component={DetailsScreen} /> <Tab.Screen name="Weekly" component={CashComponent} /> <Tab.Screen name="Monthly" component={AllAccountsComponent} /> <Tab.Screen name="Yearly" component={DetailsScreen} /> </Tab.Navigator> </View> </NavigationContainer> ); } const styles = StyleSheet.create({ app: { flex: 1, backgroundColor: colors.primary, }, container: { paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0, // TODO: доделать с исппользованием редакса }, });
JavaScript
CL
57af35d8aa4b9e9dfdb152b2afe7b67b34dd4087c9e202167f2e4289de8a2f8e
/*--------------------------------------------------------*/ /* */ /* Copyright Set Snail */ /* All rights reserved. */ /* */ /* */ /* /^\ /^\ */ /* { O} { O} */ /* \ / \ / */ /* // // _------_ */ /* // // ./~ ~-_ */ /* / ~----~/ / \ */ /* / : ./ _---_ ~- */ /* | \________) : /~ ~\ | */ /* | / | | :~~\ | | */ /* | | | | \___-~ | */ /* | \ __/`\______\. ./ */ /* \ ~-______-~\. */ /* .| ~-_ */ /* /_____________________________________~~____ */ /* */ /*--------------------------------------------------------*/ function DragEase() { var _instance = new DraggerEasePlugin(); /**The time it takes foro the ease to finish*/ _instance.time = 2; /**How fare compared to DragAmount the drag will travel after release*/ _instance.distance = 1; /**The ease used to compute the travel*/ _instance.ease = Expo.easeOut; var _easeDist = {x:0, y:0}; var _easePlugins = []; var _lastDist = {x:0, y:0}; var _renderVars = new RenderVars(); var _lastDistResetter ; //Needs to be the last plugin; _instance.priority = 10000; var _onStart = null; var _onMove = null; var _onEnd = null; _instance.onEnd = function( callback ) { _onEnd = callback; }; _instance.onMove = function( callback ) { _onMove = callback; }; _instance.onStart = function( callback ) { _onStart = callback; }; _instance.setEasePlugins = function( plugins ) { _easePlugins = plugins; }; _instance.easeStarted = function() { //Update ease; _renderVars.ease = _instance.ease; }; _instance.easeUpdated = function() { var l = _instance.dragItems.length; var item = null; for( var i = 0; i < l; i++ ) { item = _instance.dragItems[ i ]; if( _instance.use3DTransform === true ){ item.aniSetY( item.aniGetY() + _instance.dragInfo.dist.y ); item.aniSetX( item.aniGetX() + _instance.dragInfo.dist.x );// = ( parseFloat( item.style.left ) + _instance.dragInfo.dist.x ) + "px"; item.aniRender(); // item.style.top = ( parseFloat( item.style.top ) + _instance.dragInfo.dist.y ) + "px"; }else{ item.style.left = ( parseFloat( item.style.left ) + _instance.dragInfo.dist.x ) + "px"; item.style.top = ( parseFloat( item.style.top ) + _instance.dragInfo.dist.y ) + "px"; } } }; _instance.easeEnded = function() { _instance.easeUpdated(); }; _instance.dragStarted = function() { _instance.stop(); if(_onStart !== null){ _onStart(); } }; _instance.dragMove = function() { // _lastDist.setTo( dragInfo.dist.x, dragInfo.dist.y ); _lastDist.x = _instance.dragInfo.dist.x; _lastDist.y = _instance.dragInfo.dist.y; clearTimeout( _lastDistResetter ); _lastDistResetter = setTimeout( resetLastDist, 100 ); if(_onMove !== null){ _onMove(); } }; function resetLastDist() { _lastDist.x = _lastDist.y = 0; } _instance.dragEnded = function() { _instance.killTweens(); _instance.easeInfo.easeDistance = {x:_lastDist.x, y:_lastDist.y}; _instance.easeInfo.easeDistance.x *= _instance.distance; _instance.easeInfo.easeDistance.y *= _instance.distance; var l = _easePlugins.length; for( var i = 0; i < l; i++ ){ _easePlugins[ i ].easeStarted(); } // console.log("DRAG ENDED"); _renderVars.ratio = 0; TweenMax.to( _renderVars, _instance.time, { ratio:1, onUpdate:renderEase, onComplete:completeEase, ease:Linear.easeNone } ); }; _instance.stop = function() { TweenMax.killTweensOf( _renderVars ); completeEase(); }; function renderEase() { _renderVars.renderEase(); _instance.easeInfo.easeRatio = _renderVars.easeRatio; _instance.easeInfo.linearEaseRatio = _renderVars.ratio; var reversedRatio = 1 - _renderVars.easeRatio; _instance.dragInfo.dist.x = _instance.easeInfo.easeDistance.x * reversedRatio; _instance.dragInfo.dist.y = _instance.easeInfo.easeDistance.y * reversedRatio; updateEase(); } function completeEase() { var l = _easePlugins.length; for( var i = 0; i < l; i++ ){ _easePlugins[ i ].easeEnded(); } if(_onEnd !== null){ _onEnd(); } } function updateEase() { var l = _easePlugins.length; for( var i = 0; i < l; i++ ){ _easePlugins[ i ].easeUpdated(); } if(_onMove !== null){ _onMove(); } } return _instance; } function RenderVars() { var _instance = {}; _instance.lastEaseRatio = 0; _instance.ease = Linear.easeNone; _instance.ratio = 0; _instance.easeRatio = 0; _instance.renderEase = function(){ lastEaseRatio = _instance.easeRatio; _instance.easeRatio = _instance.ease.getRatio( _instance.ratio ); }; return _instance; }
JavaScript
CL
0b6a0d8e6b8ed5d0d8097efcb13c67f3dcc7eea717af4526fdcba9c8c1d20bd8
import React from 'react'; import { connect } from 'react-redux'; import Sections from '../sections'; import Collapse from '../collapse'; import './index.scss'; class Help extends Sections { constructor(props) { super(props, [ 'what-is-seedom' ]); } render() { const { open } = this.state; return ( <div className="seedom-help"> <div className="container"> <div className="column is-three-fifths is-offset-one-fifth"> <h3 className="title has-text-white">Understanding Seedom</h3> <Collapse title="What is Seedom?" collapsed={!open.includes('what-is-seedom')} onToggle={this.handleToggle('what-is-seedom')} > <div className="seedom-logo fixed" /> <br /> Seedom is a innovative way of funding altruistic causes in the form of a game. Players purchase entries and enter an encouraging message, and then one planyer is <strong>always</strong> randomly selected as the winner, which could be anyone that participates. The cause will receive 60% of the funds raised, and the winner will receive 40%. Seedom routinely runs FUNdraiser for a new altruistic causes. After you participate, you can also have <a href="#point-of-voting">a say</a> in which causes we support in the future! </Collapse> <Collapse title="Why is Seedom different?" collapsed={!open.includes('why-is-seedom-different')} onToggle={this.handleToggle('why-is-seedom-different')} > Unlike standard raffles (and lotteries, etc.), Seedom is a decentralized open source application built on the <a href="#what-is-ethereum">Ethereum blockchain</a>. It takes the efficiency, security, and transparency of the traditional single-room raffle and re-invents it with trustlessness and crowd-sourced selection into an entirely new type of completely secure fundraiser that scales to the entire world. </Collapse> <Collapse id="what-is-ethereum" title="What is Ethereum?" collapsed={!open.includes('what-is-ethereum')} onToggle={this.handleToggle('what-is-ethereum')} > <div className="ethereum-logo fixed" /> <br /> <a target="_blank" rel="noopener noreferrer" href="https://ethereum.org">Ethereum</a> is a decentralized platform that runs smart contracts: applications that run exactly as programmed without any possibility of downtime, censorship, fraud or third-party interference. <br /> <br /> These apps run on a custom built blockchain, an enormously powerful shared global infrastructure that can move value around and represent the ownership of property. </Collapse> </div> <div className="column is-three-fifths is-offset-one-fifth"> <h3 className="title has-text-white">Getting Started</h3> <Collapse id="obtaining-ether" title="Obtaining Ether to play" collapsed={!open.includes('obtaining-ether')} onToggle={this.handleToggle('obtaining-ether')} > The first step is obtaining Ether, the currency of the Ethereum platform. The easiest way to do this is through <a target="_blank" rel="noopener noreferrer" href="https://coinbase.com">Coinbase</a> on the desktop or through their <a target="_blank" rel="noopener noreferrer" href="https://play.google.com/store/apps/details?id=com.coinbase.android&hl=en_US">Google Android</a> or <a target="_blank" rel="noopener noreferrer" href="https://itunes.apple.com/us/app/coinbase-buy-bitcoin-more/id886427730?mt=8">Apple iOS</a> apps. Learn how to buy cryptocurrency from Coinbase with this <a target="_blank" href="http://blockteq.com/how-to-series/how-to-buy-cryptocurrency/">guide from Blockteq</a>. <br /> <div className="coinbase-logo" /> <br /> <a className="app-store" target="_blank" rel="noopener noreferrer" href="https://itunes.apple.com/us/app/coinbase-buy-bitcoin-more/id886427730?mt=8" /> <br /> <a className="google-play" target="_blank" rel="noopener noreferrer" href="https://play.google.com/store/apps/details?id=com.coinbase.android&hl=en_US" /> </Collapse> <Collapse title="Accessing on mobile" collapsed={!open.includes('accessing-mobile')} onToggle={this.handleToggle('accessing-mobile')} > To use Seedom on mobile, you will need a mobile Ethereum web browser. We recommend either <a target="_blank" rel="noopener noreferrer" href="https://www.toshi.org">Coinbase Wallet (formerly Toshi)</a> or <a target="_blank" rel="noopener noreferrer" href="https://trustwalletapp.com">Trust Wallet</a>. After you install, you will need to <a href="#obtaining-ether">put Ether</a> into your browser's wallet in order to participate. <br /> <br /> <div className="coinbase-logo" /> <br /> <a className="app-store" target="_blank" rel="noopener noreferrer" href="https://itunes.apple.com/app/coinbase-wallet/id1278383455?ls=1&mt=8" /> <br /> <a className="google-play" target="_blank" rel="noopener noreferrer" href="https://play.google.com/store/apps/details?id=org.toshi" /> <br /> <br /> <div className="trust-wallet-logo" /> <br /> <a className="app-store" target="_blank" rel="noopener noreferrer" href="https://itunes.apple.com/us/app/trust-ethereum-wallet/id1288339409" /> <br /> <a className="google-play" target="_blank" rel="noopener noreferrer" href="https://play.google.com/store/apps/details?id=com.wallet.crypto.trustapp" /> </Collapse> <Collapse title="Accessing on desktop" collapsed={!open.includes('accessing-desktop')} onToggle={this.handleToggle('accessing-desktop')} > To use Seedom on the desktop, you will need to install <a target="_blank" rel="noopener noreferrer" href="https://metamask.io">MetaMask</a> or use the <a target="_blank" rel="noopener noreferrer" href="https://brave.com">Brave browser</a>. You will need to <a href="#obtaining-ether">put Ether</a> into your MetaMask wallet in order to participate. Learn how to setup MetaMask and store Ether with this <a target="_blank" href="http://blockteq.com/how-to-series/how-to-store-ethereum-and-erc-20s-using-your-computer/">guide from Blockteq</a>. <br /> <br /> <a className="download-metamask" target="_blank" rel="noopener noreferrer" href="https://metamask.io" /> <br /> <iframe title="Installing Metamask" width="100%" height="315" src="https://www.youtube.com/embed/tfETpi-9ORs?rel=0&amp;showinfo=0" frameBorder="0" allowFullScreen="" /> </Collapse> </div> <div className="column is-three-fifths is-offset-one-fifth"> <h3 className="title has-text-white">Playing Seedom</h3> <Collapse title="How do I play?" collapsed={!open.includes('how-do-i-play')} onToggle={this.handleToggle('how-do-i-play')} > To play Seedom, click the "PARTICIPATE" tab at the top of this page. Click "PLAY TO WIN!" and enter the number of entries you would like to buy, a message to the world that can be up to 32 characters, and an optional email address. <br /> <br /> Each entry is intended to cost $2 USD in Ether at the beginning of each ten day fundraiser. Enter quickly as we expect this price to fluctuate due to the volatility of Ether. The number of entries you choose increases your likelihood of being chosen the random winner. <br /> <br /> Your public message to the world can be anything you want! It could be your name. It could be your favorite catchphrase or even the name of your Cryptokitty. Anything at all. The beauty about Seedom is that there is no censorship and since Seedom runs on the blockchain, your message is publicly visible and permanent. Even better is that your message will actually affect how the random winner selection process works. </Collapse> <Collapse title="Finding out if you won" collapsed={!open.includes('finding-out-if-you-won')} onToggle={this.handleToggle('finding-out-if-you-won')} > The fundraiser ends ten days after it has started. Both the cause and Seedom will reveal secret messages used to start the fundraiser. These messages, combined with those of the participants, will be used to select a winner and allocate funds to the cause. If you win, you will see a withdraw message on our homepage. Simply click withdraw and all funds will be sent directly to your Ethereum wallet. </Collapse> </div> <div className="column is-three-fifths is-offset-one-fifth"> <h3 className="title has-text-white">Suggesting Future Causes</h3> <Collapse id="point-of-voting" title="What is the point of voting?" collapsed={!open.includes('point-of-voting')} onToggle={this.handleToggle('point-of-voting')} > The Seedom team believes in the decentralization of the decision making process for altruistic causes we support. Therefore, after we kick off a fundraiser, we also kick off a polling Dapp that runs for the same ten day period on the vote tab. This polling Dapp allows any participant to vote for the cause that we may support during a future fundraiser. We can not guarantee that these cause suggestions will be selected for support as the cause has to be willing to work with the Seedom team. </Collapse> <Collapse title="How do I suggest the next cause?" collapsed={!open.includes('suggest-next-cause')} onToggle={this.handleToggle('suggest-next-cause')} > To add a new cause to the list of causes the Seedom team will consider for the next fundraiser, you must first participate with at least one entry. Afterwards, click on the "VOTE" tab at the top of this page. Enter the name of the cause and click the plus button to submit it to our polling Dapp. Others can now upvote your cause if they agree that it should be next. </Collapse> <Collapse title="How do I vote on an existing suggested cause?" collapsed={!open.includes('vote-existing-next-cause')} onToggle={this.handleToggle('vote-existing-next-cause')} > To vote on an existing suggested cause the Seedom team will consider for the next fundraiser, you must first participate with at least one entry. Afterwards, click on the "VOTE" tab at the top of this page. Scroll through the list of causes, ordered by total number of votes, and click the vote button next to the cause you would like to see us support. Next click "CAST" to confirm. </Collapse> </div> <div className="column is-three-fifths is-offset-one-fifth"> <h3 className="title has-text-white">Other</h3> <Collapse title="Why is Seedom better?" collapsed={!open.includes('why-is-seedom-better')} onToggle={this.handleToggle('why-is-seedom-better')} > There exists an abundance of chance games in the Ethereum network. The problem with many of them is that they use algorithms that can be defeated by <a target="_blank" rel="noopener noreferrer" href="https://blog.keep.network/miners-arent-your-friends-cde9b6e0e9ac">miner manipulation</a> or they rely on a a centralized third party random number service. <br /> <br /> Seedom’s algorithm takes a secret message from Seedom, a secret message from the cause, and eight randomly selected participant messages to determine the winner. This makes Seedom close to impossible to tamper with. The <a target="_blank" rel="noopener noreferrer" href="https://seedom-io.github.io/seedom-whitepaper/seedom-whitepaper.pdf">whitepaper</a> goes into more technical detail of how this works. </Collapse> <Collapse title="How does Seedom make money?" collapsed={!open.includes('how-does-seedom-make-money')} onToggle={this.handleToggle('how-does-seedom-make-money')} > Seedom does incur operating costs and as a result does take a nominal 5% (10% starting) cut on each fundraiser. </Collapse> </div> </div> </div> ); } } const mapStateToProps = state => { return { router: state.router }; }; export default connect(mapStateToProps)(Help);
JavaScript
CL
c90add49e48032f0607638fba51f4ed6f45e4314e53b82a948d695cdf2e5320c
var custom_content = `<meta charset='utf-8'/><html><head></head><body><div class="oald" id="entryContent"><div class="entry" hclass="entry" hlength="6" htag="section" id="angina" idm_id="000001970" sk="angina: :0" sum="263"><div class="top-container"><div class="top-g" id="angina_topg_1"><div class="webtop"><h1 class="headword" hclass="headword" htag="h1" id="angina_h_1">angina</h1> <span class="pos" hclass="pos" htag="span">noun</span><span class="phonetics"> <div class="phons_br" geo="br" hclass="phons_br" htag="div" wd="angina"><a class="sound audio_play_button pron-uk icon-audio" onclick="document.getElementById('OALD10_pron_angina__gb_1').play();" style="cursor: pointer" title="angina pronunciationEnglish" valign="top"></a><span class="phon">/ænˈdʒaɪnə/</span></div> <div class="phons_n_am" geo="n_am" hclass="phons_n_am" htag="div" wd="angina"><a class="sound audio_play_button pron-us icon-audio" onclick="document.getElementById('OALD10_pron_angina__us_1').play();" style="cursor: pointer" title="angina pronunciationAmerican" valign="top"></a><span class="phon">/ænˈdʒaɪnə/</span></div></span><div class="variants" hclass="variants" htag="div" id="angina_vgs_1" type="vf">(<span class="v-g" id="angina_vg_1"><span class="labels" hclass="labels" htag="span"><span class="subj" id="angina_subj_1" subj="med">medical</span></span> <span class="v" id="angina_v_1">angina pectoris</span><span class="phonetics"> <div class="phons_br" geo="br" hclass="phons_br" htag="div" wd="angina pectoris"><a class="sound audio_play_button pron-uk icon-audio" onclick="document.getElementById('OALD10_pron_angina_pectoris_1_gb_1').play();" style="cursor: pointer" title="angina pectoris pronunciationEnglish" valign="top"></a><span class="phon">/ænˌdʒaɪnə ˈpektərɪs/</span></div> <div class="phons_n_am" geo="n_am" hclass="phons_n_am" htag="div" wd="angina pectoris"><a class="sound audio_play_button pron-us icon-audio" onclick="document.getElementById('OALD10_pron_angina_pectoris_1_us_1').play();" style="cursor: pointer" title="angina pectoris pronunciationAmerican" valign="top"></a><span class="phon">/ænˌdʒaɪnə ˈpektərɪs/</span></div></span></span>)</div> <span class="grammar" hclass="grammar" htag="span">[uncountable]</span></div></div></div><ol class="sense_single" htag="ol"><li class="sense" hclass="sense" htag="li" id="angina_sng_1"><span class="sensetop" hclass="sensetop" htag="span"><span class="def" hclass="def" htag="span">severe pain in the chest caused by a low supply of blood to the heart during exercise because the <a class="Ref" href="https://www.oxfordlearnersdictionaries.com/definition/english/artery#artery_topg_1" title="arteries definition"><span class="ndv">arteries</span></a> are partly blocked</span></span><div class="collapse" hclass="collapse" htag="div"><span class="unbox" id="angina_unbox_1" unbox="wordorigin"><span class="box_title" onclick="toggle_active(this)">Word Origin</span><span class="body"><span class="p">mid 16th cent.: from Latin, ‘quinsy’ ‘inflammation of the throat’, from Greek <span class="ei">ankhonē</span> ‘strangling’.</span></span></span></div></li></ol></div></div></body></html><audio id="OALD10_pron_angina__gb_1" preload="none" src="OALD10_pron_angina__gb_1.mp3"></audio><audio id="OALD10_pron_angina__us_1" preload="none" src="OALD10_pron_angina__us_1.mp3"></audio><audio id="OALD10_pron_angina_pectoris_1_gb_1" preload="none" src="OALD10_pron_angina_pectoris_1_gb_1.mp3"></audio><audio id="OALD10_pron_angina_pectoris_1_us_1" preload="none" src="OALD10_pron_angina_pectoris_1_us_1.mp3"></audio>`; window.parent.postMessage(custom_content,'*');
JavaScript
CL
d20f2741477a5ebf74a245e12c8ddd680bea9465509a0c5f3af1aa9bd16596a3
const rawData = { articles: [ { id: 'allergy', title: 'Аллергия на холод', date: new Date().toLocaleDateString('se').replace(/\D/g, '.'), description: 'Детская кожа у детей нежнее и тоньше, чем у взрослых, поэтому реагирует на холод быстрее и дольше.', author: { firstName: 'Долгушина', lastName: 'Елена', website: 'https://twitter.com/samerbuna', }, blockquote: `Что же, вообще не гулять? Ведь в широтах средней полосы холод и сырость — обычное явление, проследить развитие заболевания, назначить терапию и оценить ее эффективность.`, source: 'http://www.katiebulmer.com/wp-content/uploads/2015/12/health.jpg', name: 'allergy.jpg', body: [ { headline:'', text:` Вы вернулись с малышом с зимней прогулки и радуетесь его румяным с мороза щечкам. Но проходит несколько часов, а румянец все не спадает, хуже того, к нему добавляется сыпь. Ребенок жалуется на сильный зуд, пытается расчесывать щеки. Серьезно отнеситесь к этим проявлениям организма: у малыша, скорее всего, холодовая аллергия — специфическая сосудистая реакция на понижение температуры.Детская кожа у детей нежнее и тоньше, чем у взрослых, поэтому реагирует на холод быстрее и дольше. Если у взрослых прежде всего страдают руки (в кистях рук затруднен отток крови из-за основного положения их при ходьбе — вниз; также, частые контакты с водой удаляют защитный слой, созданный сальными железами, и кожа рук становится излишне сухой, а холод и мороз добавляют проблем: кожа рук трескается, шелушится, покрывается сыпью, а иногда волдырями), то у детей прежде всего страдает лицо. Помимо покраснения щек и подбородка от холода могут слезиться и краснеть белки глаз, шелушиться и растрескиваться губы. Появляются «заеды» в уголках рта. Веки и губы могут отекать. ` }, { headline:'Холодовая аллергия у детей', text:` Вообще, симптомы холодовой аллергии схожи с симптомами конъюнктивита и простуды: заложенный нос, дыхание с хрипами, сухой кашель (особенно ночью).Легкая форма холодовой аллергии выражается несильным зудом, мелкими высыпаниями, и небольшим отеком лица, иногда рук, которые за один — три часа проходят без лечения.При тяжелой форме холодовой аллергии или длительном пребывании ребенка на морозе могут возникнуть такие опасные осложнения как отек Квинке и бронхоспазм. Спровоцировать холодовую аллергию может и холодный сырой ветер в межсезонье, а не только мороз.Что же, вообще не гулять? Ведь в широтах средней полосы холод и сырость — обычное явление, донимающее жителей многие месяцы в году. Не стоит надеяться, что организм с возрастом адаптируется к холоду. По мере взросления, реакции человека, страдающего аллергией на холод, станут тяжелее. Поэтому, необходимо показать ребенка аллергологу, во-первых, для того, чтобы подтвердить или исключить дерматиты, дерматозы и другие кожные заболевания, протекающие с такими же симптомами: сыпь, зуд, пузырьки на руках. Во-вторых, специалист назначит необходимые анализы, уточнит состояние здоровья ребенка. Многие хронические и острые заболевания, болезни внутренних органов, ОРВИ (часто аллергия на холод начинается после перенесенных простуд), гельминтозы, стрессовые ситуации снижают иммунитет, что влечет за собой неправильную реакцию клеток, которые располагаются в поверхностных слоях эпидермиса. Раздражаясь от холода, они производят огромное количество гистамина, который выбрасывают в межклеточное пространство. Врач выяснит, что послужило снижению иммунитета ребенка и назначит лечение. ` }, { headline:'Правила для родителей', text:` Родителям необходимо соблюдать правила питания малыша, исключать аллергические продукты. Чтобы не допустить пищевой аллергии, все мясные блюда (тефтели, котлеты) готовят на пару, так как жареная пища является сильным аллергеном. До полутора-двух лет следует измельчать блендером все ингредиенты супа, а не класть полезные кусочки в бульон, так как дети проглатывают их не жуя. Из-за несовершенной пищеварительной системы малышей, кусочки мяса и рыбы не до конца перевариваются, а непереваренный белок — сильный аллерген. Аллергены разрушаются при варке. Овощи и крупы следует варить на тихом огне около получаса. И конечно, кормить малыша только свежеприготовленной едой. Исключения составляют специальные детские консервы, которые готовятся по гипоаллергенной технологии. Не гуляйте с ребенком в ветреную погоду и сильную метель. Необходимо свести воздействие холода и ветра на открытые участки кожи к минимуму: за полчаса до выхода мазать лицо ребенка детским кремом или барсучьим жиром, губы – гигиенической помадой. Из головных уборов предпочтительнее «шлем», максимально закрывающий лицо, на руки – непромокаемые варежки. Не разрешайте ребенку трогать снег, ограничьте пребывание на холоде до получаса, так как более длительные прогулки принесут больше вреда, чем пользы. Одевайте ребенка по погоде, не кутайте его, если он уже ходит, а если лежит в коляске — плюс еще слой одежды. Обувь выбирайте из натуральных материалов (валенки, унты) и точно по размеру. Летом начните закалять малыша, посоветовавшись с врачом. Свести все проявления аллергии к минимуму—задача родителей и врачей. Разумный подход к быту и режиму малыша, спокойная обстановка в семье, выполнение рекомендаций врача помогут в борьбе с аллергией. В редких случаях, когда холодовая аллергия передается из поколения в поколение и протекает тяжело, приходится задуматься о переезде в местность с более благоприятным климатом. Также, отмечены случаи, когда у женщин с детства страдавших холодовой аллергией, после родов полностью пропадали все ее симптомы. Видимо играет роль гормональная перестройка организма.Изучайте себя и ребенка, подмечайте реакции организма на разные обстоятельства, ищите грамотного аллерголога, и обязательно справитесь с холодовой аллергией.` }, ], }, { id: 'mom', title: 'Как пережить жару будущей маме?', description: ` Летняя жара доставляет немало хлопот даже тем беременным, которые знают о токсикозе только от подруг. Во многих случаях... `, date: new Date().toLocaleDateString('se').replace(/\D/g, '.'), name: 'pregnancy.jpg', author: { firstName: 'Светлана', lastName: 'Евсеева', }, blockquote: `Беременной женщине (конечно же не на последних неделях беременности) важно быть активной и много времени проводить на свежем воздухе.`, body: [ { headline:'', text:` Летняя жара доставляет немало хлопот даже тем беременным, которые знают о токсикозе только от подруг. Во многих случаях, беременность летом – это усиливающиеся тошнота, отеки рук и ног, ощущение того, что кожа вот-вот загорится и т.д. Советы акушеров-гинекологов и терапевтов, как пережить летнюю беременность с минимальным стрессом для психики и организма помогут как будущим роженицам, так и тем девушкам и женщинам, которые только планируют стать мамой. А также будущим папам, ведь кто же еще лучше всего позаботится о любимой?` }, { headline:'Как снизить влияние высокой температуры воздуха и духоты', text:` Беременной женщине в жару дискомфортнее, чем остальным: гормональная перестройка, помноженная на духоту, усиливает тошноту, головокружение, будущую маму и так бросает в пот, плюс плацента сама по себе выделяет дополнительное тепло. Поэтому беременной важно обезопасить себя от лишнего перегревания. В первую очередь не забывайте, что в период беременности ваше тело – «дом» для будущего человечка, поэтому исходя из соображений о безопасности малыша, не стесняйтесь просить уступить место в транспорте, не молчите, если стало плохо на работе, требуйте включить кондиционер и т.д.` }, { headline:'', text:` Спасти от жары поможет прохладная вода во всех ее проявлениях: ванночки для ног, обтирания, душ, умывание. Если вы преодолели первый триместр беременности, то можно добавить в ванночку для ног эфирное масло лаванды, грейпфрута или лайма – они хорошо охлаждают и успокаивают нервную систему, помогают снять отечность ног. Но если у вас нет аллергии: об использовании эфирных масел во время беременности лучше посоветоваться со своим врачом. То же – относительно использования тоников, термальной воды, охлаждающих спреев и т.д.` }, { headline:'Носите удобную одежду и правильно распределяйте нагрузки ', text:` Каблуки, синтетические узкие майки и т.д. оставьте на потом, а сейчас старайтесь одеваться в свободную одежду из натуральных тканей и носить удобную, открытую обувь. То же касается постельного белья. Беременной женщине (конечно же не на последних неделях беременности) важно быть активной и много времени проводить на свежем воздухе. Однако жара и активные физические упражнения несовместимы. Отличной альтернативой станет йога для беременных и плавание: это поможет разгрузить уставшие суставы и связки. Только купаясь в водоемах, обращайте внимание, можно ли там купаться, чтобы не подцепить инфекцию или кожное заболевание. Идеально было бы отдохнуть на море не меньше месяца. При отдыхе на море и вообще летом, под воздействием солнца, не забывайте защищать кожу: солнцезащитный крем, очки, панама или шляпа обязательно должны быть всегда на вас!` }, { headline:'Горячие» летние советы беременным: на что обратить внимание', text:` Для борьбы с утренней тошнотой, которая может обостриться в жару, можно использовать имбирь: капсулы, порошок или натертый корень имбиря в чай. Но опять же – все действия согласовываем со своим акушером-гинекологом: при сильной тошноте врач может назначить дополнительный прием витаминов группы В. Также снизить токсикоз поможет прием пищи мелкими порциями, отказ от жирной пищи. Для облегчения состояния в период беременности медики также советуют: -снять кольца и перстни до того, как начнут отекать пальцы и пока их не носить -снять отечность и усталость ног поможет массаж. Попросите мужа или родственников осторожно помассировать вам ноги, двигаясь от ступней к коленам -избегайте кофе, газированных напитков, они усиливают жажду и вызывают тошноту -не перегружайте себя делами. Лучшее времяпрепровождение в жару – раскладной стул или гамак в тени и интересная книга.` }, ] }, { id: 'teeth', title: 'Зубы мудрости: лечить или удалять', description: 'Лабораторная диагностика необходима медицине как важнейший источник информации об организме ', date: new Date().toLocaleDateString('se').replace(/\D/g, '.'), name: 'teeth.jpg', author: { firstName: 'Светлана', lastName: 'Евсеева', }, body: [ { headline:'', text:` «Зубы мудрости лучше удалять» - данное мнение весьма распространено. Процесс, когда зубы мудрости прорезываются, весьма болезненный, во многих случаях такой «мудрый» зуб вообще не может появиться и создает немало хлопот. Также иногда выросшие без проблем зубы мудрости могут начать болеть из-за разрушительного воздействия на зуб кариеса и т.д. Нужно ли лечить такой зуб, или лучше его сразу удалить, как «безнадежный». Давайте узнаем, что думают по этому поводу стоматологи и насколько зубы мудрости важны для организма человека вообще.` }, { headline:'Почему зуб «мудрый» и доставляет столько беспокойства', text:` Прорезываться зубы мудрости начинают в среднем между 18 и 25 годами, а иногда даже в 35-40 лет. Своим названием зубы мудрости обязаны именно их позднему появлению, ведь смена с молочных зубов на постоянные начинается в среднем в период с 7 до 13 лет. Зубы мудрости ничем не отличаются по внешнему виду от любого другого многокорневого зуба. Они располагаются восьмыми по счету от центральных резцов как в верхней, так и в нижней челюсти. Поэтому зубы мудрости также называют 8-м зубом, в среднем вырастает 4 зуба мудрости. Но могут быть и исключения, когда зачатки восьмого зуба погибают, и зуб не прорезывается. Процесс эволюционирования человека привел к тому, что размер его челюсти изменился. От поколения к поколению нагрузка на челюсти в связи с употреблением более мягко пищи становилась меньше. И размеры челюсти сократились, более короткая челюсть привела к тому, что зубам мудрости стало сложнее прорезываться.` }, { headline:'Почему зуб «мудрый» и доставляет столько беспокойства', text:` Прорезываться зубы мудрости начинают в среднем между 18 и 25 годами, а иногда даже в 35-40 лет. Своим названием зубы мудрости обязаны именно их позднему появлению, ведь смена с молочных зубов на постоянные начинается в среднем в период с 7 до 13 лет. Зубы мудрости ничем не отличаются по внешнему виду от любого другого многокорневого зуба. Они располагаются восьмыми по счету от центральных резцов как в верхней, так и в нижней челюсти. Поэтому зубы мудрости также называют 8-м зубом, в среднем вырастает 4 зуба мудрости. Но могут быть и исключения, когда зачатки восьмого зуба погибают, и зуб не прорезывается. Процесс эволюционирования человека привел к тому, что размер его челюсти изменился. От поколения к поколению нагрузка на челюсти в связи с употреблением более мягко пищи становилась меньше. И размеры челюсти сократились, более короткая челюсть привела к тому, что зубам мудрости стало сложнее прорезываться.` }, { headline:'Удалять или сохранять: что говорят стоматологи', text:` Если при прорезывании восьмого зуба у человека не хватает для него места в челюсти, то зуб мудрости начинает сдвигать расположенные рядом зубы, а сам процесс может растянуться на несколько лет. При прорезывании такого зуба наполовину стоматолог может порекомендовать удалить зуб, чтобы в дальнейшем избежать смещения зубного ряда. Если в 8-м зубе, который вырос без проблем, образовался кариес, зуб начал беспокоить, то специалист предложит изначально полечить зуб. Такой «мудрый» зуб может стать опорой для установки зубного протеза («моста») в случае удаления седьмого или шестого зуба. Также показано лечение, а не удаление восьмого зуба-антагониста, то есть зуба мудрости, влияющего на формирование прикуса противоположной челюсти. Также важно своевременно протезировать удаленные зубы, иначе зуб-антагонист может сместиться и занять образовавшуюся на месте удаленного зуба полость.` }, { headline:'Когда удаления зуба не избежать', text:` В ряде случаев лечение зубов мудрости не обосновано и специалист посоветует такие зубы удалить. А именно: -Если восьмой зуб прорезался неправильно и непригоден для протезирования в будущем -Воспалительный процесс в таком зубе привел к развитию инфекционного периодонтита – воспалению удерживающих зуб связок -Развилось воспаление в капюшоне возле зуба мудрости (перикорнит). Это бывает в случаях, когда зубу не удается полностью появиться из десны и в маленькой впадинке между самим зубом и слизистой оболочкой начинает застревать пища, размножаться микроорганизмы и воспалительный процесс переходит в хроническое состояние. Тогда зуб мудрости имеет смысл удалить. Если восьмые зубы у вас прорезались полностью и не доставили хлопот, то специалисты напоминают, что их важно не забывать тщательно чистить, как и остальные зубы. Восьмые зубы находятся глубже всех, поэтому важно счищать с них налет и остатки пищи не менее тщательно, пользоваться зубной нитью и ополаскивателями для полости рта.` }, ], }, { id: 'children3', title: 'Сколько сладкого можно ребенку?', description: `“Сладкое любят большинство людей, и в особенности — малыши. Но сколько таких продуктов им можно давать? И в каких случаях... `, date: new Date().toLocaleDateString('se').replace(/\D/g, '.'), name: 'children.jpg', author: { firstName: 'Светлана', lastName: 'Евсеева', }, body: [ { headline:'', text:` “Сладкое любят большинство людей, и в особенности — малыши. Но сколько таких продуктов им можно давать? И в каких случаях их следует исключить? Информационно-аналитическому отделу детской поликлиники «Маркушка» удалось получить необходимые пояснения от д-ра Петры Шуриц (Petra Schuritz), эксперта-специалиста по детскому питанию из Ассоциации акушеров и семейных детских врачей г. Фульда (Германия, Федеральная земля Гессен). Почему дети любят сладкое? Дети любят его уже от рождения. Сначала для новорожденного материнское молоко слегка сладковатое, а потом он питается подслащенными фруктовыми пюре и кашами. Вкус на сладкое у малыша практически «безошибочен», а натуральные сладкие продукты он с самого рождения воспринимает как безобидные и не ядовитые. Потом малыш начинает осознает неоценимый вкус конфет. И тут кроется определенная опасность — повышение потребности в сладких и приторно-сладких продуктах. Условно: десяти процентов сладких продуктов достаточно для малыша Максимально десяти процентов (т.е. 95 ккал для ребенка первого года жизни и 110 ккал для ребенка в 2-3 года, в расчете на ежедневную энергитическую потребность) вполне достаточно и не опасно для малыша — так считают все детские врачи. Но желательно даже меньше и, кроме того, следует как можно дольше ограждать малыша от шоколада и шоколадных изделий. Простое условное правило: ребенку ежедневно разрешено столько сладостей, сколько умещается в его руке. Сладкие продукты — только для удовольствия` }, { headline:'', text:` Конфеты и вообще сладкие продукты не следует использовать как средства поощрения, утешения или воспитания детей. Ребенок уже с самого раннего детства должен привыкнуть, что такие изделия — это просто нечастое удовольствие. Иначе, повзрослев, он может уже самостоятельно считать их средством утешения и средством решения каких-то психологических проблем. В итоге может появиться непреодолимая тяга к сладкому. Правильная форма и состав продуктов. Маленький ребенок не получит никакого удовольствия, если он просто проглотит маленькую конфету или драже, к тому же это опасно. Кроме того, желательно исключить продукты с искусственными красителями, ароматизаторами, значительным содержанием лимонной кислоты и гидрогенизированных жиров. А можно ли маленькому ребенку в день рождения давать пирожное? Можно, но (в качестве примера) самостоятельно испеченное морковное пирожное, с небольшой добавкой муки и меда.` }, ], blockquote: `Простое условное правило: ребенку ежедневно разрешено столько сладостей, сколько умещается в его руке.`, }, { id: 'children', title: '"Святая пятерка" симптомов жертвы токсических отношений', description: `Жизнь каждого из нас могла бы напоминать бег в красивом развевающемся платье по цветущему лугу в солнечный ... `, date: new Date().toLocaleDateString('se').replace(/\D/g, '.'), name: '6-min.jpg', author: { firstName: 'Светлана', lastName: 'Евсеева', }, body: [ { headline:'', text:` Жизнь каждого из нас могла бы напоминать бег в красивом развевающемся платье по цветущему лугу в солнечный июньский день. Но среди маков и васильков на этом прекрасном лугу часто попадаются такие матерые репейники, что от вашего красивого платья остаются одни лохмотья. Назовем их «токсичные партнеры». Степень родства с таким зельем может быть очень разная. Это и муж, и друг, и мама, и коллега по работе. Самое главное, что вы пустили этого человека в самую интимную зону своей жизни. Самое главное, что он для вас значим. Токсичный партнер сидит себе в вашей жизни и берет от вас абсолютно все, что ему нужно для собственного комфорта. А вот вы, мои дорогие, начинаете болеть. Приблизительно через год-полтора от начала стабильных (более-менее обозначенных) отношений с нашими объектами формируются специфические симптомы. Очень яркие, манифестные, но лечению почти не поддающиеся. Я, благодаря клиническим наблюдениям, вывела "святую пятерку" симптомов жертвы токсических отношений. Чем и хочу сегодня поделиться с вами. Итак:` }, { headline:'1.Вазомоторный ринит.', text:` Постоянно заложен нос. Утром больше, после сна. Причем, на стороне, на которой спали, заложенность больше. Сопли прозрачные, солоноватые, как будто морской водички носом вдохнули. Жидкие. Могут потечь внезапно. Сопровождается приступами болезненного чихания и слезотечением. Что это? Невыплаканные слезы. Запрет на "горевание", запрет на "раскисание". "Я должен(на) быть сильной". "Причин для расстройства нет, я сам(а) себе напридумывал(а)". Плюс критическое недосыпание. Что делать? Выспаться и выплакаться. В произвольном порядке. Реветь белугой. Потом принять теплый душ и спать. ` }, { headline:'2. Боли в спине', text:` Болит приступами. В разных отделах, но, чаще всего, поясница. Вроде все нормально, вчера бегала, на стол накрывала, полы мыла, а сегодня над детской кроваткой нагнулась - хлоп! Аж в глазах от боли потемнело. Ходить больно, сидеть больно, лежать больно. Обезболивающие помогают мало. Мануальщиков ненавидите. Что это? Отсутствие базовой защиты. Жизнь в "подвешенном" состоянии. Финансовая нестабильность. Хроническая усталость. Все это приводит к критическому мышечному спазму (миофасциальный блок), который дает болевой синдром, зачастую, сильней, чем при переломах. Что делать?По возможности, раздать домочадцев. Хоть на сутки. Теплая ванная с большим количеством соли. Любой. Надо помочь мышцам расслабиться. Особенно, их глубоким слоям. Никаких мануальных "хрустов" или рывков. ЭТО НЕ ЗАКЛИНИЛО, ЭТО СПАЗМ! А спазм снимается только расслаблением. Техники глубокого дыхания. Из специалистов - телесно-ориентированные терапевты, кранио-сакральные, остеопаты.` }, { headline:'3. Аденомиоз, эндоментриоз (если жертва-женщина).', text:` Месячные нерегулярные, цикл укорачивается. Идут сгустками, кровь темная, иногда выделения шоколадного цвета. Менструации становятся болезненными и затяжными. Доктора пугают. Самой страшно, когда видишь, что из тебя вываливается. Что это? Отвратительный секс. "Я не хочу с ним спать". Отсутствие оргазма. Женщина чувствует себя станком для облегчения. Принуждение к близости. Обвинение в "несостоятельности" в постели. Что делать? Поменять партнера. Срочно. Если у женщины возникает аденомиоз, то токсическое воздействие партнера на нее запредельное. Дальше тянуть некуда. Оправданий нет. Организм противится контакту с ним и создает единственно возможные условия для оправданного отказа - постоянные, обильные, болезненные месячные. Аденомиоз по степени агрессивности приравнивается к опухолевым процессам. Помните об этом, когда решите "еще немного потерпеть". ` }, { headline:'4.Боль головы.', text:` Может накрывать по типу мигрени. Может жечь затылок. Может быть кластерная боль (будто палку в глаз воткнули). Параллельно может подташнивать. Периодически подводит память. Ухудшается зрение. Что это? Результат того, что вас постоянно выставляют в дурном свете. Подсознательно вы знаете себя и свою суть. А на вас годами напяливают совершенно другие образы. Обесценивание. Вовлечение в чужие игры. Туманные перспективы. И, конечно же, недосыпание. Что делать? Послать этого гребаного "худрука" к чертовой матери и срежиссировать свою жизнь самому. Иначе инсульт в 36 лет обеспечен. Вспомнить, кто я. Или познакомиться с собой заново. Выспаться.". ` }, { headline:'5. Сыпь.', text:` Кожа постоянно чем-то обсыпана. То прыщи, то шелушение, то аллергия. Параллельно с этим выпадают волосы и слоятся ногти. Антигистаминные перепробованы даже будущих поколений. Витаминные комплексы приняты размером с нефтеперерабатывающие. Косметологи за ваш счет пару раз съездили на Бали. А воз и ныне там. И картина в зеркале вызывает глухое отчаяние. Что это? Кожа - барьерный орган. И сыпью она протестует против "вражеского лазутчика", постоянно через этот барьер перелезающего. Причем, нагло и бесцеремонно. Результат постоянного пресловутого "нарушения границ". Плюс агрессия, которую тщательно маскируем. "Ты же хорошая девочка". Плюс аутоагрессия. "Я сама во всем виновата". Что делать? В первую очередь, не врать самой себе. Дать право психануть и честно признаться, на кого. Отстроить границы. Желательно с помощью специалиста. Повыбрасывать стопитсот баночек из ванной, оставить самый простой уход и делать это с наслаждением и любовью к себе, а не как обязаловку. Пересмотреть отношение к сигарете. И к качеству еды. Побольше гулять. Желательно, в приятной компании. А из витаминов стоит оставить группу В с магнием и цинком. Для нервишек, которые и драконят кожу. Если хоть что-то из этого списка отозвалось – пора устраивать «прополку» своей жизни. Значит, завелся репейник. Не бойтесь это делать, ваше тело за это скажет только «спасибо». Берегите себя и будьте здоровы! ` }, ], blockquote: `“Токсичный партнер сидит себе в вашей жизни и берет от вас абсолютно все, что ему нужно для собственного комфорта. А вот вы, мои дорогие, начинаете болеть.”.`, }, { id: 'children2', title: 'А какой наркоз самый лучший?', description: `“«Самый лучший наркоз – это тот, которым хорошо владеет анестезиолог» - глубокомысленно отвечаю я и иду переодеваться в синий хирургический костюм. `, date: new Date().toLocaleDateString('se').replace(/\D/g, '.'), name: '7-min.jpg', author: { firstName: 'Светлана', lastName: 'Евсеева', }, body: [ { headline:'', text:` «Доктор, - часто спрашивают перепуганные пациенты перед операцией, - а какой наркоз самый лучший?» «Самый лучший наркоз – это тот, которым хорошо владеет анестезиолог» - глубокомысленно отвечаю я и иду переодеваться в синий хирургический костюм. А пациентов в замешательстве оставлять нельзя. Они начинают читать форумы и делать собственные выводы из чужого, зачастую, не очень удачного опыта. И вся эта каша в головах дает неожиданный и не очень приятный эффект где? Правильно, именно в операционной. Вот для того, чтоб люди, далекие от хирургии владели правильной информацией о работе анестезиолога, я и хочу сегодня поговорить об искусстве обезболивания. Прежде всего, давайте разграничим понятия «наркоз» и «анестезия». Наркоз – когда человек во время операции спит. Анестезия – когда человеку не больно, но спать при этом он и не может. Поэтому понятия «местный наркоз» не существует в принципе. ` }, { headline:'', text:` А вот «местная анестезия» - распространенная манипуляция, когда нужно обезболить небольшую зону хирургического вмешательства (например, при офтальмологических вмешательствах, удалении незначительных образований на коже, вросшем ногте и т.д) и весь организм для этого отключать совершенно не нужно. Как же хитрые доктора вводят пациентов в сонное состояние, то есть, в наркоз? Самый распространенный способ – внутривенный. Сейчас есть достаточный выбор медикаментов с разной глубиной и временем действия. Пациенту ставят в вену специальный гибкий катетер, потом просят посчитать от одного до десяти (как вариант) … и удивленный пациент, досчитавший всего до семи, просыпается в палате, очень даже хорошо себя чувствуя. Уже с пластырем или швами в запланированном месте. Маленьким детям часто используют внутримышечный наркоз. После подготовительных мероприятий, проведения специфических проб, малышу в попу вводят лекарство в рассчитанной дозе, и он мягко и спокойно в течении 2-3 минут засыпает на руках у мамы. Или у папы, тут уже родители выбирают, у кого психика крепче. Ребенок, в данном случае, не получает дополнительного стресса от вынужденной разлуки с родителями, а родители спокойней отдают докторам мирно спящего малыша. А не орущего и вырывающегося. Да и просыпается маленький пациент уже в палате под ласковый голос мамы.` }, { headline:'', text:` Есть еще ингаляционный наркоз. Когда пациенту через маску или специальную трубочку, введенную в трахею, дают вдыхать специальные газы, вызывающие сон. Это хороший и достаточно управляемый метод. Газ выключили – пациент проснулся. Можно использовать и при краткосрочных операциях, и, в сочетании с другими препаратами, при длительных вмешательствах. Но вот единственный нюанс – требует специальной аппаратуры с мощными фильтрами. Касательно анестезии, то есть, непосредственно обезболивания, тоже есть много вариантов. И варианты эти выбираются в зависимости от зоны и глубины хирургического вмешательства: - если анестетик в виде мази, спрея, геля или раствора наносится на зону воздействия – это аппликационная анестезия; - если анестетик вводится с помощью иглы (инъекция) в ткани области хирургического вмешательства, постепенно, послойно выключая чувствительность даной зоны – это инфильтрационная анестезия; ` }, { headline:'', text:` - если обезболивающий препарат доктор вводит строго по анатомическим ориентирам в область около крупного нерва, что может выключить чувствительность крупной зоны и даже целой конечности – это проводниковая анестезия; - если же анестезиолог вводит обезболивающее в район позвоночника, что может полностью блокировать передачу импульса практически в половине тела и позволяет провести массивные операции на больших и чувствительных зонах – это либо спинномозговая, либо эпидуральная анестезия. В современной медицине есть огромный выбор лекарств для наркоза и анестезии, а также способов их введения. Часто делают комбинированную анестезию, сочетают несколько видов и способов использования. Все зависит от состояния пациента и объема операции. Именно поэтому очень важно, чтоб пациент и врач были максимально откровенны между собой. А я очень надеюсь, что, при всем арсенале нынешней медицины, вы выберете быть здоровыми.` }, ], blockquote: `Простое условное правило: ребенку ежедневно разрешено столько сладостей, сколько умещается в его руке.`, }, { id: 'heart', title: 'Варикозное расширение вен: причины и последствия.', description: `Диагноз «варикозное расширение вен нижних конечностей» настолько распространенный, что люди не уделяют заболеванию необходимое внимание...`, date: new Date().toLocaleDateString('se').replace(/\D/g, '.'), name: '8-min.jpg', author: { firstName: 'Светлана', lastName: 'Евсеева', website: 'https://twitter.com/reactjs', }, body: [ { headline:'', text:` Диагноз «варикозное расширение вен нижних конечностей» настолько распространенный, что люди не уделяют заболеванию необходимое внимание. Но последствия развития варикоза могут стать довольно плачевными, поэтому лучше все-таки обратить внимание на проблему на ранней стадии и вовремя начать с ней бороться. ` }, { headline:'Возможные причины варикоза', text:` Варикозное расширение вен – это болезнь, при которой вены растягиваются, искривляются, расширяются и теряют свою природную эластичность. Из-за этого ноги сильно устают, болят и отекают к концу дня, позже на них появляются косметические дефекты в виде венозных сеточек и вздутых вен, что очень некрасиво само по себе, а также довольно опасно. Самое худшее последствие варикоза – развитие тромбофлебита. При этой болезни тромб образовывается в вене, может оторваться от стенки сосуда в любой момент, попасть в сосуды легких и нарушить работу дыхательной системы. Из-за этого человек может умереть.` }, { headline:'Причин варикозного расширения вен несколько:', text:` Плохая наследственность. Варикозное расширение вен считается семейной болезнью, ведь через гены человеку передаются особенности строения сосудов. В 90% случаев болезнь достается нам по наследству, особенно по женской линии. Беременность. Во время ожидания малыша у женщины существенно снижается тонус вен, также на них оказывает давление постоянно растущая матка. Кроме того, не стоит забывать, что в период беременности будущая мама существенно прибавляет в весе. А роды – это вообще испытание для вен. Условия труда. Люди, которые из-за особенностей своей профессии вынуждены постоянно стоять, более подвержены риску развития варикоза. Речь идет о продавцах, поварах, официантах, парикмахерах, рабочих у станка. Кроме того, вредно постоянно сидеть, поэтому офисная работа – также неблагоприятный фактор в данном случае. Также вредно сидеть в позе «нога на ногу». Неудобная обувь и одежда. Узкая обувь, особенно на высоких каблуках – верный путь к варикозу. Она значительно увеличивает нагрузку на ноги и вены на них. Также вредно носить слишком обтягивающую, узкую одежду, например, периодически модные узкие джинсы. Чрезмерные физические нагрузки. Особенно опасен подъем тяжестей, силовые тренировки, единоборства.` }, { headline:'Что делать при первых признаках варикоза?', text:` Если у вас чрезмерно устают, отекают или болят ноги, появилась венозная сеточка на ногах, обратитесь за помощью к специалисту, чтобы не допустить развития болезни. Лечением варикозного расширения вен занимается флеболог, но если в вашем населенном пункте не принимает этот узкий специалист, можно обратиться к хирургу. На ранней стадии развития болезни варикоз лечат консервативными методами: с помощью гелей и мазей, препаратов против венозной недостаточности. Также возможно лечение лазером, озонотерапией. Если варикозное расширение уже в запущенном состоянии, необходимо хирургическое вмешательство – флебэктомия. Тогда больная вена просто удаляется.` }, { headline:'', text:` Чтобы избежать варикоза, нужно вести активный образ жизни, больше двигаться: ходить, плавать, ездить на велосипеде. Также стоит следить за своим питанием, чтобы не допускать появления лишнего веса, который очень неблагоприятно сказывается на состоянии вен. Не злоупотребляйте обувью на высоких каблуках и узкой И помните: варикозное расширение вен нижних конечностей может привести к тромбофлебиту, что очень опасно для здоровья и жизни человека. Поэтому не забывайте о важности профилактики и своевременного лечения этой болезни.` }, ], blockquote: `Варикозное расширение вен считается семейной болезнью, ведь через гены человеку передаются особенности строения сосудов.`, }, { id: 'heart2', title: 'Что делать при сильном сердцебиении?', description: `Расстройства ритма и частоты сердечных сокращение приводит к разным нарушениям в человеческом организме. В результате ...`, date: new Date().toLocaleDateString('se').replace(/\D/g, '.'), name: 'heart.jpg', author: { firstName: 'Светлана', lastName: 'Евсеева', website: 'https://twitter.com/reactjs', }, body: [ { headline:'', text:`Расстройства ритма и частоты сердечных сокращение приводит к разным нарушениям в человеческом организме. В результате развиваются сердечно-сосудистые заболевания, негативно влияющие на его работу в целом. Мы не привыкли реагировать на учащенное сердцебиение…а зря, при приступах тахикардии обязательно нужно измерить пульс и принять меры.` }, { headline:'Причины и симптомы тахикардии', text:` Если приступы тахикардии длиться некоторое время, то они провоцируют некоторые изменения в работе организма. Существует множество причин для появления учащенного сердцебиения: физические нагрузки – вызывают учащенное дыхание, и как результат, приступы тахикардии; эмоциональный сбой. Разные чувства вызывают тахикардию. При этом это могут быть и положительные, и отрицательные эмоции – радость, страх, раздражение; аллергическая реакция, возникающая на какой-то раздражитель; переедание, особенно на ночь вызывает аритмию; у женщин во время наступления климакса; повышение температуры при любых причинах. Это может быть и простуда, и стресс. При повышении t на один градус, сердцебиение учащается на 10 ударов; употребление энергетических напитков, которые содержат вещества, увеличивающие частоту сердечных сокращений.` }, { headline:'Первая помощь при тахикардии', text:` Когда начинается приступ, самым важным условием является полный покой и нормальное дыхание. Важно, чтобы ничего не передавливало горло и грудь. В помещении нужно открыть окна и проветрить комнату. Если под язык положить таблетку Валидола через несколько минут сердцебиение восстановится. Если этого не произойдет, рекомендуется вызывать «скорую помощь». При нормальном состоянии частота сердечных сокращений должна быть 60-80 ударов в минуту. Но в момент приступа или физической нагрузки важно соблюдать допустимые параметры. Они вычисляются следующим образом: от 220 нужно отнять возраст. Например, в 40 лет в момент нагрузки сердцебиение не должно превышать 180 ударов в минуту. Итак, основные действия неотложной помощи: обеспечить приток свежего воздуха; выпить Валидол или Корвалол; умыться холодной водой и положить на лоб холодный компресс; нужно сильно подуться и покашлять. Такие манипуляции нужно совершать пока не приедет «скорая помощь», потом врачи уже примут меры, в зависимости от состояния здоровья.` }, { headline:'Питание при тахикардии', text:` При тахикардии важно правильно питаться и кушать по определенной схеме: есть нужно регулярно, ежедневно в одно и то же время; питаться рекомендуется небольшими порциями, но часто; на ночь кушать нельзя; от сладкого рекомендуется отказаться; хотя бы раз в неделю нужно делать разгрузочный день; важно соблюдать количество растительных и животных жиров; необходимо насытить рацион продуктами с высоким содержанием магния и калия. Важно в рацион включить следующие продукты: мед, который укрепляет сосуды; орехи, усиливающие кровоснабжение головного мозга; отвар шиповника, для укрепления сердечной мышцы; каши на молоке (не очень сладкие); мясо индейки, кролика, нутрии – оно нежирное и диетическое.` }, ], blockquote: `Контролируйте частоту сердечных сокращений, правильно питайтесь и соблюдайте врачебные рекомендации – здоровье важный аспект полноценной жизни!`, } ] } const deepCopy = (obj) => JSON.parse(JSON.stringify(obj)) let appData = { articles: [] } export const getArticleList = () => { appData.articles = rawData.articles.reduce((acc, article) => { acc.push({ id: article.id, title: article.title, date: article.date, name: article.name, description: article.description, blockquote: article.blockquote }) return acc }, []) return Promise.resolve(deepCopy(appData.articles)) } export const getArticle = (articleId) => { appData.currentArticle = rawData.articles.find(article => article.id === articleId) return Promise.resolve(deepCopy(appData.currentArticle)) } export const addArticle = (articleInfo) => { const newArticle = Object.assign({}, articleInfo, { id: articleInfo.title.toLowerCase().replace(/[^a-z]+/, '-'), date: new Date().toString(), }) rawData.articles.push(newArticle) appData.currentArticle = newArticle return Promise.resolve(deepCopy(appData.currentArticle)) }
JavaScript
CL
320bbf54080b9d47ca2b73160125d04c3d0b83b048ab6f79a4682642eb0a335a
/** * Copyright (c) 2015-present, tbud, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule TButton * @flow */ 'use strict'; import React, {Component, PropTypes} from 'react'; import {Scale} from 'toothless_scale'; import defaultStyles from './ButtonDefaultStyles'; class TButton extends Component { constructor(props) { super(props); } static defaultProps = { type: 'default', value: 'OK', disabled: false, block: false, style: {}, onPress: ()=> { } }; static propTypes = { type: PropTypes.oneOf['primary', 'flat', 'default'], value: PropTypes.string.isRequired, disabled: PropTypes.bool, flat: PropTypes.bool, block: PropTypes.bool, onPress: PropTypes.func }; render() { const { value, disabled, style, type, block, } = this.props; let target = {}; Object.assign( target, Scale.getStyle(TButton.name, `buttonBox_${type}`, defaultStyles), disabled ? Scale.getStyle(TButton.name, `buttonBox_${type}${disabled ? '_disabled' : ''}`, defaultStyles) : {}, style.buttonBox, Scale.getStyle(TButton.name, `buttonText_${type}`, defaultStyles), disabled ? Scale.getStyle(TButton.name, `buttonText_${type}${disabled ? '_disabled' : ''}`, defaultStyles) : {}, style.buttonText, block ? {flex:1, display:'block',} : {}, ); let context = <button onClick={disabled ? null: this.props.onPress} style={target}>{value}</button>; if (block) { context = ( <div style={{display:'flex'}}> {context} </div> ) } return ( <div>{context}</div> ) } } module.exports = TButton;
JavaScript
CL
e7cd907db9bf95ca1f2d8b27bd2cd1900f0a9a617244ad751a19a85f3755192a
/** * Imports */ import BaseStore from 'fluxible/addons/BaseStore'; import contentActions from '../../constants/contents'; /** * Store */ class ContentsListStore extends BaseStore { static storeName = 'ContentsListStore'; static handlers = { [contentActions.CONTENTS_FIND]: 'handleListRequest', [contentActions.CONTENTS_FIND_SUCCESS]: 'handleListSuccess', [contentActions.CONTENTS_FIND_ERROR]: 'handleListError' }; constructor(dispatcher) { super(dispatcher); this.loading = false; this.error = undefined; this.contents = undefined; } getState() { return { loading: this.loading, error: this.error, contents: this.contents } } // // Isomorphic stuff // dehydrate() { return this.getState(); } rehydrate(state) { this.loading = state.loading; this.error = state.error; this.contents = state.contents; } // // Getters // isLoading() { return this.loading === true; } getError() { return this.error; } getContents() { if (this.contents && this.contents.items) { return this.contents.items; } else { return []; } } /** * Returns the contents that contain all of the given tags * @param {array} tags * @param {boolean} enabled - Return only the ones that are enabled */ getContentsWithTags(tags, enabled) { tags = tags || []; if (this.contents && this.contents.items) { return this.contents.items.filter(function (item) { let containsAllTags = tags.every(function(val) { return item.tags.indexOf(val) >= 0; }); return (enabled === true) ? item.enabled && containsAllTags : containsAllTags; }); } else { return []; } } /** * Returns the contents ordered by the "order" metadata value */ getOrderedContents(tags, enabled) { let contents = (tags) ? this.getContentsWithTags(tags, enabled) : this.getContents(); contents.sort(function (a, b) { if (a.metadata.order < b.metadata.order) return -1; else if (a.metadata.order > b.metadata.order || !a.metadata.order) return 1; else return 0; }); return contents; } /** * Returns the contents of given type ordered by the "order" metadata value * @param type - content type * @param tags - (optional) array of tags that content must have * @param enabled - (optional) boolean stating that contents should either be enabled or disabled. If not provided, both are considered. */ getOrderedContentsOfType(type, tags, enabled) { return this.getOrderedContents(tags, enabled).filter(c => c.type === type); } // // Handlers // handleListRequest() { this.loading = true; this.emitChange(); } handleListSuccess(payload) { this.loading = false; this.error = null; this.contents = payload; this.emitChange(); } handleListError(payload) { this.loading = false; this.error = payload; this.emitChange(); } } /** * Export */ export default ContentsListStore;
JavaScript
CL
24e9f78b553573ecb6d212d1d42fcb9e1b2a35e2d2ef19faae3d19cd15347ed5
webpackJsonp([0],{ /***/ 886: /***/ (function(module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; Object.defineProperty(exports, "__esModule", { value: true }); const core_1 = __webpack_require__(0); const ionic_angular_1 = __webpack_require__(5); const info_user_1 = __webpack_require__(887); let InfoUserPageModule = class InfoUserPageModule { }; InfoUserPageModule = __decorate([ core_1.NgModule({ declarations: [ info_user_1.InfoUserPage, ], imports: [ ionic_angular_1.IonicPageModule.forChild(info_user_1.InfoUserPage), ], }) ], InfoUserPageModule); exports.InfoUserPageModule = InfoUserPageModule; //# sourceMappingURL=info-user.module.js.map /***/ }), /***/ 887: /***/ (function(module, exports, __webpack_require__) { "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); const core_1 = __webpack_require__(0); const ionic_angular_1 = __webpack_require__(5); let InfoUserPage = class InfoUserPage { constructor(navCtrl, navParams) { this.navCtrl = navCtrl; this.navParams = navParams; } ionViewDidLoad() { console.log('ionViewDidLoad InfoUserPage'); } }; InfoUserPage = __decorate([ core_1.Component({ selector: 'page-info-user',template:/*ion-inline-start:"/Users/mmage/projects/eeappOK/src/pages/info-user/info-user.html"*/'<!--\n Generated template for the InfoUserPage page.\n\n See http://ionicframework.com/docs/components/#navigation for more info on\n Ionic pages and navigation.\n-->\n<ion-header>\n\n <ion-navbar>\n <ion-title>InfoUser</ion-title>\n </ion-navbar>\n\n</ion-header>\n\n\n<ion-content padding>\n\n</ion-content>\n'/*ion-inline-end:"/Users/mmage/projects/eeappOK/src/pages/info-user/info-user.html"*/, }), __metadata("design:paramtypes", [ionic_angular_1.NavController, ionic_angular_1.NavParams]) ], InfoUserPage); exports.InfoUserPage = InfoUserPage; //# sourceMappingURL=info-user.js.map /***/ }) }); //# sourceMappingURL=0.js.map
JavaScript
CL
6f6191f78197dba3cc9d6632dcbbb50affb3a37fd15ffc233d7586a5f247c3e1
import { useCallback, useState } from "react" /* * It's a good practice to by default memoize any API exposed by the hook * so that clients can apply any optimizations to their code when needed, so * make sure you: wrap functions within `useCallback` and expensive computations * within `useMemo` as appropriated. */ export function useBoard(initialState) { const [board, setBoard] = useState(initialState) const reset = useCallback(() => setBoard(initialState), [initialState]) const take = useCallback( (row, col, takenBy) => { board[row][col] = takenBy setBoard([...board]) }, [board], ) return { board, take, reset, } }
JavaScript
CL
a268318e8a7be824e3029ed366e5e82b1890877ff44f43b93eddb9717e5c3a8f
import rio from '@shoutem/redux-io'; import { getExtensionSettings } from 'shoutem.application'; import { shoutemApi } from './services'; import { STATUSES_SCHEMA, USERS_SCHEMA, } from './const'; const APPLICATION_EXTENSION = 'shoutem.application'; export const apiVersion = '59'; export function appDidMount(app) { const store = app.getStore(); const state = store.getState(); const apiEndpoint = getExtensionSettings(state, APPLICATION_EXTENSION).legacyApiEndpoint; shoutemApi.init(apiEndpoint); const apiRequestOptions = { resourceType: 'JSON', headers: { 'Content-Type': 'application/json', }, }; rio.registerResource({ schema: STATUSES_SCHEMA, request: { endpoint: '', ...apiRequestOptions, }, }); rio.registerResource({ schema: USERS_SCHEMA, request: { endpoint: '', ...apiRequestOptions, }, }); }
JavaScript
CL
8ba30fc940e62fc04b4e6a1b8d72b87e4b471d959ba0ccb016c1d345782f1a2b
const { CONSTANTS, log, isEmpty } = require('./utils'); let { data } = require('./data'); const chalk = require('chalk'); const { BOOLEAN, NUMBER, ARRAY } = CONSTANTS.TYPES; const { User, Organisation, Ticket } = data.getEntities(); class Display { constructor() { this.tabWidth = 15; } /** * Print key and value in tabular fashion * * @param {string} key Key to print * @param {string} val Value for the key */ log(results) { try { if (results.length == 0) { log.message('No results found'); } else { log.success(`Found ${results.length} result${results.length > 1? 's': ''}`); } console.log(); for (let i in results) { let res = results[i]; log.simple(chalk.bgMagenta(`--- ${Number(i) + 1} ---`)); res.log(); } } catch (error) { log.error('Error occured while printing the details', error); } } } let display = new Display(); /** * The class defines the properties we can create search criteria on. * * @param {string} entityChoice The the choice of entity selected * @returns the class of the Entity we are searching for. */ let getEntity = function(entityChoice) { let { USERS, TICKETS, ORGANISATIONS } = CONSTANTS.ENTITIES, Entity; try { let { Organisation, User, Ticket } = data.getEntities(); switch (entityChoice) { case USERS: { Entity = User; break; } case TICKETS: { Entity = Ticket; break; } case ORGANISATIONS: { Entity = Organisation; break; } default: throw TypeError(`Type ${entityChoice} does not exist`); } } catch (error) { log.error('Error while fetching option fields', error); } return Entity; }; /** * @param {any} choiceType type of the field searching for * @returns the inquirer prompt type for corresponding data type of field. */ let getInputType = function (choiceType) { let options = { type: 'input' }; switch (choiceType) { case NUMBER: { options.type = 'number'; break; } case BOOLEAN: { options.type = 'confirm'; options.default = true; break; } } return options; }; // Linear secondary search /** * Loop through all the entities present and return the array of entities found. * * @param {string} entity The type of entity to search. Should match with Constants defined * @param {string} field The name of the property user is searching for * @param {any} value Value of the the field. Should be String, Number, Boolean or null * * @returns The list of entities matching the criteria */ let simpleSearch = function (entity, field, value) { let results = [], entities, Entity; const { USERS, TICKETS, ORGANISATIONS } = CONSTANTS.ENTITIES; switch (entity) { case USERS: entities = data.getUsers(true); Entity = User; break; case TICKETS: entities = data.getTickets(true); Entity = Ticket; break; case ORGANISATIONS: entities = data.getOrganisations(true); Entity = Organisation; break; } try { results = entities.filter((entry) => { let type = Entity.getFieldType(field); // Match null criteria if (value == null && (isEmpty(entry[field]))) { return true; } if (entry.hasOwnProperty(field)) { if (type == ARRAY && entry[field].indexOf(value) > 0) { return true; } else if (entry[field] == value) { return true; } } return false; }); } catch (error) { log.error('Error while performing simple search for ' + `${field} with value ${value} under ${entity}`, error); } return results; }; // Advanced key based search (primary search - use map from data.js) /** * This function will search inside indexes created and if the index is not present for field then * it will return false. * * @param {string} entity The type of entity to search. Should match with Constants defined * @param {string} field The name of the property user is searching for * @param {any} value Value of the the field. Should be String, Number, Boolean or null * * @returns The list of entities matching the criteria if index exists or returns false */ let testAdvancedSearch = function (entity, field, value) { const { USERS, TICKETS, ORGANISATIONS } = CONSTANTS.ENTITIES; // Don't abstract this swtich case at data layer as this is a logical requirement let optimisedEntities; try { switch (entity) { case USERS: [, optimisedEntities] = data.getUsers(); break; case TICKETS: [, optimisedEntities] = data.getTickets(); break; case ORGANISATIONS: [, optimisedEntities] = data.getOrganisations(); break; default: throw TypeError(`Cannot find Entity of type ${entity}`); } } catch (error) { log.error('Unexpected Error Occured while searching. Falling back to basic search technique . . .', error); // Not a big issue, we can still search using basic search return false; } if (optimisedEntities.hasOwnProperty(field)) { let val = optimisedEntities[field][value]; return val == undefined ? [] : val; } return false; }; // Prepare search /** * Search for entities that are persent in our given dataset. Matches using * type of entity searching for, field name and value name. * * It will try to look into the indexes and if the index is absent, then it will * search inside the entire dataset. * * @param {string} entity The type of entity to search. Should match with Constants defined * @param {string} field The name of the property user is searching for * @param {any} value Value of the the field. Should be String, Number, Boolean or null * * @returns The list of entities matching the criteria */ let search = function (entity, field, value) { // Find out if we can search the field on an entity using advanced mode let searchResult = testAdvancedSearch(entity, field, value); let result = []; // Do advanced search if possible if (searchResult) { result = searchResult; } // Fall back to basic search if need be else { log.message('Fetching search results . . .'); result = simpleSearch(entity, field, value); } // Get associated data // Return the resulting array return result; }; module.exports = { getInputType, search, display, getEntity, };
JavaScript
CL
c91e6eb5d96cb91814aa5f1af665ef1e931c47019bf742695e7718e17849e516
import React from 'react'; import * as ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import './asset/css/styles.css'; import 'filepond/dist/filepond.min.css'; import 'filepond-plugin-image-preview/dist/filepond-plugin-image-preview.css'; import 'dplayer/dist/DPlayer.min.css'; // file pond import { registerPlugin } from 'filepond'; import FilePondPluginImagePreview from 'filepond-plugin-image-preview'; import FilePondPluginFileRename from 'filepond-plugin-file-rename'; import FilePondPluginFileValidateType from 'filepond-plugin-file-validate-type'; import registerServiceWorker from './registerServiceWorker'; import RootRouter from './urls'; import store from './redux/store/configStore'; import JssRegistry from './JssRegistry'; registerPlugin( FilePondPluginImagePreview, FilePondPluginFileRename, FilePondPluginFileValidateType, ); ReactDOM.render( <JssRegistry> <Provider store={store}> <RootRouter /> </Provider> </JssRegistry>, document.getElementById('root'), ); registerServiceWorker();
JavaScript
CL
ee72c1dbb71db24bd9c7b28cefbdb52e66d56b504aca041dd2c00f4e76da6bfb
webpackJsonp(["main"],{ /***/ "./src/$$_lazy_route_resource lazy recursive": /***/ (function(module, exports) { function webpackEmptyAsyncContext(req) { // Here Promise.resolve().then() is used instead of new Promise() to prevent // uncatched exception popping up in devtools return Promise.resolve().then(function() { throw new Error("Cannot find module '" + req + "'."); }); } webpackEmptyAsyncContext.keys = function() { return []; }; webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext; module.exports = webpackEmptyAsyncContext; webpackEmptyAsyncContext.id = "./src/$$_lazy_route_resource lazy recursive"; /***/ }), /***/ "./src/app/app.component.css": /***/ (function(module, exports) { module.exports = "" /***/ }), /***/ "./src/app/app.component.html": /***/ (function(module, exports) { module.exports = "<app-header></app-header>\n<router-outlet></router-outlet>\n" /***/ }), /***/ "./src/app/app.component.ts": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AppComponent; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__("./node_modules/@angular/core/esm5/core.js"); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var AppComponent = /** @class */ (function () { function AppComponent() { this.title = 'app'; } AppComponent = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["Component"])({ selector: 'app-root', template: __webpack_require__("./src/app/app.component.html"), styles: [__webpack_require__("./src/app/app.component.css")] }) ], AppComponent); return AppComponent; }()); /***/ }), /***/ "./src/app/app.module.ts": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AppModule; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_platform_browser__ = __webpack_require__("./node_modules/@angular/platform-browser/esm5/platform-browser.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_core__ = __webpack_require__("./node_modules/@angular/core/esm5/core.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_forms__ = __webpack_require__("./node_modules/@angular/forms/esm5/forms.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__angular_common_http__ = __webpack_require__("./node_modules/@angular/common/esm5/http.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__angular_material_dialog__ = __webpack_require__("./node_modules/@angular/material/esm5/dialog.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__angular_material_progress_bar__ = __webpack_require__("./node_modules/@angular/material/esm5/progress-bar.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6_primeng_message__ = __webpack_require__("./node_modules/primeng/message.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6_primeng_message___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_6_primeng_message__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__app_component__ = __webpack_require__("./src/app/app.component.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__book_book_component__ = __webpack_require__("./src/app/book/book.component.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__angular_router__ = __webpack_require__("./node_modules/@angular/router/esm5/router.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__book_detail_book_detail_component__ = __webpack_require__("./src/app/book-detail/book-detail.component.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__book_create_book_create_component__ = __webpack_require__("./src/app/book-create/book-create.component.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__book_edit_book_edit_component__ = __webpack_require__("./src/app/book-edit/book-edit.component.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__header_header_component__ = __webpack_require__("./src/app/header/header.component.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__angular_platform_browser_animations__ = __webpack_require__("./node_modules/@angular/platform-browser/esm5/animations.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__angular_material__ = __webpack_require__("./node_modules/@angular/material/esm5/material.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__angular_material_sidenav__ = __webpack_require__("./node_modules/@angular/material/esm5/sidenav.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__angular_material_toolbar__ = __webpack_require__("./node_modules/@angular/material/esm5/toolbar.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__angular_material_card__ = __webpack_require__("./node_modules/@angular/material/esm5/card.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__angular_material_grid_list__ = __webpack_require__("./node_modules/@angular/material/esm5/grid-list.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__angular_material_tabs__ = __webpack_require__("./node_modules/@angular/material/esm5/tabs.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__angular_material_chips__ = __webpack_require__("./node_modules/@angular/material/esm5/chips.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_22__angular_material_radio__ = __webpack_require__("./node_modules/@angular/material/esm5/radio.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_23__angular_material_input__ = __webpack_require__("./node_modules/@angular/material/esm5/input.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_24__angular_material_icon__ = __webpack_require__("./node_modules/@angular/material/esm5/icon.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_25__angular_material_divider__ = __webpack_require__("./node_modules/@angular/material/esm5/divider.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_26__angular_material_list__ = __webpack_require__("./node_modules/@angular/material/esm5/list.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_27_primeng_table__ = __webpack_require__("./node_modules/primeng/table.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_27_primeng_table___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_27_primeng_table__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_28__angular_material_menu__ = __webpack_require__("./node_modules/@angular/material/esm5/menu.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_29__angular_material_snack_bar__ = __webpack_require__("./node_modules/@angular/material/esm5/snack-bar.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_30__angular_material_progress_spinner__ = __webpack_require__("./node_modules/@angular/material/esm5/progress-spinner.es5.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_31_primeng_growl__ = __webpack_require__("./node_modules/primeng/growl.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_31_primeng_growl___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_31_primeng_growl__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_32_primeng_inputtext__ = __webpack_require__("./node_modules/primeng/inputtext.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_32_primeng_inputtext___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_32_primeng_inputtext__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_33_primeng_button__ = __webpack_require__("./node_modules/primeng/button.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_33_primeng_button___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_33_primeng_button__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_34_primeng_radiobutton__ = __webpack_require__("./node_modules/primeng/radiobutton.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_34_primeng_radiobutton___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_34_primeng_radiobutton__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_35_primeng_checkbox__ = __webpack_require__("./node_modules/primeng/checkbox.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_35_primeng_checkbox___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_35_primeng_checkbox__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_36_primeng_dropdown__ = __webpack_require__("./node_modules/primeng/dropdown.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_36_primeng_dropdown___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_36_primeng_dropdown__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_37_primeng_calendar__ = __webpack_require__("./node_modules/primeng/calendar.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_37_primeng_calendar___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_37_primeng_calendar__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_38_primeng_inputtextarea__ = __webpack_require__("./node_modules/primeng/inputtextarea.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_38_primeng_inputtextarea___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_38_primeng_inputtextarea__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_39_primeng_spinner__ = __webpack_require__("./node_modules/primeng/spinner.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_39_primeng_spinner___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_39_primeng_spinner__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_40_primeng_chart__ = __webpack_require__("./node_modules/primeng/chart.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_40_primeng_chart___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_40_primeng_chart__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_41__chart_chart_component__ = __webpack_require__("./src/app/chart/chart.component.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_42__shared_common_service__ = __webpack_require__("./src/app/shared/common.service.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_43_primeng_dialog__ = __webpack_require__("./node_modules/primeng/dialog.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_43_primeng_dialog___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_43_primeng_dialog__); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var appRoutes = [ { path: 'books', component: __WEBPACK_IMPORTED_MODULE_8__book_book_component__["a" /* BookComponent */], data: { title: 'Book List' } }, { path: 'books/charts', component: __WEBPACK_IMPORTED_MODULE_41__chart_chart_component__["a" /* ChartComponent */], data: { title: 'Charts' } }, { path: 'book-details/:id', component: __WEBPACK_IMPORTED_MODULE_10__book_detail_book_detail_component__["a" /* BookDetailComponent */], data: { title: 'Book Details' } }, { path: 'book-create', component: __WEBPACK_IMPORTED_MODULE_11__book_create_book_create_component__["a" /* BookCreateComponent */], data: { title: 'Create Book' } }, { path: 'book-edit/:id', component: __WEBPACK_IMPORTED_MODULE_12__book_edit_book_edit_component__["a" /* BookEditComponent */], data: { title: 'Edit Book' } }, { path: '', redirectTo: '/books', pathMatch: 'full' } ]; var AppModule = /** @class */ (function () { function AppModule() { } AppModule = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_1__angular_core__["NgModule"])({ declarations: [ __WEBPACK_IMPORTED_MODULE_7__app_component__["a" /* AppComponent */], __WEBPACK_IMPORTED_MODULE_8__book_book_component__["a" /* BookComponent */], __WEBPACK_IMPORTED_MODULE_10__book_detail_book_detail_component__["a" /* BookDetailComponent */], __WEBPACK_IMPORTED_MODULE_11__book_create_book_create_component__["a" /* BookCreateComponent */], __WEBPACK_IMPORTED_MODULE_12__book_edit_book_edit_component__["a" /* BookEditComponent */], __WEBPACK_IMPORTED_MODULE_13__header_header_component__["a" /* HeaderComponent */], __WEBPACK_IMPORTED_MODULE_41__chart_chart_component__["a" /* ChartComponent */] ], imports: [ __WEBPACK_IMPORTED_MODULE_0__angular_platform_browser__["a" /* BrowserModule */], __WEBPACK_IMPORTED_MODULE_3__angular_common_http__["b" /* HttpClientModule */], __WEBPACK_IMPORTED_MODULE_2__angular_forms__["FormsModule"], __WEBPACK_IMPORTED_MODULE_14__angular_platform_browser_animations__["a" /* BrowserAnimationsModule */], __WEBPACK_IMPORTED_MODULE_15__angular_material__["a" /* MatButtonModule */], __WEBPACK_IMPORTED_MODULE_15__angular_material__["b" /* MatCheckboxModule */], __WEBPACK_IMPORTED_MODULE_16__angular_material_sidenav__["a" /* MatSidenavModule */], __WEBPACK_IMPORTED_MODULE_17__angular_material_toolbar__["a" /* MatToolbarModule */], __WEBPACK_IMPORTED_MODULE_18__angular_material_card__["a" /* MatCardModule */], __WEBPACK_IMPORTED_MODULE_20__angular_material_tabs__["a" /* MatTabsModule */], __WEBPACK_IMPORTED_MODULE_21__angular_material_chips__["a" /* MatChipsModule */], __WEBPACK_IMPORTED_MODULE_19__angular_material_grid_list__["a" /* MatGridListModule */], __WEBPACK_IMPORTED_MODULE_22__angular_material_radio__["a" /* MatRadioModule */], __WEBPACK_IMPORTED_MODULE_15__angular_material__["c" /* MatFormFieldModule */], __WEBPACK_IMPORTED_MODULE_15__angular_material__["d" /* MatSelectModule */], __WEBPACK_IMPORTED_MODULE_23__angular_material_input__["b" /* MatInputModule */], __WEBPACK_IMPORTED_MODULE_24__angular_material_icon__["a" /* MatIconModule */], __WEBPACK_IMPORTED_MODULE_32_primeng_inputtext__["InputTextModule"], __WEBPACK_IMPORTED_MODULE_33_primeng_button__["ButtonModule"], __WEBPACK_IMPORTED_MODULE_34_primeng_radiobutton__["RadioButtonModule"], __WEBPACK_IMPORTED_MODULE_27_primeng_table__["TableModule"], __WEBPACK_IMPORTED_MODULE_35_primeng_checkbox__["CheckboxModule"], __WEBPACK_IMPORTED_MODULE_36_primeng_dropdown__["DropdownModule"], __WEBPACK_IMPORTED_MODULE_37_primeng_calendar__["CalendarModule"], __WEBPACK_IMPORTED_MODULE_38_primeng_inputtextarea__["InputTextareaModule"], __WEBPACK_IMPORTED_MODULE_39_primeng_spinner__["SpinnerModule"], __WEBPACK_IMPORTED_MODULE_28__angular_material_menu__["a" /* MatMenuModule */], __WEBPACK_IMPORTED_MODULE_4__angular_material_dialog__["b" /* MatDialogModule */], __WEBPACK_IMPORTED_MODULE_29__angular_material_snack_bar__["b" /* MatSnackBarModule */], __WEBPACK_IMPORTED_MODULE_26__angular_material_list__["a" /* MatListModule */], __WEBPACK_IMPORTED_MODULE_25__angular_material_divider__["a" /* MatDividerModule */], __WEBPACK_IMPORTED_MODULE_40_primeng_chart__["ChartModule"], __WEBPACK_IMPORTED_MODULE_6_primeng_message__["MessageModule"], __WEBPACK_IMPORTED_MODULE_5__angular_material_progress_bar__["a" /* MatProgressBarModule */], __WEBPACK_IMPORTED_MODULE_31_primeng_growl__["GrowlModule"], __WEBPACK_IMPORTED_MODULE_30__angular_material_progress_spinner__["a" /* MatProgressSpinnerModule */], __WEBPACK_IMPORTED_MODULE_43_primeng_dialog__["DialogModule"], __WEBPACK_IMPORTED_MODULE_9__angular_router__["c" /* RouterModule */].forRoot(appRoutes, { enableTracing: true } // <-- debugging purposes only ) ], providers: [__WEBPACK_IMPORTED_MODULE_42__shared_common_service__["a" /* CommonService */]], bootstrap: [__WEBPACK_IMPORTED_MODULE_7__app_component__["a" /* AppComponent */]] }) ], AppModule); return AppModule; }()); /***/ }), /***/ "./src/app/book-create/book-create.component.css": /***/ (function(module, exports) { module.exports = "" /***/ }), /***/ "./src/app/book-create/book-create.component.html": /***/ (function(module, exports) { module.exports = "<div class=\"ui-g-12\">\r\n<mat-drawer-container class=\"example-container\" style=\"background-color:#3f51b5;\">\r\n <mat-drawer mode=\"side\" opened=\"true\" style=\"background-color:#3f51b5;\">\r\n <div class=\"ui-g\">\r\n <mat-list>\r\n <mat-list-item style=\"cursor:pointer;color:white;\" routerLinkActive=\"active\" [routerLinkActiveOptions]=\"{exact: true}\" routerLink=\"/book-create\">Add Books</mat-list-item>\r\n <mat-divider></mat-divider>\r\n <mat-list-item style=\"cursor:pointer;color:white;\" routerLinkActive=\"active\" [routerLinkActiveOptions]=\"{exact: true}\" routerLink=\"/books/charts\">Analysis</mat-list-item>\r\n <mat-divider></mat-divider>\r\n </mat-list>\r\n </div>\r\n </mat-drawer>\r\n <mat-drawer-content>\r\n <div class=\"ui-g-12\">\r\n <mat-card style=\"margin: 10px 200px 10px 100px;border: 0.1px solid;height: 1000px;\">\r\n <h4 style=\"font-size:20px;margin: 20px 100px 20px 300px;\">ADD NEW BOOK</h4>\r\n <form (ngSubmit)=\"saveBook(bookForm)\" #bookForm=\"ngForm\" style=\"margin: 40px 100px 20px 300px;\">\r\n <span class=\"ui-float-label\">\r\n <input id=\"float-input\" type=\"text\" pInputText [(ngModel)]=\"book.isbn\" name=\"isbn\" required #isbn=\"ngModel\">\r\n <label for=\"float-input\">ISBN</label>\r\n <span *ngIf=\"!isbn.valid && isbn.touched\">\r\n <p-message severity=\"error\" text=\"Field is required\"></p-message>\r\n </span>\r\n </span>\r\n <br>\r\n <span class=\"ui-float-label\">\r\n <input id=\"float-input\" type=\"text\" pInputText [(ngModel)]=\"book.title\" name=\"title\" required #title=\"ngModel\">\r\n <label for=\"float-input\">Title</label>\r\n <span *ngIf=\"!title.valid && title.touched\">\r\n <p-message severity=\"error\" text=\"Field is required\"></p-message>\r\n </span>\r\n </span>\r\n <br>\r\n <span class=\"ui-float-label\">\r\n <input id=\"float-input\" type=\"text\" pInputText [(ngModel)]=\"book.author\" name=\"author\" required #author=\"ngModel\">\r\n <label for=\"float-input\">Author</label>\r\n <span *ngIf=\"!author.valid && author.touched\">\r\n <p-message severity=\"error\" text=\"Field is required\"></p-message>\r\n </span>\r\n </span>\r\n <br>\r\n <span class=\"ui-float-label\">\r\n <input id=\"float-input\" type=\"text\" pInputText [(ngModel)]=\"book.description\" name=\"description\" required #description=\"ngModel\">\r\n <label for=\"float-input\">Description</label>\r\n <span *ngIf=\"!description.valid && description.touched\">\r\n <p-message severity=\"error\" text=\"Field is required\"></p-message>\r\n </span>\r\n </span>\r\n\r\n <br>\r\n <span class=\"ui-float-label\">\r\n <input id=\"float-input\" type=\"text\" pInputText [(ngModel)]=\"book.publisher\" name=\"publisher\" required #publisher=\"ngModel\">\r\n <label for=\"float-input\">Publisher</label>\r\n <span *ngIf=\"!publisher.valid && publisher.touched\">\r\n <p-message severity=\"error\" text=\"Field is required\"></p-message>\r\n </span>\r\n </span>\r\n <br>\r\n <h5>Published Date:</h5>\r\n <p-calendar [(ngModel)]=\"book.published_date\" name=\"book.published_date\"></p-calendar>\r\n <br>\r\n <div class=\"ui-g\" style=\"display:block;\">\r\n <h5>Availability:</h5>\r\n <div class=\"ui-g-12\"><p-radioButton name=\"group1\" value=\"Yes\" label=\"Yes\" [(ngModel)]=\"book.available\" inputId=\"opt1\"></p-radioButton></div>\r\n <div class=\"ui-g-12\"><p-radioButton name=\"group1\" value=\"No\" label=\"No\" [(ngModel)]=\"book.available\" inputId=\"opt2\"></p-radioButton></div>\r\n </div>\r\n <h5>Genre:</h5>\r\n <div class=\"ui-g\" style=\"width:250px;margin-bottom:10px\">\r\n <div class=\"ui-g-12\"><p-radioButton name=\"group2\" value=\"Fiction\" label=\"Fiction\" [(ngModel)]=\"book.genre\" inputId=\"Fiction\"></p-radioButton></div>\r\n <div class=\"ui-g-12\"><p-radioButton name=\"group2\" value=\"Science and Technology\" label=\"Science and Technology\" [(ngModel)]=\"book.genre\" inputId=\"Science and Technology\"></p-radioButton></div>\r\n <div class=\"ui-g-12\"><p-radioButton name=\"group2\" value=\"Comic\" label=\"Comic\" [(ngModel)]=\"book.genre\" inputId=\"Comic\"></p-radioButton></div>\r\n <div class=\"ui-g-12\"><p-radioButton name=\"group2\" value=\"Engineering\" label=\"Engineering\" [(ngModel)]=\"book.genre\" inputId=\"Engineering\"></p-radioButton></div>\r\n </div>\r\n <button mat-button type=\"submit\" style=\"border: 1px solid;\" [disabled]=\"!bookForm.form.valid\" color=\"primary\">ADD BOOK</button>\r\n </form>\r\n </mat-card>\r\n </div>\r\n </mat-drawer-content>\r\n </mat-drawer-container>\r\n</div>\r\n" /***/ }), /***/ "./src/app/book-create/book-create.component.ts": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BookCreateComponent; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__("./node_modules/@angular/core/esm5/core.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_router__ = __webpack_require__("./node_modules/@angular/router/esm5/router.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__shared_common_service__ = __webpack_require__("./src/app/shared/common.service.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__angular_material__ = __webpack_require__("./node_modules/@angular/material/esm5/material.es5.js"); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var BookCreateComponent = /** @class */ (function () { function BookCreateComponent(router, commonService, route, snackBar) { this.router = router; this.commonService = commonService; this.route = route; this.snackBar = snackBar; this.book = {}; } BookCreateComponent.prototype.ngOnInit = function () { }; BookCreateComponent.prototype.saveBook = function (form) { var _this = this; console.log("Inside the on save"); console.log("seeeeeeeeeeeeeeeeeee"); console.log(form); this.commonService.storeRecipes(this.book) .subscribe(function (response) { console.log("res is"); console.log(response); var id = response['_id']; console.log("id is" + id); _this.router.navigate(['/book-details', id], { relativeTo: _this.route }); _this.snackBar.open("Book has been created", "OK", { duration: 20000, }); }, function (err) { console.log(err); }); }; BookCreateComponent = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["Component"])({ selector: 'app-book-create', template: __webpack_require__("./src/app/book-create/book-create.component.html"), styles: [__webpack_require__("./src/app/book-create/book-create.component.css")], encapsulation: __WEBPACK_IMPORTED_MODULE_0__angular_core__["ViewEncapsulation"].None }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1__angular_router__["b" /* Router */], __WEBPACK_IMPORTED_MODULE_2__shared_common_service__["a" /* CommonService */], __WEBPACK_IMPORTED_MODULE_1__angular_router__["a" /* ActivatedRoute */], __WEBPACK_IMPORTED_MODULE_3__angular_material__["e" /* MatSnackBar */]]) ], BookCreateComponent); return BookCreateComponent; }()); /***/ }), /***/ "./src/app/book-detail/book-detail.component.css": /***/ (function(module, exports) { module.exports = "" /***/ }), /***/ "./src/app/book-detail/book-detail.component.html": /***/ (function(module, exports) { module.exports = "<div class=\"ui-g-12\">\r\n<mat-drawer-container class=\"example-container\" style=\"background-color:#3f51b5;\">\r\n <mat-drawer mode=\"side\" opened=\"true\" style=\"background-color:#3f51b5;\">\r\n <div class=\"ui-g\">\r\n <mat-list>\r\n <mat-list-item style=\"cursor:pointer;color:white;\" routerLinkActive=\"active\" [routerLinkActiveOptions]=\"{exact: true}\" routerLink=\"/book-create\">Add Books</mat-list-item>\r\n <mat-divider></mat-divider>\r\n <mat-list-item style=\"cursor:pointer;color:white;\" routerLinkActive=\"active\" [routerLinkActiveOptions]=\"{exact: true}\" routerLink=\"/books/charts\">Analysis</mat-list-item>\r\n <mat-divider></mat-divider>\r\n </mat-list>\r\n </div>\r\n </mat-drawer>\r\n <mat-drawer-content>\r\n <mat-card style=\"margin: 10px 200px 10px 100px;border: 0.1px solid;height: 800px;\">\r\n <mat-card-content>\r\n <h2 class=\"example-h2\">{{ book.title }}</h2>\r\n <mat-tab-group class=\"demo-tab-group\">\r\n <mat-tab label=\"ISBN\">\r\n <div class=\"demo-tab-content\" style=\"height: 200px\">\r\n <br>\r\n <ul>\r\n <li>{{ book.isbn }}</li>\r\n </ul>\r\n </div>\r\n </mat-tab>\r\n <mat-tab label=\"Author\">\r\n <div class=\"demo-tab-content\" style=\"height: 200px\">\r\n <br>\r\n <ul>\r\n <li>{{ book.author }}</li>\r\n </ul>\r\n </div>\r\n </mat-tab>\r\n <mat-tab label=\"Description\">\r\n <div class=\"demo-tab-content\" style=\"height: 200px\">\r\n <br>\r\n <ul>\r\n <li>\r\n {{ book.description }}\r\n </li>\r\n </ul>\r\n </div>\r\n </mat-tab>\r\n <mat-tab label=\"Publisher\">\r\n <div class=\"demo-tab-content\" style=\"height: 200px\">\r\n <br>\r\n <ul>\r\n <li>\r\n {{ book.publisher }}\r\n </li>\r\n </ul>\r\n </div>\r\n </mat-tab>\r\n <mat-tab label=\"Published Date\">\r\n <div class=\"demo-tab-content\" style=\"height: 200px\">\r\n <br>\r\n <ul>\r\n <li>\r\n {{ book.published_date }}\r\n </li>\r\n </ul>\r\n </div>\r\n </mat-tab>\r\n <mat-tab label=\"Availability\">\r\n <div class=\"demo-tab-content\" style=\"height: 200px\">\r\n <br>\r\n <ul>\r\n <li>\r\n {{ book.available }}\r\n </li>\r\n </ul>\r\n </div>\r\n </mat-tab>\r\n <mat-tab label=\"Genre\">\r\n <div class=\"demo-tab-content\" style=\"height: 200px\">\r\n <br>\r\n <ul>\r\n <li>\r\n {{ book.genre }}\r\n </li>\r\n </ul>\r\n </div>\r\n </mat-tab>\r\n <mat-tab label=\"Types Available\">\r\n <div class=\"demo-tab-content\" style=\"height: 200px\">\r\n <br>\r\n <ul>\r\n <li>\r\n {{ book.type }}\r\n </li>\r\n </ul>\r\n </div>\r\n </mat-tab>\r\n </mat-tab-group>\r\n <mat-card-actions>\r\n <!-- <a [routerLink]=\"['/book-edit', book._id]\" class=\"btn btn-success\">EDIT</a> -->\r\n <button mat-button style=\"border: 1px solid;\" [routerLink]=\"['/book-edit', book._id]\" color=\"primary\">EDIT</button>\r\n <button mat-button style=\"border: 1px solid;\" (click)=\"deleteBook(book._id)\" color=\"accent\">DELETE</button>\r\n <!-- <button class=\"btn btn-danger\" type=\"button\" (click)=\"deleteBook(book._id)\">DELETE</button> -->\r\n </mat-card-actions>\r\n </mat-card-content>\r\n </mat-card>\r\n\r\n </mat-drawer-content>\r\n</mat-drawer-container>\r\n</div>\r\n" /***/ }), /***/ "./src/app/book-detail/book-detail.component.ts": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BookDetailComponent; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__("./node_modules/@angular/core/esm5/core.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_common_http__ = __webpack_require__("./node_modules/@angular/common/esm5/http.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_router__ = __webpack_require__("./node_modules/@angular/router/esm5/router.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__shared_common_service__ = __webpack_require__("./src/app/shared/common.service.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__angular_material__ = __webpack_require__("./node_modules/@angular/material/esm5/material.es5.js"); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var BookDetailComponent = /** @class */ (function () { function BookDetailComponent(router, route, http, commonService, snackBar) { this.router = router; this.route = route; this.http = http; this.commonService = commonService; this.snackBar = snackBar; this.book = {}; } BookDetailComponent.prototype.ngOnInit = function () { this.getBookDetail(this.route.snapshot.params['id']); }; BookDetailComponent.prototype.getBookDetail = function (id) { var _this = this; this.commonService.getOneBook(id) .subscribe(function (data) { _this.book = data; }); }; BookDetailComponent.prototype.deleteBook = function (id) { var _this = this; this.commonService.deleteOneBook(id) .subscribe(function (res) { _this.router.navigate(['/books'], { relativeTo: _this.route }); _this.snackBar.open("Book has been deleted", "OK", { duration: 20000, }); }, function (err) { console.log(err); }); }; BookDetailComponent = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["Component"])({ selector: 'app-book-detail', template: __webpack_require__("./src/app/book-detail/book-detail.component.html"), styles: [__webpack_require__("./src/app/book-detail/book-detail.component.css")], encapsulation: __WEBPACK_IMPORTED_MODULE_0__angular_core__["ViewEncapsulation"].None }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_2__angular_router__["b" /* Router */], __WEBPACK_IMPORTED_MODULE_2__angular_router__["a" /* ActivatedRoute */], __WEBPACK_IMPORTED_MODULE_1__angular_common_http__["a" /* HttpClient */], __WEBPACK_IMPORTED_MODULE_3__shared_common_service__["a" /* CommonService */], __WEBPACK_IMPORTED_MODULE_4__angular_material__["e" /* MatSnackBar */]]) ], BookDetailComponent); return BookDetailComponent; }()); /***/ }), /***/ "./src/app/book-edit/book-edit.component.css": /***/ (function(module, exports) { module.exports = "" /***/ }), /***/ "./src/app/book-edit/book-edit.component.html": /***/ (function(module, exports) { module.exports = "\r\n<div class=\"ui-g-12\">\r\n<mat-drawer-container class=\"example-container\" style=\"background-color:#3f51b5;\">\r\n <mat-drawer mode=\"side\" opened=\"true\" style=\"background-color:#3f51b5;\">\r\n <div class=\"ui-g\">\r\n <mat-list>\r\n <mat-list-item style=\"cursor:pointer;color:white;\" routerLinkActive=\"active\" [routerLinkActiveOptions]=\"{exact: true}\" routerLink=\"/book-create\">Add Books</mat-list-item>\r\n <mat-divider></mat-divider>\r\n <mat-list-item style=\"cursor:pointer;color:white;\" routerLinkActive=\"active\" [routerLinkActiveOptions]=\"{exact: true}\" routerLink=\"/books/charts\">Analysis</mat-list-item>\r\n <mat-divider></mat-divider>\r\n </mat-list>\r\n </div>\r\n </mat-drawer>\r\n <mat-drawer-content>\r\n <mat-card style=\"margin: 10px 200px 10px 100px;border: 0.1px solid;height: 800px;\">\r\n\r\n <h4 style=\"font-size:20px;margin: 20px 100px 20px 300px;\">EDIT BOOK</h4>\r\n <button type=\"button\" pButton (click)=\"clear(bookForm)\" icon=\"fa-close\" style=\"float:left\" label=\"Clear Form\" class=\"ui-button-danger\"></button>\r\n <form (ngSubmit)=\"updateBook(book._id,book)\" #bookForm=\"ngForm\" style=\"margin: 40px 100px 20px 200px;\">\r\n <span class=\"ui-float-label\">\r\n <input id=\"float-input\" type=\"text\" pInputText [(ngModel)]=\"book.isbn\" name=\"isbn\" required>\r\n <label for=\"float-input\">ISBN</label>\r\n </span>\r\n <br>\r\n <span class=\"ui-float-label\">\r\n <input id=\"float-input\" type=\"text\" pInputText [(ngModel)]=\"book.title\" name=\"title\" required>\r\n <label for=\"float-input\">Title</label>\r\n </span>\r\n <br>\r\n <span class=\"ui-float-label\">\r\n <input id=\"float-input\" type=\"text\" pInputText [(ngModel)]=\"book.author\" name=\"author\" required>\r\n <label for=\"float-input\">Author</label>\r\n </span>\r\n <br>\r\n <span class=\"ui-float-label\">\r\n <input id=\"float-input\" type=\"text\" pInputText [(ngModel)]=\"book.description\" name=\"description\" required>\r\n <label for=\"float-input\">Description</label>\r\n <!-- <textarea rows=\"5\" cols=\"30\" pInputTextarea autoResize=\"autoResize\"></textarea> -->\r\n </span>\r\n <br>\r\n <span class=\"ui-float-label\">\r\n <input id=\"float-input\" type=\"text\" pInputText [(ngModel)]=\"book.publisher\" name=\"publisher\" required>\r\n <label for=\"float-input\">Publisher</label>\r\n </span>\r\n <br>\r\n <!-- <div class=\"ui-g-12 ui-md-4\" style=\"display:block;\">\r\n <h5>Published Date</h5>\r\n <p-calendar [(ngModel)]=\"book.published_date\" name=\"book.published_date\"></p-calendar>\r\n </div> -->\r\n\r\n\r\n <h5>Availability:</h5>\r\n <div class=\"ui-g-12\"><p-radioButton name=\"group1\" value=\"Yes\" label=\"Yes\" [(ngModel)]=\"book.available\" inputId=\"opt1\"></p-radioButton></div>\r\n <div class=\"ui-g-12\"><p-radioButton name=\"group1\" value=\"No\" label=\"No\" [(ngModel)]=\"book.available\" inputId=\"opt2\"></p-radioButton></div>\r\n\r\n\r\n\r\n <h5>Genre:</h5>\r\n <div class=\"ui-g\" style=\"width:250px;margin-bottom:10px\">\r\n <div class=\"ui-g-12\"><p-checkbox name=\"group2\" value=\"Fiction\" label=\"Fiction\" [(ngModel)]=\"book.genre\" inputId=\"Fiction\"></p-checkbox></div>\r\n <div class=\"ui-g-12\"><p-checkbox name=\"group2\" value=\"Science and Technology\" label=\"Science and Technology\" [(ngModel)]=\"book.genre\" inputId=\"Science and Technology\"></p-checkbox></div>\r\n <div class=\"ui-g-12\"><p-checkbox name=\"group2\" value=\"Comic\" label=\"Comic\" [(ngModel)]=\"book.genre\" inputId=\"Comic\"></p-checkbox></div>\r\n <div class=\"ui-g-12\"><p-checkbox name=\"group2\" value=\"Engineering\" label=\"Engineering\" [(ngModel)]=\"book.genre\" inputId=\"Engineering\"></p-checkbox></div>\r\n </div>\r\n\r\n <button mat-button type=\"submit\" style=\"border: 1px solid;\" [disabled]=\"!bookForm.form.valid\" color=\"primary\">SAVE</button>\r\n </form>\r\n </mat-card>\r\n </mat-drawer-content>\r\n</mat-drawer-container>\r\n</div>\r\n" /***/ }), /***/ "./src/app/book-edit/book-edit.component.ts": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BookEditComponent; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__("./node_modules/@angular/core/esm5/core.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_router__ = __webpack_require__("./node_modules/@angular/router/esm5/router.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_common_http__ = __webpack_require__("./node_modules/@angular/common/esm5/http.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__shared_common_service__ = __webpack_require__("./src/app/shared/common.service.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__angular_material__ = __webpack_require__("./node_modules/@angular/material/esm5/material.es5.js"); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var BookEditComponent = /** @class */ (function () { function BookEditComponent(http, router, route, commonService, snackBar) { this.http = http; this.router = router; this.route = route; this.commonService = commonService; this.snackBar = snackBar; this.book = {}; } BookEditComponent.prototype.ngOnInit = function () { this.getBook(this.route.snapshot.params['id']); }; BookEditComponent.prototype.getBook = function (id) { var _this = this; this.commonService.getOneBook(id) .subscribe(function (data) { _this.book = data; }); }; BookEditComponent.prototype.updateBook = function (id, data) { var _this = this; this.commonService.updateExistingBook(id, data) .subscribe(function (response) { var id = response['_id']; _this.router.navigate(['/book-details', id], { relativeTo: _this.route }); _this.snackBar.open("Book has been edited", "OK", { duration: 20000, }); }, function (err) { console.log(err); }); }; BookEditComponent.prototype.clear = function (bf) { bf.reset(); }; BookEditComponent = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["Component"])({ selector: 'app-book-edit', template: __webpack_require__("./src/app/book-edit/book-edit.component.html"), styles: [__webpack_require__("./src/app/book-edit/book-edit.component.css")], encapsulation: __WEBPACK_IMPORTED_MODULE_0__angular_core__["ViewEncapsulation"].None }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_2__angular_common_http__["a" /* HttpClient */], __WEBPACK_IMPORTED_MODULE_1__angular_router__["b" /* Router */], __WEBPACK_IMPORTED_MODULE_1__angular_router__["a" /* ActivatedRoute */], __WEBPACK_IMPORTED_MODULE_3__shared_common_service__["a" /* CommonService */], __WEBPACK_IMPORTED_MODULE_4__angular_material__["e" /* MatSnackBar */]]) ], BookEditComponent); return BookEditComponent; }()); // openSnackBar() { // this.snackBar.open("Book with this ISBN already exists", "OK", { // duration: 2000, // }); // } /***/ }), /***/ "./src/app/book/book.component.css": /***/ (function(module, exports) { module.exports = "" /***/ }), /***/ "./src/app/book/book.component.html": /***/ (function(module, exports) { module.exports = "<div class=\"ui-g-12\">\r\n<mat-drawer-container class=\"example-container\" style=\"background-color:#3f51b5;\">\r\n <mat-drawer mode=\"side\" opened=\"true\" style=\"background-color:#3f51b5;\">\r\n <div class=\"ui-g\">\r\n <mat-list>\r\n <mat-list-item style=\"cursor:pointer;color:white;\" routerLinkActive=\"active\" [routerLinkActiveOptions]=\"{exact: true}\" routerLink=\"/book-create\">Add Books</mat-list-item>\r\n <mat-divider></mat-divider>\r\n <mat-list-item style=\"cursor:pointer;color:white;\" routerLinkActive=\"active\" [routerLinkActiveOptions]=\"{exact: true}\" routerLink=\"/books/charts\">Analysis</mat-list-item>\r\n <mat-divider></mat-divider>\r\n </mat-list>\r\n </div>\r\n </mat-drawer>\r\n <mat-drawer-content>\r\n <div class=\"ui-g-12\">\r\n <mat-card style=\"margin: 10px 200px 10px 100px;border: 0.1px solid;height: 800px;\">\r\n <p-table [value]=\"books\">\r\n <ng-template pTemplate=\"header\">\r\n <tr>\r\n <th>Title</th>\r\n <th>Author</th>\r\n <th>Action</th>\r\n </tr>\r\n </ng-template>\r\n <ng-template pTemplate=\"body\" let-book>\r\n <tr>\r\n <td>{{book.title}}</td>\r\n <td>{{book.author}}</td>\r\n <td>\r\n <mat-chip-list>\r\n <mat-chip style=\"color:#3f51b5;cursor:pointer;background-color: white;border: 1px solid rgb(63, 81, 181);\" selected=\"true\" [routerLink]=\"['/book-details',book._id]\">Show Detail</mat-chip>\r\n </mat-chip-list>\r\n </td>\r\n </tr>\r\n </ng-template>\r\n </p-table>\r\n </mat-card>\r\n </div>\r\n </mat-drawer-content>\r\n</mat-drawer-container>\r\n</div>\r\n" /***/ }), /***/ "./src/app/book/book.component.ts": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BookComponent; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__("./node_modules/@angular/core/esm5/core.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_common_http__ = __webpack_require__("./node_modules/@angular/common/esm5/http.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_router__ = __webpack_require__("./node_modules/@angular/router/esm5/router.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__shared_common_service__ = __webpack_require__("./src/app/shared/common.service.ts"); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var BookComponent = /** @class */ (function () { function BookComponent(http, router, commonService) { this.http = http; this.router = router; this.commonService = commonService; this.total = 0; } BookComponent.prototype.ngOnInit = function () { var _this = this; this.commonService.getBooks() .subscribe(function (data) { _this.books = data; }); }; BookComponent = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["Component"])({ selector: 'app-book', template: __webpack_require__("./src/app/book/book.component.html"), styles: [__webpack_require__("./src/app/book/book.component.css")] }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1__angular_common_http__["a" /* HttpClient */], __WEBPACK_IMPORTED_MODULE_2__angular_router__["b" /* Router */], __WEBPACK_IMPORTED_MODULE_3__shared_common_service__["a" /* CommonService */]]) ], BookComponent); return BookComponent; }()); /***/ }), /***/ "./src/app/chart/chart.component.css": /***/ (function(module, exports) { module.exports = "" /***/ }), /***/ "./src/app/chart/chart.component.html": /***/ (function(module, exports) { module.exports = "<div class=\"ui-g\">\r\n<mat-drawer-container class=\"example-container\" style=\"background-color:#3f51b5;\">\r\n <mat-drawer mode=\"side\" opened=\"true\" style=\"background-color:#3f51b5;\">\r\n <div class=\"ui-g\">\r\n <mat-list>\r\n <mat-list-item style=\"cursor:pointer;color:white;\" routerLinkActive=\"active\" [routerLinkActiveOptions]=\"{exact: true}\" routerLink=\"/book-create\">Add Books</mat-list-item>\r\n <mat-divider></mat-divider>\r\n <mat-list-item style=\"cursor:pointer;color:white;\" routerLinkActive=\"active\" [routerLinkActiveOptions]=\"{exact: true}\" routerLink=\"/books/charts\">Analysis</mat-list-item>\r\n <mat-divider></mat-divider>\r\n </mat-list>\r\n </div>\r\n </mat-drawer>\r\n <mat-drawer-content style=\"background-color: white;\">\r\n <mat-card style=\"margin: 10px 200px 10px 100px;border: 0.1px solid;\">\r\n <h2>BOOKS ANALYTICS</h2>\r\n <div class=\"ui-g\">\r\n <div class=\"ui-g-12\">\r\n <!-- <p-button label=\"Click\" (click)=\"getCharts()\"></p-button> -->\r\n <button mat-button style=\"border: 1px solid;\" color=\"primary\" (click)=\"getChartAsPerGenre('availability')\">AVAILABILITY STATISTICS</button>\r\n <button mat-button style=\"border: 1px solid;\" color=\"primary\" (click)=\"getChartAsPerGenre('genre')\">GENRE STATISTICS</button>\r\n <!-- <p-button label=\"Analyse As Per Genre\" (click)=\"getChartAsPerGenre()\"></p-button> -->\r\n </div>\r\n <div class=\"ui-g-12\">\r\n <p-chart type=\"pie\" [data]=\"data\" [options]=\"options\"></p-chart>\r\n </div>\r\n </div>\r\n </mat-card>\r\n </mat-drawer-content>\r\n</mat-drawer-container>\r\n</div>\r\n" /***/ }), /***/ "./src/app/chart/chart.component.ts": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ChartComponent; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__("./node_modules/@angular/core/esm5/core.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_common_http__ = __webpack_require__("./node_modules/@angular/common/esm5/http.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__shared_common_service__ = __webpack_require__("./src/app/shared/common.service.ts"); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var ChartComponent = /** @class */ (function () { function ChartComponent(http, commonService) { this.http = http; this.commonService = commonService; this.totalNo = 0; this.totalYes = 0; this.toggle = 1; } ChartComponent.prototype.ngOnInit = function () { }; ChartComponent.prototype.getChartAsPerGenre = function (value) { var _this = this; console.log("value is " + value); this.data = { labels: [], datasets: [ { data: [], backgroundColor: [ "#FF6384", "#36A2EB", "#41552B", "#72162F" ], hoverBackgroundColor: [ "#FF6384", "#36A2EB", "#41552B", "#72162F" ] } ] }; this.options = { title: { display: true, text: 'Chart', fontSize: 14 }, legend: { position: 'bottom' } }; if (value == 'genre') { console.log("if part is triggered"); this.commonService.getChartDataNew() .subscribe(function (data) { var i2 = 0; var arrayLabels2 = []; var valueLabels2 = []; while (data[i2]) { arrayLabels2.push(data[i2]._id); valueLabels2.push(data[i2].total); i2 = i2 + 1; } _this.data.labels = arrayLabels2; console.log("the this.data.labels" + _this.data.labels); _this.data.datasets[0].data = valueLabels2; console.log("the this.data.datasets[0].data" + _this.data.datasets[0].data); _this.options.title.text = "Analyzing the books as per GENRE"; console.log("my title"); console.log(_this.options.title.text); }); } else { console.log("else part is triggered"); this.commonService.getChartData() .subscribe(function (data) { var i = 0; var arrayLabels = []; var valueLabels = []; while (data[i]) { arrayLabels.push(data[i]._id); valueLabels.push(data[i].total); i = i + 1; } _this.data.labels = arrayLabels; console.log("the this.data.labels" + _this.data.labels); _this.data.datasets[0].data = valueLabels; console.log("the this.data.datasets[0].data" + _this.data.datasets[0].data); _this.options.title.text = "Analyzing the books as per AVAILABILITY"; }); } }; ChartComponent = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["Component"])({ selector: 'app-chart', template: __webpack_require__("./src/app/chart/chart.component.html"), styles: [__webpack_require__("./src/app/chart/chart.component.css")] }), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1__angular_common_http__["a" /* HttpClient */], __WEBPACK_IMPORTED_MODULE_2__shared_common_service__["a" /* CommonService */]]) ], ChartComponent); return ChartComponent; }()); /***/ }), /***/ "./src/app/header/header.component.css": /***/ (function(module, exports) { module.exports = "/* .menu-first,.menu-button{\r\n background-color: #3f51b5;\r\n} */\r\n" /***/ }), /***/ "./src/app/header/header.component.html": /***/ (function(module, exports) { module.exports = " <!-- <div class=\"navbar-header\">\n <a routerLink=\"/books\" class=\"navbar-brand\">Book Shelf</a>\n </div>\n <div class=\"collapse navbar-collapse\">\n <ul class=\"nav navbar-nav\">\n <li routerLinkActive=\"active\"><a routerLink=\"/book-create\">Add Books</a></li>\n <li routerLinkActive=\"active\"><a routerLink=\"\">Sign Up</a></li>\n <li routerLinkActive=\"active\">Sign In</li>\n </ul>\n </div> -->\n <mat-toolbar color=\"primary\">\n <button type=\"button\" (click)=\"showDialog()\" pButton icon=\"fa-external-link-square\" label=\"BOOK SHELF\"></button>\n </mat-toolbar>\n <div class=\"menu-first\" style=\"border-bottom: 0.5px solid black;\">\n <button mat-button [matMenuTriggerFor]=\"menu\">Menu</button>\n <mat-menu class=\"menu-button\" #menu=\"matMenu\" [overlapTrigger]=\"false\">\n <button class=\"menu-button\" mat-menu-item routerLink=\"/books\" color=\"primary\">Home</button>\n <button class=\"menu-button\" mat-menu-item routerLink=\"/book-create\" color=\"primary\">Add Books</button>\n </mat-menu>\n </div>\n\n <p-dialog header=\"How does Book Shelf work?\" [(visible)]=\"display\" [modal]=\"true\" [responsive]=\"true\" [width]=\"350\" [minWidth]=\"200\" [minY]=\"70\">\n <span>\n Book Shelf is an app that helps add/edit/delete/view the books in/from the database. Also, it provides with\n the analytics section. The analytics section helps analyse the books stored in the database. Here, it helps\n analysing the books based on availability and genre.\n </span>\n <p-footer>\n <button type=\"button\" pButton icon=\"fa-check\" (click)=\"display=false\" label=\"Got It!\"></button>\n </p-footer>\n </p-dialog>\n" /***/ }), /***/ "./src/app/header/header.component.ts": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HeaderComponent; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__("./node_modules/@angular/core/esm5/core.js"); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var HeaderComponent = /** @class */ (function () { function HeaderComponent() { this.display = false; } HeaderComponent.prototype.ngOnInit = function () { }; HeaderComponent.prototype.showDialog = function () { this.display = true; }; HeaderComponent = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["Component"])({ selector: 'app-header', template: __webpack_require__("./src/app/header/header.component.html"), styles: [__webpack_require__("./src/app/header/header.component.css")] }), __metadata("design:paramtypes", []) ], HeaderComponent); return HeaderComponent; }()); /***/ }), /***/ "./src/app/shared/common.service.ts": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CommonService; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__("./node_modules/@angular/core/esm5/core.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_common_http__ = __webpack_require__("./node_modules/@angular/common/esm5/http.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__angular_router__ = __webpack_require__("./node_modules/@angular/router/esm5/router.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_rxjs_Rx__ = __webpack_require__("./node_modules/rxjs/_esm5/Rx.js"); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var CommonService = /** @class */ (function () { function CommonService(http, router) { this.http = http; this.router = router; } //Get books CommonService.prototype.getBooks = function () { return this.http.get('/book', { observe: 'body', responseType: 'json', }) .map(function (books) { console.log(books); return books; }); }; //Create Books - post CommonService.prototype.storeRecipes = function (newBook) { console.log("the value of new book is" + newBook); return this.http.post('/book', newBook, { observe: 'body' }); }; //Update the Book CommonService.prototype.updateExistingBook = function (id, updatedBook) { console.log("the value of new book is" + updatedBook); return this.http.put('/book/' + id, updatedBook, { observe: 'body' }); }; //Get Book details CommonService.prototype.getOneBook = function (id) { return this.http.get('/book/' + id, { observe: 'body' }); }; //Delete Books CommonService.prototype.deleteOneBook = function (id) { return this.http.delete('/book/' + id, { observe: 'body' }); }; //charts CommonService.prototype.getChartData = function () { return this.http.get('/book/charts', { observe: 'body' }); }; CommonService.prototype.getChartDataNew = function () { return this.http.get('/book/charts/aggr2', { observe: 'body' }); }; CommonService = __decorate([ Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["Injectable"])(), __metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1__angular_common_http__["a" /* HttpClient */], __WEBPACK_IMPORTED_MODULE_2__angular_router__["b" /* Router */]]) ], CommonService); return CommonService; }()); /***/ }), /***/ "./src/environments/environment.ts": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return environment; }); // The file contents for the current environment will overwrite these during build. // The build system defaults to the dev environment which uses `environment.ts`, but if you do // `ng build --env=prod` then `environment.prod.ts` will be used instead. // The list of which env maps to which file can be found in `.angular-cli.json`. var environment = { production: false }; /***/ }), /***/ "./src/main.ts": /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__("./node_modules/@angular/core/esm5/core.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__angular_platform_browser_dynamic__ = __webpack_require__("./node_modules/@angular/platform-browser-dynamic/esm5/platform-browser-dynamic.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__app_app_module__ = __webpack_require__("./src/app/app.module.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__environments_environment__ = __webpack_require__("./src/environments/environment.ts"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_hammerjs__ = __webpack_require__("./node_modules/hammerjs/hammer.js"); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_hammerjs___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_4_hammerjs__); if (__WEBPACK_IMPORTED_MODULE_3__environments_environment__["a" /* environment */].production) { Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["enableProdMode"])(); } Object(__WEBPACK_IMPORTED_MODULE_1__angular_platform_browser_dynamic__["a" /* platformBrowserDynamic */])().bootstrapModule(__WEBPACK_IMPORTED_MODULE_2__app_app_module__["a" /* AppModule */]) .catch(function (err) { return console.log(err); }); /***/ }), /***/ 0: /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__("./src/main.ts"); /***/ }) },[0]); //# sourceMappingURL=main.bundle.js.map
JavaScript
CL
3374b08feee84346cabd28e4d47995a5c1ae8775e1620f8f5fe23f03c8a36823
/** * AnimateCSS.js: * Этот файл определяет функцию с именем animateCSS(), служащую основой * для создания анимации на базе CSS. Аргументы функции: * * element: Анимируемы HTML-элемент. * numFrames: Общее число кадров в анимации. * timePerFrame: Количиство миллисекунд отображения каждого кажра. * animation: Объект, определяющий анимацию; описывается далее. * whendone: Необязательная функция, вызываемая по завершении анимации. * Если функция указана, ей в качестве аргумента передается * значение аргумента element. * * Функция animateCSS() просто определяет платформу для анимации. Выполняемую * анимацию определяют свойства объекта animation. Каждое свойство должно * иметь то же имя, что и свойство CSS-стиля. Значением каждого свойства * должна быть функция, возвращающая значение для этого свойства стиля. * Каждой функции передается номер кадра и общий промежуток времени, прошедший * с начала анимации, а функция может использовать это для вычисления * значения стиля, которое она должна вернуть для данного фрейма. * Например, чтобы анимировать изображение так, чтобы оно передвигалось * из левого верхнего угла, вы можете вызвать функцию animateCSS так: * * animateCSS(image, 25, 50, * {top: function(frame, time) {return frame*8 + "px"; }, * left: function(frame, time) {return frame*8 + "px"; } * }); */ function animateCSS(element, numFrames, timePerFrame, animation, whendone){ var frame = 0; var time = 0; // Определить вызов displayNextFrame() каждые timePerFrame миллисекунд. // Так будет отображаться каждый кадр анимации. var intervalId = setInterval(displayNextFrame, timePerFrame); // На этом работа animateCSS() завершается, но предыдущая строка гарантирует, // что следующая вложенная функция будет вызываться для каждого кадра анимации. function displayNextFrame(){ if (frame >= numFrames) { // Проверить, не закончилась ли анимация clearInterval(intervalId); // Если да - прекратить вызов if (whendone) whendone(element); // Вызвать функцию whendone return; // и завершить работу } // Обойти в цикле все свойства, определяемые объектом анимации for (var cssprop in animation){ // Для каждого свойства вызвать его функцию анимации, передавая // ей номер кадра и прошедшее впемя. Используем возвращаемое // функцией значение в качестве нового значения соответствующего // свойства стиля для указанного элемента. Используем блок // try/catch, чтобы игнорировать любые исключительные ситуации, // возникающие из-за неверных возвращаемых значений. var unframe = 150-(frame-150); try { if (cssprop == "clip"){ if (frame < 150){ //element.style.visibility = "hidden"; element.style[cssprop] = animation[cssprop](frame); } else { element.style.visibility = "visible"; element.style[cssprop] = animation[cssprop](unframe); } } else { element.style[cssprop] = animation[cssprop](frame); } }catch (e){} } frame++; time += timePerFrame; } } function animato(){ animateCSS(document.getElementById("title"), 300, 20, {top: function(f) {return 600-f*2 + "px";}, clip: function(f) {return "rect("+f+"px auto auto auto)";}}); } function animats(){ animateCSS(document.getElementById("titl"), 300, 20, {left: function(f) {return 400 + 100*Math.cos(f/8) + "px"}, top: function(f) {return 400 + 100*Math.sin(f/8) + "px"}}); } if (window.addEventListener) window.addEventListener("load", animato, false); else if (window.attachEvent) window.attachEvent("onload", animato); if (window.addEventListener) window.addEventListener("load", animats, false); else if (window.attachEvent) window.attachEvent("onload", animats);
JavaScript
CL
80bf0d4620ac0b074e437d38e734c24566d0f3faecbdadad7837cf83cbec39e5
import 'react-native-gesture-handler'; import React, { Component } from 'react'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; import reducer from './reducers'; import middleware from './middleware'; import { Ionicons } from '@expo/vector-icons' import DeckList from './components/DeckList'; import AddDeck from './components/AddDeck'; import Deck from './components/Deck'; import AddCard from './components/AddCard'; import Quiz from './components/Quiz' const store = createStore(reducer, middleware); const Tab = createBottomTabNavigator(); const Stack = createStackNavigator(); class Home extends Component { render() { return ( <Tab.Navigator> <Tab.Screen name='Deck List' component={DeckList} options={{ tabBarIcon: () => ( <Ionicons name="md-card" size={30} /> ) }} /> <Tab.Screen name='Add Deck' component={AddDeck} options={{ tabBarIcon: () => ( <Ionicons name="md-add" size={30} /> ) }} /> </Tab.Navigator> ) } } export default class App extends Component { render() { return ( <Provider store={store}> <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={Home} /> <Stack.Screen name="DeckList" component={DeckList} /> <Stack.Screen name="AddDeck" component={AddDeck} /> <Stack.Screen name="Deck" component={Deck} /> <Stack.Screen name="Add Card" component={AddCard} /> <Stack.Screen name="Quiz" component={Quiz} /> </Stack.Navigator> </NavigationContainer> </Provider> ) } }
JavaScript
CL
454cf227de2ef71a7899152123b35c7efe11ec608638e0d5acf5390adf62ea96
import { Fragment, useState, useEffect } from 'react'; import utils from '../styles/utils'; import { works } from '../assets/data/works'; import useWindowSize from '../components/size'; import General from '../components/layouts/general'; import Header from '../components/template/header'; import Slider from '../components/works/slider'; import Timeline from '../components/works/timeline'; import Description from '../components/works/description'; import Topic from '../components/works/topic'; const Works = (props) => { const isMobile = useWindowSize().width < 768; const { height } = useWindowSize(); const imgPath = (path, img) => { return `https://cdn.jsdelivr.net/gh/thanawat-bcr/tutorism-portfolio-resources/${path}/${img}.png`; }; const [workIndex, setWorkIndex] = useState(0); const work = () => { return works[workIndex]; }; const [modal, setModal] = useState(false); return ( <Fragment> <General> <div className='h-full flex flex-col' style={{ marginTop: '4rem' }}> <Header head='My' body='Works'></Header> <div style={{ height: `calc(100% - 124px)` }} className='flex'> <Timeline works={works} workIndex={workIndex} setWorkIndex={setWorkIndex} imgPath={imgPath} setModal={setModal} ></Timeline> {!isMobile ? ( <> <Topic work={work()}></Topic> <div className={`w-full`}> <Slider work={work()} imgPath={imgPath}></Slider> <Description work={work()}></Description> </div> </> ) : ( <div className={`flex flex-col mx-auto bg-screen ${ modal ? 'work-slide' : '' }`} style={{ position: 'fixed', top: `${height}px`, width: '100vw', height: `calc(${height}px - 4rem)`, left: '0', padding: '1.5rem 1rem', transition: '300ms ease-in-out', }} > <div className='absolute top-0 right-0 my-8 mx-8 font-light text-lg pointer' onClick={() => { setModal(false); }} > x </div> <div style={{ paddingLeft: '1rem' }}> <Topic work={work()}></Topic> </div> <div className={`w-full`} style={{ height: '50%' }}> <Slider work={work()} imgPath={imgPath}></Slider> <Description work={work()}></Description> </div> </div> )} </div> </div> </General> <style jsx>{utils}</style> <style jsx>{` .work-slide { transform: translateY(-${height - 64}px); } `}</style> </Fragment> ); }; export default Works;
JavaScript
CL
1266dfcab40c4b7d7744938dad70a8577a1f3e3ab4619034d4e5611f096837fe
import { isEmpty, isArray } from '@/utils' import { getBrandDetail } from '@/api/store' import { loginIn, loginOut, updateUserInfo } from '@/api/sys' import { ROLE_BRAND, ROLE_STORE, ROLE_STUFF } from '@/utils/const' import { getRules, setRules, getUserId, setUserId, getStoreId, setStoreId, setNickName, getNickName, setUserName, getUserName, setUserRole, getUserRole, getRealName, setRealName, setAvatar, getAvatar, getToken, setToken, getBrandName, setBrandName, getBrandLogo, setBrandLogo, clearAll, } from '@/utils/cache/auth' function calcMenus(menus) { let rules = [] if(!isArray(menus)) { return rules } for(let item of menus) { if(!isEmpty(item.code)) { rules.push(item.code) } rules = rules.concat(calcMenus(item.sysMenuList)) } return rules } const user = { state: { token: getToken(), userId: getUserId(), storeId: getStoreId(), nickname: getNickName(), realName: getRealName(), avatar: getAvatar(), rules: getRules(), userName: getUserName(), userRole: getUserRole(), brandName: getBrandName(), brandLogo: getBrandLogo() }, mutations: { SET_USER_ID: (state, userId) => { state.userId = userId }, SET_STORE_ID: (state, storeId) => { state.storeId = storeId }, SET_TOKEN: (state, token) => { state.token = token }, SET_NICK_NAME: (state, name) => { state.nickname = name }, SET_REAL_NAME: (state, name) => { state.realName = name }, SET_AVATAR: (state, avatar) => { state.avatar = avatar }, SET_ROLES: (state, rules) => { state.rules = rules }, SET_USER_NAME: (state, name) => { state.userName = name }, SET_USER_ROLE: (state, role) => { state.userRole = role }, SET_BRAND_NAME: (state, name) => { state.brandName = name }, SET_BRAND_LOGO: (state, logo) => { state.brandLogo = logo } }, actions: { // 用户名登录 LoginByUsername({ dispatch, commit }, loginInfo) { const user = loginInfo.user.trim() const pass = loginInfo.pass const brand = loginInfo.brand return new Promise((resolve, reject) => { loginIn(user, pass, brand) .then(res => { if (res.success && res.entity) { const { id, headImg, nickName, code, storeId, realName, token, userName, sysMenuList } = res.entity let menus = sysMenuList || [] if (isArray(menus) && menus.length > 0) { let rules = calcMenus(menus) if (code === ROLE_BRAND) { rules.push('user-role-brand') } if (code === ROLE_STORE) { rules.push('user-role-store') } if (code === ROLE_STUFF) { rules.push('user-role-stuff') } commit('SET_ROLES', rules) setRules(rules) } else { return reject(new Error('无权限')) } commit('SET_USER_ID', id) commit('SET_STORE_ID', storeId) commit('SET_AVATAR', headImg) commit('SET_NICK_NAME', nickName) commit('SET_REAL_NAME', realName) commit('SET_TOKEN', token) commit('SET_USER_NAME', userName) commit('SET_USER_ROLE', code) setUserId(id) setStoreId(storeId) setAvatar(headImg) setNickName(nickName) setRealName(realName) setToken(token) setUserName(userName) setUserRole(code) dispatch('LoadBrandInfo') .then(() => { resolve() }) .catch(err => { reject(new Error(err.message || '加载品牌信息失败')) }) } else { reject(new Error(res.message)) } }) .catch(err => { reject(err) }) }) }, // 申请入驻 // ApplyEnter({ dispatch, commit }, data = {}) { // return new Promise((resolve, reject) => { // enterApply(data) // .then(res => { // if (res.success && res.entity) { // const { id, headImg, nickName, code, storeId, realName, token, userName, sysMenuList } = res.entity // let menus = sysMenuList || [] // if (isArray(menus) && menus.length > 0) { // let rules = calcMenus(menus) // if (code === ROLE_BRAND) { // rules.push('user-role-brand') // } // if (code === ROLE_STORE) { // rules.push('user-role-store') // } // if (code === ROLE_STUFF) { // rules.push('user-role-stuff') // } // commit('SET_ROLES', rules) // setRules(rules) // } else { // return reject(new Error('无权限')) // } // commit('SET_USER_ID', id) // commit('SET_STORE_ID', storeId) // commit('SET_AVATAR', headImg) // commit('SET_NICK_NAME', nickName) // commit('SET_REAL_NAME', realName) // commit('SET_TOKEN', token) // commit('SET_USER_NAME', userName) // commit('SET_USER_ROLE', code) // setUserId(id) // setStoreId(storeId) // setAvatar(headImg) // setNickName(nickName) // setRealName(realName) // setToken(token) // setUserName(userName) // setUserRole(code) // dispatch('LoadBrandInfo') // .then(() => { // resolve() // }) // .catch(err => { // reject(new Error(err.message || '加载品牌信息失败')) // }) // } else { // reject(new Error(res.message)) // } // }) // .catch(err => { // reject(err) // }) // }) // }, LoadBrandInfo({ commit }) { return new Promise( resolve => { getBrandDetail() .then(res => { let name = null let logo = null if (res.success && res.entity) { let d = res.entity logo = d.logo name = d.shortName || d.zhName || d.enName } commit('SET_BRAND_NAME', name) commit('SET_BRAND_LOGO', logo) setBrandName(name) setBrandLogo(logo) }) .catch(() => { commit('SET_BRAND_NAME', null) commit('SET_BRAND_LOGO', null) setBrandName(null) setBrandLogo(null) }).finally(() => { resolve() }) }) }, // 更新用户信息 UpdateUserInfo({ commit }, data = {}) { return new Promise((resolve, reject) => { updateUserInfo(data) .then(res => { if (res.success && res.entity) { const { userName } = data commit('SET_REAL_NAME', userName) setRealName(userName) resolve() } else { reject(new Error(res.message)) } }) .catch(err => { reject(err) }) }) }, // 前端登出 FedLogOut({ commit }) { return new Promise(resolve => { clearAll() resolve() }) }, // 后端登出 LogOut({ commit }) { return new Promise((resolve, reject) => { loginOut().finally(() => { clearAll() resolve() }) }) } } } export default user
JavaScript
CL
8ca8bfa1d591635036493d8160b5b4d4d21ac6ff6917d2ec05e90d62ae41c3d0
import React, {Component} from "react"; import {observer, inject} from "mobx-react"; import {Modal, Empty, message} from "antd"; import LocalHistory from "../LocalHistory"; import {AutoSaveInterval, getLocalDocuments, setLocalDocuments, setLocalDraft} from "../LocalHistory/util"; import IndexDB from "../LocalHistory/indexdb"; import debouce from "lodash.debounce"; const DocumentID = 1; @inject("dialog") @inject("content") @observer class HistoryDialog extends Component { timer = null; db = null; constructor(props) { super(props); this.state = { documents: [], }; } async componentDidMount() { await this.initIndexDB(); } componentWillUnmount() { clearInterval(this.timer); } get editor() { return this.props.content.markdownEditor; } // // async UNSAFE_componentWillReceiveProps(nextProps) { // // 文档 id 变更 // if (this.props.documentID !== nextProps.documentID && nextProps.documentID != null) { // if (this.db) { // await this.overrideLocalDocuments(nextProps.documentID); // } // } // } // closeDialog = () => { this.props.dialog.setHistoryOpen(false); }; editLocalDocument = (content) => { this.props.content.setContent(content); message.success("恢复成功!"); this.closeDialog(); }; autoSave = async (isRecent = false) => { const Content = this.props.content.markdownEditor.getValue(); if (Content.trim() !== "") { const document = { Content, DocumentID: this.props.documentID, SaveTime: new Date(), }; const setLocalDocumentMethod = isRecent && this.state.documents.length > 0 ? setLocalDraft : setLocalDocuments; await setLocalDocumentMethod(this.db, this.state.documents, document); await this.overrideLocalDocuments(this.props.documentID); } }; async initIndexDB() { try { const indexDB = new IndexDB({ name: "mdnice-local-history", storeName: "customers", storeOptions: {keyPath: "id", autoIncrement: true}, storeInit: (objectStore) => { objectStore.createIndex("DocumentID", "DocumentID", {unique: false}); objectStore.createIndex("SaveTime", "SaveTime", {unique: false}); }, }); this.db = await indexDB.init(); if (this.db && this.props.documentID) { await this.overrideLocalDocuments(this.props.documentID); } // 每隔一段时间自动保存 this.timer = setInterval(async () => { await this.autoSave(); }, AutoSaveInterval); // 每改变内容自动保存最近的一条 this.editor.on && this.editor.on( "change", debouce(async () => { await this.autoSave(true); }, 1000), ); } catch (e) { console.error(e); } } // 刷新本地历史文档 async overrideLocalDocuments(documentID) { const localDocuments = await getLocalDocuments(this.db, +documentID); // console.log('refresh local',localDocuments); this.setState({ documents: localDocuments, }); } render() { return ( <Modal className="nice-md-local-history" title="本地历史" centered width={1080} visible={this.props.dialog.isHistoryOpen} onCancel={this.closeDialog} footer={null} > {this.state.documents && this.state.documents.length > 0 ? ( <LocalHistory content={this.props.content.content} documents={this.state.documents} documentID={this.props.documentID} onEdit={this.editLocalDocument} onCancel={this.closeDialog} /> ) : ( <Empty style={{width: "100%"}} description="暂无本地历史" /> )} </Modal> ); } } HistoryDialog.defaultProps = { documentID: DocumentID, }; export default HistoryDialog;
JavaScript
CL
a07e1bb20532e0070f325ef21e114a99f2cf60982c619c8d9f5850a2d204eea5
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. */ import React, { useState, useContext, useEffect } from 'react'; import Paper from '@material-ui/core/Paper'; import PropTypes from 'prop-types'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import { FormattedMessage } from 'react-intl'; import { makeStyles } from '@material-ui/core/styles'; import AuthManager from 'AppData/AuthManager'; import Icon from '@material-ui/core/Icon'; import { Icon as Icons } from '@iconify/react'; import postmanIcon from '@iconify/icons-simple-icons/postman'; import Button from '@material-ui/core/Button'; import fileDownload from 'js-file-download'; import converter from 'graphql-to-postman'; import GraphQLUI from './GraphQLUI'; import TryOutController from '../ApiConsole/TryOutController'; import { ApiContext } from '../ApiContext'; import Api from '../../../../data/api'; import Progress from '../../../Shared/Progress'; let graphQLSchema; const useStyles = makeStyles((theme) => ({ buttonIcon: { marginRight: 10, }, paper: { margin: theme.spacing(1), padding: theme.spacing(1), }, grid: { marginTop: theme.spacing(4), marginBottom: theme.spacing(4), paddingRight: theme.spacing(2), justifyContent: 'center', }, userNotificationPaper: { padding: theme.spacing(2), }, titleSub: { marginLeft: theme.spacing(2), paddingTop: theme.spacing(2), paddingBottom: theme.spacing(2), }, })); export default function GraphQLConsole() { const classes = useStyles(); const { api } = useContext(ApiContext); const environmentObject = api.endpointURLs; const [URLs, setURLs] = useState(environmentObject[0].URLs); const [securitySchemeType, setSecurityScheme] = useState('OAUTH'); const [notFound, setNotFound] = useState(false); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [selectedEnvironment, setSelectedEnvironment] = useState(); const [environments, setEnvironments] = useState(); const [scopes, setScopes] = useState([]); const [productionAccessToken, setProductionAccessToken] = useState(); const [sandboxAccessToken, setSandboxAccessToken] = useState(); const [selectedKeyType, setSelectedKey] = useState('PRODUCTION'); const [sandboxApiKey, setSandboxApiKey] = useState(''); const [productionApiKey, setProductionApiKey] = useState(''); const [keys, setKeys] = useState([]); const [labels, setLabels] = useState(); const user = AuthManager.getUser(); useEffect(() => { const apiID = api.id; const apiClient = new Api(); const promiseAPI = apiClient.getAPIById(apiID); promiseAPI .then((apiResponse) => { const apiData = apiResponse.obj; if (apiData.endpointURLs) { const environment = apiData.endpointURLs.map((endpoint) => { return endpoint.environmentName; }); setEnvironments(environment); } if (apiData.labels) { const Label = apiData.labels.map((label) => { return label.name; }); setLabels(Label); } if (apiData.scopes) { const scopeList = apiData.scopes.map((scope) => { return scope.name; }); setScopes(scopeList); } }) .catch((error) => { if (process.env.NODE_ENV !== 'production') { console.error(error); } const { status } = error; if (status === 404) { setNotFound(true); } }); }, []); /** * Load the access token for given key type */ function updateAccessToken() { let accessToken; if (keys.get(selectedKeyType)) { ({ accessToken } = keys.get(selectedKeyType).token); } if (selectedKeyType === 'PRODUCTION') { setProductionAccessToken(accessToken); } else { setSandboxAccessToken(accessToken); } } /** * set Password * @param {*} selectedKey * @param {*} isUpdateToken */ function setSelectedKeyType(selectedKey, isUpdateToken) { if (isUpdateToken) { setSelectedKey(selectedKey, updateAccessToken); } else { setSelectedKey(selectedKey); } } function accessTokenProvider() { if (securitySchemeType === 'BASIC') { const credentials = username + ':' + password; return btoa(credentials); } if (securitySchemeType === 'API-KEY') { if (selectedKeyType === 'PRODUCTION') { return productionApiKey; } else { return sandboxApiKey; } } else if (selectedKeyType === 'PRODUCTION') { return productionAccessToken; } else { return sandboxAccessToken; } } function grapgQLToPostman(graphQL, URL) { converter.convert({ type: 'string', data: graphQL, }, {}, (error, result) => { if (error) { console.log(error); } else { const urlValue = URL.https; const results = result; results.output[0].data.variable[0].value = urlValue; const outputData = results.output[0].data; fileDownload( JSON.stringify(outputData), 'postman collection', ); console.log('Conversion success'); } }); } function handleSchema(schema) { graphQLSchema = schema; } if (api == null) { return <Progress />; } if (notFound) { return 'API Not found !'; } let isApiKeyEnabled = false; let authorizationHeader = api.authorizationHeader ? api.authorizationHeader : 'Authorization'; if (api && api.securityScheme) { isApiKeyEnabled = api.securityScheme.includes('api_key'); if (isApiKeyEnabled && securitySchemeType === 'API-KEY') { authorizationHeader = 'apikey'; } } const isPrototypedAPI = api.lifeCycleStatus && api.lifeCycleStatus.toLowerCase() === 'prototyped'; return ( <> <Typography variant='h4' className={classes.titleSub}> <FormattedMessage id='Apis.Details.GraphQLConsole.GraphQLConsole.title' defaultMessage='Try Out' /> </Typography> <Paper className={classes.paper}> <Grid container className={classes.grid}> {!isPrototypedAPI && !user && ( <Grid item md={6}> <Paper className={classes.userNotificationPaper}> <Typography variant='h5' component='h3'> <Icon>warning</Icon> {' '} <FormattedMessage id='notice' defaultMessage='Notice' /> </Typography> <Typography component='p'> <FormattedMessage id='api.console.require.access.token' defaultMessage={'You need an access token to try the API. Please log ' + 'in and subscribe to the API to generate an access token. If you already ' + 'have an access token, please provide it below.'} /> </Typography> </Paper> </Grid> )} </Grid> <TryOutController setSecurityScheme={setSecurityScheme} securitySchemeType={securitySchemeType} setSelectedEnvironment={setSelectedEnvironment} selectedEnvironment={selectedEnvironment} productionAccessToken={productionAccessToken} setProductionAccessToken={setProductionAccessToken} sandboxAccessToken={sandboxAccessToken} setSandboxAccessToken={setSandboxAccessToken} environments={environments} scopes={scopes} labels={labels} setUsername={setUsername} setPassword={setPassword} username={username} password={password} setSelectedKeyType={setSelectedKeyType} convertToPostman={grapgQLToPostman} selectedKeyType={selectedKeyType} setKeys={setKeys} setURLs={setURLs} setProductionApiKey={setProductionApiKey} setSandboxApiKey={setSandboxApiKey} productionApiKey={productionApiKey} sandboxApiKey={sandboxApiKey} environmentObject={environmentObject} api={api} /> <Paper /> <Grid container> <Grid xs={11} item /> <Grid xs={1} item> <Button size='small' onClick={() => grapgQLToPostman(graphQLSchema, URLs)}> <Icons icon={postmanIcon} width={30} height={30} /> <FormattedMessage id='Apis.Details.GraphQLConsole.GraphQLConsole.download.postman' defaultMessage='Postman collection' /> </Button> </Grid> </Grid> </Paper> <Paper className={classes.paper}> <GraphQLUI authorizationHeader={authorizationHeader} URLs={URLs} securitySchemeType={securitySchemeType} accessTokenProvider={accessTokenProvider} handleSchema={handleSchema} /> </Paper> </> ); } GraphQLConsole.propTypes = { classes: PropTypes.shape({ paper: PropTypes.string.isRequired, titleSub: PropTypes.string.isRequired, root: PropTypes.string.isRequired, }).isRequired, };
JavaScript
CL
f0ce496761b96dfbf49453ab75d2338d812270f2c606e53cf4c6329c813bd7c4
// primary file for the API // dependencies // http module enables requests and responses via a server const http = require('http'); // use fs module allows us to read from / write to the file system var fs = require('fs') // the url module splits up a web address into useable parts const url = require('url'); // https allows us to create a server that uses TLS / SSL protocol. const https = require('https') // this decoder allows us to decode Buffer objects into strings var StringDecoder = require('string_decoder').StringDecoder; // this is our import that contains server configurations: var config = require('./config') // here, we instantiate our http server, which will call our unifiedServer, which contains our logic var httpServer = http.createServer(function(req, res) { unifiedServer(req, res); }) // and start it: httpServer.listen(config.httpPort, function() { console.log("the server is listening on port " + config.httpPort ) }) // this object points to the files with our keys and certificates used in https.createServer var httpsServerOptions = { 'key': fs.readFileSync('./https/key.pem'), 'cert': fs.readFileSync('./https/cert.pem') } // instantiating the https server, passing in our keys/cert object, also calls our unifiedServer var httpsServer = https.createServer(httpsServerOptions, function(req, res) { unifiedServer(req, res); }) // starting it: httpsServer.listen(config.httpsPort, function() { console.log("the server is listening on port " + config.httpsPort) }) // all the server logic for both the http and https server var unifiedServer = function(req, res) { // get url and parse it to get meta data about host // true activates the query string module. var parsedUrl = url.parse(req.url, true) // a url method that gets untrimmed path from url: var path = parsedUrl.pathname; // here, we trim the path using regex, which means: // \/+ - matches any slashes that occur at start OR (|) end // /g - global match rather than stopping at the first - to perform a global, case-insensitive serach, use g with i) // use the .replace method: slashes with blank space '' var trimmedPath = path.replace(/^\/+|\/+$/g,''); // get the query parameters and translates into an object with keys and values. // we can do this because we marked 'true' on url.parse var queryStringObject = parsedUrl.query; // get HTTP method and place in lowercase: var method = req.method.toLowerCase() // get the headers as an Object: var headers = req.headers; // get the StringDecoder module to decode our buffer var decoder = new StringDecoder('utf-8'); var buffer = ''; // .on binds an event (arbitrarily called 'data') to the 'req' object. // So, each time the req object recieves data, we run this function // this function decodes the data and appends it to our buffer until there's no more data?: req.on('data', function(data) { buffer += decoder.write(data); }) // By this time, the buffering is over, so: req.on('end', function() { // we end the decoding: buffer += decoder.end() // check if the trimmed path matches any of the keys in our router object. If not, the chosenHandler is handlers.notFound. var chosenHandler = typeof(router[trimmedPath]) !== 'undefined' ? router[trimmedPath] : handlers.notFound; // Construct data object to send to the handler var data = { 'trimmedPath': trimmedPath, 'queryStringObject': queryStringObject, 'method': method, 'headers': headers, 'payload': buffer } // call the handler function (whether it is handler.notFound or one in the router object) // pass in data object (above) and function noted in 2nd parameter. // the handler function will take the data as well as the noted function as a callback chosenHandler(data, function(statusCode, payload) { // set the statusCode: statusCode = typeof(statusCode) == 'number' ? statusCode : 200; // if theres no payload object, default to empty object payload = typeof(payload) == 'object' ? payload : {}; // to pass a payload via HTTP, we need to stringify it: var payloadString = JSON.stringify(payload); // create the head for our response: res.writeHead(statusCode, { "Content-Type": "application/json" }) // send our payload: res.end(payloadString); // for kicks, I'm parsing logging the payload.payload, // which I had set as {"abc":"123"} var obj = JSON.parse(payload.payload) console.log("returning ", statusCode, obj.abc); }) }) } // define handlers var handlers = {}; // ping handler handlers.ping = function(data, callback) { callback(200, data)// this is the function passed in as the chosenHandler argumnet } // not found handler handlers.notFound = function(data, callback) { callback(404 ) // this is the function passed in as the chosenHandler argumnet } // define a request router var router = { 'ping': handlers.ping, }
JavaScript
CL
c3d0f786c5e9bee3867e422b213072ba4abd64c4976e4bd8ca66f55cc09e2a75
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, {Component} from 'react'; import {View, StatusBar} from 'react-native'; import FlashMessage from 'react-native-flash-message'; import {Provider} from 'react-redux'; import store from './src/redux/store'; import Router from './src/routes/router'; import {setCustomText, setCustomTextInput} from 'react-native-global-props'; const customTextProps = { style: { fontFamily: 'Cairo-SemiBold', }, }; setCustomText(customTextProps); setCustomTextInput(customTextProps); export default class App extends Component { render() { return ( <Provider store={store}> <View style={{flex: 1}}> <StatusBar hidden /> <Router /> <FlashMessage position="bottom" duration={5000} /> </View> </Provider> ); } }
JavaScript
CL
d82a79786c00a3b96f1911b05ab67367d606d68ac6186008a5b290098bfcce1d
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[7],{ /***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/Register.vue?vue&type=script&lang=js&": /*!*******************************************************************************************************************************************************************!*\ !*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/components/Register.vue?vue&type=script&lang=js& ***! \*******************************************************************************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ __webpack_exports__["default"] = ({ data: function data() { return { registerForm: { name: null, email: null, password: null, c_password: null }, message: null, snackbar: false }; }, methods: { register: function register() { var _this = this; this.$store.dispatch("userRegister", this.registerForm).then(function () { _this.$router.push("/login"); })["catch"](function (error) { _this.message = "Register Failed"; _this.snackbar = !_this.snackbar; }); } } }); /***/ }), /***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/Register.vue?vue&type=template&id=97358ae4&": /*!***********************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/components/Register.vue?vue&type=template&id=97358ae4& ***! \***********************************************************************************************************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; }); var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c( "v-content", [ _c( "v-container", { staticClass: "fill-height", attrs: { fluid: "" } }, [ _c( "v-row", { attrs: { align: "center", justify: "center" } }, [ _c( "v-col", { attrs: { cols: "12", sm: "8", md: "6" } }, [ _c( "v-card", [ _c( "v-toolbar", { attrs: { color: "primary", flat: "" } }, [ _c( "v-btn", { attrs: { icon: "" }, on: { click: function($event) { return _vm.$router.go(-1) } } }, [_c("v-icon", [_vm._v("mdi-chevron-left")])], 1 ), _vm._v(" "), _c("v-toolbar-title", [_vm._v("Register")]) ], 1 ), _vm._v(" "), _c( "v-card-text", [ _c( "v-form", [ _c("v-text-field", { attrs: { label: "name" }, model: { value: _vm.registerForm.name, callback: function($$v) { _vm.$set(_vm.registerForm, "name", $$v) }, expression: "registerForm.name" } }), _vm._v(" "), _c("v-text-field", { attrs: { label: "email", type: "email" }, model: { value: _vm.registerForm.email, callback: function($$v) { _vm.$set(_vm.registerForm, "email", $$v) }, expression: "registerForm.email" } }), _vm._v(" "), _c("v-text-field", { attrs: { label: "password", type: "password" }, model: { value: _vm.registerForm.password, callback: function($$v) { _vm.$set(_vm.registerForm, "password", $$v) }, expression: "registerForm.password" } }), _vm._v(" "), _c("v-text-field", { attrs: { label: "re-password", type: "password" }, model: { value: _vm.registerForm.c_password, callback: function($$v) { _vm.$set( _vm.registerForm, "c_password", $$v ) }, expression: "registerForm.c_password" } }) ], 1 ) ], 1 ), _vm._v(" "), _c( "v-card-actions", [ _c("v-spacer"), _vm._v(" "), _c( "v-btn", { attrs: { type: "submit", color: "primary" }, on: { click: function($event) { $event.preventDefault() return _vm.register($event) } } }, [_vm._v("Register")] ) ], 1 ) ], 1 ), _vm._v(" "), _c( "v-snackbar", { attrs: { color: "error" }, model: { value: _vm.snackbar, callback: function($$v) { _vm.snackbar = $$v }, expression: "snackbar" } }, [_vm._v(_vm._s(_vm.message))] ) ], 1 ) ], 1 ) ], 1 ) ], 1 ) } var staticRenderFns = [] render._withStripped = true /***/ }), /***/ "./resources/js/components/Register.vue": /*!**********************************************!*\ !*** ./resources/js/components/Register.vue ***! \**********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Register_vue_vue_type_template_id_97358ae4___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Register.vue?vue&type=template&id=97358ae4& */ "./resources/js/components/Register.vue?vue&type=template&id=97358ae4&"); /* harmony import */ var _Register_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Register.vue?vue&type=script&lang=js& */ "./resources/js/components/Register.vue?vue&type=script&lang=js&"); /* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js"); /* normalize component */ var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__["default"])( _Register_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"], _Register_vue_vue_type_template_id_97358ae4___WEBPACK_IMPORTED_MODULE_0__["render"], _Register_vue_vue_type_template_id_97358ae4___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"], false, null, null, null ) /* hot reload */ if (false) { var api; } component.options.__file = "resources/js/components/Register.vue" /* harmony default export */ __webpack_exports__["default"] = (component.exports); /***/ }), /***/ "./resources/js/components/Register.vue?vue&type=script&lang=js&": /*!***********************************************************************!*\ !*** ./resources/js/components/Register.vue?vue&type=script&lang=js& ***! \***********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Register_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../node_modules/babel-loader/lib??ref--4-0!../../../node_modules/vue-loader/lib??vue-loader-options!./Register.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/Register.vue?vue&type=script&lang=js&"); /* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Register_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]); /***/ }), /***/ "./resources/js/components/Register.vue?vue&type=template&id=97358ae4&": /*!*****************************************************************************!*\ !*** ./resources/js/components/Register.vue?vue&type=template&id=97358ae4& ***! \*****************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Register_vue_vue_type_template_id_97358ae4___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../node_modules/vue-loader/lib??vue-loader-options!./Register.vue?vue&type=template&id=97358ae4& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/Register.vue?vue&type=template&id=97358ae4&"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Register_vue_vue_type_template_id_97358ae4___WEBPACK_IMPORTED_MODULE_0__["render"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Register_vue_vue_type_template_id_97358ae4___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; }); /***/ }) }]);
JavaScript
CL
0d5508eadd33593b9522022e0a91b729d77ca31c113eee07f8b9a0d4b21783e5
const { GraphQLObjectType, GraphQLInt, GraphQLString, GraphQLBoolean, GraphQLList, GraphQLSchema } = require('graphql'); const axios = require('axios'); // This is an example of working with 3'rd party api. In this case it is the Space X API // the key's on the field then need to match what is in the json on the api. i.e flight_number etc. // flight_number: {type: GraphQLInt} >>> We use GraphQLInt because an intereger(number) is returned from the json. // Space X Launch Type const LaunchType = new GraphQLObjectType({ name: 'Launch', fields: () => ({ flight_number: {type: GraphQLInt}, mission_name: {type: GraphQLString}, launch_year: {type: GraphQLString}, launch_date_local: {type: GraphQLString}, launch_success: {type: GraphQLBoolean}, rocket: {type: RocketType} }) }); // Rocket Type const RocketType = new GraphQLObjectType({ name: 'Rocket', fields: () => ({ rocket_id: {type: GraphQLString}, rocket_name: {type: GraphQLString}, rocket_type: {type: GraphQLString}, first_stage: {type: FirstStage} }) }) const FirstStage = new GraphQLObjectType({ name: 'FirstStage', fields: () => ({ // Need to use GraphQL list here because cores is an array with objects cores: {type: GraphQLList(Cores)} }) }) const Cores = new GraphQLObjectType({ name: 'CoresInfo', fields: () => ({ core_serial: {type: GraphQLString} }) }) // Parkering const Parkering = new GraphQLObjectType ({ name: 'Parkering', fields: () => ({ id: {type: GraphQLInt}, parkeringstilbyderNavn: {type: GraphQLString}, aktivVersjon: {type: ParkeringInfo} }) }) // Parkering Info const ParkeringInfo = new GraphQLObjectType ({ name: 'ParkeringInfo', fields: () => ({ navn: {type: GraphQLString}, adresse: {type: GraphQLString} }) }) // RootQuery const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { launches: { type: new GraphQLList(LaunchType), resolve(parent, args) { return axios.get('https://api.spacexdata.com/v3/launches') .then(res => { return res.data }) } }, // This is how you query spesific data with params. i.e Id numbers, names, etc. // quert in GraphiQL would look like this: // { // launch(flight_number: 2) { // mission_name --> DemoSat // flight_number --> 2 // } // } launch: { type: LaunchType, args: { flight_number: {type: GraphQLInt} }, resolve(parent, args) { return axios.get(`https://api.spacexdata.com/v3/launches/${args.flight_number}`) .then (res => { return res.data }) } }, // ------------------------------------------------------------------------- parkering: { type: new GraphQLList(Parkering), resolve(parent, args) { return axios.get('https://www.vegvesen.no/ws/no/vegvesen/veg/parkeringsomraade/parkeringsregisteret/v1/parkeringsomraade?datafelter=alle') .then(res => { return res.data }) } } } }); module.exports = new GraphQLSchema({ query: RootQuery });
JavaScript
CL
1935c2577eb732f32b42efc69b61c8bc6bc7f69bc9d36a04f478645be57ac424
import consola from 'consola' import chalk from 'chalk' import opener from 'opener' import { common, server } from '../options' import { eventsMapping, formatPath } from '../utils' import { showBanner } from '../utils/banner' import { showMemoryUsage } from '../utils/memory' export default { name: 'dev', description: 'Start the application in development mode (e.g. hot-code reloading, error reporting)', usage: 'dev <dir>', options: { ...common, ...server, open: { alias: 'o', type: 'boolean', description: 'Opens the server listeners url in the default browser' } }, async run (cmd) { const { argv } = cmd await this.startDev(cmd, argv, argv.open) }, async startDev (cmd, argv) { let nuxt try { nuxt = await this._listenDev(cmd, argv) } catch (error) { consola.fatal(error) return } try { await this._buildDev(cmd, argv, nuxt) } catch (error) { await nuxt.callHook('cli:buildError', error) consola.error(error) } return nuxt }, async _listenDev (cmd, argv) { const config = await cmd.getNuxtConfig({ dev: true, _build: true }) const nuxt = await cmd.getNuxt(config) // Setup hooks nuxt.hook('watch:restart', payload => this.onWatchRestart(payload, { nuxt, cmd, argv })) nuxt.hook('bundler:change', changedFileName => this.onBundlerChange(changedFileName)) // Wait for nuxt to be ready await nuxt.ready() // Start listening await nuxt.server.listen() // Show banner when listening showBanner(nuxt, false) // Opens the server listeners url in the default browser (only once) if (argv.open) { argv.open = false const openerPromises = nuxt.server.listeners.map(listener => opener(listener.url)) await Promise.all(openerPromises) } // Return instance return nuxt }, async _buildDev (cmd, argv, nuxt) { // Create builder instance const builder = await cmd.getBuilder(nuxt) // Start Build await builder.build() // Print memory usage showMemoryUsage() // Return instance return nuxt }, logChanged ({ event, path }) { const { icon, color, action } = eventsMapping[event] || eventsMapping.change consola.log({ type: event, icon: chalk[color].bold(icon), message: `${action} ${chalk.cyan(formatPath(path))}` }) }, async onWatchRestart ({ event, path }, { nuxt, cmd, argv }) { this.logChanged({ event, path }) await nuxt.close() await this.startDev(cmd, argv) }, onBundlerChange (path) { this.logChanged({ event: 'change', path }) } }
JavaScript
CL
25c8f398ee5b451b1bca4ce1d184c4362dfd07e884dbe021c4a3865e99da7e4c
/** * ----------------------------------------------------------------------------- * * @review isipka * * ----------------------------------------------------------------------------- */ /** * Generic ML MlObserver class. * * * @class FM.MlObserver * @memberOf FM * @extends FM.LmObject * @param {FM.AppObject} app application object. * @param {object} [attrs] DOM node attributes. * @param {node} node DOM node. * List of DOM attributes (check inherited attributes too): * <table class="fm-mlattrs"> * <thead> * <tr> * <th>Name</th><th>description</th><th>Default</th> * </tr> * </thead> * <tbody> * <tr> * <td>data-fmml-attr-name</td> * <td>Host DM.Object attribute to observe.</td> * <td>-</td> * </tr> * <tr> * <td>data-fmml-attr-type</td> * <td>Host DM.Object attribute type.</td> * <td>[string], number, date</td> * </tr> * <tr> * <td>data-fmml-attr-decimals</td> * <td>Number of decimals to display. Applies only if attribute type is <i>number</i>.</td> * <td></td> * </tr> * <tr> * <td>data-fmml-date-format</td> * <td>Date format of attribute value. Applies only if attribute type is <i>date</i>.</td> * <td></td> * </tr> * <tr> * <td>data-fmml-date-is-utc</td> * <td>Attribute value representing date is UTC. Applies only if attribute type is <i>date</i>.</td> * <td>[true], false</td> * </tr> * <tr> * <td>data-fmml-attr-default-value</td> * <td>Default attribute value.</td> * <td>-</td> * </tr> * <tr> * <td>data-fmml-date-display-as</td> * <td>Display date in given format. Applies only if attribute type is <i>date</i>.</td> * <td></td> * </tr> * <tr> * <td>data-fmml-error-host</td> * <td>DOM node id of error host</td> * <td>-</td> * </tr> * <tr> * <td>data-fmml-validation-rules</td> * <td> * Observer validation rules. Using FM macros (if rules starts with @) or JavaScript eval. * Macro validation rules are separated by semicolon. * Eval method must return <i>true</i> to consider observer value valid. Expression is evaluated * in FM context: this.A (application), this.H (host), this.O (observer), this.D (DM object) * </td> * <td>-</td> * </tr> * <tr> * <td>data-fmml-validation-message</td> * <td> * Error message if validation fails. * </td> * <td>Invalid value.</td> * </tr> * <tr> * <tr> * <td>data-fmml-force-validation</td> * <td> * Validate observer even if attribute value is empty. * </td> * <td>[id],true</td> * </tr> * <tr> * <td>data-fmml-run-on-update</td> * <td> * DOM node id of the host to run on attribute update. * Current host DM object is sent as argument. * </td> * <td>-</td> * </tr> * </tbody> * </table> * * @example &lt;!-- example of HTML template --&gt; &lt;div data-fmml-host="Host"&gt; &lt;span data-fmml-observer=&quot;Observer&quot; data-fmml-attr-name=&quot;value&quot; &gt;&lt;/span&gt; &lt;/div&gt; */ FM.MlObserver = FM.defineClass('MlObserver', FM.LmObject); // methods FM.MlObserver.prototype._init = function(app, attrs, node) { this._super("_init", app, attrs); this.objectSubClass = "Observer"; this.log(attrs, FM.logLevels.debug, 'MlObserver._init'); this.node = node ? node : null; this.node.fmmlObserver = this; this.lastValue = null; this.extensions = []; this.renderers = {}; this.currentRenderer = null; // find error host this.errorObject = this.getAttr('data-fmml-error-host', '') != '' ? new FM.DmGenericError({ id: '', text: '' }) : null; this.log("New observer created.", FM.logLevels.debug, 'MlObserver._init'); } /** * Run observer. * * @public * @function */ FM.MlObserver.prototype.run = function() { this.log(this.getNode(), FM.logLevels.debug, 'MlObserver.run'); this._super("run"); this.log("Starting all registred extensions ...", FM.logLevels.debug, 'MlObserver.run'); for (var i = 0; i < this.extensions.length; i++) { try { this.runExtension(this.extensions[i]); } catch (err) { this.log(err, FM.logLevels.error, 'MlObserver.run'); } } this.log("Set DOM node value ...", FM.logLevels.debug, 'MlObserver.run'); this.setNodeValue(); this.log("New observer started.", FM.logLevels.debug, 'MlObserver.run'); return true; } /** * Dispose observer. * * @public * @function */ FM.MlObserver.prototype.dispose = function() { this.log(this.getNode(), FM.logLevels.debug, 'MlObserver.dispose'); this.log("Disposing all registred extensions ...", FM.logLevels.debug, 'MlObserver.dispose'); var exts = FM.cloneObject(this.extensions); for (var i = 0; i < exts.length; i++) { var extObj = exts[i]; if (FM.isset(extObj.dispose)) { try { extObj.dispose(this); } catch (err) { this.log(err, FM.logLevels.error, 'MlObserver.dispose'); } } } this.extensions = []; this.log("Removing observer from DOM node ...", FM.logLevels.debug, 'MlObserver.dispose'); if (this.node) { this.node.fmmlObserver = null; } this.log("Removing observer from host ...", FM.logLevels.debug, 'MlObserver.dispose'); if (this.host) { this.host.removeObserver(this); } if (this.errorObject) { this.log("Disposing error object ...", FM.logLevels.debug, 'MlObserver.dispose'); this.errorObject.dispose(); this.errorObject = null; } return this._super("dispose"); this.log("New observer disposed.", FM.logLevels.debug, 'MlObserver.dispose'); } /** * Returns last eror. * * @returns {FM.DmGenericError} */ FM.MlObserver.prototype.getLastError = function() { var errhost = this._getErrorHost(); return errhost ? errhost.getDmObject() : null; } /** * Set last eror. * * @param {FM.DmGenericError|string} oErr Error to set. * * @return {FM.DmGenericError} */ FM.MlObserver.prototype.setLastError = function(oErr) { var errhost = this._getErrorHost(); if (!errhost) { return this.getHost() ? this.getHost().setLastError(oErr) : (this.getApp() ? this.getApp().setLastError(oErr) : oErr) ; } oErr = FM.isset(oErr) && oErr ? oErr : ""; if (!FM.isObject(oErr)) { if (FM.isString(oErr)) { oErr = new FM.DmGenericError({"messageId": "GE", "text": oErr}); } else { oErr = new FM.DmGenericError(); } } if (!errhost.isExecuted()) { errhost.run(oErr); } else { var dmobj = errhost.getDmObject(); if (!dmobj) { errhost.setDmObject(oErr); } else { dmobj.forEachAttr(function(attr, value) { dmobj.setAttr(attr, oErr.getAttr(attr, null)); return true; }); dmobj.setChanged(true, true); oErr = dmobj; } } return oErr; } /** * Check if observer is valid. * * @pulbic * @function * @param {boolean} [force=false] Validate even if value is null or empty string. * @returns {boolean} */ FM.MlObserver.prototype.isValid = function(force) { this.log(this.getNode(), FM.logLevels.debug, 'MlObserver.isValid'); var rules = this.getAttr("data-fmml-validation-rules", ''); var response = true; var value = this.getValue(); if (rules != '') { force = FM.isset(force) ? force : ( this.getAttr('data-fmml-force-validation', 'false') == 'true' ? true : false ); if (force || value != "") { // eval if (FM.startsWith(rules, "@")) { var value = FM.resolveAttrName({}, rules, false, { A: this.getApp(), H: this.getHost(), O: this, D: this.getDmObject() }); return (value == true); } // predefined (old way) var allRules = rules != null && rules != '' ? rules.split(";") : []; for (var i = 0; i < allRules.length; i++) { var invert = false; var rule = allRules[i]; var ruleArr = rule != null && rule != '' ? rule.split("=") : []; var ruleOperator = ruleArr.length > 0 ? ruleArr[0] : ''; var ruleParamStr = ruleArr.length > 1 ? ruleArr[1] : ''; var ruleParams = ruleParamStr.split(","); if (FM.endsWith(ruleOperator, "!")) { ruleOperator = ruleOperator.substring(0, ruleOperator.length - 1); invert = true; } var v = true; var fn = FM.MlObserver.getValidationRule(this.getApp(), ruleOperator); if (fn) { v = fn(this, ruleParams) == (invert ? false : true); } if (!v) { response = false; break; } } } } if (response) { $(this.node).removeClass("fmmlInvalidValue"); this.setLastError(new FM.DmGenericError({ messageId: '', text: '' })); } else { $(this.node).addClass("fmmlInvalidValue"); this.setLastError(new FM.DmGenericError({ messageId: 'UIVALIDATION', text: this.getAttr('data-fmml-validation-message', 'Invalid value') })); } this.log( response ? "Observer is valid" : "Validation failed: " + ruleOperator, FM.logLevels.debug, 'MlObserver.isValid' ); return response; //no rules } /** * Called by host to signal change of data model, * * @public * @function * */ FM.MlObserver.prototype.update = function() { if (!this.isExecuted()) { return false; } this.log(this.getNode(), FM.logLevels.debug, 'MlObserver.update'); var dmObj = this.getDmObject(); var dtstmp = dmObj ? dmObj.getProperty('timestamp', '0') : '0'; if ( dmObj && dmObj.isAttr(this.getAttr('data-fmml-attr-name','')) && dtstmp != '0' && dtstmp == this.getProperty('updateTimestamp', '0') ) { this.log("Aborting, processed updateTimestamp.", FM.logLevels.debug, 'MlObserver.update'); return false; } this.setProperty('updateTimestamp', dtstmp); // notify extensions this.log("Updating all extensions ...", FM.logLevels.debug, 'MlObserver.update'); for (var i = 0; i < this.extensions.length; i++) { var extObj = this.extensions[i]; if (FM.isset(extObj.update)) { try { extObj.update(this); } catch (err) { this.log(err, FM.logLevels.error, 'MlObserver.update'); } } } // sync node with dmobject this.log("Set DOM node value ...", FM.logLevels.debug, 'MlObserver.update'); this.setNodeValue(); // check if obs is valid and run update host var retc = false; if (this.isValid()) { var hostToRun = this.getAttr('data-fmml-run-on-update', ''); if (hostToRun != '') { this.log("Running [" + hostToRun + "] on update ...", FM.logLevels.debug, 'MlObserver.update'); var node = document.getElementById(hostToRun); if (node && FM.isset(node.fmmlHost) && node.fmmlHost) { try { node.fmmlHost.run(this.getDmObject()); } catch (err) { this.log(err, FM.logLevels.error, 'MlObserver.update'); } } else { this.log("Host [" + hostToRun + "] not found", FM.logLevels.warn, 'MlObserver.update'); } } retc = true; } this.log("Done.", FM.logLevels.debug, 'MlObserver.update'); return retc; } /** * Set observer current value. * * @public * @function * @param {...} value New value. */ FM.MlObserver.prototype.setValue = function(value) { if (!this.isExecuted()) { return false; } this.log(this.getNode(), FM.logLevels.debug, 'MlObserver.setValue'); // conf var attrname = this.getAttr('data-fmml-attr-name', ''); var host = this.getHost(); this.log("Set Observer attribute [" + attrname + "] to [" + value + "] ...", FM.logLevels.debug, 'MlObserver.setValue'); // value var dmobj = this.getDmObject(); if (!dmobj) { this.log("DmObject not found", FM.logLevels.warn, 'MlObserver.setValue'); return false; } // set value = this._formatValue(value); dmobj.setAttr(attrname, value, true); // end this.log("Done.", FM.logLevels.debug, 'MlObserver.setValue'); return true; } /** * Returns observer current value. * * @public * @function * @returns {...} */ FM.MlObserver.prototype.getValue = function() { this.log(this.getNode(), FM.logLevels.debug, 'MlObserver.getValue'); if (!this.isExecuted()) { this.log("Observer is not executed,returning undefined.", FM.logLevels.warn, 'MlObserver.getValue'); return undefined; } // conf if(!this.isAttr('data-fmml-attr-name') && !this.isAttr('data-fmml-attr-default-value')) { this.log("Attribute name is not defined, returning undefined.", FM.logLevels.warn, 'MlObserver.getValue'); return undefined; } var attrname = this.getAttr('data-fmml-attr-name', ''); var defval = this.resolveAttrValue('data-fmml-attr-default-value', ''); var dmobj = this.getDmObject(); // value var value = FM.resolveAttrName(dmobj ? dmobj.options : {}, attrname, defval, { A: this.getApp(), H: this.getHost(), O: this, D: this.getDmObject() }); // end this.log("Done.", FM.logLevels.debug, 'MlObserver.getValue'); return value; } /** * * @ignore */ FM.MlObserver.prototype._getErrorHost = function() { var errnode = document.getElementById(this.getAttr('data-fmml-error-host', '')); return ( errnode && FM.isset(errnode.fmmlHost) && errnode.fmmlHost ? errnode.fmmlHost : null ); } /** * * @ignore */ FM.MlObserver.prototype._formatValue = function(value) { var attrtype = this.getAttr('data-fmml-attr-type', 'string'); var decplaces = parseInt(this.getAttr('data-fmml-attr-decimals', '-1')); var dateIsUtc = this.getAttr('data-fmml-date-is-utc', 'true') != 'false'; var dateFormat = this.getAttr('data-fmml-date-format', this.getApp().getAttr('fm_date_format', undefined)) ; // dates if (attrtype == "date") { var dateObj = null; if (FM.isObject(value) && FM.isset(value.getTime)) { dateObj = value; } else if (FM.isDateString(value)) { dateObj = FM.parseDateString(value, dateIsUtc); } else { dateObj = FM.parseLocalDateString(value); } if (dateObj) { value = FM.dateToString(dateObj, dateIsUtc, dateFormat); } } else if (attrtype == "number") { value = parseFloat(0.0 + value); if (decplaces > -1) { value = value.toFixed(decplaces); } } return value; } /** * * @ignore */ FM.MlObserver.prototype._formatValueForRendering = function(value) { var attrtype = this.getAttr('data-fmml-attr-type', 'string'); var dateIsUtc = this.getAttr('data-fmml-date-is-utc', 'true') != 'false'; var dateFormat = this.getAttr( 'data-fmml-date-display-as', this.getApp().getAttr('fm_date_display_as', undefined) ); var decplaces = parseInt(this.getAttr('data-fmml-attr-decimals', '-1')); // dates if (attrtype == "date") { var dateObj = null; if (FM.isDateString(value)) { dateObj = FM.parseDateString(value, dateIsUtc); } else { dateObj = FM.parseLocalDateString(value); } if (dateObj) { if (dateFormat == 'local') { value = FM.dateLocalFormat(dateObj); } else if (dateFormat == 'ago') { value = FM.strTimeBetween(dateObj, new Date()); } else { value = FM.dateFormat(dateObj, dateFormat); } } } else if (attrtype == "number") { value = parseFloat(0.0 + value); if (decplaces > -1) { value = value.toFixed(decplaces); } } return value; } /** * Render observer value in DOM node using current renderer. * * @param {boolean} force Render event of value is not changed. */ FM.MlObserver.prototype.setNodeValue = function(force) { this.log(this.getNode(), FM.logLevels.debug, 'MlObserver.setNodeValue'); force = FM.isset(force) && force == true ? true : false; // get value var nfvalue = this.getValue(); if(!FM.isset(nfvalue)) { this.log("Undefined value, aborting.", FM.logLevels.warn, 'MlObserver.setNodeValue'); return; } // formating this.log("Formating value [" + nfvalue + "]...", FM.logLevels.debug, 'MlObserver.setNodeValue'); var value = this._formatValueForRendering(nfvalue); this.log("Formated value is [" + value + "].", FM.logLevels.debug, 'MlObserver.setNodeValue'); // not changed if (!force && value == this.lastValue) { this.log("Aborting, formated value is not changed.", FM.logLevels.debug, 'MlObserver.setNodeValue'); return; } // remember this.lastValue = value; // render this.log("Rendering value ...", FM.logLevels.debug, 'MlObserver.setNodeValue'); if (this.getCurrentRenderer()) { this.getCurrentRenderer().render(value); return; } // def render var doSelection = false; try { doSelection = this.node.selectionStart ? true : false; } catch (e) { } var selStart = 0, selEnd = 0; if (doSelection) { selStart = this.node.selectionStart; selEnd = this.node.selectionEnd; } if (this.node.nodeName == 'INPUT' || this.node.nodeName == 'TEXTAREA') { if ($(this.node).is(':checkbox')) { if (value && value != '' && value.toLowerCase() != 'false') { $(this.node).attr('checked', 'checked'); } else { $(this.node).removeAttr('checked'); } } else if ($(this.node).is(':radio')) { $("input:radio[name ='" + $(this.node).attr("name") + "']").val([value]); } else { $(this.node).val(value); } } else if (this.node.nodeName == 'IMG') { $(this.node).attr("src", value); } else if (this.node.nodeName == 'A') { $(this.node).attr("href", value); } else if (FM.isset(this.node.value)) { $(this.node).val(value); } else { $(this.node).html(value); } // selection range restore if (doSelection) { this.node.setSelectionRange(selStart, selEnd); } //end this.log("Done.", FM.logLevels.debug, 'MlObserver.setNodeValue'); } /** * Add extension. * * @public * @function * @param {FM.MlExtension} extObj Extension to add. Usualy there is no need to call this function manualy. */ FM.MlObserver.prototype.addExtension = function(extObj) { this.log(this.getNode(), FM.logLevels.debug, 'MlObserver.addExtension'); this.log("Adding extension:", FM.logLevels.debug, 'MlObserver.addExtension'); this.log(extObj, FM.logLevels.debug, 'MlObserver.addExtension'); this.extensions.push(extObj); if (this.isExecuted()) { this.log("Running added extension ...", FM.logLevels.debug, 'MlObserver.addExtension'); try { this.runExtension(extObj); } catch (err) { this.log(err, FM.logLevels.error, 'MlObserver.addExtension'); } } this.log("Done.", FM.logLevels.debug, 'MlObserver.addExtension'); return true; } /** * Remove extension. * * @public * @function * @param {FM.MlExtension} extObj Extension to remove. Usualy there is no need to call this function manualy. */ FM.MlObserver.prototype.removeExtension = function(extObj) { this.log(this.getNode(), FM.logLevels.debug, 'MlObserver.removeExtension'); this.log("Removing extension:", FM.logLevels.debug, 'MlObserver.removeExtension'); this.log(extObj, FM.logLevels.debug, 'MlObserver.removeExtension'); for (var i = 0; i < this.extensions.length; i++) { if (extObj == this.extensions[i]) { if (FM.isset(this.extensions[i].dispose)) { this.extensions[i].dispose(this); } delete this.extensions[i]; this.log("Done.", FM.logLevels.debug, 'MlObserver.removeExtension'); return true; } } this.log("Not found.", FM.logLevels.warn, 'MlObserver.removeExtension'); return false; } /** * Run extension. Usualy there is no need to call this function manualy. * * @public * @function * @param {FM.MlExtension} extObj Extension to run. */ FM.MlObserver.prototype.runExtension = function(extObj) { if (FM.isset(extObj.run)) { extObj.run(this); } } /** * Returns observer DOM node. * * @public * @function * @returns {node} */ FM.MlObserver.prototype.getNode = function() { return this.node; } /** * Returns current observer DM object. * * @public * @function * @returns {FM.DmObject} */ FM.MlObserver.prototype.getDmObject = function() { return(this.getHost() ? this.getHost().getDmObject(this.node) : null); } /** * Returns host this observer belongs to. * * @public * @function * @returns {FM.MlHost} */ FM.MlObserver.prototype.getHost = function() { if (this.host) return(this.host); this.host = FM.MlObserver.findHost(this.node); return(this.host); } /** * * @ignore */ FM.MlObserver.prototype.onHostEvent = function(sender, ev, evdata) { this.log(this.getNode(), FM.logLevels.debug, 'MlObserver.onHostEvent'); this.log("Event:" + ev, FM.logLevels.debug, 'MlObserver.onHostEvent'); this.log("Event data:", FM.logLevels.debug, 'MlObserver.onHostEvent'); this.log(evdata, FM.logLevels.debug, 'MlObserver.onHostEvent'); var fnd = false; if (FM.isset(this[ev])) { fnd = true; try { this.log("Event is found, executing ...", FM.logLevels.debug, 'MlObserver.onHostEvent'); this[ev](sender, evdata); } catch (e) { this.log(err, FM.logLevels.error, 'MlObserver.onHostEvent'); } } else { this.log("Event is not found, checking extensions ...", FM.logLevels.debug, 'MlObserver.onHostEvent'); // notify extensions for (var i = 0; i < this.extensions.length; i++) { var extObj = this.extensions[i]; if (FM.isset(extObj[ev])) { try { this.log("Executing event in extension:", FM.logLevels.debug, 'MlObserver.onHostEvent'); this.log(extObj, FM.logLevels.debug, 'MlObserver.onHostEvent'); extObj[ev](sender, evdata); } catch (e) { this.log(e, FM.logLevels.error, 'MlObserver.onHostEvent'); } fnd = true; } } } this.log("Done.", FM.logLevels.debug, 'MlObserver.onHostEvent'); return fnd; } /** * * @ignore */ FM.MlObserver.prototype.resolveAttrValue = function(val, defv) { val = FM.resolveAttrValue(this.options, val, defv, { A: this.getApp(), H: this.getHost(), O: this, D: this.getDmObject() }); return val; } /** * Returns current renderer. * * @public * @function * @returns {FM.MlExtension} */ FM.MlObserver.prototype.getCurrentRenderer = function() { return this.currentRenderer; } /** * * @ignore */ FM.MlObserver.prototype._checkCurrentRenderer = function() { for (var i = this.extensions.length - 1; i > -1; i--) { var ext = this.extensions[i]; if (FM.isset(this.renderers[ext.getID()] && this.renderers[ext.getID()])) { this.currentRenderer = ext; return this.currentRenderer; } } return this.currentRenderer; } /** * Add extension to list of available renderers. * Last registered extension is active renderer. * @public * @function * @param {FM.MlExtension} renderer Renderer to add. */ FM.MlObserver.prototype.addRenderer = function(r) { if (!r) return; var curr = this.getCurrentRenderer(); this.renderers[r.getID()] = r; var newr = this._checkCurrentRenderer(); if (curr != newr) { if (curr) curr.disableRenderer(); if (newr) newr.enableRenderer(); } } /** * Remove extension from list of available renderers. * @public * @function * @param {FM.MlExtension} renderer Renderer to remove. */ FM.MlObserver.prototype.removeRenderer = function(r) { if (!r) return; var curr = this.getCurrentRenderer(); if (FM.isset(this.renderers[r.getID()])) { this.renderers[r.getID()] = null; } var newr = this._checkCurrentRenderer(); if (curr != newr) { if (curr) curr.disableRenderer(); if (newr) newr.enableRenderer(); } } /** * Search for first child node with FM.MlHost instance. * * @public * @static * @function * @param {node} node DOM node to start searching from. * @returns {FM.MlHost|null} */ FM.MlObserver.findHost = function(node) { return FM.findNodeWithAttr(node, "fmmlHost"); } /** * * @ignore */ FM.MlObserver.observerTypes = { GLOBAL: {} }; /** * Register application observer type. * * @public * @static * @function * @param {string} type name. * @param {FM.MlHost} fn Observer class function. * @param {string} [appCls='GLOBAL'] Application subclass type. * * @returns {boolean} */ FM.MlObserver.addObserver = function(type, fn, appCls) { appCls = FM.isset(appCls) && FM.isString(appCls) && appCls != '' ? appCls : 'GLOBAL'; if (!FM.isset(fn) || !FM.isFunction(fn)) return false; if (!FM.isset(type) || !type || type == '') return false; if (!FM.isset(FM.MlObserver.observerTypes[appCls])) { FM.MlObserver.observerTypes[appCls] = {}; } FM.MlObserver.observerTypes[appCls][type] = fn; return true; } /** * Returns MlObserver <b>config</b> class function for <b>config</b> subclass type. * * @public * @static * @function * @param {FM.AppObject} app Current application. * @param {String} type Observer subclass type. * @return {FM.MlObserver} Class function. */ FM.MlObserver.getConfiguration = function(app, name) { var list = FM.MlObserver.observerTypes; app = FM.isset(app) && app ? app : null; var appCls = app ? app.getSubClassName() : null; var appCfg = appCls && FM.isset(list[appCls]) ? list[appCls] : null; var obj = null; if (appCfg && FM.isset(appCfg[name])) { obj = appCfg[name]; } else if (app && FM.isArray(app.applicationObjectsSpace)) { FM.forEach(app.applicationObjectsSpace, function(i, ns) { if (FM.isset(list[ns]) && FM.isset(list[ns][name])) { obj = list[ns][name]; return false; } return true; }); } if (!obj && FM.isset(list['GLOBAL'][name])) { obj = list['GLOBAL'][name]; } return obj; } /** * Returns new instance of chosen <b>sctype</b> observer type. * @static * @public * @function * @param {FM.AppObject} app Current application. * @param {object} attrs Observer attributes. * @param {node} node Observer node. * @param {String} type Observer subclass type. * * @return {FM.MlObserver} New observer instance. */ FM.MlObserver.newObserver = function(app, attrs, node, type) { var clsFn = FM.MlObserver.getConfiguration(app, type); return clsFn ? new clsFn(app, attrs, node) : null; } FM.MlObserver.addObserver("Observer", FM.MlObserver, 'GLOBAL'); /** * Validation rules. * * @namespace */ FM.MlObserver.validationRules = { /** * Global validation rules. Available to all applications. * * @namespace */ GLOBAL: { /** * Equal validation rule. * Example: * * @param {FM.MlObserver} observer Observer. * @param {array} ruleParams Rule parameters. * * @returns {boolean} */ equal: function(observer, ruleParams, cbFn) { var value = observer.getValue(); if (ruleParams.length < 1) return false; for (var i = 0; i < ruleParams.length; i++) { if (FM.startsWith(ruleParams[i], '#')) { if (value != $(ruleParams[i]).val()) return false; } else { try { if (value != '' + eval(ruleParams[i])) { return false; } } catch (e) { return false; } } } return true; }, /** * Greather then validation rule. * Example: * * @param {FM.MlObserver} observer Observer. * @param {array} ruleParams Rule parameters. * * @returns {boolean} */ gt: function(observer, ruleParams, cbFn) { var value = observer.getValue(); if (ruleParams.length < 1) return false; for (var i = 0; i < ruleParams.length; i++) { if (FM.startsWith(ruleParams[i], '#')) { if (value != $(ruleParams[i]).val()) return false; } else { try { if (parseFloat(value) > parseFloat(eval(ruleParams[i]))) { return true; } } catch (e) { return false; } } } return false; }, /** * Less then rule. * Example: * * @param {FM.MlObserver} observer Observer. * @param {array} ruleParams Rule parameters. * * @returns {boolean} */ lt: function(observer, ruleParams, cbFn) { var value = observer.getValue(); if (ruleParams.length < 1) return false; for (var i = 0; i < ruleParams.length; i++) { if (FM.startsWith(ruleParams[i], '#')) { if (value != $(ruleParams[i]).val()) return false; } else { try { if (parseFloat(value) < parseFloat(eval(ruleParams[i]))) { return true; } } catch (e) { return false; } } } return false; }, /** * Empty validation rule. * Example: * * @param {FM.MlObserver} observer Observer. * @param {array} ruleParams Rule parameters. * * @returns {boolean} */ empty: function(observer, ruleParams, cbFn) { var value = observer.getValue(); if (value == null || value == '') { return true; } return false; }, /** * validEmail validation rule. * Example: * * @param {FM.MlObserver} observer Observer. * @param {array} ruleParams Rule parameters. * * @returns {boolean} */ validEmail: function(observer, ruleParams, cbFn) { var value = observer.getValue(); if (value == null || value == '') { return true; } // check if email address is valid return FM.validateEmail(value); } } } /** * Returns requested validation rule function. * * @public * @static * @param {type} app Current application. * @param {type} name Validation rule name. * @returns {function} */ FM.MlObserver.getValidationRule = function(app, name) { var list = FM.MlObserver.validationRules; app = FM.isset(app) && app ? app : null; var appCls = app ? app.getSubClassName() : null; var appCfg = appCls && FM.isset(list[appCls]) ? list[appCls] : null; var obj = null; if (appCfg && FM.isset(appCfg[name])) { obj = appCfg[name]; } else if (app && FM.isArray(app.applicationObjectsSpace)) { FM.forEach(app.applicationObjectsSpace, function(i, ns) { if (FM.isset(list[ns]) && FM.isset(list[ns][name])) { obj = list[ns][name]; return false; } return true; }); } if (!obj && FM.isset(list['GLOBAL'][name])) { obj = list['GLOBAL'][name]; } return obj; } /** * Register new validation rule. * * @public * @static * @param {string} name Validation rule name. * @param {function} fn Validation rule function. * Function receives two arguments (observer instance and array of rule parameters) * and returns <i>true</i> or <i>false</i>. * @param {string} [appCls='GLOBAL'] Application subclass type. */ FM.MlObserver.addValidationRule = function(name, fn, appCls) { appCls = FM.isset(appCls) && FM.isString(appCls) && appCls != '' ? appCls : 'GLOBAL'; if (!FM.isset(name) || !name || name == '') return false; if (!FM.isset(fn) || !FM.isFunction(fn)) return false; if (!FM.isset(FM.MlObserver.validationRules[appCls])) { FM.MlObserver.validationRules[appCls] = {}; } FM.MlObserver.validationRules[appCls][name] = fn; return true; }
JavaScript
CL
df87cdcdf9ceef9234f77d8615d7350bafb5b2311e3e72838a56286f2af006a9
const path = require('path') const resolve = paths => path.resolve(__dirname, paths) const { VueLoaderPlugin } = require('vue-loader') module.exports = { mode: 'production', entry: resolve('../packages/wmview/index.ts'), output: { path: resolve('../dist'), filename: 'index.js', libraryTarget: 'umd', library: 'wmview', globalObject: "typeof self !== 'undefined' ? self : this", }, externals: { // 不打包vue vue: { root: 'Vue', commonjs: 'vue', commonjs2: 'vue', }, }, resolve: { // 解析模块 对应的扩展名 extensions: ['.ts', '.tsx', '.js', '.vue'], }, module: { rules: [ { test: /\.(ts|js)x?$/, exclude: /node_modules/, loader: 'babel-loader', // 需要配配置文件 }, { test: /\.vue$/, loader: 'vue-loader', }, ], }, plugins: [new VueLoaderPlugin()], }
JavaScript
CL
b587cf5746c473420fefd228b0188c1ff055ce097e7fb3b4552a53c634cdbef9
"use strict"; var fs = require('fs') , shell = require('shelljs') , chalk = require('chalk') , utils = require('../../tools/utils') ; module.exports = function(resourceName) { //init strings const name = utils.getNormalizedName(resourceName); const plural = utils.pluralize(name); const camelName = utils.camelCase(name); const camelNamePlural = utils.camelCase(plural); const PascalName = utils.capitalizeFirstLetter(name); const PascalNamePlural = utils.capitalizeFirstLetter(plural); const allCaps = utils.startCase(name).toUpperCase(); const allCapsPlural = utils.startCase(plural).toUpperCase(); const lowercase = utils.startCase(name).toLowerCase(); const lowercasePlural = utils.startCase(plural).toLowerCase(); const kebabName = utils.kebabCase(name); const kebabNamePlural = utils.kebabCase(plural); const actionCase = utils.actionCase(name); const actionCasePlural = utils.actionCase(plural); const startName = utils.startCase(name); var serverPath = "./server/resources/" + camelName; var checkServer = utils.checkIfExists(serverPath); if(checkServer) { console.log(" " + chalk.bgRed("NOTE:") + chalk.red(" A Server Resource by that name already exists. Skip this step.")); return; } console.log(chalk.cyan(" Creating Server Resource called " + name)); let replacements = { name , plural , camelName , camelNamePlural , PascalName , PascalNamePlural , allCaps , allCapsPlural , lowercase , lowercasePlural , kebabName , kebabNamePlural , actionCase , actionCasePlural , startName } console.log(chalk.dim(" DIR", __dirname)); //server only has 3 core files: Model, controller, and api utils.mkdir(serverPath, () => { utils.write(serverPath + '/' + PascalName + 'Model.js' , utils.readTemplateAndReplace(__dirname, '/server/Model.js' , replacements)); utils.write(serverPath + '/' + camelNamePlural + 'Api.js' , utils.readTemplateAndReplace(__dirname, '/server/api.js' , replacements)); utils.write(serverPath + '/' + camelNamePlural + 'Controller.js' //only one we add an "s" too , utils.readTemplateAndReplace(__dirname, '/server/controller.js' , replacements)); }) //now integrate into application var newApiReference = "\nrouteFilenames.push('" + camelName + "/" + camelNamePlural + "Api');"; utils.append("./server/router/api-router.js", newApiReference); var newDbReference = "\nlet " + PascalName + " = require('./resources/" + camelName + "/" + PascalName + "Model');"; utils.append("./server/db.js", newDbReference); console.log(chalk.magenta(" Finished creating Server Resource.")); }
JavaScript
CL
970d14bce57a0c0f0bb3cde91e0492f96f4feda72c9403147d22b31359077dd4
'use strict'; const Redis = require('ioredis'); const Redlock = require('redlock'); const config = require('config'); const logger = require('screwdriver-logger'); class Lock { /** * Constructor */ constructor() { if (config.get('redisLock.enabled')) { const redisLockConfig = config.get('redisLock.options'); const connectionDetails = { host: redisLockConfig.redisConnection.host, options: { password: redisLockConfig.redisConnection.options && redisLockConfig.redisConnection.options.password, tls: redisLockConfig.redisConnection.options ? redisLockConfig.redisConnection.options.tls : false }, port: redisLockConfig.redisConnection.port }; try { this.redis = new Redis(connectionDetails.port, connectionDetails.host, connectionDetails.options); this.redlock = new Redlock([this.redis], { driftFactor: redisLockConfig.driftFactor, retryCount: redisLockConfig.retryCount, retryDelay: redisLockConfig.retryDelay, retryJitter: redisLockConfig.retryJitter }); } catch (err) { logger.error('Failed to initialize redlock', err); } } } /** * Attempt to acquire a lock for resource, will retry acquiring lock depending * on configuration. * @method lock * @param {String} resource the string identifier for the resource to lock * @param {Number} ttl maximum lock duration in milliseconds * @returns {Promise} */ async lock(resource, ttl = 20000) { if (this.redlock) { try { const lock = await this.redlock.lock(resource, ttl); return lock; } catch (err) { logger.error(`Failed to lock ${resource}`, err); } } return null; } /** * Attempt to release a lock for resource. * * @method unlock * @param {Object} lock Lock representing the resource * @param {String} resource the string identifier for the resource to lock * @returns {Promise} */ async unlock(lock, resource) { try { if (lock) { const wait = await lock.unlock(); return wait; } } catch (err) { logger.error(`Failed to unlock ${resource}`, err); } return null; } } module.exports = new Lock();
JavaScript
CL
3945e9ba659cb9ba54f79e044db31fd05ebe5abe4858704865fea7948ef94683
/* Copyright 2023 Adobe. All rights reserved. This file is licensed to you 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 REPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // import { playwrightLauncher } from '@web/test-runner-playwright'; const filteredLogs = ['Running in dev mode', 'lit-html is in dev mode']; export default /** @type {import("@web/test-runner").TestRunnerConfig} */ ({ /** Test files to run */ files: 'dist/test/**/*.test.js', /** Resolve bare module imports */ nodeResolve: { exportConditions: ['browser', 'development'], }, /** Filter out lit dev mode logs */ filterBrowserLogs(log) { for (const arg of log.args) { if ( typeof arg === 'string' && filteredLogs.some(l => arg.includes(l)) ) { return false; } } return true; }, /** Compile JS for older browsers. Requires @web/dev-server-esbuild plugin */ // esbuildTarget: 'auto', /** Amount of browsers to run concurrently */ // concurrentBrowsers: 2, /** Amount of test files per browser to test concurrently */ // concurrency: 1, /** Browsers to run tests on */ // browsers: [ // playwrightLauncher({ product: 'chromium' }), // playwrightLauncher({ product: 'firefox' }), // playwrightLauncher({ product: 'webkit' }), // ], // See documentation for all available options });
JavaScript
CL
9bb4c340b95df5b0e10a4cd03e04676574a33b7cc020977cb026e55ba3a4d73e
/*npm install gulp-cache gulp-clean-css gulp-imagemin */ // 载入gulp var gulp = require('gulp'), // sass = require('gulp-ruby-sass'), // autoprefixer = require('gulp-autoprefixer'), //自动增加浏览器前缀 // loadplugins = require('gulp-load-plugins'), //自动加载插件 // jshint = require('gulp-jshint'), //js拼写检查 // uglify = require('gulp-uglify'), //js压缩 // rename = require('gulp-rename'), //修改文件名 // clean = require('gulp-clean'), //清理文件 // concat = require('gulp-concat'), // notify = require('gulp-notify'), cache = require('gulp-cache'), //文件缓存,有改动才压缩合并 autoprefixer = require('autoprefixer'), // 处理浏览器私有前缀 postcss = require('gulp-postcss'), px2rem = require('postcss-px2rem'), minifycss = require('gulp-clean-css'), //压缩CSS文件 imagemin = require('gulp-imagemin'), //压缩图片 pngquant = require('imagemin-pngquant'); //压缩png24半透明 // spritesmith = require('gulp-css-spritesmith'), //雪碧图 // livereload = require('gulp-livereload'); // 样式 gulp.task('styles', function() { var processors = [px2rem({ remUnit: 75 }), autoprefixer({ brpwsers: ['last 10 version', '>1%'] })]; // 75代表了1rem对应的px值,这个值根据设计师提供的设计图的总宽度/10决定 // 如若需要原样输出,则在后面加上注释/*no*/ return gulp.src('src/static/css_test/*.css') //.pipe(sass({ style: 'expanded', })) //.pipe(gulp.dest('union/css/')) //.pipe(rename({ suffix: '.min' })) //.pipe(autoprefixer({brpwsers:['last 2 version', 'android >= 4.0']})) .pipe(postcss(processors)) .pipe(minifycss({ 'advanced': false, //类型:Boolean 默认:true [是否开启高级优化(合并选择器等)] 'compatibility': 'ie7', //保留ie7及以下兼容写法 类型:String 默认:''or'*' [启用兼容模式; 'ie7':IE7兼容模式,'ie8':IE8兼容模式,'*':IE9+兼容模式] 'keepBreaks': true, //类型:Boolean 默认:false [是否保留换行] 'keepSpecialComments': '*' //保留所有特殊前缀 当你用autoprefixer生成的浏览器前缀,如果不加这个参数,有可能将会删除你的部分前缀 })) .pipe(gulp.dest('src/static/css/')) }); gulp.task('styles2', function() { var processors = [px2rem({ remUnit: 234.375 }), autoprefixer({ brpwsers: ['last 10 version', '>1%'] })]; return gulp.src('src/static/css_test/*.css') //.pipe(sass({ style: 'expanded', })) //.pipe(gulp.dest('union/css/')) //.pipe(rename({ suffix: '.min' })) //.pipe(autoprefixer({brpwsers:['last 2 version', 'android >= 4.0']})) .pipe(postcss(processors)) .pipe(minifycss({ 'advanced': false, //类型:Boolean 默认:true [是否开启高级优化(合并选择器等)] 'compatibility': 'ie7', //保留ie7及以下兼容写法 类型:String 默认:''or'*' [启用兼容模式; 'ie7':IE7兼容模式,'ie8':IE8兼容模式,'*':IE9+兼容模式] 'keepBreaks': true, //类型:Boolean 默认:false [是否保留换行] 'keepSpecialComments': '*' //保留所有特殊前缀 当你用autoprefixer生成的浏览器前缀,如果不加这个参数,有可能将会删除你的部分前缀 })) .pipe(gulp.dest('src/static/css/')) }); // 脚本 /*gulp.task('scripts', function() { return gulp.src('js/*.js') .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('default')) .pipe(concat('main.js')) .pipe(gulp.dest('dist/scripts')) .pipe(rename({ suffix: '.min' })) .pipe(uglify()) .pipe(gulp.dest('dist/scripts')) .pipe(notify({ message: 'Scripts task complete' })); }); */ // 图片 gulp.task('images', function() { gulp.src(['src/static/images_test/**/*{.jpg,.jpeg,.png}', '!*.sp.png']) .pipe(cache(imagemin({ progressive: true, svgoPlugins: [{ removeViewBox: false }], //不要移除svg的viewbox属性 use: [pngquant()] //pngquant深度压缩 }))) .pipe(gulp.dest('src/static/images/')); }); // // var spritesmith = require('gulp.spritesmith'); // gulp.task('imgSprite', function() { // return gulp.src('sportstoday/images_test/*.sp.png') //需要合并的图片地址 // .pipe(spritesmith({ // imgName: 'sportstoday/images/icon_sprite.png', //保存合并后图片的地址 // cssName: 'sportstoday/style_test/sprite.css', //保存合并后对于css样式的地址 // padding: 2, //合并时两个图片的间距 // algorithm: 'binary-tree', //注释1 // cssTemplate: function(data) { // var arr = []; // data.sprites.forEach(function(sprite) { // arr.push(".icon-" + sprite.name + // "{" + // //"background-image: url(‘/union/"+sprite.escaped_image+"‘);"+ // "background-position: " + sprite.px.offset_x + " " + sprite.px.offset_y + ";" + // "width:" + sprite.px.width + ";" + // "height:" + sprite.px.height + ";" + // "}\n"); // }); // return arr.join(""); // } // })) // //.pipe(replace(/^\.icon-/gm, '.')) // .pipe(gulp.dest('./sportstoday/images_test/')); // }); // 清理 gulp.task('clean', function() { return gulp.src(['images_test', 'css_test'], { read: false }) .pipe(clean()); }); // 预设任务 gulp.task('default', ['watch'], function() {}); // 监控 gulp.task('watch', function() { // 监控所有.css档 gulp.watch('src/static/css_test/*.css', ['styles2']); // 监控所有.js档 //gulp.watch('src/scripts/*.js', ['scripts']); //监控所有图片档 // gulp.watch('src/static/images_test/**/*.*', ['images']); // 建立即时重整伺服器 //var server = livereload(); // 监控当前目录下的档案,一旦有更动,便进行重整 // gulp.watch(['./**/*.*'],['serve']).on('change',browserSync.reload); });
JavaScript
CL
394141e99cdd1241100681c84b2273a3d4ef7e9996ddac52029fc34bdf906ba6
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.useProgram = useProgram; exports.useProgramUniforms = useProgramUniforms; var _react = require("react"); var _warning = _interopRequireDefault(require("warning")); var prefix = 'react-vertex:'; function log(source) { if (typeof source !== 'string') { (0, _warning["default"])(false, "".concat(prefix, " Shader source should be a string!")); return ''; } var lines = source.split('\n'); for (var i = 0; i < lines.length; i++) { lines[i] = i + 1 + ': ' + lines[i]; } return lines.join('\n'); } function useShader(gl, source) { var isVertShader = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var memoized = (0, _react.useMemo)(function () { var _gl$getShaderPrecisio, _gl$getShaderPrecisio2; if (source.constructor === WebGLShader) { return source; } var shaderType = isVertShader ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER; var shader = gl.createShader(shaderType); var precision = 'lowp'; // prettier-ignore if ((_gl$getShaderPrecisio = gl.getShaderPrecisionFormat(shaderType, gl.HIGH_FLOAT)) !== null && _gl$getShaderPrecisio !== void 0 && _gl$getShaderPrecisio.precision || 0 > 0) { precision = 'highp'; } else if ((_gl$getShaderPrecisio2 = gl.getShaderPrecisionFormat(shaderType, gl.MEDIUM_FLOAT)) !== null && _gl$getShaderPrecisio2 !== void 0 && _gl$getShaderPrecisio2.precision || 0 > 0) { precision = 'mediump'; } var prepped = source.replace('<<FLOAT_PRECISION>>', precision); if (shader) { gl.shaderSource(shader, prepped); gl.compileShader(shader); (0, _warning["default"])(gl.getShaderParameter(shader, gl.COMPILE_STATUS), "".concat(prefix, "\n").concat(gl.getShaderInfoLog(shader), "\n").concat(log(prepped))); } else { (0, _warning["default"])(false, "".concat(prefix, "\nShader could not be compiled. Source:\n").concat(source)); } return shader; }, [gl, source, isVertShader]); return memoized; } function useProgram(gl, vertSource, fragSource) { var vert = useShader(gl, vertSource, true); var frag = useShader(gl, fragSource, false); var memoized = (0, _react.useMemo)(function () { var program = gl.createProgram(); if (program && vert && frag) { gl.attachShader(program, vert); gl.attachShader(program, frag); gl.linkProgram(program); (0, _warning["default"])(gl.getProgramParameter(program, gl.LINK_STATUS), "".concat(prefix, " Error creating program")); } else { throw Error('Program could not be created.'); } return program; }, [gl, vert, frag]); (0, _react.useEffect)(function () { return function () { return gl.deleteProgram(memoized); }; }, [gl, memoized]); gl.useProgram(memoized); return memoized; } function useProgramUniforms(gl, program) { var memoized = (0, _react.useMemo)(function () { var uniforms = {}; var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); for (var i = 0; i < uniformCount; i++) { var _gl$getActiveUniform; var _name = (_gl$getActiveUniform = gl.getActiveUniform(program, i)) === null || _gl$getActiveUniform === void 0 ? void 0 : _gl$getActiveUniform.name; if (_name) { uniforms[_name] = gl.getUniformLocation(program, _name); } } return uniforms; }, [gl, program]); return memoized; } //# sourceMappingURL=shaders.js.map
JavaScript
CL
0a3f804f006c5152ae504b924bf04e26a51ebbff2a46355a93356316f133e332
// @ts-check const Discord = require("thunderstorm") const c = require("centra") const entities = require("entities") const encoding = require("@lavalink/encoding") const passthrough = require("../../passthrough") const { constants, sync, frisky, config, ipc } = passthrough /** * @type {import("../../modules/utilities")} */ const utils = sync.require("../../modules/utilities") /** * @type {import("./common")} */ const common = sync.require("./common.js") const stationData = new Map([ ["original", { title: "Frisky Radio: Original", queue: "Frisky Radio: Original", client_name: "frisky", url: "http://stream.friskyradio.com/frisky_mp3_hi", // 44100Hz 2ch 128k MP3 beta_url: "http://stream.friskyradio.com/frisky_mp3_hi" // 44100Hz 2ch 128k MP3 }], ["deep", { title: "Frisky Radio: Deep", queue: "Frisky Radio: Deep", client_name: "deep", url: "http://deep.friskyradio.com/friskydeep_acchi", // 32000Hz 2ch 128k MP3 (!) beta_url: "http://deep.friskyradio.com/friskydeep_aachi" // 32000Hz 2ch 128k MP3 (!) }], ["chill", { title: "Frisky Radio: Chill", queue: "Frisky Radio: Chill", client_name: "chill", url: "http://chill.friskyradio.com/friskychill_mp3_high", // 44100Hz 2ch 128k MP3 beta_url: "https://stream.chill.friskyradio.com/mp3_high" // 44100Hz 2ch 128k MP3 }], ["classics", { title: "Frisky Radio: Classics", queue: "Frisky Radio: Classics", client_name: "classics", url: "https://stream.classics.friskyradio.com/mp3_high", // 44100Hz 2ch 128k MP3 beta_url: "https://stream.classics.friskyradio.com/mp3_high" // 44100Hz 2ch 128k MP3 }] ]) class Song { constructor() { this.title = "" this.track = "" this.lengthSeconds = -1 this.queueLine = "" this.npUpdateFrequency = 0 this.noPauseReason = "" this.error = "" this.typeWhileGetRelated = true /** only used for error logs at the moment (???) */ this.id = "" this.live = null this.thumbnail = { src: "", width: 0, height: 0 } /** * might not be set! * @type {import("./queue").Queue} */ this.queue = null this.validated = false setTimeout(() => { if (!this.validated) this.validationError("must call validate() in constructor") }) } /** * @returns {any} */ toObject() { return { class: "Did not override generic toObject" } } getState() { const object = this.toObject() return { title: this.title, length: this.lengthSeconds, thumbnail: this.thumbnail, live: this.live, class: object.class, id: object.id } } /** * @param {number} time milliseconds * @param {boolean} paused */ // @ts-ignore getProgress(time, paused) { return "" } /** * An array of Song objects from related songs * @returns {Promise<Song[]>} */ getRelated() { return Promise.resolve([]) } /** * Sendable data showing the related songs * @returns {Promise<string|Discord.MessageEmbed>} */ showRelated() { return Promise.resolve("This isn't a real song.") } showLink() { return Promise.resolve(constants.baseURL) } /** * Get sendable data with information about this song * @returns {Promise<string|Discord.MessageEmbed>} */ showInfo() { return Promise.resolve("This isn't a real song.") } /** * @returns {Promise<string>} */ async getLyrics() { const picked = common.genius.pickApart(this) if (!picked.artist || !picked.title) return null let lyrics try { lyrics = await common.genius.getLyrics(picked.title, picked.artist) } catch { lyrics = null } return lyrics } /** * @param {string} message */ validationError(message) { console.error(`Song validation error: ${this.constructor.name} ${message}`) } validate() { ["id", "track", "title", "queueLine", "npUpdateFrequency"].forEach(key => { if (!this[key]) this.validationError(`unset ${key}`) }) ;["getProgress", "getRelated", "showRelated", "showInfo", "toObject"].forEach(key => { if (this[key] === Song.prototype[key]) this.validationError(`unset ${key}`) }) if (typeof (this.lengthSeconds) != "number" || this.lengthSeconds < 0) this.validationError("unset lengthSeconds") if (!this.thumbnail.src) this.validationError("unset thumbnail src") if (this.live === null) this.validationError("unset live") this.validated = true } /** * Code to run to prepare the song for playback, such as fetching its `track`. */ prepare() { return Promise.resolve() } /** * Code to run after the song was regenerated from resuming a queue */ resume() { return Promise.resolve() } /** * Clean up event listeners and such when the song is removed */ destroy() { return undefined } } class YouTubeSong extends Song { /** * @param {string} id * @param {string} title * @param {number} lengthSeconds * @param {string} [track] * @param {string} [uploader] */ constructor(id, title, lengthSeconds, track = null, uploader = undefined) { super() this.id = id this.thumbnail = { src: `https://i.ytimg.com/vi/${id}/mqdefault.jpg`, width: 320, height: 180 } this.title = title this.uploader = uploader this.lengthSeconds = lengthSeconds /** @type {string} */ // the vscode type checker is dumb, it would seem this.track = track || "!" this.queueLine = `**${this.title}** (${common.prettySeconds(this.lengthSeconds)})` this.npUpdateFrequency = 5000 this.typeWhileGetRelated = true this.live = false this.related = new utils.AsyncValueCache( () => { return c(`${this.getInvidiousOrigin()}/api/v1/videos/${this.id}`).send().then(async data => { const json = await data.json() this.typeWhileGetRelated = false return json.recommendedVideos.filter(v => v.lengthSeconds > 0).slice(0, 10) }) }) // eslint-disable-next-line require-await this.prepareCache = new utils.AsyncValueCache(async () => { if (this.track == "!") { return common.searchYouTube(this.id, this.queue.voiceChannel.rtcRegion).then(tracks => { if (!tracks[0]) this.error = `No results for ID ${this.id}` else if (tracks[0] && !tracks[0].track) this.error = `Missing track for ID ${this.id}` else { this.track = tracks[0].track if (tracks[0].info) this.uploader = tracks[0].info.author } }).catch(message => { this.error = message }) } }) this.validate() } toObject() { return { class: "YouTubeSong", id: this.id, title: this.title, lengthSeconds: this.lengthSeconds, track: this.track, uploader: this.uploader } } /** * @param {number} time milliseconds * @param {boolean} paused */ getProgress(time, paused) { const max = this.lengthSeconds const rightTime = common.prettySeconds(max) if (time > max) time = max const leftTime = common.prettySeconds(time) const bar = utils.progressBar(18, time, max, paused ? " [PAUSED] " : "") return `\`[ ${leftTime} ${bar} ${rightTime} ]\`` } async getRelated() { const related = await this.related.get().catch(() => []) return related.map(v => new YouTubeSong(v.videoId, v.title, v.lengthSeconds)) } showRelated() { return this.related.get().then(related => { if (related.length) { return new Discord.MessageEmbed() .setTitle("Related content from YouTube") .setDescription( related.map((v, i) => `${i + 1}. **${Discord.Util.escapeMarkdown(v.title)}** (${common.prettySeconds(v.lengthSeconds)})` + `\n — ${v.author}` ) ) .setFooter("Play one of these? &music related play <number>, or &m rel p <number>") .setColor(constants.standard_embed_color) } else { return "No related content available for the current song." } }).catch(() => { this.typeWhileGetRelated = false return `Invidious didn't return valid data.\ \n<${this.getInvidiousOrigin()}/api/v1/videos/${this.id}>\ \n<${this.getInvidiousOrigin()}/v/${this.id}>\ \n<https://youtu.be/${this.id}>` }) } getInvidiousOrigin() { return common.nodes.getByID(this.queue.nodeID).invidious_origin } showLink() { return this.showInfo() } showInfo() { return Promise.resolve(`https://www.youtube.com/watch?v=${this.id}`) } prepare() { return this.prepareCache.get() } resume() { return Promise.resolve() } destroy() { return undefined } } class FriskySong extends Song { /** * @param {string} station * @param {any} [data] */ constructor(station, data = {}) { super() this.station = station if (!stationData.has(this.station)) throw new Error(`Unsupported station: ${this.station}`) this.stationData = stationData.get(this.station) this.id = `frisky/${this.station}` // designed for error reporting this.thumbnail = { src: constants.frisky_placeholder, width: 320, height: 180 } this.title = this.stationData.title this.queueLine = `**${this.stationData.queue}** (LIVE)` if (data.track) this.track = data.track else { const url = this.station === "chill" ? this.stationData.url : this.stationData.beta_url this.track = encoding.encode({ flags: 1, version: 2, title: "Frisky Radio", author: "Feeling Frisky?", length: BigInt(0), identifier: url, isStream: true, uri: url, source: "http", position: BigInt(0) }) } this.lengthSeconds = 0 this.npUpdateFrequency = 15000 this.typeWhileGetRelated = false this.noPauseReason = "You can't pause live radio." this.live = true this.friskyStation = frisky.managers.stream.stations.get(this.stationData.client_name) this.stationInfoGetter = new utils.AsyncValueCache( /** * @returns {Promise<import("frisky-client/lib/Stream")>} */ () => new Promise((resolve, reject) => { let attempts = 0 const attempt = () => { const retry = (reason) => { if (attempts < 5) { setTimeout(() => { attempt() }, 1000) } else { reject(reason) } } attempts++ const index = this.friskyStation.findNowPlayingIndex() if (index == null) return retry("Current item is unknown") const stream = this.friskyStation.getSchedule()[index] if (!stream) return retry("Current stream not available") if (!stream.mix) return retry("Current mix not available") if (!stream.mix.data) return retry("Current mix data not available") const episode = stream.mix.episode if (!episode) return retry("Current episode not available") if (!episode.data) return retry("Current episode data not available") // console.log("Retrieved Frisky station data in "+(Date.now()-time)+"ms") return resolve(stream) } attempt() }) ) this._filledBarOffset = 0 this.validate() } toObject() { return { class: "FriskySong", station: this.station, track: this.track } } getRelated() { return Promise.resolve([]) } showRelated() { return Promise.resolve("Try the other stations on Frisky Radio! `&frisky`, `&frisky deep`, `&frisky chill`") } showLink() { return this.stationInfoGetter.get().then(stream => { return `https://beta.frisky.fm/mix/${stream.mix.id}` }).catch(() => "https://beta.frisy.fm") } showInfo() { return this.stationInfoGetter.get().then(stream => { const mix = stream.mix const stationCase = this.station[0].toUpperCase() + this.station.slice(1).toLowerCase() let percentPassed = Math.floor(((-stream.getTimeUntil()) / (stream.data.duration * 1000)) * 100) if (percentPassed < 0) percentPassed = 0 if (percentPassed > 100) percentPassed = 100 const embed = new Discord.MessageEmbed() .setColor(constants.standard_embed_color) .setTitle(`FRISKY: ${mix.data.title}`) .setURL(`https://beta.frisky.fm/mix/${mix.id}`) .addFields({ name: "Details", value: utils.tableifyRows( [ ["Episode", `${mix.data.title} / [view](https://beta.frisky.fm/mix/${mix.id})`], ["Show", `${mix.data.title.split(" - ")[0]} / [view](https://beta.frisky.fm/shows/${mix.data.show_id.id})`], ["Genre", mix.data.genre.join(", ")], ["Station", stationCase], ["Schedule", `started ${utils.shortTime(-stream.getTimeUntil(), "ms", ["d", "h", "m"])} ago, ${utils.shortTime(stream.getTimeUntil() + stream.data.duration * 1000, "ms", ["d", "h", "m"])} remaining (${percentPassed}%)`] ], ["left", ""], () => "`" ) }) if (mix.episode) { embed.setThumbnail(this.thumbnail.src) } if (mix.data.track_list && mix.data.track_list.length) { let trackList = mix.data.track_list .slice(0, 6) .map(track => `${track.artist} - ${track.title}`) .join("\n") const hidden = mix.data.track_list.length - 6 if (hidden > 0) trackList += `\n_and ${hidden} more..._` embed.addFields({ name: "Track list", value: trackList }) } return embed }).catch(reason => { console.error(reason) return "Unfortunately, we failed to retrieve information about the current song." }) } /** * @param {number} time */ getProgress(time) { const part = "= ⋄ ==== ⋄ ===" const fragment = part.substr(7 - this._filledBarOffset, 7) const bar = `${fragment.repeat(3)}` // SC: ZWSP x 2 this._filledBarOffset++ if (this._filledBarOffset >= 7) this._filledBarOffset = 0 // eslint-disable-next-line no-irregular-whitespace return `\`[ ${common.prettySeconds(time)} ​${bar}​ LIVE ]\`` // SC: ZWSP x 2 } async prepare() { if (!this.bound) { this.bound = this.stationUpdate.bind(this) this.friskyStation.events.addListener("changed", this.bound) await this.stationUpdate() } return Promise.resolve() } stationUpdate() { this.stationInfoGetter.clear() return this.stationInfoGetter.get().then(stream => { const mix = stream.mix // console.log(mix) this.title = mix.data.title this.thumbnail.src = mix.episode.data.album_art.url this.thumbnail.width = mix.episode.data.album_art.image_width this.thumbnail.height = mix.episode.data.album_art.image_height if (this.queue) { const index = this.queue.songs.indexOf(this) if (index !== -1) ipc.replier.sendSongUpdate(this.queue, this, index) } }).catch(reason => { console.error(reason) }) } resume() { return this.prepare() } destroy() { if (this.bound) this.friskyStation.events.removeListener("changed", this.bound) } } class SoundCloudSong extends Song { /** * @param {import("../../typings").LavalinkInfo} data * @param {string} track */ constructor(data, track) { super() this.title = data.title this.track = track this.artist = data.author this.lengthSeconds = Math.floor(data.length / 1000) this.queueLine = `**${this.title}** (${common.prettySeconds(this.lengthSeconds)})` this.npUpdateFrequency = 5000 this.error = "" this.typeWhileGetRelated = false this.trackNumber = data.identifier.match(/soundcloud:tracks:(\d+)/)[1] this.id = `sc/${this.trackNumber}` this.live = data.isStream || false this.thumbnail = { src: constants.soundcloud_placeholder, width: 616, height: 440 } this.uri = data.uri this.validate() } /** * @param {number} time milliseconds * @param {boolean} paused */ getProgress(time, paused) { const max = this.lengthSeconds const rightTime = common.prettySeconds(max) if (time > max) time = max const leftTime = common.prettySeconds(time) const bar = utils.progressBar(18, time, max, paused ? " [PAUSED] " : "") return `\`[ ${leftTime} ${bar} ${rightTime} ]\`` } getRelated() { return Promise.resolve([]) } showRelated() { return Promise.resolve("Try finding related songs on SoundCloud.") } showLink() { return this.showInfo() } showInfo() { return Promise.resolve(this.uri) } toObject() { return { class: "SoundCloudSong", id: this.id, trackNumber: this.trackNumber, title: this.title, lengthSeconds: this.lengthSeconds, track: this.track, uri: this.uri, live: this.live } } getState() { return Object.assign(super.getState(), { trackNumber: this.trackNumber }) } } // @ts-ignore class SpotifySong extends YouTubeSong { /** * @param {import("../../typings").SpotifyTrack & { track?: string, youtubeID?: string }} data */ constructor(data) { super(data.youtubeID || "!", data.name, Math.floor(data.duration_ms / 1000)) this.trackNumber = data.track_number this.live = false this.thumbnail = data.album && data.album.images[0] ? { src: data.album.images[0].url, width: data.album.images[0].width, height: data.album.images[0].height } : { src: constants.spotify_placeholder, width: 386, height: 386 } this.uri = data.uri this.typeWhileGetRelated = false this.related = [] this.artist = data.artists[0].name // eslint-disable-next-line require-await this.prepareCache = new utils.AsyncValueCache(async () => { if (this.id == "!" || this.track == "!") { return common.searchYouTube(`${this.artist} - ${this.title}`, this.queue.voiceChannel.rtcRegion).then(tracks => { if (!tracks[0]) this.error = `No results for ${this.title}` let decided = tracks[0] const found = tracks.find(item => item.info && item.info.author.includes("- Topic")) if (found) decided = found if (decided && decided.track) { this.id = decided.info.identifier this.lengthSeconds = Math.round(decided.info.length / 1000) this.queueLine = `**${this.title}** (${common.prettySeconds(this.lengthSeconds)})` this.track = decided.track ipc.replier.sendSongUpdate(this.queue, this, this.queue.songs.indexOf(this)) } else this.error = `Missing track for ${this.title}` }).catch(message => { this.error = message }) } }) this.validate() } toObject() { return { class: "SpotifySong", trackNumber: this.trackNumber, durationMS: this.lengthSeconds * 1000, lengthSeconds: this.lengthSeconds, uploader: this.artist, title: this.title, uri: this.uri, artist: this.artist, id: this.id, track: this.track } } getRelated() { return Promise.resolve([]) } showRelated() { return Promise.resolve("Try finding related songs on Spotify.") } showLink() { const ID = this.uri.match(/spotify:track:([\d\w]+)/)[1] return Promise.resolve(`https://open.spotify.com/track/${ID}`) } async showInfo() { const SP = await this.showLink() const YT = await super.showInfo() return Promise.resolve(`${SP}\n${YT}`) } prepare() { return this.prepareCache.get() } } class ExternalSong extends Song { /** * @param {string} link */ constructor(link) { super() const to = new URL(link) let name const pathnamereg = /\/?(\w+)\.\w+/ if (!to.pathname.match(pathnamereg)) name = "Unknown Track" else name = to.pathname.match(pathnamereg)[1] this.title = entities.decodeHTML(name.replace(/_/g, " ")) this.live = true this.thumbnail = { src: constants.local_placeholder, width: 512, height: 512 } this.uri = link this.track = "!" this.lengthSeconds = 0 this.npUpdateFrequency = 15000 this.queueLine = `**${this.title}** (LIVE)` this.typeWhileGetRelated = false this.noPauseReason = "You can't pause external audio." this.id = String(Date.now()) this._filledBarOffset = 0 this.validate() } async prepare() { let info try { info = await common.getTracks(this.uri, this.queue.voiceChannel.rtcRegion) } catch { this.error = `Missing track for ${this.title}` return } if (!Array.isArray(info) || !info || !info[0] || !info[0].track) this.error = `Missing track for ${this.title}` this.track = info[0].track if (info[0].info.isSeekable) { this.live = false this.lengthSeconds = Math.round(info[0].info.length / 1000) this.queueLine = `**${this.title}** (${common.prettySeconds(this.lengthSeconds)})` this.noPauseReason = undefined ipc.replier.sendSongUpdate(this.queue, this, this.queue.songs.indexOf(this)) } } toObject() { return { title: this.title, class: "ExternalSong", lengthSeconds: this.lengthSeconds, uri: this.uri, id: this.id, track: this.track } } getRelated() { return Promise.resolve([]) } showRelated() { return Promise.resolve("Try finding related songs on other websites") } showLink() { return Promise.resolve(this.uri) } showInfo() { return this.showLink() } /** * @param {number} time * @param {boolean} paused */ getProgress(time, paused) { let bar const leftTime = common.prettySeconds(time) const rightTime = this.live ? "LIVE" : common.prettySeconds(this.lengthSeconds) if (this.live) { const part = "= ⋄ ==== ⋄ ===" const fragment = part.substr(7 - this._filledBarOffset, 7) bar = `${fragment.repeat(3)}` // SC: ZWSP x 2 this._filledBarOffset++ if (this._filledBarOffset >= 7) this._filledBarOffset = 0 } else { if (time > this.lengthSeconds) time = this.lengthSeconds bar = utils.progressBar(18, time, this.lengthSeconds, paused ? " [PAUSED] " : "") } return `\`[ ${leftTime} ​${bar}​ ${rightTime} ]\`` // SC: ZWSP x 2 } resume() { return this.prepare() } } class ListenMoeSong extends Song { /** * @param {"jp" | "kp"} station */ constructor(station) { super() this.station = station this.stationData = passthrough.listenMoe[station] this.live = true this.lengthSeconds = this.stationData.nowPlaying.duration this.id = this._id this.title = this.stationData.nowPlaying.title this.queueLine = `**${this.title}** (${this.lengthSeconds ? common.prettySeconds(this.lengthSeconds) : "LIVE"})` this.thumbnail = { src: constants.listen_moe_placeholder, width: 64, height: 64 } this.uri = this.stationData.Constants.STREAM_URLS[station === "jp" ? "JPOP" : "KPOP"].opus this.track = encoding.encode({ flags: 1, version: 2, title: "Listen.moe", author: "Delivering the best JPOP and KPOP music around!", length: BigInt(0), identifier: this.uri, isStream: true, uri: this.uri, source: "http", position: BigInt(0) }) this.npUpdateFrequency = 15000 this.typeWhileGetRelated = false this.noPauseReason = "You can't pause live audio." this._filledBarOffset = 0 this.validate() } get _id() { return String((this.stationData.nowPlaying.albums && this.stationData.nowPlaying.albums[0] ? (this.stationData.nowPlaying.albums[0].id || this.stationData.nowPlaying.id) : this.stationData.nowPlaying.id)) } prepare() { if (!this.bound) { this.bound = this.stationUpdate.bind(this) this.stationData.on("trackUpdate", this.bound) } return Promise.resolve() } toObject() { return { class: "ListenMoeSong", station: this.station, lengthSeconds: this.lengthSeconds, uri: this.uri, id: this.id, track: this.track } } getRelated() { return Promise.resolve([]) } showRelated() { return Promise.resolve("Try the other stations on <https://listen.moe>") } showLink() { return Promise.resolve(`https://listen.moe/albums/${this.id}`) } async showInfo() { const link = await this.showLink() return `https://listen.moe\n${link}` } /** * @param {number} fallback */ getProgress(fallback) { let time if (this.stationData.lastTrackStartedAt) time = Math.floor((Date.now() - this.stationData.lastTrackStartedAt) / 1000) else time = fallback const part = "= ⋄ ==== ⋄ ===" const fragment = part.substr(7 - this._filledBarOffset, 7) let bar if (!this.lengthSeconds) bar = `${fragment.repeat(3)}` // SC: ZWSP x 2 else { if (time > this.lengthSeconds) time = this.lengthSeconds bar = utils.progressBar(18, time, this.lengthSeconds) } this._filledBarOffset++ if (this._filledBarOffset >= 7) this._filledBarOffset = 0 return `\`[ ${common.prettySeconds(time)} ​${bar}​ ${this.lengthSeconds ? common.prettySeconds(this.lengthSeconds) : "LIVE"} ]\`` // SC: ZWSP x 2 } resume() { return this.prepare() } destroy() { if (this.bound) this.stationData.removeListener("trackUpdate", this.bound) } /** * @param {import("listensomemoe/dist/Types").Track} track */ stationUpdate(track) { this.title = track.title this.lengthSeconds = track.duration this.id = this._id this.queueLine = `**${this.title}** (${this.lengthSeconds ? common.prettySeconds(this.lengthSeconds) : "LIVE"})` ipc.replier.sendSongUpdate(this.queue, this, this.queue.songs.indexOf(this)) } } class NewgroundsSong extends Song { /** * @param {{ href: string, author: string, title: string, id: number, mp3URL: string, duration: number, track?: string }} data */ constructor(data) { super() this.title = data.title this.author = data.author this.uri = data.href this.streamURL = data.mp3URL this.id = String(data.id) this.live = false this.lengthSeconds = data.duration this.thumbnail = { src: constants.newgrounds_placeholder, width: 1200, height: 1200 } this.track = data.track || "!" this.queueLine = `**${this.title}** (${common.prettySeconds(this.lengthSeconds)})` this.npUpdateFrequency = 5000 this.error = "" this.typeWhileGetRelated = false this.validate() } toObject() { return { class: "NewgroundsSong", href: this.uri, title: this.title, author: this.author, id: this.id, mp3URL: this.streamURL, duration: this.lengthSeconds, track: this.track } } getRelated() { return Promise.resolve([]) } showRelated() { return Promise.resolve("Try finding related songs on NewGrounds") } async prepare() { if (this.track && this.track != "!") return let data try { data = await common.getTracks(this.streamURL, this.queue.voiceChannel.rtcRegion) } catch { this.error = `Missing track for ${this.title}` return } if (!Array.isArray(data) || !data || !data[0] || !data[0].track) this.error = `Missing track for ${this.title}` this.track = data[0].track } showLink() { return Promise.resolve(this.uri) } showInfo() { return this.showLink() } /** * @param {number} time milliseconds * @param {boolean} paused */ getProgress(time, paused) { const max = this.lengthSeconds const rightTime = common.prettySeconds(max) if (time > max) time = max const leftTime = common.prettySeconds(time) const bar = utils.progressBar(18, time, max, paused ? " [PAUSED] " : "") return `\`[ ${leftTime} ${bar} ${rightTime} ]\`` } } // Just for name parity class TwitterSong extends Song { /** * @param {{ title: string, uri: string, displayURI: string }} data */ constructor(data) { super() this.track = "!" this.title = data.title this.uri = data.uri this.displayURI = data.displayURI this.live = false this.lengthSeconds = 0 const match = this.displayURI.match(/\/status\/(\d+)/) if (match && match[1]) this.id = `tw/${match[1]}` else this.id = `tw/${this.displayURI}` this.thumbnail = { src: constants.twitter_placeholder, width: 1066, height: 877 } this.queueLine = `**${this.title}** (LOADING)` this.npUpdateFrequency = 5000 this.error = "" this.typeWhileGetRelated = false this.validate() } toObject() { return { class: "TwitterSong", uri: this.uri, displayURI: this.displayURI, title: this.title, id: this.id, lengthSeconds: this.lengthSeconds, track: this.track } } getRelated() { return Promise.resolve([]) } showRelated() { return Promise.resolve("Try finding related Tweets on Twitter") } async prepare() { if (this.track && this.track != "!") return let data try { data = await common.getTracks(this.uri, this.queue.voiceChannel.rtcRegion) } catch { this.error = `Missing track for ${this.title}` return } if (!Array.isArray(data) || !data || !data[0] || !data[0].track) this.error = `Missing track for ${this.title}` this.track = data[0].track this.lengthSeconds = Math.round(data[0].info.length / 1000) this.queueLine = `**${this.title}** (${common.prettySeconds(this.lengthSeconds)})` ipc.replier.sendSongUpdate(this.queue, this, this.queue.songs.indexOf(this)) } showLink() { return Promise.resolve(this.displayURI) } showInfo() { return this.showLink() } /** * @param {number} time milliseconds * @param {boolean} paused */ getProgress(time, paused) { const max = this.lengthSeconds const rightTime = common.prettySeconds(max) if (time > max) time = max const leftTime = common.prettySeconds(time) const bar = utils.progressBar(18, time, max, paused ? " [PAUSED] " : "") return `\`[ ${leftTime} ${bar} ${rightTime} ]\`` } } // @ts-ignore class iTunesSong extends YouTubeSong { /** * @param {import("../../typings").iTunesSearchResult} data */ constructor(data) { super("!", data.trackName, Math.floor(data.trackTimeMillis / 1000)) this.live = false this.id = `appl/${data.trackId}` this.ytID = "!" this.related = [] this.artist = data.artistName this.trackViewURL = data.trackViewUrl this.thumbnail = { src: data.artworkUrl100, width: 100, height: 100 } this.queueLine = `**${this.title}** (${common.prettySeconds(this.lengthSeconds)})` this.npUpdateFrequency = 5000 this.error = "" this.typeWhileGetRelated = false // eslint-disable-next-line require-await this.prepareCache = new utils.AsyncValueCache(async () => { if (this.ytID == "!" || this.track == "!") { return common.searchYouTube(`${this.artist} - ${this.title}`, this.queue.voiceChannel.rtcRegion).then(tracks => { if (!tracks[0]) this.error = `No results for ${this.title}` let decided = tracks[0] const found = tracks.find(item => item.info && item.info.author.includes("- Topic")) if (found) decided = found if (decided && decided.track) { this.ytID = decided.info.identifier this.lengthSeconds = Math.round(decided.info.length / 1000) this.queueLine = `**${this.title}** (${common.prettySeconds(this.lengthSeconds)})` this.track = decided.track ipc.replier.sendSongUpdate(this.queue, this, this.queue.songs.indexOf(this)) } else this.error = `Missing track for ${this.title}` }).catch(message => { this.error = message }) } }) this.validate() } toObject() { return { class: "iTunesSong", trackName: this.title, trackTimeMillis: this.lengthSeconds * 1000, lengthSeconds: this.lengthSeconds, artistName: this.artist, title: this.title, trackViewURL: this.trackViewURL, trackId: this.id, track: this.track, artworkUrl100: this.thumbnail.src, id: this.id, uploader: this.artist } } getRelated() { return Promise.resolve([]) } showRelated() { return Promise.resolve("Try finding related songs on iTunes.") } showLink() { return Promise.resolve(this.trackViewURL) } async showInfo() { const iT = await this.showLink() const YT = `https://www.youtube.com/watch?v=${this.ytID}` return Promise.resolve(`${iT}\n${YT}`) } prepare() { return this.prepareCache.get() } } /** * @param {{ track: string, info: { identifier: string, title: string, length: number, author: string } }} data */ function makeYouTubeSongFromData(data) { return new YouTubeSong(data.info.identifier, data.info.title, Math.round(data.info.length / 1000), data.track || null, data.info.author) } /** * @param {string} trackNumber * @param {string} title * @param {number} lengthSeconds * @param {boolean} live * @param {string} uri * @param {string} track */ function makeSoundCloudSong(trackNumber, title, lengthSeconds, live, uri, track) { // @ts-ignore return new SoundCloudSong({ identifier: `soundcloud:tracks:${trackNumber}`, title: title, length: lengthSeconds * 1000, isStream: live, uri: uri }, track) } /** * @param {import("../../typings").SpotifyTrack} data * @param {string} [id] * @param {string} [track] */ function makeSpotifySong(data, id = undefined, track = undefined) { if (id) Object.assign(data, { youtubeID: id }) if (track) Object.assign(data, { track: track }) return new SpotifySong(data) } /** * @param {string} link */ function makeExternalSong(link) { return new ExternalSong(link) } /** * @param {"jp" | "kp"} station */ function makeListenMoeSong(station) { return new ListenMoeSong(station) } /** * @param {{ href: string, author: string, title: string, id: number, mp3URL: string, duration: number, track?: string }} data */ function makeNewgroundsSong(data) { return new NewgroundsSong(data) } /** * @param {{ title: string, uri: string, displayURI: string }} data */ function makeTwitterSong(data) { return new TwitterSong(data) } /** * @param {import("../../typings").iTunesSearchResult} data */ function makeiTunesSong(data) { return new iTunesSong(data) } module.exports.makeYouTubeSongFromData = makeYouTubeSongFromData module.exports.Song = Song module.exports.YouTubeSong = YouTubeSong module.exports.FriskySong = FriskySong module.exports.SoundCloudSong = SoundCloudSong module.exports.makeSoundCloudSong = makeSoundCloudSong module.exports.SpotifySong = SpotifySong module.exports.makeSpotifySong = makeSpotifySong module.exports.ExternalSong = ExternalSong module.exports.makeExternalSong = makeExternalSong module.exports.ListenMoeSong = ListenMoeSong module.exports.makeListenMoeSong = makeListenMoeSong module.exports.NewgroundsSong = NewgroundsSong module.exports.makeNewgroundsSong = makeNewgroundsSong module.exports.TwitterSong = TwitterSong module.exports.makeTwitterSong = makeTwitterSong module.exports.iTunesSong = iTunesSong module.exports.makeiTunesSong = makeiTunesSong
JavaScript
CL
2358e59db0983058e20c22fec5291e887abe581e3dce97fb62f1b551d23aa92d
import { func } from 'prop-types'; import { useState } from 'react'; /** * @description Replicated functionality of `constructor(props)` * from class components to be used in functional components * @param {Function} callback - the function to be called inside constructor */ const useConstructor = (callback = () => {}) => { const [hasBeenCalled, setHasBeenCalled] = useState(false); if (hasBeenCalled) return; callback(); setHasBeenCalled(true); }; useConstructor.propTypes = { callback: func.isRequired, }; export default useConstructor;
JavaScript
CL
06db8078d9ba5f3564f581a6c5b9a32099fae3d6ecd9c484e62d0568d68d3cca
/*! * Copyright 2014 Apereo Foundation (AF) Licensed under the * Educational Community 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://opensource.org/licenses/ECL-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. */ define(['jquery', 'oae.core', 'jquery.fileupload', 'jquery.iframe-transport', 'jquery.jeditable'], function($, oae) { return function(uid) { ////////////////////// // WIDGET VARIABLES // ////////////////////// // The widget container var $rootel = $('#' + uid); // Variable that keeps track of the selected files to upload var selectedFiles = []; var selectedFilesSize = 0; // Variable that keeps track of the selected visibility for the files to upload var visibility = null; // Generate a widget ID for the new instance of the `setpermissions` widget. This widget ID // will be used in the event communication between this widget and the `setpermissions` widget. var setPermissionsId = oae.api.util.generateId(); // IE9 and below don't support XHR file uploads and we fall back to iframe transport var useIframeTransport = !$.support.xhrFileUpload && !$.support.xhrFormDataFileUpload; // Variable that keeps track of the current context var contextData = null; /////////////// // UTILITIES // /////////////// /** * Reset the state of the widget when the modal dialog has been closed */ var reset = function() { // Unbind the setpermissions handler $(document).off('oae.setpermissions.changed.' + setPermissionsId); // Reset the setpermissions content $('#upload-permissions-container', $rootel).html(''); // Reset the selected Files list and total size selectedFiles = []; selectedFilesSize = 0; // Reset the fileupload form $('form', $rootel)[0].reset(); // Hide all steps $('#upload-modal .modal-body > div', $rootel).hide(); // Show the first step $('#upload-modal .modal-body > div:first-child', $rootel).show(); $('#upload-modal > .modal-footer', $rootel).show(); // Reset controls $('#upload-modal *').prop('disabled', false); $('#upload-upload', $rootel).hide(); $('#upload-permissions', $rootel).hide(); // Reset the progress bar $('.progress', $rootel).hide(); updateProgress(0); // Remove the focus style on the Browse button $('#upload-browse-button', $rootel).removeClass('oae-focus'); }; /** * Filters selected files to include only those that can be uploaded * * @param {Object[]} files Array of file objects to be considered for uploading * @return {Object[]} Array after removing invalid files */ var filterFiles = function(files) { return $.grep(files, function(file) { // If using iframe transport, all we can consider is the name since // browsers that require iframe (IE9) don't report size if (useIframeTransport) { return file.name; } // In other cases, we can look at size as well return file.size && file.name; }); }; /** * Adds selected files to the list of files to upload. Filters out folders and size 0 files * * @param {Object} data The data object containing information on the files that are selected for upload * @return {Number} Number of valid files added */ var addToSelected = function(data) { // Restrict to valid files only var files = filterFiles(data.files); $.each(files, function(index, file) { // Add the file to the queue selectedFiles.push({ 'displayName': file.name, 'description': '', 'file': file, 'resourceType': 'content', 'resourceSubType': 'file' }); // Update total size if available selectedFilesSize += file.size ? file.size : 0; }); return files.length; }; /** * Updates the progress indicator * * @param {Number} progress Number between 0 and 100 indicating the upload progress */ var updateProgress = function(progress) { $('.progress-bar', $rootel).css('width', progress + '%').attr('aria-valuenow', progress); $('.progress-bar .sr-only', $rootel).text(progress + '%'); }; /** * Saves the edited file name to the corresponding item in the array of selected files * * @param {String} value The new value for the item * @return {String} The value to show in the editable field after editing completed */ var editableSubmitted = function(value) { value = $.trim(value); var prevValue = this.revert; var $listItem = $(this).parents('li'); // If no name has been entered, we fall back to the previous value if (!value) { return prevValue; } else { var fileIndex = $('#upload-selected-container li').index($listItem); selectedFiles[fileIndex].displayName = value; return value; } }; /** * Shows a success or failure notification when the upload has completed. * * @param {Number} errCount The number of errors that occurred during the upload */ var showCompleteNotification = function(errCount) { // Render and show the notification var notificationTitle = oae.api.util.template().render($('#upload-notification-title-template', $rootel), { 'context': contextData, 'errCount': errCount, 'files': selectedFiles }); var notificationBody = oae.api.util.template().render($('#upload-notification-body-template', $rootel), { 'context': contextData, 'errCount': errCount, 'files': selectedFiles }); oae.api.util.notification(notificationTitle, notificationBody, errCount ? 'error' : 'success'); // Hide the modal when there are no upload errors if (!errCount) { $('#upload-modal', $rootel).modal('hide'); } }; ///////////////////// // VIEW MANAGEMENT // ///////////////////// /** * When files are dropped onto an element that's designated as a drop zone, we skip the first step of * selecting files and proceed with showing the files that were dropped * * @param {Object} dropData The data received from dropping files onto the container * @return {Number} Number of valid files shown */ var showDropped = function(dropData) { // Since we already have the selected files we skip to the next step setUpUploadField(); // Add the dropped files to the fileupload field $('#upload-input', $rootel).fileupload('add', dropData.data.files); // Add the selected files to the internal list of selected files var filesShown = addToSelected(dropData.data); if (filesShown > 0) { // Ensure the overview is visible showOverview(); // Render the selected list renderSelected(); } return filesShown; }; /** * Shows the drop zone with browse button */ var showDropzone = function() { $('#upload-dropzone', $rootel).show(); }; /** * Shows the permissions widget to allow for updates in visiblity and members */ var showPermissions = function() { // Hide all containers $('#upload-modal .modal-body > div', $rootel).hide(); $('#upload-modal .modal-content > .modal-footer', $rootel).hide(); // Show the permissions container $('#upload-modal .modal-body > div#upload-permissions-container', $rootel).show(); $('#upload-upload', $rootel).hide(); }; /** * Shows an overview of the selected files */ var showOverview = function() { // Hide all containers $('#upload-modal .modal-body > div', $rootel).hide(); // Show the overview container $('#upload-modal .modal-content > .modal-footer', $rootel).show(); $('#upload-modal .modal-body > div#upload-overview-container', $rootel).show(); $('#upload-permissions', $rootel).show(); $('#upload-upload', $rootel).show(); }; /** * Renders a list of the selected files to upload */ var renderSelected = function() { oae.api.util.template().render('#upload-selected-template', { 'files': selectedFiles, 'displayOptions': { 'metadata': false } }, $('#upload-selected-container', $rootel)); // Initiate the widget that will deal with permission management setUpSetPermissions(); // Give focus to the first item in the list $('#upload-selected-container li:first-child', $rootel).focus(); // Apply jEditable for inline editing of file names $('.jeditable-field', $rootel).editable(editableSubmitted, { 'onblur': 'submit', 'select' : true }); // Apply jQuery Tooltip to the file title field to show that the fields are editable. // The custom template adds ARIA accessibility to the default bootstrap functionality $('[rel="tooltip"]', $rootel).each(function() { var tooltipId = oae.api.util.generateId(); $(this).attr('aria-describedby', tooltipId); $(this).tooltip({ 'template': '<div class="tooltip" role="tooltip" id="' + tooltipId + '"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' }); }); }; //////////////////// // INITIALIZATION // //////////////////// /** * Reset the widget when the modal dialog is closed */ var setUpReset = function() { $('#upload-modal').on('hidden.bs.modal', function(ev) { // Bootstrap will send out a `hidden` event when certain components are destroyed. // We can only reset the widget when the modal is closed though. // e.g. `$('[rel="tooltip"]', $rootel).tooltip('destroy');` if ($(ev.target).hasClass('modal')) { reset(); } }); }; /** * Load the `setpermissions` widget into this widget. That widget will take care of permission * management (visibility + sharing) of the selected files */ var setUpSetPermissions = function() { // Remove the previous `setpermissions` widget var $setPermissionsContainer = $('#upload-permissions-container', $rootel); $setPermissionsContainer.html(''); // When the current context is the current user, the configured default tenant visibility for files // will be used as the default visibility. Otherwise, the visibility of the current context will be // used as the default visibility if (contextData.id === oae.data.me.id) { visibility = oae.api.config.getValue('oae-content', 'visibility', 'files'); } else { visibility = contextData.visibility; } // Event that will be triggered when permission changes have been made in the `setpermissions` widget $(document).on('oae.setpermissions.changed.' + setPermissionsId, function(ev, data) { // Update visibility for files visibility = data.visibility; // Update the members of the selected files $.each(selectedFiles, function(index, file) { file.viewers = _.chain(data.selectedPrincipalItems) .filter(function(selectedPrincipalItem) { return (selectedPrincipalItem.id !== oae.data.me.id); }) .pluck('shareId') .value(); file.folders = _.pluck(data.selectedFolderItems, 'id'); }); // Add the permissions summary $('#upload-permissions', $rootel).html(data.summary); // Switch back to the overview showOverview(); }); // Event that will be triggered when permission changes have been cancelled $(document).on('oae.setpermissions.cancel.' + setPermissionsId, showOverview); // Always add the created files to the current user's library var preFill = [{ 'displayName': oae.api.i18n.translate('__MSG__MY_LIBRARY__'), 'id': oae.data.me.id, 'fixed': true }]; // If the current user is creating the files from within a group, // the group is added as a fixed item as well if (contextData.id !== oae.data.me.id) { preFill.push($.extend({'fixed': true}, contextData)); } // Load the `setpermissions` widget into its container oae.api.widget.insertWidget('setpermissions', setPermissionsId, $setPermissionsContainer, false, { 'count': selectedFiles.length, 'preFill': preFill, 'type': 'file', 'visibility': visibility }); }; /** * Remove a selected file from the list and reset the widget when no files remain */ var setUpDelete = function() { $rootel.on('click', '.upload-trash', function(ev) { // Get the index of the list item var $listItem = $(this).parents('li'); var fileIndex = $('#upload-selected-container li', $rootel).index($listItem); // Subtract the size of the file from the total selectedFilesSize -= selectedFiles[fileIndex].file.size; // This corresponds to the array from which we'll remove the selected file selectedFiles.splice(fileIndex, 1); // Also remove it from the UI $listItem.fadeOut(250, function() { $listItem.remove(); // If there are no files left reset the widget if (!selectedFiles.length) { reset(); setUpUploadField(); } }); }); }; /** * Initlializes the jQuery fileupload plugin on the upload form */ var setUpUploadField = function() { // Used to hold the size of the file being uploaded. var prevFile = false; // A progress event can be fired multiple times for the same file depending on the size of the file // We make the distinction between files in the events by looking at the size of the file in the event // If the size of prevFile is equal to the size of totalPrevFile that means that the event is still handling the same file // Usage is described in the `progress` handler below var totalPrevFile = 0; var totalUploaded = 0; var fileuploadOptions = { 'url': '/api/content/create', 'dropZone': $('#upload-dropzone', $rootel), 'forceIframeTransport': useIframeTransport, // This is mandatory for browsers that require the iframe transport (i.e., IE9) 'replaceFileInput': false, // Drop is fired when a user drops files on the dropzone 'drop': function(ev, data) { // Ensure at least one file is valid if (addToSelected(data) > 0) { showOverview(); renderSelected(); } else { oae.api.util.notification( oae.api.i18n.translate('__MSG__FILE_NOT_ADDED__', 'upload'), oae.api.i18n.translate('__MSG__PLEASE_SELECT_A_VALID_FILE_TO_UPLOAD__', 'upload'), 'error' ); } }, 'add': function() {/* Overriding `add` to avoid submitting the files on selection */}, // Change is fired when a user browses for files 'change': function(ev, data) { addToSelected(data); showOverview(); renderSelected(); }, 'progress': function(ev, data) { // The progress event can be sent out multiple times during the same file upload depending on the size of the file. // If the 'prevFile' variable is false, fill it up with the size of the first file that is uploaded // This check will only be true on the first progress event of the first file that's uploaded if (!prevFile) { prevFile = data.total; } // If the size of the previous file event is the same as the size of the current file event // it's assumed that this is the same file. In that case the 'loaded' is not added to the total loaded size if (prevFile === data.total) { totalPrevFile = data.loaded; // If the size is not the same it's assumed the plugin is handling a different file // and the size of the previous file is added to the total of all files } else { totalUploaded += prevFile; prevFile = data.total; totalPrevFile = data.loaded; } // Update the progress bar updateProgress(((totalUploaded + totalPrevFile) / selectedFilesSize) * 100); } }; $('#upload-input', $rootel).fileupload(fileuploadOptions); }; /** * Start the file upload process. This iterates over all selected files and uploads them one at * a time. Regular updates are provided in the form of a loading spinner icon and success or fail icon */ var setUpUploadHandling = function() { $('#upload-upload', $rootel).on('click', function() { var done = 0; var errCount = 0; // If we need an iframe for the upload, progress will probably not be supported if (!useIframeTransport) { // Show the progress bar when the upload starts $('.progress', $rootel).show(); } // Disable editing on upload // Note: the file input element can not be disabled, as that will cause IE9 // to drop it from the DOM and not submit its file content to the server $('#upload-modal *').not('input[type="file"]').prop('disabled', true); $('.jeditable-field', $rootel).editable('destroy'); $('[rel="tooltip"]', $rootel).tooltip('destroy'); // Lock the modal so it cannot be closed during upload $('#upload-modal', $rootel).modal('lock'); /** * Upload the actual files. Progress is shown for each individual file and * the progress bar is updated after each file upload. * * @param {Number} index The index of the file that's currently being uploaded */ var upload = function(index) { var file = selectedFiles[index]; if (file) { var $listItem = $($('#upload-selected-container li', $rootel)[index]); var $spinner = $listItem.find('.upload-progress'); var $ok = $listItem.find('.fa-check'); var $warning = $listItem.find('.fa-exclamation-triangle'); // Show the uploading animation and add focus to it so the browser scrolls $spinner.removeClass('hide').focus(); oae.api.content.createFile(file.displayName, file.description, visibility, $('#upload-input', $rootel), file.file, [], file.viewers, file.folders, function(error, data) { $spinner.addClass('hide'); if (!error) { $ok.show(); // Update the file object with the profile path of the content file.profilePath = data.profilePath; } else { $warning.show(); // Update the error count errCount++; } done++; if (done !== selectedFiles.length) { upload(done); } else { $(window).trigger('done.addcontent.oae'); // Unlock the modal $('#upload-modal', $rootel).modal('unlock'); // If we need an iframe for the upload, progress will probably not be supported if (!useIframeTransport) { updateProgress(100); } showCompleteNotification(errCount); } }); } }; upload(0); }); }; /** * Initialize the upload modal dialog */ var setUpUploadModal = function() { $(document).on('click', '.oae-trigger-upload', function() { oae.api.util.template().render($('#upload-body-template', $rootel), {'ios': oae.api.util.isIos()}, $('.modal-body', $rootel)); $('#upload-modal', $rootel).modal({ 'backdrop': 'static' }); showDropzone(); setUpUploadField(); }); // Defined `oae-dnd-upload` dropzones will trigger the `oae-trigger-upload` event when files // have been dropped. This is caught by the upload widget which shows the modal dialog and // renders the files into a list. $(document).on('oae.trigger.upload', function(ev, data) { // Non-null data indicates a pre-selected set of potential files has been provided if (data) { // Ensure at least one file is valid before continuing if (filterFiles(data.data.files).length > 0) { oae.api.util.template().render( $('#upload-body-template', $rootel), {'ios': oae.api.util.isIos()}, $('.modal-body', $rootel) ); $('#upload-modal', $rootel).modal({ 'backdrop': 'static' }); showOverview(); showDropped(data); // If no files are valid, show error notification } else { oae.api.util.notification( oae.api.i18n.translate('__MSG__FILE_NOT_ADDED__', 'upload'), oae.api.i18n.translate('__MSG__PLEASE_SELECT_A_VALID_FILE_TO_UPLOAD__', 'upload'), 'error' ); } // If no pre-selected set is provided, just show the modal } else { oae.api.util.template().render($('#upload-body-template', $rootel), { 'ios': oae.api.util.isIos() }, $('.modal-body', $rootel) ); $('#upload-modal', $rootel).modal({ 'backdrop': 'static' }); showDropzone(); setUpUploadField(); } }); // Binds the 'change' button that shows the setpermissions widget $rootel.on('click', '.setpermissions-change-permissions', showPermissions); // Receive the context information and cache it $(document).on('oae.context.send.upload', function(ev, ctx) { contextData = ctx; }); // Request the context information $(document).trigger('oae.context.get', 'upload'); }; setUpReset(); setUpUploadHandling(); setUpUploadModal(); setUpDelete(); }; });
JavaScript
CL
8ab2c2dfed8f0f16ecebd92baad90e7b81441887f69a36ee95e3d885bc28cf17
const gulp = require('gulp'); const webpack = require('gulp-webpack'); const sourcemaps = require('gulp-sourcemaps'); const babel = require('gulp-babel'); const concat = require('gulp-concat'); const uglify = require('gulp-uglify'); const rename = require('gulp-rename') const postcss = require('gulp-postcss'); const precss = require('precss'); const postcssfocus = require('postcss-focus') const autoprefixer = require('autoprefixer'); // const mqpacker = require('css-mqpacker'); const csswring = require('csswring'); const lost = require('lost'); const njRender = require('gulp-nunjucks-render'); const nj = njRender.nunjucks; const gm = require('gulp-gm'); const parallel = require('concurrent-transform'); const os = require('os'); const browserSync = require('browser-sync'); const reload = browserSync.reload; gulp.task('scripts', () => { return gulp.src('src/scripts/app.js') .pipe(webpack()) .pipe(sourcemaps.init()) .pipe(babel({ presets: ['es2015'] })) .pipe(rename('app.js')) .pipe(gulp.dest('dist')) .pipe(rename('app.min.js')) .pipe(uglify()) .pipe(sourcemaps.write('.')) .pipe(gulp.dest('dist')) .pipe(reload({stream:true})); }); gulp.task('vendor', () => { return gulp.src('src/scripts/vendor/**/*.js') .pipe(gulp.dest('dist/vendor')); }); gulp.task('htaccess', () => { return gulp.src('src/.htaccess') .pipe(gulp.dest('dist')); }); gulp.task('styles', () => { const processors = [ precss(), postcssfocus, lost, autoprefixer({browsers: ['last 2 versions']}), // mqpacker, csswring ]; return gulp.src('src/styles/styles.css') .pipe(postcss(processors)) .pipe(gulp.dest('dist')) }); gulp.task('markup', () => { nj.configure(['src/templates'], {watch: false}); return gulp.src('src/html/**/*.+(html|nj|nunjucks)') .pipe(njRender()) .pipe(gulp.dest('dist')); }); gulp.task('images', () => { return gulp.src('src/media/layout/**/*.+(gif|jpg|png|svg)') .pipe(gulp.dest('dist/images')); }); gulp.task('fonts', () => { return gulp.src('src/fonts/**/*') .pipe(gulp.dest('dist/fonts')); }); gulp.task('locations', () => { gulp.src('src/media/locations/**/*') .pipe(parallel( gm((tmp) => tmp.resize(900).quality(60)), os.cpus().length )) .pipe(gulp.dest('dist/images/locations')); }); gulp.task('watch', () => { gulp.watch('src/templates/**/*.+(html|nj|nunjucks)', ['markup', reload]); gulp.watch('src/html/**/*.+(html|nj|nunjucks)', ['markup', reload]); gulp.watch('src/styles/**/*.css', ['styles', reload]); gulp.watch(['src/scripts/**/*.js'], ['scripts', 'vendor', reload]); gulp.watch(['src/fonts/**/*'], ['fonts', reload]); gulp.watch(['src/media/layout/**/*.+(gif|jpg|png|svg)'], ['images', reload]); gulp.watch("*.html", reload); gulp.watch("src/.htaccess", ['htaccess', reload]); }); gulp.task('sync', () => { browserSync({ server: { baseDir: "./dist/" } }); }); gulp.task('server', ['markup', 'styles', 'fonts', 'images', 'sync', 'scripts', 'vendor', 'htaccess', 'watch']); gulp.task('default', ['markup', 'styles', 'fonts', 'images', 'scripts', 'vendor', 'htaccess']);
JavaScript
CL
36bd4d8c12238416191dbfda0e830529c8e355ae45aff2d1b4f88387a07bf3c0
var url = require('url'); var XRegExp = require('xregexp'); var extend = require('extend'); var core = require('../../../core').Core; var base = require('../../base').Base; module.exports = function(options) { return { /** * {@link qrs.md|See parent documentation} * @namespace */ reloadtask: { /** * @namespace * @memberOf reloadtask */ id: function(id) { return { /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask/{id} * * This method is generated * * @memberOf reloadtask.id * * @example * ```javascript * qrsApi.reloadtask.id(id).delete().then(function() { * console.log('done') * }) * ``` * * @returns {Promise} a promise resolving without a return value when the request is finished */ delete: function() { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask/' + id + '', method: 'DELETE' })); }, /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask/{id}?privileges={appendprivileges} * * This method is generated * * @memberOf reloadtask.id * * @example * ```javascript * qrsApi.reloadtask.id(id).get(appendprivileges).then(function(ReloadTask) { * console.log(ReloadTask) * }) * ``` * * @param {string=} appendprivileges the appendprivileges parameter * @returns {Promise.<ReloadTask>} a promise resolving to the response to the request */ get: function(appendprivileges) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask/' + id + '' + core.ifNotUndef(appendprivileges, '?privileges=' + appendprivileges, ''), method: 'GET' })); }, /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask/{id}?privileges={appendprivileges} * * This method is generated * * @memberOf reloadtask.id * * @example * ```javascript * qrsApi.reloadtask.id(id).put(postParams, appendprivileges).then(function(ReloadTask) { * console.log(ReloadTask) * }) * ``` * * @param {ReloadTask} postParams the parameters to send as request body to the API endpoint * @param {string=} appendprivileges the appendprivileges parameter * @returns {Promise.<ReloadTask>} a promise resolving to the response to the request */ put: function(postParams, appendprivileges) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask/' + id + '' + core.ifNotUndef(appendprivileges, '?privileges=' + appendprivileges, ''), method: 'PUT' }), postParams); } }; }, /** * @namespace * @memberOf reloadtask */ reloadtaskid: function(reloadtaskid) { return { /** * @namespace * @memberOf reloadtask.reloadtaskid */ scriptlog: { /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask/{reloadtaskid}/scriptlog?filereferenceid={filereferenceid} * * This method is manual * * @memberOf reloadtask.reloadtaskid.scriptlog * * @example * ```javascript * qrsApi.reloadtask.reloadtaskid(reloadtaskid).scriptlog.get(filereferenceid).then(function(Guid) { * console.log(Guid) * }) * ``` * * @param {string=} filereferenceid the filereferenceid parameter * @returns {Promise.<Guid>} a promise resolving to the response to the request */ get: function(filereferenceid) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask/' + reloadtaskid + '/scriptlog' + core.ifNotUndef(filereferenceid, '?filereferenceid=' + filereferenceid, ''), method: 'GET' })); } } }; }, /** * @namespace * @memberOf reloadtask */ count: { /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask/count?filter={filter} * * This method is generated * * @memberOf reloadtask.count * * @example * ```javascript * qrsApi.reloadtask.count.get(filter).then(function(int) { * console.log(int) * }) * ``` * * @param {string=} filter the filter parameter * @returns {Promise.<int>} a promise resolving to the response to the request */ get: function(filter) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask/count' + core.ifNotUndef(filter, '?filter=' + filter, ''), method: 'GET' })); } }, /** * @namespace * @memberOf reloadtask */ create: { /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask/create * * This method is manual * * @memberOf reloadtask.create * * @example * ```javascript * qrsApi.reloadtask.create.post(postParams).then(function(ReloadTask) { * console.log(ReloadTask) * }) * ``` * * @param {ReloadTaskBundle} postParams the parameters to send as request body to the API endpoint * @returns {Promise.<ReloadTask>} a promise resolving to the response to the request */ post: function(postParams) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask/create', method: 'POST' }), postParams); } }, /** * @namespace * @memberOf reloadtask */ full: { /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask/full?filter={filter}&orderby={orderby}&privileges={appendprivileges} * * This method is generated * * @memberOf reloadtask.full * * @example * ```javascript * qrsApi.reloadtask.full.get(filter, orderby, appendprivileges).then(function(Array.<ReloadTask>) { * console.log(Array.<ReloadTask>) * }) * ``` * * @param {string=} filter the filter parameter * @param {string=} orderby the orderby parameter * @param {string=} appendprivileges the appendprivileges parameter * @returns {Promise.<Array.<ReloadTask>>} a promise resolving to the response to the request */ get: function(filter, orderby, appendprivileges) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask/full' + (core.ifNotUndef(filter, '&filter=' + filter, '') + core.ifNotUndef(orderby, '&orderby=' + orderby, '') + core.ifNotUndef(appendprivileges, '&privileges=' + appendprivileges, '')).replace(/^&/, '?'), method: 'GET' })); } }, /** * @namespace * @memberOf reloadtask */ many: { /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask/many?privileges={appendprivileges} * * This method is generated * * @memberOf reloadtask.many * * @example * ```javascript * qrsApi.reloadtask.many.post(postParams, appendprivileges).then(function(Array.<ReloadTask>) { * console.log(Array.<ReloadTask>) * }) * ``` * * @param {List<ReloadTask>} postParams the parameters to send as request body to the API endpoint * @param {string=} appendprivileges the appendprivileges parameter * @returns {Promise.<Array.<ReloadTask>>} a promise resolving to the response to the request */ post: function(postParams, appendprivileges) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask/many' + core.ifNotUndef(appendprivileges, '?privileges=' + appendprivileges, ''), method: 'POST' }), postParams); } }, /** * @namespace * @memberOf reloadtask */ previewcreateprivilege: { /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask/previewcreateprivilege * * This method is generated * * @memberOf reloadtask.previewcreateprivilege * * @example * ```javascript * qrsApi.reloadtask.previewcreateprivilege.post(postParams).then(function(Boolean) { * console.log(Boolean) * }) * ``` * * @param {ReloadTask} postParams the parameters to send as request body to the API endpoint * @returns {Promise.<Boolean>} a promise resolving to the response to the request */ post: function(postParams) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask/previewcreateprivilege', method: 'POST' }), postParams); } }, /** * @namespace * @memberOf reloadtask */ table: { /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask/table?filter={filter}&skip={skip}&take={take}&sortcolumn={sortcolumn}&orderascending={orderascending} * * This method is generated * * @memberOf reloadtask.table * * @example * ```javascript * qrsApi.reloadtask.table.post(postParams, filter, skip, take, sortcolumn, orderascending).then(function(Object) { * console.log(Object) * }) * ``` * * @param {TableDefinition} postParams the parameters to send as request body to the API endpoint * @param {string=} filter the filter parameter * @param {string=} skip the skip parameter * @param {string=} take the take parameter * @param {string=} sortcolumn the sortcolumn parameter * @param {string=} orderascending the orderascending parameter * @returns {Promise.<Object>} a promise resolving to the response to the request */ post: function(postParams, filter, skip, take, sortcolumn, orderascending) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask/table' + (core.ifNotUndef(filter, '&filter=' + filter, '') + core.ifNotUndef(skip, '&skip=' + skip, '') + core.ifNotUndef(take, '&take=' + take, '') + core.ifNotUndef(sortcolumn, '&sortcolumn=' + sortcolumn, '') + core.ifNotUndef(orderascending, '&orderascending=' + orderascending, '')).replace(/^&/, '?'), method: 'POST' }), postParams); } }, /** * @namespace * @memberOf reloadtask */ update: { /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask/update * * This method is manual * * @memberOf reloadtask.update * * @example * ```javascript * qrsApi.reloadtask.update.post(postParams).then(function(ReloadTask) { * console.log(ReloadTask) * }) * ``` * * @param {ReloadTaskChange} postParams the parameters to send as request body to the API endpoint * @returns {Promise.<ReloadTask>} a promise resolving to the response to the request */ post: function(postParams) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask/update', method: 'POST' }), postParams); } }, /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask?filter={filter}&orderby={orderby}&privileges={appendprivileges} * * This method is generated * * @memberOf reloadtask * * @example * ```javascript * qrsApi.reloadtask.get(filter, orderby, appendprivileges).then(function(Array.<ReloadTask>) { * console.log(Array.<ReloadTask>) * }) * ``` * * @param {string=} filter the filter parameter * @param {string=} orderby the orderby parameter * @param {string=} appendprivileges the appendprivileges parameter * @returns {Promise.<Array.<ReloadTask>>} a promise resolving to the response to the request */ get: function(filter, orderby, appendprivileges) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask' + (core.ifNotUndef(filter, '&filter=' + filter, '') + core.ifNotUndef(orderby, '&orderby=' + orderby, '') + core.ifNotUndef(appendprivileges, '&privileges=' + appendprivileges, '')).replace(/^&/, '?'), method: 'GET' })); }, /** * Makes a request on the Qlik Sense QRS API: * * /qrs/reloadtask?privileges={appendprivileges} * * This method is generated * * @memberOf reloadtask * * @example * ```javascript * qrsApi.reloadtask.post(postParams, appendprivileges).then(function(ReloadTask) { * console.log(ReloadTask) * }) * ``` * * @param {ReloadTask} postParams the parameters to send as request body to the API endpoint * @param {string=} appendprivileges the appendprivileges parameter * @returns {Promise.<ReloadTask>} a promise resolving to the response to the request */ post: function(postParams, appendprivileges) { return base.request(extend(true, {}, options, { restUri: options.qrsRestUri + '/qrs/reloadtask' + core.ifNotUndef(appendprivileges, '?privileges=' + appendprivileges, ''), method: 'POST' }), postParams); } } }; };
JavaScript
CL
58806f23a7d2ddee8187f5ce7692b017329cacaf8e3f196a74658fa57c92d296
var https = require("https"); var queryString = require("querystring"); var strftime = require("strftime"); var fs = require("fs"); var xml2js = require("xml2js"); /** * @type {{togglApiKey: string, clockanApiKey: string, startDate: string, endDate: string}} */ var config = JSON.parse(fs.readFileSync(__dirname + "/config.json")); var togglApiKey = config.togglApiKey; var clockanApiKey = config.clockanApiKey; var startDate = config.startDate; var endDate = config.endDate; var userAgent = "VaclavSir/ClockanToggl"; /** * report[project][day][description] = {duration: hours, ids: [1, 2, 3]} * * @typedef {Object.<string, Object.<string, Object.<string, {duration: number, ids: Array<number>}>>>} */ var GroupedReport; /** * @param togglApiKey {string} * @param startDate {string} * @param endDate {string} * @param callback {function(GroupedReport, GroupedReport)} */ var getTogglReport = function (togglApiKey, startDate, endDate, callback) { var togglAuthorizationHeader = "Basic " + new Buffer(togglApiKey + ":api_token").toString("base64"); https.get( { "host": "toggl.com", "path": "/api/v8/workspaces?" + queryString.stringify({ "user_agent": userAgent }), "headers": { "Authorization": togglAuthorizationHeader } }, function (/**IncomingMessage*/ res) { var data = ""; res.on("data", function (/**Buffer*/ chunk) { data += chunk; }); res.on("end", function () { /** * Function to process a single workspace and eventually call itself to * process more pages, if the result is paginated. * * @param workspace {{id: number}} * @param page {?number} */ var processWorkspace = function (workspace, page) { page = page || 1; https.get( { "host": "www.toggl.com", "path": "/reports/api/v2/details?" + queryString.stringify({ "workspace_id": workspace.id, "since": startDate, "until": endDate, "page": page, "user_agent": userAgent }), "headers": { "Authorization": togglAuthorizationHeader } }, function (/**IncomingMessage*/ res) { var data = ""; res.on("data", function (/**Buffer*/ chunk) { data += chunk }); res.on("end", function () { /** * @typedef {{ * id: number, * description: string, * start: string, * dur: number, * project: string, * tags: Array<string> * }} */ var TimeEntry; /** * @type {{ * total_count: number, * per_page: number, * data: Array<TimeEntry> * }} */ var report = JSON.parse(data.toString()); var reportedTimes = {}; var unreportedTimes = {}; report.data.forEach(function (/**TimeEntry*/ entry) { var entryDate = new Date(entry.start); var day = strftime("%F", entryDate); var properReport = (entry.tags.indexOf("reported") === -1) ? unreportedTimes : reportedTimes; properReport[entry.project] = properReport[entry.project] || {}; properReport[entry.project][day] = properReport[entry.project][day] || {}; properReport[entry.project][day][entry.description] = properReport[entry.project][day][entry.description] || {duration: 0, ids: []}; properReport[entry.project][day][entry.description].duration += entry.dur / 3600000; properReport[entry.project][day][entry.description].ids.push(entry.id); }); callback(unreportedTimes, reportedTimes); if (report.total_count > (report.per_page * page)) { processWorkspace(workspace, page + 1); } }) } ); }; var workspacesData = /**Array*/ JSON.parse(data.toString()); workspacesData.forEach(processWorkspace) }) } ); }; /** * @param clockanApiKey {string} * @param callback {function(Object.<string, number>)} */ var getClockanProjects = function (clockanApiKey, callback) { var clockanAuthorizationHeader = "Basic " + new Buffer(clockanApiKey + ":x").toString("base64"); /** * clockanProjects['projectName'] = 123456 * * @type {Object.<string, number>} */ var clockanProjects = {}; https.get({ "host": "www.clockan.com", "path": "/projects.xml", "headers": { "Authorization": clockanAuthorizationHeader, "Accept": "application/xml", "User-Agent": userAgent } }, function (/**IncomingMessage*/ res) { var data = ""; res.on("data", function (/**Buffer*/ chunk) { data += chunk; }); res.on("end", function () { xml2js.parseString(data, function (err, /**{projects: {project: Array<Object>}}*/ result) { result.projects.project.forEach(function (/**{id: Array<{_: number}, name: Array<string>}*/project) { var id = project.id.pop()._; var name = project.name.pop(); clockanProjects[name] = id; }); console.log("Known Clockan projects:") console.log(clockanProjects); callback(clockanProjects); }); }); }); }; /** * @param unreportedTimes {GroupedReport} * @param reportedTimes {GroupedReport} */ var processReport = function (unreportedTimes, reportedTimes) { var togglAuthorizationHeader = "Basic " + new Buffer(togglApiKey + ":api_token").toString("base64"); var clockanAuthorizationHeader = "Basic " + new Buffer(clockanApiKey + ":x").toString("base64"); https.get({ "host": "www.clockan.com", "path": "/me.xml", "headers": { "Authorization": clockanAuthorizationHeader, "Accept": "application/xml", "User-Agent": userAgent } }, function (/**IncomingMessage*/ res) { var data = ""; res.on("data", function (/**Buffer*/ chunk) { data += chunk; }); res.on("end", function () { xml2js.parseString(data, function (err, /**{person: {id: Array<{_: number}>}}*/ result) { var clockanPersonId = result.person.id.pop()._; getClockanProjects(clockanApiKey, function (clockanProjects) { Object.keys(unreportedTimes).forEach(function (togglProjectName) { Object.keys(unreportedTimes[togglProjectName]).forEach(function (entryDate) { Object.keys(unreportedTimes[togglProjectName][entryDate]).forEach(function (description) { /** * @type {{duration: number, ids: Array<number>}} */ var timeRecord = unreportedTimes[togglProjectName][entryDate][description]; var clockanProjectName = config.projects[togglProjectName]; var clockanProjectId = clockanProjects[clockanProjectName]; console.log(); console.log("Toggl project: " + togglProjectName); console.log("Clockan project: " + clockanProjectName + " " + clockanProjectId); console.log("Date (duration): " + entryDate + " (" + timeRecord.duration.toFixed(4) + ")"); console.log("Task: " + description); console.log("Entry IDs: " + timeRecord.ids); // POST entry to Clockan if (clockanProjectId) { var message = "<?xml version=\"1.0\"?>" + "<time-entry>" + "<person-id>" + clockanPersonId + "</person-id>" + "<date>" + entryDate + "</date>" + "<hours>" + timeRecord.duration.toFixed(4) + "</hours>" + "<description>" + description + "</description>" + "</time-entry>"; var createEntryRequest = https.request({ "method": "POST", "host": "www.clockan.com", "path": "/projects/" + clockanProjectId + "/time_entries.xml", "headers": { "Authorization": clockanAuthorizationHeader, "Accept": "application/xml", "Content-Type": "application/xml", "User-Agent": "VaclavSir/ClockanToggl", "Content-Length": Buffer.byteLength(message, "utf8") } }, function (/**IncomingMessage*/ res) { if (res.statusCode >= 200 && res.statusCode < 300) { res.on("data", function (data) { console.log(data.toString()); }) // POST tag to Toggl var togglTagRequest = https.request({ "method": "PUT", "host": "www.toggl.com", "path": "/api/v8/time_entries/" + timeRecord.ids.join(",") + "?" + queryString.stringify({ "user_agent": userAgent }), "headers": { "Authorization": togglAuthorizationHeader } }, function (/**IncomingMessage*/ res) { if (res.statusCode >= 200 && res.statusCode < 300) { console.log("Tagged on Toggl with 'reported' tag."); } else { console.warn("Toggl returned status " + res.statusCode + ", tag 'reported' might not have been set."); } }); togglTagRequest.write(JSON.stringify({"time_entry": {"tags": ["reported"], "tag_action": "add"}})); togglTagRequest.end(); } else { console.warn("Clockan returned status " + res.statusCode + ", entries were not tagged."); } }); createEntryRequest.write(message); createEntryRequest.end(); console.log("Sent to Clockan."); console.log(message); } }) }) }); }); }); }); }); }; getTogglReport(togglApiKey, startDate, endDate, processReport);
JavaScript
CL
0e0972c08d79b848148f6ea7258f37b26c10f5cc49327ad2521d3f82c5f185a5
/* jshint node: true */ 'use strict'; var os = require('os'); var fs = require('fs'); var config = require('./config'); var spawn = require('child_process').spawn; var _ = require('lodash'); var Tail = require('tail').Tail; var log4js = require('log4js'); log4js.configure(config.LOG4JS_SETTINGS); var logger = log4js.getLogger('agent'); // TODO: extra requirements: // 1. lybica module should be in PYTHONPATH // 2. LYBICA_API_URL // 3. LYBICA_HDFS_URL delete process.env.http_proxy; delete process.env.https_proxy; process.env.LYBICA_API_URL = config.LYBICA_API_URL; process.env.LYBICA_HDFS_URL = config.LYBICA_HDFS_URL; process.env.PYTHONPATH = config.PYTHONPATH; function Agent() { this.labels = config.LABELS; this.platform = os.type(); this.name = os.hostname(); this.runners = { all: config.RUNNERS, running: 0 }; this.tasks = []; } Agent.prototype.canRun = function(task) { // TODO: agent ip should match task ctrl pc ip if (agent.runners.all === agent.runners.running) { logger.warn('no more runners available'); return false; } var taskLabels = task.labels || []; return taskLabels.filter(function(l) { return config.LABELS.indexOf(l) < 0; }).length === 0; }; Agent.prototype.run = function(task, callback) { logger.info('run task: %j', task); var taskId = task._id; agent.runners.running += 1; process.env.TASK_ID = taskId; // set env variable TASK_ID var workspace = __dirname + '/builds/' + taskId; process.env.WORKSPACE = workspace; var consoleTxt = workspace + '/' + taskId + '_console.txt'; agent.tasks.push({id: taskId, consoletxt: consoleTxt}); // save task into agent tasks fs.mkdir(workspace, function(err) { if (err) { socket.emit('error', err); logger.error('failed to create workspace "%s", error: %s', workspace, err); } var consoleStream = fs.createWriteStream(consoleTxt); var runner = spawn('python', ['-m', 'lybica']); runner.stdout.pipe(consoleStream); runner.stderr.pipe(consoleStream); runner.on('close', function(code) { // TODO: cleanup workspace if code is 0 logger.info('Exit Code: ' + code); _.remove(agent.tasks, function(e) { return e.id === taskId; }); agent.runners.running -= 1; callback(null, code); }); }); }; var agent = new Agent(); var socket = require('socket.io-client')(config.SERVER_ADDR); logger.info('start lybica agent, try to connect to "%s"', config.SERVER_ADDR); socket.on('connect', function() { logger.info('connected! update agent status'); socket.emit('agent', agent); }); socket.on('task', function(task) { if (agent.canRun(task)) { logger.info('start to run task "%s"', task._id); socket.emit('start', task); agent.run(task, function(err, exitCode) { if (err) { socket.emit('error', err); return; } logger.info('task "%s" done with exit code "%d"', task._id, exitCode); socket.emit('done', task); }); } }); socket.on('console', function(msg) { logger.info('got console event for task %s', msg.task); var task = _.find(agent.tasks, {id: msg.task}); if (task === undefined) { logger.warn('cannot find task %s', msg.task); return; } // READ from console file fs.createReadStream(task.consoletxt) .on('data', function(data) { socket.emit('data', {to: msg.from, data: data.toString()}); }) .on('close', function() { // Tail var tail = new Tail(task.consoletxt); tail.on('line', function(data) { socket.emit('data', {to: msg.from, data: data + '\n'}); }); tail.on('error', function(error) { socket.emit('error', error); }); }); }); socket.on('disconnect', function() { logger.info('agent disconnected by remote server!'); });
JavaScript
CL
40dd80e3012d4d66dab4da75d8b8cc7d998d7874d38c955708b1650a8490c1fa
import { Platform } from 'react-native'; import { takeEvery, apply, put, select } from 'redux-saga/effects'; import moment from 'moment'; import { orderCancelFetchSuccess, orderCancelFetchFailure, } from '../actions/orderCancel'; import { queryOrderListFetch } from '../actions/queryOrderList'; import { queryOrderFetch } from '../actions/queryOrder'; import { addError } from '../actions/error'; import buyoo from '../helpers/apiClient'; import { ORDER_CANCEL } from '../constants/actionTypes'; import { encryptMD5, signTypeMD5 } from '../../components/AuthEncrypt'; import { getAuthUserFunid } from '../selectors'; export function* orderCancelFetchWatchHandle(action) { try { const { tradeno, orderno, status } = action.payload; const funid = yield select(getAuthUserFunid); const Key = 'tradeKey'; const appId = Platform.OS === 'ios' ? '1' : '2'; const method = 'fun.trade.orderCancel'; const charset = 'utf-8'; const timestamp = moment().format('YYYY-MM-DD HH:mm:ss'); const version = '2.0'; const signType = signTypeMD5(appId, method, charset, Key, true); const encrypt = encryptMD5( [ { key: 'funid', value: funid, }, { key: 'orderno', value: orderno, }, { key: 'tradeno', value: tradeno, }, { key: 'status', value: status, }, ], Key, ); const options = [ { appid: appId, method, charset, signtype: signType, encrypt, timestamp, version, funid, orderno, tradeno, status, }, ]; const response = yield apply(buyoo, buyoo.orderCancel, options); if (response.code !== 10000) { yield put(orderCancelFetchFailure()); yield put(addError(`msg: ${response.msg}; code: ${response.code}`)); } else { yield put( orderCancelFetchSuccess({ orderno, tradeno, }), ); } } catch (err) { console.log(err); yield put(orderCancelFetchFailure()); yield put(addError(typeof err === 'string' ? err : err.toString())); } } export function* orderCancelFetchWatch() { yield takeEvery(ORDER_CANCEL.REQUEST, orderCancelFetchWatchHandle); } export function* orderCancelSuccessWatchHandle(action) { try { const { orderno, tradeno } = action.payload; yield put( queryOrderFetch({ orderNo: orderno, tradeNo: tradeno, }), ); yield put( queryOrderListFetch({ index: 0, status: '99999', }), ); yield put( queryOrderListFetch({ index: 1, status: '10000', }), ); } catch (err) { console.warn(err); } } export function* orderCancelSuccessWatch() { yield takeEvery(ORDER_CANCEL.SUCCESS, orderCancelSuccessWatchHandle); }
JavaScript
CL
393adaf44316c87620a0cfd6e2c7e56cdad658534ef0323bd72fb9be9b2d7cae
const firebase = require("firebase"); const dotenv = require("dotenv"); dotenv.config(); const config = { apiKey: process.env.FIREBASE_KEY, authDomain: process.env.FIREBASE_DOMAIN, databaseURL: process.env.FIREBASE_DATABASE, projectId: process.env.FIREBASE_PROJECT_ID }; // Initialize Firebase firebase.initializeApp(config); // Helper function 1: compare if two objs have the same keys, if it does, it runs the next helper function const helperMethod1 = { compareProductKeys: async (prev, curr) => { for (let key in prev) { if (curr.hasOwnProperty(key)) { await helperMethod2.compareItemPosition(prev[key], curr[key]); } } return curr; } }; // Helper function 2: compare two sorted arrays and add a counter key, value to the current array of objs const helperMethod2 = { compareItemPosition: async (prev, curr) => { for (let itema of prev) { let itemaPosition = prev.indexOf(itema); for (let itemb of curr) { if (itemb.title === itema.title) { let itembPosition = curr.indexOf(itemb); itemb.counter = itemaPosition - itembPosition; } else if (!itemb.hasOwnProperty("counter")) { itemb.counter = 0; } } } return curr; } }; const countCounterKeys = obj => { return new Promise((resolve, reject) => { let results = []; for (let key in obj) { for (let item of obj[key]) { if (item.counter > 0) { results.push({ ...item, category: key }); } } } let sorted = sortObject(results); resolve(sorted); reject(new Error("ERROR: Error while creating a list of sorted objects.")); }); }; // Sorts an object based on their counter key value const sortObject = arr => { return new Promise((resolve, reject) => { let sorted = arr.sort((a, b) => { return a.counter > b.counter ? -1 : 1; }); resolve(sorted); reject(new Error("ERROR: Error while sorting object.")); }); }; const firebaseMethods = { // Update 'previous' key with 'current' key values. setPreviousData: async () => { let ref = firebase.database().ref("/"); // Fetching one snapshot of the Firebase DB and updating the 'previous' key with the current 'data' key. ref.once("value", async snapshot => { const data = await snapshot.val(); await firebase .database() .ref() .update({ previous: data.data }); }); }, // Updates 'data' key with the data passed as an argument writeData: async data => { await firebase .database() .ref() .update({ data: data }); }, // Disconnect firebase from server disconnectFirebase: async () => { console.log("Disconnecting Firebase..."); await firebase.database().goOffline(); console.log("Disconnected."); }, // Counts positions escalated by a product, relative to the previous scrape addCounterKey: async () => { let ref = firebase.database().ref("/"); // Fetching one snapshot of the Firebase DB and updating the 'previous' key with the current 'data' key. ref.once("value", async snapshot => { const curdata = await snapshot.val(); let cur = await helperMethod1.compareProductKeys( curdata.previous.scrapes, curdata.data.scrapes ); await firebase .database() .ref("/data/") .update({ scrapes: cur }); }); }, // Push an array of products that escalated more than 1 spot on the list to Firebase DB. addEscalatedProducts: async () => { let ref = firebase.database().ref("/"); ref.once("value", async snapshot => { const curdata = await snapshot.val(); let cur = await countCounterKeys(curdata.data.scrapes); console.log("List created. Updating database..."); await firebase .database() .ref() .update({ escalated: cur }); console.log("Done"); }); } }; module.exports = firebaseMethods;
JavaScript
CL
da63d2a5186bcdb5c308be3935fd775d5a30803e6cd6b454eccbec4ae4e86a1c
const { React, getModule, contextMenu, getModuleByDisplayName } = require('powercord/webpack'); const { Tooltip, Icon, Spinner } = require('powercord/components'); module.exports = class RichQuote extends React.Component { constructor (props) { super(props); this.state = { searchStatus: false }; } static getDerivedStateFromProps (props, state) { return { ...Object.assign({}, props), ...state }; } async search () { const { transitionTo } = await getModule([ 'transitionTo' ]); const setStatus = (s, link) => this.setState({ ...this.state, searchStatus: s, link }); // contains code by Bowser65 (Powercord's server, https://discord.com/channels/538759280057122817/539443165455974410/662376605418782730) function searchAPI (content, author_id, max_id, id, dm, asc) { return new Promise((resolve, reject) => { const Search = getModule(m => m.prototype && m.prototype.retryLater, false); const opts = { author_id, max_id, content }; const s = new Search(id, dm ? 'DM' : 'GUILD', asc ? { offset: 0, sort_by: 'timestamp', sort_order: 'asc', ...opts } : opts); s.fetch(res => resolve(res.body), () => void 0, reject); }); } setStatus('loading'); const result = await searchAPI(this.props.search.raw, this.props.author.id, this.props.search.timestamp, this.props.channel.guild_id || this.props.channel.id, !this.props.channel.guild_id ); if (result.messages.length === 0) setStatus('error'); else { const message = result.messages[0].filter((e) => e?.content.includes(this.props.search.raw))[0]; if (!message) setStatus('error'); else { const link = [ this.props.channel.guild_id || '@me', message.channel_id, message.id ]; setStatus('done', link); if (this.props.settings.cacheSearch) { const searchResult = { content: message.content, authorId: message.author.id, link }; let newCache = false; if (!window.localStorage.richQuoteCache) newCache = true; const { searches } = newCache ? false : JSON.parse(window.localStorage.richQuoteCache); window.localStorage.richQuoteCache = JSON.stringify({ searches: searches ? [ ...searches, searchResult ] : [ searchResult ]}); } transitionTo(`/channels/${link.join('/')}`); } } } openPopout (event) { const UserPopout = getModuleByDisplayName('UserPopout', false); const PopoutDispatcher = getModule([ 'openPopout' ], false); const guildId = this.props.channel.guild_id; const userId = this.props.author.id; // modified from smart typers PopoutDispatcher.openPopout(event.target, { closeOnScroll: false, containerClass: 'rich-quotes-popout', render: (props) => React.createElement(UserPopout, { ...props, userId, guildId }), shadow: false, position: 'right' }, 'quote-user-popout'); } openUserContextMenu (event) { const GroupDMUserContextMenu = getModuleByDisplayName('GroupDMUserContextMenu', false); const GuildChannelUserContextMenu = getModuleByDisplayName('GuildChannelUserContextMenu', false); const userStore = getModule([ 'getCurrentUser' ], false); const guildId = this.props.channel.guild_id; const userId = this.props.author.id; if (!guildId) { return contextMenu.openContextMenu(event, (props) => React.createElement(GroupDMUserContextMenu, { ...props, user: userStore.getUser(userId), channel: this.props.channel })); } contextMenu.openContextMenu(event, (props) => React.createElement(GuildChannelUserContextMenu, { ...props, user: userStore.getUser(userId), guildId, channelId: this.props.channel.id, showMediaItems: false, popoutPosition: 'top' })); } render () { const { transitionTo } = getModule([ 'transitionTo' ], false); const { getName } = getModule([ 'getName' ], false); const MessageTimestamp = getModule([ 'MessageTimestamp' ], false); const Timestamp = getModule(m => m.prototype && m.prototype.toDate && m.prototype.month, false); const { avatar, clickable, username } = getModule([ 'systemMessageAccessories' ], false); const link = this.state.link, searchMsg = this.state.searchStatus, previewQuote = this.props.channel.id === 'owo'; const quoteTimestamp = link && this.props.settings.displayTimestamp ? new MessageTimestamp.MessageTimestamp({ className: 'rq-timestamp', compact: false, timestamp: new Timestamp(this.props.message.timestamp), isOnlyVisibleOnHover: false }) : false; const highlightAlter = this.props.mentionType >= 2 ? 'rq-highlight-alt' : '', mention = this.props.mentionType !== 0 ? `rq-highlight ${highlightAlter}` : '', container = 'rq-highlight-container', highlightContainer = this.props.mentionType >= 2 ? `${container} ${this.props.mentionType === 3 ? `${container}-alt` : ''}` : ''; const MessageContent = getModule(m => m.type && m.type.displayName === 'MessageContent', false); const jumpTooltip = 'Jump to Message', searchTooltip = searchMsg ? searchMsg === 'error' ? 'Could not find matching message' : 'Message search loading...' : 'Search for Message'; const previewJump = document.getElementById('owo-0')?.scrollIntoViewIfNeeded; const allowSearch = !searchMsg && !previewQuote; // Nickname handler const displayName = this.props.settings.displayNickname ? getName(link ? link[0] : this.props.channel.guild_id, this.props.channel.id, this.props.author) : false; return ( <div id="a11y-hack"><div key={this.props.content} className='rq-inline'><div className={highlightContainer}> <div className='rq-header threads-header-hack'> <img className={`rq-avatar threads-avatar-hack revert-reply-hack ${avatar} ${clickable}`} src={this.props.author.avatarURL} onClick={(e) => this.openPopout(e)} onContextMenu={(e) => this.openUserContextMenu(e)} aria-hidden="true" alt=" "> </img> <div className='rq-userTag'> <span className={`rq-username ${mention} ${username} ${clickable}`} onClick={(e) => this.openPopout(e) } onContextMenu={(e) => this.openUserContextMenu(e)} >{`${this.props.mentionType !== 0 ? '@' : ''}${displayName}`}</span>{ link && this.props.settings.displayChannel ? <span> <span className='rq-infoText'>{`posted in ${this.props.channel.name ? '' : 'a DM'}`}</span> { this.props.channel.name ? <span className={`rq-channel ${!previewQuote ? 'rq-clickable' : ''} rq-highlight ${highlightAlter}`} onClick= {() => !previewQuote ? transitionTo(`/channels/${link.slice(0, 2).join('/')}`) : false } >{`#${this.props.channel.name}`}</span> : false } </span> : false }{ quoteTimestamp } </div> </div> <div className='rq-button-container'>{ link ? <Tooltip position="left" text={jumpTooltip}> <div className='rq-button rq-jump rq-clickable' onClick= {() => !previewQuote ? transitionTo(`/channels/${link.join('/')}`) : previewJump()}> <Icon className='rq-180-flip' name="Reply"/> </div></Tooltip> : <Tooltip position="left" text={searchTooltip}> <div key={searchMsg} className={`rq-button rq-search ${ allowSearch ? 'rq-clickable' : ''}`} onClick= {async () => allowSearch ? this.search() : false}>{ !searchMsg ? <Icon className='rq-searching' name="Search"/> : searchMsg === 'loading' ? <Spinner className='rq-loading' type='pulsingEllipsis'/> : <div className='rq-error'>!</div> }</div></Tooltip> }</div> <div className='rq-content'> {this.props.content ? <MessageContent message={this.props.message} content={this.props.content}/> : null} {this.props.accessories} </div> </div></div></div> ); } };
JavaScript
CL
6eac906a2331f555e19f87ebfe962fd39217d0c4bd2853269cb488a649e68bb3
/** * Kandy.js (Next) * kandy.link.js * Version: 3.0.0-beta.17786 */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["createKandy"] = factory(); else root["createKandy"] = factory(); })(window, 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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./src/index.link.js"); /******/ }) /************************************************************************/ /******/ ({ /***/ "../../node_modules/babel-runtime/core-js/array/from.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/array/from.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/array/from */ "../../node_modules/core-js/library/fn/array/from.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/get-iterator.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/get-iterator.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/get-iterator */ "../../node_modules/core-js/library/fn/get-iterator.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/json/stringify.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/json/stringify.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/json/stringify */ "../../node_modules/core-js/library/fn/json/stringify.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/object/assign.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/object/assign.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/assign */ "../../node_modules/core-js/library/fn/object/assign.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/object/create.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/object/create.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/create */ "../../node_modules/core-js/library/fn/object/create.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/object/define-properties.js": /*!*******************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/object/define-properties.js ***! \*******************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/define-properties */ "../../node_modules/core-js/library/fn/object/define-properties.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/object/define-property.js": /*!*****************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/object/define-property.js ***! \*****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/define-property */ "../../node_modules/core-js/library/fn/object/define-property.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/object/freeze.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/object/freeze.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/freeze */ "../../node_modules/core-js/library/fn/object/freeze.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/object/get-own-property-descriptor.js": /*!*****************************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/object/get-own-property-descriptor.js ***! \*****************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/get-own-property-descriptor */ "../../node_modules/core-js/library/fn/object/get-own-property-descriptor.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/object/get-prototype-of.js": /*!******************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/object/get-prototype-of.js ***! \******************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/get-prototype-of */ "../../node_modules/core-js/library/fn/object/get-prototype-of.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/object/keys.js": /*!******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/object/keys.js ***! \******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/keys */ "../../node_modules/core-js/library/fn/object/keys.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/object/values.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/object/values.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/object/values */ "../../node_modules/core-js/library/fn/object/values.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/promise.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/promise.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/promise */ "../../node_modules/core-js/library/fn/promise.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/symbol.js": /*!*************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/symbol.js ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/symbol */ "../../node_modules/core-js/library/fn/symbol/index.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/core-js/symbol/iterator.js": /*!**********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/core-js/symbol/iterator.js ***! \**********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(/*! core-js/library/fn/symbol/iterator */ "../../node_modules/core-js/library/fn/symbol/iterator.js"), __esModule: true }; /***/ }), /***/ "../../node_modules/babel-runtime/helpers/classCallCheck.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/helpers/classCallCheck.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; exports.default = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; /***/ }), /***/ "../../node_modules/babel-runtime/helpers/defineProperty.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/helpers/defineProperty.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _defineProperty = __webpack_require__(/*! ../core-js/object/define-property */ "../../node_modules/babel-runtime/core-js/object/define-property.js"); var _defineProperty2 = _interopRequireDefault(_defineProperty); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (obj, key, value) { if (key in obj) { (0, _defineProperty2.default)(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; /***/ }), /***/ "../../node_modules/babel-runtime/helpers/extends.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/helpers/extends.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _assign = __webpack_require__(/*! ../core-js/object/assign */ "../../node_modules/babel-runtime/core-js/object/assign.js"); var _assign2 = _interopRequireDefault(_assign); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _assign2.default || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /***/ }), /***/ "../../node_modules/babel-runtime/helpers/toConsumableArray.js": /*!************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/helpers/toConsumableArray.js ***! \************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _from = __webpack_require__(/*! ../core-js/array/from */ "../../node_modules/babel-runtime/core-js/array/from.js"); var _from2 = _interopRequireDefault(_from); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return (0, _from2.default)(arr); } }; /***/ }), /***/ "../../node_modules/babel-runtime/helpers/typeof.js": /*!*************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/helpers/typeof.js ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _iterator = __webpack_require__(/*! ../core-js/symbol/iterator */ "../../node_modules/babel-runtime/core-js/symbol/iterator.js"); var _iterator2 = _interopRequireDefault(_iterator); var _symbol = __webpack_require__(/*! ../core-js/symbol */ "../../node_modules/babel-runtime/core-js/symbol.js"); var _symbol2 = _interopRequireDefault(_symbol); var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { return typeof obj === "undefined" ? "undefined" : _typeof(obj); } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); }; /***/ }), /***/ "../../node_modules/babel-runtime/regenerator/index.js": /*!****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/babel-runtime/regenerator/index.js ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! regenerator-runtime */ "../../node_modules/regenerator-runtime/runtime-module.js"); /***/ }), /***/ "../../node_modules/base-64/base64.js": /*!***********************************************************!*\ !*** /home/circleci/kandy/node_modules/base-64/base64.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! http://mths.be/base64 v0.1.0 by @mathias | MIT license */ ;(function(root) { // Detect free variables `exports`. var freeExports = typeof exports == 'object' && exports; // Detect free variable `module`. var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; // Detect free variable `global`, from Node.js or Browserified code, and use // it as `root`. var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ var InvalidCharacterError = function(message) { this.message = message; }; InvalidCharacterError.prototype = new Error; InvalidCharacterError.prototype.name = 'InvalidCharacterError'; var error = function(message) { // Note: the error messages used throughout this file match those used by // the native `atob`/`btoa` implementation in Chromium. throw new InvalidCharacterError(message); }; var TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // http://whatwg.org/html/common-microsyntaxes.html#space-character var REGEX_SPACE_CHARACTERS = /[\t\n\f\r ]/g; // `decode` is designed to be fully compatible with `atob` as described in the // HTML Standard. http://whatwg.org/html/webappapis.html#dom-windowbase64-atob // The optimized base64-decoding algorithm used is based on @atk’s excellent // implementation. https://gist.github.com/atk/1020396 var decode = function(input) { input = String(input) .replace(REGEX_SPACE_CHARACTERS, ''); var length = input.length; if (length % 4 == 0) { input = input.replace(/==?$/, ''); length = input.length; } if ( length % 4 == 1 || // http://whatwg.org/C#alphanumeric-ascii-characters /[^+a-zA-Z0-9/]/.test(input) ) { error( 'Invalid character: the string to be decoded is not correctly encoded.' ); } var bitCounter = 0; var bitStorage; var buffer; var output = ''; var position = -1; while (++position < length) { buffer = TABLE.indexOf(input.charAt(position)); bitStorage = bitCounter % 4 ? bitStorage * 64 + buffer : buffer; // Unless this is the first of a group of 4 characters… if (bitCounter++ % 4) { // …convert the first 8 bits to a single ASCII character. output += String.fromCharCode( 0xFF & bitStorage >> (-2 * bitCounter & 6) ); } } return output; }; // `encode` is designed to be fully compatible with `btoa` as described in the // HTML Standard: http://whatwg.org/html/webappapis.html#dom-windowbase64-btoa var encode = function(input) { input = String(input); if (/[^\0-\xFF]/.test(input)) { // Note: no need to special-case astral symbols here, as surrogates are // matched, and the input is supposed to only contain ASCII anyway. error( 'The string to be encoded contains characters outside of the ' + 'Latin1 range.' ); } var padding = input.length % 3; var output = ''; var position = -1; var a; var b; var c; var d; var buffer; // Make sure any padding is handled outside of the loop. var length = input.length - padding; while (++position < length) { // Read three bytes, i.e. 24 bits. a = input.charCodeAt(position) << 16; b = input.charCodeAt(++position) << 8; c = input.charCodeAt(++position); buffer = a + b + c; // Turn the 24 bits into four chunks of 6 bits each, and append the // matching character for each of them to the output. output += ( TABLE.charAt(buffer >> 18 & 0x3F) + TABLE.charAt(buffer >> 12 & 0x3F) + TABLE.charAt(buffer >> 6 & 0x3F) + TABLE.charAt(buffer & 0x3F) ); } if (padding == 2) { a = input.charCodeAt(position) << 8; b = input.charCodeAt(++position); buffer = a + b; output += ( TABLE.charAt(buffer >> 10) + TABLE.charAt((buffer >> 4) & 0x3F) + TABLE.charAt((buffer << 2) & 0x3F) + '=' ); } else if (padding == 1) { buffer = input.charCodeAt(position); output += ( TABLE.charAt(buffer >> 2) + TABLE.charAt((buffer << 4) & 0x3F) + '==' ); } return output; }; var base64 = { 'encode': encode, 'decode': decode, 'version': '0.1.0' }; // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( true ) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return base64; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { var key; } }(this)); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "../../node_modules/webpack/buildin/module.js")(module), __webpack_require__(/*! ./../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "../../node_modules/bottlejs/dist/bottle.js": /*!*****************************************************************!*\ !*** /home/circleci/kandy/node_modules/bottlejs/dist/bottle.js ***! \*****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;;(function(undefined) { 'use strict'; /** * BottleJS v1.7.0 - 2018-01-29 * A powerful dependency injection micro container * * Copyright (c) 2018 Stephen Young * Licensed MIT */ /** * String constants */ var DELIMITER = '.'; var FUNCTION_TYPE = 'function'; var STRING_TYPE = 'string'; var GLOBAL_NAME = '__global__'; var PROVIDER_SUFFIX = 'Provider'; /** * Unique id counter; * * @type Number */ var id = 0; /** * Local slice alias * * @type Functions */ var slice = Array.prototype.slice; /** * Iterator used to walk down a nested object. * * If Bottle.config.strict is true, this method will throw an exception if it encounters an * undefined path * * @param Object obj * @param String prop * @return mixed * @throws Error if Bottle is unable to resolve the requested service. */ var getNested = function getNested(obj, prop) { var service = obj[prop]; if (service === undefined && globalConfig.strict) { throw new Error('Bottle was unable to resolve a service. `' + prop + '` is undefined.'); } return service; }; /** * Get a nested bottle. Will set and return if not set. * * @param String name * @return Bottle */ var getNestedBottle = function getNestedBottle(name) { var bottle; if (!this.nested[name]) { bottle = Bottle.pop(); this.nested[name] = bottle; this.factory(name, function SubProviderFactory() { return bottle.container; }); } return this.nested[name]; }; /** * Get a service stored under a nested key * * @param String fullname * @return Service */ var getNestedService = function getNestedService(fullname) { return fullname.split(DELIMITER).reduce(getNested, this); }; /** * Register a constant * * @param String name * @param mixed value * @return Bottle */ var constant = function constant(name, value) { var parts = name.split(DELIMITER); name = parts.pop(); defineConstant.call(parts.reduce(setValueObject, this.container), name, value); return this; }; var defineConstant = function defineConstant(name, value) { Object.defineProperty(this, name, { configurable : false, enumerable : true, value : value, writable : false }); }; /** * Register decorator. * * @param String fullname * @param Function func * @return Bottle */ var decorator = function decorator(fullname, func) { var parts, name; if (typeof fullname === FUNCTION_TYPE) { func = fullname; fullname = GLOBAL_NAME; } parts = fullname.split(DELIMITER); name = parts.shift(); if (parts.length) { getNestedBottle.call(this, name).decorator(parts.join(DELIMITER), func); } else { if (!this.decorators[name]) { this.decorators[name] = []; } this.decorators[name].push(func); } return this; }; /** * Register a function that will be executed when Bottle#resolve is called. * * @param Function func * @return Bottle */ var defer = function defer(func) { this.deferred.push(func); return this; }; /** * Immediately instantiates the provided list of services and returns them. * * @param Array services * @return Array Array of instances (in the order they were provided) */ var digest = function digest(services) { return (services || []).map(getNestedService, this.container); }; /** * Register a factory inside a generic provider. * * @param String name * @param Function Factory * @return Bottle */ var factory = function factory(name, Factory) { return provider.call(this, name, function GenericProvider() { this.$get = Factory; }); }; /** * Register an instance factory inside a generic factory. * * @param {String} name - The name of the service * @param {Function} Factory - The factory function, matches the signature required for the * `factory` method * @return Bottle */ var instanceFactory = function instanceFactory(name, Factory) { return factory.call(this, name, function GenericInstanceFactory(container) { return { instance : Factory.bind(Factory, container) }; }); }; /** * A filter function for removing bottle container methods and providers from a list of keys */ var byMethod = function byMethod(name) { return !/^\$(?:decorator|register|list)$|Provider$/.test(name); }; /** * List the services registered on the container. * * @param Object container * @return Array */ var list = function list(container) { return Object.keys(container || this.container || {}).filter(byMethod); }; /** * Function used by provider to set up middleware for each request. * * @param Number id * @param String name * @param Object instance * @param Object container * @return void */ var applyMiddleware = function applyMiddleware(middleware, name, instance, container) { var descriptor = { configurable : true, enumerable : true }; if (middleware.length) { descriptor.get = function getWithMiddlewear() { var index = 0; var next = function nextMiddleware(err) { if (err) { throw err; } if (middleware[index]) { middleware[index++](instance, next); } }; next(); return instance; }; } else { descriptor.value = instance; descriptor.writable = true; } Object.defineProperty(container, name, descriptor); return container[name]; }; /** * Register middleware. * * @param String name * @param Function func * @return Bottle */ var middleware = function middleware(fullname, func) { var parts, name; if (typeof fullname === FUNCTION_TYPE) { func = fullname; fullname = GLOBAL_NAME; } parts = fullname.split(DELIMITER); name = parts.shift(); if (parts.length) { getNestedBottle.call(this, name).middleware(parts.join(DELIMITER), func); } else { if (!this.middlewares[name]) { this.middlewares[name] = []; } this.middlewares[name].push(func); } return this; }; /** * Named bottle instances * * @type Object */ var bottles = {}; /** * Get an instance of bottle. * * If a name is provided the instance will be stored in a local hash. Calling Bottle.pop multiple * times with the same name will return the same instance. * * @param String name * @return Bottle */ var pop = function pop(name) { var instance; if (typeof name === STRING_TYPE) { instance = bottles[name]; if (!instance) { bottles[name] = instance = new Bottle(); instance.constant('BOTTLE_NAME', name); } return instance; } return new Bottle(); }; /** * Clear all named bottles. */ var clear = function clear(name) { if (typeof name === STRING_TYPE) { delete bottles[name]; } else { bottles = {}; } }; /** * Used to process decorators in the provider * * @param Object instance * @param Function func * @return Mixed */ var reducer = function reducer(instance, func) { return func(instance); }; /** * Register a provider. * * @param String fullname * @param Function Provider * @return Bottle */ var provider = function provider(fullname, Provider) { var parts, name; parts = fullname.split(DELIMITER); if (this.providerMap[fullname] && parts.length === 1 && !this.container[fullname + PROVIDER_SUFFIX]) { return console.error(fullname + ' provider already instantiated.'); } this.originalProviders[fullname] = Provider; this.providerMap[fullname] = true; name = parts.shift(); if (parts.length) { getNestedBottle.call(this, name).provider(parts.join(DELIMITER), Provider); return this; } return createProvider.call(this, name, Provider); }; /** * Get decorators and middleware including globals * * @return array */ var getWithGlobal = function getWithGlobal(collection, name) { return (collection[name] || []).concat(collection.__global__ || []); }; /** * Create the provider properties on the container * * @param String name * @param Function Provider * @return Bottle */ var createProvider = function createProvider(name, Provider) { var providerName, properties, container, id, decorators, middlewares; id = this.id; container = this.container; decorators = this.decorators; middlewares = this.middlewares; providerName = name + PROVIDER_SUFFIX; properties = Object.create(null); properties[providerName] = { configurable : true, enumerable : true, get : function getProvider() { var instance = new Provider(); delete container[providerName]; container[providerName] = instance; return instance; } }; properties[name] = { configurable : true, enumerable : true, get : function getService() { var provider = container[providerName]; var instance; if (provider) { // filter through decorators instance = getWithGlobal(decorators, name).reduce(reducer, provider.$get(container)); delete container[providerName]; delete container[name]; } return instance === undefined ? instance : applyMiddleware(getWithGlobal(middlewares, name), name, instance, container); } }; Object.defineProperties(container, properties); return this; }; /** * Register a service, factory, provider, or value based on properties on the object. * * properties: * * Obj.$name String required ex: `'Thing'` * * Obj.$type String optional 'service', 'factory', 'provider', 'value'. Default: 'service' * * Obj.$inject Mixed optional only useful with $type 'service' name or array of names * * Obj.$value Mixed optional Normally Obj is registered on the container. However, if this * property is included, it's value will be registered on the container * instead of the object itsself. Useful for registering objects on the * bottle container without modifying those objects with bottle specific keys. * * @param Function Obj * @return Bottle */ var register = function register(Obj) { var value = Obj.$value === undefined ? Obj : Obj.$value; return this[Obj.$type || 'service'].apply(this, [Obj.$name, value].concat(Obj.$inject || [])); }; /** * Deletes providers from the map and container. * * @param String name * @return void */ var removeProviderMap = function resetProvider(name) { delete this.providerMap[name]; delete this.container[name]; delete this.container[name + PROVIDER_SUFFIX]; }; /** * Resets all providers on a bottle instance. * * @return void */ var resetProviders = function resetProviders() { var providers = this.originalProviders; Object.keys(this.originalProviders).forEach(function resetPrvider(provider) { var parts = provider.split(DELIMITER); if (parts.length > 1) { parts.forEach(removeProviderMap, getNestedBottle.call(this, parts[0])); } removeProviderMap.call(this, provider); this.provider(provider, providers[provider]); }, this); }; /** * Execute any deferred functions * * @param Mixed data * @return Bottle */ var resolve = function resolve(data) { this.deferred.forEach(function deferredIterator(func) { func(data); }); return this; }; /** * Register a function service */ var serviceFactory = function serviceFactory(name, factoryService) { return createService.apply(this, [name, factoryService, false].concat(slice.call(arguments, 2))); }; /** * Register a class service * * @param String name * @param Function Service * @return Bottle */ var service = function service(name, Service) { return createService.apply(this, [name, Service, true].concat(slice.call(arguments, 2))); }; /** * Private helper for creating service and service factories. * * @param String name * @param Function Service * @return Bottle */ var createService = function createService(name, Service, isClass) { var deps = arguments.length > 3 ? slice.call(arguments, 3) : []; var bottle = this; return factory.call(this, name, function GenericFactory() { var serviceFactory = Service; // alias for jshint var args = deps.map(getNestedService, bottle.container); if (!isClass) { return serviceFactory.apply(null, args); } return new (Service.bind.apply(Service, [null].concat(args)))(); }); }; /** * Register a value * * @param String name * @param mixed val * @return Bottle */ var value = function value(name, val) { var parts; parts = name.split(DELIMITER); name = parts.pop(); defineValue.call(parts.reduce(setValueObject, this.container), name, val); return this; }; /** * Iterator for setting a plain object literal via defineValue * * @param Object container * @param string name */ var setValueObject = function setValueObject(container, name) { var nestedContainer = container[name]; if (!nestedContainer) { nestedContainer = {}; defineValue.call(container, name, nestedContainer); } return nestedContainer; }; /** * Define a mutable property on the container. * * @param String name * @param mixed val * @return void * @scope container */ var defineValue = function defineValue(name, val) { Object.defineProperty(this, name, { configurable : true, enumerable : true, value : val, writable : true }); }; /** * Bottle constructor * * @param String name Optional name for functional construction */ var Bottle = function Bottle(name) { if (!(this instanceof Bottle)) { return Bottle.pop(name); } this.id = id++; this.decorators = {}; this.middlewares = {}; this.nested = {}; this.providerMap = {}; this.originalProviders = {}; this.deferred = []; this.container = { $decorator : decorator.bind(this), $register : register.bind(this), $list : list.bind(this) }; }; /** * Bottle prototype */ Bottle.prototype = { constant : constant, decorator : decorator, defer : defer, digest : digest, factory : factory, instanceFactory: instanceFactory, list : list, middleware : middleware, provider : provider, resetProviders : resetProviders, register : register, resolve : resolve, service : service, serviceFactory : serviceFactory, value : value }; /** * Bottle static */ Bottle.pop = pop; Bottle.clear = clear; Bottle.list = list; /** * Global config */ var globalConfig = Bottle.config = { strict : false }; /** * Exports script adapted from lodash v2.4.1 Modern Build * * @see http://lodash.com/ */ /** * Valid object type map * * @type Object */ var objectTypes = { 'function' : true, 'object' : true }; (function exportBottle(root) { /** * Free variable exports * * @type Function */ var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; /** * Free variable module * * @type Object */ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** * CommonJS module.exports * * @type Function */ var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; /** * Free variable `global` * * @type Object */ var freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } /** * Export */ if ("function" === FUNCTION_TYPE && typeof __webpack_require__(/*! !webpack amd options */ "../../node_modules/webpack/buildin/amd-options.js") === 'object' && __webpack_require__(/*! !webpack amd options */ "../../node_modules/webpack/buildin/amd-options.js")) { root.Bottle = Bottle; !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return Bottle; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (freeExports && freeModule) { if (moduleExports) { (freeModule.exports = Bottle).Bottle = Bottle; } else { freeExports.Bottle = Bottle; } } else { root.Bottle = Bottle; } }((objectTypes[typeof window] && window) || this)); }.call(this)); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/module.js */ "../../node_modules/webpack/buildin/module.js")(module), __webpack_require__(/*! ./../../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "../../node_modules/core-js/library/fn/array/from.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/array/from.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.string.iterator */ "../../node_modules/core-js/library/modules/es6.string.iterator.js"); __webpack_require__(/*! ../../modules/es6.array.from */ "../../node_modules/core-js/library/modules/es6.array.from.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Array.from; /***/ }), /***/ "../../node_modules/core-js/library/fn/get-iterator.js": /*!****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/get-iterator.js ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../modules/web.dom.iterable */ "../../node_modules/core-js/library/modules/web.dom.iterable.js"); __webpack_require__(/*! ../modules/es6.string.iterator */ "../../node_modules/core-js/library/modules/es6.string.iterator.js"); module.exports = __webpack_require__(/*! ../modules/core.get-iterator */ "../../node_modules/core-js/library/modules/core.get-iterator.js"); /***/ }), /***/ "../../node_modules/core-js/library/fn/json/stringify.js": /*!******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/json/stringify.js ***! \******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var core = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js"); var $JSON = core.JSON || (core.JSON = { stringify: JSON.stringify }); module.exports = function stringify(it) { // eslint-disable-line no-unused-vars return $JSON.stringify.apply($JSON, arguments); }; /***/ }), /***/ "../../node_modules/core-js/library/fn/object/assign.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/object/assign.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.assign */ "../../node_modules/core-js/library/modules/es6.object.assign.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Object.assign; /***/ }), /***/ "../../node_modules/core-js/library/fn/object/create.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/object/create.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.create */ "../../node_modules/core-js/library/modules/es6.object.create.js"); var $Object = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Object; module.exports = function create(P, D) { return $Object.create(P, D); }; /***/ }), /***/ "../../node_modules/core-js/library/fn/object/define-properties.js": /*!****************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/object/define-properties.js ***! \****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.define-properties */ "../../node_modules/core-js/library/modules/es6.object.define-properties.js"); var $Object = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Object; module.exports = function defineProperties(T, D) { return $Object.defineProperties(T, D); }; /***/ }), /***/ "../../node_modules/core-js/library/fn/object/define-property.js": /*!**************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/object/define-property.js ***! \**************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.define-property */ "../../node_modules/core-js/library/modules/es6.object.define-property.js"); var $Object = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Object; module.exports = function defineProperty(it, key, desc) { return $Object.defineProperty(it, key, desc); }; /***/ }), /***/ "../../node_modules/core-js/library/fn/object/freeze.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/object/freeze.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.freeze */ "../../node_modules/core-js/library/modules/es6.object.freeze.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Object.freeze; /***/ }), /***/ "../../node_modules/core-js/library/fn/object/get-own-property-descriptor.js": /*!**************************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/object/get-own-property-descriptor.js ***! \**************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.get-own-property-descriptor */ "../../node_modules/core-js/library/modules/es6.object.get-own-property-descriptor.js"); var $Object = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Object; module.exports = function getOwnPropertyDescriptor(it, key) { return $Object.getOwnPropertyDescriptor(it, key); }; /***/ }), /***/ "../../node_modules/core-js/library/fn/object/get-prototype-of.js": /*!***************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/object/get-prototype-of.js ***! \***************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.get-prototype-of */ "../../node_modules/core-js/library/modules/es6.object.get-prototype-of.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Object.getPrototypeOf; /***/ }), /***/ "../../node_modules/core-js/library/fn/object/keys.js": /*!***************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/object/keys.js ***! \***************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.object.keys */ "../../node_modules/core-js/library/modules/es6.object.keys.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Object.keys; /***/ }), /***/ "../../node_modules/core-js/library/fn/object/values.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/object/values.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es7.object.values */ "../../node_modules/core-js/library/modules/es7.object.values.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Object.values; /***/ }), /***/ "../../node_modules/core-js/library/fn/promise.js": /*!***********************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/promise.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../modules/es6.object.to-string */ "../../node_modules/core-js/library/modules/es6.object.to-string.js"); __webpack_require__(/*! ../modules/es6.string.iterator */ "../../node_modules/core-js/library/modules/es6.string.iterator.js"); __webpack_require__(/*! ../modules/web.dom.iterable */ "../../node_modules/core-js/library/modules/web.dom.iterable.js"); __webpack_require__(/*! ../modules/es6.promise */ "../../node_modules/core-js/library/modules/es6.promise.js"); __webpack_require__(/*! ../modules/es7.promise.finally */ "../../node_modules/core-js/library/modules/es7.promise.finally.js"); __webpack_require__(/*! ../modules/es7.promise.try */ "../../node_modules/core-js/library/modules/es7.promise.try.js"); module.exports = __webpack_require__(/*! ../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Promise; /***/ }), /***/ "../../node_modules/core-js/library/fn/symbol/index.js": /*!****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/symbol/index.js ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.symbol */ "../../node_modules/core-js/library/modules/es6.symbol.js"); __webpack_require__(/*! ../../modules/es6.object.to-string */ "../../node_modules/core-js/library/modules/es6.object.to-string.js"); __webpack_require__(/*! ../../modules/es7.symbol.async-iterator */ "../../node_modules/core-js/library/modules/es7.symbol.async-iterator.js"); __webpack_require__(/*! ../../modules/es7.symbol.observable */ "../../node_modules/core-js/library/modules/es7.symbol.observable.js"); module.exports = __webpack_require__(/*! ../../modules/_core */ "../../node_modules/core-js/library/modules/_core.js").Symbol; /***/ }), /***/ "../../node_modules/core-js/library/fn/symbol/iterator.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/fn/symbol/iterator.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ../../modules/es6.string.iterator */ "../../node_modules/core-js/library/modules/es6.string.iterator.js"); __webpack_require__(/*! ../../modules/web.dom.iterable */ "../../node_modules/core-js/library/modules/web.dom.iterable.js"); module.exports = __webpack_require__(/*! ../../modules/_wks-ext */ "../../node_modules/core-js/library/modules/_wks-ext.js").f('iterator'); /***/ }), /***/ "../../node_modules/core-js/library/modules/_a-function.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_a-function.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (it) { if (typeof it != 'function') throw TypeError(it + ' is not a function!'); return it; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_add-to-unscopables.js": /*!****************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_add-to-unscopables.js ***! \****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function () { /* empty */ }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_an-instance.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_an-instance.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (it, Constructor, name, forbiddenField) { if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { throw TypeError(name + ': incorrect invocation!'); } return it; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_an-object.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_an-object.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(/*! ./_is-object */ "../../node_modules/core-js/library/modules/_is-object.js"); module.exports = function (it) { if (!isObject(it)) throw TypeError(it + ' is not an object!'); return it; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_array-includes.js": /*!************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_array-includes.js ***! \************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(/*! ./_to-iobject */ "../../node_modules/core-js/library/modules/_to-iobject.js"); var toLength = __webpack_require__(/*! ./_to-length */ "../../node_modules/core-js/library/modules/_to-length.js"); var toAbsoluteIndex = __webpack_require__(/*! ./_to-absolute-index */ "../../node_modules/core-js/library/modules/_to-absolute-index.js"); module.exports = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) if (IS_INCLUDES || index in O) { if (O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_classof.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_classof.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(/*! ./_cof */ "../../node_modules/core-js/library/modules/_cof.js"); var TAG = __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js")('toStringTag'); // ES3 wrong here var ARG = cof(function () { return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; } catch (e) { /* empty */ } }; module.exports = function (it) { var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_cof.js": /*!*************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_cof.js ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = function (it) { return toString.call(it).slice(8, -1); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_core.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_core.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { var core = module.exports = { version: '2.5.5' }; if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef /***/ }), /***/ "../../node_modules/core-js/library/modules/_create-property.js": /*!*************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_create-property.js ***! \*************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $defineProperty = __webpack_require__(/*! ./_object-dp */ "../../node_modules/core-js/library/modules/_object-dp.js"); var createDesc = __webpack_require__(/*! ./_property-desc */ "../../node_modules/core-js/library/modules/_property-desc.js"); module.exports = function (object, index, value) { if (index in object) $defineProperty.f(object, index, createDesc(0, value)); else object[index] = value; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_ctx.js": /*!*************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_ctx.js ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(/*! ./_a-function */ "../../node_modules/core-js/library/modules/_a-function.js"); module.exports = function (fn, that, length) { aFunction(fn); if (that === undefined) return fn; switch (length) { case 1: return function (a) { return fn.call(that, a); }; case 2: return function (a, b) { return fn.call(that, a, b); }; case 3: return function (a, b, c) { return fn.call(that, a, b, c); }; } return function (/* ...args */) { return fn.apply(that, arguments); }; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_defined.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_defined.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_descriptors.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_descriptors.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(/*! ./_fails */ "../../node_modules/core-js/library/modules/_fails.js")(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /***/ "../../node_modules/core-js/library/modules/_dom-create.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_dom-create.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(/*! ./_is-object */ "../../node_modules/core-js/library/modules/_is-object.js"); var document = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js").document; // typeof document.createElement is 'object' in old IE var is = isObject(document) && isObject(document.createElement); module.exports = function (it) { return is ? document.createElement(it) : {}; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_enum-bug-keys.js": /*!***********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_enum-bug-keys.js ***! \***********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }), /***/ "../../node_modules/core-js/library/modules/_enum-keys.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_enum-keys.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var getKeys = __webpack_require__(/*! ./_object-keys */ "../../node_modules/core-js/library/modules/_object-keys.js"); var gOPS = __webpack_require__(/*! ./_object-gops */ "../../node_modules/core-js/library/modules/_object-gops.js"); var pIE = __webpack_require__(/*! ./_object-pie */ "../../node_modules/core-js/library/modules/_object-pie.js"); module.exports = function (it) { var result = getKeys(it); var getSymbols = gOPS.f; if (getSymbols) { var symbols = getSymbols(it); var isEnum = pIE.f; var i = 0; var key; while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); } return result; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_export.js": /*!****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_export.js ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js"); var core = __webpack_require__(/*! ./_core */ "../../node_modules/core-js/library/modules/_core.js"); var ctx = __webpack_require__(/*! ./_ctx */ "../../node_modules/core-js/library/modules/_ctx.js"); var hide = __webpack_require__(/*! ./_hide */ "../../node_modules/core-js/library/modules/_hide.js"); var has = __webpack_require__(/*! ./_has */ "../../node_modules/core-js/library/modules/_has.js"); var PROTOTYPE = 'prototype'; var $export = function (type, name, source) { var IS_FORCED = type & $export.F; var IS_GLOBAL = type & $export.G; var IS_STATIC = type & $export.S; var IS_PROTO = type & $export.P; var IS_BIND = type & $export.B; var IS_WRAP = type & $export.W; var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); var expProto = exports[PROTOTYPE]; var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; var key, own, out; if (IS_GLOBAL) source = name; for (key in source) { // contains in native own = !IS_FORCED && target && target[key] !== undefined; if (own && has(exports, key)) continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function (C) { var F = function (a, b, c) { if (this instanceof C) { switch (arguments.length) { case 0: return new C(); case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if (IS_PROTO) { (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }), /***/ "../../node_modules/core-js/library/modules/_fails.js": /*!***************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_fails.js ***! \***************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (exec) { try { return !!exec(); } catch (e) { return true; } }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_for-of.js": /*!****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_for-of.js ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var ctx = __webpack_require__(/*! ./_ctx */ "../../node_modules/core-js/library/modules/_ctx.js"); var call = __webpack_require__(/*! ./_iter-call */ "../../node_modules/core-js/library/modules/_iter-call.js"); var isArrayIter = __webpack_require__(/*! ./_is-array-iter */ "../../node_modules/core-js/library/modules/_is-array-iter.js"); var anObject = __webpack_require__(/*! ./_an-object */ "../../node_modules/core-js/library/modules/_an-object.js"); var toLength = __webpack_require__(/*! ./_to-length */ "../../node_modules/core-js/library/modules/_to-length.js"); var getIterFn = __webpack_require__(/*! ./core.get-iterator-method */ "../../node_modules/core-js/library/modules/core.get-iterator-method.js"); var BREAK = {}; var RETURN = {}; var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); var f = ctx(fn, that, entries ? 2 : 1); var index = 0; var length, step, iterator, result; if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if (result === BREAK || result === RETURN) return result; } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { result = call(iterator, f, step.value, entries); if (result === BREAK || result === RETURN) return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; /***/ }), /***/ "../../node_modules/core-js/library/modules/_global.js": /*!****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_global.js ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef /***/ }), /***/ "../../node_modules/core-js/library/modules/_has.js": /*!*************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_has.js ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function (it, key) { return hasOwnProperty.call(it, key); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_hide.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_hide.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(/*! ./_object-dp */ "../../node_modules/core-js/library/modules/_object-dp.js"); var createDesc = __webpack_require__(/*! ./_property-desc */ "../../node_modules/core-js/library/modules/_property-desc.js"); module.exports = __webpack_require__(/*! ./_descriptors */ "../../node_modules/core-js/library/modules/_descriptors.js") ? function (object, key, value) { return dP.f(object, key, createDesc(1, value)); } : function (object, key, value) { object[key] = value; return object; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_html.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_html.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var document = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js").document; module.exports = document && document.documentElement; /***/ }), /***/ "../../node_modules/core-js/library/modules/_ie8-dom-define.js": /*!************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_ie8-dom-define.js ***! \************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(/*! ./_descriptors */ "../../node_modules/core-js/library/modules/_descriptors.js") && !__webpack_require__(/*! ./_fails */ "../../node_modules/core-js/library/modules/_fails.js")(function () { return Object.defineProperty(__webpack_require__(/*! ./_dom-create */ "../../node_modules/core-js/library/modules/_dom-create.js")('div'), 'a', { get: function () { return 7; } }).a != 7; }); /***/ }), /***/ "../../node_modules/core-js/library/modules/_invoke.js": /*!****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_invoke.js ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function (fn, args, that) { var un = that === undefined; switch (args.length) { case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_iobject.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_iobject.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(/*! ./_cof */ "../../node_modules/core-js/library/modules/_cof.js"); // eslint-disable-next-line no-prototype-builtins module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_is-array-iter.js": /*!***********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_is-array-iter.js ***! \***********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(/*! ./_iterators */ "../../node_modules/core-js/library/modules/_iterators.js"); var ITERATOR = __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js")('iterator'); var ArrayProto = Array.prototype; module.exports = function (it) { return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_is-array.js": /*!******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_is-array.js ***! \******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(/*! ./_cof */ "../../node_modules/core-js/library/modules/_cof.js"); module.exports = Array.isArray || function isArray(arg) { return cof(arg) == 'Array'; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_is-object.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_is-object.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_iter-call.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_iter-call.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(/*! ./_an-object */ "../../node_modules/core-js/library/modules/_an-object.js"); module.exports = function (iterator, fn, value, entries) { try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch (e) { var ret = iterator['return']; if (ret !== undefined) anObject(ret.call(iterator)); throw e; } }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_iter-create.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_iter-create.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var create = __webpack_require__(/*! ./_object-create */ "../../node_modules/core-js/library/modules/_object-create.js"); var descriptor = __webpack_require__(/*! ./_property-desc */ "../../node_modules/core-js/library/modules/_property-desc.js"); var setToStringTag = __webpack_require__(/*! ./_set-to-string-tag */ "../../node_modules/core-js/library/modules/_set-to-string-tag.js"); var IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(/*! ./_hide */ "../../node_modules/core-js/library/modules/_hide.js")(IteratorPrototype, __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js")('iterator'), function () { return this; }); module.exports = function (Constructor, NAME, next) { Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_iter-define.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_iter-define.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var LIBRARY = __webpack_require__(/*! ./_library */ "../../node_modules/core-js/library/modules/_library.js"); var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); var redefine = __webpack_require__(/*! ./_redefine */ "../../node_modules/core-js/library/modules/_redefine.js"); var hide = __webpack_require__(/*! ./_hide */ "../../node_modules/core-js/library/modules/_hide.js"); var Iterators = __webpack_require__(/*! ./_iterators */ "../../node_modules/core-js/library/modules/_iterators.js"); var $iterCreate = __webpack_require__(/*! ./_iter-create */ "../../node_modules/core-js/library/modules/_iter-create.js"); var setToStringTag = __webpack_require__(/*! ./_set-to-string-tag */ "../../node_modules/core-js/library/modules/_set-to-string-tag.js"); var getPrototypeOf = __webpack_require__(/*! ./_object-gpo */ "../../node_modules/core-js/library/modules/_object-gpo.js"); var ITERATOR = __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js")('iterator'); var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` var FF_ITERATOR = '@@iterator'; var KEYS = 'keys'; var VALUES = 'values'; var returnThis = function () { return this; }; module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { $iterCreate(Constructor, NAME, next); var getMethod = function (kind) { if (!BUGGY && kind in proto) return proto[kind]; switch (kind) { case KEYS: return function keys() { return new Constructor(this, kind); }; case VALUES: return function values() { return new Constructor(this, kind); }; } return function entries() { return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator'; var DEF_VALUES = DEFAULT == VALUES; var VALUES_BUG = false; var proto = Base.prototype; var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; var $default = $native || getMethod(DEFAULT); var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; var methods, key, IteratorPrototype; // Fix native if ($anyNative) { IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if (DEF_VALUES && $native && $native.name !== VALUES) { VALUES_BUG = true; $default = function values() { return $native.call(this); }; } // Define iterator if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if (DEFAULT) { methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if (FORCED) for (key in methods) { if (!(key in proto)) redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_iter-detect.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_iter-detect.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js")('iterator'); var SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function () { SAFE_CLOSING = true; }; // eslint-disable-next-line no-throw-literal Array.from(riter, function () { throw 2; }); } catch (e) { /* empty */ } module.exports = function (exec, skipClosing) { if (!skipClosing && !SAFE_CLOSING) return false; var safe = false; try { var arr = [7]; var iter = arr[ITERATOR](); iter.next = function () { return { done: safe = true }; }; arr[ITERATOR] = function () { return iter; }; exec(arr); } catch (e) { /* empty */ } return safe; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_iter-step.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_iter-step.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (done, value) { return { value: value, done: !!done }; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_iterators.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_iterators.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = {}; /***/ }), /***/ "../../node_modules/core-js/library/modules/_library.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_library.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = true; /***/ }), /***/ "../../node_modules/core-js/library/modules/_meta.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_meta.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var META = __webpack_require__(/*! ./_uid */ "../../node_modules/core-js/library/modules/_uid.js")('meta'); var isObject = __webpack_require__(/*! ./_is-object */ "../../node_modules/core-js/library/modules/_is-object.js"); var has = __webpack_require__(/*! ./_has */ "../../node_modules/core-js/library/modules/_has.js"); var setDesc = __webpack_require__(/*! ./_object-dp */ "../../node_modules/core-js/library/modules/_object-dp.js").f; var id = 0; var isExtensible = Object.isExtensible || function () { return true; }; var FREEZE = !__webpack_require__(/*! ./_fails */ "../../node_modules/core-js/library/modules/_fails.js")(function () { return isExtensible(Object.preventExtensions({})); }); var setMeta = function (it) { setDesc(it, META, { value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs } }); }; var fastKey = function (it, create) { // return primitive with prefix if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return 'F'; // not necessary to add metadata if (!create) return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function (it, create) { if (!has(it, META)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return true; // not necessary to add metadata if (!create) return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function (it) { if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_microtask.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_microtask.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js"); var macrotask = __webpack_require__(/*! ./_task */ "../../node_modules/core-js/library/modules/_task.js").set; var Observer = global.MutationObserver || global.WebKitMutationObserver; var process = global.process; var Promise = global.Promise; var isNode = __webpack_require__(/*! ./_cof */ "../../node_modules/core-js/library/modules/_cof.js")(process) == 'process'; module.exports = function () { var head, last, notify; var flush = function () { var parent, fn; if (isNode && (parent = process.domain)) parent.exit(); while (head) { fn = head.fn; head = head.next; try { fn(); } catch (e) { if (head) notify(); else last = undefined; throw e; } } last = undefined; if (parent) parent.enter(); }; // Node.js if (isNode) { notify = function () { process.nextTick(flush); }; // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 } else if (Observer && !(global.navigator && global.navigator.standalone)) { var toggle = true; var node = document.createTextNode(''); new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new notify = function () { node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if (Promise && Promise.resolve) { var promise = Promise.resolve(); notify = function () { promise.then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function () { // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } return function (fn) { var task = { fn: fn, next: undefined }; if (last) last.next = task; if (!head) { head = task; notify(); } last = task; }; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_new-promise-capability.js": /*!********************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_new-promise-capability.js ***! \********************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 25.4.1.5 NewPromiseCapability(C) var aFunction = __webpack_require__(/*! ./_a-function */ "../../node_modules/core-js/library/modules/_a-function.js"); function PromiseCapability(C) { var resolve, reject; this.promise = new C(function ($$resolve, $$reject) { if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); } module.exports.f = function (C) { return new PromiseCapability(C); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-assign.js": /*!***********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-assign.js ***! \***********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // 19.1.2.1 Object.assign(target, source, ...) var getKeys = __webpack_require__(/*! ./_object-keys */ "../../node_modules/core-js/library/modules/_object-keys.js"); var gOPS = __webpack_require__(/*! ./_object-gops */ "../../node_modules/core-js/library/modules/_object-gops.js"); var pIE = __webpack_require__(/*! ./_object-pie */ "../../node_modules/core-js/library/modules/_object-pie.js"); var toObject = __webpack_require__(/*! ./_to-object */ "../../node_modules/core-js/library/modules/_to-object.js"); var IObject = __webpack_require__(/*! ./_iobject */ "../../node_modules/core-js/library/modules/_iobject.js"); var $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) module.exports = !$assign || __webpack_require__(/*! ./_fails */ "../../node_modules/core-js/library/modules/_fails.js")(function () { var A = {}; var B = {}; // eslint-disable-next-line no-undef var S = Symbol(); var K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function (k) { B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source) { // eslint-disable-line no-unused-vars var T = toObject(target); var aLen = arguments.length; var index = 1; var getSymbols = gOPS.f; var isEnum = pIE.f; while (aLen > index) { var S = IObject(arguments[index++]); var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); var length = keys.length; var j = 0; var key; while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; } return T; } : $assign; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-create.js": /*!***********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-create.js ***! \***********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(/*! ./_an-object */ "../../node_modules/core-js/library/modules/_an-object.js"); var dPs = __webpack_require__(/*! ./_object-dps */ "../../node_modules/core-js/library/modules/_object-dps.js"); var enumBugKeys = __webpack_require__(/*! ./_enum-bug-keys */ "../../node_modules/core-js/library/modules/_enum-bug-keys.js"); var IE_PROTO = __webpack_require__(/*! ./_shared-key */ "../../node_modules/core-js/library/modules/_shared-key.js")('IE_PROTO'); var Empty = function () { /* empty */ }; var PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function () { // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__(/*! ./_dom-create */ "../../node_modules/core-js/library/modules/_dom-create.js")('iframe'); var i = enumBugKeys.length; var lt = '<'; var gt = '>'; var iframeDocument; iframe.style.display = 'none'; __webpack_require__(/*! ./_html */ "../../node_modules/core-js/library/modules/_html.js").appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties) { var result; if (O !== null) { Empty[PROTOTYPE] = anObject(O); result = new Empty(); Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-dp.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-dp.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(/*! ./_an-object */ "../../node_modules/core-js/library/modules/_an-object.js"); var IE8_DOM_DEFINE = __webpack_require__(/*! ./_ie8-dom-define */ "../../node_modules/core-js/library/modules/_ie8-dom-define.js"); var toPrimitive = __webpack_require__(/*! ./_to-primitive */ "../../node_modules/core-js/library/modules/_to-primitive.js"); var dP = Object.defineProperty; exports.f = __webpack_require__(/*! ./_descriptors */ "../../node_modules/core-js/library/modules/_descriptors.js") ? Object.defineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (IE8_DOM_DEFINE) try { return dP(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-dps.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-dps.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var dP = __webpack_require__(/*! ./_object-dp */ "../../node_modules/core-js/library/modules/_object-dp.js"); var anObject = __webpack_require__(/*! ./_an-object */ "../../node_modules/core-js/library/modules/_an-object.js"); var getKeys = __webpack_require__(/*! ./_object-keys */ "../../node_modules/core-js/library/modules/_object-keys.js"); module.exports = __webpack_require__(/*! ./_descriptors */ "../../node_modules/core-js/library/modules/_descriptors.js") ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = getKeys(Properties); var length = keys.length; var i = 0; var P; while (length > i) dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-gopd.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-gopd.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var pIE = __webpack_require__(/*! ./_object-pie */ "../../node_modules/core-js/library/modules/_object-pie.js"); var createDesc = __webpack_require__(/*! ./_property-desc */ "../../node_modules/core-js/library/modules/_property-desc.js"); var toIObject = __webpack_require__(/*! ./_to-iobject */ "../../node_modules/core-js/library/modules/_to-iobject.js"); var toPrimitive = __webpack_require__(/*! ./_to-primitive */ "../../node_modules/core-js/library/modules/_to-primitive.js"); var has = __webpack_require__(/*! ./_has */ "../../node_modules/core-js/library/modules/_has.js"); var IE8_DOM_DEFINE = __webpack_require__(/*! ./_ie8-dom-define */ "../../node_modules/core-js/library/modules/_ie8-dom-define.js"); var gOPD = Object.getOwnPropertyDescriptor; exports.f = __webpack_require__(/*! ./_descriptors */ "../../node_modules/core-js/library/modules/_descriptors.js") ? gOPD : function getOwnPropertyDescriptor(O, P) { O = toIObject(O); P = toPrimitive(P, true); if (IE8_DOM_DEFINE) try { return gOPD(O, P); } catch (e) { /* empty */ } if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-gopn-ext.js": /*!*************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-gopn-ext.js ***! \*************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(/*! ./_to-iobject */ "../../node_modules/core-js/library/modules/_to-iobject.js"); var gOPN = __webpack_require__(/*! ./_object-gopn */ "../../node_modules/core-js/library/modules/_object-gopn.js").f; var toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function (it) { try { return gOPN(it); } catch (e) { return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it) { return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-gopn.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-gopn.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = __webpack_require__(/*! ./_object-keys-internal */ "../../node_modules/core-js/library/modules/_object-keys-internal.js"); var hiddenKeys = __webpack_require__(/*! ./_enum-bug-keys */ "../../node_modules/core-js/library/modules/_enum-bug-keys.js").concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return $keys(O, hiddenKeys); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-gops.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-gops.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-gpo.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-gpo.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__(/*! ./_has */ "../../node_modules/core-js/library/modules/_has.js"); var toObject = __webpack_require__(/*! ./_to-object */ "../../node_modules/core-js/library/modules/_to-object.js"); var IE_PROTO = __webpack_require__(/*! ./_shared-key */ "../../node_modules/core-js/library/modules/_shared-key.js")('IE_PROTO'); var ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function (O) { O = toObject(O); if (has(O, IE_PROTO)) return O[IE_PROTO]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-keys-internal.js": /*!******************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-keys-internal.js ***! \******************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var has = __webpack_require__(/*! ./_has */ "../../node_modules/core-js/library/modules/_has.js"); var toIObject = __webpack_require__(/*! ./_to-iobject */ "../../node_modules/core-js/library/modules/_to-iobject.js"); var arrayIndexOf = __webpack_require__(/*! ./_array-includes */ "../../node_modules/core-js/library/modules/_array-includes.js")(false); var IE_PROTO = __webpack_require__(/*! ./_shared-key */ "../../node_modules/core-js/library/modules/_shared-key.js")('IE_PROTO'); module.exports = function (object, names) { var O = toIObject(object); var i = 0; var result = []; var key; for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-keys.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-keys.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(/*! ./_object-keys-internal */ "../../node_modules/core-js/library/modules/_object-keys-internal.js"); var enumBugKeys = __webpack_require__(/*! ./_enum-bug-keys */ "../../node_modules/core-js/library/modules/_enum-bug-keys.js"); module.exports = Object.keys || function keys(O) { return $keys(O, enumBugKeys); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-pie.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-pie.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-sap.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-sap.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); var core = __webpack_require__(/*! ./_core */ "../../node_modules/core-js/library/modules/_core.js"); var fails = __webpack_require__(/*! ./_fails */ "../../node_modules/core-js/library/modules/_fails.js"); module.exports = function (KEY, exec) { var fn = (core.Object || {})[KEY] || Object[KEY]; var exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_object-to-array.js": /*!*************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_object-to-array.js ***! \*************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var getKeys = __webpack_require__(/*! ./_object-keys */ "../../node_modules/core-js/library/modules/_object-keys.js"); var toIObject = __webpack_require__(/*! ./_to-iobject */ "../../node_modules/core-js/library/modules/_to-iobject.js"); var isEnum = __webpack_require__(/*! ./_object-pie */ "../../node_modules/core-js/library/modules/_object-pie.js").f; module.exports = function (isEntries) { return function (it) { var O = toIObject(it); var keys = getKeys(O); var length = keys.length; var i = 0; var result = []; var key; while (length > i) if (isEnum.call(O, key = keys[i++])) { result.push(isEntries ? [key, O[key]] : O[key]); } return result; }; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_perform.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_perform.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (exec) { try { return { e: false, v: exec() }; } catch (e) { return { e: true, v: e }; } }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_promise-resolve.js": /*!*************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_promise-resolve.js ***! \*************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(/*! ./_an-object */ "../../node_modules/core-js/library/modules/_an-object.js"); var isObject = __webpack_require__(/*! ./_is-object */ "../../node_modules/core-js/library/modules/_is-object.js"); var newPromiseCapability = __webpack_require__(/*! ./_new-promise-capability */ "../../node_modules/core-js/library/modules/_new-promise-capability.js"); module.exports = function (C, x) { anObject(C); if (isObject(x) && x.constructor === C) return x; var promiseCapability = newPromiseCapability.f(C); var resolve = promiseCapability.resolve; resolve(x); return promiseCapability.promise; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_property-desc.js": /*!***********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_property-desc.js ***! \***********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_redefine-all.js": /*!**********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_redefine-all.js ***! \**********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var hide = __webpack_require__(/*! ./_hide */ "../../node_modules/core-js/library/modules/_hide.js"); module.exports = function (target, src, safe) { for (var key in src) { if (safe && target[key]) target[key] = src[key]; else hide(target, key, src[key]); } return target; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_redefine.js": /*!******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_redefine.js ***! \******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./_hide */ "../../node_modules/core-js/library/modules/_hide.js"); /***/ }), /***/ "../../node_modules/core-js/library/modules/_set-species.js": /*!*********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_set-species.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var global = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js"); var core = __webpack_require__(/*! ./_core */ "../../node_modules/core-js/library/modules/_core.js"); var dP = __webpack_require__(/*! ./_object-dp */ "../../node_modules/core-js/library/modules/_object-dp.js"); var DESCRIPTORS = __webpack_require__(/*! ./_descriptors */ "../../node_modules/core-js/library/modules/_descriptors.js"); var SPECIES = __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js")('species'); module.exports = function (KEY) { var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { configurable: true, get: function () { return this; } }); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_set-to-string-tag.js": /*!***************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_set-to-string-tag.js ***! \***************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var def = __webpack_require__(/*! ./_object-dp */ "../../node_modules/core-js/library/modules/_object-dp.js").f; var has = __webpack_require__(/*! ./_has */ "../../node_modules/core-js/library/modules/_has.js"); var TAG = __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js")('toStringTag'); module.exports = function (it, tag, stat) { if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_shared-key.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_shared-key.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var shared = __webpack_require__(/*! ./_shared */ "../../node_modules/core-js/library/modules/_shared.js")('keys'); var uid = __webpack_require__(/*! ./_uid */ "../../node_modules/core-js/library/modules/_uid.js"); module.exports = function (key) { return shared[key] || (shared[key] = uid(key)); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_shared.js": /*!****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_shared.js ***! \****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js"); var SHARED = '__core-js_shared__'; var store = global[SHARED] || (global[SHARED] = {}); module.exports = function (key) { return store[key] || (store[key] = {}); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_species-constructor.js": /*!*****************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_species-constructor.js ***! \*****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = __webpack_require__(/*! ./_an-object */ "../../node_modules/core-js/library/modules/_an-object.js"); var aFunction = __webpack_require__(/*! ./_a-function */ "../../node_modules/core-js/library/modules/_a-function.js"); var SPECIES = __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js")('species'); module.exports = function (O, D) { var C = anObject(O).constructor; var S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_string-at.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_string-at.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(/*! ./_to-integer */ "../../node_modules/core-js/library/modules/_to-integer.js"); var defined = __webpack_require__(/*! ./_defined */ "../../node_modules/core-js/library/modules/_defined.js"); // true -> String#at // false -> String#codePointAt module.exports = function (TO_STRING) { return function (that, pos) { var s = String(defined(that)); var i = toInteger(pos); var l = s.length; var a, b; if (i < 0 || i >= l) return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_task.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_task.js ***! \**************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var ctx = __webpack_require__(/*! ./_ctx */ "../../node_modules/core-js/library/modules/_ctx.js"); var invoke = __webpack_require__(/*! ./_invoke */ "../../node_modules/core-js/library/modules/_invoke.js"); var html = __webpack_require__(/*! ./_html */ "../../node_modules/core-js/library/modules/_html.js"); var cel = __webpack_require__(/*! ./_dom-create */ "../../node_modules/core-js/library/modules/_dom-create.js"); var global = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js"); var process = global.process; var setTask = global.setImmediate; var clearTask = global.clearImmediate; var MessageChannel = global.MessageChannel; var Dispatch = global.Dispatch; var counter = 0; var queue = {}; var ONREADYSTATECHANGE = 'onreadystatechange'; var defer, channel, port; var run = function () { var id = +this; // eslint-disable-next-line no-prototype-builtins if (queue.hasOwnProperty(id)) { var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function (event) { run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if (!setTask || !clearTask) { setTask = function setImmediate(fn) { var args = []; var i = 1; while (arguments.length > i) args.push(arguments[i++]); queue[++counter] = function () { // eslint-disable-next-line no-new-func invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id) { delete queue[id]; }; // Node.js 0.8- if (__webpack_require__(/*! ./_cof */ "../../node_modules/core-js/library/modules/_cof.js")(process) == 'process') { defer = function (id) { process.nextTick(ctx(run, id, 1)); }; // Sphere (JS game engine) Dispatch API } else if (Dispatch && Dispatch.now) { defer = function (id) { Dispatch.now(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if (MessageChannel) { channel = new MessageChannel(); port = channel.port2; channel.port1.onmessage = listener; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { defer = function (id) { global.postMessage(id + '', '*'); }; global.addEventListener('message', listener, false); // IE8- } else if (ONREADYSTATECHANGE in cel('script')) { defer = function (id) { html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function (id) { setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_to-absolute-index.js": /*!***************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_to-absolute-index.js ***! \***************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(/*! ./_to-integer */ "../../node_modules/core-js/library/modules/_to-integer.js"); var max = Math.max; var min = Math.min; module.exports = function (index, length) { index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_to-integer.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_to-integer.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil; var floor = Math.floor; module.exports = function (it) { return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_to-iobject.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_to-iobject.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(/*! ./_iobject */ "../../node_modules/core-js/library/modules/_iobject.js"); var defined = __webpack_require__(/*! ./_defined */ "../../node_modules/core-js/library/modules/_defined.js"); module.exports = function (it) { return IObject(defined(it)); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_to-length.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_to-length.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(/*! ./_to-integer */ "../../node_modules/core-js/library/modules/_to-integer.js"); var min = Math.min; module.exports = function (it) { return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_to-object.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_to-object.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(/*! ./_defined */ "../../node_modules/core-js/library/modules/_defined.js"); module.exports = function (it) { return Object(defined(it)); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_to-primitive.js": /*!**********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_to-primitive.js ***! \**********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(/*! ./_is-object */ "../../node_modules/core-js/library/modules/_is-object.js"); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function (it, S) { if (!isObject(it)) return it; var fn, val; if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_uid.js": /*!*************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_uid.js ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { var id = 0; var px = Math.random(); module.exports = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_wks-define.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_wks-define.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var global = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js"); var core = __webpack_require__(/*! ./_core */ "../../node_modules/core-js/library/modules/_core.js"); var LIBRARY = __webpack_require__(/*! ./_library */ "../../node_modules/core-js/library/modules/_library.js"); var wksExt = __webpack_require__(/*! ./_wks-ext */ "../../node_modules/core-js/library/modules/_wks-ext.js"); var defineProperty = __webpack_require__(/*! ./_object-dp */ "../../node_modules/core-js/library/modules/_object-dp.js").f; module.exports = function (name) { var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/_wks-ext.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_wks-ext.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { exports.f = __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js"); /***/ }), /***/ "../../node_modules/core-js/library/modules/_wks.js": /*!*************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/_wks.js ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var store = __webpack_require__(/*! ./_shared */ "../../node_modules/core-js/library/modules/_shared.js")('wks'); var uid = __webpack_require__(/*! ./_uid */ "../../node_modules/core-js/library/modules/_uid.js"); var Symbol = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js").Symbol; var USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function (name) { return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }), /***/ "../../node_modules/core-js/library/modules/core.get-iterator-method.js": /*!*********************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/core.get-iterator-method.js ***! \*********************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var classof = __webpack_require__(/*! ./_classof */ "../../node_modules/core-js/library/modules/_classof.js"); var ITERATOR = __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js")('iterator'); var Iterators = __webpack_require__(/*! ./_iterators */ "../../node_modules/core-js/library/modules/_iterators.js"); module.exports = __webpack_require__(/*! ./_core */ "../../node_modules/core-js/library/modules/_core.js").getIteratorMethod = function (it) { if (it != undefined) return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }), /***/ "../../node_modules/core-js/library/modules/core.get-iterator.js": /*!**************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/core.get-iterator.js ***! \**************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var anObject = __webpack_require__(/*! ./_an-object */ "../../node_modules/core-js/library/modules/_an-object.js"); var get = __webpack_require__(/*! ./core.get-iterator-method */ "../../node_modules/core-js/library/modules/core.get-iterator-method.js"); module.exports = __webpack_require__(/*! ./_core */ "../../node_modules/core-js/library/modules/_core.js").getIterator = function (it) { var iterFn = get(it); if (typeof iterFn != 'function') throw TypeError(it + ' is not iterable!'); return anObject(iterFn.call(it)); }; /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.array.from.js": /*!***********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.array.from.js ***! \***********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var ctx = __webpack_require__(/*! ./_ctx */ "../../node_modules/core-js/library/modules/_ctx.js"); var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); var toObject = __webpack_require__(/*! ./_to-object */ "../../node_modules/core-js/library/modules/_to-object.js"); var call = __webpack_require__(/*! ./_iter-call */ "../../node_modules/core-js/library/modules/_iter-call.js"); var isArrayIter = __webpack_require__(/*! ./_is-array-iter */ "../../node_modules/core-js/library/modules/_is-array-iter.js"); var toLength = __webpack_require__(/*! ./_to-length */ "../../node_modules/core-js/library/modules/_to-length.js"); var createProperty = __webpack_require__(/*! ./_create-property */ "../../node_modules/core-js/library/modules/_create-property.js"); var getIterFn = __webpack_require__(/*! ./core.get-iterator-method */ "../../node_modules/core-js/library/modules/core.get-iterator-method.js"); $export($export.S + $export.F * !__webpack_require__(/*! ./_iter-detect */ "../../node_modules/core-js/library/modules/_iter-detect.js")(function (iter) { Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { var O = toObject(arrayLike); var C = typeof this == 'function' ? this : Array; var aLen = arguments.length; var mapfn = aLen > 1 ? arguments[1] : undefined; var mapping = mapfn !== undefined; var index = 0; var iterFn = getIterFn(O); var length, result, step, iterator; if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } } else { length = toLength(O.length); for (result = new C(length); length > index; index++) { createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } result.length = index; return result; } }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.array.iterator.js": /*!***************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.array.iterator.js ***! \***************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var addToUnscopables = __webpack_require__(/*! ./_add-to-unscopables */ "../../node_modules/core-js/library/modules/_add-to-unscopables.js"); var step = __webpack_require__(/*! ./_iter-step */ "../../node_modules/core-js/library/modules/_iter-step.js"); var Iterators = __webpack_require__(/*! ./_iterators */ "../../node_modules/core-js/library/modules/_iterators.js"); var toIObject = __webpack_require__(/*! ./_to-iobject */ "../../node_modules/core-js/library/modules/_to-iobject.js"); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(/*! ./_iter-define */ "../../node_modules/core-js/library/modules/_iter-define.js")(Array, 'Array', function (iterated, kind) { this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function () { var O = this._t; var kind = this._k; var index = this._i++; if (!O || index >= O.length) { this._t = undefined; return step(1); } if (kind == 'keys') return step(0, index); if (kind == 'values') return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.object.assign.js": /*!**************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.object.assign.js ***! \**************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); $export($export.S + $export.F, 'Object', { assign: __webpack_require__(/*! ./_object-assign */ "../../node_modules/core-js/library/modules/_object-assign.js") }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.object.create.js": /*!**************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.object.create.js ***! \**************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', { create: __webpack_require__(/*! ./_object-create */ "../../node_modules/core-js/library/modules/_object-create.js") }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.object.define-properties.js": /*!*************************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.object.define-properties.js ***! \*************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) $export($export.S + $export.F * !__webpack_require__(/*! ./_descriptors */ "../../node_modules/core-js/library/modules/_descriptors.js"), 'Object', { defineProperties: __webpack_require__(/*! ./_object-dps */ "../../node_modules/core-js/library/modules/_object-dps.js") }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.object.define-property.js": /*!***********************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.object.define-property.js ***! \***********************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !__webpack_require__(/*! ./_descriptors */ "../../node_modules/core-js/library/modules/_descriptors.js"), 'Object', { defineProperty: __webpack_require__(/*! ./_object-dp */ "../../node_modules/core-js/library/modules/_object-dp.js").f }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.object.freeze.js": /*!**************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.object.freeze.js ***! \**************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.5 Object.freeze(O) var isObject = __webpack_require__(/*! ./_is-object */ "../../node_modules/core-js/library/modules/_is-object.js"); var meta = __webpack_require__(/*! ./_meta */ "../../node_modules/core-js/library/modules/_meta.js").onFreeze; __webpack_require__(/*! ./_object-sap */ "../../node_modules/core-js/library/modules/_object-sap.js")('freeze', function ($freeze) { return function freeze(it) { return $freeze && isObject(it) ? $freeze(meta(it)) : it; }; }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.object.get-own-property-descriptor.js": /*!***********************************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.object.get-own-property-descriptor.js ***! \***********************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = __webpack_require__(/*! ./_to-iobject */ "../../node_modules/core-js/library/modules/_to-iobject.js"); var $getOwnPropertyDescriptor = __webpack_require__(/*! ./_object-gopd */ "../../node_modules/core-js/library/modules/_object-gopd.js").f; __webpack_require__(/*! ./_object-sap */ "../../node_modules/core-js/library/modules/_object-sap.js")('getOwnPropertyDescriptor', function () { return function getOwnPropertyDescriptor(it, key) { return $getOwnPropertyDescriptor(toIObject(it), key); }; }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.object.get-prototype-of.js": /*!************************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.object.get-prototype-of.js ***! \************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.9 Object.getPrototypeOf(O) var toObject = __webpack_require__(/*! ./_to-object */ "../../node_modules/core-js/library/modules/_to-object.js"); var $getPrototypeOf = __webpack_require__(/*! ./_object-gpo */ "../../node_modules/core-js/library/modules/_object-gpo.js"); __webpack_require__(/*! ./_object-sap */ "../../node_modules/core-js/library/modules/_object-sap.js")('getPrototypeOf', function () { return function getPrototypeOf(it) { return $getPrototypeOf(toObject(it)); }; }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.object.keys.js": /*!************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.object.keys.js ***! \************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // 19.1.2.14 Object.keys(O) var toObject = __webpack_require__(/*! ./_to-object */ "../../node_modules/core-js/library/modules/_to-object.js"); var $keys = __webpack_require__(/*! ./_object-keys */ "../../node_modules/core-js/library/modules/_object-keys.js"); __webpack_require__(/*! ./_object-sap */ "../../node_modules/core-js/library/modules/_object-sap.js")('keys', function () { return function keys(it) { return $keys(toObject(it)); }; }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.object.to-string.js": /*!*****************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.object.to-string.js ***! \*****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.promise.js": /*!********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.promise.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var LIBRARY = __webpack_require__(/*! ./_library */ "../../node_modules/core-js/library/modules/_library.js"); var global = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js"); var ctx = __webpack_require__(/*! ./_ctx */ "../../node_modules/core-js/library/modules/_ctx.js"); var classof = __webpack_require__(/*! ./_classof */ "../../node_modules/core-js/library/modules/_classof.js"); var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); var isObject = __webpack_require__(/*! ./_is-object */ "../../node_modules/core-js/library/modules/_is-object.js"); var aFunction = __webpack_require__(/*! ./_a-function */ "../../node_modules/core-js/library/modules/_a-function.js"); var anInstance = __webpack_require__(/*! ./_an-instance */ "../../node_modules/core-js/library/modules/_an-instance.js"); var forOf = __webpack_require__(/*! ./_for-of */ "../../node_modules/core-js/library/modules/_for-of.js"); var speciesConstructor = __webpack_require__(/*! ./_species-constructor */ "../../node_modules/core-js/library/modules/_species-constructor.js"); var task = __webpack_require__(/*! ./_task */ "../../node_modules/core-js/library/modules/_task.js").set; var microtask = __webpack_require__(/*! ./_microtask */ "../../node_modules/core-js/library/modules/_microtask.js")(); var newPromiseCapabilityModule = __webpack_require__(/*! ./_new-promise-capability */ "../../node_modules/core-js/library/modules/_new-promise-capability.js"); var perform = __webpack_require__(/*! ./_perform */ "../../node_modules/core-js/library/modules/_perform.js"); var promiseResolve = __webpack_require__(/*! ./_promise-resolve */ "../../node_modules/core-js/library/modules/_promise-resolve.js"); var PROMISE = 'Promise'; var TypeError = global.TypeError; var process = global.process; var $Promise = global[PROMISE]; var isNode = classof(process) == 'process'; var empty = function () { /* empty */ }; var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; var USE_NATIVE = !!function () { try { // correct subclassing with @@species support var promise = $Promise.resolve(1); var FakePromise = (promise.constructor = {})[__webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js")('species')] = function (exec) { exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch (e) { /* empty */ } }(); // helpers var isThenable = function (it) { var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var notify = function (promise, isReject) { if (promise._n) return; promise._n = true; var chain = promise._c; microtask(function () { var value = promise._v; var ok = promise._s == 1; var i = 0; var run = function (reaction) { var handler = ok ? reaction.ok : reaction.fail; var resolve = reaction.resolve; var reject = reaction.reject; var domain = reaction.domain; var result, then, exited; try { if (handler) { if (!ok) { if (promise._h == 2) onHandleUnhandled(promise); promise._h = 1; } if (handler === true) result = value; else { if (domain) domain.enter(); result = handler(value); // may throw if (domain) { domain.exit(); exited = true; } } if (result === reaction.promise) { reject(TypeError('Promise-chain cycle')); } else if (then = isThenable(result)) { then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch (e) { if (domain && !exited) domain.exit(); reject(e); } }; while (chain.length > i) run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if (isReject && !promise._h) onUnhandled(promise); }); }; var onUnhandled = function (promise) { task.call(global, function () { var value = promise._v; var unhandled = isUnhandled(promise); var result, handler, console; if (unhandled) { result = perform(function () { if (isNode) { process.emit('unhandledRejection', value, promise); } else if (handler = global.onunhandledrejection) { handler({ promise: promise, reason: value }); } else if ((console = global.console) && console.error) { console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if (unhandled && result.e) throw result.v; }); }; var isUnhandled = function (promise) { return promise._h !== 1 && (promise._a || promise._c).length === 0; }; var onHandleUnhandled = function (promise) { task.call(global, function () { var handler; if (isNode) { process.emit('rejectionHandled', promise); } else if (handler = global.onrejectionhandled) { handler({ promise: promise, reason: promise._v }); } }); }; var $reject = function (value) { var promise = this; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if (!promise._a) promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function (value) { var promise = this; var then; if (promise._d) return; promise._d = true; promise = promise._w || promise; // unwrap try { if (promise === value) throw TypeError("Promise can't be resolved itself"); if (then = isThenable(value)) { microtask(function () { var wrapper = { _w: promise, _d: false }; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch (e) { $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch (e) { $reject.call({ _w: promise, _d: false }, e); // wrap } }; // constructor polyfill if (!USE_NATIVE) { // 25.4.3.1 Promise(executor) $Promise = function Promise(executor) { anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch (err) { $reject.call(this, err); } }; // eslint-disable-next-line no-unused-vars Internal = function Promise(executor) { this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = __webpack_require__(/*! ./_redefine-all */ "../../node_modules/core-js/library/modules/_redefine-all.js")($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected) { var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if (this._a) this._a.push(reaction); if (this._s) notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function (onRejected) { return this.then(undefined, onRejected); } }); OwnPromiseCapability = function () { var promise = new Internal(); this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; newPromiseCapabilityModule.f = newPromiseCapability = function (C) { return C === $Promise || C === Wrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); __webpack_require__(/*! ./_set-to-string-tag */ "../../node_modules/core-js/library/modules/_set-to-string-tag.js")($Promise, PROMISE); __webpack_require__(/*! ./_set-species */ "../../node_modules/core-js/library/modules/_set-species.js")(PROMISE); Wrapper = __webpack_require__(/*! ./_core */ "../../node_modules/core-js/library/modules/_core.js")[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r) { var capability = newPromiseCapability(this); var $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x) { return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); } }); $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(/*! ./_iter-detect */ "../../node_modules/core-js/library/modules/_iter-detect.js")(function (iter) { $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable) { var C = this; var capability = newPromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; var result = perform(function () { var values = []; var index = 0; var remaining = 1; forOf(iterable, false, function (promise) { var $index = index++; var alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function (value) { if (alreadyCalled) return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if (result.e) reject(result.v); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable) { var C = this; var capability = newPromiseCapability(C); var reject = capability.reject; var result = perform(function () { forOf(iterable, false, function (promise) { C.resolve(promise).then(capability.resolve, reject); }); }); if (result.e) reject(result.v); return capability.promise; } }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.string.iterator.js": /*!****************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.string.iterator.js ***! \****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $at = __webpack_require__(/*! ./_string-at */ "../../node_modules/core-js/library/modules/_string-at.js")(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(/*! ./_iter-define */ "../../node_modules/core-js/library/modules/_iter-define.js")(String, 'String', function (iterated) { this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function () { var O = this._t; var index = this._i; var point; if (index >= O.length) return { value: undefined, done: true }; point = $at(O, index); this._i += point.length; return { value: point, done: false }; }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es6.symbol.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es6.symbol.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // ECMAScript 6 symbols shim var global = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js"); var has = __webpack_require__(/*! ./_has */ "../../node_modules/core-js/library/modules/_has.js"); var DESCRIPTORS = __webpack_require__(/*! ./_descriptors */ "../../node_modules/core-js/library/modules/_descriptors.js"); var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); var redefine = __webpack_require__(/*! ./_redefine */ "../../node_modules/core-js/library/modules/_redefine.js"); var META = __webpack_require__(/*! ./_meta */ "../../node_modules/core-js/library/modules/_meta.js").KEY; var $fails = __webpack_require__(/*! ./_fails */ "../../node_modules/core-js/library/modules/_fails.js"); var shared = __webpack_require__(/*! ./_shared */ "../../node_modules/core-js/library/modules/_shared.js"); var setToStringTag = __webpack_require__(/*! ./_set-to-string-tag */ "../../node_modules/core-js/library/modules/_set-to-string-tag.js"); var uid = __webpack_require__(/*! ./_uid */ "../../node_modules/core-js/library/modules/_uid.js"); var wks = __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js"); var wksExt = __webpack_require__(/*! ./_wks-ext */ "../../node_modules/core-js/library/modules/_wks-ext.js"); var wksDefine = __webpack_require__(/*! ./_wks-define */ "../../node_modules/core-js/library/modules/_wks-define.js"); var enumKeys = __webpack_require__(/*! ./_enum-keys */ "../../node_modules/core-js/library/modules/_enum-keys.js"); var isArray = __webpack_require__(/*! ./_is-array */ "../../node_modules/core-js/library/modules/_is-array.js"); var anObject = __webpack_require__(/*! ./_an-object */ "../../node_modules/core-js/library/modules/_an-object.js"); var isObject = __webpack_require__(/*! ./_is-object */ "../../node_modules/core-js/library/modules/_is-object.js"); var toIObject = __webpack_require__(/*! ./_to-iobject */ "../../node_modules/core-js/library/modules/_to-iobject.js"); var toPrimitive = __webpack_require__(/*! ./_to-primitive */ "../../node_modules/core-js/library/modules/_to-primitive.js"); var createDesc = __webpack_require__(/*! ./_property-desc */ "../../node_modules/core-js/library/modules/_property-desc.js"); var _create = __webpack_require__(/*! ./_object-create */ "../../node_modules/core-js/library/modules/_object-create.js"); var gOPNExt = __webpack_require__(/*! ./_object-gopn-ext */ "../../node_modules/core-js/library/modules/_object-gopn-ext.js"); var $GOPD = __webpack_require__(/*! ./_object-gopd */ "../../node_modules/core-js/library/modules/_object-gopd.js"); var $DP = __webpack_require__(/*! ./_object-dp */ "../../node_modules/core-js/library/modules/_object-dp.js"); var $keys = __webpack_require__(/*! ./_object-keys */ "../../node_modules/core-js/library/modules/_object-keys.js"); var gOPD = $GOPD.f; var dP = $DP.f; var gOPN = gOPNExt.f; var $Symbol = global.Symbol; var $JSON = global.JSON; var _stringify = $JSON && $JSON.stringify; var PROTOTYPE = 'prototype'; var HIDDEN = wks('_hidden'); var TO_PRIMITIVE = wks('toPrimitive'); var isEnum = {}.propertyIsEnumerable; var SymbolRegistry = shared('symbol-registry'); var AllSymbols = shared('symbols'); var OPSymbols = shared('op-symbols'); var ObjectProto = Object[PROTOTYPE]; var USE_NATIVE = typeof $Symbol == 'function'; var QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function () { return _create(dP({}, 'a', { get: function () { return dP(this, 'a', { value: 7 }).a; } })).a != 7; }) ? function (it, key, D) { var protoDesc = gOPD(ObjectProto, key); if (protoDesc) delete ObjectProto[key]; dP(it, key, D); if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); } : dP; var wrap = function (tag) { var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { return typeof it == 'symbol'; } : function (it) { return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D) { if (it === ObjectProto) $defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if (has(AllSymbols, key)) { if (!D.enumerable) { if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; D = _create(D, { enumerable: createDesc(0, false) }); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P) { anObject(it); var keys = enumKeys(P = toIObject(P)); var i = 0; var l = keys.length; var key; while (l > i) $defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P) { return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key) { var E = isEnum.call(this, key = toPrimitive(key, true)); if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { it = toIObject(it); key = toPrimitive(key, true); if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; var D = gOPD(it, key); if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it) { var names = gOPN(toIObject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { var IS_OP = it === ObjectProto; var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); var result = []; var i = 0; var key; while (names.length > i) { if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if (!USE_NATIVE) { $Symbol = function Symbol() { if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function (value) { if (this === ObjectProto) $set.call(OPSymbols, value); if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString() { return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; __webpack_require__(/*! ./_object-gopn */ "../../node_modules/core-js/library/modules/_object-gopn.js").f = gOPNExt.f = $getOwnPropertyNames; __webpack_require__(/*! ./_object-pie */ "../../node_modules/core-js/library/modules/_object-pie.js").f = $propertyIsEnumerable; __webpack_require__(/*! ./_object-gops */ "../../node_modules/core-js/library/modules/_object-gops.js").f = $getOwnPropertySymbols; if (DESCRIPTORS && !__webpack_require__(/*! ./_library */ "../../node_modules/core-js/library/modules/_library.js")) { redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function (name) { return wrap(wks(name)); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); for (var es6Symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function (key) { return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(sym) { if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; }, useSetter: function () { setter = true; }, useSimple: function () { setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it) { var args = [it]; var i = 1; var replacer, $replacer; while (arguments.length > i) args.push(arguments[i++]); $replacer = replacer = args[1]; if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined if (!isArray(replacer)) replacer = function (key, value) { if (typeof $replacer == 'function') value = $replacer.call(this, key, value); if (!isSymbol(value)) return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(/*! ./_hide */ "../../node_modules/core-js/library/modules/_hide.js")($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }), /***/ "../../node_modules/core-js/library/modules/es7.object.values.js": /*!**************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es7.object.values.js ***! \**************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // https://github.com/tc39/proposal-object-values-entries var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); var $values = __webpack_require__(/*! ./_object-to-array */ "../../node_modules/core-js/library/modules/_object-to-array.js")(false); $export($export.S, 'Object', { values: function values(it) { return $values(it); } }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es7.promise.finally.js": /*!****************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es7.promise.finally.js ***! \****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-promise-finally var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); var core = __webpack_require__(/*! ./_core */ "../../node_modules/core-js/library/modules/_core.js"); var global = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js"); var speciesConstructor = __webpack_require__(/*! ./_species-constructor */ "../../node_modules/core-js/library/modules/_species-constructor.js"); var promiseResolve = __webpack_require__(/*! ./_promise-resolve */ "../../node_modules/core-js/library/modules/_promise-resolve.js"); $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { var C = speciesConstructor(this, core.Promise || global.Promise); var isFunction = typeof onFinally == 'function'; return this.then( isFunction ? function (x) { return promiseResolve(C, onFinally()).then(function () { return x; }); } : onFinally, isFunction ? function (e) { return promiseResolve(C, onFinally()).then(function () { throw e; }); } : onFinally ); } }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es7.promise.try.js": /*!************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es7.promise.try.js ***! \************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // https://github.com/tc39/proposal-promise-try var $export = __webpack_require__(/*! ./_export */ "../../node_modules/core-js/library/modules/_export.js"); var newPromiseCapability = __webpack_require__(/*! ./_new-promise-capability */ "../../node_modules/core-js/library/modules/_new-promise-capability.js"); var perform = __webpack_require__(/*! ./_perform */ "../../node_modules/core-js/library/modules/_perform.js"); $export($export.S, 'Promise', { 'try': function (callbackfn) { var promiseCapability = newPromiseCapability.f(this); var result = perform(callbackfn); (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); return promiseCapability.promise; } }); /***/ }), /***/ "../../node_modules/core-js/library/modules/es7.symbol.async-iterator.js": /*!**********************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es7.symbol.async-iterator.js ***! \**********************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./_wks-define */ "../../node_modules/core-js/library/modules/_wks-define.js")('asyncIterator'); /***/ }), /***/ "../../node_modules/core-js/library/modules/es7.symbol.observable.js": /*!******************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/es7.symbol.observable.js ***! \******************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./_wks-define */ "../../node_modules/core-js/library/modules/_wks-define.js")('observable'); /***/ }), /***/ "../../node_modules/core-js/library/modules/web.dom.iterable.js": /*!*************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/core-js/library/modules/web.dom.iterable.js ***! \*************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./es6.array.iterator */ "../../node_modules/core-js/library/modules/es6.array.iterator.js"); var global = __webpack_require__(/*! ./_global */ "../../node_modules/core-js/library/modules/_global.js"); var hide = __webpack_require__(/*! ./_hide */ "../../node_modules/core-js/library/modules/_hide.js"); var Iterators = __webpack_require__(/*! ./_iterators */ "../../node_modules/core-js/library/modules/_iterators.js"); var TO_STRING_TAG = __webpack_require__(/*! ./_wks */ "../../node_modules/core-js/library/modules/_wks.js")('toStringTag'); var DOMIterables = ('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(','); for (var i = 0; i < DOMIterables.length; i++) { var NAME = DOMIterables[i]; var Collection = global[NAME]; var proto = Collection && Collection.prototype; if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = Iterators.Array; } /***/ }), /***/ "../../node_modules/error-stack-parser/error-stack-parser.js": /*!**********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/error-stack-parser/error-stack-parser.js ***! \**********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function(root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers. /* istanbul ignore next */ if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! stackframe */ "../../node_modules/stackframe/stackframe.js")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} }(this, function ErrorStackParser(StackFrame) { 'use strict'; var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\S+\:\d+/; var CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+\:\d+|\(native\))/m; var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code\])?$/; return { /** * Given an Error object, extract the most information from it. * * @param {Error} error object * @return {Array} of StackFrames */ parse: function ErrorStackParser$$parse(error) { if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') { return this.parseOpera(error); } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) { return this.parseV8OrIE(error); } else if (error.stack) { return this.parseFFOrSafari(error); } else { throw new Error('Cannot parse given Error object'); } }, // Separate line and column numbers from a string of the form: (URI:Line:Column) extractLocation: function ErrorStackParser$$extractLocation(urlLike) { // Fail-fast but return locations like "(native)" if (urlLike.indexOf(':') === -1) { return [urlLike]; } var regExp = /(.+?)(?:\:(\d+))?(?:\:(\d+))?$/; var parts = regExp.exec(urlLike.replace(/[\(\)]/g, '')); return [parts[1], parts[2] || undefined, parts[3] || undefined]; }, parseV8OrIE: function ErrorStackParser$$parseV8OrIE(error) { var filtered = error.stack.split('\n').filter(function(line) { return !!line.match(CHROME_IE_STACK_REGEXP); }, this); return filtered.map(function(line) { if (line.indexOf('(eval ') > -1) { // Throw away eval information until we implement stacktrace.js/stackframe#8 line = line.replace(/eval code/g, 'eval').replace(/(\(eval at [^\()]*)|(\)\,.*$)/g, ''); } var tokens = line.replace(/^\s+/, '').replace(/\(eval code/g, '(').split(/\s+/).slice(1); var locationParts = this.extractLocation(tokens.pop()); var functionName = tokens.join(' ') || undefined; var fileName = ['eval', '<anonymous>'].indexOf(locationParts[0]) > -1 ? undefined : locationParts[0]; return new StackFrame({ functionName: functionName, fileName: fileName, lineNumber: locationParts[1], columnNumber: locationParts[2], source: line }); }, this); }, parseFFOrSafari: function ErrorStackParser$$parseFFOrSafari(error) { var filtered = error.stack.split('\n').filter(function(line) { return !line.match(SAFARI_NATIVE_CODE_REGEXP); }, this); return filtered.map(function(line) { // Throw away eval information until we implement stacktrace.js/stackframe#8 if (line.indexOf(' > eval') > -1) { line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval\:\d+\:\d+/g, ':$1'); } if (line.indexOf('@') === -1 && line.indexOf(':') === -1) { // Safari eval frames only have function names and nothing else return new StackFrame({ functionName: line }); } else { var tokens = line.split('@'); var locationParts = this.extractLocation(tokens.pop()); var functionName = tokens.join('@') || undefined; return new StackFrame({ functionName: functionName, fileName: locationParts[0], lineNumber: locationParts[1], columnNumber: locationParts[2], source: line }); } }, this); }, parseOpera: function ErrorStackParser$$parseOpera(e) { if (!e.stacktrace || (e.message.indexOf('\n') > -1 && e.message.split('\n').length > e.stacktrace.split('\n').length)) { return this.parseOpera9(e); } else if (!e.stack) { return this.parseOpera10(e); } else { return this.parseOpera11(e); } }, parseOpera9: function ErrorStackParser$$parseOpera9(e) { var lineRE = /Line (\d+).*script (?:in )?(\S+)/i; var lines = e.message.split('\n'); var result = []; for (var i = 2, len = lines.length; i < len; i += 2) { var match = lineRE.exec(lines[i]); if (match) { result.push(new StackFrame({ fileName: match[2], lineNumber: match[1], source: lines[i] })); } } return result; }, parseOpera10: function ErrorStackParser$$parseOpera10(e) { var lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i; var lines = e.stacktrace.split('\n'); var result = []; for (var i = 0, len = lines.length; i < len; i += 2) { var match = lineRE.exec(lines[i]); if (match) { result.push( new StackFrame({ functionName: match[3] || undefined, fileName: match[2], lineNumber: match[1], source: lines[i] }) ); } } return result; }, // Opera 10.65+ Error.stack very similar to FF/Safari parseOpera11: function ErrorStackParser$$parseOpera11(error) { var filtered = error.stack.split('\n').filter(function(line) { return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/); }, this); return filtered.map(function(line) { var tokens = line.split('@'); var locationParts = this.extractLocation(tokens.pop()); var functionCall = (tokens.shift() || ''); var functionName = functionCall .replace(/<anonymous function(: (\w+))?>/, '$2') .replace(/\([^\)]*\)/g, '') || undefined; var argsRaw; if (functionCall.match(/\(([^\)]*)\)/)) { argsRaw = functionCall.replace(/^[^\(]+\(([^\)]*)\)$/, '$1'); } var args = (argsRaw === undefined || argsRaw === '[arguments not available]') ? undefined : argsRaw.split(','); return new StackFrame({ functionName: functionName, args: args, fileName: locationParts[0], lineNumber: locationParts[1], columnNumber: locationParts[2], source: line }); }, this); } }; })); /***/ }), /***/ "../../node_modules/fetch-ponyfill/build/fetch-browser.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/fetch-ponyfill/build/fetch-browser.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;(function (self) { 'use strict'; function fetchPonyfill(options) { var Promise = options && options.Promise || self.Promise; var XMLHttpRequest = options && options.XMLHttpRequest || self.XMLHttpRequest; var global = self; return (function () { var self = Object.create(global, { fetch: { value: undefined, writable: true } }); (function(self) { 'use strict'; if (self.fetch) { return } var support = { searchParams: 'URLSearchParams' in self, iterable: 'Symbol' in self && 'iterator' in Symbol, blob: 'FileReader' in self && 'Blob' in self && (function() { try { new Blob() return true } catch(e) { return false } })(), formData: 'FormData' in self, arrayBuffer: 'ArrayBuffer' in self } if (support.arrayBuffer) { var viewClasses = [ '[object Int8Array]', '[object Uint8Array]', '[object Uint8ClampedArray]', '[object Int16Array]', '[object Uint16Array]', '[object Int32Array]', '[object Uint32Array]', '[object Float32Array]', '[object Float64Array]' ] var isDataView = function(obj) { return obj && DataView.prototype.isPrototypeOf(obj) } var isArrayBufferView = ArrayBuffer.isView || function(obj) { return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 } } function normalizeName(name) { if (typeof name !== 'string') { name = String(name) } if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { throw new TypeError('Invalid character in header field name') } return name.toLowerCase() } function normalizeValue(value) { if (typeof value !== 'string') { value = String(value) } return value } // Build a destructive iterator for the value list function iteratorFor(items) { var iterator = { next: function() { var value = items.shift() return {done: value === undefined, value: value} } } if (support.iterable) { iterator[Symbol.iterator] = function() { return iterator } } return iterator } function Headers(headers) { this.map = {} if (headers instanceof Headers) { headers.forEach(function(value, name) { this.append(name, value) }, this) } else if (Array.isArray(headers)) { headers.forEach(function(header) { this.append(header[0], header[1]) }, this) } else if (headers) { Object.getOwnPropertyNames(headers).forEach(function(name) { this.append(name, headers[name]) }, this) } } Headers.prototype.append = function(name, value) { name = normalizeName(name) value = normalizeValue(value) var oldValue = this.map[name] this.map[name] = oldValue ? oldValue+','+value : value } Headers.prototype['delete'] = function(name) { delete this.map[normalizeName(name)] } Headers.prototype.get = function(name) { name = normalizeName(name) return this.has(name) ? this.map[name] : null } Headers.prototype.has = function(name) { return this.map.hasOwnProperty(normalizeName(name)) } Headers.prototype.set = function(name, value) { this.map[normalizeName(name)] = normalizeValue(value) } Headers.prototype.forEach = function(callback, thisArg) { for (var name in this.map) { if (this.map.hasOwnProperty(name)) { callback.call(thisArg, this.map[name], name, this) } } } Headers.prototype.keys = function() { var items = [] this.forEach(function(value, name) { items.push(name) }) return iteratorFor(items) } Headers.prototype.values = function() { var items = [] this.forEach(function(value) { items.push(value) }) return iteratorFor(items) } Headers.prototype.entries = function() { var items = [] this.forEach(function(value, name) { items.push([name, value]) }) return iteratorFor(items) } if (support.iterable) { Headers.prototype[Symbol.iterator] = Headers.prototype.entries } function consumed(body) { if (body.bodyUsed) { return Promise.reject(new TypeError('Already read')) } body.bodyUsed = true } function fileReaderReady(reader) { return new Promise(function(resolve, reject) { reader.onload = function() { resolve(reader.result) } reader.onerror = function() { reject(reader.error) } }) } function readBlobAsArrayBuffer(blob) { var reader = new FileReader() var promise = fileReaderReady(reader) reader.readAsArrayBuffer(blob) return promise } function readBlobAsText(blob) { var reader = new FileReader() var promise = fileReaderReady(reader) reader.readAsText(blob) return promise } function readArrayBufferAsText(buf) { var view = new Uint8Array(buf) var chars = new Array(view.length) for (var i = 0; i < view.length; i++) { chars[i] = String.fromCharCode(view[i]) } return chars.join('') } function bufferClone(buf) { if (buf.slice) { return buf.slice(0) } else { var view = new Uint8Array(buf.byteLength) view.set(new Uint8Array(buf)) return view.buffer } } function Body() { this.bodyUsed = false this._initBody = function(body) { this._bodyInit = body if (!body) { this._bodyText = '' } else if (typeof body === 'string') { this._bodyText = body } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { this._bodyBlob = body } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { this._bodyFormData = body } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this._bodyText = body.toString() } else if (support.arrayBuffer && support.blob && isDataView(body)) { this._bodyArrayBuffer = bufferClone(body.buffer) // IE 10-11 can't handle a DataView body. this._bodyInit = new Blob([this._bodyArrayBuffer]) } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { this._bodyArrayBuffer = bufferClone(body) } else { throw new Error('unsupported BodyInit type') } if (!this.headers.get('content-type')) { if (typeof body === 'string') { this.headers.set('content-type', 'text/plain;charset=UTF-8') } else if (this._bodyBlob && this._bodyBlob.type) { this.headers.set('content-type', this._bodyBlob.type) } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8') } } } if (support.blob) { this.blob = function() { var rejected = consumed(this) if (rejected) { return rejected } if (this._bodyBlob) { return Promise.resolve(this._bodyBlob) } else if (this._bodyArrayBuffer) { return Promise.resolve(new Blob([this._bodyArrayBuffer])) } else if (this._bodyFormData) { throw new Error('could not read FormData body as blob') } else { return Promise.resolve(new Blob([this._bodyText])) } } this.arrayBuffer = function() { if (this._bodyArrayBuffer) { return consumed(this) || Promise.resolve(this._bodyArrayBuffer) } else { return this.blob().then(readBlobAsArrayBuffer) } } } this.text = function() { var rejected = consumed(this) if (rejected) { return rejected } if (this._bodyBlob) { return readBlobAsText(this._bodyBlob) } else if (this._bodyArrayBuffer) { return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) } else if (this._bodyFormData) { throw new Error('could not read FormData body as text') } else { return Promise.resolve(this._bodyText) } } if (support.formData) { this.formData = function() { return this.text().then(decode) } } this.json = function() { return this.text().then(JSON.parse) } return this } // HTTP methods whose capitalization should be normalized var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] function normalizeMethod(method) { var upcased = method.toUpperCase() return (methods.indexOf(upcased) > -1) ? upcased : method } function Request(input, options) { options = options || {} var body = options.body if (input instanceof Request) { if (input.bodyUsed) { throw new TypeError('Already read') } this.url = input.url this.credentials = input.credentials if (!options.headers) { this.headers = new Headers(input.headers) } this.method = input.method this.mode = input.mode if (!body && input._bodyInit != null) { body = input._bodyInit input.bodyUsed = true } } else { this.url = String(input) } this.credentials = options.credentials || this.credentials || 'omit' if (options.headers || !this.headers) { this.headers = new Headers(options.headers) } this.method = normalizeMethod(options.method || this.method || 'GET') this.mode = options.mode || this.mode || null this.referrer = null if ((this.method === 'GET' || this.method === 'HEAD') && body) { throw new TypeError('Body not allowed for GET or HEAD requests') } this._initBody(body) } Request.prototype.clone = function() { return new Request(this, { body: this._bodyInit }) } function decode(body) { var form = new FormData() body.trim().split('&').forEach(function(bytes) { if (bytes) { var split = bytes.split('=') var name = split.shift().replace(/\+/g, ' ') var value = split.join('=').replace(/\+/g, ' ') form.append(decodeURIComponent(name), decodeURIComponent(value)) } }) return form } function parseHeaders(rawHeaders) { var headers = new Headers() rawHeaders.split(/\r?\n/).forEach(function(line) { var parts = line.split(':') var key = parts.shift().trim() if (key) { var value = parts.join(':').trim() headers.append(key, value) } }) return headers } Body.call(Request.prototype) function Response(bodyInit, options) { if (!options) { options = {} } this.type = 'default' this.status = 'status' in options ? options.status : 200 this.ok = this.status >= 200 && this.status < 300 this.statusText = 'statusText' in options ? options.statusText : 'OK' this.headers = new Headers(options.headers) this.url = options.url || '' this._initBody(bodyInit) } Body.call(Response.prototype) Response.prototype.clone = function() { return new Response(this._bodyInit, { status: this.status, statusText: this.statusText, headers: new Headers(this.headers), url: this.url }) } Response.error = function() { var response = new Response(null, {status: 0, statusText: ''}) response.type = 'error' return response } var redirectStatuses = [301, 302, 303, 307, 308] Response.redirect = function(url, status) { if (redirectStatuses.indexOf(status) === -1) { throw new RangeError('Invalid status code') } return new Response(null, {status: status, headers: {location: url}}) } self.Headers = Headers self.Request = Request self.Response = Response self.fetch = function(input, init) { return new Promise(function(resolve, reject) { var request = new Request(input, init) var xhr = new XMLHttpRequest() xhr.onload = function() { var options = { status: xhr.status, statusText: xhr.statusText, headers: parseHeaders(xhr.getAllResponseHeaders() || '') } options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL') var body = 'response' in xhr ? xhr.response : xhr.responseText resolve(new Response(body, options)) } xhr.onerror = function() { reject(new TypeError('Network request failed')) } xhr.ontimeout = function() { reject(new TypeError('Network request failed')) } xhr.open(request.method, request.url, true) if (request.credentials === 'include') { xhr.withCredentials = true } if ('responseType' in xhr && support.blob) { xhr.responseType = 'blob' } request.headers.forEach(function(value, name) { xhr.setRequestHeader(name, value) }) xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit) }) } self.fetch.polyfill = true })(typeof self !== 'undefined' ? self : this); return { fetch: self.fetch, Headers: self.Headers, Request: self.Request, Response: self.Response }; }()); } if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return fetchPonyfill; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} }(typeof self === 'undefined' ? this : self)); /***/ }), /***/ "../../node_modules/invariant/browser.js": /*!**************************************************************!*\ !*** /home/circleci/kandy/node_modules/invariant/browser.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. */ /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (true) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /***/ }), /***/ "../../node_modules/lodash-es/_DataView.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_DataView.js ***! \****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _getNative_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_getNative.js */ "../../node_modules/lodash-es/_getNative.js"); /* harmony import */ var _root_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_root.js */ "../../node_modules/lodash-es/_root.js"); /* Built-in method references that are verified to be native. */ var DataView = Object(_getNative_js__WEBPACK_IMPORTED_MODULE_0__["default"])(_root_js__WEBPACK_IMPORTED_MODULE_1__["default"], 'DataView'); /* harmony default export */ __webpack_exports__["default"] = (DataView); /***/ }), /***/ "../../node_modules/lodash-es/_Map.js": /*!***********************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_Map.js ***! \***********************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _getNative_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_getNative.js */ "../../node_modules/lodash-es/_getNative.js"); /* harmony import */ var _root_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_root.js */ "../../node_modules/lodash-es/_root.js"); /* Built-in method references that are verified to be native. */ var Map = Object(_getNative_js__WEBPACK_IMPORTED_MODULE_0__["default"])(_root_js__WEBPACK_IMPORTED_MODULE_1__["default"], 'Map'); /* harmony default export */ __webpack_exports__["default"] = (Map); /***/ }), /***/ "../../node_modules/lodash-es/_Promise.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_Promise.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _getNative_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_getNative.js */ "../../node_modules/lodash-es/_getNative.js"); /* harmony import */ var _root_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_root.js */ "../../node_modules/lodash-es/_root.js"); /* Built-in method references that are verified to be native. */ var Promise = Object(_getNative_js__WEBPACK_IMPORTED_MODULE_0__["default"])(_root_js__WEBPACK_IMPORTED_MODULE_1__["default"], 'Promise'); /* harmony default export */ __webpack_exports__["default"] = (Promise); /***/ }), /***/ "../../node_modules/lodash-es/_Set.js": /*!***********************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_Set.js ***! \***********************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _getNative_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_getNative.js */ "../../node_modules/lodash-es/_getNative.js"); /* harmony import */ var _root_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_root.js */ "../../node_modules/lodash-es/_root.js"); /* Built-in method references that are verified to be native. */ var Set = Object(_getNative_js__WEBPACK_IMPORTED_MODULE_0__["default"])(_root_js__WEBPACK_IMPORTED_MODULE_1__["default"], 'Set'); /* harmony default export */ __webpack_exports__["default"] = (Set); /***/ }), /***/ "../../node_modules/lodash-es/_Symbol.js": /*!**************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_Symbol.js ***! \**************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _root_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_root.js */ "../../node_modules/lodash-es/_root.js"); /** Built-in value references. */ var Symbol = _root_js__WEBPACK_IMPORTED_MODULE_0__["default"].Symbol; /* harmony default export */ __webpack_exports__["default"] = (Symbol); /***/ }), /***/ "../../node_modules/lodash-es/_WeakMap.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_WeakMap.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _getNative_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_getNative.js */ "../../node_modules/lodash-es/_getNative.js"); /* harmony import */ var _root_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_root.js */ "../../node_modules/lodash-es/_root.js"); /* Built-in method references that are verified to be native. */ var WeakMap = Object(_getNative_js__WEBPACK_IMPORTED_MODULE_0__["default"])(_root_js__WEBPACK_IMPORTED_MODULE_1__["default"], 'WeakMap'); /* harmony default export */ __webpack_exports__["default"] = (WeakMap); /***/ }), /***/ "../../node_modules/lodash-es/_arrayLikeKeys.js": /*!*********************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_arrayLikeKeys.js ***! \*********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseTimes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseTimes.js */ "../../node_modules/lodash-es/_baseTimes.js"); /* harmony import */ var _isArguments_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isArguments.js */ "../../node_modules/lodash-es/isArguments.js"); /* harmony import */ var _isArray_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./isArray.js */ "../../node_modules/lodash-es/isArray.js"); /* harmony import */ var _isBuffer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./isBuffer.js */ "../../node_modules/lodash-es/isBuffer.js"); /* harmony import */ var _isIndex_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./_isIndex.js */ "../../node_modules/lodash-es/_isIndex.js"); /* harmony import */ var _isTypedArray_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./isTypedArray.js */ "../../node_modules/lodash-es/isTypedArray.js"); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = Object(_isArray_js__WEBPACK_IMPORTED_MODULE_2__["default"])(value), isArg = !isArr && Object(_isArguments_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value), isBuff = !isArr && !isArg && Object(_isBuffer_js__WEBPACK_IMPORTED_MODULE_3__["default"])(value), isType = !isArr && !isArg && !isBuff && Object(_isTypedArray_js__WEBPACK_IMPORTED_MODULE_5__["default"])(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? Object(_baseTimes_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. Object(_isIndex_js__WEBPACK_IMPORTED_MODULE_4__["default"])(key, length) ))) { result.push(key); } } return result; } /* harmony default export */ __webpack_exports__["default"] = (arrayLikeKeys); /***/ }), /***/ "../../node_modules/lodash-es/_arrayMap.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_arrayMap.js ***! \****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /* harmony default export */ __webpack_exports__["default"] = (arrayMap); /***/ }), /***/ "../../node_modules/lodash-es/_baseFindIndex.js": /*!*********************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseFindIndex.js ***! \*********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /* harmony default export */ __webpack_exports__["default"] = (baseFindIndex); /***/ }), /***/ "../../node_modules/lodash-es/_baseGetTag.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseGetTag.js ***! \******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Symbol_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_Symbol.js */ "../../node_modules/lodash-es/_Symbol.js"); /* harmony import */ var _getRawTag_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_getRawTag.js */ "../../node_modules/lodash-es/_getRawTag.js"); /* harmony import */ var _objectToString_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./_objectToString.js */ "../../node_modules/lodash-es/_objectToString.js"); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = _Symbol_js__WEBPACK_IMPORTED_MODULE_0__["default"] ? _Symbol_js__WEBPACK_IMPORTED_MODULE_0__["default"].toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? Object(_getRawTag_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value) : Object(_objectToString_js__WEBPACK_IMPORTED_MODULE_2__["default"])(value); } /* harmony default export */ __webpack_exports__["default"] = (baseGetTag); /***/ }), /***/ "../../node_modules/lodash-es/_baseIndexOf.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseIndexOf.js ***! \*******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseFindIndex_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseFindIndex.js */ "../../node_modules/lodash-es/_baseFindIndex.js"); /* harmony import */ var _baseIsNaN_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_baseIsNaN.js */ "../../node_modules/lodash-es/_baseIsNaN.js"); /* harmony import */ var _strictIndexOf_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./_strictIndexOf.js */ "../../node_modules/lodash-es/_strictIndexOf.js"); /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? Object(_strictIndexOf_js__WEBPACK_IMPORTED_MODULE_2__["default"])(array, value, fromIndex) : Object(_baseFindIndex_js__WEBPACK_IMPORTED_MODULE_0__["default"])(array, _baseIsNaN_js__WEBPACK_IMPORTED_MODULE_1__["default"], fromIndex); } /* harmony default export */ __webpack_exports__["default"] = (baseIndexOf); /***/ }), /***/ "../../node_modules/lodash-es/_baseIsArguments.js": /*!***********************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseIsArguments.js ***! \***********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseGetTag.js */ "../../node_modules/lodash-es/_baseGetTag.js"); /* harmony import */ var _isObjectLike_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isObjectLike.js */ "../../node_modules/lodash-es/isObjectLike.js"); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return Object(_isObjectLike_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value) && Object(_baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value) == argsTag; } /* harmony default export */ __webpack_exports__["default"] = (baseIsArguments); /***/ }), /***/ "../../node_modules/lodash-es/_baseIsMap.js": /*!*****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseIsMap.js ***! \*****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _getTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_getTag.js */ "../../node_modules/lodash-es/_getTag.js"); /* harmony import */ var _isObjectLike_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isObjectLike.js */ "../../node_modules/lodash-es/isObjectLike.js"); /** `Object#toString` result references. */ var mapTag = '[object Map]'; /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return Object(_isObjectLike_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value) && Object(_getTag_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value) == mapTag; } /* harmony default export */ __webpack_exports__["default"] = (baseIsMap); /***/ }), /***/ "../../node_modules/lodash-es/_baseIsNaN.js": /*!*****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseIsNaN.js ***! \*****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /* harmony default export */ __webpack_exports__["default"] = (baseIsNaN); /***/ }), /***/ "../../node_modules/lodash-es/_baseIsNative.js": /*!********************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseIsNative.js ***! \********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _isFunction_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction.js */ "../../node_modules/lodash-es/isFunction.js"); /* harmony import */ var _isMasked_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_isMasked.js */ "../../node_modules/lodash-es/_isMasked.js"); /* harmony import */ var _isObject_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./isObject.js */ "../../node_modules/lodash-es/isObject.js"); /* harmony import */ var _toSource_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./_toSource.js */ "../../node_modules/lodash-es/_toSource.js"); /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!Object(_isObject_js__WEBPACK_IMPORTED_MODULE_2__["default"])(value) || Object(_isMasked_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value)) { return false; } var pattern = Object(_isFunction_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value) ? reIsNative : reIsHostCtor; return pattern.test(Object(_toSource_js__WEBPACK_IMPORTED_MODULE_3__["default"])(value)); } /* harmony default export */ __webpack_exports__["default"] = (baseIsNative); /***/ }), /***/ "../../node_modules/lodash-es/_baseIsTypedArray.js": /*!************************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseIsTypedArray.js ***! \************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseGetTag.js */ "../../node_modules/lodash-es/_baseGetTag.js"); /* harmony import */ var _isLength_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isLength.js */ "../../node_modules/lodash-es/isLength.js"); /* harmony import */ var _isObjectLike_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./isObjectLike.js */ "../../node_modules/lodash-es/isObjectLike.js"); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return Object(_isObjectLike_js__WEBPACK_IMPORTED_MODULE_2__["default"])(value) && Object(_isLength_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value.length) && !!typedArrayTags[Object(_baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value)]; } /* harmony default export */ __webpack_exports__["default"] = (baseIsTypedArray); /***/ }), /***/ "../../node_modules/lodash-es/_baseKeys.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseKeys.js ***! \****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _isPrototype_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_isPrototype.js */ "../../node_modules/lodash-es/_isPrototype.js"); /* harmony import */ var _nativeKeys_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_nativeKeys.js */ "../../node_modules/lodash-es/_nativeKeys.js"); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!Object(_isPrototype_js__WEBPACK_IMPORTED_MODULE_0__["default"])(object)) { return Object(_nativeKeys_js__WEBPACK_IMPORTED_MODULE_1__["default"])(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /* harmony default export */ __webpack_exports__["default"] = (baseKeys); /***/ }), /***/ "../../node_modules/lodash-es/_baseTimes.js": /*!*****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseTimes.js ***! \*****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /* harmony default export */ __webpack_exports__["default"] = (baseTimes); /***/ }), /***/ "../../node_modules/lodash-es/_baseToString.js": /*!********************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseToString.js ***! \********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Symbol_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_Symbol.js */ "../../node_modules/lodash-es/_Symbol.js"); /* harmony import */ var _arrayMap_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_arrayMap.js */ "../../node_modules/lodash-es/_arrayMap.js"); /* harmony import */ var _isArray_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./isArray.js */ "../../node_modules/lodash-es/isArray.js"); /* harmony import */ var _isSymbol_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./isSymbol.js */ "../../node_modules/lodash-es/isSymbol.js"); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol_js__WEBPACK_IMPORTED_MODULE_0__["default"] ? _Symbol_js__WEBPACK_IMPORTED_MODULE_0__["default"].prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (Object(_isArray_js__WEBPACK_IMPORTED_MODULE_2__["default"])(value)) { // Recursively convert values (susceptible to call stack limits). return Object(_arrayMap_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value, baseToString) + ''; } if (Object(_isSymbol_js__WEBPACK_IMPORTED_MODULE_3__["default"])(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /* harmony default export */ __webpack_exports__["default"] = (baseToString); /***/ }), /***/ "../../node_modules/lodash-es/_baseUnary.js": /*!*****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseUnary.js ***! \*****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /* harmony default export */ __webpack_exports__["default"] = (baseUnary); /***/ }), /***/ "../../node_modules/lodash-es/_baseValues.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_baseValues.js ***! \******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _arrayMap_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_arrayMap.js */ "../../node_modules/lodash-es/_arrayMap.js"); /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return Object(_arrayMap_js__WEBPACK_IMPORTED_MODULE_0__["default"])(props, function(key) { return object[key]; }); } /* harmony default export */ __webpack_exports__["default"] = (baseValues); /***/ }), /***/ "../../node_modules/lodash-es/_coreJsData.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_coreJsData.js ***! \******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _root_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_root.js */ "../../node_modules/lodash-es/_root.js"); /** Used to detect overreaching core-js shims. */ var coreJsData = _root_js__WEBPACK_IMPORTED_MODULE_0__["default"]['__core-js_shared__']; /* harmony default export */ __webpack_exports__["default"] = (coreJsData); /***/ }), /***/ "../../node_modules/lodash-es/_freeGlobal.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_freeGlobal.js ***! \******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /* harmony default export */ __webpack_exports__["default"] = (freeGlobal); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "../../node_modules/lodash-es/_getNative.js": /*!*****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_getNative.js ***! \*****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseIsNative_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseIsNative.js */ "../../node_modules/lodash-es/_baseIsNative.js"); /* harmony import */ var _getValue_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_getValue.js */ "../../node_modules/lodash-es/_getValue.js"); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = Object(_getValue_js__WEBPACK_IMPORTED_MODULE_1__["default"])(object, key); return Object(_baseIsNative_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value) ? value : undefined; } /* harmony default export */ __webpack_exports__["default"] = (getNative); /***/ }), /***/ "../../node_modules/lodash-es/_getPrototype.js": /*!********************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_getPrototype.js ***! \********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _overArg_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_overArg.js */ "../../node_modules/lodash-es/_overArg.js"); /** Built-in value references. */ var getPrototype = Object(_overArg_js__WEBPACK_IMPORTED_MODULE_0__["default"])(Object.getPrototypeOf, Object); /* harmony default export */ __webpack_exports__["default"] = (getPrototype); /***/ }), /***/ "../../node_modules/lodash-es/_getRawTag.js": /*!*****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_getRawTag.js ***! \*****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Symbol_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_Symbol.js */ "../../node_modules/lodash-es/_Symbol.js"); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = _Symbol_js__WEBPACK_IMPORTED_MODULE_0__["default"] ? _Symbol_js__WEBPACK_IMPORTED_MODULE_0__["default"].toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /* harmony default export */ __webpack_exports__["default"] = (getRawTag); /***/ }), /***/ "../../node_modules/lodash-es/_getTag.js": /*!**************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_getTag.js ***! \**************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _DataView_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_DataView.js */ "../../node_modules/lodash-es/_DataView.js"); /* harmony import */ var _Map_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_Map.js */ "../../node_modules/lodash-es/_Map.js"); /* harmony import */ var _Promise_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./_Promise.js */ "../../node_modules/lodash-es/_Promise.js"); /* harmony import */ var _Set_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./_Set.js */ "../../node_modules/lodash-es/_Set.js"); /* harmony import */ var _WeakMap_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./_WeakMap.js */ "../../node_modules/lodash-es/_WeakMap.js"); /* harmony import */ var _baseGetTag_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./_baseGetTag.js */ "../../node_modules/lodash-es/_baseGetTag.js"); /* harmony import */ var _toSource_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./_toSource.js */ "../../node_modules/lodash-es/_toSource.js"); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = Object(_toSource_js__WEBPACK_IMPORTED_MODULE_6__["default"])(_DataView_js__WEBPACK_IMPORTED_MODULE_0__["default"]), mapCtorString = Object(_toSource_js__WEBPACK_IMPORTED_MODULE_6__["default"])(_Map_js__WEBPACK_IMPORTED_MODULE_1__["default"]), promiseCtorString = Object(_toSource_js__WEBPACK_IMPORTED_MODULE_6__["default"])(_Promise_js__WEBPACK_IMPORTED_MODULE_2__["default"]), setCtorString = Object(_toSource_js__WEBPACK_IMPORTED_MODULE_6__["default"])(_Set_js__WEBPACK_IMPORTED_MODULE_3__["default"]), weakMapCtorString = Object(_toSource_js__WEBPACK_IMPORTED_MODULE_6__["default"])(_WeakMap_js__WEBPACK_IMPORTED_MODULE_4__["default"]); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = _baseGetTag_js__WEBPACK_IMPORTED_MODULE_5__["default"]; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((_DataView_js__WEBPACK_IMPORTED_MODULE_0__["default"] && getTag(new _DataView_js__WEBPACK_IMPORTED_MODULE_0__["default"](new ArrayBuffer(1))) != dataViewTag) || (_Map_js__WEBPACK_IMPORTED_MODULE_1__["default"] && getTag(new _Map_js__WEBPACK_IMPORTED_MODULE_1__["default"]) != mapTag) || (_Promise_js__WEBPACK_IMPORTED_MODULE_2__["default"] && getTag(_Promise_js__WEBPACK_IMPORTED_MODULE_2__["default"].resolve()) != promiseTag) || (_Set_js__WEBPACK_IMPORTED_MODULE_3__["default"] && getTag(new _Set_js__WEBPACK_IMPORTED_MODULE_3__["default"]) != setTag) || (_WeakMap_js__WEBPACK_IMPORTED_MODULE_4__["default"] && getTag(new _WeakMap_js__WEBPACK_IMPORTED_MODULE_4__["default"]) != weakMapTag)) { getTag = function(value) { var result = Object(_baseGetTag_js__WEBPACK_IMPORTED_MODULE_5__["default"])(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? Object(_toSource_js__WEBPACK_IMPORTED_MODULE_6__["default"])(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /* harmony default export */ __webpack_exports__["default"] = (getTag); /***/ }), /***/ "../../node_modules/lodash-es/_getValue.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_getValue.js ***! \****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /* harmony default export */ __webpack_exports__["default"] = (getValue); /***/ }), /***/ "../../node_modules/lodash-es/_isIndex.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_isIndex.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } /* harmony default export */ __webpack_exports__["default"] = (isIndex); /***/ }), /***/ "../../node_modules/lodash-es/_isMasked.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_isMasked.js ***! \****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _coreJsData_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_coreJsData.js */ "../../node_modules/lodash-es/_coreJsData.js"); /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(_coreJsData_js__WEBPACK_IMPORTED_MODULE_0__["default"] && _coreJsData_js__WEBPACK_IMPORTED_MODULE_0__["default"].keys && _coreJsData_js__WEBPACK_IMPORTED_MODULE_0__["default"].keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /* harmony default export */ __webpack_exports__["default"] = (isMasked); /***/ }), /***/ "../../node_modules/lodash-es/_isPrototype.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_isPrototype.js ***! \*******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /* harmony default export */ __webpack_exports__["default"] = (isPrototype); /***/ }), /***/ "../../node_modules/lodash-es/_nativeKeys.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_nativeKeys.js ***! \******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _overArg_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_overArg.js */ "../../node_modules/lodash-es/_overArg.js"); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = Object(_overArg_js__WEBPACK_IMPORTED_MODULE_0__["default"])(Object.keys, Object); /* harmony default export */ __webpack_exports__["default"] = (nativeKeys); /***/ }), /***/ "../../node_modules/lodash-es/_nodeUtil.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_nodeUtil.js ***! \****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(module) {/* harmony import */ var _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_freeGlobal.js */ "../../node_modules/lodash-es/_freeGlobal.js"); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__["default"].process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* harmony default export */ __webpack_exports__["default"] = (nodeUtil); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/harmony-module.js */ "../../node_modules/webpack/buildin/harmony-module.js")(module))) /***/ }), /***/ "../../node_modules/lodash-es/_objectToString.js": /*!**********************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_objectToString.js ***! \**********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /* harmony default export */ __webpack_exports__["default"] = (objectToString); /***/ }), /***/ "../../node_modules/lodash-es/_overArg.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_overArg.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /* harmony default export */ __webpack_exports__["default"] = (overArg); /***/ }), /***/ "../../node_modules/lodash-es/_root.js": /*!************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_root.js ***! \************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_freeGlobal.js */ "../../node_modules/lodash-es/_freeGlobal.js"); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = _freeGlobal_js__WEBPACK_IMPORTED_MODULE_0__["default"] || freeSelf || Function('return this')(); /* harmony default export */ __webpack_exports__["default"] = (root); /***/ }), /***/ "../../node_modules/lodash-es/_strictIndexOf.js": /*!*********************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_strictIndexOf.js ***! \*********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /* harmony default export */ __webpack_exports__["default"] = (strictIndexOf); /***/ }), /***/ "../../node_modules/lodash-es/_toSource.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/_toSource.js ***! \****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /* harmony default export */ __webpack_exports__["default"] = (toSource); /***/ }), /***/ "../../node_modules/lodash-es/identity.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/identity.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } /* harmony default export */ __webpack_exports__["default"] = (identity); /***/ }), /***/ "../../node_modules/lodash-es/includes.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/includes.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseIndexOf_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseIndexOf.js */ "../../node_modules/lodash-es/_baseIndexOf.js"); /* harmony import */ var _isArrayLike_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isArrayLike.js */ "../../node_modules/lodash-es/isArrayLike.js"); /* harmony import */ var _isString_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./isString.js */ "../../node_modules/lodash-es/isString.js"); /* harmony import */ var _toInteger_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./toInteger.js */ "../../node_modules/lodash-es/toInteger.js"); /* harmony import */ var _values_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./values.js */ "../../node_modules/lodash-es/values.js"); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = Object(_isArrayLike_js__WEBPACK_IMPORTED_MODULE_1__["default"])(collection) ? collection : Object(_values_js__WEBPACK_IMPORTED_MODULE_4__["default"])(collection); fromIndex = (fromIndex && !guard) ? Object(_toInteger_js__WEBPACK_IMPORTED_MODULE_3__["default"])(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return Object(_isString_js__WEBPACK_IMPORTED_MODULE_2__["default"])(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && Object(_baseIndexOf_js__WEBPACK_IMPORTED_MODULE_0__["default"])(collection, value, fromIndex) > -1); } /* harmony default export */ __webpack_exports__["default"] = (includes); /***/ }), /***/ "../../node_modules/lodash-es/isArguments.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isArguments.js ***! \******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseIsArguments_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseIsArguments.js */ "../../node_modules/lodash-es/_baseIsArguments.js"); /* harmony import */ var _isObjectLike_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isObjectLike.js */ "../../node_modules/lodash-es/isObjectLike.js"); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = Object(_baseIsArguments_js__WEBPACK_IMPORTED_MODULE_0__["default"])(function() { return arguments; }()) ? _baseIsArguments_js__WEBPACK_IMPORTED_MODULE_0__["default"] : function(value) { return Object(_isObjectLike_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /* harmony default export */ __webpack_exports__["default"] = (isArguments); /***/ }), /***/ "../../node_modules/lodash-es/isArray.js": /*!**************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isArray.js ***! \**************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /* harmony default export */ __webpack_exports__["default"] = (isArray); /***/ }), /***/ "../../node_modules/lodash-es/isArrayLike.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isArrayLike.js ***! \******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _isFunction_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isFunction.js */ "../../node_modules/lodash-es/isFunction.js"); /* harmony import */ var _isLength_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isLength.js */ "../../node_modules/lodash-es/isLength.js"); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && Object(_isLength_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value.length) && !Object(_isFunction_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value); } /* harmony default export */ __webpack_exports__["default"] = (isArrayLike); /***/ }), /***/ "../../node_modules/lodash-es/isBuffer.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isBuffer.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(module) {/* harmony import */ var _root_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_root.js */ "../../node_modules/lodash-es/_root.js"); /* harmony import */ var _stubFalse_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./stubFalse.js */ "../../node_modules/lodash-es/stubFalse.js"); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root_js__WEBPACK_IMPORTED_MODULE_0__["default"].Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || _stubFalse_js__WEBPACK_IMPORTED_MODULE_1__["default"]; /* harmony default export */ __webpack_exports__["default"] = (isBuffer); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/harmony-module.js */ "../../node_modules/webpack/buildin/harmony-module.js")(module))) /***/ }), /***/ "../../node_modules/lodash-es/isEmpty.js": /*!**************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isEmpty.js ***! \**************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseKeys_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseKeys.js */ "../../node_modules/lodash-es/_baseKeys.js"); /* harmony import */ var _getTag_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_getTag.js */ "../../node_modules/lodash-es/_getTag.js"); /* harmony import */ var _isArguments_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./isArguments.js */ "../../node_modules/lodash-es/isArguments.js"); /* harmony import */ var _isArray_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./isArray.js */ "../../node_modules/lodash-es/isArray.js"); /* harmony import */ var _isArrayLike_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./isArrayLike.js */ "../../node_modules/lodash-es/isArrayLike.js"); /* harmony import */ var _isBuffer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./isBuffer.js */ "../../node_modules/lodash-es/isBuffer.js"); /* harmony import */ var _isPrototype_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./_isPrototype.js */ "../../node_modules/lodash-es/_isPrototype.js"); /* harmony import */ var _isTypedArray_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./isTypedArray.js */ "../../node_modules/lodash-es/isTypedArray.js"); /** `Object#toString` result references. */ var mapTag = '[object Map]', setTag = '[object Set]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (Object(_isArrayLike_js__WEBPACK_IMPORTED_MODULE_4__["default"])(value) && (Object(_isArray_js__WEBPACK_IMPORTED_MODULE_3__["default"])(value) || typeof value == 'string' || typeof value.splice == 'function' || Object(_isBuffer_js__WEBPACK_IMPORTED_MODULE_5__["default"])(value) || Object(_isTypedArray_js__WEBPACK_IMPORTED_MODULE_7__["default"])(value) || Object(_isArguments_js__WEBPACK_IMPORTED_MODULE_2__["default"])(value))) { return !value.length; } var tag = Object(_getTag_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (Object(_isPrototype_js__WEBPACK_IMPORTED_MODULE_6__["default"])(value)) { return !Object(_baseKeys_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /* harmony default export */ __webpack_exports__["default"] = (isEmpty); /***/ }), /***/ "../../node_modules/lodash-es/isFunction.js": /*!*****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isFunction.js ***! \*****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseGetTag.js */ "../../node_modules/lodash-es/_baseGetTag.js"); /* harmony import */ var _isObject_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isObject.js */ "../../node_modules/lodash-es/isObject.js"); /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!Object(_isObject_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = Object(_baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /* harmony default export */ __webpack_exports__["default"] = (isFunction); /***/ }), /***/ "../../node_modules/lodash-es/isLength.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isLength.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /* harmony default export */ __webpack_exports__["default"] = (isLength); /***/ }), /***/ "../../node_modules/lodash-es/isMap.js": /*!************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isMap.js ***! \************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseIsMap_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseIsMap.js */ "../../node_modules/lodash-es/_baseIsMap.js"); /* harmony import */ var _baseUnary_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_baseUnary.js */ "../../node_modules/lodash-es/_baseUnary.js"); /* harmony import */ var _nodeUtil_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./_nodeUtil.js */ "../../node_modules/lodash-es/_nodeUtil.js"); /* Node.js helper references. */ var nodeIsMap = _nodeUtil_js__WEBPACK_IMPORTED_MODULE_2__["default"] && _nodeUtil_js__WEBPACK_IMPORTED_MODULE_2__["default"].isMap; /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? Object(_baseUnary_js__WEBPACK_IMPORTED_MODULE_1__["default"])(nodeIsMap) : _baseIsMap_js__WEBPACK_IMPORTED_MODULE_0__["default"]; /* harmony default export */ __webpack_exports__["default"] = (isMap); /***/ }), /***/ "../../node_modules/lodash-es/isNil.js": /*!************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isNil.js ***! \************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /* harmony default export */ __webpack_exports__["default"] = (isNil); /***/ }), /***/ "../../node_modules/lodash-es/isNull.js": /*!*************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isNull.js ***! \*************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /* harmony default export */ __webpack_exports__["default"] = (isNull); /***/ }), /***/ "../../node_modules/lodash-es/isObject.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isObject.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /* harmony default export */ __webpack_exports__["default"] = (isObject); /***/ }), /***/ "../../node_modules/lodash-es/isObjectLike.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isObjectLike.js ***! \*******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /* harmony default export */ __webpack_exports__["default"] = (isObjectLike); /***/ }), /***/ "../../node_modules/lodash-es/isPlainObject.js": /*!********************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isPlainObject.js ***! \********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseGetTag.js */ "../../node_modules/lodash-es/_baseGetTag.js"); /* harmony import */ var _getPrototype_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_getPrototype.js */ "../../node_modules/lodash-es/_getPrototype.js"); /* harmony import */ var _isObjectLike_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./isObjectLike.js */ "../../node_modules/lodash-es/isObjectLike.js"); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!Object(_isObjectLike_js__WEBPACK_IMPORTED_MODULE_2__["default"])(value) || Object(_baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value) != objectTag) { return false; } var proto = Object(_getPrototype_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /* harmony default export */ __webpack_exports__["default"] = (isPlainObject); /***/ }), /***/ "../../node_modules/lodash-es/isString.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isString.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseGetTag.js */ "../../node_modules/lodash-es/_baseGetTag.js"); /* harmony import */ var _isArray_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isArray.js */ "../../node_modules/lodash-es/isArray.js"); /* harmony import */ var _isObjectLike_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./isObjectLike.js */ "../../node_modules/lodash-es/isObjectLike.js"); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!Object(_isArray_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value) && Object(_isObjectLike_js__WEBPACK_IMPORTED_MODULE_2__["default"])(value) && Object(_baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value) == stringTag); } /* harmony default export */ __webpack_exports__["default"] = (isString); /***/ }), /***/ "../../node_modules/lodash-es/isSymbol.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isSymbol.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseGetTag.js */ "../../node_modules/lodash-es/_baseGetTag.js"); /* harmony import */ var _isObjectLike_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isObjectLike.js */ "../../node_modules/lodash-es/isObjectLike.js"); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (Object(_isObjectLike_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value) && Object(_baseGetTag_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value) == symbolTag); } /* harmony default export */ __webpack_exports__["default"] = (isSymbol); /***/ }), /***/ "../../node_modules/lodash-es/isTypedArray.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isTypedArray.js ***! \*******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseIsTypedArray_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseIsTypedArray.js */ "../../node_modules/lodash-es/_baseIsTypedArray.js"); /* harmony import */ var _baseUnary_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_baseUnary.js */ "../../node_modules/lodash-es/_baseUnary.js"); /* harmony import */ var _nodeUtil_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./_nodeUtil.js */ "../../node_modules/lodash-es/_nodeUtil.js"); /* Node.js helper references. */ var nodeIsTypedArray = _nodeUtil_js__WEBPACK_IMPORTED_MODULE_2__["default"] && _nodeUtil_js__WEBPACK_IMPORTED_MODULE_2__["default"].isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? Object(_baseUnary_js__WEBPACK_IMPORTED_MODULE_1__["default"])(nodeIsTypedArray) : _baseIsTypedArray_js__WEBPACK_IMPORTED_MODULE_0__["default"]; /* harmony default export */ __webpack_exports__["default"] = (isTypedArray); /***/ }), /***/ "../../node_modules/lodash-es/isUndefined.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/isUndefined.js ***! \******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /* harmony default export */ __webpack_exports__["default"] = (isUndefined); /***/ }), /***/ "../../node_modules/lodash-es/keys.js": /*!***********************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/keys.js ***! \***********************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _arrayLikeKeys_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_arrayLikeKeys.js */ "../../node_modules/lodash-es/_arrayLikeKeys.js"); /* harmony import */ var _baseKeys_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_baseKeys.js */ "../../node_modules/lodash-es/_baseKeys.js"); /* harmony import */ var _isArrayLike_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./isArrayLike.js */ "../../node_modules/lodash-es/isArrayLike.js"); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return Object(_isArrayLike_js__WEBPACK_IMPORTED_MODULE_2__["default"])(object) ? Object(_arrayLikeKeys_js__WEBPACK_IMPORTED_MODULE_0__["default"])(object) : Object(_baseKeys_js__WEBPACK_IMPORTED_MODULE_1__["default"])(object); } /* harmony default export */ __webpack_exports__["default"] = (keys); /***/ }), /***/ "../../node_modules/lodash-es/last.js": /*!***********************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/last.js ***! \***********************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /* harmony default export */ __webpack_exports__["default"] = (last); /***/ }), /***/ "../../node_modules/lodash-es/stubFalse.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/stubFalse.js ***! \****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } /* harmony default export */ __webpack_exports__["default"] = (stubFalse); /***/ }), /***/ "../../node_modules/lodash-es/toFinite.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/toFinite.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _toNumber_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./toNumber.js */ "../../node_modules/lodash-es/toNumber.js"); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = Object(_toNumber_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /* harmony default export */ __webpack_exports__["default"] = (toFinite); /***/ }), /***/ "../../node_modules/lodash-es/toInteger.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/toInteger.js ***! \****************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _toFinite_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./toFinite.js */ "../../node_modules/lodash-es/toFinite.js"); /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = Object(_toFinite_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /* harmony default export */ __webpack_exports__["default"] = (toInteger); /***/ }), /***/ "../../node_modules/lodash-es/toNumber.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/toNumber.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _isObject_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isObject.js */ "../../node_modules/lodash-es/isObject.js"); /* harmony import */ var _isSymbol_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./isSymbol.js */ "../../node_modules/lodash-es/isSymbol.js"); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (Object(_isSymbol_js__WEBPACK_IMPORTED_MODULE_1__["default"])(value)) { return NAN; } if (Object(_isObject_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = Object(_isObject_js__WEBPACK_IMPORTED_MODULE_0__["default"])(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /* harmony default export */ __webpack_exports__["default"] = (toNumber); /***/ }), /***/ "../../node_modules/lodash-es/toString.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/toString.js ***! \***************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseToString_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseToString.js */ "../../node_modules/lodash-es/_baseToString.js"); /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : Object(_baseToString_js__WEBPACK_IMPORTED_MODULE_0__["default"])(value); } /* harmony default export */ __webpack_exports__["default"] = (toString); /***/ }), /***/ "../../node_modules/lodash-es/values.js": /*!*************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash-es/values.js ***! \*************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _baseValues_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_baseValues.js */ "../../node_modules/lodash-es/_baseValues.js"); /* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./keys.js */ "../../node_modules/lodash-es/keys.js"); /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : Object(_baseValues_js__WEBPACK_IMPORTED_MODULE_0__["default"])(object, Object(_keys_js__WEBPACK_IMPORTED_MODULE_1__["default"])(object)); } /* harmony default export */ __webpack_exports__["default"] = (values); /***/ }), /***/ "../../node_modules/lodash/_Symbol.js": /*!***********************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/_Symbol.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var root = __webpack_require__(/*! ./_root */ "../../node_modules/lodash/_root.js"); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }), /***/ "../../node_modules/lodash/_baseGetTag.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/_baseGetTag.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(/*! ./_Symbol */ "../../node_modules/lodash/_Symbol.js"), getRawTag = __webpack_require__(/*! ./_getRawTag */ "../../node_modules/lodash/_getRawTag.js"), objectToString = __webpack_require__(/*! ./_objectToString */ "../../node_modules/lodash/_objectToString.js"); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }), /***/ "../../node_modules/lodash/_freeGlobal.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/_freeGlobal.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "../../node_modules/lodash/_getRawTag.js": /*!**************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/_getRawTag.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(/*! ./_Symbol */ "../../node_modules/lodash/_Symbol.js"); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; /***/ }), /***/ "../../node_modules/lodash/_objectToString.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/_objectToString.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; /***/ }), /***/ "../../node_modules/lodash/_root.js": /*!*********************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/_root.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(/*! ./_freeGlobal */ "../../node_modules/lodash/_freeGlobal.js"); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; /***/ }), /***/ "../../node_modules/lodash/before.js": /*!**********************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/before.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(/*! ./toInteger */ "../../node_modules/lodash/toInteger.js"); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } module.exports = before; /***/ }), /***/ "../../node_modules/lodash/fp.js": /*!******************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/fp.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _ = __webpack_require__(/*! ./lodash.min */ "../../node_modules/lodash/lodash.min.js").runInContext(); module.exports = __webpack_require__(/*! ./fp/_baseConvert */ "../../node_modules/lodash/fp/_baseConvert.js")(_, _); /***/ }), /***/ "../../node_modules/lodash/fp/_baseConvert.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/fp/_baseConvert.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var mapping = __webpack_require__(/*! ./_mapping */ "../../node_modules/lodash/fp/_mapping.js"), fallbackHolder = __webpack_require__(/*! ./placeholder */ "../../node_modules/lodash/fp/placeholder.js"); /** Built-in value reference. */ var push = Array.prototype.push; /** * Creates a function, with an arity of `n`, that invokes `func` with the * arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} n The arity of the new function. * @returns {Function} Returns the new function. */ function baseArity(func, n) { return n == 2 ? function(a, b) { return func.apply(undefined, arguments); } : function(a) { return func.apply(undefined, arguments); }; } /** * Creates a function that invokes `func`, with up to `n` arguments, ignoring * any additional arguments. * * @private * @param {Function} func The function to cap arguments for. * @param {number} n The arity cap. * @returns {Function} Returns the new function. */ function baseAry(func, n) { return n == 2 ? function(a, b) { return func(a, b); } : function(a) { return func(a); }; } /** * Creates a clone of `array`. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the cloned array. */ function cloneArray(array) { var length = array ? array.length : 0, result = Array(length); while (length--) { result[length] = array[length]; } return result; } /** * Creates a function that clones a given object using the assignment `func`. * * @private * @param {Function} func The assignment function. * @returns {Function} Returns the new cloner function. */ function createCloner(func) { return function(object) { return func({}, object); }; } /** * A specialized version of `_.spread` which flattens the spread array into * the arguments of the invoked `func`. * * @private * @param {Function} func The function to spread arguments over. * @param {number} start The start position of the spread. * @returns {Function} Returns the new function. */ function flatSpread(func, start) { return function() { var length = arguments.length, lastIndex = length - 1, args = Array(length); while (length--) { args[length] = arguments[length]; } var array = args[start], otherArgs = args.slice(0, start); if (array) { push.apply(otherArgs, array); } if (start != lastIndex) { push.apply(otherArgs, args.slice(start + 1)); } return func.apply(this, otherArgs); }; } /** * Creates a function that wraps `func` and uses `cloner` to clone the first * argument it receives. * * @private * @param {Function} func The function to wrap. * @param {Function} cloner The function to clone arguments. * @returns {Function} Returns the new immutable function. */ function wrapImmutable(func, cloner) { return function() { var length = arguments.length; if (!length) { return; } var args = Array(length); while (length--) { args[length] = arguments[length]; } var result = args[0] = cloner.apply(undefined, args); func.apply(undefined, args); return result; }; } /** * The base implementation of `convert` which accepts a `util` object of methods * required to perform conversions. * * @param {Object} util The util object. * @param {string} name The name of the function to convert. * @param {Function} func The function to convert. * @param {Object} [options] The options object. * @param {boolean} [options.cap=true] Specify capping iteratee arguments. * @param {boolean} [options.curry=true] Specify currying. * @param {boolean} [options.fixed=true] Specify fixed arity. * @param {boolean} [options.immutable=true] Specify immutable operations. * @param {boolean} [options.rearg=true] Specify rearranging arguments. * @returns {Function|Object} Returns the converted function or object. */ function baseConvert(util, name, func, options) { var setPlaceholder, isLib = typeof name == 'function', isObj = name === Object(name); if (isObj) { options = func; func = name; name = undefined; } if (func == null) { throw new TypeError; } options || (options = {}); var config = { 'cap': 'cap' in options ? options.cap : true, 'curry': 'curry' in options ? options.curry : true, 'fixed': 'fixed' in options ? options.fixed : true, 'immutable': 'immutable' in options ? options.immutable : true, 'rearg': 'rearg' in options ? options.rearg : true }; var forceCurry = ('curry' in options) && options.curry, forceFixed = ('fixed' in options) && options.fixed, forceRearg = ('rearg' in options) && options.rearg, placeholder = isLib ? func : fallbackHolder, pristine = isLib ? func.runInContext() : undefined; var helpers = isLib ? func : { 'ary': util.ary, 'assign': util.assign, 'clone': util.clone, 'curry': util.curry, 'forEach': util.forEach, 'isArray': util.isArray, 'isError': util.isError, 'isFunction': util.isFunction, 'isWeakMap': util.isWeakMap, 'iteratee': util.iteratee, 'keys': util.keys, 'rearg': util.rearg, 'toInteger': util.toInteger, 'toPath': util.toPath }; var ary = helpers.ary, assign = helpers.assign, clone = helpers.clone, curry = helpers.curry, each = helpers.forEach, isArray = helpers.isArray, isError = helpers.isError, isFunction = helpers.isFunction, isWeakMap = helpers.isWeakMap, keys = helpers.keys, rearg = helpers.rearg, toInteger = helpers.toInteger, toPath = helpers.toPath; var aryMethodKeys = keys(mapping.aryMethod); var wrappers = { 'castArray': function(castArray) { return function() { var value = arguments[0]; return isArray(value) ? castArray(cloneArray(value)) : castArray.apply(undefined, arguments); }; }, 'iteratee': function(iteratee) { return function() { var func = arguments[0], arity = arguments[1], result = iteratee(func, arity), length = result.length; if (config.cap && typeof arity == 'number') { arity = arity > 2 ? (arity - 2) : 1; return (length && length <= arity) ? result : baseAry(result, arity); } return result; }; }, 'mixin': function(mixin) { return function(source) { var func = this; if (!isFunction(func)) { return mixin(func, Object(source)); } var pairs = []; each(keys(source), function(key) { if (isFunction(source[key])) { pairs.push([key, func.prototype[key]]); } }); mixin(func, Object(source)); each(pairs, function(pair) { var value = pair[1]; if (isFunction(value)) { func.prototype[pair[0]] = value; } else { delete func.prototype[pair[0]]; } }); return func; }; }, 'nthArg': function(nthArg) { return function(n) { var arity = n < 0 ? 1 : (toInteger(n) + 1); return curry(nthArg(n), arity); }; }, 'rearg': function(rearg) { return function(func, indexes) { var arity = indexes ? indexes.length : 0; return curry(rearg(func, indexes), arity); }; }, 'runInContext': function(runInContext) { return function(context) { return baseConvert(util, runInContext(context), options); }; } }; /*--------------------------------------------------------------------------*/ /** * Casts `func` to a function with an arity capped iteratee if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @returns {Function} Returns the cast function. */ function castCap(name, func) { if (config.cap) { var indexes = mapping.iterateeRearg[name]; if (indexes) { return iterateeRearg(func, indexes); } var n = !isLib && mapping.iterateeAry[name]; if (n) { return iterateeAry(func, n); } } return func; } /** * Casts `func` to a curried function if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @param {number} n The arity of `func`. * @returns {Function} Returns the cast function. */ function castCurry(name, func, n) { return (forceCurry || (config.curry && n > 1)) ? curry(func, n) : func; } /** * Casts `func` to a fixed arity function if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @param {number} n The arity cap. * @returns {Function} Returns the cast function. */ function castFixed(name, func, n) { if (config.fixed && (forceFixed || !mapping.skipFixed[name])) { var data = mapping.methodSpread[name], start = data && data.start; return start === undefined ? ary(func, n) : flatSpread(func, start); } return func; } /** * Casts `func` to an rearged function if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @param {number} n The arity of `func`. * @returns {Function} Returns the cast function. */ function castRearg(name, func, n) { return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name])) ? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n]) : func; } /** * Creates a clone of `object` by `path`. * * @private * @param {Object} object The object to clone. * @param {Array|string} path The path to clone by. * @returns {Object} Returns the cloned object. */ function cloneByPath(object, path) { path = toPath(path); var index = -1, length = path.length, lastIndex = length - 1, result = clone(Object(object)), nested = result; while (nested != null && ++index < length) { var key = path[index], value = nested[key]; if (value != null && !(isFunction(value) || isError(value) || isWeakMap(value))) { nested[key] = clone(index == lastIndex ? value : Object(value)); } nested = nested[key]; } return result; } /** * Converts `lodash` to an immutable auto-curried iteratee-first data-last * version with conversion `options` applied. * * @param {Object} [options] The options object. See `baseConvert` for more details. * @returns {Function} Returns the converted `lodash`. */ function convertLib(options) { return _.runInContext.convert(options)(undefined); } /** * Create a converter function for `func` of `name`. * * @param {string} name The name of the function to convert. * @param {Function} func The function to convert. * @returns {Function} Returns the new converter function. */ function createConverter(name, func) { var realName = mapping.aliasToReal[name] || name, methodName = mapping.remap[realName] || realName, oldOptions = options; return function(options) { var newUtil = isLib ? pristine : helpers, newFunc = isLib ? pristine[methodName] : func, newOptions = assign(assign({}, oldOptions), options); return baseConvert(newUtil, realName, newFunc, newOptions); }; } /** * Creates a function that wraps `func` to invoke its iteratee, with up to `n` * arguments, ignoring any additional arguments. * * @private * @param {Function} func The function to cap iteratee arguments for. * @param {number} n The arity cap. * @returns {Function} Returns the new function. */ function iterateeAry(func, n) { return overArg(func, function(func) { return typeof func == 'function' ? baseAry(func, n) : func; }); } /** * Creates a function that wraps `func` to invoke its iteratee with arguments * arranged according to the specified `indexes` where the argument value at * the first index is provided as the first argument, the argument value at * the second index is provided as the second argument, and so on. * * @private * @param {Function} func The function to rearrange iteratee arguments for. * @param {number[]} indexes The arranged argument indexes. * @returns {Function} Returns the new function. */ function iterateeRearg(func, indexes) { return overArg(func, function(func) { var n = indexes.length; return baseArity(rearg(baseAry(func, n), indexes), n); }); } /** * Creates a function that invokes `func` with its first argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function() { var length = arguments.length; if (!length) { return func(); } var args = Array(length); while (length--) { args[length] = arguments[length]; } var index = config.rearg ? 0 : (length - 1); args[index] = transform(args[index]); return func.apply(undefined, args); }; } /** * Creates a function that wraps `func` and applys the conversions * rules by `name`. * * @private * @param {string} name The name of the function to wrap. * @param {Function} func The function to wrap. * @returns {Function} Returns the converted function. */ function wrap(name, func) { var result, realName = mapping.aliasToReal[name] || name, wrapped = func, wrapper = wrappers[realName]; if (wrapper) { wrapped = wrapper(func); } else if (config.immutable) { if (mapping.mutate.array[realName]) { wrapped = wrapImmutable(func, cloneArray); } else if (mapping.mutate.object[realName]) { wrapped = wrapImmutable(func, createCloner(func)); } else if (mapping.mutate.set[realName]) { wrapped = wrapImmutable(func, cloneByPath); } } each(aryMethodKeys, function(aryKey) { each(mapping.aryMethod[aryKey], function(otherName) { if (realName == otherName) { var data = mapping.methodSpread[realName], afterRearg = data && data.afterRearg; result = afterRearg ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey) : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey); result = castCap(realName, result); result = castCurry(realName, result, aryKey); return false; } }); return !result; }); result || (result = wrapped); if (result == func) { result = forceCurry ? curry(result, 1) : function() { return func.apply(this, arguments); }; } result.convert = createConverter(realName, func); if (mapping.placeholder[realName]) { setPlaceholder = true; result.placeholder = func.placeholder = placeholder; } return result; } /*--------------------------------------------------------------------------*/ if (!isObj) { return wrap(name, func); } var _ = func; // Convert methods by ary cap. var pairs = []; each(aryMethodKeys, function(aryKey) { each(mapping.aryMethod[aryKey], function(key) { var func = _[mapping.remap[key] || key]; if (func) { pairs.push([key, wrap(key, func)]); } }); }); // Convert remaining methods. each(keys(_), function(key) { var func = _[key]; if (typeof func == 'function') { var length = pairs.length; while (length--) { if (pairs[length][0] == key) { return; } } func.convert = createConverter(key, func); pairs.push([key, func]); } }); // Assign to `_` leaving `_.prototype` unchanged to allow chaining. each(pairs, function(pair) { _[pair[0]] = pair[1]; }); _.convert = convertLib; if (setPlaceholder) { _.placeholder = placeholder; } // Assign aliases. each(keys(_), function(key) { each(mapping.realToAlias[key] || [], function(alias) { _[alias] = _[key]; }); }); return _; } module.exports = baseConvert; /***/ }), /***/ "../../node_modules/lodash/fp/_mapping.js": /*!***************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/fp/_mapping.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** Used to map aliases to their real names. */ exports.aliasToReal = { // Lodash aliases. 'each': 'forEach', 'eachRight': 'forEachRight', 'entries': 'toPairs', 'entriesIn': 'toPairsIn', 'extend': 'assignIn', 'extendAll': 'assignInAll', 'extendAllWith': 'assignInAllWith', 'extendWith': 'assignInWith', 'first': 'head', // Methods that are curried variants of others. 'conforms': 'conformsTo', 'matches': 'isMatch', 'property': 'get', // Ramda aliases. '__': 'placeholder', 'F': 'stubFalse', 'T': 'stubTrue', 'all': 'every', 'allPass': 'overEvery', 'always': 'constant', 'any': 'some', 'anyPass': 'overSome', 'apply': 'spread', 'assoc': 'set', 'assocPath': 'set', 'complement': 'negate', 'compose': 'flowRight', 'contains': 'includes', 'dissoc': 'unset', 'dissocPath': 'unset', 'dropLast': 'dropRight', 'dropLastWhile': 'dropRightWhile', 'equals': 'isEqual', 'identical': 'eq', 'indexBy': 'keyBy', 'init': 'initial', 'invertObj': 'invert', 'juxt': 'over', 'omitAll': 'omit', 'nAry': 'ary', 'path': 'get', 'pathEq': 'matchesProperty', 'pathOr': 'getOr', 'paths': 'at', 'pickAll': 'pick', 'pipe': 'flow', 'pluck': 'map', 'prop': 'get', 'propEq': 'matchesProperty', 'propOr': 'getOr', 'props': 'at', 'symmetricDifference': 'xor', 'symmetricDifferenceBy': 'xorBy', 'symmetricDifferenceWith': 'xorWith', 'takeLast': 'takeRight', 'takeLastWhile': 'takeRightWhile', 'unapply': 'rest', 'unnest': 'flatten', 'useWith': 'overArgs', 'where': 'conformsTo', 'whereEq': 'isMatch', 'zipObj': 'zipObject' }; /** Used to map ary to method names. */ exports.aryMethod = { '1': [ 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create', 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow', 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll', 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse', 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart', 'uniqueId', 'words', 'zipAll' ], '2': [ 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith', 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith', 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN', 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference', 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq', 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get', 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection', 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy', 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty', 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit', 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial', 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll', 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove', 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex', 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy', 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight', 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars', 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith', 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject', 'zipObjectDeep' ], '3': [ 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith', 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr', 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith', 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth', 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd', 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight', 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy', 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy', 'xorWith', 'zipWith' ], '4': [ 'fill', 'setWith', 'updateWith' ] }; /** Used to map ary to rearg configs. */ exports.aryRearg = { '2': [1, 0], '3': [2, 0, 1], '4': [3, 2, 0, 1] }; /** Used to map method names to their iteratee ary. */ exports.iterateeAry = { 'dropRightWhile': 1, 'dropWhile': 1, 'every': 1, 'filter': 1, 'find': 1, 'findFrom': 1, 'findIndex': 1, 'findIndexFrom': 1, 'findKey': 1, 'findLast': 1, 'findLastFrom': 1, 'findLastIndex': 1, 'findLastIndexFrom': 1, 'findLastKey': 1, 'flatMap': 1, 'flatMapDeep': 1, 'flatMapDepth': 1, 'forEach': 1, 'forEachRight': 1, 'forIn': 1, 'forInRight': 1, 'forOwn': 1, 'forOwnRight': 1, 'map': 1, 'mapKeys': 1, 'mapValues': 1, 'partition': 1, 'reduce': 2, 'reduceRight': 2, 'reject': 1, 'remove': 1, 'some': 1, 'takeRightWhile': 1, 'takeWhile': 1, 'times': 1, 'transform': 2 }; /** Used to map method names to iteratee rearg configs. */ exports.iterateeRearg = { 'mapKeys': [1], 'reduceRight': [1, 0] }; /** Used to map method names to rearg configs. */ exports.methodRearg = { 'assignInAllWith': [1, 0], 'assignInWith': [1, 2, 0], 'assignAllWith': [1, 0], 'assignWith': [1, 2, 0], 'differenceBy': [1, 2, 0], 'differenceWith': [1, 2, 0], 'getOr': [2, 1, 0], 'intersectionBy': [1, 2, 0], 'intersectionWith': [1, 2, 0], 'isEqualWith': [1, 2, 0], 'isMatchWith': [2, 1, 0], 'mergeAllWith': [1, 0], 'mergeWith': [1, 2, 0], 'padChars': [2, 1, 0], 'padCharsEnd': [2, 1, 0], 'padCharsStart': [2, 1, 0], 'pullAllBy': [2, 1, 0], 'pullAllWith': [2, 1, 0], 'rangeStep': [1, 2, 0], 'rangeStepRight': [1, 2, 0], 'setWith': [3, 1, 2, 0], 'sortedIndexBy': [2, 1, 0], 'sortedLastIndexBy': [2, 1, 0], 'unionBy': [1, 2, 0], 'unionWith': [1, 2, 0], 'updateWith': [3, 1, 2, 0], 'xorBy': [1, 2, 0], 'xorWith': [1, 2, 0], 'zipWith': [1, 2, 0] }; /** Used to map method names to spread configs. */ exports.methodSpread = { 'assignAll': { 'start': 0 }, 'assignAllWith': { 'start': 0 }, 'assignInAll': { 'start': 0 }, 'assignInAllWith': { 'start': 0 }, 'defaultsAll': { 'start': 0 }, 'defaultsDeepAll': { 'start': 0 }, 'invokeArgs': { 'start': 2 }, 'invokeArgsMap': { 'start': 2 }, 'mergeAll': { 'start': 0 }, 'mergeAllWith': { 'start': 0 }, 'partial': { 'start': 1 }, 'partialRight': { 'start': 1 }, 'without': { 'start': 1 }, 'zipAll': { 'start': 0 } }; /** Used to identify methods which mutate arrays or objects. */ exports.mutate = { 'array': { 'fill': true, 'pull': true, 'pullAll': true, 'pullAllBy': true, 'pullAllWith': true, 'pullAt': true, 'remove': true, 'reverse': true }, 'object': { 'assign': true, 'assignAll': true, 'assignAllWith': true, 'assignIn': true, 'assignInAll': true, 'assignInAllWith': true, 'assignInWith': true, 'assignWith': true, 'defaults': true, 'defaultsAll': true, 'defaultsDeep': true, 'defaultsDeepAll': true, 'merge': true, 'mergeAll': true, 'mergeAllWith': true, 'mergeWith': true, }, 'set': { 'set': true, 'setWith': true, 'unset': true, 'update': true, 'updateWith': true } }; /** Used to track methods with placeholder support */ exports.placeholder = { 'bind': true, 'bindKey': true, 'curry': true, 'curryRight': true, 'partial': true, 'partialRight': true }; /** Used to map real names to their aliases. */ exports.realToAlias = (function() { var hasOwnProperty = Object.prototype.hasOwnProperty, object = exports.aliasToReal, result = {}; for (var key in object) { var value = object[key]; if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } } return result; }()); /** Used to map method names to other names. */ exports.remap = { 'assignAll': 'assign', 'assignAllWith': 'assignWith', 'assignInAll': 'assignIn', 'assignInAllWith': 'assignInWith', 'curryN': 'curry', 'curryRightN': 'curryRight', 'defaultsAll': 'defaults', 'defaultsDeepAll': 'defaultsDeep', 'findFrom': 'find', 'findIndexFrom': 'findIndex', 'findLastFrom': 'findLast', 'findLastIndexFrom': 'findLastIndex', 'getOr': 'get', 'includesFrom': 'includes', 'indexOfFrom': 'indexOf', 'invokeArgs': 'invoke', 'invokeArgsMap': 'invokeMap', 'lastIndexOfFrom': 'lastIndexOf', 'mergeAll': 'merge', 'mergeAllWith': 'mergeWith', 'padChars': 'pad', 'padCharsEnd': 'padEnd', 'padCharsStart': 'padStart', 'propertyOf': 'get', 'rangeStep': 'range', 'rangeStepRight': 'rangeRight', 'restFrom': 'rest', 'spreadFrom': 'spread', 'trimChars': 'trim', 'trimCharsEnd': 'trimEnd', 'trimCharsStart': 'trimStart', 'zipAll': 'zip' }; /** Used to track methods that skip fixing their arity. */ exports.skipFixed = { 'castArray': true, 'flow': true, 'flowRight': true, 'iteratee': true, 'mixin': true, 'rearg': true, 'runInContext': true }; /** Used to track methods that skip rearranging arguments. */ exports.skipRearg = { 'add': true, 'assign': true, 'assignIn': true, 'bind': true, 'bindKey': true, 'concat': true, 'difference': true, 'divide': true, 'eq': true, 'gt': true, 'gte': true, 'isEqual': true, 'lt': true, 'lte': true, 'matchesProperty': true, 'merge': true, 'multiply': true, 'overArgs': true, 'partial': true, 'partialRight': true, 'propertyOf': true, 'random': true, 'range': true, 'rangeRight': true, 'subtract': true, 'zip': true, 'zipObject': true, 'zipObjectDeep': true }; /***/ }), /***/ "../../node_modules/lodash/fp/placeholder.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/fp/placeholder.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** * The default argument placeholder value for methods. * * @type {Object} */ module.exports = {}; /***/ }), /***/ "../../node_modules/lodash/isObject.js": /*!************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/isObject.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }), /***/ "../../node_modules/lodash/isObjectLike.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/isObjectLike.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; /***/ }), /***/ "../../node_modules/lodash/isSymbol.js": /*!************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/isSymbol.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ "../../node_modules/lodash/_baseGetTag.js"), isObjectLike = __webpack_require__(/*! ./isObjectLike */ "../../node_modules/lodash/isObjectLike.js"); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; /***/ }), /***/ "../../node_modules/lodash/lodash.min.js": /*!**************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/lodash.min.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_RESULT__;/** * @license * Lodash lodash.com/license | Underscore.js 1.8.3 underscorejs.org/LICENSE */ ;(function(){function n(n,t,r){switch(r.length){case 0:return n.call(t);case 1:return n.call(t,r[0]);case 2:return n.call(t,r[0],r[1]);case 3:return n.call(t,r[0],r[1],r[2])}return n.apply(t,r)}function t(n,t,r,e){for(var u=-1,i=null==n?0:n.length;++u<i;){var o=n[u];t(e,o,r(o),n)}return e}function r(n,t){for(var r=-1,e=null==n?0:n.length;++r<e&&false!==t(n[r],r,n););return n}function e(n,t){for(var r=null==n?0:n.length;r--&&false!==t(n[r],r,n););return n}function u(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(!t(n[r],r,n))return false; return true}function i(n,t){for(var r=-1,e=null==n?0:n.length,u=0,i=[];++r<e;){var o=n[r];t(o,r,n)&&(i[u++]=o)}return i}function o(n,t){return!(null==n||!n.length)&&-1<v(n,t,0)}function f(n,t,r){for(var e=-1,u=null==n?0:n.length;++e<u;)if(r(t,n[e]))return true;return false}function c(n,t){for(var r=-1,e=null==n?0:n.length,u=Array(e);++r<e;)u[r]=t(n[r],r,n);return u}function a(n,t){for(var r=-1,e=t.length,u=n.length;++r<e;)n[u+r]=t[r];return n}function l(n,t,r,e){var u=-1,i=null==n?0:n.length;for(e&&i&&(r=n[++u]);++u<i;)r=t(r,n[u],u,n); return r}function s(n,t,r,e){var u=null==n?0:n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);return r}function h(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(t(n[r],r,n))return true;return false}function p(n,t,r){var e;return r(n,function(n,r,u){if(t(n,r,u))return e=r,false}),e}function _(n,t,r,e){var u=n.length;for(r+=e?1:-1;e?r--:++r<u;)if(t(n[r],r,n))return r;return-1}function v(n,t,r){if(t===t)n:{--r;for(var e=n.length;++r<e;)if(n[r]===t){n=r;break n}n=-1}else n=_(n,d,r);return n}function g(n,t,r,e){ --r;for(var u=n.length;++r<u;)if(e(n[r],t))return r;return-1}function d(n){return n!==n}function y(n,t){var r=null==n?0:n.length;return r?m(n,t)/r:F}function b(n){return function(t){return null==t?T:t[n]}}function x(n){return function(t){return null==n?T:n[t]}}function j(n,t,r,e,u){return u(n,function(n,u,i){r=e?(e=false,n):t(r,n,u,i)}),r}function w(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].c;return n}function m(n,t){for(var r,e=-1,u=n.length;++e<u;){var i=t(n[e]);i!==T&&(r=r===T?i:r+i)}return r; }function A(n,t){for(var r=-1,e=Array(n);++r<n;)e[r]=t(r);return e}function k(n,t){return c(t,function(t){return[t,n[t]]})}function E(n){return function(t){return n(t)}}function S(n,t){return c(t,function(t){return n[t]})}function O(n,t){return n.has(t)}function I(n,t){for(var r=-1,e=n.length;++r<e&&-1<v(t,n[r],0););return r}function R(n,t){for(var r=n.length;r--&&-1<v(t,n[r],0););return r}function z(n){return"\\"+Cn[n]}function W(n){var t=-1,r=Array(n.size);return n.forEach(function(n,e){r[++t]=[e,n]; }),r}function B(n,t){return function(r){return n(t(r))}}function L(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){var o=n[r];o!==t&&"__lodash_placeholder__"!==o||(n[r]="__lodash_placeholder__",i[u++]=r)}return i}function U(n){var t=-1,r=Array(n.size);return n.forEach(function(n){r[++t]=n}),r}function C(n){var t=-1,r=Array(n.size);return n.forEach(function(n){r[++t]=[n,n]}),r}function D(n){if(Rn.test(n)){for(var t=On.lastIndex=0;On.test(n);)++t;n=t}else n=Qn(n);return n}function M(n){return Rn.test(n)?n.match(On)||[]:n.split(""); }var T,$=1/0,F=NaN,N=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]],P=/\b__p\+='';/g,Z=/\b(__p\+=)''\+/g,q=/(__e\(.*?\)|\b__t\))\+'';/g,V=/&(?:amp|lt|gt|quot|#39);/g,K=/[&<>"']/g,G=RegExp(V.source),H=RegExp(K.source),J=/<%-([\s\S]+?)%>/g,Y=/<%([\s\S]+?)%>/g,Q=/<%=([\s\S]+?)%>/g,X=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,nn=/^\w*$/,tn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,rn=/[\\^$.*+?()[\]{}|]/g,en=RegExp(rn.source),un=/^\s+|\s+$/g,on=/^\s+/,fn=/\s+$/,cn=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,an=/\{\n\/\* \[wrapped with (.+)\] \*/,ln=/,? & /,sn=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,hn=/\\(\\)?/g,pn=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,_n=/\w*$/,vn=/^[-+]0x[0-9a-f]+$/i,gn=/^0b[01]+$/i,dn=/^\[object .+?Constructor\]$/,yn=/^0o[0-7]+$/i,bn=/^(?:0|[1-9]\d*)$/,xn=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,jn=/($^)/,wn=/['\n\r\u2028\u2029\\]/g,mn="[\\ufe0e\\ufe0f]?(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?(?:\\u200d(?:[^\\ud800-\\udfff]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff])[\\ufe0e\\ufe0f]?(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?)*",An="(?:[\\u2700-\\u27bf]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff])"+mn,kn="(?:[^\\ud800-\\udfff][\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]?|[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff]|[\\ud800-\\udfff])",En=RegExp("['\u2019]","g"),Sn=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]","g"),On=RegExp("\\ud83c[\\udffb-\\udfff](?=\\ud83c[\\udffb-\\udfff])|"+kn+mn,"g"),In=RegExp(["[A-Z\\xc0-\\xd6\\xd8-\\xde]?[a-z\\xdf-\\xf6\\xf8-\\xff]+(?:['\u2019](?:d|ll|m|re|s|t|ve))?(?=[\\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]|[A-Z\\xc0-\\xd6\\xd8-\\xde]|$)|(?:[A-Z\\xc0-\\xd6\\xd8-\\xde]|[^\\ud800-\\udfff\\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\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])+(?:['\u2019](?:D|LL|M|RE|S|T|VE))?(?=[\\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]|[A-Z\\xc0-\\xd6\\xd8-\\xde](?:[a-z\\xdf-\\xf6\\xf8-\\xff]|[^\\ud800-\\udfff\\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\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])|$)|[A-Z\\xc0-\\xd6\\xd8-\\xde]?(?:[a-z\\xdf-\\xf6\\xf8-\\xff]|[^\\ud800-\\udfff\\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\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])+(?:['\u2019](?:d|ll|m|re|s|t|ve))?|[A-Z\\xc0-\\xd6\\xd8-\\xde]+(?:['\u2019](?: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_])|\\d+",An].join("|"),"g"),Rn=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]"),zn=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Wn="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".split(" "),Bn={}; Bn["[object Float32Array]"]=Bn["[object Float64Array]"]=Bn["[object Int8Array]"]=Bn["[object Int16Array]"]=Bn["[object Int32Array]"]=Bn["[object Uint8Array]"]=Bn["[object Uint8ClampedArray]"]=Bn["[object Uint16Array]"]=Bn["[object Uint32Array]"]=true,Bn["[object Arguments]"]=Bn["[object Array]"]=Bn["[object ArrayBuffer]"]=Bn["[object Boolean]"]=Bn["[object DataView]"]=Bn["[object Date]"]=Bn["[object Error]"]=Bn["[object Function]"]=Bn["[object Map]"]=Bn["[object Number]"]=Bn["[object Object]"]=Bn["[object RegExp]"]=Bn["[object Set]"]=Bn["[object String]"]=Bn["[object WeakMap]"]=false; var Ln={};Ln["[object Arguments]"]=Ln["[object Array]"]=Ln["[object ArrayBuffer]"]=Ln["[object DataView]"]=Ln["[object Boolean]"]=Ln["[object Date]"]=Ln["[object Float32Array]"]=Ln["[object Float64Array]"]=Ln["[object Int8Array]"]=Ln["[object Int16Array]"]=Ln["[object Int32Array]"]=Ln["[object Map]"]=Ln["[object Number]"]=Ln["[object Object]"]=Ln["[object RegExp]"]=Ln["[object Set]"]=Ln["[object String]"]=Ln["[object Symbol]"]=Ln["[object Uint8Array]"]=Ln["[object Uint8ClampedArray]"]=Ln["[object Uint16Array]"]=Ln["[object Uint32Array]"]=true, Ln["[object Error]"]=Ln["[object Function]"]=Ln["[object WeakMap]"]=false;var Un,Cn={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Dn=parseFloat,Mn=parseInt,Tn=typeof global=="object"&&global&&global.Object===Object&&global,$n=typeof self=="object"&&self&&self.Object===Object&&self,Fn=Tn||$n||Function("return this")(),Nn=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Pn=Nn&&typeof module=="object"&&module&&!module.nodeType&&module,Zn=Pn&&Pn.exports===Nn,qn=Zn&&Tn.process; n:{try{Un=qn&&qn.binding&&qn.binding("util");break n}catch(n){}Un=void 0}var Vn=Un&&Un.isArrayBuffer,Kn=Un&&Un.isDate,Gn=Un&&Un.isMap,Hn=Un&&Un.isRegExp,Jn=Un&&Un.isSet,Yn=Un&&Un.isTypedArray,Qn=b("length"),Xn=x({"\xc0":"A","\xc1":"A","\xc2":"A","\xc3":"A","\xc4":"A","\xc5":"A","\xe0":"a","\xe1":"a","\xe2":"a","\xe3":"a","\xe4":"a","\xe5":"a","\xc7":"C","\xe7":"c","\xd0":"D","\xf0":"d","\xc8":"E","\xc9":"E","\xca":"E","\xcb":"E","\xe8":"e","\xe9":"e","\xea":"e","\xeb":"e","\xcc":"I","\xcd":"I","\xce":"I", "\xcf":"I","\xec":"i","\xed":"i","\xee":"i","\xef":"i","\xd1":"N","\xf1":"n","\xd2":"O","\xd3":"O","\xd4":"O","\xd5":"O","\xd6":"O","\xd8":"O","\xf2":"o","\xf3":"o","\xf4":"o","\xf5":"o","\xf6":"o","\xf8":"o","\xd9":"U","\xda":"U","\xdb":"U","\xdc":"U","\xf9":"u","\xfa":"u","\xfb":"u","\xfc":"u","\xdd":"Y","\xfd":"y","\xff":"y","\xc6":"Ae","\xe6":"ae","\xde":"Th","\xfe":"th","\xdf":"ss","\u0100":"A","\u0102":"A","\u0104":"A","\u0101":"a","\u0103":"a","\u0105":"a","\u0106":"C","\u0108":"C","\u010a":"C", "\u010c":"C","\u0107":"c","\u0109":"c","\u010b":"c","\u010d":"c","\u010e":"D","\u0110":"D","\u010f":"d","\u0111":"d","\u0112":"E","\u0114":"E","\u0116":"E","\u0118":"E","\u011a":"E","\u0113":"e","\u0115":"e","\u0117":"e","\u0119":"e","\u011b":"e","\u011c":"G","\u011e":"G","\u0120":"G","\u0122":"G","\u011d":"g","\u011f":"g","\u0121":"g","\u0123":"g","\u0124":"H","\u0126":"H","\u0125":"h","\u0127":"h","\u0128":"I","\u012a":"I","\u012c":"I","\u012e":"I","\u0130":"I","\u0129":"i","\u012b":"i","\u012d":"i", "\u012f":"i","\u0131":"i","\u0134":"J","\u0135":"j","\u0136":"K","\u0137":"k","\u0138":"k","\u0139":"L","\u013b":"L","\u013d":"L","\u013f":"L","\u0141":"L","\u013a":"l","\u013c":"l","\u013e":"l","\u0140":"l","\u0142":"l","\u0143":"N","\u0145":"N","\u0147":"N","\u014a":"N","\u0144":"n","\u0146":"n","\u0148":"n","\u014b":"n","\u014c":"O","\u014e":"O","\u0150":"O","\u014d":"o","\u014f":"o","\u0151":"o","\u0154":"R","\u0156":"R","\u0158":"R","\u0155":"r","\u0157":"r","\u0159":"r","\u015a":"S","\u015c":"S", "\u015e":"S","\u0160":"S","\u015b":"s","\u015d":"s","\u015f":"s","\u0161":"s","\u0162":"T","\u0164":"T","\u0166":"T","\u0163":"t","\u0165":"t","\u0167":"t","\u0168":"U","\u016a":"U","\u016c":"U","\u016e":"U","\u0170":"U","\u0172":"U","\u0169":"u","\u016b":"u","\u016d":"u","\u016f":"u","\u0171":"u","\u0173":"u","\u0174":"W","\u0175":"w","\u0176":"Y","\u0177":"y","\u0178":"Y","\u0179":"Z","\u017b":"Z","\u017d":"Z","\u017a":"z","\u017c":"z","\u017e":"z","\u0132":"IJ","\u0133":"ij","\u0152":"Oe","\u0153":"oe", "\u0149":"'n","\u017f":"s"}),nt=x({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}),tt=x({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"}),rt=function x(mn){function An(n){if(du(n)&&!of(n)&&!(n instanceof Un)){if(n instanceof On)return n;if(ii.call(n,"__wrapped__"))return $e(n)}return new On(n)}function kn(){}function On(n,t){this.__wrapped__=n,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=T}function Un(n){this.__wrapped__=n,this.__actions__=[],this.__dir__=1, this.__filtered__=false,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[]}function Cn(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function Tn(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function $n(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function Nn(n){var t=-1,r=null==n?0:n.length;for(this.__data__=new $n;++t<r;)this.add(n[t])}function Pn(n){ this.size=(this.__data__=new Tn(n)).size}function qn(n,t){var r,e=of(n),u=!e&&uf(n),i=!e&&!u&&cf(n),o=!e&&!u&&!i&&pf(n),u=(e=e||u||i||o)?A(n.length,Xu):[],f=u.length;for(r in n)!t&&!ii.call(n,r)||e&&("length"==r||i&&("offset"==r||"parent"==r)||o&&("buffer"==r||"byteLength"==r||"byteOffset"==r)||Se(r,f))||u.push(r);return u}function Qn(n){var t=n.length;return t?n[ir(0,t-1)]:T}function et(n,t){return Ce(Ur(n),pt(t,0,n.length))}function ut(n){return Ce(Ur(n))}function it(n,t,r){(r===T||au(n[t],r))&&(r!==T||t in n)||st(n,t,r); }function ot(n,t,r){var e=n[t];ii.call(n,t)&&au(e,r)&&(r!==T||t in n)||st(n,t,r)}function ft(n,t){for(var r=n.length;r--;)if(au(n[r][0],t))return r;return-1}function ct(n,t,r,e){return eo(n,function(n,u,i){t(e,n,r(n),i)}),e}function at(n,t){return n&&Cr(t,zu(t),n)}function lt(n,t){return n&&Cr(t,Wu(t),n)}function st(n,t,r){"__proto__"==t&&mi?mi(n,t,{configurable:true,enumerable:true,value:r,writable:true}):n[t]=r}function ht(n,t){for(var r=-1,e=t.length,u=Vu(e),i=null==n;++r<e;)u[r]=i?T:Iu(n,t[r]);return u; }function pt(n,t,r){return n===n&&(r!==T&&(n=n<=r?n:r),t!==T&&(n=n>=t?n:t)),n}function _t(n,t,e,u,i,o){var f,c=1&t,a=2&t,l=4&t;if(e&&(f=i?e(n,u,i,o):e(n)),f!==T)return f;if(!gu(n))return n;if(u=of(n)){if(f=me(n),!c)return Ur(n,f)}else{var s=_o(n),h="[object Function]"==s||"[object GeneratorFunction]"==s;if(cf(n))return Ir(n,c);if("[object Object]"==s||"[object Arguments]"==s||h&&!i){if(f=a||h?{}:Ae(n),!c)return a?Mr(n,lt(f,n)):Dr(n,at(f,n))}else{if(!Ln[s])return i?n:{};f=ke(n,s,c)}}if(o||(o=new Pn), i=o.get(n))return i;if(o.set(n,f),hf(n))return n.forEach(function(r){f.add(_t(r,t,e,r,n,o))}),f;if(lf(n))return n.forEach(function(r,u){f.set(u,_t(r,t,e,u,n,o))}),f;var a=l?a?ve:_e:a?Wu:zu,p=u?T:a(n);return r(p||n,function(r,u){p&&(u=r,r=n[u]),ot(f,u,_t(r,t,e,u,n,o))}),f}function vt(n){var t=zu(n);return function(r){return gt(r,n,t)}}function gt(n,t,r){var e=r.length;if(null==n)return!e;for(n=Yu(n);e--;){var u=r[e],i=t[u],o=n[u];if(o===T&&!(u in n)||!i(o))return false}return true}function dt(n,t,r){if(typeof n!="function")throw new ni("Expected a function"); return yo(function(){n.apply(T,r)},t)}function yt(n,t,r,e){var u=-1,i=o,a=true,l=n.length,s=[],h=t.length;if(!l)return s;r&&(t=c(t,E(r))),e?(i=f,a=false):200<=t.length&&(i=O,a=false,t=new Nn(t));n:for(;++u<l;){var p=n[u],_=null==r?p:r(p),p=e||0!==p?p:0;if(a&&_===_){for(var v=h;v--;)if(t[v]===_)continue n;s.push(p)}else i(t,_,e)||s.push(p)}return s}function bt(n,t){var r=true;return eo(n,function(n,e,u){return r=!!t(n,e,u)}),r}function xt(n,t,r){for(var e=-1,u=n.length;++e<u;){var i=n[e],o=t(i);if(null!=o&&(f===T?o===o&&!ju(o):r(o,f)))var f=o,c=i; }return c}function jt(n,t){var r=[];return eo(n,function(n,e,u){t(n,e,u)&&r.push(n)}),r}function wt(n,t,r,e,u){var i=-1,o=n.length;for(r||(r=Ee),u||(u=[]);++i<o;){var f=n[i];0<t&&r(f)?1<t?wt(f,t-1,r,e,u):a(u,f):e||(u[u.length]=f)}return u}function mt(n,t){return n&&io(n,t,zu)}function At(n,t){return n&&oo(n,t,zu)}function kt(n,t){return i(t,function(t){return pu(n[t])})}function Et(n,t){t=Sr(t,n);for(var r=0,e=t.length;null!=n&&r<e;)n=n[De(t[r++])];return r&&r==e?n:T}function St(n,t,r){return t=t(n), of(n)?t:a(t,r(n))}function Ot(n){if(null==n)n=n===T?"[object Undefined]":"[object Null]";else if(wi&&wi in Yu(n)){var t=ii.call(n,wi),r=n[wi];try{n[wi]=T;var e=true}catch(n){}var u=ci.call(n);e&&(t?n[wi]=r:delete n[wi]),n=u}else n=ci.call(n);return n}function It(n,t){return n>t}function Rt(n,t){return null!=n&&ii.call(n,t)}function zt(n,t){return null!=n&&t in Yu(n)}function Wt(n,t,r){for(var e=r?f:o,u=n[0].length,i=n.length,a=i,l=Vu(i),s=1/0,h=[];a--;){var p=n[a];a&&t&&(p=c(p,E(t))),s=Ui(p.length,s), l[a]=!r&&(t||120<=u&&120<=p.length)?new Nn(a&&p):T}var p=n[0],_=-1,v=l[0];n:for(;++_<u&&h.length<s;){var g=p[_],d=t?t(g):g,g=r||0!==g?g:0;if(v?!O(v,d):!e(h,d,r)){for(a=i;--a;){var y=l[a];if(y?!O(y,d):!e(n[a],d,r))continue n}v&&v.push(d),h.push(g)}}return h}function Bt(n,t,r){var e={};return mt(n,function(n,u,i){t(e,r(n),u,i)}),e}function Lt(t,r,e){return r=Sr(r,t),t=2>r.length?t:Et(t,hr(r,0,-1)),r=null==t?t:t[De(qe(r))],null==r?T:n(r,t,e)}function Ut(n){return du(n)&&"[object Arguments]"==Ot(n)}function Ct(n){ return du(n)&&"[object ArrayBuffer]"==Ot(n)}function Dt(n){return du(n)&&"[object Date]"==Ot(n)}function Mt(n,t,r,e,u){if(n===t)t=true;else if(null==n||null==t||!du(n)&&!du(t))t=n!==n&&t!==t;else n:{var i=of(n),o=of(t),f=i?"[object Array]":_o(n),c=o?"[object Array]":_o(t),f="[object Arguments]"==f?"[object Object]":f,c="[object Arguments]"==c?"[object Object]":c,a="[object Object]"==f,o="[object Object]"==c;if((c=f==c)&&cf(n)){if(!cf(t)){t=false;break n}i=true,a=false}if(c&&!a)u||(u=new Pn),t=i||pf(n)?se(n,t,r,e,Mt,u):he(n,t,f,r,e,Mt,u);else{ if(!(1&r)&&(i=a&&ii.call(n,"__wrapped__"),f=o&&ii.call(t,"__wrapped__"),i||f)){n=i?n.value():n,t=f?t.value():t,u||(u=new Pn),t=Mt(n,t,r,e,u);break n}if(c)t:if(u||(u=new Pn),i=1&r,f=_e(n),o=f.length,c=_e(t).length,o==c||i){for(a=o;a--;){var l=f[a];if(!(i?l in t:ii.call(t,l))){t=false;break t}}if((c=u.get(n))&&u.get(t))t=c==t;else{c=true,u.set(n,t),u.set(t,n);for(var s=i;++a<o;){var l=f[a],h=n[l],p=t[l];if(e)var _=i?e(p,h,l,t,n,u):e(h,p,l,n,t,u);if(_===T?h!==p&&!Mt(h,p,r,e,u):!_){c=false;break}s||(s="constructor"==l); }c&&!s&&(r=n.constructor,e=t.constructor,r!=e&&"constructor"in n&&"constructor"in t&&!(typeof r=="function"&&r instanceof r&&typeof e=="function"&&e instanceof e)&&(c=false)),u.delete(n),u.delete(t),t=c}}else t=false;else t=false}}return t}function Tt(n){return du(n)&&"[object Map]"==_o(n)}function $t(n,t,r,e){var u=r.length,i=u,o=!e;if(null==n)return!i;for(n=Yu(n);u--;){var f=r[u];if(o&&f[2]?f[1]!==n[f[0]]:!(f[0]in n))return false}for(;++u<i;){var f=r[u],c=f[0],a=n[c],l=f[1];if(o&&f[2]){if(a===T&&!(c in n))return false; }else{if(f=new Pn,e)var s=e(a,l,c,n,t,f);if(s===T?!Mt(l,a,3,e,f):!s)return false}}return true}function Ft(n){return!(!gu(n)||fi&&fi in n)&&(pu(n)?si:dn).test(Me(n))}function Nt(n){return du(n)&&"[object RegExp]"==Ot(n)}function Pt(n){return du(n)&&"[object Set]"==_o(n)}function Zt(n){return du(n)&&vu(n.length)&&!!Bn[Ot(n)]}function qt(n){return typeof n=="function"?n:null==n?Tu:typeof n=="object"?of(n)?Jt(n[0],n[1]):Ht(n):Pu(n)}function Vt(n){if(!ze(n))return Bi(n);var t,r=[];for(t in Yu(n))ii.call(n,t)&&"constructor"!=t&&r.push(t); return r}function Kt(n,t){return n<t}function Gt(n,t){var r=-1,e=lu(n)?Vu(n.length):[];return eo(n,function(n,u,i){e[++r]=t(n,u,i)}),e}function Ht(n){var t=xe(n);return 1==t.length&&t[0][2]?We(t[0][0],t[0][1]):function(r){return r===n||$t(r,n,t)}}function Jt(n,t){return Ie(n)&&t===t&&!gu(t)?We(De(n),t):function(r){var e=Iu(r,n);return e===T&&e===t?Ru(r,n):Mt(t,e,3)}}function Yt(n,t,r,e,u){n!==t&&io(t,function(i,o){if(gu(i)){u||(u=new Pn);var f=u,c="__proto__"==o?T:n[o],a="__proto__"==o?T:t[o],l=f.get(a); if(l)it(n,o,l);else{var l=e?e(c,a,o+"",n,t,f):T,s=l===T;if(s){var h=of(a),p=!h&&cf(a),_=!h&&!p&&pf(a),l=a;h||p||_?of(c)?l=c:su(c)?l=Ur(c):p?(s=false,l=Ir(a,true)):_?(s=false,l=zr(a,true)):l=[]:bu(a)||uf(a)?(l=c,uf(c)?l=Su(c):(!gu(c)||r&&pu(c))&&(l=Ae(a))):s=false}s&&(f.set(a,l),Yt(l,a,r,e,f),f.delete(a)),it(n,o,l)}}else f=e?e("__proto__"==o?T:n[o],i,o+"",n,t,u):T,f===T&&(f=i),it(n,o,f)},Wu)}function Qt(n,t){var r=n.length;if(r)return t+=0>t?r:0,Se(t,r)?n[t]:T}function Xt(n,t,r){var e=-1;return t=c(t.length?t:[Tu],E(ye())), n=Gt(n,function(n){return{a:c(t,function(t){return t(n)}),b:++e,c:n}}),w(n,function(n,t){var e;n:{e=-1;for(var u=n.a,i=t.a,o=u.length,f=r.length;++e<o;){var c=Wr(u[e],i[e]);if(c){e=e>=f?c:c*("desc"==r[e]?-1:1);break n}}e=n.b-t.b}return e})}function nr(n,t){return tr(n,t,function(t,r){return Ru(n,r)})}function tr(n,t,r){for(var e=-1,u=t.length,i={};++e<u;){var o=t[e],f=Et(n,o);r(f,o)&&lr(i,Sr(o,n),f)}return i}function rr(n){return function(t){return Et(t,n)}}function er(n,t,r,e){var u=e?g:v,i=-1,o=t.length,f=n; for(n===t&&(t=Ur(t)),r&&(f=c(n,E(r)));++i<o;)for(var a=0,l=t[i],l=r?r(l):l;-1<(a=u(f,l,a,e));)f!==n&&bi.call(f,a,1),bi.call(n,a,1);return n}function ur(n,t){for(var r=n?t.length:0,e=r-1;r--;){var u=t[r];if(r==e||u!==i){var i=u;Se(u)?bi.call(n,u,1):xr(n,u)}}}function ir(n,t){return n+Oi(Mi()*(t-n+1))}function or(n,t){var r="";if(!n||1>t||9007199254740991<t)return r;do t%2&&(r+=n),(t=Oi(t/2))&&(n+=n);while(t);return r}function fr(n,t){return bo(Be(n,t,Tu),n+"")}function cr(n){return Qn(Lu(n))}function ar(n,t){ var r=Lu(n);return Ce(r,pt(t,0,r.length))}function lr(n,t,r,e){if(!gu(n))return n;t=Sr(t,n);for(var u=-1,i=t.length,o=i-1,f=n;null!=f&&++u<i;){var c=De(t[u]),a=r;if(u!=o){var l=f[c],a=e?e(l,c,f):T;a===T&&(a=gu(l)?l:Se(t[u+1])?[]:{})}ot(f,c,a),f=f[c]}return n}function sr(n){return Ce(Lu(n))}function hr(n,t,r){var e=-1,u=n.length;for(0>t&&(t=-t>u?0:u+t),r=r>u?u:r,0>r&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0,r=Vu(u);++e<u;)r[e]=n[e+t];return r}function pr(n,t){var r;return eo(n,function(n,e,u){return r=t(n,e,u), !r}),!!r}function _r(n,t,r){var e=0,u=null==n?e:n.length;if(typeof t=="number"&&t===t&&2147483647>=u){for(;e<u;){var i=e+u>>>1,o=n[i];null!==o&&!ju(o)&&(r?o<=t:o<t)?e=i+1:u=i}return u}return vr(n,t,Tu,r)}function vr(n,t,r,e){t=r(t);for(var u=0,i=null==n?0:n.length,o=t!==t,f=null===t,c=ju(t),a=t===T;u<i;){var l=Oi((u+i)/2),s=r(n[l]),h=s!==T,p=null===s,_=s===s,v=ju(s);(o?e||_:a?_&&(e||h):f?_&&h&&(e||!p):c?_&&h&&!p&&(e||!v):p||v?0:e?s<=t:s<t)?u=l+1:i=l}return Ui(i,4294967294)}function gr(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){ var o=n[r],f=t?t(o):o;if(!r||!au(f,c)){var c=f;i[u++]=0===o?0:o}}return i}function dr(n){return typeof n=="number"?n:ju(n)?F:+n}function yr(n){if(typeof n=="string")return n;if(of(n))return c(n,yr)+"";if(ju(n))return to?to.call(n):"";var t=n+"";return"0"==t&&1/n==-$?"-0":t}function br(n,t,r){var e=-1,u=o,i=n.length,c=true,a=[],l=a;if(r)c=false,u=f;else if(200<=i){if(u=t?null:lo(n))return U(u);c=false,u=O,l=new Nn}else l=t?[]:a;n:for(;++e<i;){var s=n[e],h=t?t(s):s,s=r||0!==s?s:0;if(c&&h===h){for(var p=l.length;p--;)if(l[p]===h)continue n; t&&l.push(h),a.push(s)}else u(l,h,r)||(l!==a&&l.push(h),a.push(s))}return a}function xr(n,t){return t=Sr(t,n),n=2>t.length?n:Et(n,hr(t,0,-1)),null==n||delete n[De(qe(t))]}function jr(n,t,r,e){for(var u=n.length,i=e?u:-1;(e?i--:++i<u)&&t(n[i],i,n););return r?hr(n,e?0:i,e?i+1:u):hr(n,e?i+1:0,e?u:i)}function wr(n,t){var r=n;return r instanceof Un&&(r=r.value()),l(t,function(n,t){return t.func.apply(t.thisArg,a([n],t.args))},r)}function mr(n,t,r){var e=n.length;if(2>e)return e?br(n[0]):[];for(var u=-1,i=Vu(e);++u<e;)for(var o=n[u],f=-1;++f<e;)f!=u&&(i[u]=yt(i[u]||o,n[f],t,r)); return br(wt(i,1),t,r)}function Ar(n,t,r){for(var e=-1,u=n.length,i=t.length,o={};++e<u;)r(o,n[e],e<i?t[e]:T);return o}function kr(n){return su(n)?n:[]}function Er(n){return typeof n=="function"?n:Tu}function Sr(n,t){return of(n)?n:Ie(n,t)?[n]:xo(Ou(n))}function Or(n,t,r){var e=n.length;return r=r===T?e:r,!t&&r>=e?n:hr(n,t,r)}function Ir(n,t){if(t)return n.slice();var r=n.length,r=vi?vi(r):new n.constructor(r);return n.copy(r),r}function Rr(n){var t=new n.constructor(n.byteLength);return new _i(t).set(new _i(n)), t}function zr(n,t){return new n.constructor(t?Rr(n.buffer):n.buffer,n.byteOffset,n.length)}function Wr(n,t){if(n!==t){var r=n!==T,e=null===n,u=n===n,i=ju(n),o=t!==T,f=null===t,c=t===t,a=ju(t);if(!f&&!a&&!i&&n>t||i&&o&&c&&!f&&!a||e&&o&&c||!r&&c||!u)return 1;if(!e&&!i&&!a&&n<t||a&&r&&u&&!e&&!i||f&&r&&u||!o&&u||!c)return-1}return 0}function Br(n,t,r,e){var u=-1,i=n.length,o=r.length,f=-1,c=t.length,a=Li(i-o,0),l=Vu(c+a);for(e=!e;++f<c;)l[f]=t[f];for(;++u<o;)(e||u<i)&&(l[r[u]]=n[u]);for(;a--;)l[f++]=n[u++]; return l}function Lr(n,t,r,e){var u=-1,i=n.length,o=-1,f=r.length,c=-1,a=t.length,l=Li(i-f,0),s=Vu(l+a);for(e=!e;++u<l;)s[u]=n[u];for(l=u;++c<a;)s[l+c]=t[c];for(;++o<f;)(e||u<i)&&(s[l+r[o]]=n[u++]);return s}function Ur(n,t){var r=-1,e=n.length;for(t||(t=Vu(e));++r<e;)t[r]=n[r];return t}function Cr(n,t,r,e){var u=!r;r||(r={});for(var i=-1,o=t.length;++i<o;){var f=t[i],c=e?e(r[f],n[f],f,r,n):T;c===T&&(c=n[f]),u?st(r,f,c):ot(r,f,c)}return r}function Dr(n,t){return Cr(n,ho(n),t)}function Mr(n,t){return Cr(n,po(n),t); }function Tr(n,r){return function(e,u){var i=of(e)?t:ct,o=r?r():{};return i(e,n,ye(u,2),o)}}function $r(n){return fr(function(t,r){var e=-1,u=r.length,i=1<u?r[u-1]:T,o=2<u?r[2]:T,i=3<n.length&&typeof i=="function"?(u--,i):T;for(o&&Oe(r[0],r[1],o)&&(i=3>u?T:i,u=1),t=Yu(t);++e<u;)(o=r[e])&&n(t,o,e,i);return t})}function Fr(n,t){return function(r,e){if(null==r)return r;if(!lu(r))return n(r,e);for(var u=r.length,i=t?u:-1,o=Yu(r);(t?i--:++i<u)&&false!==e(o[i],i,o););return r}}function Nr(n){return function(t,r,e){ var u=-1,i=Yu(t);e=e(t);for(var o=e.length;o--;){var f=e[n?o:++u];if(false===r(i[f],f,i))break}return t}}function Pr(n,t,r){function e(){return(this&&this!==Fn&&this instanceof e?i:n).apply(u?r:this,arguments)}var u=1&t,i=Vr(n);return e}function Zr(n){return function(t){t=Ou(t);var r=Rn.test(t)?M(t):T,e=r?r[0]:t.charAt(0);return t=r?Or(r,1).join(""):t.slice(1),e[n]()+t}}function qr(n){return function(t){return l(Du(Cu(t).replace(En,"")),n,"")}}function Vr(n){return function(){var t=arguments;switch(t.length){ case 0:return new n;case 1:return new n(t[0]);case 2:return new n(t[0],t[1]);case 3:return new n(t[0],t[1],t[2]);case 4:return new n(t[0],t[1],t[2],t[3]);case 5:return new n(t[0],t[1],t[2],t[3],t[4]);case 6:return new n(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new n(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=ro(n.prototype),t=n.apply(r,t);return gu(t)?t:r}}function Kr(t,r,e){function u(){for(var o=arguments.length,f=Vu(o),c=o,a=de(u);c--;)f[c]=arguments[c];return c=3>o&&f[0]!==a&&f[o-1]!==a?[]:L(f,a), o-=c.length,o<e?ue(t,r,Jr,u.placeholder,T,f,c,T,T,e-o):n(this&&this!==Fn&&this instanceof u?i:t,this,f)}var i=Vr(t);return u}function Gr(n){return function(t,r,e){var u=Yu(t);if(!lu(t)){var i=ye(r,3);t=zu(t),r=function(n){return i(u[n],n,u)}}return r=n(t,r,e),-1<r?u[i?t[r]:r]:T}}function Hr(n){return pe(function(t){var r=t.length,e=r,u=On.prototype.thru;for(n&&t.reverse();e--;){var i=t[e];if(typeof i!="function")throw new ni("Expected a function");if(u&&!o&&"wrapper"==ge(i))var o=new On([],true)}for(e=o?e:r;++e<r;)var i=t[e],u=ge(i),f="wrapper"==u?so(i):T,o=f&&Re(f[0])&&424==f[1]&&!f[4].length&&1==f[9]?o[ge(f[0])].apply(o,f[3]):1==i.length&&Re(i)?o[u]():o.thru(i); return function(){var n=arguments,e=n[0];if(o&&1==n.length&&of(e))return o.plant(e).value();for(var u=0,n=r?t[u].apply(this,n):e;++u<r;)n=t[u].call(this,n);return n}})}function Jr(n,t,r,e,u,i,o,f,c,a){function l(){for(var d=arguments.length,y=Vu(d),b=d;b--;)y[b]=arguments[b];if(_){var x,j=de(l),b=y.length;for(x=0;b--;)y[b]===j&&++x}if(e&&(y=Br(y,e,u,_)),i&&(y=Lr(y,i,o,_)),d-=x,_&&d<a)return j=L(y,j),ue(n,t,Jr,l.placeholder,r,y,j,f,c,a-d);if(j=h?r:this,b=p?j[n]:n,d=y.length,f){x=y.length;for(var w=Ui(f.length,x),m=Ur(y);w--;){ var A=f[w];y[w]=Se(A,x)?m[A]:T}}else v&&1<d&&y.reverse();return s&&c<d&&(y.length=c),this&&this!==Fn&&this instanceof l&&(b=g||Vr(b)),b.apply(j,y)}var s=128&t,h=1&t,p=2&t,_=24&t,v=512&t,g=p?T:Vr(n);return l}function Yr(n,t){return function(r,e){return Bt(r,n,t(e))}}function Qr(n,t){return function(r,e){var u;if(r===T&&e===T)return t;if(r!==T&&(u=r),e!==T){if(u===T)return e;typeof r=="string"||typeof e=="string"?(r=yr(r),e=yr(e)):(r=dr(r),e=dr(e)),u=n(r,e)}return u}}function Xr(t){return pe(function(r){ return r=c(r,E(ye())),fr(function(e){var u=this;return t(r,function(t){return n(t,u,e)})})})}function ne(n,t){t=t===T?" ":yr(t);var r=t.length;return 2>r?r?or(t,n):t:(r=or(t,Si(n/D(t))),Rn.test(t)?Or(M(r),0,n).join(""):r.slice(0,n))}function te(t,r,e,u){function i(){for(var r=-1,c=arguments.length,a=-1,l=u.length,s=Vu(l+c),h=this&&this!==Fn&&this instanceof i?f:t;++a<l;)s[a]=u[a];for(;c--;)s[a++]=arguments[++r];return n(h,o?e:this,s)}var o=1&r,f=Vr(t);return i}function re(n){return function(t,r,e){ e&&typeof e!="number"&&Oe(t,r,e)&&(r=e=T),t=mu(t),r===T?(r=t,t=0):r=mu(r),e=e===T?t<r?1:-1:mu(e);var u=-1;r=Li(Si((r-t)/(e||1)),0);for(var i=Vu(r);r--;)i[n?r:++u]=t,t+=e;return i}}function ee(n){return function(t,r){return typeof t=="string"&&typeof r=="string"||(t=Eu(t),r=Eu(r)),n(t,r)}}function ue(n,t,r,e,u,i,o,f,c,a){var l=8&t,s=l?o:T;o=l?T:o;var h=l?i:T;return i=l?T:i,t=(t|(l?32:64))&~(l?64:32),4&t||(t&=-4),u=[n,t,u,h,s,i,o,f,c,a],r=r.apply(T,u),Re(n)&&go(r,u),r.placeholder=e,Le(r,n,t)}function ie(n){ var t=Ju[n];return function(n,r){if(n=Eu(n),r=null==r?0:Ui(Au(r),292)){var e=(Ou(n)+"e").split("e"),e=t(e[0]+"e"+(+e[1]+r)),e=(Ou(e)+"e").split("e");return+(e[0]+"e"+(+e[1]-r))}return t(n)}}function oe(n){return function(t){var r=_o(t);return"[object Map]"==r?W(t):"[object Set]"==r?C(t):k(t,n(t))}}function fe(n,t,r,e,u,i,o,f){var c=2&t;if(!c&&typeof n!="function")throw new ni("Expected a function");var a=e?e.length:0;if(a||(t&=-97,e=u=T),o=o===T?o:Li(Au(o),0),f=f===T?f:Au(f),a-=u?u.length:0,64&t){ var l=e,s=u;e=u=T}var h=c?T:so(n);return i=[n,t,r,e,u,l,s,i,o,f],h&&(r=i[1],n=h[1],t=r|n,e=128==n&&8==r||128==n&&256==r&&i[7].length<=h[8]||384==n&&h[7].length<=h[8]&&8==r,131>t||e)&&(1&n&&(i[2]=h[2],t|=1&r?0:4),(r=h[3])&&(e=i[3],i[3]=e?Br(e,r,h[4]):r,i[4]=e?L(i[3],"__lodash_placeholder__"):h[4]),(r=h[5])&&(e=i[5],i[5]=e?Lr(e,r,h[6]):r,i[6]=e?L(i[5],"__lodash_placeholder__"):h[6]),(r=h[7])&&(i[7]=r),128&n&&(i[8]=null==i[8]?h[8]:Ui(i[8],h[8])),null==i[9]&&(i[9]=h[9]),i[0]=h[0],i[1]=t),n=i[0],t=i[1], r=i[2],e=i[3],u=i[4],f=i[9]=i[9]===T?c?0:n.length:Li(i[9]-a,0),!f&&24&t&&(t&=-25),Le((h?fo:go)(t&&1!=t?8==t||16==t?Kr(n,t,f):32!=t&&33!=t||u.length?Jr.apply(T,i):te(n,t,r,e):Pr(n,t,r),i),n,t)}function ce(n,t,r,e){return n===T||au(n,ri[r])&&!ii.call(e,r)?t:n}function ae(n,t,r,e,u,i){return gu(n)&&gu(t)&&(i.set(t,n),Yt(n,t,T,ae,i),i.delete(t)),n}function le(n){return bu(n)?T:n}function se(n,t,r,e,u,i){var o=1&r,f=n.length,c=t.length;if(f!=c&&!(o&&c>f))return false;if((c=i.get(n))&&i.get(t))return c==t;var c=-1,a=true,l=2&r?new Nn:T; for(i.set(n,t),i.set(t,n);++c<f;){var s=n[c],p=t[c];if(e)var _=o?e(p,s,c,t,n,i):e(s,p,c,n,t,i);if(_!==T){if(_)continue;a=false;break}if(l){if(!h(t,function(n,t){if(!O(l,t)&&(s===n||u(s,n,r,e,i)))return l.push(t)})){a=false;break}}else if(s!==p&&!u(s,p,r,e,i)){a=false;break}}return i.delete(n),i.delete(t),a}function he(n,t,r,e,u,i,o){switch(r){case"[object DataView]":if(n.byteLength!=t.byteLength||n.byteOffset!=t.byteOffset)break;n=n.buffer,t=t.buffer;case"[object ArrayBuffer]":if(n.byteLength!=t.byteLength||!i(new _i(n),new _i(t)))break; return true;case"[object Boolean]":case"[object Date]":case"[object Number]":return au(+n,+t);case"[object Error]":return n.name==t.name&&n.message==t.message;case"[object RegExp]":case"[object String]":return n==t+"";case"[object Map]":var f=W;case"[object Set]":if(f||(f=U),n.size!=t.size&&!(1&e))break;return(r=o.get(n))?r==t:(e|=2,o.set(n,t),t=se(f(n),f(t),e,u,i,o),o.delete(n),t);case"[object Symbol]":if(no)return no.call(n)==no.call(t)}return false}function pe(n){return bo(Be(n,T,Pe),n+"")}function _e(n){ return St(n,zu,ho)}function ve(n){return St(n,Wu,po)}function ge(n){for(var t=n.name+"",r=Ki[t],e=ii.call(Ki,t)?r.length:0;e--;){var u=r[e],i=u.func;if(null==i||i==n)return u.name}return t}function de(n){return(ii.call(An,"placeholder")?An:n).placeholder}function ye(){var n=An.iteratee||$u,n=n===$u?qt:n;return arguments.length?n(arguments[0],arguments[1]):n}function be(n,t){var r=n.__data__,e=typeof t;return("string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==t:null===t)?r[typeof t=="string"?"string":"hash"]:r.map; }function xe(n){for(var t=zu(n),r=t.length;r--;){var e=t[r],u=n[e];t[r]=[e,u,u===u&&!gu(u)]}return t}function je(n,t){var r=null==n?T:n[t];return Ft(r)?r:T}function we(n,t,r){t=Sr(t,n);for(var e=-1,u=t.length,i=false;++e<u;){var o=De(t[e]);if(!(i=null!=n&&r(n,o)))break;n=n[o]}return i||++e!=u?i:(u=null==n?0:n.length,!!u&&vu(u)&&Se(o,u)&&(of(n)||uf(n)))}function me(n){var t=n.length,r=new n.constructor(t);return t&&"string"==typeof n[0]&&ii.call(n,"index")&&(r.index=n.index,r.input=n.input),r}function Ae(n){ return typeof n.constructor!="function"||ze(n)?{}:ro(gi(n))}function ke(n,t,r){var e=n.constructor;switch(t){case"[object ArrayBuffer]":return Rr(n);case"[object Boolean]":case"[object Date]":return new e(+n);case"[object DataView]":return t=r?Rr(n.buffer):n.buffer,new n.constructor(t,n.byteOffset,n.byteLength);case"[object Float32Array]":case"[object Float64Array]":case"[object Int8Array]":case"[object Int16Array]":case"[object Int32Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]": case"[object Uint16Array]":case"[object Uint32Array]":return zr(n,r);case"[object Map]":return new e;case"[object Number]":case"[object String]":return new e(n);case"[object RegExp]":return t=new n.constructor(n.source,_n.exec(n)),t.lastIndex=n.lastIndex,t;case"[object Set]":return new e;case"[object Symbol]":return no?Yu(no.call(n)):{}}}function Ee(n){return of(n)||uf(n)||!!(xi&&n&&n[xi])}function Se(n,t){var r=typeof n;return t=null==t?9007199254740991:t,!!t&&("number"==r||"symbol"!=r&&bn.test(n))&&-1<n&&0==n%1&&n<t; }function Oe(n,t,r){if(!gu(r))return false;var e=typeof t;return!!("number"==e?lu(r)&&Se(t,r.length):"string"==e&&t in r)&&au(r[t],n)}function Ie(n,t){if(of(n))return false;var r=typeof n;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=n&&!ju(n))||(nn.test(n)||!X.test(n)||null!=t&&n in Yu(t))}function Re(n){var t=ge(n),r=An[t];return typeof r=="function"&&t in Un.prototype&&(n===r||(t=so(r),!!t&&n===t[0]))}function ze(n){var t=n&&n.constructor;return n===(typeof t=="function"&&t.prototype||ri)}function We(n,t){ return function(r){return null!=r&&(r[n]===t&&(t!==T||n in Yu(r)))}}function Be(t,r,e){return r=Li(r===T?t.length-1:r,0),function(){for(var u=arguments,i=-1,o=Li(u.length-r,0),f=Vu(o);++i<o;)f[i]=u[r+i];for(i=-1,o=Vu(r+1);++i<r;)o[i]=u[i];return o[r]=e(f),n(t,this,o)}}function Le(n,t,r){var e=t+"";t=bo;var u,i=Te;return u=(u=e.match(an))?u[1].split(ln):[],r=i(u,r),(i=r.length)&&(u=i-1,r[u]=(1<i?"& ":"")+r[u],r=r.join(2<i?", ":" "),e=e.replace(cn,"{\n/* [wrapped with "+r+"] */\n")),t(n,e)}function Ue(n){ var t=0,r=0;return function(){var e=Ci(),u=16-(e-r);if(r=e,0<u){if(800<=++t)return arguments[0]}else t=0;return n.apply(T,arguments)}}function Ce(n,t){var r=-1,e=n.length,u=e-1;for(t=t===T?e:t;++r<t;){var e=ir(r,u),i=n[e];n[e]=n[r],n[r]=i}return n.length=t,n}function De(n){if(typeof n=="string"||ju(n))return n;var t=n+"";return"0"==t&&1/n==-$?"-0":t}function Me(n){if(null!=n){try{return ui.call(n)}catch(n){}return n+""}return""}function Te(n,t){return r(N,function(r){var e="_."+r[0];t&r[1]&&!o(n,e)&&n.push(e); }),n.sort()}function $e(n){if(n instanceof Un)return n.clone();var t=new On(n.__wrapped__,n.__chain__);return t.__actions__=Ur(n.__actions__),t.__index__=n.__index__,t.__values__=n.__values__,t}function Fe(n,t,r){var e=null==n?0:n.length;return e?(r=null==r?0:Au(r),0>r&&(r=Li(e+r,0)),_(n,ye(t,3),r)):-1}function Ne(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=e-1;return r!==T&&(u=Au(r),u=0>r?Li(e+u,0):Ui(u,e-1)),_(n,ye(t,3),u,true)}function Pe(n){return(null==n?0:n.length)?wt(n,1):[]}function Ze(n){ return n&&n.length?n[0]:T}function qe(n){var t=null==n?0:n.length;return t?n[t-1]:T}function Ve(n,t){return n&&n.length&&t&&t.length?er(n,t):n}function Ke(n){return null==n?n:Ti.call(n)}function Ge(n){if(!n||!n.length)return[];var t=0;return n=i(n,function(n){if(su(n))return t=Li(n.length,t),true}),A(t,function(t){return c(n,b(t))})}function He(t,r){if(!t||!t.length)return[];var e=Ge(t);return null==r?e:c(e,function(t){return n(r,T,t)})}function Je(n){return n=An(n),n.__chain__=true,n}function Ye(n,t){ return t(n)}function Qe(){return this}function Xe(n,t){return(of(n)?r:eo)(n,ye(t,3))}function nu(n,t){return(of(n)?e:uo)(n,ye(t,3))}function tu(n,t){return(of(n)?c:Gt)(n,ye(t,3))}function ru(n,t,r){return t=r?T:t,t=n&&null==t?n.length:t,fe(n,128,T,T,T,T,t)}function eu(n,t){var r;if(typeof t!="function")throw new ni("Expected a function");return n=Au(n),function(){return 0<--n&&(r=t.apply(this,arguments)),1>=n&&(t=T),r}}function uu(n,t,r){return t=r?T:t,n=fe(n,8,T,T,T,T,T,t),n.placeholder=uu.placeholder, n}function iu(n,t,r){return t=r?T:t,n=fe(n,16,T,T,T,T,T,t),n.placeholder=iu.placeholder,n}function ou(n,t,r){function e(t){var r=c,e=a;return c=a=T,_=t,s=n.apply(e,r)}function u(n){var r=n-p;return n-=_,p===T||r>=t||0>r||g&&n>=l}function i(){var n=Ko();if(u(n))return o(n);var r,e=yo;r=n-_,n=t-(n-p),r=g?Ui(n,l-r):n,h=e(i,r)}function o(n){return h=T,d&&c?e(n):(c=a=T,s)}function f(){var n=Ko(),r=u(n);if(c=arguments,a=this,p=n,r){if(h===T)return _=n=p,h=yo(i,t),v?e(n):s;if(g)return h=yo(i,t),e(p)}return h===T&&(h=yo(i,t)), s}var c,a,l,s,h,p,_=0,v=false,g=false,d=true;if(typeof n!="function")throw new ni("Expected a function");return t=Eu(t)||0,gu(r)&&(v=!!r.leading,l=(g="maxWait"in r)?Li(Eu(r.maxWait)||0,t):l,d="trailing"in r?!!r.trailing:d),f.cancel=function(){h!==T&&ao(h),_=0,c=p=a=h=T},f.flush=function(){return h===T?s:o(Ko())},f}function fu(n,t){function r(){var e=arguments,u=t?t.apply(this,e):e[0],i=r.cache;return i.has(u)?i.get(u):(e=n.apply(this,e),r.cache=i.set(u,e)||i,e)}if(typeof n!="function"||null!=t&&typeof t!="function")throw new ni("Expected a function"); return r.cache=new(fu.Cache||$n),r}function cu(n){if(typeof n!="function")throw new ni("Expected a function");return function(){var t=arguments;switch(t.length){case 0:return!n.call(this);case 1:return!n.call(this,t[0]);case 2:return!n.call(this,t[0],t[1]);case 3:return!n.call(this,t[0],t[1],t[2])}return!n.apply(this,t)}}function au(n,t){return n===t||n!==n&&t!==t}function lu(n){return null!=n&&vu(n.length)&&!pu(n)}function su(n){return du(n)&&lu(n)}function hu(n){if(!du(n))return false;var t=Ot(n);return"[object Error]"==t||"[object DOMException]"==t||typeof n.message=="string"&&typeof n.name=="string"&&!bu(n); }function pu(n){return!!gu(n)&&(n=Ot(n),"[object Function]"==n||"[object GeneratorFunction]"==n||"[object AsyncFunction]"==n||"[object Proxy]"==n)}function _u(n){return typeof n=="number"&&n==Au(n)}function vu(n){return typeof n=="number"&&-1<n&&0==n%1&&9007199254740991>=n}function gu(n){var t=typeof n;return null!=n&&("object"==t||"function"==t)}function du(n){return null!=n&&typeof n=="object"}function yu(n){return typeof n=="number"||du(n)&&"[object Number]"==Ot(n)}function bu(n){return!(!du(n)||"[object Object]"!=Ot(n))&&(n=gi(n), null===n||(n=ii.call(n,"constructor")&&n.constructor,typeof n=="function"&&n instanceof n&&ui.call(n)==ai))}function xu(n){return typeof n=="string"||!of(n)&&du(n)&&"[object String]"==Ot(n)}function ju(n){return typeof n=="symbol"||du(n)&&"[object Symbol]"==Ot(n)}function wu(n){if(!n)return[];if(lu(n))return xu(n)?M(n):Ur(n);if(ji&&n[ji]){n=n[ji]();for(var t,r=[];!(t=n.next()).done;)r.push(t.value);return r}return t=_o(n),("[object Map]"==t?W:"[object Set]"==t?U:Lu)(n)}function mu(n){return n?(n=Eu(n), n===$||n===-$?1.7976931348623157e308*(0>n?-1:1):n===n?n:0):0===n?n:0}function Au(n){n=mu(n);var t=n%1;return n===n?t?n-t:n:0}function ku(n){return n?pt(Au(n),0,4294967295):0}function Eu(n){if(typeof n=="number")return n;if(ju(n))return F;if(gu(n)&&(n=typeof n.valueOf=="function"?n.valueOf():n,n=gu(n)?n+"":n),typeof n!="string")return 0===n?n:+n;n=n.replace(un,"");var t=gn.test(n);return t||yn.test(n)?Mn(n.slice(2),t?2:8):vn.test(n)?F:+n}function Su(n){return Cr(n,Wu(n))}function Ou(n){return null==n?"":yr(n); }function Iu(n,t,r){return n=null==n?T:Et(n,t),n===T?r:n}function Ru(n,t){return null!=n&&we(n,t,zt)}function zu(n){return lu(n)?qn(n):Vt(n)}function Wu(n){if(lu(n))n=qn(n,true);else if(gu(n)){var t,r=ze(n),e=[];for(t in n)("constructor"!=t||!r&&ii.call(n,t))&&e.push(t);n=e}else{if(t=[],null!=n)for(r in Yu(n))t.push(r);n=t}return n}function Bu(n,t){if(null==n)return{};var r=c(ve(n),function(n){return[n]});return t=ye(t),tr(n,r,function(n,r){return t(n,r[0])})}function Lu(n){return null==n?[]:S(n,zu(n)); }function Uu(n){return Tf(Ou(n).toLowerCase())}function Cu(n){return(n=Ou(n))&&n.replace(xn,Xn).replace(Sn,"")}function Du(n,t,r){return n=Ou(n),t=r?T:t,t===T?zn.test(n)?n.match(In)||[]:n.match(sn)||[]:n.match(t)||[]}function Mu(n){return function(){return n}}function Tu(n){return n}function $u(n){return qt(typeof n=="function"?n:_t(n,1))}function Fu(n,t,e){var u=zu(t),i=kt(t,u);null!=e||gu(t)&&(i.length||!u.length)||(e=t,t=n,n=this,i=kt(t,zu(t)));var o=!(gu(e)&&"chain"in e&&!e.chain),f=pu(n);return r(i,function(r){ var e=t[r];n[r]=e,f&&(n.prototype[r]=function(){var t=this.__chain__;if(o||t){var r=n(this.__wrapped__);return(r.__actions__=Ur(this.__actions__)).push({func:e,args:arguments,thisArg:n}),r.__chain__=t,r}return e.apply(n,a([this.value()],arguments))})}),n}function Nu(){}function Pu(n){return Ie(n)?b(De(n)):rr(n)}function Zu(){return[]}function qu(){return false}mn=null==mn?Fn:rt.defaults(Fn.Object(),mn,rt.pick(Fn,Wn));var Vu=mn.Array,Ku=mn.Date,Gu=mn.Error,Hu=mn.Function,Ju=mn.Math,Yu=mn.Object,Qu=mn.RegExp,Xu=mn.String,ni=mn.TypeError,ti=Vu.prototype,ri=Yu.prototype,ei=mn["__core-js_shared__"],ui=Hu.prototype.toString,ii=ri.hasOwnProperty,oi=0,fi=function(){ var n=/[^.]+$/.exec(ei&&ei.keys&&ei.keys.IE_PROTO||"");return n?"Symbol(src)_1."+n:""}(),ci=ri.toString,ai=ui.call(Yu),li=Fn._,si=Qu("^"+ui.call(ii).replace(rn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),hi=Zn?mn.Buffer:T,pi=mn.Symbol,_i=mn.Uint8Array,vi=hi?hi.f:T,gi=B(Yu.getPrototypeOf,Yu),di=Yu.create,yi=ri.propertyIsEnumerable,bi=ti.splice,xi=pi?pi.isConcatSpreadable:T,ji=pi?pi.iterator:T,wi=pi?pi.toStringTag:T,mi=function(){try{var n=je(Yu,"defineProperty"); return n({},"",{}),n}catch(n){}}(),Ai=mn.clearTimeout!==Fn.clearTimeout&&mn.clearTimeout,ki=Ku&&Ku.now!==Fn.Date.now&&Ku.now,Ei=mn.setTimeout!==Fn.setTimeout&&mn.setTimeout,Si=Ju.ceil,Oi=Ju.floor,Ii=Yu.getOwnPropertySymbols,Ri=hi?hi.isBuffer:T,zi=mn.isFinite,Wi=ti.join,Bi=B(Yu.keys,Yu),Li=Ju.max,Ui=Ju.min,Ci=Ku.now,Di=mn.parseInt,Mi=Ju.random,Ti=ti.reverse,$i=je(mn,"DataView"),Fi=je(mn,"Map"),Ni=je(mn,"Promise"),Pi=je(mn,"Set"),Zi=je(mn,"WeakMap"),qi=je(Yu,"create"),Vi=Zi&&new Zi,Ki={},Gi=Me($i),Hi=Me(Fi),Ji=Me(Ni),Yi=Me(Pi),Qi=Me(Zi),Xi=pi?pi.prototype:T,no=Xi?Xi.valueOf:T,to=Xi?Xi.toString:T,ro=function(){ function n(){}return function(t){return gu(t)?di?di(t):(n.prototype=t,t=new n,n.prototype=T,t):{}}}();An.templateSettings={escape:J,evaluate:Y,interpolate:Q,variable:"",imports:{_:An}},An.prototype=kn.prototype,An.prototype.constructor=An,On.prototype=ro(kn.prototype),On.prototype.constructor=On,Un.prototype=ro(kn.prototype),Un.prototype.constructor=Un,Cn.prototype.clear=function(){this.__data__=qi?qi(null):{},this.size=0},Cn.prototype.delete=function(n){return n=this.has(n)&&delete this.__data__[n], this.size-=n?1:0,n},Cn.prototype.get=function(n){var t=this.__data__;return qi?(n=t[n],"__lodash_hash_undefined__"===n?T:n):ii.call(t,n)?t[n]:T},Cn.prototype.has=function(n){var t=this.__data__;return qi?t[n]!==T:ii.call(t,n)},Cn.prototype.set=function(n,t){var r=this.__data__;return this.size+=this.has(n)?0:1,r[n]=qi&&t===T?"__lodash_hash_undefined__":t,this},Tn.prototype.clear=function(){this.__data__=[],this.size=0},Tn.prototype.delete=function(n){var t=this.__data__;return n=ft(t,n),!(0>n)&&(n==t.length-1?t.pop():bi.call(t,n,1), --this.size,true)},Tn.prototype.get=function(n){var t=this.__data__;return n=ft(t,n),0>n?T:t[n][1]},Tn.prototype.has=function(n){return-1<ft(this.__data__,n)},Tn.prototype.set=function(n,t){var r=this.__data__,e=ft(r,n);return 0>e?(++this.size,r.push([n,t])):r[e][1]=t,this},$n.prototype.clear=function(){this.size=0,this.__data__={hash:new Cn,map:new(Fi||Tn),string:new Cn}},$n.prototype.delete=function(n){return n=be(this,n).delete(n),this.size-=n?1:0,n},$n.prototype.get=function(n){return be(this,n).get(n); },$n.prototype.has=function(n){return be(this,n).has(n)},$n.prototype.set=function(n,t){var r=be(this,n),e=r.size;return r.set(n,t),this.size+=r.size==e?0:1,this},Nn.prototype.add=Nn.prototype.push=function(n){return this.__data__.set(n,"__lodash_hash_undefined__"),this},Nn.prototype.has=function(n){return this.__data__.has(n)},Pn.prototype.clear=function(){this.__data__=new Tn,this.size=0},Pn.prototype.delete=function(n){var t=this.__data__;return n=t.delete(n),this.size=t.size,n},Pn.prototype.get=function(n){ return this.__data__.get(n)},Pn.prototype.has=function(n){return this.__data__.has(n)},Pn.prototype.set=function(n,t){var r=this.__data__;if(r instanceof Tn){var e=r.__data__;if(!Fi||199>e.length)return e.push([n,t]),this.size=++r.size,this;r=this.__data__=new $n(e)}return r.set(n,t),this.size=r.size,this};var eo=Fr(mt),uo=Fr(At,true),io=Nr(),oo=Nr(true),fo=Vi?function(n,t){return Vi.set(n,t),n}:Tu,co=mi?function(n,t){return mi(n,"toString",{configurable:true,enumerable:false,value:Mu(t),writable:true})}:Tu,ao=Ai||function(n){ return Fn.clearTimeout(n)},lo=Pi&&1/U(new Pi([,-0]))[1]==$?function(n){return new Pi(n)}:Nu,so=Vi?function(n){return Vi.get(n)}:Nu,ho=Ii?function(n){return null==n?[]:(n=Yu(n),i(Ii(n),function(t){return yi.call(n,t)}))}:Zu,po=Ii?function(n){for(var t=[];n;)a(t,ho(n)),n=gi(n);return t}:Zu,_o=Ot;($i&&"[object DataView]"!=_o(new $i(new ArrayBuffer(1)))||Fi&&"[object Map]"!=_o(new Fi)||Ni&&"[object Promise]"!=_o(Ni.resolve())||Pi&&"[object Set]"!=_o(new Pi)||Zi&&"[object WeakMap]"!=_o(new Zi))&&(_o=function(n){ var t=Ot(n);if(n=(n="[object Object]"==t?n.constructor:T)?Me(n):"")switch(n){case Gi:return"[object DataView]";case Hi:return"[object Map]";case Ji:return"[object Promise]";case Yi:return"[object Set]";case Qi:return"[object WeakMap]"}return t});var vo=ei?pu:qu,go=Ue(fo),yo=Ei||function(n,t){return Fn.setTimeout(n,t)},bo=Ue(co),xo=function(n){n=fu(n,function(n){return 500===t.size&&t.clear(),n});var t=n.cache;return n}(function(n){var t=[];return 46===n.charCodeAt(0)&&t.push(""),n.replace(tn,function(n,r,e,u){ t.push(e?u.replace(hn,"$1"):r||n)}),t}),jo=fr(function(n,t){return su(n)?yt(n,wt(t,1,su,true)):[]}),wo=fr(function(n,t){var r=qe(t);return su(r)&&(r=T),su(n)?yt(n,wt(t,1,su,true),ye(r,2)):[]}),mo=fr(function(n,t){var r=qe(t);return su(r)&&(r=T),su(n)?yt(n,wt(t,1,su,true),T,r):[]}),Ao=fr(function(n){var t=c(n,kr);return t.length&&t[0]===n[0]?Wt(t):[]}),ko=fr(function(n){var t=qe(n),r=c(n,kr);return t===qe(r)?t=T:r.pop(),r.length&&r[0]===n[0]?Wt(r,ye(t,2)):[]}),Eo=fr(function(n){var t=qe(n),r=c(n,kr);return(t=typeof t=="function"?t:T)&&r.pop(), r.length&&r[0]===n[0]?Wt(r,T,t):[]}),So=fr(Ve),Oo=pe(function(n,t){var r=null==n?0:n.length,e=ht(n,t);return ur(n,c(t,function(n){return Se(n,r)?+n:n}).sort(Wr)),e}),Io=fr(function(n){return br(wt(n,1,su,true))}),Ro=fr(function(n){var t=qe(n);return su(t)&&(t=T),br(wt(n,1,su,true),ye(t,2))}),zo=fr(function(n){var t=qe(n),t=typeof t=="function"?t:T;return br(wt(n,1,su,true),T,t)}),Wo=fr(function(n,t){return su(n)?yt(n,t):[]}),Bo=fr(function(n){return mr(i(n,su))}),Lo=fr(function(n){var t=qe(n);return su(t)&&(t=T), mr(i(n,su),ye(t,2))}),Uo=fr(function(n){var t=qe(n),t=typeof t=="function"?t:T;return mr(i(n,su),T,t)}),Co=fr(Ge),Do=fr(function(n){var t=n.length,t=1<t?n[t-1]:T,t=typeof t=="function"?(n.pop(),t):T;return He(n,t)}),Mo=pe(function(n){function t(t){return ht(t,n)}var r=n.length,e=r?n[0]:0,u=this.__wrapped__;return!(1<r||this.__actions__.length)&&u instanceof Un&&Se(e)?(u=u.slice(e,+e+(r?1:0)),u.__actions__.push({func:Ye,args:[t],thisArg:T}),new On(u,this.__chain__).thru(function(n){return r&&!n.length&&n.push(T), n})):this.thru(t)}),To=Tr(function(n,t,r){ii.call(n,r)?++n[r]:st(n,r,1)}),$o=Gr(Fe),Fo=Gr(Ne),No=Tr(function(n,t,r){ii.call(n,r)?n[r].push(t):st(n,r,[t])}),Po=fr(function(t,r,e){var u=-1,i=typeof r=="function",o=lu(t)?Vu(t.length):[];return eo(t,function(t){o[++u]=i?n(r,t,e):Lt(t,r,e)}),o}),Zo=Tr(function(n,t,r){st(n,r,t)}),qo=Tr(function(n,t,r){n[r?0:1].push(t)},function(){return[[],[]]}),Vo=fr(function(n,t){if(null==n)return[];var r=t.length;return 1<r&&Oe(n,t[0],t[1])?t=[]:2<r&&Oe(t[0],t[1],t[2])&&(t=[t[0]]), Xt(n,wt(t,1),[])}),Ko=ki||function(){return Fn.Date.now()},Go=fr(function(n,t,r){var e=1;if(r.length)var u=L(r,de(Go)),e=32|e;return fe(n,e,t,r,u)}),Ho=fr(function(n,t,r){var e=3;if(r.length)var u=L(r,de(Ho)),e=32|e;return fe(t,e,n,r,u)}),Jo=fr(function(n,t){return dt(n,1,t)}),Yo=fr(function(n,t,r){return dt(n,Eu(t)||0,r)});fu.Cache=$n;var Qo=fr(function(t,r){r=1==r.length&&of(r[0])?c(r[0],E(ye())):c(wt(r,1),E(ye()));var e=r.length;return fr(function(u){for(var i=-1,o=Ui(u.length,e);++i<o;)u[i]=r[i].call(this,u[i]); return n(t,this,u)})}),Xo=fr(function(n,t){return fe(n,32,T,t,L(t,de(Xo)))}),nf=fr(function(n,t){return fe(n,64,T,t,L(t,de(nf)))}),tf=pe(function(n,t){return fe(n,256,T,T,T,t)}),rf=ee(It),ef=ee(function(n,t){return n>=t}),uf=Ut(function(){return arguments}())?Ut:function(n){return du(n)&&ii.call(n,"callee")&&!yi.call(n,"callee")},of=Vu.isArray,ff=Vn?E(Vn):Ct,cf=Ri||qu,af=Kn?E(Kn):Dt,lf=Gn?E(Gn):Tt,sf=Hn?E(Hn):Nt,hf=Jn?E(Jn):Pt,pf=Yn?E(Yn):Zt,_f=ee(Kt),vf=ee(function(n,t){return n<=t}),gf=$r(function(n,t){ if(ze(t)||lu(t))Cr(t,zu(t),n);else for(var r in t)ii.call(t,r)&&ot(n,r,t[r])}),df=$r(function(n,t){Cr(t,Wu(t),n)}),yf=$r(function(n,t,r,e){Cr(t,Wu(t),n,e)}),bf=$r(function(n,t,r,e){Cr(t,zu(t),n,e)}),xf=pe(ht),jf=fr(function(n,t){n=Yu(n);var r=-1,e=t.length,u=2<e?t[2]:T;for(u&&Oe(t[0],t[1],u)&&(e=1);++r<e;)for(var u=t[r],i=Wu(u),o=-1,f=i.length;++o<f;){var c=i[o],a=n[c];(a===T||au(a,ri[c])&&!ii.call(n,c))&&(n[c]=u[c])}return n}),wf=fr(function(t){return t.push(T,ae),n(Sf,T,t)}),mf=Yr(function(n,t,r){ null!=t&&typeof t.toString!="function"&&(t=ci.call(t)),n[t]=r},Mu(Tu)),Af=Yr(function(n,t,r){null!=t&&typeof t.toString!="function"&&(t=ci.call(t)),ii.call(n,t)?n[t].push(r):n[t]=[r]},ye),kf=fr(Lt),Ef=$r(function(n,t,r){Yt(n,t,r)}),Sf=$r(function(n,t,r,e){Yt(n,t,r,e)}),Of=pe(function(n,t){var r={};if(null==n)return r;var e=false;t=c(t,function(t){return t=Sr(t,n),e||(e=1<t.length),t}),Cr(n,ve(n),r),e&&(r=_t(r,7,le));for(var u=t.length;u--;)xr(r,t[u]);return r}),If=pe(function(n,t){return null==n?{}:nr(n,t); }),Rf=oe(zu),zf=oe(Wu),Wf=qr(function(n,t,r){return t=t.toLowerCase(),n+(r?Uu(t):t)}),Bf=qr(function(n,t,r){return n+(r?"-":"")+t.toLowerCase()}),Lf=qr(function(n,t,r){return n+(r?" ":"")+t.toLowerCase()}),Uf=Zr("toLowerCase"),Cf=qr(function(n,t,r){return n+(r?"_":"")+t.toLowerCase()}),Df=qr(function(n,t,r){return n+(r?" ":"")+Tf(t)}),Mf=qr(function(n,t,r){return n+(r?" ":"")+t.toUpperCase()}),Tf=Zr("toUpperCase"),$f=fr(function(t,r){try{return n(t,T,r)}catch(n){return hu(n)?n:new Gu(n)}}),Ff=pe(function(n,t){ return r(t,function(t){t=De(t),st(n,t,Go(n[t],n))}),n}),Nf=Hr(),Pf=Hr(true),Zf=fr(function(n,t){return function(r){return Lt(r,n,t)}}),qf=fr(function(n,t){return function(r){return Lt(n,r,t)}}),Vf=Xr(c),Kf=Xr(u),Gf=Xr(h),Hf=re(),Jf=re(true),Yf=Qr(function(n,t){return n+t},0),Qf=ie("ceil"),Xf=Qr(function(n,t){return n/t},1),nc=ie("floor"),tc=Qr(function(n,t){return n*t},1),rc=ie("round"),ec=Qr(function(n,t){return n-t},0);return An.after=function(n,t){if(typeof t!="function")throw new ni("Expected a function"); return n=Au(n),function(){if(1>--n)return t.apply(this,arguments)}},An.ary=ru,An.assign=gf,An.assignIn=df,An.assignInWith=yf,An.assignWith=bf,An.at=xf,An.before=eu,An.bind=Go,An.bindAll=Ff,An.bindKey=Ho,An.castArray=function(){if(!arguments.length)return[];var n=arguments[0];return of(n)?n:[n]},An.chain=Je,An.chunk=function(n,t,r){if(t=(r?Oe(n,t,r):t===T)?1:Li(Au(t),0),r=null==n?0:n.length,!r||1>t)return[];for(var e=0,u=0,i=Vu(Si(r/t));e<r;)i[u++]=hr(n,e,e+=t);return i},An.compact=function(n){for(var t=-1,r=null==n?0:n.length,e=0,u=[];++t<r;){ var i=n[t];i&&(u[e++]=i)}return u},An.concat=function(){var n=arguments.length;if(!n)return[];for(var t=Vu(n-1),r=arguments[0];n--;)t[n-1]=arguments[n];return a(of(r)?Ur(r):[r],wt(t,1))},An.cond=function(t){var r=null==t?0:t.length,e=ye();return t=r?c(t,function(n){if("function"!=typeof n[1])throw new ni("Expected a function");return[e(n[0]),n[1]]}):[],fr(function(e){for(var u=-1;++u<r;){var i=t[u];if(n(i[0],this,e))return n(i[1],this,e)}})},An.conforms=function(n){return vt(_t(n,1))},An.constant=Mu, An.countBy=To,An.create=function(n,t){var r=ro(n);return null==t?r:at(r,t)},An.curry=uu,An.curryRight=iu,An.debounce=ou,An.defaults=jf,An.defaultsDeep=wf,An.defer=Jo,An.delay=Yo,An.difference=jo,An.differenceBy=wo,An.differenceWith=mo,An.drop=function(n,t,r){var e=null==n?0:n.length;return e?(t=r||t===T?1:Au(t),hr(n,0>t?0:t,e)):[]},An.dropRight=function(n,t,r){var e=null==n?0:n.length;return e?(t=r||t===T?1:Au(t),t=e-t,hr(n,0,0>t?0:t)):[]},An.dropRightWhile=function(n,t){return n&&n.length?jr(n,ye(t,3),true,true):[]; },An.dropWhile=function(n,t){return n&&n.length?jr(n,ye(t,3),true):[]},An.fill=function(n,t,r,e){var u=null==n?0:n.length;if(!u)return[];for(r&&typeof r!="number"&&Oe(n,t,r)&&(r=0,e=u),u=n.length,r=Au(r),0>r&&(r=-r>u?0:u+r),e=e===T||e>u?u:Au(e),0>e&&(e+=u),e=r>e?0:ku(e);r<e;)n[r++]=t;return n},An.filter=function(n,t){return(of(n)?i:jt)(n,ye(t,3))},An.flatMap=function(n,t){return wt(tu(n,t),1)},An.flatMapDeep=function(n,t){return wt(tu(n,t),$)},An.flatMapDepth=function(n,t,r){return r=r===T?1:Au(r), wt(tu(n,t),r)},An.flatten=Pe,An.flattenDeep=function(n){return(null==n?0:n.length)?wt(n,$):[]},An.flattenDepth=function(n,t){return null!=n&&n.length?(t=t===T?1:Au(t),wt(n,t)):[]},An.flip=function(n){return fe(n,512)},An.flow=Nf,An.flowRight=Pf,An.fromPairs=function(n){for(var t=-1,r=null==n?0:n.length,e={};++t<r;){var u=n[t];e[u[0]]=u[1]}return e},An.functions=function(n){return null==n?[]:kt(n,zu(n))},An.functionsIn=function(n){return null==n?[]:kt(n,Wu(n))},An.groupBy=No,An.initial=function(n){ return(null==n?0:n.length)?hr(n,0,-1):[]},An.intersection=Ao,An.intersectionBy=ko,An.intersectionWith=Eo,An.invert=mf,An.invertBy=Af,An.invokeMap=Po,An.iteratee=$u,An.keyBy=Zo,An.keys=zu,An.keysIn=Wu,An.map=tu,An.mapKeys=function(n,t){var r={};return t=ye(t,3),mt(n,function(n,e,u){st(r,t(n,e,u),n)}),r},An.mapValues=function(n,t){var r={};return t=ye(t,3),mt(n,function(n,e,u){st(r,e,t(n,e,u))}),r},An.matches=function(n){return Ht(_t(n,1))},An.matchesProperty=function(n,t){return Jt(n,_t(t,1))},An.memoize=fu, An.merge=Ef,An.mergeWith=Sf,An.method=Zf,An.methodOf=qf,An.mixin=Fu,An.negate=cu,An.nthArg=function(n){return n=Au(n),fr(function(t){return Qt(t,n)})},An.omit=Of,An.omitBy=function(n,t){return Bu(n,cu(ye(t)))},An.once=function(n){return eu(2,n)},An.orderBy=function(n,t,r,e){return null==n?[]:(of(t)||(t=null==t?[]:[t]),r=e?T:r,of(r)||(r=null==r?[]:[r]),Xt(n,t,r))},An.over=Vf,An.overArgs=Qo,An.overEvery=Kf,An.overSome=Gf,An.partial=Xo,An.partialRight=nf,An.partition=qo,An.pick=If,An.pickBy=Bu,An.property=Pu, An.propertyOf=function(n){return function(t){return null==n?T:Et(n,t)}},An.pull=So,An.pullAll=Ve,An.pullAllBy=function(n,t,r){return n&&n.length&&t&&t.length?er(n,t,ye(r,2)):n},An.pullAllWith=function(n,t,r){return n&&n.length&&t&&t.length?er(n,t,T,r):n},An.pullAt=Oo,An.range=Hf,An.rangeRight=Jf,An.rearg=tf,An.reject=function(n,t){return(of(n)?i:jt)(n,cu(ye(t,3)))},An.remove=function(n,t){var r=[];if(!n||!n.length)return r;var e=-1,u=[],i=n.length;for(t=ye(t,3);++e<i;){var o=n[e];t(o,e,n)&&(r.push(o), u.push(e))}return ur(n,u),r},An.rest=function(n,t){if(typeof n!="function")throw new ni("Expected a function");return t=t===T?t:Au(t),fr(n,t)},An.reverse=Ke,An.sampleSize=function(n,t,r){return t=(r?Oe(n,t,r):t===T)?1:Au(t),(of(n)?et:ar)(n,t)},An.set=function(n,t,r){return null==n?n:lr(n,t,r)},An.setWith=function(n,t,r,e){return e=typeof e=="function"?e:T,null==n?n:lr(n,t,r,e)},An.shuffle=function(n){return(of(n)?ut:sr)(n)},An.slice=function(n,t,r){var e=null==n?0:n.length;return e?(r&&typeof r!="number"&&Oe(n,t,r)?(t=0, r=e):(t=null==t?0:Au(t),r=r===T?e:Au(r)),hr(n,t,r)):[]},An.sortBy=Vo,An.sortedUniq=function(n){return n&&n.length?gr(n):[]},An.sortedUniqBy=function(n,t){return n&&n.length?gr(n,ye(t,2)):[]},An.split=function(n,t,r){return r&&typeof r!="number"&&Oe(n,t,r)&&(t=r=T),r=r===T?4294967295:r>>>0,r?(n=Ou(n))&&(typeof t=="string"||null!=t&&!sf(t))&&(t=yr(t),!t&&Rn.test(n))?Or(M(n),0,r):n.split(t,r):[]},An.spread=function(t,r){if(typeof t!="function")throw new ni("Expected a function");return r=null==r?0:Li(Au(r),0), fr(function(e){var u=e[r];return e=Or(e,0,r),u&&a(e,u),n(t,this,e)})},An.tail=function(n){var t=null==n?0:n.length;return t?hr(n,1,t):[]},An.take=function(n,t,r){return n&&n.length?(t=r||t===T?1:Au(t),hr(n,0,0>t?0:t)):[]},An.takeRight=function(n,t,r){var e=null==n?0:n.length;return e?(t=r||t===T?1:Au(t),t=e-t,hr(n,0>t?0:t,e)):[]},An.takeRightWhile=function(n,t){return n&&n.length?jr(n,ye(t,3),false,true):[]},An.takeWhile=function(n,t){return n&&n.length?jr(n,ye(t,3)):[]},An.tap=function(n,t){return t(n), n},An.throttle=function(n,t,r){var e=true,u=true;if(typeof n!="function")throw new ni("Expected a function");return gu(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),ou(n,t,{leading:e,maxWait:t,trailing:u})},An.thru=Ye,An.toArray=wu,An.toPairs=Rf,An.toPairsIn=zf,An.toPath=function(n){return of(n)?c(n,De):ju(n)?[n]:Ur(xo(Ou(n)))},An.toPlainObject=Su,An.transform=function(n,t,e){var u=of(n),i=u||cf(n)||pf(n);if(t=ye(t,4),null==e){var o=n&&n.constructor;e=i?u?new o:[]:gu(n)&&pu(o)?ro(gi(n)):{}; }return(i?r:mt)(n,function(n,r,u){return t(e,n,r,u)}),e},An.unary=function(n){return ru(n,1)},An.union=Io,An.unionBy=Ro,An.unionWith=zo,An.uniq=function(n){return n&&n.length?br(n):[]},An.uniqBy=function(n,t){return n&&n.length?br(n,ye(t,2)):[]},An.uniqWith=function(n,t){return t=typeof t=="function"?t:T,n&&n.length?br(n,T,t):[]},An.unset=function(n,t){return null==n||xr(n,t)},An.unzip=Ge,An.unzipWith=He,An.update=function(n,t,r){return null==n?n:lr(n,t,Er(r)(Et(n,t)),void 0)},An.updateWith=function(n,t,r,e){ return e=typeof e=="function"?e:T,null!=n&&(n=lr(n,t,Er(r)(Et(n,t)),e)),n},An.values=Lu,An.valuesIn=function(n){return null==n?[]:S(n,Wu(n))},An.without=Wo,An.words=Du,An.wrap=function(n,t){return Xo(Er(t),n)},An.xor=Bo,An.xorBy=Lo,An.xorWith=Uo,An.zip=Co,An.zipObject=function(n,t){return Ar(n||[],t||[],ot)},An.zipObjectDeep=function(n,t){return Ar(n||[],t||[],lr)},An.zipWith=Do,An.entries=Rf,An.entriesIn=zf,An.extend=df,An.extendWith=yf,Fu(An,An),An.add=Yf,An.attempt=$f,An.camelCase=Wf,An.capitalize=Uu, An.ceil=Qf,An.clamp=function(n,t,r){return r===T&&(r=t,t=T),r!==T&&(r=Eu(r),r=r===r?r:0),t!==T&&(t=Eu(t),t=t===t?t:0),pt(Eu(n),t,r)},An.clone=function(n){return _t(n,4)},An.cloneDeep=function(n){return _t(n,5)},An.cloneDeepWith=function(n,t){return t=typeof t=="function"?t:T,_t(n,5,t)},An.cloneWith=function(n,t){return t=typeof t=="function"?t:T,_t(n,4,t)},An.conformsTo=function(n,t){return null==t||gt(n,t,zu(t))},An.deburr=Cu,An.defaultTo=function(n,t){return null==n||n!==n?t:n},An.divide=Xf,An.endsWith=function(n,t,r){ n=Ou(n),t=yr(t);var e=n.length,e=r=r===T?e:pt(Au(r),0,e);return r-=t.length,0<=r&&n.slice(r,e)==t},An.eq=au,An.escape=function(n){return(n=Ou(n))&&H.test(n)?n.replace(K,nt):n},An.escapeRegExp=function(n){return(n=Ou(n))&&en.test(n)?n.replace(rn,"\\$&"):n},An.every=function(n,t,r){var e=of(n)?u:bt;return r&&Oe(n,t,r)&&(t=T),e(n,ye(t,3))},An.find=$o,An.findIndex=Fe,An.findKey=function(n,t){return p(n,ye(t,3),mt)},An.findLast=Fo,An.findLastIndex=Ne,An.findLastKey=function(n,t){return p(n,ye(t,3),At); },An.floor=nc,An.forEach=Xe,An.forEachRight=nu,An.forIn=function(n,t){return null==n?n:io(n,ye(t,3),Wu)},An.forInRight=function(n,t){return null==n?n:oo(n,ye(t,3),Wu)},An.forOwn=function(n,t){return n&&mt(n,ye(t,3))},An.forOwnRight=function(n,t){return n&&At(n,ye(t,3))},An.get=Iu,An.gt=rf,An.gte=ef,An.has=function(n,t){return null!=n&&we(n,t,Rt)},An.hasIn=Ru,An.head=Ze,An.identity=Tu,An.includes=function(n,t,r,e){return n=lu(n)?n:Lu(n),r=r&&!e?Au(r):0,e=n.length,0>r&&(r=Li(e+r,0)),xu(n)?r<=e&&-1<n.indexOf(t,r):!!e&&-1<v(n,t,r); },An.indexOf=function(n,t,r){var e=null==n?0:n.length;return e?(r=null==r?0:Au(r),0>r&&(r=Li(e+r,0)),v(n,t,r)):-1},An.inRange=function(n,t,r){return t=mu(t),r===T?(r=t,t=0):r=mu(r),n=Eu(n),n>=Ui(t,r)&&n<Li(t,r)},An.invoke=kf,An.isArguments=uf,An.isArray=of,An.isArrayBuffer=ff,An.isArrayLike=lu,An.isArrayLikeObject=su,An.isBoolean=function(n){return true===n||false===n||du(n)&&"[object Boolean]"==Ot(n)},An.isBuffer=cf,An.isDate=af,An.isElement=function(n){return du(n)&&1===n.nodeType&&!bu(n)},An.isEmpty=function(n){ if(null==n)return true;if(lu(n)&&(of(n)||typeof n=="string"||typeof n.splice=="function"||cf(n)||pf(n)||uf(n)))return!n.length;var t=_o(n);if("[object Map]"==t||"[object Set]"==t)return!n.size;if(ze(n))return!Vt(n).length;for(var r in n)if(ii.call(n,r))return false;return true},An.isEqual=function(n,t){return Mt(n,t)},An.isEqualWith=function(n,t,r){var e=(r=typeof r=="function"?r:T)?r(n,t):T;return e===T?Mt(n,t,T,r):!!e},An.isError=hu,An.isFinite=function(n){return typeof n=="number"&&zi(n)},An.isFunction=pu, An.isInteger=_u,An.isLength=vu,An.isMap=lf,An.isMatch=function(n,t){return n===t||$t(n,t,xe(t))},An.isMatchWith=function(n,t,r){return r=typeof r=="function"?r:T,$t(n,t,xe(t),r)},An.isNaN=function(n){return yu(n)&&n!=+n},An.isNative=function(n){if(vo(n))throw new Gu("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return Ft(n)},An.isNil=function(n){return null==n},An.isNull=function(n){return null===n},An.isNumber=yu,An.isObject=gu,An.isObjectLike=du,An.isPlainObject=bu,An.isRegExp=sf, An.isSafeInteger=function(n){return _u(n)&&-9007199254740991<=n&&9007199254740991>=n},An.isSet=hf,An.isString=xu,An.isSymbol=ju,An.isTypedArray=pf,An.isUndefined=function(n){return n===T},An.isWeakMap=function(n){return du(n)&&"[object WeakMap]"==_o(n)},An.isWeakSet=function(n){return du(n)&&"[object WeakSet]"==Ot(n)},An.join=function(n,t){return null==n?"":Wi.call(n,t)},An.kebabCase=Bf,An.last=qe,An.lastIndexOf=function(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=e;if(r!==T&&(u=Au(r),u=0>u?Li(e+u,0):Ui(u,e-1)), t===t){for(r=u+1;r--&&n[r]!==t;);n=r}else n=_(n,d,u,true);return n},An.lowerCase=Lf,An.lowerFirst=Uf,An.lt=_f,An.lte=vf,An.max=function(n){return n&&n.length?xt(n,Tu,It):T},An.maxBy=function(n,t){return n&&n.length?xt(n,ye(t,2),It):T},An.mean=function(n){return y(n,Tu)},An.meanBy=function(n,t){return y(n,ye(t,2))},An.min=function(n){return n&&n.length?xt(n,Tu,Kt):T},An.minBy=function(n,t){return n&&n.length?xt(n,ye(t,2),Kt):T},An.stubArray=Zu,An.stubFalse=qu,An.stubObject=function(){return{}},An.stubString=function(){ return""},An.stubTrue=function(){return true},An.multiply=tc,An.nth=function(n,t){return n&&n.length?Qt(n,Au(t)):T},An.noConflict=function(){return Fn._===this&&(Fn._=li),this},An.noop=Nu,An.now=Ko,An.pad=function(n,t,r){n=Ou(n);var e=(t=Au(t))?D(n):0;return!t||e>=t?n:(t=(t-e)/2,ne(Oi(t),r)+n+ne(Si(t),r))},An.padEnd=function(n,t,r){n=Ou(n);var e=(t=Au(t))?D(n):0;return t&&e<t?n+ne(t-e,r):n},An.padStart=function(n,t,r){n=Ou(n);var e=(t=Au(t))?D(n):0;return t&&e<t?ne(t-e,r)+n:n},An.parseInt=function(n,t,r){ return r||null==t?t=0:t&&(t=+t),Di(Ou(n).replace(on,""),t||0)},An.random=function(n,t,r){if(r&&typeof r!="boolean"&&Oe(n,t,r)&&(t=r=T),r===T&&(typeof t=="boolean"?(r=t,t=T):typeof n=="boolean"&&(r=n,n=T)),n===T&&t===T?(n=0,t=1):(n=mu(n),t===T?(t=n,n=0):t=mu(t)),n>t){var e=n;n=t,t=e}return r||n%1||t%1?(r=Mi(),Ui(n+r*(t-n+Dn("1e-"+((r+"").length-1))),t)):ir(n,t)},An.reduce=function(n,t,r){var e=of(n)?l:j,u=3>arguments.length;return e(n,ye(t,4),r,u,eo)},An.reduceRight=function(n,t,r){var e=of(n)?s:j,u=3>arguments.length; return e(n,ye(t,4),r,u,uo)},An.repeat=function(n,t,r){return t=(r?Oe(n,t,r):t===T)?1:Au(t),or(Ou(n),t)},An.replace=function(){var n=arguments,t=Ou(n[0]);return 3>n.length?t:t.replace(n[1],n[2])},An.result=function(n,t,r){t=Sr(t,n);var e=-1,u=t.length;for(u||(u=1,n=T);++e<u;){var i=null==n?T:n[De(t[e])];i===T&&(e=u,i=r),n=pu(i)?i.call(n):i}return n},An.round=rc,An.runInContext=x,An.sample=function(n){return(of(n)?Qn:cr)(n)},An.size=function(n){if(null==n)return 0;if(lu(n))return xu(n)?D(n):n.length; var t=_o(n);return"[object Map]"==t||"[object Set]"==t?n.size:Vt(n).length},An.snakeCase=Cf,An.some=function(n,t,r){var e=of(n)?h:pr;return r&&Oe(n,t,r)&&(t=T),e(n,ye(t,3))},An.sortedIndex=function(n,t){return _r(n,t)},An.sortedIndexBy=function(n,t,r){return vr(n,t,ye(r,2))},An.sortedIndexOf=function(n,t){var r=null==n?0:n.length;if(r){var e=_r(n,t);if(e<r&&au(n[e],t))return e}return-1},An.sortedLastIndex=function(n,t){return _r(n,t,true)},An.sortedLastIndexBy=function(n,t,r){return vr(n,t,ye(r,2),true); },An.sortedLastIndexOf=function(n,t){if(null==n?0:n.length){var r=_r(n,t,true)-1;if(au(n[r],t))return r}return-1},An.startCase=Df,An.startsWith=function(n,t,r){return n=Ou(n),r=null==r?0:pt(Au(r),0,n.length),t=yr(t),n.slice(r,r+t.length)==t},An.subtract=ec,An.sum=function(n){return n&&n.length?m(n,Tu):0},An.sumBy=function(n,t){return n&&n.length?m(n,ye(t,2)):0},An.template=function(n,t,r){var e=An.templateSettings;r&&Oe(n,t,r)&&(t=T),n=Ou(n),t=yf({},t,e,ce),r=yf({},t.imports,e.imports,ce);var u,i,o=zu(r),f=S(r,o),c=0; r=t.interpolate||jn;var a="__p+='";r=Qu((t.escape||jn).source+"|"+r.source+"|"+(r===Q?pn:jn).source+"|"+(t.evaluate||jn).source+"|$","g");var l="sourceURL"in t?"//# sourceURL="+t.sourceURL+"\n":"";if(n.replace(r,function(t,r,e,o,f,l){return e||(e=o),a+=n.slice(c,l).replace(wn,z),r&&(u=true,a+="'+__e("+r+")+'"),f&&(i=true,a+="';"+f+";\n__p+='"),e&&(a+="'+((__t=("+e+"))==null?'':__t)+'"),c=l+t.length,t}),a+="';",(t=t.variable)||(a="with(obj){"+a+"}"),a=(i?a.replace(P,""):a).replace(Z,"$1").replace(q,"$1;"), a="function("+(t||"obj")+"){"+(t?"":"obj||(obj={});")+"var __t,__p=''"+(u?",__e=_.escape":"")+(i?",__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}":";")+a+"return __p}",t=$f(function(){return Hu(o,l+"return "+a).apply(T,f)}),t.source=a,hu(t))throw t;return t},An.times=function(n,t){if(n=Au(n),1>n||9007199254740991<n)return[];var r=4294967295,e=Ui(n,4294967295);for(t=ye(t),n-=4294967295,e=A(e,t);++r<n;)t(r);return e},An.toFinite=mu,An.toInteger=Au,An.toLength=ku,An.toLower=function(n){ return Ou(n).toLowerCase()},An.toNumber=Eu,An.toSafeInteger=function(n){return n?pt(Au(n),-9007199254740991,9007199254740991):0===n?n:0},An.toString=Ou,An.toUpper=function(n){return Ou(n).toUpperCase()},An.trim=function(n,t,r){return(n=Ou(n))&&(r||t===T)?n.replace(un,""):n&&(t=yr(t))?(n=M(n),r=M(t),t=I(n,r),r=R(n,r)+1,Or(n,t,r).join("")):n},An.trimEnd=function(n,t,r){return(n=Ou(n))&&(r||t===T)?n.replace(fn,""):n&&(t=yr(t))?(n=M(n),t=R(n,M(t))+1,Or(n,0,t).join("")):n},An.trimStart=function(n,t,r){ return(n=Ou(n))&&(r||t===T)?n.replace(on,""):n&&(t=yr(t))?(n=M(n),t=I(n,M(t)),Or(n,t).join("")):n},An.truncate=function(n,t){var r=30,e="...";if(gu(t))var u="separator"in t?t.separator:u,r="length"in t?Au(t.length):r,e="omission"in t?yr(t.omission):e;n=Ou(n);var i=n.length;if(Rn.test(n))var o=M(n),i=o.length;if(r>=i)return n;if(i=r-D(e),1>i)return e;if(r=o?Or(o,0,i).join(""):n.slice(0,i),u===T)return r+e;if(o&&(i+=r.length-i),sf(u)){if(n.slice(i).search(u)){var f=r;for(u.global||(u=Qu(u.source,Ou(_n.exec(u))+"g")), u.lastIndex=0;o=u.exec(f);)var c=o.index;r=r.slice(0,c===T?i:c)}}else n.indexOf(yr(u),i)!=i&&(u=r.lastIndexOf(u),-1<u&&(r=r.slice(0,u)));return r+e},An.unescape=function(n){return(n=Ou(n))&&G.test(n)?n.replace(V,tt):n},An.uniqueId=function(n){var t=++oi;return Ou(n)+t},An.upperCase=Mf,An.upperFirst=Tf,An.each=Xe,An.eachRight=nu,An.first=Ze,Fu(An,function(){var n={};return mt(An,function(t,r){ii.call(An.prototype,r)||(n[r]=t)}),n}(),{chain:false}),An.VERSION="4.17.5",r("bind bindKey curry curryRight partial partialRight".split(" "),function(n){ An[n].placeholder=An}),r(["drop","take"],function(n,t){Un.prototype[n]=function(r){r=r===T?1:Li(Au(r),0);var e=this.__filtered__&&!t?new Un(this):this.clone();return e.__filtered__?e.__takeCount__=Ui(r,e.__takeCount__):e.__views__.push({size:Ui(r,4294967295),type:n+(0>e.__dir__?"Right":"")}),e},Un.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()}}),r(["filter","map","takeWhile"],function(n,t){var r=t+1,e=1==r||3==r;Un.prototype[n]=function(n){var t=this.clone();return t.__iteratees__.push({ iteratee:ye(n,3),type:r}),t.__filtered__=t.__filtered__||e,t}}),r(["head","last"],function(n,t){var r="take"+(t?"Right":"");Un.prototype[n]=function(){return this[r](1).value()[0]}}),r(["initial","tail"],function(n,t){var r="drop"+(t?"":"Right");Un.prototype[n]=function(){return this.__filtered__?new Un(this):this[r](1)}}),Un.prototype.compact=function(){return this.filter(Tu)},Un.prototype.find=function(n){return this.filter(n).head()},Un.prototype.findLast=function(n){return this.reverse().find(n); },Un.prototype.invokeMap=fr(function(n,t){return typeof n=="function"?new Un(this):this.map(function(r){return Lt(r,n,t)})}),Un.prototype.reject=function(n){return this.filter(cu(ye(n)))},Un.prototype.slice=function(n,t){n=Au(n);var r=this;return r.__filtered__&&(0<n||0>t)?new Un(r):(0>n?r=r.takeRight(-n):n&&(r=r.drop(n)),t!==T&&(t=Au(t),r=0>t?r.dropRight(-t):r.take(t-n)),r)},Un.prototype.takeRightWhile=function(n){return this.reverse().takeWhile(n).reverse()},Un.prototype.toArray=function(){return this.take(4294967295); },mt(Un.prototype,function(n,t){var r=/^(?:filter|find|map|reject)|While$/.test(t),e=/^(?:head|last)$/.test(t),u=An[e?"take"+("last"==t?"Right":""):t],i=e||/^find/.test(t);u&&(An.prototype[t]=function(){function t(n){return n=u.apply(An,a([n],f)),e&&h?n[0]:n}var o=this.__wrapped__,f=e?[1]:arguments,c=o instanceof Un,l=f[0],s=c||of(o);s&&r&&typeof l=="function"&&1!=l.length&&(c=s=false);var h=this.__chain__,p=!!this.__actions__.length,l=i&&!h,c=c&&!p;return!i&&s?(o=c?o:new Un(this),o=n.apply(o,f),o.__actions__.push({ func:Ye,args:[t],thisArg:T}),new On(o,h)):l&&c?n.apply(this,f):(o=this.thru(t),l?e?o.value()[0]:o.value():o)})}),r("pop push shift sort splice unshift".split(" "),function(n){var t=ti[n],r=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",e=/^(?:pop|shift)$/.test(n);An.prototype[n]=function(){var n=arguments;if(e&&!this.__chain__){var u=this.value();return t.apply(of(u)?u:[],n)}return this[r](function(r){return t.apply(of(r)?r:[],n)})}}),mt(Un.prototype,function(n,t){var r=An[t];if(r){var e=r.name+""; (Ki[e]||(Ki[e]=[])).push({name:t,func:r})}}),Ki[Jr(T,2).name]=[{name:"wrapper",func:T}],Un.prototype.clone=function(){var n=new Un(this.__wrapped__);return n.__actions__=Ur(this.__actions__),n.__dir__=this.__dir__,n.__filtered__=this.__filtered__,n.__iteratees__=Ur(this.__iteratees__),n.__takeCount__=this.__takeCount__,n.__views__=Ur(this.__views__),n},Un.prototype.reverse=function(){if(this.__filtered__){var n=new Un(this);n.__dir__=-1,n.__filtered__=true}else n=this.clone(),n.__dir__*=-1;return n; },Un.prototype.value=function(){var n,t=this.__wrapped__.value(),r=this.__dir__,e=of(t),u=0>r,i=e?t.length:0;n=i;for(var o=this.__views__,f=0,c=-1,a=o.length;++c<a;){var l=o[c],s=l.size;switch(l.type){case"drop":f+=s;break;case"dropRight":n-=s;break;case"take":n=Ui(n,f+s);break;case"takeRight":f=Li(f,n-s)}}if(n={start:f,end:n},o=n.start,f=n.end,n=f-o,o=u?f:o-1,f=this.__iteratees__,c=f.length,a=0,l=Ui(n,this.__takeCount__),!e||!u&&i==n&&l==n)return wr(t,this.__actions__);e=[];n:for(;n--&&a<l;){for(o+=r, u=-1,i=t[o];++u<c;){var h=f[u],s=h.type,h=(0,h.iteratee)(i);if(2==s)i=h;else if(!h){if(1==s)continue n;break n}}e[a++]=i}return e},An.prototype.at=Mo,An.prototype.chain=function(){return Je(this)},An.prototype.commit=function(){return new On(this.value(),this.__chain__)},An.prototype.next=function(){this.__values__===T&&(this.__values__=wu(this.value()));var n=this.__index__>=this.__values__.length;return{done:n,value:n?T:this.__values__[this.__index__++]}},An.prototype.plant=function(n){for(var t,r=this;r instanceof kn;){ var e=$e(r);e.__index__=0,e.__values__=T,t?u.__wrapped__=e:t=e;var u=e,r=r.__wrapped__}return u.__wrapped__=n,t},An.prototype.reverse=function(){var n=this.__wrapped__;return n instanceof Un?(this.__actions__.length&&(n=new Un(this)),n=n.reverse(),n.__actions__.push({func:Ye,args:[Ke],thisArg:T}),new On(n,this.__chain__)):this.thru(Ke)},An.prototype.toJSON=An.prototype.valueOf=An.prototype.value=function(){return wr(this.__wrapped__,this.__actions__)},An.prototype.first=An.prototype.head,ji&&(An.prototype[ji]=Qe), An}(); true?(Fn._=rt, !(__WEBPACK_AMD_DEFINE_RESULT__ = (function(){return rt}).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))):undefined}).call(this); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./../webpack/buildin/module.js */ "../../node_modules/webpack/buildin/module.js")(module))) /***/ }), /***/ "../../node_modules/lodash/once.js": /*!********************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/once.js ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var before = __webpack_require__(/*! ./before */ "../../node_modules/lodash/before.js"); /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } module.exports = once; /***/ }), /***/ "../../node_modules/lodash/toFinite.js": /*!************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/toFinite.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var toNumber = __webpack_require__(/*! ./toNumber */ "../../node_modules/lodash/toNumber.js"); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } module.exports = toFinite; /***/ }), /***/ "../../node_modules/lodash/toInteger.js": /*!*************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/toInteger.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var toFinite = __webpack_require__(/*! ./toFinite */ "../../node_modules/lodash/toFinite.js"); /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } module.exports = toInteger; /***/ }), /***/ "../../node_modules/lodash/toNumber.js": /*!************************************************************!*\ !*** /home/circleci/kandy/node_modules/lodash/toNumber.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(/*! ./isObject */ "../../node_modules/lodash/isObject.js"), isSymbol = __webpack_require__(/*! ./isSymbol */ "../../node_modules/lodash/isSymbol.js"); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber; /***/ }), /***/ "../../node_modules/loglevel/lib/loglevel.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/loglevel/lib/loglevel.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/* * loglevel - https://github.com/pimterry/loglevel * * Copyright (c) 2013 Tim Perry * Licensed under the MIT license. */ (function (root, definition) { "use strict"; if (true) { !(__WEBPACK_AMD_DEFINE_FACTORY__ = (definition), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} }(this, function () { "use strict"; // Slightly dubious tricks to cut down minimized file size var noop = function() {}; var undefinedType = "undefined"; var logMethods = [ "trace", "debug", "info", "warn", "error" ]; // Cross-browser bind equivalent that works at least back to IE6 function bindMethod(obj, methodName) { var method = obj[methodName]; if (typeof method.bind === 'function') { return method.bind(obj); } else { try { return Function.prototype.bind.call(method, obj); } catch (e) { // Missing bind shim or IE8 + Modernizr, fallback to wrapping return function() { return Function.prototype.apply.apply(method, [obj, arguments]); }; } } } // Build the best logging method possible for this env // Wherever possible we want to bind, not wrap, to preserve stack traces function realMethod(methodName) { if (methodName === 'debug') { methodName = 'log'; } if (typeof console === undefinedType) { return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives } else if (console[methodName] !== undefined) { return bindMethod(console, methodName); } else if (console.log !== undefined) { return bindMethod(console, 'log'); } else { return noop; } } // These private functions always need `this` to be set properly function replaceLoggingMethods(level, loggerName) { /*jshint validthis:true */ for (var i = 0; i < logMethods.length; i++) { var methodName = logMethods[i]; this[methodName] = (i < level) ? noop : this.methodFactory(methodName, level, loggerName); } // Define log.log as an alias for log.debug this.log = this.debug; } // In old IE versions, the console isn't present until you first open it. // We build realMethod() replacements here that regenerate logging methods function enableLoggingWhenConsoleArrives(methodName, level, loggerName) { return function () { if (typeof console !== undefinedType) { replaceLoggingMethods.call(this, level, loggerName); this[methodName].apply(this, arguments); } }; } // By default, we use closely bound real methods wherever possible, and // otherwise we wait for a console to appear, and then try again. function defaultMethodFactory(methodName, level, loggerName) { /*jshint validthis:true */ return realMethod(methodName) || enableLoggingWhenConsoleArrives.apply(this, arguments); } function Logger(name, defaultLevel, factory) { var self = this; var currentLevel; var storageKey = "loglevel"; if (name) { storageKey += ":" + name; } function persistLevelIfPossible(levelNum) { var levelName = (logMethods[levelNum] || 'silent').toUpperCase(); if (typeof window === undefinedType) return; // Use localStorage if available try { window.localStorage[storageKey] = levelName; return; } catch (ignore) {} // Use session cookie as fallback try { window.document.cookie = encodeURIComponent(storageKey) + "=" + levelName + ";"; } catch (ignore) {} } function getPersistedLevel() { var storedLevel; if (typeof window === undefinedType) return; try { storedLevel = window.localStorage[storageKey]; } catch (ignore) {} // Fallback to cookies if local storage gives us nothing if (typeof storedLevel === undefinedType) { try { var cookie = window.document.cookie; var location = cookie.indexOf( encodeURIComponent(storageKey) + "="); if (location !== -1) { storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1]; } } catch (ignore) {} } // If the stored level is not valid, treat it as if nothing was stored. if (self.levels[storedLevel] === undefined) { storedLevel = undefined; } return storedLevel; } /* * * Public logger API - see https://github.com/pimterry/loglevel for details * */ self.name = name; self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3, "ERROR": 4, "SILENT": 5}; self.methodFactory = factory || defaultMethodFactory; self.getLevel = function () { return currentLevel; }; self.setLevel = function (level, persist) { if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) { level = self.levels[level.toUpperCase()]; } if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) { currentLevel = level; if (persist !== false) { // defaults to true persistLevelIfPossible(level); } replaceLoggingMethods.call(self, level, name); if (typeof console === undefinedType && level < self.levels.SILENT) { return "No console available for logging"; } } else { throw "log.setLevel() called with invalid level: " + level; } }; self.setDefaultLevel = function (level) { if (!getPersistedLevel()) { self.setLevel(level, false); } }; self.enableAll = function(persist) { self.setLevel(self.levels.TRACE, persist); }; self.disableAll = function(persist) { self.setLevel(self.levels.SILENT, persist); }; // Initialize with the right level var initialLevel = getPersistedLevel(); if (initialLevel == null) { initialLevel = defaultLevel == null ? "WARN" : defaultLevel; } self.setLevel(initialLevel, false); } /* * * Top-level API * */ var defaultLogger = new Logger(); var _loggersByName = {}; defaultLogger.getLogger = function getLogger(name) { if (typeof name !== "string" || name === "") { throw new TypeError("You must supply a name when creating a logger."); } var logger = _loggersByName[name]; if (!logger) { logger = _loggersByName[name] = new Logger( name, defaultLogger.getLevel(), defaultLogger.methodFactory); } return logger; }; // Grab the current global log variable in case of overwrite var _log = (typeof window !== undefinedType) ? window.log : undefined; defaultLogger.noConflict = function() { if (typeof window !== undefinedType && window.log === defaultLogger) { window.log = _log; } return defaultLogger; }; defaultLogger.getLoggers = function getLoggers() { return _loggersByName; }; return defaultLogger; })); /***/ }), /***/ "../../node_modules/pako/index.js": /*!*******************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/index.js ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Top level file is just a mixin of submodules & constants var assign = __webpack_require__(/*! ./lib/utils/common */ "../../node_modules/pako/lib/utils/common.js").assign; var deflate = __webpack_require__(/*! ./lib/deflate */ "../../node_modules/pako/lib/deflate.js"); var inflate = __webpack_require__(/*! ./lib/inflate */ "../../node_modules/pako/lib/inflate.js"); var constants = __webpack_require__(/*! ./lib/zlib/constants */ "../../node_modules/pako/lib/zlib/constants.js"); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; /***/ }), /***/ "../../node_modules/pako/lib/deflate.js": /*!*************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/deflate.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var zlib_deflate = __webpack_require__(/*! ./zlib/deflate */ "../../node_modules/pako/lib/zlib/deflate.js"); var utils = __webpack_require__(/*! ./utils/common */ "../../node_modules/pako/lib/utils/common.js"); var strings = __webpack_require__(/*! ./utils/strings */ "../../node_modules/pako/lib/utils/strings.js"); var msg = __webpack_require__(/*! ./zlib/messages */ "../../node_modules/pako/lib/zlib/messages.js"); var ZStream = __webpack_require__(/*! ./zlib/zstream */ "../../node_modules/pako/lib/zlib/zstream.js"); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overridden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * - `dictionary` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ function Deflate(options) { if (!(this instanceof Deflate)) return new Deflate(options); this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } if (opt.dictionary) { var dict; // Convert data if needed if (typeof opt.dictionary === 'string') { // If we need to compress text, change encoding to utf8. dict = strings.string2buf(opt.dictionary); } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { dict = new Uint8Array(opt.dictionary); } else { dict = opt.dictionary; } status = zlib_deflate.deflateSetDictionary(this.strm, dict); if (status !== Z_OK) { throw new Error(msg[status]); } this._dict_set = true; } } /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): output data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function (status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate algorithm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * - dictionary * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg || msg[deflator.err]; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; /***/ }), /***/ "../../node_modules/pako/lib/inflate.js": /*!*************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/inflate.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var zlib_inflate = __webpack_require__(/*! ./zlib/inflate */ "../../node_modules/pako/lib/zlib/inflate.js"); var utils = __webpack_require__(/*! ./utils/common */ "../../node_modules/pako/lib/utils/common.js"); var strings = __webpack_require__(/*! ./utils/strings */ "../../node_modules/pako/lib/utils/strings.js"); var c = __webpack_require__(/*! ./zlib/constants */ "../../node_modules/pako/lib/zlib/constants.js"); var msg = __webpack_require__(/*! ./zlib/messages */ "../../node_modules/pako/lib/zlib/messages.js"); var ZStream = __webpack_require__(/*! ./zlib/zstream */ "../../node_modules/pako/lib/zlib/zstream.js"); var GZheader = __webpack_require__(/*! ./zlib/gzheader */ "../../node_modules/pako/lib/zlib/gzheader.js"); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overridden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * - `dictionary` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ function Inflate(options) { if (!(this instanceof Inflate)) return new Inflate(options); this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new GZheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); } /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var dictionary = this.options.dictionary; var status, _mode; var next_out_utf8, tail, utf8str; var dict; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_NEED_DICT && dictionary) { // Convert data if needed if (typeof dictionary === 'string') { dict = strings.string2buf(dictionary); } else if (toString.call(dictionary) === '[object ArrayBuffer]') { dict = new Uint8Array(dictionary); } else { dict = dictionary; } status = zlib_inflate.inflateSetDictionary(this.strm, dict); } if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): output data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function (status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 aligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg || msg[inflator.err]; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; /***/ }), /***/ "../../node_modules/pako/lib/utils/common.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/utils/common.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); function _has(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (_has(source, p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs + len), dest_offs); return; } // Fallback to ordinary array for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i = 0, l = chunks.length; i < l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i = 0, l = chunks.length; i < l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); /***/ }), /***/ "../../node_modules/pako/lib/utils/strings.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/utils/strings.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // String encode/decode helpers var utils = __webpack_require__(/*! ./common */ "../../node_modules/pako/lib/utils/common.js"); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safari // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q = 0; q < 256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i = 0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i = 0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function (buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function (str) { var buf = new utils.Buf8(str.length); for (var i = 0, len = buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len * 2); for (out = 0, i = 0; i < len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function (buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max - 1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means buffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; /***/ }), /***/ "../../node_modules/pako/lib/zlib/adler32.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/zlib/adler32.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It isn't worth it to make additional optimizations as in original. // Small size is preferable. // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; /***/ }), /***/ "../../node_modules/pako/lib/zlib/constants.js": /*!********************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/zlib/constants.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; /***/ }), /***/ "../../node_modules/pako/lib/zlib/crc32.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/zlib/crc32.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n = 0; n < 256; n++) { c = n; for (var k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc ^= -1; for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; /***/ }), /***/ "../../node_modules/pako/lib/zlib/deflate.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/zlib/deflate.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = __webpack_require__(/*! ../utils/common */ "../../node_modules/pako/lib/utils/common.js"); var trees = __webpack_require__(/*! ./trees */ "../../node_modules/pako/lib/zlib/trees.js"); var adler32 = __webpack_require__(/*! ./adler32 */ "../../node_modules/pako/lib/zlib/adler32.js"); var crc32 = __webpack_require__(/*! ./crc32 */ "../../node_modules/pako/lib/zlib/crc32.js"); var msg = __webpack_require__(/*! ./messages */ "../../node_modules/pako/lib/zlib/messages.js"); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only(s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; // zmemcpy(buf, strm->next_in, len); utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH - 1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH - 1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length - 1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH - 1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ function Config(good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; } var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); //s->pending_buf = (uchf *) overlay; s.pending_buf = new utils.Buf8(s.pending_buf_size); // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); s.d_buf = 1 * s.lit_bufsize; //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Initializes the compression dictionary from the given byte * sequence without producing any compressed output. */ function deflateSetDictionary(strm, dictionary) { var dictLength = dictionary.length; var s; var str, n; var wrap; var avail; var next; var input; var tmpDict; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } s = strm.state; wrap = s.wrap; if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { return Z_STREAM_ERROR; } /* when using zlib wrappers, compute Adler-32 for provided dictionary */ if (wrap === 1) { /* adler32(strm->adler, dictionary, dictLength); */ strm.adler = adler32(strm.adler, dictionary, dictLength, 0); } s.wrap = 0; /* avoid computing Adler-32 in read_buf */ /* if dictionary would fill window, just replace the history */ if (dictLength >= s.w_size) { if (wrap === 0) { /* already empty otherwise */ /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); s.strstart = 0; s.block_start = 0; s.insert = 0; } /* use the tail */ // dictionary = dictionary.slice(dictLength - s.w_size); tmpDict = new utils.Buf8(s.w_size); utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); dictionary = tmpDict; dictLength = s.w_size; } /* insert dictionary into window and hash */ avail = strm.avail_in; next = strm.next_in; input = strm.input; strm.avail_in = dictLength; strm.next_in = 0; strm.input = dictionary; fill_window(s); while (s.lookahead >= MIN_MATCH) { str = s.strstart; n = s.lookahead - (MIN_MATCH - 1); do { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; } while (--n); s.strstart = str; s.lookahead = MIN_MATCH - 1; fill_window(s); } s.strstart += s.lookahead; s.block_start = s.strstart; s.insert = s.lookahead; s.lookahead = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; strm.next_in = next; strm.input = input; strm.avail_in = avail; s.wrap = wrap; return Z_OK; } exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ /***/ }), /***/ "../../node_modules/pako/lib/zlib/gzheader.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/zlib/gzheader.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; /***/ }), /***/ "../../node_modules/pako/lib/zlib/inffast.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/zlib/inffast.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defaults, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; /***/ }), /***/ "../../node_modules/pako/lib/zlib/inflate.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/zlib/inflate.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = __webpack_require__(/*! ../utils/common */ "../../node_modules/pako/lib/utils/common.js"); var adler32 = __webpack_require__(/*! ./adler32 */ "../../node_modules/pako/lib/zlib/adler32.js"); var crc32 = __webpack_require__(/*! ./crc32 */ "../../node_modules/pako/lib/zlib/crc32.js"); var inflate_fast = __webpack_require__(/*! ./inffast */ "../../node_modules/pako/lib/zlib/inffast.js"); var inflate_table = __webpack_require__(/*! ./inftrees */ "../../node_modules/pako/lib/zlib/inftrees.js"); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function zswap32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window, src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window, src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more convenient processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = zswap32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = { bits: state.lenbits }; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = { bits: state.lenbits }; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = { bits: state.distbits }; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defaults, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' instead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too if ((state.flags ? hold : zswap32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } function inflateSetDictionary(strm, dictionary) { var dictLength = dictionary.length; var state; var dictid; var ret; /* check state */ if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } state = strm.state; if (state.wrap !== 0 && state.mode !== DICT) { return Z_STREAM_ERROR; } /* check for correct dictionary identifier */ if (state.mode === DICT) { dictid = 1; /* adler32(0, null, 0)*/ /* dictid = adler32(dictid, dictionary, dictLength); */ dictid = adler32(dictid, dictionary, dictLength, 0); if (dictid !== state.check) { return Z_DATA_ERROR; } } /* copy dictionary to window using updatewindow(), which will amend the existing dictionary if appropriate */ ret = updatewindow(strm, dictionary, dictLength, dictLength); if (ret) { state.mode = MEM; return Z_MEM_ERROR; } state.havedict = 1; // Tracev((stderr, "inflate: dictionary set\n")); return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ /***/ }), /***/ "../../node_modules/pako/lib/zlib/inftrees.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/zlib/inftrees.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = __webpack_require__(/*! ../utils/common */ "../../node_modules/pako/lib/utils/common.js"); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* process all codes and make table entries */ for (;;) { /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; /***/ }), /***/ "../../node_modules/pako/lib/zlib/messages.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/zlib/messages.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. module.exports = { 2: 'need dictionary', /* Z_NEED_DICT 2 */ 1: 'stream end', /* Z_STREAM_END 1 */ 0: '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; /***/ }), /***/ "../../node_modules/pako/lib/zlib/trees.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/zlib/trees.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var utils = __webpack_require__(/*! ../utils/common */ "../../node_modules/pako/lib/utils/common.js"); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ /* eslint-disable comma-spacing,array-bracket-spacing */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* eslint-enable comma-spacing,array-bracket-spacing */ /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES + 2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; } var static_l_desc; var static_d_desc; var static_bl_desc; function TreeDesc(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ } function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short(s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n - base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length - 1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m * 2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; tree[m * 2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits - 1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n * 2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES - 1; code++) { base_length[code] = length; for (n = 0; n < (1 << extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length - 1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1 << extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n * 2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n * 2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES + 1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n * 2 + 1]/*.Len*/ = 5; static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n * 2; var _m2 = m * 2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code + LITERALS + 1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node * 2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6 * 2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count - 3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count - 3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count - 11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes - 1, 5); send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES << 1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len + 3 + 7) >>> 3; static_lenb = (s.static_len + 3 + 7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc * 2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defaults, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize - 1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; /***/ }), /***/ "../../node_modules/pako/lib/zlib/zstream.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/pako/lib/zlib/zstream.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; /***/ }), /***/ "../../node_modules/process/browser.js": /*!************************************************************!*\ !*** /home/circleci/kandy/node_modules/process/browser.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /***/ "../../node_modules/promiscuous/promiscuous.js": /*!********************************************************************!*\ !*** /home/circleci/kandy/node_modules/promiscuous/promiscuous.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(setImmediate) {/**@license MIT-promiscuous-©Ruben Verborgh*/ (function (func, obj) { // Type checking utility function function is(type, item) { return (typeof item)[0] == type; } // Creates a promise, calling callback(resolve, reject), ignoring other parameters. function Promise(callback, handler) { // The `handler` variable points to the function that will // 1) handle a .then(resolved, rejected) call // 2) handle a resolve or reject call (if the first argument === `is`) // Before 2), `handler` holds a queue of callbacks. // After 2), `handler` is a finalized .then handler. handler = function pendingHandler(resolved, rejected, value, queue, then, i) { queue = pendingHandler.q; // Case 1) handle a .then(resolved, rejected) call if (resolved != is) { return Promise(function (resolve, reject) { queue.push({ p: this, r: resolve, j: reject, 1: resolved, 0: rejected }); }); } // Case 2) handle a resolve or reject call // (`resolved` === `is` acts as a sentinel) // The actual function signature is // .re[ject|solve](<is>, success, value) // Check if the value is a promise and try to obtain its `then` method if (value && (is(func, value) | is(obj, value))) { try { then = value.then; } catch (reason) { rejected = 0; value = reason; } } // If the value is a promise, take over its state if (is(func, then)) { try { then.call(value, transferState(1), rejected = transferState(0)); } catch (reason) { rejected(reason); } } // The value is not a promise; handle resolve/reject else { // Replace this handler with a finalized resolved/rejected handler handler = function (Resolved, Rejected) { // If the Resolved or Rejected parameter is not a function, // return the original promise (now stored in the `callback` variable) if (!is(func, (Resolved = rejected ? Resolved : Rejected))) return callback; // Otherwise, return a finalized promise, transforming the value with the function return Promise(function (resolve, reject) { finalize(this, resolve, reject, value, Resolved); }); }; // Resolve/reject pending callbacks i = 0; while (i < queue.length) { then = queue[i++]; // If no callback, just resolve/reject the promise if (!is(func, resolved = then[rejected])) (rejected ? then.r : then.j)(value); // Otherwise, resolve/reject the promise with the result of the callback else finalize(then.p, then.r, then.j, value, resolved); } } // Returns a function that transfers the state of the promise function transferState(resolved) { return function (value) { then && (then = 0, pendingHandler(is, resolved, value)); }; } }; // The queue of pending callbacks; garbage-collected when handler is resolved/rejected handler.q = []; // Create and return the promise (reusing the callback variable) callback.call(callback = { then: function (resolved, rejected) { return handler(resolved, rejected); }, "catch": function (rejected) { return handler(0, rejected); } }, function (value) { handler(is, 1, value); }, function (reason) { handler(is, 0, reason); }); return callback; } // Finalizes the promise by resolving/rejecting it with the transformed value function finalize(promise, resolve, reject, value, transform) { setImmediate(function () { try { // Transform the value through and check whether it's a promise value = transform(value); transform = value && (is(obj, value) | is(func, value)) && value.then; // Return the result if it's not a promise if (!is(func, transform)) resolve(value); // If it's a promise, make sure it's not circular else if (value == promise) reject(TypeError()); // Take over the promise's state else transform.call(value, resolve, reject); } catch (error) { reject(error); } }); } // Export the main module module.exports = Promise; // Creates a resolved promise Promise.resolve = ResolvedPromise; function ResolvedPromise(value) { return Promise(function (resolve) { resolve(value); }); } // Creates a rejected promise Promise.reject = function (reason) { return Promise(function (resolve, reject) { reject(reason); }); }; // Transforms an array of promises into a promise for an array Promise.all = function (promises) { return Promise(function (resolve, reject, count, values) { // Array of collected values values = []; // Resolve immediately if there are no promises count = promises.length || resolve(values); // Transform all elements (`map` is shorter than `forEach`) promises.map(function (promise, index) { ResolvedPromise(promise).then( // Store the value and resolve if it was the last function (value) { values[index] = value; --count || resolve(values); }, // Reject if one element fails reject); }); }); }; // Returns a promise that resolves or rejects as soon as one promise in the array does Promise.race = function (promises) { return Promise(function (resolve, reject) { // Register to all promises in the array promises.map(function (promise) { ResolvedPromise(promise).then(resolve, reject); }); }); }; })('f', 'o'); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../timers-browserify/main.js */ "../../node_modules/timers-browserify/main.js").setImmediate)) /***/ }), /***/ "../../node_modules/reduce-reducers/dist/index.js": /*!***********************************************************************!*\ !*** /home/circleci/kandy/node_modules/reduce-reducers/dist/index.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { for (var _len = arguments.length, reducers = Array(_len), _key = 0; _key < _len; _key++) { reducers[_key] = arguments[_key]; } return function (previous, current) { return reducers.reduce(function (p, r) { return r(p, current); }, previous); }; }; module.exports = exports["default"]; /***/ }), /***/ "../../node_modules/redux-actions/es/arrayToObject.js": /*!***************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-actions/es/arrayToObject.js ***! \***************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony default export */ __webpack_exports__["default"] = (function (array, callback) { return array.reduce(function (partialObject, element) { return callback(partialObject, element); }, {}); }); /***/ }), /***/ "../../node_modules/redux-actions/es/camelCase.js": /*!***********************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-actions/es/camelCase.js ***! \***********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // based on https://github.com/lodash/lodash/blob/4.17.2/lodash.js#L14100 // eslint-disable-next-line max-len var wordPattern = /[A-Z\xc0-\xd6\xd8-\xde]?[a-z\xdf-\xf6\xf8-\xff]+(?:['’](?:d|ll|m|re|s|t|ve))?(?=[\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]|[A-Z\xc0-\xd6\xd8-\xde]|$)|(?:[A-Z\xc0-\xd6\xd8-\xde]|[^\ud800-\udfff\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\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?=[\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]|[A-Z\xc0-\xd6\xd8-\xde](?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\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\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])|$)|[A-Z\xc0-\xd6\xd8-\xde]?(?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\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\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:d|ll|m|re|s|t|ve))?|[A-Z\xc0-\xd6\xd8-\xde]+(?:['’](?:D|LL|M|RE|S|T|VE))?|\d*(?:(?:1ST|2ND|3RD|(?![123])\dTH)\b)|\d*(?:(?:1st|2nd|3rd|(?![123])\dth)\b)|\d+|(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?)*/g; var namespacer = '/'; function camelCase(string) { return string.match(wordPattern).reduce(function (camelCased, word, index) { return camelCased + (index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.substring(1).toLowerCase()); }, ''); } /* harmony default export */ __webpack_exports__["default"] = (function (type) { return type.split(namespacer).map(camelCase).join(namespacer); }); /***/ }), /***/ "../../node_modules/redux-actions/es/combineActions.js": /*!****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-actions/es/combineActions.js ***! \****************************************************************************/ /*! exports provided: ACTION_TYPE_DELIMITER, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ACTION_TYPE_DELIMITER", function() { return ACTION_TYPE_DELIMITER; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return combineActions; }); /* harmony import */ var lodash_es_isString__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash-es/isString */ "../../node_modules/lodash-es/isString.js"); /* harmony import */ var lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash-es/isFunction */ "../../node_modules/lodash-es/isFunction.js"); /* harmony import */ var lodash_es_isEmpty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash-es/isEmpty */ "../../node_modules/lodash-es/isEmpty.js"); /* harmony import */ var lodash_es_toString__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash-es/toString */ "../../node_modules/lodash-es/toString.js"); /* harmony import */ var lodash_es_isSymbol__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash-es/isSymbol */ "../../node_modules/lodash-es/isSymbol.js"); /* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! invariant */ "../../node_modules/invariant/browser.js"); /* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_5__); var ACTION_TYPE_DELIMITER = '||'; function isValidActionType(type) { return Object(lodash_es_isString__WEBPACK_IMPORTED_MODULE_0__["default"])(type) || Object(lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_1__["default"])(type) || Object(lodash_es_isSymbol__WEBPACK_IMPORTED_MODULE_4__["default"])(type); } function isValidActionTypes(types) { if (Object(lodash_es_isEmpty__WEBPACK_IMPORTED_MODULE_2__["default"])(types)) { return false; } return types.every(isValidActionType); } function combineActions() { for (var _len = arguments.length, actionsTypes = Array(_len), _key = 0; _key < _len; _key++) { actionsTypes[_key] = arguments[_key]; } invariant__WEBPACK_IMPORTED_MODULE_5___default()(isValidActionTypes(actionsTypes), 'Expected action types to be strings, symbols, or action creators'); var combinedActionType = actionsTypes.map(lodash_es_toString__WEBPACK_IMPORTED_MODULE_3__["default"]).join(ACTION_TYPE_DELIMITER); return { toString: function toString() { return combinedActionType; } }; } /***/ }), /***/ "../../node_modules/redux-actions/es/createAction.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-actions/es/createAction.js ***! \**************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return createAction; }); /* harmony import */ var lodash_es_identity__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash-es/identity */ "../../node_modules/lodash-es/identity.js"); /* harmony import */ var lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash-es/isFunction */ "../../node_modules/lodash-es/isFunction.js"); /* harmony import */ var lodash_es_isNull__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash-es/isNull */ "../../node_modules/lodash-es/isNull.js"); /* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! invariant */ "../../node_modules/invariant/browser.js"); /* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_3__); function createAction(type) { var payloadCreator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : lodash_es_identity__WEBPACK_IMPORTED_MODULE_0__["default"]; var metaCreator = arguments[2]; invariant__WEBPACK_IMPORTED_MODULE_3___default()(Object(lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_1__["default"])(payloadCreator) || Object(lodash_es_isNull__WEBPACK_IMPORTED_MODULE_2__["default"])(payloadCreator), 'Expected payloadCreator to be a function, undefined or null'); var finalPayloadCreator = Object(lodash_es_isNull__WEBPACK_IMPORTED_MODULE_2__["default"])(payloadCreator) || payloadCreator === lodash_es_identity__WEBPACK_IMPORTED_MODULE_0__["default"] ? lodash_es_identity__WEBPACK_IMPORTED_MODULE_0__["default"] : function (head) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return head instanceof Error ? head : payloadCreator.apply(undefined, [head].concat(args)); }; var hasMeta = Object(lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_1__["default"])(metaCreator); var typeString = type.toString(); var actionCreator = function actionCreator() { var payload = finalPayloadCreator.apply(undefined, arguments); var action = { type: type }; if (payload instanceof Error) { action.error = true; } if (payload !== undefined) { action.payload = payload; } if (hasMeta) { action.meta = metaCreator.apply(undefined, arguments); } return action; }; actionCreator.toString = function () { return typeString; }; return actionCreator; } /***/ }), /***/ "../../node_modules/redux-actions/es/createActions.js": /*!***************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-actions/es/createActions.js ***! \***************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return createActions; }); /* harmony import */ var _camelCase__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./camelCase */ "../../node_modules/redux-actions/es/camelCase.js"); /* harmony import */ var lodash_es_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash-es/identity */ "../../node_modules/lodash-es/identity.js"); /* harmony import */ var lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash-es/isPlainObject */ "../../node_modules/lodash-es/isPlainObject.js"); /* harmony import */ var lodash_es_isArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash-es/isArray */ "../../node_modules/lodash-es/isArray.js"); /* harmony import */ var lodash_es_last__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash-es/last */ "../../node_modules/lodash-es/last.js"); /* harmony import */ var lodash_es_isString__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! lodash-es/isString */ "../../node_modules/lodash-es/isString.js"); /* harmony import */ var lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! lodash-es/isFunction */ "../../node_modules/lodash-es/isFunction.js"); /* harmony import */ var lodash_es_isNil__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! lodash-es/isNil */ "../../node_modules/lodash-es/isNil.js"); /* harmony import */ var _createAction__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./createAction */ "../../node_modules/redux-actions/es/createAction.js"); /* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! invariant */ "../../node_modules/invariant/browser.js"); /* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_9__); /* harmony import */ var _arrayToObject__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./arrayToObject */ "../../node_modules/redux-actions/es/arrayToObject.js"); /* harmony import */ var _flattenUtils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./flattenUtils */ "../../node_modules/redux-actions/es/flattenUtils.js"); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function createActions(actionMap) { for (var _len = arguments.length, identityActions = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { identityActions[_key - 1] = arguments[_key]; } var options = Object(lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_2__["default"])(Object(lodash_es_last__WEBPACK_IMPORTED_MODULE_4__["default"])(identityActions)) ? identityActions.pop() : {}; invariant__WEBPACK_IMPORTED_MODULE_9___default()(identityActions.every(lodash_es_isString__WEBPACK_IMPORTED_MODULE_5__["default"]) && (Object(lodash_es_isString__WEBPACK_IMPORTED_MODULE_5__["default"])(actionMap) || Object(lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_2__["default"])(actionMap)), 'Expected optional object followed by string action types'); if (Object(lodash_es_isString__WEBPACK_IMPORTED_MODULE_5__["default"])(actionMap)) { return actionCreatorsFromIdentityActions([actionMap].concat(identityActions), options); } return _extends({}, actionCreatorsFromActionMap(actionMap, options), actionCreatorsFromIdentityActions(identityActions, options)); } function actionCreatorsFromActionMap(actionMap, options) { var flatActionMap = Object(_flattenUtils__WEBPACK_IMPORTED_MODULE_11__["flattenActionMap"])(actionMap, options); var flatActionCreators = actionMapToActionCreators(flatActionMap); return Object(_flattenUtils__WEBPACK_IMPORTED_MODULE_11__["unflattenActionCreators"])(flatActionCreators, options); } function actionMapToActionCreators(actionMap) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, prefix = _ref.prefix, _ref$namespace = _ref.namespace, namespace = _ref$namespace === undefined ? _flattenUtils__WEBPACK_IMPORTED_MODULE_11__["defaultNamespace"] : _ref$namespace; function isValidActionMapValue(actionMapValue) { if (Object(lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_6__["default"])(actionMapValue) || Object(lodash_es_isNil__WEBPACK_IMPORTED_MODULE_7__["default"])(actionMapValue)) { return true; } else if (Object(lodash_es_isArray__WEBPACK_IMPORTED_MODULE_3__["default"])(actionMapValue)) { var _actionMapValue = _slicedToArray(actionMapValue, 2), _actionMapValue$ = _actionMapValue[0], payload = _actionMapValue$ === undefined ? lodash_es_identity__WEBPACK_IMPORTED_MODULE_1__["default"] : _actionMapValue$, meta = _actionMapValue[1]; return Object(lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_6__["default"])(payload) && Object(lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_6__["default"])(meta); } return false; } return Object(_arrayToObject__WEBPACK_IMPORTED_MODULE_10__["default"])(Object.keys(actionMap), function (partialActionCreators, type) { var actionMapValue = actionMap[type]; invariant__WEBPACK_IMPORTED_MODULE_9___default()(isValidActionMapValue(actionMapValue), 'Expected function, undefined, null, or array with payload and meta ' + ('functions for ' + type)); var prefixedType = prefix ? '' + prefix + namespace + type : type; var actionCreator = Object(lodash_es_isArray__WEBPACK_IMPORTED_MODULE_3__["default"])(actionMapValue) ? _createAction__WEBPACK_IMPORTED_MODULE_8__["default"].apply(undefined, [prefixedType].concat(_toConsumableArray(actionMapValue))) : Object(_createAction__WEBPACK_IMPORTED_MODULE_8__["default"])(prefixedType, actionMapValue); return _extends({}, partialActionCreators, _defineProperty({}, type, actionCreator)); }); } function actionCreatorsFromIdentityActions(identityActions, options) { var actionMap = Object(_arrayToObject__WEBPACK_IMPORTED_MODULE_10__["default"])(identityActions, function (partialActionMap, type) { return _extends({}, partialActionMap, _defineProperty({}, type, lodash_es_identity__WEBPACK_IMPORTED_MODULE_1__["default"])); }); var actionCreators = actionMapToActionCreators(actionMap, options); return Object(_arrayToObject__WEBPACK_IMPORTED_MODULE_10__["default"])(Object.keys(actionCreators), function (partialActionCreators, type) { return _extends({}, partialActionCreators, _defineProperty({}, Object(_camelCase__WEBPACK_IMPORTED_MODULE_0__["default"])(type), actionCreators[type])); }); } /***/ }), /***/ "../../node_modules/redux-actions/es/flattenUtils.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-actions/es/flattenUtils.js ***! \**************************************************************************/ /*! exports provided: defaultNamespace, flattenActionMap, flattenReducerMap, unflattenActionCreators */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultNamespace", function() { return defaultNamespace; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "flattenActionMap", function() { return flattenActionMap; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "flattenReducerMap", function() { return flattenReducerMap; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unflattenActionCreators", function() { return unflattenActionCreators; }); /* harmony import */ var _camelCase__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./camelCase */ "../../node_modules/redux-actions/es/camelCase.js"); /* harmony import */ var _ownKeys__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ownKeys */ "../../node_modules/redux-actions/es/ownKeys.js"); /* harmony import */ var _hasGeneratorInterface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./hasGeneratorInterface */ "../../node_modules/redux-actions/es/hasGeneratorInterface.js"); /* harmony import */ var lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash-es/isPlainObject */ "../../node_modules/lodash-es/isPlainObject.js"); /* harmony import */ var lodash_es_isMap__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash-es/isMap */ "../../node_modules/lodash-es/isMap.js"); var defaultNamespace = '/'; function get(key, x) { return Object(lodash_es_isMap__WEBPACK_IMPORTED_MODULE_4__["default"])(x) ? x.get(key) : x[key]; } var flattenWhenNode = function flattenWhenNode(predicate) { return function flatten(map) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$namespace = _ref.namespace, namespace = _ref$namespace === undefined ? defaultNamespace : _ref$namespace, prefix = _ref.prefix; var partialFlatMap = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var partialFlatActionType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; function connectNamespace(type) { return partialFlatActionType ? '' + partialFlatActionType + namespace + type : type; } function connectPrefix(type) { if (partialFlatActionType || !prefix) { return type; } return '' + prefix + namespace + type; } Object(_ownKeys__WEBPACK_IMPORTED_MODULE_1__["default"])(map).forEach(function (type) { var nextNamespace = connectPrefix(connectNamespace(type)); var mapValue = get(type, map); if (!predicate(mapValue)) { partialFlatMap[nextNamespace] = mapValue; } else { flatten(mapValue, { namespace: namespace, prefix: prefix }, partialFlatMap, nextNamespace); } }); return partialFlatMap; }; }; var flattenActionMap = flattenWhenNode(lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_3__["default"]); var flattenReducerMap = flattenWhenNode(function (node) { return (Object(lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_3__["default"])(node) || Object(lodash_es_isMap__WEBPACK_IMPORTED_MODULE_4__["default"])(node)) && !Object(_hasGeneratorInterface__WEBPACK_IMPORTED_MODULE_2__["default"])(node); }); function unflattenActionCreators(flatActionCreators) { var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref2$namespace = _ref2.namespace, namespace = _ref2$namespace === undefined ? defaultNamespace : _ref2$namespace, prefix = _ref2.prefix; function unflatten(flatActionType) { var partialNestedActionCreators = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var partialFlatActionTypePath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; var nextNamespace = Object(_camelCase__WEBPACK_IMPORTED_MODULE_0__["default"])(partialFlatActionTypePath.shift()); if (partialFlatActionTypePath.length) { if (!partialNestedActionCreators[nextNamespace]) { partialNestedActionCreators[nextNamespace] = {}; } unflatten(flatActionType, partialNestedActionCreators[nextNamespace], partialFlatActionTypePath); } else { partialNestedActionCreators[nextNamespace] = flatActionCreators[flatActionType]; } } var nestedActionCreators = {}; Object.getOwnPropertyNames(flatActionCreators).forEach(function (type) { var unprefixedType = prefix ? type.replace('' + prefix + namespace, '') : type; return unflatten(type, nestedActionCreators, unprefixedType.split(namespace)); }); return nestedActionCreators; } /***/ }), /***/ "../../node_modules/redux-actions/es/handleAction.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-actions/es/handleAction.js ***! \**************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return handleAction; }); /* harmony import */ var lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash-es/isFunction */ "../../node_modules/lodash-es/isFunction.js"); /* harmony import */ var lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash-es/isPlainObject */ "../../node_modules/lodash-es/isPlainObject.js"); /* harmony import */ var lodash_es_identity__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash-es/identity */ "../../node_modules/lodash-es/identity.js"); /* harmony import */ var lodash_es_isNil__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash-es/isNil */ "../../node_modules/lodash-es/isNil.js"); /* harmony import */ var lodash_es_isUndefined__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash-es/isUndefined */ "../../node_modules/lodash-es/isUndefined.js"); /* harmony import */ var lodash_es_includes__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! lodash-es/includes */ "../../node_modules/lodash-es/includes.js"); /* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! invariant */ "../../node_modules/invariant/browser.js"); /* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_6__); /* harmony import */ var _combineActions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./combineActions */ "../../node_modules/redux-actions/es/combineActions.js"); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); function handleAction(type) { var reducer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : lodash_es_identity__WEBPACK_IMPORTED_MODULE_2__["default"]; var defaultState = arguments[2]; var types = type.toString().split(_combineActions__WEBPACK_IMPORTED_MODULE_7__["ACTION_TYPE_DELIMITER"]); invariant__WEBPACK_IMPORTED_MODULE_6___default()(!Object(lodash_es_isUndefined__WEBPACK_IMPORTED_MODULE_4__["default"])(defaultState), 'defaultState for reducer handling ' + types.join(', ') + ' should be defined'); invariant__WEBPACK_IMPORTED_MODULE_6___default()(Object(lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_0__["default"])(reducer) || Object(lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_1__["default"])(reducer), 'Expected reducer to be a function or object with next and throw reducers'); var _ref = Object(lodash_es_isFunction__WEBPACK_IMPORTED_MODULE_0__["default"])(reducer) ? [reducer, reducer] : [reducer.next, reducer.throw].map(function (aReducer) { return Object(lodash_es_isNil__WEBPACK_IMPORTED_MODULE_3__["default"])(aReducer) ? lodash_es_identity__WEBPACK_IMPORTED_MODULE_2__["default"] : aReducer; }), _ref2 = _slicedToArray(_ref, 2), nextReducer = _ref2[0], throwReducer = _ref2[1]; return function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultState; var action = arguments[1]; var actionType = action.type; if (!actionType || !Object(lodash_es_includes__WEBPACK_IMPORTED_MODULE_5__["default"])(types, actionType.toString())) { return state; } return (action.error === true ? throwReducer : nextReducer)(state, action); }; } /***/ }), /***/ "../../node_modules/redux-actions/es/handleActions.js": /*!***************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-actions/es/handleActions.js ***! \***************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return handleActions; }); /* harmony import */ var lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash-es/isPlainObject */ "../../node_modules/lodash-es/isPlainObject.js"); /* harmony import */ var lodash_es_isMap__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash-es/isMap */ "../../node_modules/lodash-es/isMap.js"); /* harmony import */ var reduce_reducers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! reduce-reducers */ "../../node_modules/reduce-reducers/dist/index.js"); /* harmony import */ var reduce_reducers__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(reduce_reducers__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! invariant */ "../../node_modules/invariant/browser.js"); /* harmony import */ var invariant__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(invariant__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var _handleAction__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./handleAction */ "../../node_modules/redux-actions/es/handleAction.js"); /* harmony import */ var _ownKeys__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./ownKeys */ "../../node_modules/redux-actions/es/ownKeys.js"); /* harmony import */ var _flattenUtils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./flattenUtils */ "../../node_modules/redux-actions/es/flattenUtils.js"); function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function get(key, x) { return Object(lodash_es_isMap__WEBPACK_IMPORTED_MODULE_1__["default"])(x) ? x.get(key) : x[key]; } function handleActions(handlers, defaultState) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; invariant__WEBPACK_IMPORTED_MODULE_3___default()(Object(lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_0__["default"])(handlers) || Object(lodash_es_isMap__WEBPACK_IMPORTED_MODULE_1__["default"])(handlers), 'Expected handlers to be a plain object.'); var flattenedReducerMap = Object(_flattenUtils__WEBPACK_IMPORTED_MODULE_6__["flattenReducerMap"])(handlers, options); var reducers = Object(_ownKeys__WEBPACK_IMPORTED_MODULE_5__["default"])(flattenedReducerMap).map(function (type) { return Object(_handleAction__WEBPACK_IMPORTED_MODULE_4__["default"])(type, get(type, flattenedReducerMap), defaultState); }); var reducer = reduce_reducers__WEBPACK_IMPORTED_MODULE_2___default.a.apply(undefined, _toConsumableArray(reducers)); return function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultState; var action = arguments[1]; return reducer(state, action); }; } /***/ }), /***/ "../../node_modules/redux-actions/es/hasGeneratorInterface.js": /*!***********************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-actions/es/hasGeneratorInterface.js ***! \***********************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return hasGeneratorInterface; }); /* harmony import */ var _ownKeys__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ownKeys */ "../../node_modules/redux-actions/es/ownKeys.js"); function hasGeneratorInterface(handler) { var keys = Object(_ownKeys__WEBPACK_IMPORTED_MODULE_0__["default"])(handler); var hasOnlyInterfaceNames = keys.every(function (ownKey) { return ownKey === 'next' || ownKey === 'throw'; }); return keys.length && keys.length <= 2 && hasOnlyInterfaceNames; } /***/ }), /***/ "../../node_modules/redux-actions/es/index.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-actions/es/index.js ***! \*******************************************************************/ /*! exports provided: createAction, createActions, handleAction, handleActions, combineActions */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _createAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createAction */ "../../node_modules/redux-actions/es/createAction.js"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "createAction", function() { return _createAction__WEBPACK_IMPORTED_MODULE_0__["default"]; }); /* harmony import */ var _handleAction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./handleAction */ "../../node_modules/redux-actions/es/handleAction.js"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "handleAction", function() { return _handleAction__WEBPACK_IMPORTED_MODULE_1__["default"]; }); /* harmony import */ var _handleActions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./handleActions */ "../../node_modules/redux-actions/es/handleActions.js"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "handleActions", function() { return _handleActions__WEBPACK_IMPORTED_MODULE_2__["default"]; }); /* harmony import */ var _combineActions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./combineActions */ "../../node_modules/redux-actions/es/combineActions.js"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "combineActions", function() { return _combineActions__WEBPACK_IMPORTED_MODULE_3__["default"]; }); /* harmony import */ var _createActions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./createActions */ "../../node_modules/redux-actions/es/createActions.js"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "createActions", function() { return _createActions__WEBPACK_IMPORTED_MODULE_4__["default"]; }); /***/ }), /***/ "../../node_modules/redux-actions/es/ownKeys.js": /*!*********************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-actions/es/ownKeys.js ***! \*********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ownKeys; }); /* harmony import */ var lodash_es_isMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash-es/isMap */ "../../node_modules/lodash-es/isMap.js"); function ownKeys(object) { if (Object(lodash_es_isMap__WEBPACK_IMPORTED_MODULE_0__["default"])(object)) { return Array.from(object.keys()); } if (typeof Reflect !== 'undefined' && typeof Reflect.ownKeys === 'function') { return Reflect.ownKeys(object); } var keys = Object.getOwnPropertyNames(object); if (typeof Object.getOwnPropertySymbols === 'function') { keys = keys.concat(Object.getOwnPropertySymbols(object)); } return keys; } /***/ }), /***/ "../../node_modules/redux-devtools-extension/index.js": /*!***************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-devtools-extension/index.js ***! \***************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var compose = __webpack_require__(/*! redux */ "../../node_modules/redux/es/index.js").compose; exports.__esModule = true; exports.composeWithDevTools = ( typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() { if (arguments.length === 0) return undefined; if (typeof arguments[0] === 'object') return compose; return compose.apply(null, arguments); } ); exports.devToolsEnhancer = ( typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function() { return function(noop) { return noop; } } ); /***/ }), /***/ "../../node_modules/redux-logger/dist/redux-logger.js": /*!***************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-logger/dist/redux-logger.js ***! \***************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; var _defineProperties = __webpack_require__(/*! babel-runtime/core-js/object/define-properties */ "../../node_modules/babel-runtime/core-js/object/define-properties.js"); var _defineProperties2 = _interopRequireDefault(_defineProperties); var _from = __webpack_require__(/*! babel-runtime/core-js/array/from */ "../../node_modules/babel-runtime/core-js/array/from.js"); var _from2 = _interopRequireDefault(_from); var _iterator = __webpack_require__(/*! babel-runtime/core-js/symbol/iterator */ "../../node_modules/babel-runtime/core-js/symbol/iterator.js"); var _iterator2 = _interopRequireDefault(_iterator); var _symbol = __webpack_require__(/*! babel-runtime/core-js/symbol */ "../../node_modules/babel-runtime/core-js/symbol.js"); var _symbol2 = _interopRequireDefault(_symbol); var _assign = __webpack_require__(/*! babel-runtime/core-js/object/assign */ "../../node_modules/babel-runtime/core-js/object/assign.js"); var _assign2 = _interopRequireDefault(_assign); var _keys = __webpack_require__(/*! babel-runtime/core-js/object/keys */ "../../node_modules/babel-runtime/core-js/object/keys.js"); var _keys2 = _interopRequireDefault(_keys); var _create = __webpack_require__(/*! babel-runtime/core-js/object/create */ "../../node_modules/babel-runtime/core-js/object/create.js"); var _create2 = _interopRequireDefault(_create); var _typeof2 = __webpack_require__(/*! babel-runtime/helpers/typeof */ "../../node_modules/babel-runtime/helpers/typeof.js"); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } !function (e, t) { "object" == ( false ? undefined : (0, _typeof3.default)(exports)) && "undefined" != typeof module ? t(exports) : true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (t), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : undefined; }(undefined, function (e) { "use strict"; function t(e, t) { e.super_ = t, e.prototype = (0, _create2.default)(t.prototype, { constructor: { value: e, enumerable: !1, writable: !0, configurable: !0 } }); }function r(e, t) { Object.defineProperty(this, "kind", { value: e, enumerable: !0 }), t && t.length && Object.defineProperty(this, "path", { value: t, enumerable: !0 }); }function n(e, t, r) { n.super_.call(this, "E", e), Object.defineProperty(this, "lhs", { value: t, enumerable: !0 }), Object.defineProperty(this, "rhs", { value: r, enumerable: !0 }); }function o(e, t) { o.super_.call(this, "N", e), Object.defineProperty(this, "rhs", { value: t, enumerable: !0 }); }function i(e, t) { i.super_.call(this, "D", e), Object.defineProperty(this, "lhs", { value: t, enumerable: !0 }); }function a(e, t, r) { a.super_.call(this, "A", e), Object.defineProperty(this, "index", { value: t, enumerable: !0 }), Object.defineProperty(this, "item", { value: r, enumerable: !0 }); }function f(e, t, r) { var n = e.slice((r || t) + 1 || e.length);return e.length = t < 0 ? e.length + t : t, e.push.apply(e, n), e; }function u(e) { var t = "undefined" == typeof e ? "undefined" : N(e);return "object" !== t ? t : e === Math ? "math" : null === e ? "null" : Array.isArray(e) ? "array" : "[object Date]" === Object.prototype.toString.call(e) ? "date" : "function" == typeof e.toString && /^\/.*\//.test(e.toString()) ? "regexp" : "object"; }function l(e, t, r, c, s, d, p) { s = s || [], p = p || [];var g = s.slice(0);if ("undefined" != typeof d) { if (c) { if ("function" == typeof c && c(g, d)) return;if ("object" === ("undefined" == typeof c ? "undefined" : N(c))) { if (c.prefilter && c.prefilter(g, d)) return;if (c.normalize) { var h = c.normalize(g, d, e, t);h && (e = h[0], t = h[1]); } } }g.push(d); }"regexp" === u(e) && "regexp" === u(t) && (e = e.toString(), t = t.toString());var y = "undefined" == typeof e ? "undefined" : N(e), v = "undefined" == typeof t ? "undefined" : N(t), b = "undefined" !== y || p && p[p.length - 1].lhs && p[p.length - 1].lhs.hasOwnProperty(d), m = "undefined" !== v || p && p[p.length - 1].rhs && p[p.length - 1].rhs.hasOwnProperty(d);if (!b && m) r(new o(g, t));else if (!m && b) r(new i(g, e));else if (u(e) !== u(t)) r(new n(g, e, t));else if ("date" === u(e) && e - t !== 0) r(new n(g, e, t));else if ("object" === y && null !== e && null !== t) { if (p.filter(function (t) { return t.lhs === e; }).length) e !== t && r(new n(g, e, t));else { if (p.push({ lhs: e, rhs: t }), Array.isArray(e)) { var w;e.length;for (w = 0; w < e.length; w++) { w >= t.length ? r(new a(g, w, new i(void 0, e[w]))) : l(e[w], t[w], r, c, g, w, p); }for (; w < t.length;) { r(new a(g, w, new o(void 0, t[w++]))); } } else { var x = (0, _keys2.default)(e), S = (0, _keys2.default)(t);x.forEach(function (n, o) { var i = S.indexOf(n);i >= 0 ? (l(e[n], t[n], r, c, g, n, p), S = f(S, i)) : l(e[n], void 0, r, c, g, n, p); }), S.forEach(function (e) { l(void 0, t[e], r, c, g, e, p); }); }p.length = p.length - 1; } } else e !== t && ("number" === y && isNaN(e) && isNaN(t) || r(new n(g, e, t))); }function c(e, t, r, n) { return n = n || [], l(e, t, function (e) { e && n.push(e); }, r), n.length ? n : void 0; }function s(e, t, r) { if (r.path && r.path.length) { var n, o = e[t], i = r.path.length - 1;for (n = 0; n < i; n++) { o = o[r.path[n]]; }switch (r.kind) {case "A": s(o[r.path[n]], r.index, r.item);break;case "D": delete o[r.path[n]];break;case "E":case "N": o[r.path[n]] = r.rhs;} } else switch (r.kind) {case "A": s(e[t], r.index, r.item);break;case "D": e = f(e, t);break;case "E":case "N": e[t] = r.rhs;}return e; }function d(e, t, r) { if (e && t && r && r.kind) { for (var n = e, o = -1, i = r.path ? r.path.length - 1 : 0; ++o < i;) { "undefined" == typeof n[r.path[o]] && (n[r.path[o]] = "number" == typeof r.path[o] ? [] : {}), n = n[r.path[o]]; }switch (r.kind) {case "A": s(r.path ? n[r.path[o]] : n, r.index, r.item);break;case "D": delete n[r.path[o]];break;case "E":case "N": n[r.path[o]] = r.rhs;} } }function p(e, t, r) { if (r.path && r.path.length) { var n, o = e[t], i = r.path.length - 1;for (n = 0; n < i; n++) { o = o[r.path[n]]; }switch (r.kind) {case "A": p(o[r.path[n]], r.index, r.item);break;case "D": o[r.path[n]] = r.lhs;break;case "E": o[r.path[n]] = r.lhs;break;case "N": delete o[r.path[n]];} } else switch (r.kind) {case "A": p(e[t], r.index, r.item);break;case "D": e[t] = r.lhs;break;case "E": e[t] = r.lhs;break;case "N": e = f(e, t);}return e; }function g(e, t, r) { if (e && t && r && r.kind) { var n, o, i = e;for (o = r.path.length - 1, n = 0; n < o; n++) { "undefined" == typeof i[r.path[n]] && (i[r.path[n]] = {}), i = i[r.path[n]]; }switch (r.kind) {case "A": p(i[r.path[n]], r.index, r.item);break;case "D": i[r.path[n]] = r.lhs;break;case "E": i[r.path[n]] = r.lhs;break;case "N": delete i[r.path[n]];} } }function h(e, t, r) { if (e && t) { var n = function n(_n) { r && !r(e, t, _n) || d(e, t, _n); };l(e, t, n); } }function y(e) { return "color: " + F[e].color + "; font-weight: bold"; }function v(e) { var t = e.kind, r = e.path, n = e.lhs, o = e.rhs, i = e.index, a = e.item;switch (t) {case "E": return [r.join("."), n, "→", o];case "N": return [r.join("."), o];case "D": return [r.join(".")];case "A": return [r.join(".") + "[" + i + "]", a];default: return [];} }function b(e, t, r, n) { var o = c(e, t);try { n ? r.groupCollapsed("diff") : r.group("diff"); } catch (e) { r.log("diff"); }o ? o.forEach(function (e) { var t = e.kind, n = v(e);r.log.apply(r, ["%c " + F[t].text, y(t)].concat(P(n))); }) : r.log("—— no diff ——");try { r.groupEnd(); } catch (e) { r.log("—— diff end —— "); } }function m(e, t, r, n) { switch ("undefined" == typeof e ? "undefined" : N(e)) {case "object": return "function" == typeof e[n] ? e[n].apply(e, P(r)) : e[n];case "function": return e(t);default: return e;} }function w(e) { var t = e.timestamp, r = e.duration;return function (e, n, o) { var i = ["action"];return i.push("%c" + String(e.type)), t && i.push("%c@ " + n), r && i.push("%c(in " + o.toFixed(2) + " ms)"), i.join(" "); }; }function x(e, t) { var r = t.logger, n = t.actionTransformer, o = t.titleFormatter, i = void 0 === o ? w(t) : o, a = t.collapsed, f = t.colors, u = t.level, l = t.diff, c = "undefined" == typeof t.titleFormatter;e.forEach(function (o, s) { var d = o.started, p = o.startedTime, g = o.action, h = o.prevState, y = o.error, v = o.took, w = o.nextState, x = e[s + 1];x && (w = x.prevState, v = x.started - d);var S = n(g), k = "function" == typeof a ? a(function () { return w; }, g, o) : a, j = D(p), E = f.title ? "color: " + f.title(S) + ";" : "", A = ["color: gray; font-weight: lighter;"];A.push(E), t.timestamp && A.push("color: gray; font-weight: lighter;"), t.duration && A.push("color: gray; font-weight: lighter;");var O = i(S, j, v);try { k ? f.title && c ? r.groupCollapsed.apply(r, ["%c " + O].concat(A)) : r.groupCollapsed(O) : f.title && c ? r.group.apply(r, ["%c " + O].concat(A)) : r.group(O); } catch (e) { r.log(O); }var N = m(u, S, [h], "prevState"), P = m(u, S, [S], "action"), C = m(u, S, [y, h], "error"), F = m(u, S, [w], "nextState");if (N) if (f.prevState) { var L = "color: " + f.prevState(h) + "; font-weight: bold";r[N]("%c prev state", L, h); } else r[N]("prev state", h);if (P) if (f.action) { var T = "color: " + f.action(S) + "; font-weight: bold";r[P]("%c action ", T, S); } else r[P]("action ", S);if (y && C) if (f.error) { var M = "color: " + f.error(y, h) + "; font-weight: bold;";r[C]("%c error ", M, y); } else r[C]("error ", y);if (F) if (f.nextState) { var _ = "color: " + f.nextState(w) + "; font-weight: bold";r[F]("%c next state", _, w); } else r[F]("next state", w);l && b(h, w, r, k);try { r.groupEnd(); } catch (e) { r.log("—— log end ——"); } }); }function S() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, t = (0, _assign2.default)({}, L, e), r = t.logger, n = t.stateTransformer, o = t.errorTransformer, i = t.predicate, a = t.logErrors, f = t.diffPredicate;if ("undefined" == typeof r) return function () { return function (e) { return function (t) { return e(t); }; }; };if (e.getState && e.dispatch) return console.error("[redux-logger] redux-logger not installed. Make sure to pass logger instance as middleware:\n// Logger with default options\nimport { logger } from 'redux-logger'\nconst store = createStore(\n reducer,\n applyMiddleware(logger)\n)\n// Or you can create your own logger with custom options http://bit.ly/redux-logger-options\nimport createLogger from 'redux-logger'\nconst logger = createLogger({\n // ...options\n});\nconst store = createStore(\n reducer,\n applyMiddleware(logger)\n)\n"), function () { return function (e) { return function (t) { return e(t); }; }; };var u = [];return function (e) { var r = e.getState;return function (e) { return function (l) { if ("function" == typeof i && !i(r, l)) return e(l);var c = {};u.push(c), c.started = O.now(), c.startedTime = new Date(), c.prevState = n(r()), c.action = l;var s = void 0;if (a) try { s = e(l); } catch (e) { c.error = o(e); } else s = e(l);c.took = O.now() - c.started, c.nextState = n(r());var d = t.diff && "function" == typeof f ? f(r, l) : t.diff;if (x(u, (0, _assign2.default)({}, t, { diff: d })), u.length = 0, c.error) throw c.error;return s; }; }; }; }var k, j, E = function E(e, t) { return new Array(t + 1).join(e); }, A = function A(e, t) { return E("0", t - e.toString().length) + e; }, D = function D(e) { return A(e.getHours(), 2) + ":" + A(e.getMinutes(), 2) + ":" + A(e.getSeconds(), 2) + "." + A(e.getMilliseconds(), 3); }, O = "undefined" != typeof performance && null !== performance && "function" == typeof performance.now ? performance : Date, N = "function" == typeof _symbol2.default && "symbol" == (0, _typeof3.default)(_iterator2.default) ? function (e) { return typeof e === "undefined" ? "undefined" : (0, _typeof3.default)(e); } : function (e) { return e && "function" == typeof _symbol2.default && e.constructor === _symbol2.default && e !== _symbol2.default.prototype ? "symbol" : typeof e === "undefined" ? "undefined" : (0, _typeof3.default)(e); }, P = function P(e) { if (Array.isArray(e)) { for (var t = 0, r = Array(e.length); t < e.length; t++) { r[t] = e[t]; }return r; }return (0, _from2.default)(e); }, C = [];k = "object" === ("undefined" == typeof global ? "undefined" : N(global)) && global ? global : "undefined" != typeof window ? window : {}, j = k.DeepDiff, j && C.push(function () { "undefined" != typeof j && k.DeepDiff === c && (k.DeepDiff = j, j = void 0); }), t(n, r), t(o, r), t(i, r), t(a, r), (0, _defineProperties2.default)(c, { diff: { value: c, enumerable: !0 }, observableDiff: { value: l, enumerable: !0 }, applyDiff: { value: h, enumerable: !0 }, applyChange: { value: d, enumerable: !0 }, revertChange: { value: g, enumerable: !0 }, isConflict: { value: function value() { return "undefined" != typeof j; }, enumerable: !0 }, noConflict: { value: function value() { return C && (C.forEach(function (e) { e(); }), C = null), c; }, enumerable: !0 } });var F = { E: { color: "#2196F3", text: "CHANGED:" }, N: { color: "#4CAF50", text: "ADDED:" }, D: { color: "#F44336", text: "DELETED:" }, A: { color: "#2196F3", text: "ARRAY:" } }, L = { level: "log", logger: console, logErrors: !0, collapsed: void 0, predicate: void 0, duration: !1, timestamp: !0, stateTransformer: function stateTransformer(e) { return e; }, actionTransformer: function actionTransformer(e) { return e; }, errorTransformer: function errorTransformer(e) { return e; }, colors: { title: function title() { return "inherit"; }, prevState: function prevState() { return "#9E9E9E"; }, action: function action() { return "#03A9F4"; }, nextState: function nextState() { return "#4CAF50"; }, error: function error() { return "#F20404"; } }, diff: !1, diffPredicate: void 0, transformer: void 0 }, T = function T() { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, t = e.dispatch, r = e.getState;return "function" == typeof t || "function" == typeof r ? S()({ dispatch: t, getState: r }) : void console.error("\n[redux-logger v3] BREAKING CHANGE\n[redux-logger v3] Since 3.0.0 redux-logger exports by default logger with default settings.\n[redux-logger v3] Change\n[redux-logger v3] import createLogger from 'redux-logger'\n[redux-logger v3] to\n[redux-logger v3] import { createLogger } from 'redux-logger'\n"); };e.defaults = L, e.createLogger = S, e.logger = T, e.default = T, Object.defineProperty(e, "__esModule", { value: !0 }); }); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "../../node_modules/redux-saga/es/effects.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/effects.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _io = __webpack_require__(/*! ./internal/io */ "../../node_modules/redux-saga/es/internal/io.js"); Object.defineProperty(exports, 'take', { enumerable: true, get: function get() { return _io.take; } }); Object.defineProperty(exports, 'takem', { enumerable: true, get: function get() { return _io.takem; } }); Object.defineProperty(exports, 'put', { enumerable: true, get: function get() { return _io.put; } }); Object.defineProperty(exports, 'all', { enumerable: true, get: function get() { return _io.all; } }); Object.defineProperty(exports, 'race', { enumerable: true, get: function get() { return _io.race; } }); Object.defineProperty(exports, 'call', { enumerable: true, get: function get() { return _io.call; } }); Object.defineProperty(exports, 'apply', { enumerable: true, get: function get() { return _io.apply; } }); Object.defineProperty(exports, 'cps', { enumerable: true, get: function get() { return _io.cps; } }); Object.defineProperty(exports, 'fork', { enumerable: true, get: function get() { return _io.fork; } }); Object.defineProperty(exports, 'spawn', { enumerable: true, get: function get() { return _io.spawn; } }); Object.defineProperty(exports, 'join', { enumerable: true, get: function get() { return _io.join; } }); Object.defineProperty(exports, 'cancel', { enumerable: true, get: function get() { return _io.cancel; } }); Object.defineProperty(exports, 'select', { enumerable: true, get: function get() { return _io.select; } }); Object.defineProperty(exports, 'actionChannel', { enumerable: true, get: function get() { return _io.actionChannel; } }); Object.defineProperty(exports, 'cancelled', { enumerable: true, get: function get() { return _io.cancelled; } }); Object.defineProperty(exports, 'flush', { enumerable: true, get: function get() { return _io.flush; } }); Object.defineProperty(exports, 'getContext', { enumerable: true, get: function get() { return _io.getContext; } }); Object.defineProperty(exports, 'setContext', { enumerable: true, get: function get() { return _io.setContext; } }); Object.defineProperty(exports, 'takeEvery', { enumerable: true, get: function get() { return _io.takeEvery; } }); Object.defineProperty(exports, 'takeLatest', { enumerable: true, get: function get() { return _io.takeLatest; } }); Object.defineProperty(exports, 'throttle', { enumerable: true, get: function get() { return _io.throttle; } }); /***/ }), /***/ "../../node_modules/redux-saga/es/index.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/index.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.utils = exports.effects = exports.CANCEL = exports.delay = exports.throttle = exports.takeLatest = exports.takeEvery = exports.buffers = exports.channel = exports.eventChannel = exports.END = exports.runSaga = undefined; var _runSaga = __webpack_require__(/*! ./internal/runSaga */ "../../node_modules/redux-saga/es/internal/runSaga.js"); Object.defineProperty(exports, 'runSaga', { enumerable: true, get: function get() { return _runSaga.runSaga; } }); var _channel = __webpack_require__(/*! ./internal/channel */ "../../node_modules/redux-saga/es/internal/channel.js"); Object.defineProperty(exports, 'END', { enumerable: true, get: function get() { return _channel.END; } }); Object.defineProperty(exports, 'eventChannel', { enumerable: true, get: function get() { return _channel.eventChannel; } }); Object.defineProperty(exports, 'channel', { enumerable: true, get: function get() { return _channel.channel; } }); var _buffers = __webpack_require__(/*! ./internal/buffers */ "../../node_modules/redux-saga/es/internal/buffers.js"); Object.defineProperty(exports, 'buffers', { enumerable: true, get: function get() { return _buffers.buffers; } }); var _sagaHelpers = __webpack_require__(/*! ./internal/sagaHelpers */ "../../node_modules/redux-saga/es/internal/sagaHelpers/index.js"); Object.defineProperty(exports, 'takeEvery', { enumerable: true, get: function get() { return _sagaHelpers.takeEvery; } }); Object.defineProperty(exports, 'takeLatest', { enumerable: true, get: function get() { return _sagaHelpers.takeLatest; } }); Object.defineProperty(exports, 'throttle', { enumerable: true, get: function get() { return _sagaHelpers.throttle; } }); var _utils = __webpack_require__(/*! ./internal/utils */ "../../node_modules/redux-saga/es/internal/utils.js"); Object.defineProperty(exports, 'delay', { enumerable: true, get: function get() { return _utils.delay; } }); Object.defineProperty(exports, 'CANCEL', { enumerable: true, get: function get() { return _utils.CANCEL; } }); var _middleware = __webpack_require__(/*! ./internal/middleware */ "../../node_modules/redux-saga/es/internal/middleware.js"); var _middleware2 = _interopRequireDefault(_middleware); var _effects = __webpack_require__(/*! ./effects */ "../../node_modules/redux-saga/es/effects.js"); var effects = _interopRequireWildcard(_effects); var _utils2 = __webpack_require__(/*! ./utils */ "../../node_modules/redux-saga/es/utils.js"); var utils = _interopRequireWildcard(_utils2); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _middleware2.default; exports.effects = effects; exports.utils = utils; /***/ }), /***/ "../../node_modules/redux-saga/es/internal/buffers.js": /*!***************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/buffers.js ***! \***************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.buffers = exports.BUFFER_OVERFLOW = undefined; var _utils = __webpack_require__(/*! ./utils */ "../../node_modules/redux-saga/es/internal/utils.js"); var BUFFER_OVERFLOW = exports.BUFFER_OVERFLOW = "Channel's Buffer overflow!"; var ON_OVERFLOW_THROW = 1; var ON_OVERFLOW_DROP = 2; var ON_OVERFLOW_SLIDE = 3; var ON_OVERFLOW_EXPAND = 4; var zeroBuffer = { isEmpty: _utils.kTrue, put: _utils.noop, take: _utils.noop }; function ringBuffer() { var limit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; var overflowAction = arguments[1]; var arr = new Array(limit); var length = 0; var pushIndex = 0; var popIndex = 0; var push = function push(it) { arr[pushIndex] = it; pushIndex = (pushIndex + 1) % limit; length++; }; var take = function take() { if (length != 0) { var it = arr[popIndex]; arr[popIndex] = null; length--; popIndex = (popIndex + 1) % limit; return it; } }; var flush = function flush() { var items = []; while (length) { items.push(take()); } return items; }; return { isEmpty: function isEmpty() { return length == 0; }, put: function put(it) { if (length < limit) { push(it); } else { var doubledLimit = void 0; switch (overflowAction) { case ON_OVERFLOW_THROW: throw new Error(BUFFER_OVERFLOW); case ON_OVERFLOW_SLIDE: arr[pushIndex] = it; pushIndex = (pushIndex + 1) % limit; popIndex = pushIndex; break; case ON_OVERFLOW_EXPAND: doubledLimit = 2 * limit; arr = flush(); length = arr.length; pushIndex = arr.length; popIndex = 0; arr.length = doubledLimit; limit = doubledLimit; push(it); break; default: // DROP } } }, take: take, flush: flush }; } var buffers = exports.buffers = { none: function none() { return zeroBuffer; }, fixed: function fixed(limit) { return ringBuffer(limit, ON_OVERFLOW_THROW); }, dropping: function dropping(limit) { return ringBuffer(limit, ON_OVERFLOW_DROP); }, sliding: function sliding(limit) { return ringBuffer(limit, ON_OVERFLOW_SLIDE); }, expanding: function expanding(initialSize) { return ringBuffer(initialSize, ON_OVERFLOW_EXPAND); } }; /***/ }), /***/ "../../node_modules/redux-saga/es/internal/channel.js": /*!***************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/channel.js ***! \***************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UNDEFINED_INPUT_ERROR = exports.INVALID_BUFFER = exports.isEnd = exports.END = undefined; var _assign = __webpack_require__(/*! babel-runtime/core-js/object/assign */ "../../node_modules/babel-runtime/core-js/object/assign.js"); var _assign2 = _interopRequireDefault(_assign); exports.emitter = emitter; exports.channel = channel; exports.eventChannel = eventChannel; exports.stdChannel = stdChannel; var _utils = __webpack_require__(/*! ./utils */ "../../node_modules/redux-saga/es/internal/utils.js"); var _buffers = __webpack_require__(/*! ./buffers */ "../../node_modules/redux-saga/es/internal/buffers.js"); var _scheduler = __webpack_require__(/*! ./scheduler */ "../../node_modules/redux-saga/es/internal/scheduler.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _extends = _assign2.default || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; var CHANNEL_END_TYPE = '@@redux-saga/CHANNEL_END'; var END = exports.END = { type: CHANNEL_END_TYPE }; var isEnd = exports.isEnd = function isEnd(a) { return a && a.type === CHANNEL_END_TYPE; }; function emitter() { var subscribers = []; function subscribe(sub) { subscribers.push(sub); return function () { return (0, _utils.remove)(subscribers, sub); }; } function emit(item) { var arr = subscribers.slice(); for (var i = 0, len = arr.length; i < len; i++) { arr[i](item); } } return { subscribe: subscribe, emit: emit }; } var INVALID_BUFFER = exports.INVALID_BUFFER = 'invalid buffer passed to channel factory function'; var UNDEFINED_INPUT_ERROR = exports.UNDEFINED_INPUT_ERROR = 'Saga was provided with an undefined action'; if (true) { exports.UNDEFINED_INPUT_ERROR = UNDEFINED_INPUT_ERROR += '\nHints:\n - check that your Action Creator returns a non-undefined value\n - if the Saga was started using runSaga, check that your subscribe source provides the action to its listeners\n '; } function channel() { var buffer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _buffers.buffers.fixed(); var closed = false; var takers = []; (0, _utils.check)(buffer, _utils.is.buffer, INVALID_BUFFER); function checkForbiddenStates() { if (closed && takers.length) { throw (0, _utils.internalErr)('Cannot have a closed channel with pending takers'); } if (takers.length && !buffer.isEmpty()) { throw (0, _utils.internalErr)('Cannot have pending takers with non empty buffer'); } } function put(input) { checkForbiddenStates(); (0, _utils.check)(input, _utils.is.notUndef, UNDEFINED_INPUT_ERROR); if (closed) { return; } if (!takers.length) { return buffer.put(input); } for (var i = 0; i < takers.length; i++) { var cb = takers[i]; if (!cb[_utils.MATCH] || cb[_utils.MATCH](input)) { takers.splice(i, 1); return cb(input); } } } function take(cb) { checkForbiddenStates(); (0, _utils.check)(cb, _utils.is.func, "channel.take's callback must be a function"); if (closed && buffer.isEmpty()) { cb(END); } else if (!buffer.isEmpty()) { cb(buffer.take()); } else { takers.push(cb); cb.cancel = function () { return (0, _utils.remove)(takers, cb); }; } } function flush(cb) { checkForbiddenStates(); // TODO: check if some new state should be forbidden now (0, _utils.check)(cb, _utils.is.func, "channel.flush' callback must be a function"); if (closed && buffer.isEmpty()) { cb(END); return; } cb(buffer.flush()); } function close() { checkForbiddenStates(); if (!closed) { closed = true; if (takers.length) { var arr = takers; takers = []; for (var i = 0, len = arr.length; i < len; i++) { arr[i](END); } } } } return { take: take, put: put, flush: flush, close: close, get __takers__() { return takers; }, get __closed__() { return closed; } }; } function eventChannel(subscribe) { var buffer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _buffers.buffers.none(); var matcher = arguments[2]; /** should be if(typeof matcher !== undefined) instead? see PR #273 for a background discussion **/ if (arguments.length > 2) { (0, _utils.check)(matcher, _utils.is.func, 'Invalid match function passed to eventChannel'); } var chan = channel(buffer); var close = function close() { if (!chan.__closed__) { if (unsubscribe) { unsubscribe(); } chan.close(); } }; var unsubscribe = subscribe(function (input) { if (isEnd(input)) { close(); return; } if (matcher && !matcher(input)) { return; } chan.put(input); }); if (chan.__closed__) { unsubscribe(); } if (!_utils.is.func(unsubscribe)) { throw new Error('in eventChannel: subscribe should return a function to unsubscribe'); } return { take: chan.take, flush: chan.flush, close: close }; } function stdChannel(subscribe) { var chan = eventChannel(function (cb) { return subscribe(function (input) { if (input[_utils.SAGA_ACTION]) { cb(input); return; } (0, _scheduler.asap)(function () { return cb(input); }); }); }); return _extends({}, chan, { take: function take(cb, matcher) { if (arguments.length > 1) { (0, _utils.check)(matcher, _utils.is.func, "channel.take's matcher argument must be a function"); cb[_utils.MATCH] = matcher; } chan.take(cb); } }); } /***/ }), /***/ "../../node_modules/redux-saga/es/internal/io.js": /*!**********************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/io.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.asEffect = exports.takem = undefined; exports.take = take; exports.put = put; exports.all = all; exports.race = race; exports.call = call; exports.apply = apply; exports.cps = cps; exports.fork = fork; exports.spawn = spawn; exports.join = join; exports.cancel = cancel; exports.select = select; exports.actionChannel = actionChannel; exports.cancelled = cancelled; exports.flush = flush; exports.getContext = getContext; exports.setContext = setContext; exports.takeEvery = takeEvery; exports.takeLatest = takeLatest; exports.throttle = throttle; var _utils = __webpack_require__(/*! ./utils */ "../../node_modules/redux-saga/es/internal/utils.js"); var _sagaHelpers = __webpack_require__(/*! ./sagaHelpers */ "../../node_modules/redux-saga/es/internal/sagaHelpers/index.js"); var IO = (0, _utils.sym)('IO'); var TAKE = 'TAKE'; var PUT = 'PUT'; var ALL = 'ALL'; var RACE = 'RACE'; var CALL = 'CALL'; var CPS = 'CPS'; var FORK = 'FORK'; var JOIN = 'JOIN'; var CANCEL = 'CANCEL'; var SELECT = 'SELECT'; var ACTION_CHANNEL = 'ACTION_CHANNEL'; var CANCELLED = 'CANCELLED'; var FLUSH = 'FLUSH'; var GET_CONTEXT = 'GET_CONTEXT'; var SET_CONTEXT = 'SET_CONTEXT'; var TEST_HINT = '\n(HINT: if you are getting this errors in tests, consider using createMockTask from redux-saga/utils)'; var effect = function effect(type, payload) { var _ref; return _ref = {}, _ref[IO] = true, _ref[type] = payload, _ref; }; function take() { var patternOrChannel = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '*'; if (arguments.length) { (0, _utils.check)(arguments[0], _utils.is.notUndef, 'take(patternOrChannel): patternOrChannel is undefined'); } if (_utils.is.pattern(patternOrChannel)) { return effect(TAKE, { pattern: patternOrChannel }); } if (_utils.is.channel(patternOrChannel)) { return effect(TAKE, { channel: patternOrChannel }); } throw new Error('take(patternOrChannel): argument ' + String(patternOrChannel) + ' is not valid channel or a valid pattern'); } take.maybe = function () { var eff = take.apply(undefined, arguments); eff[TAKE].maybe = true; return eff; }; var takem = /*#__PURE__*/exports.takem = (0, _utils.deprecate)(take.maybe, /*#__PURE__*/(0, _utils.updateIncentive)('takem', 'take.maybe')); function put(channel, action) { if (arguments.length > 1) { (0, _utils.check)(channel, _utils.is.notUndef, 'put(channel, action): argument channel is undefined'); (0, _utils.check)(channel, _utils.is.channel, 'put(channel, action): argument ' + channel + ' is not a valid channel'); (0, _utils.check)(action, _utils.is.notUndef, 'put(channel, action): argument action is undefined'); } else { (0, _utils.check)(channel, _utils.is.notUndef, 'put(action): argument action is undefined'); action = channel; channel = null; } return effect(PUT, { channel: channel, action: action }); } put.resolve = function () { var eff = put.apply(undefined, arguments); eff[PUT].resolve = true; return eff; }; put.sync = (0, _utils.deprecate)(put.resolve, (0, _utils.updateIncentive)('put.sync', 'put.resolve')); function all(effects) { return effect(ALL, effects); } function race(effects) { return effect(RACE, effects); } function getFnCallDesc(meth, fn, args) { (0, _utils.check)(fn, _utils.is.notUndef, meth + ': argument fn is undefined'); var context = null; if (_utils.is.array(fn)) { var _fn = fn; context = _fn[0]; fn = _fn[1]; } else if (fn.fn) { var _fn2 = fn; context = _fn2.context; fn = _fn2.fn; } if (context && _utils.is.string(fn) && _utils.is.func(context[fn])) { fn = context[fn]; } (0, _utils.check)(fn, _utils.is.func, meth + ': argument ' + fn + ' is not a function'); return { context: context, fn: fn, args: args }; } function call(fn) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return effect(CALL, getFnCallDesc('call', fn, args)); } function apply(context, fn) { var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; return effect(CALL, getFnCallDesc('apply', { context: context, fn: fn }, args)); } function cps(fn) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } return effect(CPS, getFnCallDesc('cps', fn, args)); } function fork(fn) { for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } return effect(FORK, getFnCallDesc('fork', fn, args)); } function spawn(fn) { for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { args[_key4 - 1] = arguments[_key4]; } var eff = fork.apply(undefined, [fn].concat(args)); eff[FORK].detached = true; return eff; } function join() { for (var _len5 = arguments.length, tasks = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { tasks[_key5] = arguments[_key5]; } if (tasks.length > 1) { return all(tasks.map(function (t) { return join(t); })); } var task = tasks[0]; (0, _utils.check)(task, _utils.is.notUndef, 'join(task): argument task is undefined'); (0, _utils.check)(task, _utils.is.task, 'join(task): argument ' + task + ' is not a valid Task object ' + TEST_HINT); return effect(JOIN, task); } function cancel() { for (var _len6 = arguments.length, tasks = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { tasks[_key6] = arguments[_key6]; } if (tasks.length > 1) { return all(tasks.map(function (t) { return cancel(t); })); } var task = tasks[0]; if (tasks.length === 1) { (0, _utils.check)(task, _utils.is.notUndef, 'cancel(task): argument task is undefined'); (0, _utils.check)(task, _utils.is.task, 'cancel(task): argument ' + task + ' is not a valid Task object ' + TEST_HINT); } return effect(CANCEL, task || _utils.SELF_CANCELLATION); } function select(selector) { for (var _len7 = arguments.length, args = Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) { args[_key7 - 1] = arguments[_key7]; } if (arguments.length === 0) { selector = _utils.ident; } else { (0, _utils.check)(selector, _utils.is.notUndef, 'select(selector,[...]): argument selector is undefined'); (0, _utils.check)(selector, _utils.is.func, 'select(selector,[...]): argument ' + selector + ' is not a function'); } return effect(SELECT, { selector: selector, args: args }); } /** channel(pattern, [buffer]) => creates an event channel for store actions **/ function actionChannel(pattern, buffer) { (0, _utils.check)(pattern, _utils.is.notUndef, 'actionChannel(pattern,...): argument pattern is undefined'); if (arguments.length > 1) { (0, _utils.check)(buffer, _utils.is.notUndef, 'actionChannel(pattern, buffer): argument buffer is undefined'); (0, _utils.check)(buffer, _utils.is.buffer, 'actionChannel(pattern, buffer): argument ' + buffer + ' is not a valid buffer'); } return effect(ACTION_CHANNEL, { pattern: pattern, buffer: buffer }); } function cancelled() { return effect(CANCELLED, {}); } function flush(channel) { (0, _utils.check)(channel, _utils.is.channel, 'flush(channel): argument ' + channel + ' is not valid channel'); return effect(FLUSH, channel); } function getContext(prop) { (0, _utils.check)(prop, _utils.is.string, 'getContext(prop): argument ' + prop + ' is not a string'); return effect(GET_CONTEXT, prop); } function setContext(props) { (0, _utils.check)(props, _utils.is.object, (0, _utils.createSetContextWarning)(null, props)); return effect(SET_CONTEXT, props); } function takeEvery(patternOrChannel, worker) { for (var _len8 = arguments.length, args = Array(_len8 > 2 ? _len8 - 2 : 0), _key8 = 2; _key8 < _len8; _key8++) { args[_key8 - 2] = arguments[_key8]; } return fork.apply(undefined, [_sagaHelpers.takeEveryHelper, patternOrChannel, worker].concat(args)); } function takeLatest(patternOrChannel, worker) { for (var _len9 = arguments.length, args = Array(_len9 > 2 ? _len9 - 2 : 0), _key9 = 2; _key9 < _len9; _key9++) { args[_key9 - 2] = arguments[_key9]; } return fork.apply(undefined, [_sagaHelpers.takeLatestHelper, patternOrChannel, worker].concat(args)); } function throttle(ms, pattern, worker) { for (var _len10 = arguments.length, args = Array(_len10 > 3 ? _len10 - 3 : 0), _key10 = 3; _key10 < _len10; _key10++) { args[_key10 - 3] = arguments[_key10]; } return fork.apply(undefined, [_sagaHelpers.throttleHelper, ms, pattern, worker].concat(args)); } var createAsEffectType = function createAsEffectType(type) { return function (effect) { return effect && effect[IO] && effect[type]; }; }; var asEffect = exports.asEffect = { take: createAsEffectType(TAKE), put: createAsEffectType(PUT), all: createAsEffectType(ALL), race: createAsEffectType(RACE), call: createAsEffectType(CALL), cps: createAsEffectType(CPS), fork: createAsEffectType(FORK), join: createAsEffectType(JOIN), cancel: createAsEffectType(CANCEL), select: createAsEffectType(SELECT), actionChannel: createAsEffectType(ACTION_CHANNEL), cancelled: createAsEffectType(CANCELLED), flush: createAsEffectType(FLUSH), getContext: createAsEffectType(GET_CONTEXT), setContext: createAsEffectType(SET_CONTEXT) }; /***/ }), /***/ "../../node_modules/redux-saga/es/internal/middleware.js": /*!******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/middleware.js ***! \******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = sagaMiddlewareFactory; var _utils = __webpack_require__(/*! ./utils */ "../../node_modules/redux-saga/es/internal/utils.js"); var _channel = __webpack_require__(/*! ./channel */ "../../node_modules/redux-saga/es/internal/channel.js"); var _runSaga = __webpack_require__(/*! ./runSaga */ "../../node_modules/redux-saga/es/internal/runSaga.js"); function _objectWithoutProperties(obj, keys) { var target = {};for (var i in obj) { if (keys.indexOf(i) >= 0) continue;if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;target[i] = obj[i]; }return target; } function sagaMiddlewareFactory() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _ref$context = _ref.context, context = _ref$context === undefined ? {} : _ref$context, options = _objectWithoutProperties(_ref, ['context']); var sagaMonitor = options.sagaMonitor, logger = options.logger, onError = options.onError; if (_utils.is.func(options)) { if (false) {} else { throw new Error('You passed a function to the Saga middleware. You are likely trying to start a Saga by directly passing it to the middleware. This is no longer possible starting from 0.10.0. To run a Saga, you must do it dynamically AFTER mounting the middleware into the store.\n Example:\n import createSagaMiddleware from \'redux-saga\'\n ... other imports\n\n const sagaMiddleware = createSagaMiddleware()\n const store = createStore(reducer, applyMiddleware(sagaMiddleware))\n sagaMiddleware.run(saga, ...args)\n '); } } if (logger && !_utils.is.func(logger)) { throw new Error('`options.logger` passed to the Saga middleware is not a function!'); } if ("development" === 'development' && options.onerror) { throw new Error('`options.onerror` was removed. Use `options.onError` instead.'); } if (onError && !_utils.is.func(onError)) { throw new Error('`options.onError` passed to the Saga middleware is not a function!'); } if (options.emitter && !_utils.is.func(options.emitter)) { throw new Error('`options.emitter` passed to the Saga middleware is not a function!'); } function sagaMiddleware(_ref2) { var getState = _ref2.getState, dispatch = _ref2.dispatch; var sagaEmitter = (0, _channel.emitter)(); sagaEmitter.emit = (options.emitter || _utils.ident)(sagaEmitter.emit); sagaMiddleware.run = _runSaga.runSaga.bind(null, { context: context, subscribe: sagaEmitter.subscribe, dispatch: dispatch, getState: getState, sagaMonitor: sagaMonitor, logger: logger, onError: onError }); return function (next) { return function (action) { if (sagaMonitor && sagaMonitor.actionDispatched) { sagaMonitor.actionDispatched(action); } var result = next(action); // hit reducers sagaEmitter.emit(action); return result; }; }; } sagaMiddleware.run = function () { throw new Error('Before running a Saga, you must mount the Saga middleware on the Store using applyMiddleware'); }; sagaMiddleware.setContext = function (props) { (0, _utils.check)(props, _utils.is.object, (0, _utils.createSetContextWarning)('sagaMiddleware', props)); _utils.object.assign(context, props); }; return sagaMiddleware; } /***/ }), /***/ "../../node_modules/redux-saga/es/internal/proc.js": /*!************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/proc.js ***! \************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TASK_CANCEL = exports.CHANNEL_END = exports.NOT_ITERATOR_ERROR = undefined; var _keys = __webpack_require__(/*! babel-runtime/core-js/object/keys */ "../../node_modules/babel-runtime/core-js/object/keys.js"); var _keys2 = _interopRequireDefault(_keys); var _create = __webpack_require__(/*! babel-runtime/core-js/object/create */ "../../node_modules/babel-runtime/core-js/object/create.js"); var _create2 = _interopRequireDefault(_create); var _defineProperty = __webpack_require__(/*! babel-runtime/core-js/object/define-property */ "../../node_modules/babel-runtime/core-js/object/define-property.js"); var _defineProperty2 = _interopRequireDefault(_defineProperty); var _iterator = __webpack_require__(/*! babel-runtime/core-js/symbol/iterator */ "../../node_modules/babel-runtime/core-js/symbol/iterator.js"); var _iterator2 = _interopRequireDefault(_iterator); var _typeof3 = __webpack_require__(/*! babel-runtime/helpers/typeof */ "../../node_modules/babel-runtime/helpers/typeof.js"); var _typeof4 = _interopRequireDefault(_typeof3); var _symbol = __webpack_require__(/*! babel-runtime/core-js/symbol */ "../../node_modules/babel-runtime/core-js/symbol.js"); var _symbol2 = _interopRequireDefault(_symbol); var _assign = __webpack_require__(/*! babel-runtime/core-js/object/assign */ "../../node_modules/babel-runtime/core-js/object/assign.js"); var _assign2 = _interopRequireDefault(_assign); exports.default = proc; var _utils = __webpack_require__(/*! ./utils */ "../../node_modules/redux-saga/es/internal/utils.js"); var _scheduler = __webpack_require__(/*! ./scheduler */ "../../node_modules/redux-saga/es/internal/scheduler.js"); var _io = __webpack_require__(/*! ./io */ "../../node_modules/redux-saga/es/internal/io.js"); var _channel = __webpack_require__(/*! ./channel */ "../../node_modules/redux-saga/es/internal/channel.js"); var _buffers = __webpack_require__(/*! ./buffers */ "../../node_modules/redux-saga/es/internal/buffers.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _extends = _assign2.default || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; var _typeof = typeof _symbol2.default === "function" && (0, _typeof4.default)(_iterator2.default) === "symbol" ? function (obj) { return typeof obj === "undefined" ? "undefined" : (0, _typeof4.default)(obj); } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : (0, _typeof4.default)(obj); }; function _defineEnumerableProperties(obj, descs) { for (var key in descs) { var desc = descs[key];desc.configurable = desc.enumerable = true;if ("value" in desc) desc.writable = true;(0, _defineProperty2.default)(obj, key, desc); }return obj; } var NOT_ITERATOR_ERROR = exports.NOT_ITERATOR_ERROR = 'proc first argument (Saga function result) must be an iterator'; var CHANNEL_END = exports.CHANNEL_END = { toString: function toString() { return '@@redux-saga/CHANNEL_END'; } }; var TASK_CANCEL = exports.TASK_CANCEL = { toString: function toString() { return '@@redux-saga/TASK_CANCEL'; } }; var matchers = { wildcard: function wildcard() { return _utils.kTrue; }, default: function _default(pattern) { return (typeof pattern === 'undefined' ? 'undefined' : _typeof(pattern)) === 'symbol' ? function (input) { return input.type === pattern; } : function (input) { return input.type === String(pattern); }; }, array: function array(patterns) { return function (input) { return patterns.some(function (p) { return matcher(p)(input); }); }; }, predicate: function predicate(_predicate) { return function (input) { return _predicate(input); }; } }; function matcher(pattern) { // prettier-ignore return (pattern === '*' ? matchers.wildcard : _utils.is.array(pattern) ? matchers.array : _utils.is.stringableFunc(pattern) ? matchers.default : _utils.is.func(pattern) ? matchers.predicate : matchers.default)(pattern); } /** Used to track a parent task and its forks In the new fork model, forked tasks are attached by default to their parent We model this using the concept of Parent task && main Task main task is the main flow of the current Generator, the parent tasks is the aggregation of the main tasks + all its forked tasks. Thus the whole model represents an execution tree with multiple branches (vs the linear execution tree in sequential (non parallel) programming) A parent tasks has the following semantics - It completes if all its forks either complete or all cancelled - If it's cancelled, all forks are cancelled as well - It aborts if any uncaught error bubbles up from forks - If it completes, the return value is the one returned by the main task **/ function forkQueue(name, mainTask, cb) { var tasks = [], result = void 0, completed = false; addTask(mainTask); function abort(err) { cancelAll(); cb(err, true); } function addTask(task) { tasks.push(task); task.cont = function (res, isErr) { if (completed) { return; } (0, _utils.remove)(tasks, task); task.cont = _utils.noop; if (isErr) { abort(res); } else { if (task === mainTask) { result = res; } if (!tasks.length) { completed = true; cb(result); } } }; // task.cont.cancel = task.cancel } function cancelAll() { if (completed) { return; } completed = true; tasks.forEach(function (t) { t.cont = _utils.noop; t.cancel(); }); tasks = []; } return { addTask: addTask, cancelAll: cancelAll, abort: abort, getTasks: function getTasks() { return tasks; }, taskNames: function taskNames() { return tasks.map(function (t) { return t.name; }); } }; } function createTaskIterator(_ref) { var context = _ref.context, fn = _ref.fn, args = _ref.args; if (_utils.is.iterator(fn)) { return fn; } // catch synchronous failures; see #152 and #441 var result = void 0, error = void 0; try { result = fn.apply(context, args); } catch (err) { error = err; } // i.e. a generator function returns an iterator if (_utils.is.iterator(result)) { return result; } // do not bubble up synchronous failures for detached forks // instead create a failed task. See #152 and #441 return error ? (0, _utils.makeIterator)(function () { throw error; }) : (0, _utils.makeIterator)(function () { var pc = void 0; var eff = { done: false, value: result }; var ret = function ret(value) { return { done: true, value: value }; }; return function (arg) { if (!pc) { pc = true; return eff; } else { return ret(arg); } }; }()); } var wrapHelper = function wrapHelper(helper) { return { fn: helper }; }; function proc(iterator) { var subscribe = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () { return _utils.noop; }; var dispatch = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _utils.noop; var getState = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _utils.noop; var parentContext = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; var options = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; var parentEffectId = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; var name = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 'anonymous'; var cont = arguments[8]; (0, _utils.check)(iterator, _utils.is.iterator, NOT_ITERATOR_ERROR); var effectsString = '[...effects]'; var runParallelEffect = (0, _utils.deprecate)(runAllEffect, (0, _utils.updateIncentive)(effectsString, 'all(' + effectsString + ')')); var sagaMonitor = options.sagaMonitor, logger = options.logger, onError = options.onError; var log = logger || _utils.log; var stdChannel = (0, _channel.stdChannel)(subscribe); var taskContext = (0, _create2.default)(parentContext); /** Tracks the current effect cancellation Each time the generator progresses. calling runEffect will set a new value on it. It allows propagating cancellation to child effects **/ next.cancel = _utils.noop; /** Creates a new task descriptor for this generator, We'll also create a main task to track the main flow (besides other forked tasks) **/ var task = newTask(parentEffectId, name, iterator, cont); var mainTask = { name: name, cancel: cancelMain, isRunning: true }; var taskQueue = forkQueue(name, mainTask, end); /** cancellation of the main task. We'll simply resume the Generator with a Cancel **/ function cancelMain() { if (mainTask.isRunning && !mainTask.isCancelled) { mainTask.isCancelled = true; next(TASK_CANCEL); } } /** This may be called by a parent generator to trigger/propagate cancellation cancel all pending tasks (including the main task), then end the current task. Cancellation propagates down to the whole execution tree holded by this Parent task It's also propagated to all joiners of this task and their execution tree/joiners Cancellation is noop for terminated/Cancelled tasks tasks **/ function cancel() { /** We need to check both Running and Cancelled status Tasks can be Cancelled but still Running **/ if (iterator._isRunning && !iterator._isCancelled) { iterator._isCancelled = true; taskQueue.cancelAll(); /** Ending with a Never result will propagate the Cancellation to all joiners **/ end(TASK_CANCEL); } } /** attaches cancellation logic to this task's continuation this will permit cancellation to propagate down the call chain **/ cont && (cont.cancel = cancel); // tracks the running status iterator._isRunning = true; // kicks up the generator next(); // then return the task descriptor to the caller return task; /** This is the generator driver It's a recursive async/continuation function which calls itself until the generator terminates or throws **/ function next(arg, isErr) { // Preventive measure. If we end up here, then there is really something wrong if (!mainTask.isRunning) { throw new Error('Trying to resume an already finished generator'); } try { var result = void 0; if (isErr) { result = iterator.throw(arg); } else if (arg === TASK_CANCEL) { /** getting TASK_CANCEL automatically cancels the main task We can get this value here - By cancelling the parent task manually - By joining a Cancelled task **/ mainTask.isCancelled = true; /** Cancels the current effect; this will propagate the cancellation down to any called tasks **/ next.cancel(); /** If this Generator has a `return` method then invokes it This will jump to the finally block **/ result = _utils.is.func(iterator.return) ? iterator.return(TASK_CANCEL) : { done: true, value: TASK_CANCEL }; } else if (arg === CHANNEL_END) { // We get CHANNEL_END by taking from a channel that ended using `take` (and not `takem` used to trap End of channels) result = _utils.is.func(iterator.return) ? iterator.return() : { done: true }; } else { result = iterator.next(arg); } if (!result.done) { runEffect(result.value, parentEffectId, '', next); } else { /** This Generator has ended, terminate the main task and notify the fork queue **/ mainTask.isMainRunning = false; mainTask.cont && mainTask.cont(result.value); } } catch (error) { if (mainTask.isCancelled) { log('error', 'uncaught at ' + name, error.message); } mainTask.isMainRunning = false; mainTask.cont(error, true); } } function end(result, isErr) { iterator._isRunning = false; stdChannel.close(); if (!isErr) { if ("development" === 'development' && result === TASK_CANCEL) { log('info', name + ' has been cancelled', ''); } iterator._result = result; iterator._deferredEnd && iterator._deferredEnd.resolve(result); } else { if (result instanceof Error) { result.sagaStack = 'at ' + name + ' \n ' + (result.sagaStack || result.stack); } if (!task.cont) { log('error', 'uncaught', result.sagaStack || result.stack); if (result instanceof Error && onError) { onError(result); } } iterator._error = result; iterator._isAborted = true; iterator._deferredEnd && iterator._deferredEnd.reject(result); } task.cont && task.cont(result, isErr); task.joiners.forEach(function (j) { return j.cb(result, isErr); }); task.joiners = null; } function runEffect(effect, parentEffectId) { var label = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; var cb = arguments[3]; var effectId = (0, _utils.uid)(); sagaMonitor && sagaMonitor.effectTriggered({ effectId: effectId, parentEffectId: parentEffectId, label: label, effect: effect }); /** completion callback and cancel callback are mutually exclusive We can't cancel an already completed effect And We can't complete an already cancelled effectId **/ var effectSettled = void 0; // Completion callback passed to the appropriate effect runner function currCb(res, isErr) { if (effectSettled) { return; } effectSettled = true; cb.cancel = _utils.noop; // defensive measure if (sagaMonitor) { isErr ? sagaMonitor.effectRejected(effectId, res) : sagaMonitor.effectResolved(effectId, res); } cb(res, isErr); } // tracks down the current cancel currCb.cancel = _utils.noop; // setup cancellation logic on the parent cb cb.cancel = function () { // prevents cancelling an already completed effect if (effectSettled) { return; } effectSettled = true; /** propagates cancel downward catch uncaught cancellations errors; since we can no longer call the completion callback, log errors raised during cancellations into the console **/ try { currCb.cancel(); } catch (err) { log('error', 'uncaught at ' + name, err.message); } currCb.cancel = _utils.noop; // defensive measure sagaMonitor && sagaMonitor.effectCancelled(effectId); }; /** each effect runner must attach its own logic of cancellation to the provided callback it allows this generator to propagate cancellation downward. ATTENTION! effect runners must setup the cancel logic by setting cb.cancel = [cancelMethod] And the setup must occur before calling the callback This is a sort of inversion of control: called async functions are responsible for completing the flow by calling the provided continuation; while caller functions are responsible for aborting the current flow by calling the attached cancel function Library users can attach their own cancellation logic to promises by defining a promise[CANCEL] method in their returned promises ATTENTION! calling cancel must have no effect on an already completed or cancelled effect **/ var data = void 0; // prettier-ignore return ( // Non declarative effect _utils.is.promise(effect) ? resolvePromise(effect, currCb) : _utils.is.helper(effect) ? runForkEffect(wrapHelper(effect), effectId, currCb) : _utils.is.iterator(effect) ? resolveIterator(effect, effectId, name, currCb) // declarative effects : _utils.is.array(effect) ? runParallelEffect(effect, effectId, currCb) : (data = _io.asEffect.take(effect)) ? runTakeEffect(data, currCb) : (data = _io.asEffect.put(effect)) ? runPutEffect(data, currCb) : (data = _io.asEffect.all(effect)) ? runAllEffect(data, effectId, currCb) : (data = _io.asEffect.race(effect)) ? runRaceEffect(data, effectId, currCb) : (data = _io.asEffect.call(effect)) ? runCallEffect(data, effectId, currCb) : (data = _io.asEffect.cps(effect)) ? runCPSEffect(data, currCb) : (data = _io.asEffect.fork(effect)) ? runForkEffect(data, effectId, currCb) : (data = _io.asEffect.join(effect)) ? runJoinEffect(data, currCb) : (data = _io.asEffect.cancel(effect)) ? runCancelEffect(data, currCb) : (data = _io.asEffect.select(effect)) ? runSelectEffect(data, currCb) : (data = _io.asEffect.actionChannel(effect)) ? runChannelEffect(data, currCb) : (data = _io.asEffect.flush(effect)) ? runFlushEffect(data, currCb) : (data = _io.asEffect.cancelled(effect)) ? runCancelledEffect(data, currCb) : (data = _io.asEffect.getContext(effect)) ? runGetContextEffect(data, currCb) : (data = _io.asEffect.setContext(effect)) ? runSetContextEffect(data, currCb) : /* anything else returned as is */currCb(effect) ); } function resolvePromise(promise, cb) { var cancelPromise = promise[_utils.CANCEL]; if (_utils.is.func(cancelPromise)) { cb.cancel = cancelPromise; } else if (_utils.is.func(promise.abort)) { cb.cancel = function () { return promise.abort(); }; // TODO: add support for the fetch API, whenever they get around to // adding cancel support } promise.then(cb, function (error) { return cb(error, true); }); } function resolveIterator(iterator, effectId, name, cb) { proc(iterator, subscribe, dispatch, getState, taskContext, options, effectId, name, cb); } function runTakeEffect(_ref2, cb) { var channel = _ref2.channel, pattern = _ref2.pattern, maybe = _ref2.maybe; channel = channel || stdChannel; var takeCb = function takeCb(inp) { return inp instanceof Error ? cb(inp, true) : (0, _channel.isEnd)(inp) && !maybe ? cb(CHANNEL_END) : cb(inp); }; try { channel.take(takeCb, matcher(pattern)); } catch (err) { return cb(err, true); } cb.cancel = takeCb.cancel; } function runPutEffect(_ref3, cb) { var channel = _ref3.channel, action = _ref3.action, resolve = _ref3.resolve; /** Schedule the put in case another saga is holding a lock. The put will be executed atomically. ie nested puts will execute after this put has terminated. **/ (0, _scheduler.asap)(function () { var result = void 0; try { result = (channel ? channel.put : dispatch)(action); } catch (error) { // If we have a channel or `put.resolve` was used then bubble up the error. if (channel || resolve) return cb(error, true); log('error', 'uncaught at ' + name, error.stack || error.message || error); } if (resolve && _utils.is.promise(result)) { resolvePromise(result, cb); } else { return cb(result); } }); // Put effects are non cancellables } function runCallEffect(_ref4, effectId, cb) { var context = _ref4.context, fn = _ref4.fn, args = _ref4.args; var result = void 0; // catch synchronous failures; see #152 try { result = fn.apply(context, args); } catch (error) { return cb(error, true); } return _utils.is.promise(result) ? resolvePromise(result, cb) : _utils.is.iterator(result) ? resolveIterator(result, effectId, fn.name, cb) : cb(result); } function runCPSEffect(_ref5, cb) { var context = _ref5.context, fn = _ref5.fn, args = _ref5.args; // CPS (ie node style functions) can define their own cancellation logic // by setting cancel field on the cb // catch synchronous failures; see #152 try { var cpsCb = function cpsCb(err, res) { return _utils.is.undef(err) ? cb(res) : cb(err, true); }; fn.apply(context, args.concat(cpsCb)); if (cpsCb.cancel) { cb.cancel = function () { return cpsCb.cancel(); }; } } catch (error) { return cb(error, true); } } function runForkEffect(_ref6, effectId, cb) { var context = _ref6.context, fn = _ref6.fn, args = _ref6.args, detached = _ref6.detached; var taskIterator = createTaskIterator({ context: context, fn: fn, args: args }); try { (0, _scheduler.suspend)(); var _task = proc(taskIterator, subscribe, dispatch, getState, taskContext, options, effectId, fn.name, detached ? null : _utils.noop); if (detached) { cb(_task); } else { if (taskIterator._isRunning) { taskQueue.addTask(_task); cb(_task); } else if (taskIterator._error) { taskQueue.abort(taskIterator._error); } else { cb(_task); } } } finally { (0, _scheduler.flush)(); } // Fork effects are non cancellables } function runJoinEffect(t, cb) { if (t.isRunning()) { var joiner = { task: task, cb: cb }; cb.cancel = function () { return (0, _utils.remove)(t.joiners, joiner); }; t.joiners.push(joiner); } else { t.isAborted() ? cb(t.error(), true) : cb(t.result()); } } function runCancelEffect(taskToCancel, cb) { if (taskToCancel === _utils.SELF_CANCELLATION) { taskToCancel = task; } if (taskToCancel.isRunning()) { taskToCancel.cancel(); } cb(); // cancel effects are non cancellables } function runAllEffect(effects, effectId, cb) { var keys = (0, _keys2.default)(effects); if (!keys.length) { return cb(_utils.is.array(effects) ? [] : {}); } var completedCount = 0; var completed = void 0; var results = {}; var childCbs = {}; function checkEffectEnd() { if (completedCount === keys.length) { completed = true; cb(_utils.is.array(effects) ? _utils.array.from(_extends({}, results, { length: keys.length })) : results); } } keys.forEach(function (key) { var chCbAtKey = function chCbAtKey(res, isErr) { if (completed) { return; } if (isErr || (0, _channel.isEnd)(res) || res === CHANNEL_END || res === TASK_CANCEL) { cb.cancel(); cb(res, isErr); } else { results[key] = res; completedCount++; checkEffectEnd(); } }; chCbAtKey.cancel = _utils.noop; childCbs[key] = chCbAtKey; }); cb.cancel = function () { if (!completed) { completed = true; keys.forEach(function (key) { return childCbs[key].cancel(); }); } }; keys.forEach(function (key) { return runEffect(effects[key], effectId, key, childCbs[key]); }); } function runRaceEffect(effects, effectId, cb) { var completed = void 0; var keys = (0, _keys2.default)(effects); var childCbs = {}; keys.forEach(function (key) { var chCbAtKey = function chCbAtKey(res, isErr) { if (completed) { return; } if (isErr) { // Race Auto cancellation cb.cancel(); cb(res, true); } else if (!(0, _channel.isEnd)(res) && res !== CHANNEL_END && res !== TASK_CANCEL) { var _cb; cb.cancel(); completed = true; cb((_cb = {}, _cb[key] = res, _cb)); } }; chCbAtKey.cancel = _utils.noop; childCbs[key] = chCbAtKey; }); cb.cancel = function () { // prevents unnecessary cancellation if (!completed) { completed = true; keys.forEach(function (key) { return childCbs[key].cancel(); }); } }; keys.forEach(function (key) { if (completed) { return; } runEffect(effects[key], effectId, key, childCbs[key]); }); } function runSelectEffect(_ref7, cb) { var selector = _ref7.selector, args = _ref7.args; try { var state = selector.apply(undefined, [getState()].concat(args)); cb(state); } catch (error) { cb(error, true); } } function runChannelEffect(_ref8, cb) { var pattern = _ref8.pattern, buffer = _ref8.buffer; var match = matcher(pattern); match.pattern = pattern; cb((0, _channel.eventChannel)(subscribe, buffer || _buffers.buffers.fixed(), match)); } function runCancelledEffect(data, cb) { cb(!!mainTask.isCancelled); } function runFlushEffect(channel, cb) { channel.flush(cb); } function runGetContextEffect(prop, cb) { cb(taskContext[prop]); } function runSetContextEffect(props, cb) { _utils.object.assign(taskContext, props); cb(); } function newTask(id, name, iterator, cont) { var _done, _ref9, _mutatorMap; iterator._deferredEnd = null; return _ref9 = {}, _ref9[_utils.TASK] = true, _ref9.id = id, _ref9.name = name, _done = 'done', _mutatorMap = {}, _mutatorMap[_done] = _mutatorMap[_done] || {}, _mutatorMap[_done].get = function () { if (iterator._deferredEnd) { return iterator._deferredEnd.promise; } else { var def = (0, _utils.deferred)(); iterator._deferredEnd = def; if (!iterator._isRunning) { iterator._error ? def.reject(iterator._error) : def.resolve(iterator._result); } return def.promise; } }, _ref9.cont = cont, _ref9.joiners = [], _ref9.cancel = cancel, _ref9.isRunning = function isRunning() { return iterator._isRunning; }, _ref9.isCancelled = function isCancelled() { return iterator._isCancelled; }, _ref9.isAborted = function isAborted() { return iterator._isAborted; }, _ref9.result = function result() { return iterator._result; }, _ref9.error = function error() { return iterator._error; }, _ref9.setContext = function setContext(props) { (0, _utils.check)(props, _utils.is.object, (0, _utils.createSetContextWarning)('task', props)); _utils.object.assign(taskContext, props); }, _defineEnumerableProperties(_ref9, _mutatorMap), _ref9; } } /***/ }), /***/ "../../node_modules/redux-saga/es/internal/runSaga.js": /*!***************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/runSaga.js ***! \***************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.runSaga = runSaga; var _utils = __webpack_require__(/*! ./utils */ "../../node_modules/redux-saga/es/internal/utils.js"); var _proc = __webpack_require__(/*! ./proc */ "../../node_modules/redux-saga/es/internal/proc.js"); var _proc2 = _interopRequireDefault(_proc); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var RUN_SAGA_SIGNATURE = 'runSaga(storeInterface, saga, ...args)'; var NON_GENERATOR_ERR = RUN_SAGA_SIGNATURE + ': saga argument must be a Generator function!'; function runSaga(storeInterface, saga) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } var iterator = void 0; if (_utils.is.iterator(storeInterface)) { if (true) { (0, _utils.log)('warn', 'runSaga(iterator, storeInterface) has been deprecated in favor of ' + RUN_SAGA_SIGNATURE); } iterator = storeInterface; storeInterface = saga; } else { (0, _utils.check)(saga, _utils.is.func, NON_GENERATOR_ERR); iterator = saga.apply(undefined, args); (0, _utils.check)(iterator, _utils.is.iterator, NON_GENERATOR_ERR); } var _storeInterface = storeInterface, subscribe = _storeInterface.subscribe, dispatch = _storeInterface.dispatch, getState = _storeInterface.getState, context = _storeInterface.context, sagaMonitor = _storeInterface.sagaMonitor, logger = _storeInterface.logger, onError = _storeInterface.onError; var effectId = (0, _utils.uid)(); if (sagaMonitor) { // monitors are expected to have a certain interface, let's fill-in any missing ones sagaMonitor.effectTriggered = sagaMonitor.effectTriggered || _utils.noop; sagaMonitor.effectResolved = sagaMonitor.effectResolved || _utils.noop; sagaMonitor.effectRejected = sagaMonitor.effectRejected || _utils.noop; sagaMonitor.effectCancelled = sagaMonitor.effectCancelled || _utils.noop; sagaMonitor.actionDispatched = sagaMonitor.actionDispatched || _utils.noop; sagaMonitor.effectTriggered({ effectId: effectId, root: true, parentEffectId: 0, effect: { root: true, saga: saga, args: args } }); } var task = (0, _proc2.default)(iterator, subscribe, (0, _utils.wrapSagaDispatch)(dispatch), getState, context, { sagaMonitor: sagaMonitor, logger: logger, onError: onError }, effectId, saga.name); if (sagaMonitor) { sagaMonitor.effectResolved(effectId, task); } return task; } /***/ }), /***/ "../../node_modules/redux-saga/es/internal/sagaHelpers/fsmIterator.js": /*!*******************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/sagaHelpers/fsmIterator.js ***! \*******************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.qEnd = undefined; exports.safeName = safeName; exports.default = fsmIterator; var _utils = __webpack_require__(/*! ../utils */ "../../node_modules/redux-saga/es/internal/utils.js"); var done = { done: true, value: undefined }; var qEnd = exports.qEnd = {}; function safeName(patternOrChannel) { if (_utils.is.channel(patternOrChannel)) { return 'channel'; } else if (Array.isArray(patternOrChannel)) { return String(patternOrChannel.map(function (entry) { return String(entry); })); } else { return String(patternOrChannel); } } function fsmIterator(fsm, q0) { var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'iterator'; var updateState = void 0, qNext = q0; function next(arg, error) { if (qNext === qEnd) { return done; } if (error) { qNext = qEnd; throw error; } else { updateState && updateState(arg); var _fsm$qNext = fsm[qNext](), q = _fsm$qNext[0], output = _fsm$qNext[1], _updateState = _fsm$qNext[2]; qNext = q; updateState = _updateState; return qNext === qEnd ? done : output; } } return (0, _utils.makeIterator)(next, function (error) { return next(null, error); }, name, true); } /***/ }), /***/ "../../node_modules/redux-saga/es/internal/sagaHelpers/index.js": /*!*************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/sagaHelpers/index.js ***! \*************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.throttleHelper = exports.takeLatestHelper = exports.takeEveryHelper = exports.throttle = exports.takeLatest = exports.takeEvery = undefined; var _takeEvery = __webpack_require__(/*! ./takeEvery */ "../../node_modules/redux-saga/es/internal/sagaHelpers/takeEvery.js"); var _takeEvery2 = _interopRequireDefault(_takeEvery); var _takeLatest = __webpack_require__(/*! ./takeLatest */ "../../node_modules/redux-saga/es/internal/sagaHelpers/takeLatest.js"); var _takeLatest2 = _interopRequireDefault(_takeLatest); var _throttle = __webpack_require__(/*! ./throttle */ "../../node_modules/redux-saga/es/internal/sagaHelpers/throttle.js"); var _throttle2 = _interopRequireDefault(_throttle); var _utils = __webpack_require__(/*! ../utils */ "../../node_modules/redux-saga/es/internal/utils.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var deprecationWarning = function deprecationWarning(helperName) { return 'import { ' + helperName + ' } from \'redux-saga\' has been deprecated in favor of import { ' + helperName + ' } from \'redux-saga/effects\'.\nThe latter will not work with yield*, as helper effects are wrapped automatically for you in fork effect.\nTherefore yield ' + helperName + ' will return task descriptor to your saga and execute next lines of code.'; }; var takeEvery = /*#__PURE__*/(0, _utils.deprecate)(_takeEvery2.default, /*#__PURE__*/deprecationWarning('takeEvery')); var takeLatest = /*#__PURE__*/(0, _utils.deprecate)(_takeLatest2.default, /*#__PURE__*/deprecationWarning('takeLatest')); var throttle = /*#__PURE__*/(0, _utils.deprecate)(_throttle2.default, /*#__PURE__*/deprecationWarning('throttle')); exports.takeEvery = takeEvery; exports.takeLatest = takeLatest; exports.throttle = throttle; exports.takeEveryHelper = _takeEvery2.default; exports.takeLatestHelper = _takeLatest2.default; exports.throttleHelper = _throttle2.default; /***/ }), /***/ "../../node_modules/redux-saga/es/internal/sagaHelpers/takeEvery.js": /*!*****************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/sagaHelpers/takeEvery.js ***! \*****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = takeEvery; var _fsmIterator = __webpack_require__(/*! ./fsmIterator */ "../../node_modules/redux-saga/es/internal/sagaHelpers/fsmIterator.js"); var _fsmIterator2 = _interopRequireDefault(_fsmIterator); var _io = __webpack_require__(/*! ../io */ "../../node_modules/redux-saga/es/internal/io.js"); var _channel = __webpack_require__(/*! ../channel */ "../../node_modules/redux-saga/es/internal/channel.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function takeEvery(patternOrChannel, worker) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } var yTake = { done: false, value: (0, _io.take)(patternOrChannel) }; var yFork = function yFork(ac) { return { done: false, value: _io.fork.apply(undefined, [worker].concat(args, [ac])) }; }; var action = void 0, setAction = function setAction(ac) { return action = ac; }; return (0, _fsmIterator2.default)({ q1: function q1() { return ['q2', yTake, setAction]; }, q2: function q2() { return action === _channel.END ? [_fsmIterator.qEnd] : ['q1', yFork(action)]; } }, 'q1', 'takeEvery(' + (0, _fsmIterator.safeName)(patternOrChannel) + ', ' + worker.name + ')'); } /***/ }), /***/ "../../node_modules/redux-saga/es/internal/sagaHelpers/takeLatest.js": /*!******************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/sagaHelpers/takeLatest.js ***! \******************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = takeLatest; var _fsmIterator = __webpack_require__(/*! ./fsmIterator */ "../../node_modules/redux-saga/es/internal/sagaHelpers/fsmIterator.js"); var _fsmIterator2 = _interopRequireDefault(_fsmIterator); var _io = __webpack_require__(/*! ../io */ "../../node_modules/redux-saga/es/internal/io.js"); var _channel = __webpack_require__(/*! ../channel */ "../../node_modules/redux-saga/es/internal/channel.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function takeLatest(patternOrChannel, worker) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } var yTake = { done: false, value: (0, _io.take)(patternOrChannel) }; var yFork = function yFork(ac) { return { done: false, value: _io.fork.apply(undefined, [worker].concat(args, [ac])) }; }; var yCancel = function yCancel(task) { return { done: false, value: (0, _io.cancel)(task) }; }; var task = void 0, action = void 0; var setTask = function setTask(t) { return task = t; }; var setAction = function setAction(ac) { return action = ac; }; return (0, _fsmIterator2.default)({ q1: function q1() { return ['q2', yTake, setAction]; }, q2: function q2() { return action === _channel.END ? [_fsmIterator.qEnd] : task ? ['q3', yCancel(task)] : ['q1', yFork(action), setTask]; }, q3: function q3() { return ['q1', yFork(action), setTask]; } }, 'q1', 'takeLatest(' + (0, _fsmIterator.safeName)(patternOrChannel) + ', ' + worker.name + ')'); } /***/ }), /***/ "../../node_modules/redux-saga/es/internal/sagaHelpers/throttle.js": /*!****************************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/sagaHelpers/throttle.js ***! \****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = throttle; var _fsmIterator = __webpack_require__(/*! ./fsmIterator */ "../../node_modules/redux-saga/es/internal/sagaHelpers/fsmIterator.js"); var _fsmIterator2 = _interopRequireDefault(_fsmIterator); var _io = __webpack_require__(/*! ../io */ "../../node_modules/redux-saga/es/internal/io.js"); var _channel = __webpack_require__(/*! ../channel */ "../../node_modules/redux-saga/es/internal/channel.js"); var _buffers = __webpack_require__(/*! ../buffers */ "../../node_modules/redux-saga/es/internal/buffers.js"); var _utils = __webpack_require__(/*! ../utils */ "../../node_modules/redux-saga/es/internal/utils.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function throttle(delayLength, pattern, worker) { for (var _len = arguments.length, args = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) { args[_key - 3] = arguments[_key]; } var action = void 0, channel = void 0; var yActionChannel = { done: false, value: (0, _io.actionChannel)(pattern, _buffers.buffers.sliding(1)) }; var yTake = function yTake() { return { done: false, value: (0, _io.take)(channel) }; }; var yFork = function yFork(ac) { return { done: false, value: _io.fork.apply(undefined, [worker].concat(args, [ac])) }; }; var yDelay = { done: false, value: (0, _io.call)(_utils.delay, delayLength) }; var setAction = function setAction(ac) { return action = ac; }; var setChannel = function setChannel(ch) { return channel = ch; }; return (0, _fsmIterator2.default)({ q1: function q1() { return ['q2', yActionChannel, setChannel]; }, q2: function q2() { return ['q3', yTake(), setAction]; }, q3: function q3() { return action === _channel.END ? [_fsmIterator.qEnd] : ['q4', yFork(action)]; }, q4: function q4() { return ['q2', yDelay]; } }, 'q1', 'throttle(' + (0, _fsmIterator.safeName)(pattern) + ', ' + worker.name + ')'); } /***/ }), /***/ "../../node_modules/redux-saga/es/internal/scheduler.js": /*!*****************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/scheduler.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.asap = asap; exports.suspend = suspend; exports.flush = flush; var queue = []; /** Variable to hold a counting semaphore - Incrementing adds a lock and puts the scheduler in a `suspended` state (if it's not already suspended) - Decrementing releases a lock. Zero locks puts the scheduler in a `released` state. This triggers flushing the queued tasks. **/ var semaphore = 0; /** Executes a task 'atomically'. Tasks scheduled during this execution will be queued and flushed after this task has finished (assuming the scheduler endup in a released state). **/ function exec(task) { try { suspend(); task(); } finally { release(); } } /** Executes or queues a task depending on the state of the scheduler (`suspended` or `released`) **/ function asap(task) { queue.push(task); if (!semaphore) { suspend(); flush(); } } /** Puts the scheduler in a `suspended` state. Scheduled tasks will be queued until the scheduler is released. **/ function suspend() { semaphore++; } /** Puts the scheduler in a `released` state. **/ function release() { semaphore--; } /** Releases the current lock. Executes all queued tasks if the scheduler is in the released state. **/ function flush() { release(); var task = void 0; while (!semaphore && (task = queue.shift()) !== undefined) { exec(task); } } /***/ }), /***/ "../../node_modules/redux-saga/es/internal/utils.js": /*!*************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/internal/utils.js ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.cloneableGenerator = exports.wrapSagaDispatch = exports.createSetContextWarning = exports.internalErr = exports.updateIncentive = exports.uid = exports.array = exports.object = exports.is = exports.ident = exports.noop = exports.kFalse = exports.kTrue = exports.konst = exports.SELF_CANCELLATION = exports.SAGA_ACTION = exports.CANCEL = exports.MATCH = exports.HELPER = exports.TASK = exports.sym = undefined; var _defineProperty = __webpack_require__(/*! babel-runtime/core-js/object/define-property */ "../../node_modules/babel-runtime/core-js/object/define-property.js"); var _defineProperty2 = _interopRequireDefault(_defineProperty); var _promise = __webpack_require__(/*! babel-runtime/core-js/promise */ "../../node_modules/babel-runtime/core-js/promise.js"); var _promise2 = _interopRequireDefault(_promise); var _iterator = __webpack_require__(/*! babel-runtime/core-js/symbol/iterator */ "../../node_modules/babel-runtime/core-js/symbol/iterator.js"); var _iterator2 = _interopRequireDefault(_iterator); var _typeof3 = __webpack_require__(/*! babel-runtime/helpers/typeof */ "../../node_modules/babel-runtime/helpers/typeof.js"); var _typeof4 = _interopRequireDefault(_typeof3); var _symbol = __webpack_require__(/*! babel-runtime/core-js/symbol */ "../../node_modules/babel-runtime/core-js/symbol.js"); var _symbol2 = _interopRequireDefault(_symbol); var _assign = __webpack_require__(/*! babel-runtime/core-js/object/assign */ "../../node_modules/babel-runtime/core-js/object/assign.js"); var _assign2 = _interopRequireDefault(_assign); exports.check = check; exports.hasOwn = hasOwn; exports.remove = remove; exports.deferred = deferred; exports.arrayOfDeffered = arrayOfDeffered; exports.delay = delay; exports.createMockTask = createMockTask; exports.autoInc = autoInc; exports.makeIterator = makeIterator; exports.log = log; exports.deprecate = deprecate; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _extends = _assign2.default || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; var _typeof = typeof _symbol2.default === "function" && (0, _typeof4.default)(_iterator2.default) === "symbol" ? function (obj) { return typeof obj === "undefined" ? "undefined" : (0, _typeof4.default)(obj); } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : (0, _typeof4.default)(obj); }; var sym = exports.sym = function sym(id) { return '@@redux-saga/' + id; }; var TASK = exports.TASK = sym('TASK'); var HELPER = exports.HELPER = sym('HELPER'); var MATCH = exports.MATCH = sym('MATCH'); var CANCEL = exports.CANCEL = sym('CANCEL_PROMISE'); var SAGA_ACTION = exports.SAGA_ACTION = sym('SAGA_ACTION'); var SELF_CANCELLATION = exports.SELF_CANCELLATION = sym('SELF_CANCELLATION'); var konst = exports.konst = function konst(v) { return function () { return v; }; }; var kTrue = exports.kTrue = konst(true); var kFalse = exports.kFalse = konst(false); var noop = exports.noop = function noop() {}; var ident = exports.ident = function ident(v) { return v; }; function check(value, predicate, error) { if (!predicate(value)) { log('error', 'uncaught at check', error); throw new Error(error); } } var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn(object, property) { return is.notUndef(object) && hasOwnProperty.call(object, property); } var is = exports.is = { undef: function undef(v) { return v === null || v === undefined; }, notUndef: function notUndef(v) { return v !== null && v !== undefined; }, func: function func(f) { return typeof f === 'function'; }, number: function number(n) { return typeof n === 'number'; }, string: function string(s) { return typeof s === 'string'; }, array: Array.isArray, object: function object(obj) { return obj && !is.array(obj) && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object'; }, promise: function promise(p) { return p && is.func(p.then); }, iterator: function iterator(it) { return it && is.func(it.next) && is.func(it.throw); }, iterable: function iterable(it) { return it && is.func(_symbol2.default) ? is.func(it[_iterator2.default]) : is.array(it); }, task: function task(t) { return t && t[TASK]; }, observable: function observable(ob) { return ob && is.func(ob.subscribe); }, buffer: function buffer(buf) { return buf && is.func(buf.isEmpty) && is.func(buf.take) && is.func(buf.put); }, pattern: function pattern(pat) { return pat && (is.string(pat) || (typeof pat === 'undefined' ? 'undefined' : _typeof(pat)) === 'symbol' || is.func(pat) || is.array(pat)); }, channel: function channel(ch) { return ch && is.func(ch.take) && is.func(ch.close); }, helper: function helper(it) { return it && it[HELPER]; }, stringableFunc: function stringableFunc(f) { return is.func(f) && hasOwn(f, 'toString'); } }; var object = exports.object = { assign: function assign(target, source) { for (var i in source) { if (hasOwn(source, i)) { target[i] = source[i]; } } } }; function remove(array, item) { var index = array.indexOf(item); if (index >= 0) { array.splice(index, 1); } } var array = exports.array = { from: function from(obj) { var arr = Array(obj.length); for (var i in obj) { if (hasOwn(obj, i)) { arr[i] = obj[i]; } } return arr; } }; function deferred() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var def = _extends({}, props); var promise = new _promise2.default(function (resolve, reject) { def.resolve = resolve; def.reject = reject; }); def.promise = promise; return def; } function arrayOfDeffered(length) { var arr = []; for (var i = 0; i < length; i++) { arr.push(deferred()); } return arr; } function delay(ms) { var val = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var timeoutId = void 0; var promise = new _promise2.default(function (resolve) { timeoutId = setTimeout(function () { return resolve(val); }, ms); }); promise[CANCEL] = function () { return clearTimeout(timeoutId); }; return promise; } function createMockTask() { var _ref; var running = true; var _result = void 0, _error = void 0; return _ref = {}, _ref[TASK] = true, _ref.isRunning = function isRunning() { return running; }, _ref.result = function result() { return _result; }, _ref.error = function error() { return _error; }, _ref.setRunning = function setRunning(b) { return running = b; }, _ref.setResult = function setResult(r) { return _result = r; }, _ref.setError = function setError(e) { return _error = e; }, _ref; } function autoInc() { var seed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; return function () { return ++seed; }; } var uid = exports.uid = autoInc(); var kThrow = function kThrow(err) { throw err; }; var kReturn = function kReturn(value) { return { value: value, done: true }; }; function makeIterator(next) { var thro = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : kThrow; var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; var isHelper = arguments[3]; var iterator = { name: name, next: next, throw: thro, return: kReturn }; if (isHelper) { iterator[HELPER] = true; } if (typeof _symbol2.default !== 'undefined') { iterator[_iterator2.default] = function () { return iterator; }; } return iterator; } /** Print error in a useful way whether in a browser environment (with expandable error stack traces), or in a node.js environment (text-only log output) **/ function log(level, message) { var error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; /*eslint-disable no-console*/ if (typeof window === 'undefined') { console.log('redux-saga ' + level + ': ' + message + '\n' + (error && error.stack || error)); } else { console[level](message, error); } } function deprecate(fn, deprecationWarning) { return function () { if (true) log('warn', deprecationWarning); return fn.apply(undefined, arguments); }; } var updateIncentive = exports.updateIncentive = function updateIncentive(deprecated, preferred) { return deprecated + ' has been deprecated in favor of ' + preferred + ', please update your code'; }; var internalErr = exports.internalErr = function internalErr(err) { return new Error('\n redux-saga: Error checking hooks detected an inconsistent state. This is likely a bug\n in redux-saga code and not yours. Thanks for reporting this in the project\'s github repo.\n Error: ' + err + '\n'); }; var createSetContextWarning = exports.createSetContextWarning = function createSetContextWarning(ctx, props) { return (ctx ? ctx + '.' : '') + 'setContext(props): argument ' + props + ' is not a plain object'; }; var wrapSagaDispatch = exports.wrapSagaDispatch = function wrapSagaDispatch(dispatch) { return function (action) { return dispatch((0, _defineProperty2.default)(action, SAGA_ACTION, { value: true })); }; }; var cloneableGenerator = exports.cloneableGenerator = function cloneableGenerator(generatorFunc) { return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var history = []; var gen = generatorFunc.apply(undefined, args); return { next: function next(arg) { history.push(arg); return gen.next(arg); }, clone: function clone() { var clonedGen = cloneableGenerator(generatorFunc).apply(undefined, args); history.forEach(function (arg) { return clonedGen.next(arg); }); return clonedGen; }, return: function _return(value) { return gen.return(value); }, throw: function _throw(exception) { return gen.throw(exception); } }; }; }; /***/ }), /***/ "../../node_modules/redux-saga/es/utils.js": /*!****************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux-saga/es/utils.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _utils = __webpack_require__(/*! ./internal/utils */ "../../node_modules/redux-saga/es/internal/utils.js"); Object.defineProperty(exports, 'TASK', { enumerable: true, get: function get() { return _utils.TASK; } }); Object.defineProperty(exports, 'SAGA_ACTION', { enumerable: true, get: function get() { return _utils.SAGA_ACTION; } }); Object.defineProperty(exports, 'noop', { enumerable: true, get: function get() { return _utils.noop; } }); Object.defineProperty(exports, 'is', { enumerable: true, get: function get() { return _utils.is; } }); Object.defineProperty(exports, 'deferred', { enumerable: true, get: function get() { return _utils.deferred; } }); Object.defineProperty(exports, 'arrayOfDeffered', { enumerable: true, get: function get() { return _utils.arrayOfDeffered; } }); Object.defineProperty(exports, 'createMockTask', { enumerable: true, get: function get() { return _utils.createMockTask; } }); Object.defineProperty(exports, 'cloneableGenerator', { enumerable: true, get: function get() { return _utils.cloneableGenerator; } }); var _io = __webpack_require__(/*! ./internal/io */ "../../node_modules/redux-saga/es/internal/io.js"); Object.defineProperty(exports, 'asEffect', { enumerable: true, get: function get() { return _io.asEffect; } }); var _proc = __webpack_require__(/*! ./internal/proc */ "../../node_modules/redux-saga/es/internal/proc.js"); Object.defineProperty(exports, 'CHANNEL_END', { enumerable: true, get: function get() { return _proc.CHANNEL_END; } }); /***/ }), /***/ "../../node_modules/redux/es/applyMiddleware.js": /*!*********************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux/es/applyMiddleware.js ***! \*********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return applyMiddleware; }); /* harmony import */ var _compose__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./compose */ "../../node_modules/redux/es/compose.js"); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose__WEBPACK_IMPORTED_MODULE_0__["default"].apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; } /***/ }), /***/ "../../node_modules/redux/es/bindActionCreators.js": /*!************************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux/es/bindActionCreators.js ***! \************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return bindActionCreators; }); function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } /***/ }), /***/ "../../node_modules/redux/es/combineReducers.js": /*!*********************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux/es/combineReducers.js ***! \*********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return combineReducers; }); /* harmony import */ var _createStore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createStore */ "../../node_modules/redux/es/createStore.js"); /* harmony import */ var lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lodash-es/isPlainObject */ "../../node_modules/lodash-es/isPlainObject.js"); /* harmony import */ var _utils_warning__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/warning */ "../../node_modules/redux/es/utils/warning.js"); function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state. ' + 'If you want this reducer to hold no value, you can return null instead of undefined.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore__WEBPACK_IMPORTED_MODULE_0__["ActionTypes"].INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!Object(lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_1__["default"])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } function assertReducerShape(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore__WEBPACK_IMPORTED_MODULE_0__["ActionTypes"].INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined. If you don\'t want to set a value for this reducer, ' + 'you can use null instead of undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore__WEBPACK_IMPORTED_MODULE_0__["ActionTypes"].INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined, but can be null.'); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (true) { if (typeof reducers[key] === 'undefined') { Object(_utils_warning__WEBPACK_IMPORTED_MODULE_2__["default"])('No reducer provided for key "' + key + '"'); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); var unexpectedKeyCache = void 0; if (true) { unexpectedKeyCache = {}; } var shapeAssertionError = void 0; try { assertReducerShape(finalReducers); } catch (e) { shapeAssertionError = e; } return function combination() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments[1]; if (shapeAssertionError) { throw shapeAssertionError; } if (true) { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { Object(_utils_warning__WEBPACK_IMPORTED_MODULE_2__["default"])(warningMessage); } } var hasChanged = false; var nextState = {}; for (var _i = 0; _i < finalReducerKeys.length; _i++) { var _key = finalReducerKeys[_i]; var reducer = finalReducers[_key]; var previousStateForKey = state[_key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(_key, action); throw new Error(errorMessage); } nextState[_key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } /***/ }), /***/ "../../node_modules/redux/es/compose.js": /*!*************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux/es/compose.js ***! \*************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return compose; }); /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce(function (a, b) { return function () { return a(b.apply(undefined, arguments)); }; }); } /***/ }), /***/ "../../node_modules/redux/es/createStore.js": /*!*****************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux/es/createStore.js ***! \*****************************************************************/ /*! exports provided: ActionTypes, default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionTypes", function() { return ActionTypes; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return createStore; }); /* harmony import */ var lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash-es/isPlainObject */ "../../node_modules/lodash-es/isPlainObject.js"); /* harmony import */ var symbol_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! symbol-observable */ "../../node_modules/symbol-observable/es/index.js"); /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var ActionTypes = { INIT: '@@redux/INIT' /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} [enhancer] The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ };function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!Object(lodash_es_isPlainObject__WEBPACK_IMPORTED_MODULE_0__["default"])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { var listener = listeners[i]; listener(); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/tc39/proposal-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[symbol_observable__WEBPACK_IMPORTED_MODULE_1__["default"]] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[symbol_observable__WEBPACK_IMPORTED_MODULE_1__["default"]] = observable, _ref2; } /***/ }), /***/ "../../node_modules/redux/es/index.js": /*!***********************************************************!*\ !*** /home/circleci/kandy/node_modules/redux/es/index.js ***! \***********************************************************/ /*! exports provided: createStore, combineReducers, bindActionCreators, applyMiddleware, compose */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _createStore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createStore */ "../../node_modules/redux/es/createStore.js"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "createStore", function() { return _createStore__WEBPACK_IMPORTED_MODULE_0__["default"]; }); /* harmony import */ var _combineReducers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./combineReducers */ "../../node_modules/redux/es/combineReducers.js"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "combineReducers", function() { return _combineReducers__WEBPACK_IMPORTED_MODULE_1__["default"]; }); /* harmony import */ var _bindActionCreators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bindActionCreators */ "../../node_modules/redux/es/bindActionCreators.js"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bindActionCreators", function() { return _bindActionCreators__WEBPACK_IMPORTED_MODULE_2__["default"]; }); /* harmony import */ var _applyMiddleware__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./applyMiddleware */ "../../node_modules/redux/es/applyMiddleware.js"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "applyMiddleware", function() { return _applyMiddleware__WEBPACK_IMPORTED_MODULE_3__["default"]; }); /* harmony import */ var _compose__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./compose */ "../../node_modules/redux/es/compose.js"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "compose", function() { return _compose__WEBPACK_IMPORTED_MODULE_4__["default"]; }); /* harmony import */ var _utils_warning__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/warning */ "../../node_modules/redux/es/utils/warning.js"); /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if ("development" !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { Object(_utils_warning__WEBPACK_IMPORTED_MODULE_5__["default"])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); } /***/ }), /***/ "../../node_modules/redux/es/utils/warning.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/redux/es/utils/warning.js ***! \*******************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return warning; }); /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }), /***/ "../../node_modules/regenerator-runtime/runtime-module.js": /*!*******************************************************************************!*\ !*** /home/circleci/kandy/node_modules/regenerator-runtime/runtime-module.js ***! \*******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2014-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. */ // This method of obtaining a reference to the global object needs to be // kept identical to the way it is obtained in runtime.js var g = (function() { return this })() || Function("return this")(); // Use `getOwnPropertyNames` because not all browsers support calling // `hasOwnProperty` on the global `self` object in a worker. See #183. var hadRuntime = g.regeneratorRuntime && Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0; // Save the old regeneratorRuntime in case it needs to be restored later. var oldRuntime = hadRuntime && g.regeneratorRuntime; // Force reevalutation of runtime.js. g.regeneratorRuntime = undefined; module.exports = __webpack_require__(/*! ./runtime */ "../../node_modules/regenerator-runtime/runtime.js"); if (hadRuntime) { // Restore the original runtime. g.regeneratorRuntime = oldRuntime; } else { // Remove the global property added by runtime.js. try { delete g.regeneratorRuntime; } catch(e) { g.regeneratorRuntime = undefined; } } /***/ }), /***/ "../../node_modules/regenerator-runtime/runtime.js": /*!************************************************************************!*\ !*** /home/circleci/kandy/node_modules/regenerator-runtime/runtime.js ***! \************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** * Copyright (c) 2014-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. */ !(function(global) { "use strict"; var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; var inModule = typeof module === "object"; var runtime = global.regeneratorRuntime; if (runtime) { if (inModule) { // If regeneratorRuntime is defined globally and we're in a module, // make the exports object identical to regeneratorRuntime. module.exports = runtime; } // Don't bother evaluating the rest of this file if the runtime was // already defined globally. return; } // Define the runtime globally (as expected by generated code) as either // module.exports (if we're in a module) or a new, empty object. runtime = global.regeneratorRuntime = inModule ? module.exports : {}; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { prototype[method] = function(arg) { return this._invoke(method, arg); }; }); } runtime.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; runtime.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; if (!(toStringTagSymbol in genFun)) { genFun[toStringTagSymbol] = "GeneratorFunction"; } } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. runtime.awrap = function(arg) { return { __await: arg }; }; function AsyncIterator(generator) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return Promise.resolve(value.__await).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return Promise.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. If the Promise is rejected, however, the // result for this iteration will be rejected with the same // reason. Note that rejections of yielded Promises are not // thrown back into the generator function, as is the case // when an awaited Promise is rejected. This difference in // behavior between yield and await is important, because it // allows the consumer to decide what to do with the yielded // rejection (swallow it and continue, manually .throw it back // into the generator, abandon iteration, whatever). With // await, by contrast, there is no opportunity to examine the // rejection reason outside the generator function, so the // only option is to throw it from the await expression, and // let the generator function handle the exception. result.value = unwrapped; resolve(result); }, reject); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new Promise(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; runtime.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. runtime.async = function(innerFn, outerFn, self, tryLocsList) { var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList) ); return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { if (delegate.iterator.return) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } runtime.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } runtime.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined; } return ContinueSentinel; } }; })( // In sloppy mode, unbound `this` refers to the global object, fallback to // Function constructor if we're in global strict mode. That is sadly a form // of indirect eval which violates Content Security Policy. (function() { return this })() || Function("return this")() ); /***/ }), /***/ "../../node_modules/sdp-transform/lib/grammar.js": /*!**********************************************************************!*\ !*** /home/circleci/kandy/node_modules/sdp-transform/lib/grammar.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { var grammar = module.exports = { v: [{ name: 'version', reg: /^(\d*)$/ }], o: [{ //o=- 20518 0 IN IP4 203.0.113.1 // NB: sessionId will be a String in most cases because it is huge name: 'origin', reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/, names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'], format: '%s %s %d %s IP%d %s' }], // default parsing of these only (though some of these feel outdated) s: [{ name: 'name' }], i: [{ name: 'description' }], u: [{ name: 'uri' }], e: [{ name: 'email' }], p: [{ name: 'phone' }], z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly.. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly //k: [{}], // outdated thing ignored t: [{ //t=0 0 name: 'timing', reg: /^(\d*) (\d*)/, names: ['start', 'stop'], format: '%d %d' }], c: [{ //c=IN IP4 10.47.197.26 name: 'connection', reg: /^IN IP(\d) (\S*)/, names: ['version', 'ip'], format: 'IN IP%d %s' }], b: [{ //b=AS:4000 push: 'bandwidth', reg: /^(TIAS|AS|CT|RR|RS):(\d*)/, names: ['type', 'limit'], format: '%s:%s' }], m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31 // NB: special - pushes to session // TODO: rtp/fmtp should be filtered by the payloads found here? reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/, names: ['type', 'port', 'protocol', 'payloads'], format: '%s %d %s %s' }], a: [ { //a=rtpmap:110 opus/48000/2 push: 'rtp', reg: /^rtpmap:(\d*) ([\w\-\.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/, names: ['payload', 'codec', 'rate', 'encoding'], format: function (o) { return (o.encoding) ? 'rtpmap:%d %s/%s/%s': o.rate ? 'rtpmap:%d %s/%s': 'rtpmap:%d %s'; } }, { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000 //a=fmtp:111 minptime=10; useinbandfec=1 push: 'fmtp', reg: /^fmtp:(\d*) ([\S| ]*)/, names: ['payload', 'config'], format: 'fmtp:%d %s' }, { //a=control:streamid=0 name: 'control', reg: /^control:(.*)/, format: 'control:%s' }, { //a=rtcp:65179 IN IP4 193.84.77.194 name: 'rtcp', reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/, names: ['port', 'netType', 'ipVer', 'address'], format: function (o) { return (o.address != null) ? 'rtcp:%d %s IP%d %s': 'rtcp:%d'; } }, { //a=rtcp-fb:98 trr-int 100 push: 'rtcpFbTrrInt', reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/, names: ['payload', 'value'], format: 'rtcp-fb:%d trr-int %d' }, { //a=rtcp-fb:98 nack rpsi push: 'rtcpFb', reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/, names: ['payload', 'type', 'subtype'], format: function (o) { return (o.subtype != null) ? 'rtcp-fb:%s %s %s': 'rtcp-fb:%s %s'; } }, { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset //a=extmap:1/recvonly URI-gps-string push: 'ext', reg: /^extmap:(\d+)(?:\/(\w+))? (\S*)(?: (\S*))?/, names: ['value', 'direction', 'uri', 'config'], format: function (o) { return 'extmap:%d' + (o.direction ? '/%s' : '%v') + ' %s' + (o.config ? ' %s' : ''); } }, { //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32 push: 'crypto', reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/, names: ['id', 'suite', 'config', 'sessionConfig'], format: function (o) { return (o.sessionConfig != null) ? 'crypto:%d %s %s %s': 'crypto:%d %s %s'; } }, { //a=setup:actpass name: 'setup', reg: /^setup:(\w*)/, format: 'setup:%s' }, { //a=mid:1 name: 'mid', reg: /^mid:([^\s]*)/, format: 'mid:%s' }, { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a name: 'msid', reg: /^msid:(.*)/, format: 'msid:%s' }, { //a=ptime:20 name: 'ptime', reg: /^ptime:(\d*)/, format: 'ptime:%d' }, { //a=maxptime:60 name: 'maxptime', reg: /^maxptime:(\d*)/, format: 'maxptime:%d' }, { //a=sendrecv name: 'direction', reg: /^(sendrecv|recvonly|sendonly|inactive)/ }, { //a=ice-lite name: 'icelite', reg: /^(ice-lite)/ }, { //a=ice-ufrag:F7gI name: 'iceUfrag', reg: /^ice-ufrag:(\S*)/, format: 'ice-ufrag:%s' }, { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g name: 'icePwd', reg: /^ice-pwd:(\S*)/, format: 'ice-pwd:%s' }, { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33 name: 'fingerprint', reg: /^fingerprint:(\S*) (\S*)/, names: ['type', 'hash'], format: 'fingerprint:%s %s' }, { //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0 network-id 3 network-cost 10 //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0 network-id 3 network-cost 10 //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0 network-id 3 network-cost 10 //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0 network-id 3 network-cost 10 push:'candidates', reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/, names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation', 'network-id', 'network-cost'], format: function (o) { var str = 'candidate:%s %d %s %d %s %d typ %s'; str += (o.raddr != null) ? ' raddr %s rport %d' : '%v%v'; // NB: candidate has three optional chunks, so %void middles one if it's missing str += (o.tcptype != null) ? ' tcptype %s' : '%v'; if (o.generation != null) { str += ' generation %d'; } str += (o['network-id'] != null) ? ' network-id %d' : '%v'; str += (o['network-cost'] != null) ? ' network-cost %d' : '%v'; return str; } }, { //a=end-of-candidates (keep after the candidates line for readability) name: 'endOfCandidates', reg: /^(end-of-candidates)/ }, { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ... name: 'remoteCandidates', reg: /^remote-candidates:(.*)/, format: 'remote-candidates:%s' }, { //a=ice-options:google-ice name: 'iceOptions', reg: /^ice-options:(\S*)/, format: 'ice-options:%s' }, { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1 push: 'ssrcs', reg: /^ssrc:(\d*) ([\w_-]*)(?::(.*))?/, names: ['id', 'attribute', 'value'], format: function (o) { var str = 'ssrc:%d'; if (o.attribute != null) { str += ' %s'; if (o.value != null) { str += ':%s'; } } return str; } }, { //a=ssrc-group:FEC 1 2 //a=ssrc-group:FEC-FR 3004364195 1080772241 push: 'ssrcGroups', // token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39 / %x41-5A / %x5E-7E reg: /^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/, names: ['semantics', 'ssrcs'], format: 'ssrc-group:%s %s' }, { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV name: 'msidSemantic', reg: /^msid-semantic:\s?(\w*) (\S*)/, names: ['semantic', 'token'], format: 'msid-semantic: %s %s' // space after ':' is not accidental }, { //a=group:BUNDLE audio video push: 'groups', reg: /^group:(\w*) (.*)/, names: ['type', 'mids'], format: 'group:%s %s' }, { //a=rtcp-mux name: 'rtcpMux', reg: /^(rtcp-mux)/ }, { //a=rtcp-rsize name: 'rtcpRsize', reg: /^(rtcp-rsize)/ }, { //a=sctpmap:5000 webrtc-datachannel 1024 name: 'sctpmap', reg: /^sctpmap:([\w_\/]*) (\S*)(?: (\S*))?/, names: ['sctpmapNumber', 'app', 'maxMessageSize'], format: function (o) { return (o.maxMessageSize != null) ? 'sctpmap:%s %s %s' : 'sctpmap:%s %s'; } }, { //a=x-google-flag:conference name: 'xGoogleFlag', reg: /^x-google-flag:([^\s]*)/, format: 'x-google-flag:%s' }, { //a=rid:1 send max-width=1280;max-height=720;max-fps=30;depend=0 push: 'rids', reg: /^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/, names: ['id', 'direction', 'params'], format: function (o) { return (o.params) ? 'rid:%s %s %s' : 'rid:%s %s'; } }, { //a=imageattr:97 send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320] recv [x=330,y=250] //a=imageattr:* send [x=800,y=640] recv * //a=imageattr:100 recv [x=320,y=240] push: 'imageattrs', reg: new RegExp( //a=imageattr:97 '^imageattr:(\\d+|\\*)' + //send [x=800,y=640,sar=1.1,q=0.6] [x=480,y=320] '[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)' + //recv [x=330,y=250] '(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?' ), names: ['pt', 'dir1', 'attrs1', 'dir2', 'attrs2'], format: function (o) { return 'imageattr:%s %s %s' + (o.dir2 ? ' %s %s' : ''); } }, { //a=simulcast:send 1,2,3;~4,~5 recv 6;~7,~8 //a=simulcast:recv 1;4,5 send 6;7 name: 'simulcast', reg: new RegExp( //a=simulcast: '^simulcast:' + //send 1,2,3;~4,~5 '(send|recv) ([a-zA-Z0-9\\-_~;,]+)' + //space + recv 6;~7,~8 '(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?' + //end '$' ), names: ['dir1', 'list1', 'dir2', 'list2'], format: function (o) { return 'simulcast:%s %s' + (o.dir2 ? ' %s %s' : ''); } }, { //Old simulcast draft 03 (implemented by Firefox) // https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-03 //a=simulcast: recv pt=97;98 send pt=97 //a=simulcast: send rid=5;6;7 paused=6,7 name: 'simulcast_03', reg: /^simulcast:[\s\t]+([\S+\s\t]+)$/, names: ['value'], format: 'simulcast: %s' }, { //a=framerate:25 //a=framerate:29.97 name: 'framerate', reg: /^framerate:(\d+(?:$|\.\d+))/, format: 'framerate:%s' }, { // RFC4570 //a=source-filter: incl IN IP4 239.5.2.31 10.1.15.5 name: 'sourceFilter', reg: /^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/, names: ['filterMode', 'netType', 'addressTypes', 'destAddress', 'srcList'], format: 'source-filter: %s %s %s %s %s' }, { // any a= that we don't understand is kepts verbatim on media.invalid push: 'invalid', names: ['value'] } ] }; // set sensible defaults to avoid polluting the grammar with boring details Object.keys(grammar).forEach(function (key) { var objs = grammar[key]; objs.forEach(function (obj) { if (!obj.reg) { obj.reg = /(.*)/; } if (!obj.format) { obj.format = '%s'; } }); }); /***/ }), /***/ "../../node_modules/sdp-transform/lib/index.js": /*!********************************************************************!*\ !*** /home/circleci/kandy/node_modules/sdp-transform/lib/index.js ***! \********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var parser = __webpack_require__(/*! ./parser */ "../../node_modules/sdp-transform/lib/parser.js"); var writer = __webpack_require__(/*! ./writer */ "../../node_modules/sdp-transform/lib/writer.js"); exports.write = writer; exports.parse = parser.parse; exports.parseFmtpConfig = parser.parseFmtpConfig; exports.parseParams = parser.parseParams; exports.parsePayloads = parser.parsePayloads; exports.parseRemoteCandidates = parser.parseRemoteCandidates; exports.parseImageAttributes = parser.parseImageAttributes; exports.parseSimulcastStreamList = parser.parseSimulcastStreamList; /***/ }), /***/ "../../node_modules/sdp-transform/lib/parser.js": /*!*********************************************************************!*\ !*** /home/circleci/kandy/node_modules/sdp-transform/lib/parser.js ***! \*********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var toIntIfInt = function (v) { return String(Number(v)) === v ? Number(v) : v; }; var attachProperties = function (match, location, names, rawName) { if (rawName && !names) { location[rawName] = toIntIfInt(match[1]); } else { for (var i = 0; i < names.length; i += 1) { if (match[i+1] != null) { location[names[i]] = toIntIfInt(match[i+1]); } } } }; var parseReg = function (obj, location, content) { var needsBlank = obj.name && obj.names; if (obj.push && !location[obj.push]) { location[obj.push] = []; } else if (needsBlank && !location[obj.name]) { location[obj.name] = {}; } var keyLocation = obj.push ? {} : // blank object that will be pushed needsBlank ? location[obj.name] : location; // otherwise, named location or root attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name); if (obj.push) { location[obj.push].push(keyLocation); } }; var grammar = __webpack_require__(/*! ./grammar */ "../../node_modules/sdp-transform/lib/grammar.js"); var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/); exports.parse = function (sdp) { var session = {} , media = [] , location = session; // points at where properties go under (one of the above) // parse lines we understand sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) { var type = l[0]; var content = l.slice(2); if (type === 'm') { media.push({rtp: [], fmtp: []}); location = media[media.length-1]; // point at latest media line } for (var j = 0; j < (grammar[type] || []).length; j += 1) { var obj = grammar[type][j]; if (obj.reg.test(content)) { return parseReg(obj, location, content); } } }); session.media = media; // link it up return session; }; var paramReducer = function (acc, expr) { var s = expr.split(/=(.+)/, 2); if (s.length === 2) { acc[s[0]] = toIntIfInt(s[1]); } else if (s.length === 1 && expr.length > 1) { acc[s[0]] = undefined; } return acc; }; exports.parseParams = function (str) { return str.split(/\;\s?/).reduce(paramReducer, {}); }; // For backward compatibility - alias will be removed in 3.0.0 exports.parseFmtpConfig = exports.parseParams; exports.parsePayloads = function (str) { return str.split(' ').map(Number); }; exports.parseRemoteCandidates = function (str) { var candidates = []; var parts = str.split(' ').map(toIntIfInt); for (var i = 0; i < parts.length; i += 3) { candidates.push({ component: parts[i], ip: parts[i + 1], port: parts[i + 2] }); } return candidates; }; exports.parseImageAttributes = function (str) { return str.split(' ').map(function (item) { return item.substring(1, item.length-1).split(',').reduce(paramReducer, {}); }); }; exports.parseSimulcastStreamList = function (str) { return str.split(';').map(function (stream) { return stream.split(',').map(function (format) { var scid, paused = false; if (format[0] !== '~') { scid = toIntIfInt(format); } else { scid = toIntIfInt(format.substring(1, format.length)); paused = true; } return { scid: scid, paused: paused }; }); }); }; /***/ }), /***/ "../../node_modules/sdp-transform/lib/writer.js": /*!*********************************************************************!*\ !*** /home/circleci/kandy/node_modules/sdp-transform/lib/writer.js ***! \*********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var grammar = __webpack_require__(/*! ./grammar */ "../../node_modules/sdp-transform/lib/grammar.js"); // customized util.format - discards excess arguments and can void middle ones var formatRegExp = /%[sdv%]/g; var format = function (formatStr) { var i = 1; var args = arguments; var len = args.length; return formatStr.replace(formatRegExp, function (x) { if (i >= len) { return x; // missing argument } var arg = args[i]; i += 1; switch (x) { case '%%': return '%'; case '%s': return String(arg); case '%d': return Number(arg); case '%v': return ''; } }); // NB: we discard excess arguments - they are typically undefined from makeLine }; var makeLine = function (type, obj, location) { var str = obj.format instanceof Function ? (obj.format(obj.push ? location : location[obj.name])) : obj.format; var args = [type + '=' + str]; if (obj.names) { for (var i = 0; i < obj.names.length; i += 1) { var n = obj.names[i]; if (obj.name) { args.push(location[obj.name][n]); } else { // for mLine and push attributes args.push(location[obj.names[i]]); } } } else { args.push(location[obj.name]); } return format.apply(null, args); }; // RFC specified order // TODO: extend this with all the rest var defaultOuterOrder = [ 'v', 'o', 's', 'i', 'u', 'e', 'p', 'c', 'b', 't', 'r', 'z', 'a' ]; var defaultInnerOrder = ['i', 'c', 'b', 'a']; module.exports = function (session, opts) { opts = opts || {}; // ensure certain properties exist if (session.version == null) { session.version = 0; // 'v=0' must be there (only defined version atm) } if (session.name == null) { session.name = ' '; // 's= ' must be there if no meaningful name set } session.media.forEach(function (mLine) { if (mLine.payloads == null) { mLine.payloads = ''; } }); var outerOrder = opts.outerOrder || defaultOuterOrder; var innerOrder = opts.innerOrder || defaultInnerOrder; var sdp = []; // loop through outerOrder for matching properties on session outerOrder.forEach(function (type) { grammar[type].forEach(function (obj) { if (obj.name in session && session[obj.name] != null) { sdp.push(makeLine(type, obj, session)); } else if (obj.push in session && session[obj.push] != null) { session[obj.push].forEach(function (el) { sdp.push(makeLine(type, obj, el)); }); } }); }); // then for each media line, follow the innerOrder session.media.forEach(function (mLine) { sdp.push(makeLine('m', grammar.m[0], mLine)); innerOrder.forEach(function (type) { grammar[type].forEach(function (obj) { if (obj.name in mLine && mLine[obj.name] != null) { sdp.push(makeLine(type, obj, mLine)); } else if (obj.push in mLine && mLine[obj.push] != null) { mLine[obj.push].forEach(function (el) { sdp.push(makeLine(type, obj, el)); }); } }); }); }); return sdp.join('\r\n') + '\r\n'; }; /***/ }), /***/ "../../node_modules/setimmediate/setImmediate.js": /*!**********************************************************************!*\ !*** /home/circleci/kandy/node_modules/setimmediate/setImmediate.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { "use strict"; if (global.setImmediate) { return; } var nextHandle = 1; // Spec says greater than zero var tasksByHandle = {}; var currentlyRunningATask = false; var doc = global.document; var registerImmediate; function setImmediate(callback) { // Callback can either be a function or a string if (typeof callback !== "function") { callback = new Function("" + callback); } // Copy function arguments var args = new Array(arguments.length - 1); for (var i = 0; i < args.length; i++) { args[i] = arguments[i + 1]; } // Store and register the task var task = { callback: callback, args: args }; tasksByHandle[nextHandle] = task; registerImmediate(nextHandle); return nextHandle++; } function clearImmediate(handle) { delete tasksByHandle[handle]; } function run(task) { var callback = task.callback; var args = task.args; switch (args.length) { case 0: callback(); break; case 1: callback(args[0]); break; case 2: callback(args[0], args[1]); break; case 3: callback(args[0], args[1], args[2]); break; default: callback.apply(undefined, args); break; } } function runIfPresent(handle) { // From the spec: "Wait until any invocations of this algorithm started before this one have completed." // So if we're currently running a task, we'll need to delay this invocation. if (currentlyRunningATask) { // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a // "too much recursion" error. setTimeout(runIfPresent, 0, handle); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunningATask = true; try { run(task); } finally { clearImmediate(handle); currentlyRunningATask = false; } } } } function installNextTickImplementation() { registerImmediate = function(handle) { process.nextTick(function () { runIfPresent(handle); }); }; } function canUsePostMessage() { // The test against `importScripts` prevents this implementation from being installed inside a web worker, // where `global.postMessage` means something completely different and can't be used for this purpose. if (global.postMessage && !global.importScripts) { var postMessageIsAsynchronous = true; var oldOnMessage = global.onmessage; global.onmessage = function() { postMessageIsAsynchronous = false; }; global.postMessage("", "*"); global.onmessage = oldOnMessage; return postMessageIsAsynchronous; } } function installPostMessageImplementation() { // Installs an event handler on `global` for the `message` event: see // * https://developer.mozilla.org/en/DOM/window.postMessage // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages var messagePrefix = "setImmediate$" + Math.random() + "$"; var onGlobalMessage = function(event) { if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { runIfPresent(+event.data.slice(messagePrefix.length)); } }; if (global.addEventListener) { global.addEventListener("message", onGlobalMessage, false); } else { global.attachEvent("onmessage", onGlobalMessage); } registerImmediate = function(handle) { global.postMessage(messagePrefix + handle, "*"); }; } function installMessageChannelImplementation() { var channel = new MessageChannel(); channel.port1.onmessage = function(event) { var handle = event.data; runIfPresent(handle); }; registerImmediate = function(handle) { channel.port2.postMessage(handle); }; } function installReadyStateChangeImplementation() { var html = doc.documentElement; registerImmediate = function(handle) { // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var script = doc.createElement("script"); script.onreadystatechange = function () { runIfPresent(handle); script.onreadystatechange = null; html.removeChild(script); script = null; }; html.appendChild(script); }; } function installSetTimeoutImplementation() { registerImmediate = function(handle) { setTimeout(runIfPresent, 0, handle); }; } // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global); attachTo = attachTo && attachTo.setTimeout ? attachTo : global; // Don't get fooled by e.g. browserify environments. if ({}.toString.call(global.process) === "[object process]") { // For Node.js before 0.9 installNextTickImplementation(); } else if (canUsePostMessage()) { // For non-IE10 modern browsers installPostMessageImplementation(); } else if (global.MessageChannel) { // For web workers, where supported installMessageChannelImplementation(); } else if (doc && "onreadystatechange" in doc.createElement("script")) { // For IE 6–8 installReadyStateChangeImplementation(); } else { // For older browsers installSetTimeoutImplementation(); } attachTo.setImmediate = setImmediate; attachTo.clearImmediate = clearImmediate; }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self)); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./../process/browser.js */ "../../node_modules/process/browser.js"))) /***/ }), /***/ "../../node_modules/stackframe/stackframe.js": /*!******************************************************************!*\ !*** /home/circleci/kandy/node_modules/stackframe/stackframe.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function(root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers. /* istanbul ignore next */ if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} }(this, function() { 'use strict'; function _isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function _capitalize(str) { return str.charAt(0).toUpperCase() + str.substring(1); } function _getter(p) { return function() { return this[p]; }; } var booleanProps = ['isConstructor', 'isEval', 'isNative', 'isToplevel']; var numericProps = ['columnNumber', 'lineNumber']; var stringProps = ['fileName', 'functionName', 'source']; var arrayProps = ['args']; var props = booleanProps.concat(numericProps, stringProps, arrayProps); function StackFrame(obj) { if (obj instanceof Object) { for (var i = 0; i < props.length; i++) { if (obj.hasOwnProperty(props[i]) && obj[props[i]] !== undefined) { this['set' + _capitalize(props[i])](obj[props[i]]); } } } } StackFrame.prototype = { getArgs: function() { return this.args; }, setArgs: function(v) { if (Object.prototype.toString.call(v) !== '[object Array]') { throw new TypeError('Args must be an Array'); } this.args = v; }, getEvalOrigin: function() { return this.evalOrigin; }, setEvalOrigin: function(v) { if (v instanceof StackFrame) { this.evalOrigin = v; } else if (v instanceof Object) { this.evalOrigin = new StackFrame(v); } else { throw new TypeError('Eval Origin must be an Object or StackFrame'); } }, toString: function() { var functionName = this.getFunctionName() || '{anonymous}'; var args = '(' + (this.getArgs() || []).join(',') + ')'; var fileName = this.getFileName() ? ('@' + this.getFileName()) : ''; var lineNumber = _isNumber(this.getLineNumber()) ? (':' + this.getLineNumber()) : ''; var columnNumber = _isNumber(this.getColumnNumber()) ? (':' + this.getColumnNumber()) : ''; return functionName + args + fileName + lineNumber + columnNumber; } }; for (var i = 0; i < booleanProps.length; i++) { StackFrame.prototype['get' + _capitalize(booleanProps[i])] = _getter(booleanProps[i]); StackFrame.prototype['set' + _capitalize(booleanProps[i])] = (function(p) { return function(v) { this[p] = Boolean(v); }; })(booleanProps[i]); } for (var j = 0; j < numericProps.length; j++) { StackFrame.prototype['get' + _capitalize(numericProps[j])] = _getter(numericProps[j]); StackFrame.prototype['set' + _capitalize(numericProps[j])] = (function(p) { return function(v) { if (!_isNumber(v)) { throw new TypeError(p + ' must be a Number'); } this[p] = Number(v); }; })(numericProps[j]); } for (var k = 0; k < stringProps.length; k++) { StackFrame.prototype['get' + _capitalize(stringProps[k])] = _getter(stringProps[k]); StackFrame.prototype['set' + _capitalize(stringProps[k])] = (function(p) { return function(v) { this[p] = String(v); }; })(stringProps[k]); } return StackFrame; })); /***/ }), /***/ "../../node_modules/stampit/compose.js": /*!************************************************************!*\ !*** /home/circleci/kandy/node_modules/stampit/compose.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _defineProperties = __webpack_require__(/*! babel-runtime/core-js/object/define-properties */ "../../node_modules/babel-runtime/core-js/object/define-properties.js"); var _defineProperties2 = _interopRequireDefault(_defineProperties); var _create = __webpack_require__(/*! babel-runtime/core-js/object/create */ "../../node_modules/babel-runtime/core-js/object/create.js"); var _create2 = _interopRequireDefault(_create); var _getPrototypeOf = __webpack_require__(/*! babel-runtime/core-js/object/get-prototype-of */ "../../node_modules/babel-runtime/core-js/object/get-prototype-of.js"); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _keys = __webpack_require__(/*! babel-runtime/core-js/object/keys */ "../../node_modules/babel-runtime/core-js/object/keys.js"); var _keys2 = _interopRequireDefault(_keys); var _assign = __webpack_require__(/*! babel-runtime/core-js/object/assign */ "../../node_modules/babel-runtime/core-js/object/assign.js"); var _assign2 = _interopRequireDefault(_assign); var _typeof2 = __webpack_require__(/*! babel-runtime/helpers/typeof */ "../../node_modules/babel-runtime/helpers/typeof.js"); var _typeof3 = _interopRequireDefault(_typeof2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } Object.defineProperty(exports, '__esModule', { value: true }); function isObject(obj) { var type = typeof obj === 'undefined' ? 'undefined' : (0, _typeof3.default)(obj); return !!obj && (type === 'object' || type === 'function'); } function isFunction(obj) { return typeof obj === 'function'; } var assign = _assign2.default || function assign(to) { var args = arguments; for (var s = 1; s < args.length; s += 1) { var from = args[s]; if (from) { var keys = (0, _keys2.default)(from); for (var i = 0; i < keys.length; i += 1) { var key = keys[i]; to[key] = from[key]; } } } return to; }; var isArray = Array.isArray; function isPlainObject(value) { return !!value && (typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) === 'object' && (0, _getPrototypeOf2.default)(value) === Object.prototype; } function concatAssignFunctions(dstObject, srcArray, propName) { if (!isArray(srcArray)) { return; } var length = srcArray.length; var dstArray = dstObject[propName] || []; dstObject[propName] = dstArray; for (var i = 0; i < length; i += 1) { var fn = srcArray[i]; if (isFunction(fn) && dstArray.indexOf(fn) < 0) { dstArray.push(fn); } } } function combineProperties(dstObject, srcObject, propName, action) { if (!isObject(srcObject[propName])) { return; } if (!isObject(dstObject[propName])) { dstObject[propName] = {}; } action(dstObject[propName], srcObject[propName]); } function deepMergeAssign(dstObject, srcObject, propName) { combineProperties(dstObject, srcObject, propName, merge); } function mergeAssign(dstObject, srcObject, propName) { combineProperties(dstObject, srcObject, propName, assign); } /** * The 'src' argument plays the command role. * The returned values is always of the same type as the 'src'. * @param dst * @param src * @returns {*} */ function mergeOne(dst, src) { if (src === undefined) { return dst; } // According to specification arrays must be concatenated. // Also, the '.concat' creates a new array instance. Overrides the 'dst'. if (isArray(src)) { return (isArray(dst) ? dst : []).concat(src); } // Now deal with non plain 'src' object. 'src' overrides 'dst' // Note that functions are also assigned! We do not deep merge functions. if (!isPlainObject(src)) { return src; } // See if 'dst' is allowed to be mutated. If not - it's overridden with a new plain object. var returnValue = isObject(dst) ? dst : {}; var keys = (0, _keys2.default)(src); for (var i = 0; i < keys.length; i += 1) { var key = keys[i]; var srcValue = src[key]; // Do not merge properties with the 'undefined' value. if (srcValue !== undefined) { var dstValue = returnValue[key]; // Recursive calls to mergeOne() must allow only plain objects or arrays in dst var newDst = isPlainObject(dstValue) || isArray(srcValue) ? dstValue : {}; // deep merge each property. Recursion! returnValue[key] = mergeOne(newDst, srcValue); } } return returnValue; } var merge = function merge(dst) { var srcs = [], len = arguments.length - 1; while (len-- > 0) { srcs[len] = arguments[len + 1]; }return srcs.reduce(mergeOne, dst); }; /** * Creates new factory instance. * @param {Descriptor} descriptor The information about the object the factory will be creating. * @returns {Function} The new factory function. */ function createFactory(descriptor) { return function Stamp(options) { var args = [], len = arguments.length - 1; while (len-- > 0) { args[len] = arguments[len + 1]; } // Next line was optimized for most JS VMs. Please, be careful here! var obj = (0, _create2.default)(descriptor.methods || null); merge(obj, descriptor.deepProperties); assign(obj, descriptor.properties); (0, _defineProperties2.default)(obj, descriptor.propertyDescriptors || {}); if (!descriptor.initializers || descriptor.initializers.length === 0) { return obj; } if (options === undefined) { options = {}; } var inits = descriptor.initializers; var length = inits.length; for (var i = 0; i < length; i += 1) { var initializer = inits[i]; if (isFunction(initializer)) { var returnedValue = initializer.call(obj, options, { instance: obj, stamp: Stamp, args: [options].concat(args) }); obj = returnedValue === undefined ? obj : returnedValue; } } return obj; }; } /** * Returns a new stamp given a descriptor and a compose function implementation. * @param {Descriptor} [descriptor={}] The information about the object the stamp will be creating. * @param {Compose} composeFunction The "compose" function implementation. * @returns {Stamp} */ function createStamp(descriptor, composeFunction) { var Stamp = createFactory(descriptor); merge(Stamp, descriptor.staticDeepProperties); assign(Stamp, descriptor.staticProperties); (0, _defineProperties2.default)(Stamp, descriptor.staticPropertyDescriptors || {}); var composeImplementation = isFunction(Stamp.compose) ? Stamp.compose : composeFunction; Stamp.compose = function _compose() { var args = [], len = arguments.length; while (len--) { args[len] = arguments[len]; }return composeImplementation.apply(this, args); }; assign(Stamp.compose, descriptor); return Stamp; } /** * Mutates the dstDescriptor by merging the srcComposable data into it. * @param {Descriptor} dstDescriptor The descriptor object to merge into. * @param {Composable} [srcComposable] The composable * (either descriptor or stamp) to merge data form. * @returns {Descriptor} Returns the dstDescriptor argument. */ function mergeComposable(dstDescriptor, srcComposable) { var srcDescriptor = srcComposable && srcComposable.compose || srcComposable; if (!isObject(srcDescriptor)) { return dstDescriptor; } mergeAssign(dstDescriptor, srcDescriptor, 'methods'); mergeAssign(dstDescriptor, srcDescriptor, 'properties'); deepMergeAssign(dstDescriptor, srcDescriptor, 'deepProperties'); mergeAssign(dstDescriptor, srcDescriptor, 'propertyDescriptors'); mergeAssign(dstDescriptor, srcDescriptor, 'staticProperties'); deepMergeAssign(dstDescriptor, srcDescriptor, 'staticDeepProperties'); mergeAssign(dstDescriptor, srcDescriptor, 'staticPropertyDescriptors'); mergeAssign(dstDescriptor, srcDescriptor, 'configuration'); deepMergeAssign(dstDescriptor, srcDescriptor, 'deepConfiguration'); concatAssignFunctions(dstDescriptor, srcDescriptor.initializers, 'initializers'); return dstDescriptor; } /** * Given the list of composables (stamp descriptors and stamps) returns * a new stamp (composable factory function). * @typedef {Function} Compose * @param {...(Composable)} [composables] The list of composables. * @returns {Stamp} A new stamp (aka composable factory function) */ function compose() { var composables = [], len = arguments.length; while (len--) { composables[len] = arguments[len]; }var descriptor = [this].concat(composables).filter(isObject).reduce(mergeComposable, {}); return createStamp(descriptor, compose); } /** * The Stamp Descriptor * @typedef {Function|Object} Descriptor * @returns {Stamp} A new stamp based on this Stamp * @property {Object} [methods] Methods or other data used as object instances' prototype * @property {Array<Function>} [initializers] List of initializers called for each object instance * @property {Object} [properties] Shallow assigned properties of object instances * @property {Object} [deepProperties] Deeply merged properties of object instances * @property {Object} [staticProperties] Shallow assigned properties of Stamps * @property {Object} [staticDeepProperties] Deeply merged properties of Stamps * @property {Object} [configuration] Shallow assigned properties of Stamp arbitrary metadata * @property {Object} [deepConfiguration] Deeply merged properties of Stamp arbitrary metadata * @property {Object} [propertyDescriptors] ES5 Property Descriptors applied to object instances * @property {Object} [staticPropertyDescriptors] ES5 Property Descriptors applied to Stamps */ /** * The Stamp factory function * @typedef {Function} Stamp * @returns {*} Instantiated object * @property {Descriptor} compose - The Stamp descriptor and composition function */ /** * A composable object - stamp or descriptor * @typedef {Stamp|Descriptor} Composable */ exports['default'] = compose; module.exports = exports['default']; //# sourceMappingURL=compose.js.map /***/ }), /***/ "../../node_modules/symbol-observable/es/index.js": /*!***********************************************************************!*\ !*** /home/circleci/kandy/node_modules/symbol-observable/es/index.js ***! \***********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function(global, module) {/* harmony import */ var _ponyfill_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ponyfill.js */ "../../node_modules/symbol-observable/es/ponyfill.js"); /* global window */ var root; if (typeof self !== 'undefined') { root = self; } else if (typeof window !== 'undefined') { root = window; } else if (typeof global !== 'undefined') { root = global; } else if (true) { root = module; } else {} var result = Object(_ponyfill_js__WEBPACK_IMPORTED_MODULE_0__["default"])(root); /* harmony default export */ __webpack_exports__["default"] = (result); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./../../webpack/buildin/harmony-module.js */ "../../node_modules/webpack/buildin/harmony-module.js")(module))) /***/ }), /***/ "../../node_modules/symbol-observable/es/ponyfill.js": /*!**************************************************************************!*\ !*** /home/circleci/kandy/node_modules/symbol-observable/es/ponyfill.js ***! \**************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return symbolObservablePonyfill; }); function symbolObservablePonyfill(root) { var result; var Symbol = root.Symbol; if (typeof Symbol === 'function') { if (Symbol.observable) { result = Symbol.observable; } else { result = Symbol('observable'); Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ }), /***/ "../../node_modules/timers-browserify/main.js": /*!*******************************************************************!*\ !*** /home/circleci/kandy/node_modules/timers-browserify/main.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) || (typeof self !== "undefined" && self) || window; var apply = Function.prototype.apply; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, scope, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { if (timeout) { timeout.close(); } }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(scope, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // setimmediate attaches itself to the global object __webpack_require__(/*! setimmediate */ "../../node_modules/setimmediate/setImmediate.js"); // On some exotic environments, it's not clear which object `setimmediate` was // able to install onto. Search each possibility in the same order as the // `setimmediate` library. exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || (typeof global !== "undefined" && global.setImmediate) || (this && this.setImmediate); exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || (typeof global !== "undefined" && global.clearImmediate) || (this && this.clearImmediate); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "../../node_modules/utf8/utf8.js": /*!******************************************************!*\ !*** /home/circleci/kandy/node_modules/utf8/utf8.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/utf8js v2.1.2 by @mathias */ ;(function(root) { // Detect free variables `exports` var freeExports = typeof exports == 'object' && exports; // Detect free variable `module` var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; // Detect free variable `global`, from Node.js or Browserified code, // and use it as `root` var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ var stringFromCharCode = String.fromCharCode; // Taken from https://mths.be/punycode function ucs2decode(string) { var output = []; var counter = 0; var length = string.length; var value; var extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } // Taken from https://mths.be/punycode function ucs2encode(array) { var length = array.length; var index = -1; var value; var output = ''; while (++index < length) { value = array[index]; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); } return output; } function checkScalarValue(codePoint) { if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { throw Error( 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() + ' is not a scalar value' ); } } /*--------------------------------------------------------------------------*/ function createByte(codePoint, shift) { return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); } function encodeCodePoint(codePoint) { if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence return stringFromCharCode(codePoint); } var symbol = ''; if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); } else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence checkScalarValue(codePoint); symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); symbol += createByte(codePoint, 6); } else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); symbol += createByte(codePoint, 12); symbol += createByte(codePoint, 6); } symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); return symbol; } function utf8encode(string) { var codePoints = ucs2decode(string); var length = codePoints.length; var index = -1; var codePoint; var byteString = ''; while (++index < length) { codePoint = codePoints[index]; byteString += encodeCodePoint(codePoint); } return byteString; } /*--------------------------------------------------------------------------*/ function readContinuationByte() { if (byteIndex >= byteCount) { throw Error('Invalid byte index'); } var continuationByte = byteArray[byteIndex] & 0xFF; byteIndex++; if ((continuationByte & 0xC0) == 0x80) { return continuationByte & 0x3F; } // If we end up here, it’s not a continuation byte throw Error('Invalid continuation byte'); } function decodeSymbol() { var byte1; var byte2; var byte3; var byte4; var codePoint; if (byteIndex > byteCount) { throw Error('Invalid byte index'); } if (byteIndex == byteCount) { return false; } // Read first byte byte1 = byteArray[byteIndex] & 0xFF; byteIndex++; // 1-byte sequence (no continuation bytes) if ((byte1 & 0x80) == 0) { return byte1; } // 2-byte sequence if ((byte1 & 0xE0) == 0xC0) { byte2 = readContinuationByte(); codePoint = ((byte1 & 0x1F) << 6) | byte2; if (codePoint >= 0x80) { return codePoint; } else { throw Error('Invalid continuation byte'); } } // 3-byte sequence (may include unpaired surrogates) if ((byte1 & 0xF0) == 0xE0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; if (codePoint >= 0x0800) { checkScalarValue(codePoint); return codePoint; } else { throw Error('Invalid continuation byte'); } } // 4-byte sequence if ((byte1 & 0xF8) == 0xF0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); byte4 = readContinuationByte(); codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) | (byte3 << 0x06) | byte4; if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { return codePoint; } } throw Error('Invalid UTF-8 detected'); } var byteArray; var byteCount; var byteIndex; function utf8decode(byteString) { byteArray = ucs2decode(byteString); byteCount = byteArray.length; byteIndex = 0; var codePoints = []; var tmp; while ((tmp = decodeSymbol()) !== false) { codePoints.push(tmp); } return ucs2encode(codePoints); } /*--------------------------------------------------------------------------*/ var utf8 = { 'version': '2.1.2', 'encode': utf8encode, 'decode': utf8decode }; // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( true ) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return utf8; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { var key, hasOwnProperty, object; } }(this)); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/module.js */ "../../node_modules/webpack/buildin/module.js")(module), __webpack_require__(/*! ./../webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js"))) /***/ }), /***/ "../../node_modules/uuid/lib/bytesToUuid.js": /*!*****************************************************************!*\ !*** /home/circleci/kandy/node_modules/uuid/lib/bytesToUuid.js ***! \*****************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]]; } module.exports = bytesToUuid; /***/ }), /***/ "../../node_modules/uuid/lib/rng-browser.js": /*!*****************************************************************!*\ !*** /home/circleci/kandy/node_modules/uuid/lib/rng-browser.js ***! \*****************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // Unique ID creation requires a high quality random # generator. In the // browser this is a little complicated due to unknown quality of Math.random() // and inconsistent support for the `crypto` API. We do the best we can via // feature-detection // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) || (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto)); if (getRandomValues) { // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef module.exports = function whatwgRNG() { getRandomValues(rnds8); return rnds8; }; } else { // Math.random()-based (RNG) // // If all else fails, use Math.random(). It's fast, but is of unspecified // quality. var rnds = new Array(16); module.exports = function mathRNG() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) r = Math.random() * 0x100000000; rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } return rnds; }; } /***/ }), /***/ "../../node_modules/uuid/v4.js": /*!****************************************************!*\ !*** /home/circleci/kandy/node_modules/uuid/v4.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var rng = __webpack_require__(/*! ./lib/rng */ "../../node_modules/uuid/lib/rng-browser.js"); var bytesToUuid = __webpack_require__(/*! ./lib/bytesToUuid */ "../../node_modules/uuid/lib/bytesToUuid.js"); function v4(options, buf, offset) { var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } module.exports = v4; /***/ }), /***/ "../../node_modules/webpack/buildin/amd-options.js": /*!****************************************!*\ !*** (webpack)/buildin/amd-options.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */ module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(this, {})) /***/ }), /***/ "../../node_modules/webpack/buildin/global.js": /*!***********************************!*\ !*** (webpack)/buildin/global.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1, eval)("this"); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /***/ "../../node_modules/webpack/buildin/harmony-module.js": /*!*******************************************!*\ !*** (webpack)/buildin/harmony-module.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function(originalModule) { if (!originalModule.webpackPolyfill) { var module = Object.create(originalModule); // 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; } }); Object.defineProperty(module, "exports", { enumerable: true }); module.webpackPolyfill = 1; } return module; }; /***/ }), /***/ "../../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; }; /***/ }), /***/ "../fcs/next.js": /*!**********************!*\ !*** ../fcs/next.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createFcs = createFcs; var _bottlejs = __webpack_require__(/*! bottlejs */ "../../node_modules/bottlejs/dist/bottle.js"); var _bottlejs2 = _interopRequireDefault(_bottlejs); var _loadModule = __webpack_require__(/*! ./src/loadModule */ "../fcs/src/loadModule.js"); var _loadModule2 = _interopRequireDefault(_loadModule); var _module = __webpack_require__(/*! ./src/js/module */ "../fcs/src/js/module.js"); var _module2 = _interopRequireDefault(_module); var _module3 = __webpack_require__(/*! ./src/js/call/rcc/module */ "../fcs/src/js/call/rcc/module.js"); var _module4 = _interopRequireDefault(_module3); var _module5 = __webpack_require__(/*! ./src/js/call/wam/module */ "../fcs/src/js/call/wam/module.js"); var _module6 = _interopRequireDefault(_module5); var _module7 = __webpack_require__(/*! ./src/js/call/module */ "../fcs/src/js/call/module.js"); var _module8 = _interopRequireDefault(_module7); var _module9 = __webpack_require__(/*! ./src/js/webrtc/module */ "../fcs/src/js/webrtc/module.js"); var _module10 = _interopRequireDefault(_module9); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var modules = [ // Common modules, needed in all scenarios _module2.default, // Feature modules _module8.default, // Modules needed for calls. _module4.default, _module6.default, // WebRTC Adapter module. _module10.default]; // Modules function createFcs() { var bottle = new _bottlejs2.default(); // Load all modules into bottle. modules.forEach(_loadModule2.default.bind(bottle)); var container = bottle.container; var fcs = bottle.container.Core; // Build the namespaces. fcs.logManager = container.LogManager; fcs.notification = container.Notification; fcs.call = container.Call; // Convenience access to these. fcs.NotificationCallbacks = container.NotificationCallbacks; // Run any initialization code setup by the modules. bottle.resolve(container); return fcs; } /***/ }), /***/ "../fcs/src/js/cache.js": /*!******************************!*\ !*** ../fcs/src/js/cache.js ***! \******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _assign = __webpack_require__(/*! babel-runtime/core-js/object/assign */ "../../node_modules/babel-runtime/core-js/object/assign.js"); var _assign2 = _interopRequireDefault(_assign); exports.Cache = Cache; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Cache(_ref) { var _fcs = _ref.Core, _config = _ref.Config, _global = _ref.Global; function getPrefix() { var username = _fcs.getUser() || ''; var cachePrefix = _config.cachePrefix || 'FCS'; return cachePrefix + '_' + username + '_'; } (0, _assign2.default)(this, { setItem: function setItem(keyName, keyValue) { return _global.localStorage.setItem(getPrefix() + keyName, keyValue); }, getItem: function getItem(keyName) { return _global.localStorage.getItem(getPrefix() + keyName); }, removeItem: function removeItem(keyName) { return _global.localStorage.removeItem(getPrefix() + keyName); }, clear: function clear() { for (var i = 0; i < _global.localStorage.length; ++i) { var fullKeyName = localStorage.key(i); // If the key name starts with the prefix, remove it. if (fullKeyName.indexOf(getPrefix()) === 0) { _global.localStorage.removeItem(fullKeyName); } } } }); } /***/ }), /***/ "../fcs/src/js/call/call.js": /*!**********************************!*\ !*** ../fcs/src/js/call/call.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mediaErrors = undefined; exports.CallImpl = CallImpl; var _utils = __webpack_require__(/*! ../utils */ "../fcs/src/js/utils/index.js"); var mediaErrors = exports.mediaErrors = { NOT_FOUND: 1, NOT_ALLOWED: 2, OPTIONS: 3, WRONG_VERSION: 4, NOT_INITIALIZED: 5, NEW_VERSION_WARNING: 6, INVALID_PARAMETER: 7, NO_SCREENSHARING_WARNING: 8 }; /** * Call and Remote Call Control (RCC) related resources (IMRN, Click To Call, Call Disposition). * * Available for SPiDR since 3.0.0, and for RCC since 3.1.1. * * @name call * @namespace * * @memberOf fcs * * @version @{spidr.jsl.version} */ function CallImpl(_ref) { var _callManager = _ref.CallManager, _rccManager = _ref.RccManager; /** * This field provides the state of local video status like "recvonly", "sendrecv", "sendrecv" etc. * * This is a SPiDR service only member. * * @name fcs.call#localVideoState * @field * @type {number} * @since 3.0.0 */ this.localVideoState = 0; /** * This field provides the state of remote video status like "recvonly", "sendrecv", "sendrecv" etc. * * This is a SPiDR service only member. * * @name fcs.call#remoteVideoState * @field * @since 3.0.0 * @type {number} */ this.remoteVideoState = 0; /** * Sets the handler for received call notifications. * * This is a SPiDR and RCC service event. * * @name fcs.call#onReceived * @event * @param {fcs.call#Call} call The call object * @example * // SPiDR service example is as follows: * // @since 3.0.0 * // This function listens received calls * function callReceived(call) { * console.log("There is an incomming call..."); * * //This function listens call state changes in JSL API level * call.onStateChange = function(state) { * onStateChange(call, state); * }; * * //This function listens media streams in JSL API level * call.onStreamAdded = function(streamURL) { * // Remote Video is turned on by the other end of the call * // Stream URL of Remote Video stream is passed into this function * onStreamAdded(streamURL); * }; * * // Answering the incomming call * call.answer(onAnswer, onFailure, isVideoAnswer); * } * * fcs.call.onReceived = callReceived; * * // RCC service example is as follows: * // @since 3.1.1 * function onCallReceived(call) { * console.log('There is an incomming call...'); * * call.onStateChange = function (state, statusCode, reasonText, data) { * onStateChange(call, state, data); * }; * } * * fcs.call.onReceived = onCallReceived; * */ this.onReceived = null; /** * Sets the handler for received CallReplace nofitication * * This is a SPIDR service event * * @name fcs.call#onCallReplaceReceived * @event * @param {fcs.call#Call} call the new call object * @param {fcs.call#Call} call the call object to transferred * @since 4.0.0 * @example * * * function onCallReplaceReceived(newlyCreatedCall, transferredCall) { * showInfoMessage("A Replacing call has received with id: " + newlyCreatedCall.id); * * // Assigning call object to currentCall variable to use in the application * currentCall = newlyCreatedCall; * * //This function listens call state changes in JSL API level * newlyCreatedCall.call.onStateChange = function(state) { * onStateChange(newlyCreatedCall, state); * }; * * //This function listens call state changes in JSL API level * transferredCall.onMute = function(status) { * showInfoMessage("Call mute status: " + status); * }; * } * * fcs.call.onCallReplaceReceived = onCallReplaceReceived; */ this.onCallReplaceReceived = null; /** * Sets the handler for monitored device initiated outgoing call notifications. * * This is an RCC service only event. * * @name fcs.call#onOutgoingCall * @event * @since 3.1.1 * @param {fcs.call#Call} Call The call object * * @example * //This function listens monitored device initiated outgoing calls * function outgoingCall(call) { * console.log("A new call is successful!"); * * //This function listens call state changes in JSL API level * outgoingCall.onStateChange = function(state, statusCode, reasonText, data) { * onStateChange(call, state, data); * }; * * } * fcs.call.onOutgoingCall = outgoingCall; */ this.onOutgoingCall = null; /** * Monitor session is automatically and periodically extended after it is * started (see {@link fcs.call#startMonitorDevice}). In case of extend * monitor failure, given onMonitorSessionLost callback * function is called. * * This is an RCC service only method. * * @name fcs.call#setOnMonitorSessionLost * @function * @since 3.1.1 * @param {function} callback callback function for on monitor session lost * * @example * onSuccess = function () { * console.log('Start monitor success'); * * fcs.call.setOnMonitorSessionLost( * function () { * console.log('Extend monitor session lost! Please again start new monitor session.'); * }); * } * * onFailure = function () { * console.log('Start monitor failure'); * } * * fcs.call.startMonitorDevice(deviceID, onSuccess, onFailure); * */ this.setOnMonitorSessionLost = function (callback) { return _rccManager.setOnMonitorSessionLost({ callback: callback }); }; /** * @deprecated DO NOT USE, fcs.setup will do initMedia immediatly, please see {@link fcs#setup} for more information * @name fcs.call#initMedia * @function */ this.initMedia = function (onSuccess, onFailure, options) { return _callManager.initMedia({ options: options }, onSuccess, onFailure); }; /** * Starts a call. * * This is a SPiDR and RCC service method. * * @name fcs.call#startCall * @function * @param {string} from The caller's address (e.g. SIP URI) used to establish the call. This is a SPiDR service only parameter. * @param {object} [contact] Contains users firstName and lastName. This is a SPiDR service only parameter. * @param {string} [contact.firstName="John"] First Name of the user * @param {string} [contact.lastName="Doe"] Last Name of the user * @param {string} to The callee's address (e.g. SIP URI) used to establish the call * @param {function} onSuccess The onSuccess({@link fcs.call#OutgoingCall}) callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * @param {boolean} [isVideoEnabled] This will negotiate to receive video, see sendInitialVideo. This is a SPiDR service only parameter. * @param {boolean} [sendInitialVideo] Send the video automatically with the call, this will turn the camera on, and set the call to also receive video same as setting isVideoEnabled to true. This is a SPiDR service only parameter. * @param {object} [videoResolution] Sets the quality of video. This is a SPiDR service only parameter. * @param {string} [videoResolution.width="320"] Specifies min & max width of video. * @param {string} [videoResolution.height="240"] Specifies min & maxheight of video. * @param {string} [videoResolution.minWidth="320"] Specifies min width of video. Overrides ({@link videoResolution.width}) * @param {string} [videoResolution.minHeight="240"] Specifies min height of video. Overrides ({@link videoResolution.height}) * @param {string} [videoResolution.maxWidth="320"] Specifies max width of video. Overrides ({@link videoResolution.width}) * @param {string} [videoResolution.maxHeight="240"] Specifies max height of video. Overrides ({@link videoResolution.height}) * @param {object} [params] Extra parameters. * @param {string} [params.serviceName] Contains the service name 'spidr' or 'rcc'. SPiDR service parameter is default. If it is a RCC service, the service parameter should be given. * @param {boolean} [params.isAudioEnabled] Setting this to false will disable audio for the call. This is a SPiDR service only parameter. * * @example * // SPiDR service example is as follows: * // @since 3.0.0 * // Make Voice Call * // Start a voice call to the uri indicated with "to" argument * // Login is a prerequisite for making calls * // contact is an object with two fields contact.firstName and contact.lastName that specifies caller info * fcs.call.startCall(fcs.getUser(), contact, to, * function(outgoingCall){ * //get callid for your web app to be used later for handling popup windows * var callId = outgoingCall.getId(); * * outgoingCall.onStateChange = function(state, sipResponseCode, sipReasonText, data){ * // For example, to handle the end of a call. * switch (sipResponseCode) { * case "404": * showInfoMessage("Callee does not exist"); * break; * case "480": * showInfoMessage("Callee is offline"); * break; * case "603": * showInfoMessage("Callee rejected us"); * break; * case "487": * showInfoMessage("Callee did not answer"); * break; * } * switch (data.localStatusCode) { * case "9900": * showInfoMessage("Call end reason is not provided"); * break; * case "9901": * showInfoMessage("Call is ended locally"); * break; * case "9902": * showInfoMessage("Call is rejected locally"); * break; * case "9903": * showInfoMessage("Call is ignored locally"); * break; * case "9904": * showInfoMessage("Call is responded from another device"); * break; * case "9905": * showInfoMessage("Call is transfered"); * break; * default: * break; * } * //Add statusCode that returned from the server property to the call * outgoingCall.statusCode = sipResponseCode; * outgoingCall.localStatusCode = data.localStatusCode; * outgoingCall.reasonText = sipReasonText; * outgoingCall.localReasonText = data.localReasonText; * //Put your web app code to handle call state change like ringing, onCall ...etc. * }; * * outgoingCall.onStreamAdded = function(streamURL){ * // Setting up source (src tag) of remote video container * $("#remoteVideo").attr("src", streamURL); * }; * }, * function(){ * //put your web app failure handling code * window.alert("CALL_FAILED"); * }, * false, false); * * // RCC service example is as follows: * // @since 3.1.1 * // Start a call from a monitored device. * fcs.call.startCall(undefined, undefined, * // destination * destination, * // onSuccess callback * function (outgoingCall) * { * outgoingCall.onStateChange = function (state, statusCode, reasonText, data) { * onStateChange(outgoingCall, state, data); * }; * console.log('make call request success'); * }, * // onFailure callback * function (e) { * console.log('make call request failure!'); * }, * undefined, undefined, undefined, {serviceName: 'rcc'}); * */ /* * Internal API * @param {boolean} [params.sendScreenShare] Initiate a call with screen sharing. If mediaSourceId is not provided this will trigger the browser to request for screen sharing, can be used with FireFox, or with the Kandy ChromeExtension. Audio will be disabled when in use. This is a SPiDR service only parameter. * @param {string} [params.mediaSourceId] . This will initate the call from a mediaSourceId. This is a SPiDR service only parameter. */ this.startCall = function (from, contact, to, onSuccess, onFailure, isVideoEnabled, sendInitialVideo, videoResolution, options) { var params = { from: from, contact: contact, to: to, isVideoEnabled: isVideoEnabled, sendInitialVideo: sendInitialVideo, videoResolution: videoResolution }; params = (0, _utils.extend)(params, options); if (options && options.serviceName === 'rcc') { return _rccManager.start(params, onSuccess, onFailure); } else { return _callManager.start(params, onSuccess, onFailure); } }; /** * Starts monitoring a device. * * This is an RCC service only method. * * @name fcs.call#startMonitorDevice * @function * @since 3.1.1 * @param {string} deviceID If string with length greater than 0; device monitor will be started, otherwise user monitor will be started. * @param {function} onSuccess The onSuccess callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // User is subscribed... * // If deviceID is a string with length greater than 0; device monitor will be started, * // otherwise user monitor will be started. * var deviceID = null; * fcs.call.startMonitorDevice( * deviceID, * // onSuccess callback * function () { * console.log('Start monitor success'); * }, * // onFailure callback * function () { * console.log('Start monitor failure'); * }); */ this.startMonitorDevice = function (deviceID, onSuccess, onFailure) { return _rccManager.startMonitorDevice({ deviceID: deviceID }, onSuccess, onFailure); }; /** * Stops monitoring a device. * * This is an RCC service only method. * * @name fcs.call#stopMonitorDevice * @function * @since 3.1.1 * @param {function} onSuccess The onSuccess callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * fcs.call.stopMonitorDevice( * // onSuccess callback * function () { * console.log('stop monitor success'); * }, * // onFailure callback * function () { * console.log('stop monitor failure'); * }); * */ this.stopMonitorDevice = function (onSuccess, onFailure) { return _rccManager.stopMonitorDevice(onSuccess, onFailure); }; /** * Lists the registered devices of the RCC subscriber. * * This is an RCC service only method. * * @name fcs.call#getRCCDeviceList * @function * @since 3.1.1 * @param {function} onSuccess The onSuccess callback function to be called with an array of device info objects. Each object contains deviceURI, deviceId and uuid fields. * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // User is subscribed... * fcs.call.getRCCDeviceList( * // onsuccess callback * function(deviceList) { * console.log('get device list success'); * for (i = 0; i < deviceList.length; i++) { * // use device list array elements: Sample element: * // "deviceURI":"user1@1.1.1.1:5061", * // "uuid":"00000000-0000-1000-8000-001ECAF35125", * // "deviceId":"c2lwOmVyZGVtMUA0Ny4xNjguMjQ2LjMzOjUwNjE7dHJhbnNwb3J0PXRjcCQ8dXJuOnV1aWQ6IDAw%0AMDAwMDAwLTAwMDAtMTAwMC04MDAwLTAwMUVDQUYzNTEyNT4%3D%0A" * } * }, * // onFailure callback * function(e) { * console.log('get device list failure'); * }); */ this.getRCCDeviceList = function (onSuccess, onFailure) { return _rccManager.getDeviceList(onSuccess, onFailure); }; /** * Sets log severity level for Webrtc Plugin (not used for native webrtc) * 5 levels(sensitive:0, verbose:1, info:2, warning:3, error:4). * * This is a SPiDR service only method. * * @name fcs.call#set_logSeverityLevel * @function * @since 3.0.0 * */ this.set_logSeverityLevel = function (level) { return _callManager.set_logSeverityLevel({ level: level }); }; /** * Enables log callback for Webrtc Plugin (not used for native webrtc). * * This is a SPiDR service only method. * * @name fcs.call#enable_logCallback * @function * @since 3.0.0 */ this.enable_logCallback = function () { return _callManager.enable_logCallback(); }; /** * Disables log callback for Webrtc Plugin (not used for native webrtc). * * This is a SPiDR service only method. * * @name fcs.call#disable_logCallback * @function * @since 3.0.0 */ this.disable_logCallback = function () { return _callManager.disable_logCallback(); }; /** * Gets audioInDeviceCount. * * This is a SPiDR service only method. * * @name fcs.call#get_audioInDeviceCount * @function * @since 3.0.0 */ this.get_audioInDeviceCount = function () { return _callManager.get_audioInDeviceCount(); }; /** * Gets audioOutDeviceCount. * * This is a SPiDR service only method. * * @name fcs.call#get_autioOutDeviceCount * @function * @since 3.0.0 */ this.get_audioOutDeviceCount = function () { return _callManager.get_audioOutDeviceCount(); }; /** * Gets videoDeviceCount. * * This is a SPiDR service only method. * * @name fcs.call#get_videoDeviceCount * @function * @since 3.0.0 */ this.get_videoDeviceCount = function () { return _callManager.get_videoDeviceCount(); }; /** * Returns Video Device(Camera) availability. * * This is a SPiDR service only method. * * @name fcs.call#hasVideoDevice * @function * @since 3.0.0 * * @example * if(fcs.call.hasVideoDevice()){ * // If there is a video device available, show local video container * callView.toggleLocalVideo(true); * } */ this.hasVideoDevice = function () { return _callManager.get_videoDeviceCount(); }; /** * Returns Audio Device(Microphone) availability. * * This is a SPiDR service only method. * * @name fcs.call#hasAudioDevice * @function * @since 3.0.0 * * @example * if(!fcs.call.hasAudioDevice()){ * window.alert("There is no available audio source!"); * } */ this.hasAudioDevice = function () { return _callManager.hasAudioDevice(); }; /** * * This is a SPiDR service only method. * * @name fcs.call#getUserMedia * @function * @since 3.0.0 * @param onSuccess success callback of getUserMedia * @param onFailure failure callback of getUserMedia * @param options contains audio and video constraints * * @example * fcs.call.getUserMedia( * function(mediaInfo){ * window.console.log("media initialized. mediaInfo: " + JSON.stringify(mediaInfo)); * }, * function(err){ * window.console.log("media initialization error " + err); * }, * { * "audio": true, * "video": true * } * ); */ this.getUserMedia = function (onSuccess, onFailure, options) { return _callManager.getUserMedia({ options: options, privateStream: true }, onSuccess, onFailure); }; /** * Shows device settings Window * Only works with PLUGIN. * * This is a SPiDR service only method. * * @name fcs.call#showSettingsWindow * @function * @since 3.0.0 * * @example * $("#device_settings_button").click(function() { * fcs.call.showSettingsWindow(); * }); */ this.showSettingsWindow = function (onSuccess, onFailure, options) { return _callManager.showSettingsWindow({ options: options }, onSuccess, onFailure); }; /** * Gets local video resolutions with the order below * localVideoHeight-localVideoWidth * Only works with PLUGIN. * This is a SPiDR service only method. * * @name fcs.call#getLocalVideoResolutions * @function * @since 3.0.0 * * @example * var pluginLocalVideoResolution = fcs.call.getLocalVideoResolutions(); * var localVideoHeight = pluginLocalVideoResolution[0]; * var localVideoWidth = pluginLocalVideoResolution[1]; * console.log("Local Video Dimensions: " + localVideoWidth + "," + localVideoHeight); */ this.getLocalVideoResolutions = function () { return _callManager.getLocalVideoResolutions(); }; /** * Gets remote video resolutions with the order below * remoteVideoHeight-remoteVideoWidth * Only works with PLUGIN. * This is a SPiDR service only method. * * @name fcs.call#getRemoteVideoResolutions * @function * @since 3.0.0 * * @example * var pluginRemoteVideoResolution = fcs.call.getRemoteVideoResolutions(); * var remoteVideoHeight = pluginRemoteVideoResolution[0]; * var remoteVideoWidth = pluginRemoteVideoResolution[1]; * console.log("Remote Video Dimensions: " + remoteVideoWidth + "," + remoteVideoHeight); */ this.getRemoteVideoResolutions = function () { return _callManager.getRemoteVideoResolutions(); }; /** * Shows if plugin is enabled. * Only works with PLUGIN. * This is a SPiDR service only method. * * @name fcs.call#isPluginEnabled * @function * @since 3.0.0 * * @example * if(fcs.call.isPluginEnabled()) { * $("#device_settings_details").show(); * } */ this.isPluginEnabled = function () { return _callManager.isPluginEnabled(); }; /** * Checks if any call exists. * * This is a SPiDR and RCC service method. * * @name fcs.call#hasGotCalls * @function * @param {object} params Contains the service name ({serviceName:'spidr'} or ({serviceName:'rcc'}). SPiDR service parameter is default. If it is a RCC service, the service parameter should be given. * @returns {Boolean} true if any call exists, false otherwise. * * @example * // SPiDR service example is as follows: * // @since 3.0.0 * if(fcs.call.hasGotCalls()) { * console.log('At least one call is available.'); * } * * // RCC service example is as follows: * // @since 3.1.1 * if(fcs.call.hasGotCalls({serviceName:'rcc'})) { * console.log('At least one call is available.'); * } */ this.hasGotCalls = function (options) { if (options && options.serviceName === 'rcc') { return _rccManager.hasGotCalls(); } else { return _callManager.hasGotCalls(); } }; /** * Retrived a call by Id. * * This function allow to retrive a call which was cached by the call continuation feature. * This is a SPiDR service only method. * * @name fcs.call#getIncomingCallById * @function * @since 3.0.0 * @param {string} id from The id of the incoming call * @returns {fcs.call.IncomingCall} * */ this.getIncomingCallById = function (id) { return _callManager.getIncomingCallById({ callid: id }); }; /** * Create a renderer for an audio/video stream. * This is a SPiDR service only method. * * @name fcs.call#createStreamRenderer * @function * @since 3.0.0 * @param {string} streamUrl The url of the stream * @param {object} container The DOM node into which to create the renderer (the content of the node will be cleared) * @param {object} options The options to be used for the renderer * @returns {Object} renderer Renderer object * */ this.createStreamRenderer = function (streamId, container, options) { return _callManager.createStreamRenderer({ streamId: streamId, container: container, options: options }); }; /** * Discpose of a previously created renderer. * This is a SPiDR service only method. * * @name fcs.call#disposeStreamRenderer * @function * @since 3.0.0 * @param {object} container The DOM node into which the renderer was previously created */ this.disposeStreamRenderer = function (container) { return _callManager.disposeStreamRenderer({ container: container }); }; /** * Create an audio local bridge * This is a SPiDR service only method. * * @name fcs.call#createLocalAudioBridge * @function * @since 3.0.0 * @param {function} onSuccess The onSuccess({@link fcs.call.LocalAudioBridge}) callback to be called with the LocalAudioBridge * @param {function} onFailure The onFailure({@link fcs#Errors}) callback to be called * @param {object} options The options for creating an audio bridge */ this.createLocalAudioBridge = function (onSuccess, onFailure, options) { return _callManager.createLocalAudioBridge(options, onSuccess, onFailure); }; /** * States of the Call. * * This is a SPiDR and RCC service member. * Available for SPiDR since 3.0.0, and for RCC since 3.1.1. * * @name fcs.call#States * @enum {number} * @readonly * @property {number} [IN_CALL=0] The call has been established. In rcc mode, called and calling party information is also passed to the client in on state change callback. * @property {number} [ON_HOLD=1] The call has been put on hold. * @property {number} [RINGING=2] The outgoing call is ringing. In rcc mode, called and calling party information is also passed to the client in on state change callback. * @property {number} [ENDED=3] The call has been terminated. * @property {number} [REJECTED=4] The outgoing call request has been rejected by the other party. * @property {number} [OUTGOING=5] The outgoing call request has been sent but no response have been received yet. * @property {number} [INCOMING=6] The incoming call has been received but has not been answered yet. In rcc mode, called and calling party information is also passed to the client in on state change callback. * @property {number} [ANSWERING=7] The incoming call has been answered but the call as not been establish yet. * @property {number} [JOINED=8] The call is joined. * @property {number} [RENEGOTIATION=9] The call is re-established. * @property {number} [TRANSFERRED=10] The call is transferred to a third party. * @property {number} [ON_REMOTE_HOLD=11] The call has been put on hold remotely. * @property {number} [CALL_IN_PROGRESS=12] The call is in progress. In rcc mode, called and calling party information is also passed to the client in on state change callback. * @property {number} [EARLY_MEDIA=13] Early media process successful. * EARLY_MEDIA and RINGING states can be triggered multiple times in different orders. * In each of these states, if the respondCallUpdate notification comes * and processed successfully, the state is IN_CALL. * @property {number} [TRANSFER_FAILURE=14] The call couldn't be transferred to a third party. * @property {number} [REPLACING=15] Blind Transfer is in progress for transferee. Call replacing notification has come. */ this.States = { IN_CALL: 0, ON_HOLD: 1, RINGING: 2, ENDED: 3, REJECTED: 4, OUTGOING: 5, INCOMING: 6, ANSWERING: 7, JOINED: 8, RENEGOTIATION: 9, TRANSFERRED: 10, ON_REMOTE_HOLD: 11, CALL_IN_PROGRESS: 12, EARLY_MEDIA: 13, TRANSFER_FAILURE: 14, REPLACING: 15 }; /** * States of the Media Negotiation (ICE). * * This is a SPiDR service only. * * @name fcs.call#MediaStates * @enum {number} * @readonly * @property {number} [NEW=0] The ICE agent is gathering addresses or is waiting to be given remote candidates. * @property {number} [CHECKING=1] The ICE agent has been given one or more remote candidates and is checking pairs of local and remote candidates against one another to try to find a compatible match, but has not yet found a pair which will allow the peer connection to be made. It's possible that gathering of candidates is also still underway. * @property {number} [CONNECTED=2] A usable pairing of local and remote candidates has been found for all components of the connection, and the connection has been established. It's possible that gathering is still underway, and it's also possible that the ICE agent is still checking candidates against one another looking for a better connection to use. * @property {number} [COMPLETED=3] The ICE agent has finished gathering candidates, has checked all pairs against one another, and has found a connection for all components. * @property {number} [FAILED=4] The ICE candidate has checked all candidates pairs against one another and has failed to find compatible matches for all components of the connection. It is, however, possible that the ICE agent did find compatible connections for some components. * @property {number} [DISCONNECTED=5] Checks to ensure that components are still connected failed for at least one component of the RTCPeerConnection. This is a less stringent test than "failed" and may trigger intermittently and resolve just as spontaneously on less reliable networks, or during temporary disconnections. When the problem resolves, the connection may return to the "connected" state. * @property {number} [CLOSED=6] The ICE agent for this RTCPeerConnection has shut down and is no longer handling requests. */ this.MediaStates = { NEW: 0, CHECKING: 1, CONNECTED: 2, COMPLETED: 3, FAILED: 4, DISCONNECTED: 5, CLOSED: 6 }; /** * Hold states of the Call. * * This is a SPiDR and RCC service member. * Available for SPiDR since 3.0.0, and for RCC since 3.1.1. * * @name fcs.call#HoldStates * @enum {number} * @readonly * @property {number} [LOCAL_HOLD=0] The call has been put on hold locally. * @property {number} [REMOTE_HOLD=1] The call has been put on hold remotely. * @property {number} [BOTH_HOLD=2] he call has been put on both locally and remotely. */ this.HoldStates = { LOCAL_HOLD: 0, REMOTE_HOLD: 1, BOTH_HOLD: 2 }; /** * Local status codes of the Call. * * This is a SPiDR service only member. * Available for SPiDR since 4.0.0 * * @name fcs.call#LocalStatusCodes * @enum {string} * @readonly * @property {string} [STATUS_CODE_NOT_PROVIDED="9900"] The call's status code hasn't been provided. * @property {string} [ENDED_BY_LOCAL="9901"] The call has been ended locally. * @property {string} [REJECTED_BY_LOCAL="9902"] The call has been rejected by local user. * @property {string} [IGNORED_BY_LOCAL="9903"] The call has been ignored by local user. * @property {string} [RESPONDED_FROM_ANOTHER_DEVICE="9904"] The call has been responded from another device. * @property {string} [SESSION_COMPLETED="9905"] The call session has been completed. */ this.LOCAL_STATUS_CODES = { STATUS_CODE_NOT_PROVIDED: '9900', ENDED_BY_LOCAL: '9901', REJECTED_BY_LOCAL: '9902', IGNORED_BY_LOCAL: '9903', RESPONDED_FROM_ANOTHER_DEVICE: '9904', SESSION_COMPLETED: '9905' }; /** * Local reason texts of the Call. * * This is a SPiDR service only member. * Available for SPiDR since 4.0.0 * * @name fcs.call#LocalReasonTexts * @enum {string} * @readonly * @property {string} [STATUS_CODE_NOT_PROVIDED="Reason not provided"] The call's reason text has not been provided. * @property {string} [ENDED_BY_LOCAL="Ended by local user"] The call has been ended locally. * @property {string} [REJECTED_BY_LOCAL="Rejected by local user"] The call has been rejected by local user. * @property {string} [IGNORED_BY_LOCAL="Ignored by local user"] The call has been ignored by local user. * @property {string} [RESPONDED_FROM_ANOTHER_DEVICE="Responded from another device"] The call has been answered on another device. * @property {string} [SESSION_COMPLETED="Session completed"] The call session is complete. */ this.LOCAL_REASON_TEXTS = { STATUS_CODE_NOT_PROVIDED: 'Reason not provided', ENDED_BY_LOCAL: 'Ended by local user', REJECTED_BY_LOCAL: 'Rejected by local user', IGNORED_BY_LOCAL: 'Ignored by local user', RESPONDED_FROM_ANOTHER_DEVICE: 'Responded from another device', SESSION_COMPLETED: 'Session completed' }; /** * Type of media initialization errors. * * This is a SPiDR service only member. * * @name fcs.call#MediaErrors * @enum {number} * @since 3.0.0 * @readonly * @property {number} [NOT_FOUND=1] No media source available. * @property {number} [NOT_ALLOWED=2] User did not allow media use. * @property {number} [OPTIONS=3] Missing or wrong use of options. * @property {number} [WRONG_VERSION=4] The version of the plugin is not supported. * @property {number} [NOT_INITIALIZED=5] The media is not initialized. * @property {number} [NEW_VERSION_WARNING=6] New plugin version is available. * @property {number} [INVALID_PARAMETER=7] Invalid parameter. * @property {number} [NO_SCREENSHARING_WARNING=8] Screen sharing is not possible with this browser or the screensharing extension could not be found. */ this.MediaErrors = mediaErrors; /** * Call a party through a client device using the Click To Call service. * This is a SPiDR service only method. * * @name fcs.call#clickToCall * @function * @since 3.0.0 * @param {string} callingParty The caller's address (e.g. SIP) used to establish the call * @param {string} calledParty The callee's address (e.g. SIP) used to establish the call * @param {function} onSuccess The onSuccess() callback to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback to be called * * @example * var onSuccess = function(){ * //do something here * }; * var onError = function (err) { * //do something here * }; * * fcs.call.clickToCall("user1@test.com", "user2@test.com", onSuccess, onError); */ this.clickToCall = function (callingParty, calledParty, onSuccess, onFailure) { return _callManager.clickToCall({ callingParty: callingParty, calledParty: calledParty }, onSuccess, onFailure); }; /** * Provide the user with a routable PSTN number as a result of an IMRN allocation request. * This is a SPiDR service only method. * * @name fcs.call#getIMRN * @function * @param {string} realm The pool of numbers from which IMRN will be allocated * @param {string} source The URI of the individual placing the call * @param {string} destination The URI of the individual receiving the call * @param {function} onSuccess The onSuccess() callback to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback to be called */ this.getIMRN = function (realm, source, destination, onSuccess, onFailure) { return _callManager.getIMRN({ realm: realm, source: source, destination: destination }, onSuccess, onFailure); }; /** * Return the stream refined by id * * This is a SPiDR service only method. * * @name fcs.call#getStreamById * @function * @param id of the stream */ this.getStreamById = function (streamId) { return _callManager.getStreamById({ streamId: streamId }); }; /** * Delete selected stream * * This is a SPiDR service only method. * * @name fcs.call#removeStreamById * @function * @param id of the stream */ this.removeStreamById = function (streamId) { _callManager.removeStreamById({ streamId: streamId }); }; /** * Sets specific audio input for the next call * * This is a SPiDR service only method. * * @name fcs.call#setSelectedMicrophoneId * @function * @param id of the audio input device */ this.setSelectedMicrophoneId = function (microphoneId) { _callManager.setSelectedMicrophoneId({ microphoneId: microphoneId }); }; /** * Sets specific video input for the next call * * This is a SPiDR service only method. * * @name fcs.call#setSelectedCameraId * @function * @param id of the video input device */ this.setSelectedCameraId = function (cameraId) { _callManager.setSelectedCameraId({ cameraId: cameraId }); }; /** * Sets the selected speaker as the default speaker. * It will be used for audio output for future calls. * * This is a SPiDR service only method. * * @name fcs.call#setSelectedSpeakerId * @function * @param {String} id ID of the speaker to use for call audio. * @param {Function} onSuccess Function called once the operation completes successfully. * @param {function} onFailure Function called if the operation fails to complete. */ this.setSelectedSpeakerId = function (speakerId, onSuccess, onFailure) { _callManager.setSelectedSpeakerId({ speakerId: speakerId }, onSuccess, onFailure); }; /** * Returns available video input sources * * This is a SPiDR service only method. * * @name fcs.call#getCameraList * @function * @param onSuccess success callback of getCameraList * @example * // Get the list of cameras and create an option under an existing select menu * var camSelect = document.getElementById("cameraDevice"); * * fcs.call.getCameraList(function(cList) { * for (var index = 0; index < cList.length; index++) { * var option = document.createElement("option"); * option.value = cList[index].id; * option.text = cList[index].label; * camSelect.add(option); * } * }); */ this.getCameraList = function (onSuccess) { return _callManager.getCameraList({ onSuccess: onSuccess }); }; /** * Returns available audio input sources * * This is a SPiDR service only method. * * @name fcs.call#getMicrophoneList * @function * @param onSuccess success callback of getMicrophoneList * @example * // Get the list of microphones and create an option under an existing select menu * var micSelect = document.getElementById("microphoneDevice"); * * fcs.call.getMicrophoneList(function(mList) { * for (var index = 0; index < mList.length; index++) { * var option = document.createElement("option"); * option.value = mList[index].id; * option.text = mList[index].label; * micSelect.add(option); * } * }); */ this.getMicrophoneList = function (onSuccess) { return _callManager.getMicrophoneList({ onSuccess: onSuccess }); }; /** * Returns available audio output sources * * This is a SPiDR service only method. * * @name fcs.call#getSpeakerList * @function * @param onSuccess success callback of getSpeakerList * @example * // Get the list of speakers and create an option under an existing select menu * var speakerSelect = document.getElementById("speakerDevice"); * * fcs.call.getSpeakerList(function(sList) { * for (var index = 0; index < sList.length; index++) { * var option = document.createElement("option"); * option.value = sList[index].id; * option.text = sList[index].label; * speakerSelect.add(option); * } * }); */ this.getSpeakerList = function (onSuccess) { return _callManager.getSpeakerList({ onSuccess: onSuccess }); }; /** * Sets specific media device for active call * Changes the camera and/or microphone used for the active call. * This is a SPiDR service only method. * * @name fcs.call#changeDevices * @function * @param {object} contains new device ids and active call object * var params = {"call":call}; * * @param {function} onSuccess The onSuccess() callback to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback to be called * * @since 4.0.0 * @example * // SPiDR service example is as follows: * // Change Media Devices * // During an active call with selected device id * // This method change media device which called with setSelectedCameraId or setSelectedMicrophoneId * var params = {"call":call}; * fcs.call.setSelectedCameraId(videoDeviceId); * fcs.call.setSelectedMicrophoneId(audioDeviceId); * * fcs.call.changeDevices(params, * function(){ * showInfoMessage("Device change called."); * },function(){ * showInfoMessage("Device change Failed."); * }); */ this.changeDevices = function (params, onSuccess, onFailure) { return _callManager.changeDevices(params, onSuccess, onFailure); }; /** * Changes speaker used for call audio output. * This is a SPiDR service only method. * Supported on browser's that support HTMLMediaElement.setSinkId(). * @name fcs.call#changeSpeaker * @function * @param {String} speakerId ID of the speaker to use for audio output. * @param {Function} onSuccess The success callback. * @param {Function} onFailure The failure callback. * @example * var speakerId; * // Set a speaker to use. * call.changeSpeaker(speakerId, onSuccess, onFailure); */ this.changeSpeaker = function (speakerId, onSuccess, onFailure) { return _callManager.changeSpeaker({ speakerId: speakerId }, onSuccess, onFailure); }; /** * When an monitor session refreshed notification is received, {@link fcs.call#setOnMonitorSessionRefreshed} handler will be invoked. * * This is an RCC service only method. * * @name fcs.call#setOnMonitorSessionRefreshed * @function * @since 4.1.0 * @param {function} callback callback function for on monitor session refreshed * * @example * onSuccess = function () { * console.log('Start monitor success'); * * fcs.call.setOnMonitorSessionRefreshed( * function () { * console.log('Received monitor session refreshed.'); * }); * } * * onFailure = function () { * console.log('Start monitor failure'); * } * * fcs.call.startMonitorDevice(deviceID, onSuccess, onFailure); * */ this.setOnMonitorSessionRefreshed = function (callback) { return _rccManager.setOnMonitorSessionRefreshed({ callback: callback }); }; /** * When an monitor session refreshed notification is received, {@link fcs.call#setOnMonitorSessionTerminated} handler will be invoked. * * This is an RCC service only method. * * @name fcs.call#setOnMonitorSessionTerminated * @function * @since 4.1.0 * @param {function} callback callback function for on monitor session terminated * * @example * onSuccess = function () { * console.log('Start monitor success'); * * fcs.call.setOnMonitorSessionTerminated( * function () { * console.log('Received monitor session terminated.'); * }); * } * * onFailure = function () { * console.log('Start monitor failure'); * } * * fcs.call.startMonitorDevice(deviceID, onSuccess, onFailure); * */ this.setOnMonitorSessionTerminated = function (callback) { return _rccManager.setOnMonitorSessionTerminated({ callback: callback }); }; /** * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * This is a SPiDR and RCC service class. * Available for SPiDR since 3.0.0, and for RCC since 3.1.1. * * @name fcs.call#IncomingCall * @class * @augments fcs.call.Call * @param {String} callid Unique identifier for the call * @param {Object} opts options * @param {String} callee Called party information. This is an RCC service parameter. * @param {String} caller Calling party information. This is an RCC service parameter. * @version @{spidr.jsl.version} */ this.IncomingCall = function () { /** * Sets the handler for listening for media state changed * * This is a SPiDR service only event. * * @name fcs.call#IncomingCall#onMediaStateChange * @event * @param {fcs.call.MediaStates} state Current state of the media negotiation. * **/ /** * Sets the handler for listening local video stream ready event. * * This is a SPiDR service only event. * * @name fcs.call#IncomingCall#onLocalStreamAdded * @function * @since 3.0.0.1 * **/ /** * Sets the handler for listening remote video stream ready event. * * This is a SPiDR service only event. * * @name fcs.call#IncomingCall#onStreamAdded * * @function * @since 2.0.0 * @param {?String} streamUrl remote video streamUrl * **/ /** * * This is a SPiDR service only member. * * @name fcs.call#IncomingCall#calleeNumber * @field * @since 3.0.0 * @type {String} * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.calleeNumber; */ /** * * This is a SPiDR service only member. * * @name fcs.call#IncomingCall#callerNumber * @field * @since 3.0.0 * @type {String} * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.callerNumber; */ /** * * This is a SPiDR service only member. * * @name fcs.call#IncomingCall#callerName * @field * @since 3.0.0 * @type {String} * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.callerName; */ /** * * This is a SPiDR service only member. * * @name fcs.call#IncomingCall#primaryContact * @field * @since 3.0.0 * @type {String} * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.primaryContact; */ /** * Puts the speaker into mute. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#mute * @function * @since 3.0.0 * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.mute(); */ /** * Puts the speaker into unmute. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#unmute * @function * @since 3.0.0 * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.unmute(); */ /** * Answers the call. * * This is a SPiDR and RCC service method. * * @name fcs.call#IncomingCall#answer * @function * @param {function} onSuccess The onSuccess() callback function to be called. In RCC, success callback is triggered when answered event is received. * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called. In RCC, failure call back is triggered when end or failed event is received before answered event, or there is a state failure. * @param {boolean} [sendInitialVideo] Answer call with video when video was negotiated by the other party. This is a SPiDR service only parameter. * @param {String} [videoResolution] Video quality. This is a SPiDR service only parameter. * @param {Object} [param] Extra optional parameters. * @param {boolean} [param.isAudioEnabled] Setting this to false will disable audio for the call. This is a SPiDR service only parameter. * * @example * // SPiDR service example is as follows: * // @since 3.0.0 * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * var onSuccess = function(){ * console.log('Answer call success!'); * }; * var onError = function (err) { * console.log('Answer call failure!'); * }; * * incomingCall.answer(onSuccess, onFailure, true, "1280x720"); * * // RCC service example is as follows: * // @since 3.1.1 * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.answer( * // onSuccess callback * function () { * console.log('Answer call success!'); * }, * // onFailure callback * function () { * console.log('Answer call failure!'); * }); */ /** * Rejects the call. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#reject * @function * @since 3.0.0 * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * var onSuccess = function(){ * //do something here * }; * var onError = function (err) { * //do something here * }; * * incomingCall.reject(onSuccess, onFailure); */ /** * Ignores the call. Client will not send any rest request for this one. Ignore is on client side only. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#ignore * @function * @since 3.0.0 * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * var onSuccess = function(){ * //do something here * }; * var onError = function (err) { * //do something here * }; * * incomingCall.ignore(onSuccess, onFailure); */ /** * Forwards the call. * * This is a SPiDR and RCC service method. * * @name fcs.call#IncomingCall#forward * @function * @param {string} address The address where the call is transferred (e.g. SIP URI) * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * var onSuccess = function(){ * console.log('Forward call success!'); * }; * var onError = function (err) { * console.log('Forward call failure!'); * }; * * incomingCall.forward("user1@test.com", onSuccess, onFailure); */ /** * * Checks the incoming call if it has reject option. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#canReject * @function * @since 3.0.0 * @returns {Boolean} * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.canReject(); */ /** * * Checks the incoming call if it has forward option. * * This is a SPiDR and RCC service method. * * @name fcs.call#IncomingCall#canForward * @function * @returns {Boolean} * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.canForward(); */ /** * Checks the incoming call if it has answer option. * * This is a SPiDR and RCC service method. * * @name fcs.call#IncomingCall#canAnswer * @function * @returns {Boolean} * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.canAnswer(); */ /** * Are we able to send video. * Ex: Client may try to send video but video cam can be unplugged. Returns false in that case. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#canSendVideo * @function * @since 3.0.0 * @returns {Boolean} * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.canSendVideo(); */ /** * Are we able to send video. Checks the incoming SDP. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#canReceiveVideo * @function * @since 3.0.0 * @returns {Boolean} * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.canReceiveVideo(); */ /** * Returns hold state of call. * * This is a SPiDR and RCC service method. * * @name fcs.call#IncomingCall#getHoldState * @function * @returns {@link fcs.HoldStates} or undefined if call has not been put * on hold. * * @example * // Available since 3.0.4 for SPiDR service, and since 3.1.1 for RCC service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.getHoldState(); */ /** * Gets called party. * * This is an RCC service method. * * @name fcs.call#IncomingCall#getCalledParty * @function * @returns {calledParty} string describing the called party * * @example * // Available since 3.1.0 for RCC service. * * fcs.call.onReceived = onCallReceived; * function onCallReceived(call) { * console.log("Called party: " + call.getCalledParty()); * } */ /** * Gets calling party. * * This is an RCC service method. * * @name fcs.call#IncomingCall#getCallingParty * @function * @returns {callingParty} string describing the calling party * * @example * // Available since 3.1.0 for RCC service. * * fcs.call.onReceived = onCallReceived; * function onCallReceived(call) { * console.log("Calling party: " + call.getCallingParty()); * } */ /** * Gets call id. * * This is a SPiDR and RCC service method. * * @name fcs.call#IncomingCall#getId * @function * @returns {id} Unique identifier for the call * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.getId(); */ /** * End the call. * * This is a SPiDR and RCC service method. * * `Starting with the SPiDR 4.0.0 JSL API this method fires fcs.call.States.ENDED state.` * * @name fcs.call#IncomingCall#end * @function * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.end( * // onSuccess callback * function () { * console.log('Call is ended!'); * }, * // onFailure callback * function () { * console.log('Call could not be ended!'); * }); */ /** * Holds the call. * * This is a SPiDR and RCC service method. * * @name fcs.call#IncomingCall#hold * @function * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * var onSuccess = function(){ * console.log('Call is held!'); * }; * var onFailure = function(err){ * console.log('Call could not be held!'); * }; * * incomingCall.hold(onSuccess, onFailure); */ /** * Resume the call. * * This is a SPiDR and RCC service method. * * @name fcs.call#IncomingCall#unhold * @function * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * var onSuccess = function(){ * console.log('Call is retrieved!'); * }; * var onFailure = function(err){ * console.log('Call could not be retrieved!'); * }; * * incomingCall.unhold(onSuccess, onFailure); */ /** * Get WebRTC Statistics * * This is a SPiDR service method. * * @name fcs.call#IncomingCall#getWebRtcStats * @function * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 4.0.0 for SPiDR service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.getWebRtcStats(function(stats) { * // Stats returned successfully * logger.debug("Audio Packets Lost: " + stats.audio.packetsLost); * }, * function(error) { * // Error occured * logger.error("getWebRtcStats failed: " + error); * } * ); */ /** * Get Native WebRTC Statistics * * This is a SPiDR service method. * * @name fcs.call#IncomingCall#getNativeWebRtcStats * @function * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 4.0.0 for SPiDR service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.getNativeWebRtcStats(function(results) { * // Stats returned successfully * logger.debug("getNativeWebRtcStats returned successfully: " + results); * }, * function(error) { * // Error occured * logger.error("getNativeWebRtcStats failed: " + error); * } * ); */ /** * Start WebRtc Statistics Timer * * This is a SPiDR service method. * * @name fcs.call#IncomingCall#startWebRtcStatsTimer * @function * @param {string} interval The interval is a parameter that determines how many seconds if necessary turning statistics(e.g. 10 seconds) * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 4.0.0 for SPiDR service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.startWebRtcStatsTimer(interval, * function(stats) { * // Stats returned successfully * logger.debug("Audio Packets Lost: " + stats.audio.packetsLost); * }, * function(error) { * // Error occured * logger.error("startWebRtcStatsTimer failed: " + error); * } * ); */ /** * Stop WebRtc Statistics Timer * * This is a SPiDR service method. * * @name fcs.call#IncomingCall#stopWebRtcStatsTimer * @function * * @example * // Available since 4.0.0 for SPiDR service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.stopWebRtcStatsTimer(); */ /** * Directly transfers the existing call to another recipient. * * This is a SPiDR and RCC service method. * * @name fcs.call#IncomingCall#directTransfer * @function * @param {string} address The address where the call is transferred (e.g. SIP URI) * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * var onSuccess = function(){ * console.log('Call is transferred!'); * }; * var onFailure = function(err){ * console.log('Call could not be transferred!'); * }; * * incomingCall.directTransfer("user@domain.com", onSuccess, onFailure); */ /** * Transfers an existing call to another existing call. * * * @name fcs.call#IncomingCall#consultativeTransfer * @function * @since 3.1.1 * @param {string} transferredCallId The id of call which will be transferred into the current(incoming) call * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * * // When an outgoing call is received, {@link fcs.call.event:onOutgoingCall} handler will be invoked. * * var outgoingCall = {}; * fcs.call.onOutgoingCall = function(call) { * outgoingCall = call; * }; * * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.consultativeTransfer(outgoingCall.getId(), onSuccess, onFailure); */ /** * Stop the video for this call after the call is established. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#videoStop * @function * @since 3.0.0 * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * var onSuccess = function(){ * //do something here * }; * var onFailure = function(err){ * //do something here * }; * * incomingCall.videoStop(onSuccess, onFailure); */ /** * Start the video for this call after the call is established. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#videoStart * @function * @since 3.0.0 * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure() callback function to be called * @param {object} [videoResolution] Sets the quality of video. This is a SPiDR service only parameter. * @param {string} [videoResolution.width="320"] Specifies min & max width of video. * @param {string} [videoResolution.height="240"] Specifies min & maxheight of video. * @param {string} [videoResolution.minWidth="320"] Specifies min width of video. Overrides ({@link videoResolution.width}) * @param {string} [videoResolution.minHeight="240"] Specifies min height of video. Overrides ({@link videoResolution.height}) * @param {string} [videoResolution.maxWidth="320"] Specifies max width of video. Overrides ({@link videoResolution.width}) * @param {string} [videoResolution.maxHeight="240"] Specifies max height of video. Overrides ({@link videoResolution.height}) * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * var onSuccess = function(){ * //do something here * }; * var onFailure = function(err){ * //do something here * }; * * incomingCall.videoStart(onSuccess, onFailure); */ /** * Join 2 calls. * You need two different calls to establish this functionality.<br> * * In SPiDR implementation: in order to join two calls both calls must * be put into hold state first.<br> * * In RCC implementation: in order to join two calls one call must * be in local hold state, and the other one must be in answered state. <br> * * If not call servers will not handle your request. * * This is a SPiDR and RCC service method. * * @name fcs.call#IncomingCall#join * @function * @param {fcs.call#Call} anotherCall Call that we want the current call to be joined to. * @param {function} onSuccess The onSuccess({@link fcs.call#Call}) to be called when the call have been joined provide the joined call as parameter * @param {function} [onFailure] The onFailure() to be called when media could not be join * @param {boolean} [isVideoEnabled] In order to join video calls set this to true. This is a SPiDR service only parameter. * @param {object} [videoResolution] Sets the quality of video. This is a SPiDR service only parameter. * @param {string} [videoResolution.width="320"] Specifies min & max width of video. * @param {string} [videoResolution.height="240"] Specifies min & maxheight of video. * @param {string} [videoResolution.minWidth="320"] Specifies min width of video. Overrides ({@link videoResolution.width}) * @param {string} [videoResolution.minHeight="240"] Specifies min height of video. Overrides ({@link videoResolution.height}) * @param {string} [videoResolution.maxWidth="320"] Specifies max width of video. Overrides ({@link videoResolution.width}) * @param {string} [videoResolution.maxHeight="240"] Specifies max height of video. Overrides ({@link videoResolution.height}) * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * // And another {@link fcs.call#OutgoingCall} or {@link fcs.call#IncomingCall} is required which is going to be joined. * var anotherCall; // assume this is previosuly created. * * var joinOnSuccess = function(joinedCall){ * joinedCall // newly created. * console.log('Join success!'); * }; * var joinOnFailure = function(){ * console.log('Join failure!'); * }; * * incomingCall.join(anotherCall, joinOnSuccess, joinOnFailure, isVideoEnabled, videoResolution); * * // When join() is successfuly completed, joinOnSuccess({@link fcs.call#OutgoingCall}) will be invoked. */ /** * Send Dual-tone multi-frequency signaling. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#sendDTMF * @function * @since 3.0.0 * @param {String} tone Tone to be send as dtmf. * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.sendDTMF("0"); */ /** * Force the plugin to send a IntraFrame * Only used by PLUGIN. * This needs to be called when sending video. * Solves video freeze issue. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#sendIntraFrame * @function * @since 3.0.0 * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.sendIntraFrame(); */ /** * Force the plugin to send a BlackFrame * Only used by PLUGIN. * Some of the SBC's(Session Border Controllers) do not establish one way video. * audio only side has to send a blackFrame in order to see the incoming video. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#sendBlackFrame * @function * @since 3.0.0 * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.sendBlackFrame(); */ /** * Force the plugin to refresh video renderer * with this call's remote video stream * Only used by PLUGIN. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#refreshVideoRenderer * @function * @since 3.0.0 * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.refreshVideoRenderer(); */ /** * Returns the call is a join call or not * Do not use this function if you really dont need it. * This will be handled by the framework. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#getJoin * @function * @since 3.0.0 * @returns {Boolean} isJoin * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.getJoin(); */ /** * Marks the call as a join call or not * Do not use this function if you really dont need it. * This will be handled by the framework. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#setJoin * @function * @since 3.0.0 * @param {String} join * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.setJoin(true); */ /** * Returns the button is a disabled or not * You may want to disable your buttons while waiting for a response. * Ex: this will prevent clicking multiple times for hold button until first hold response is not recieved. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#getButtonDisabler * @function * @since 3.0.0 * @returns {Boolean} buttonDisabler * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.getButtonDisabler(); */ /** * Disable the button after waiting 4000 milliseconds. * You may want to disable your buttons while waiting for a response. * Ex: this will prevent clicking multiple times for hold button until first hold response is not recieved. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#setButtonDisabler * @function * @since 3.0.0 * @param {Boolean} disable * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.setButtonDisabler(true); */ /** * Clears the timer set with fcs.call#IncomingCall#setButtonDisabler. * You may want to disable your buttons while waiting for a response. * Ex: this will prevent clicking multiple times for hold button until first hold response is not recieved. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#clearBtnTimeout * @function * @since 3.0.0 * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.clearBtnTimeout(); */ /** * Long call audit * Creates a timer after call is established. * This timer sends a "PUT" request to server. * This will continue until one request fails. * Handled by framework. You dont need to call this function. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#setAuditTimer * @function * @since 3.0.0 * @param {String} audit * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * incomingCall.setAuditTimer(audit); */ /** * Clears the long call audit prior to clearing all call resources. * Handled by framework. you dont need to call this function. * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#clearAuditTimer * @function * @since 3.0.0 * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. */ /** * @deprecated DO NOT USE, use isVideoNegotiationAvailable instead * Returns video negotation availability. * * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#isVideoNegotationAvailable * @function * @since 3.0.1 * @param {String} id Unique identifier for the call * @example * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.isVideoNegotationAvailable(); */ /** * Returns video negotiation availability. * * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#isVideoNegotiationAvailable * @function * @since 3.1.0 * @example * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.isVideoNegotiationAvailable(); */ /** * Set custom parameters * * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#setCustomParameters * @function * @since 3.0.0 * @param {Array.<{name: string, value:string}>} customParameters Custom SIP header parameters for the call. * * @example * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.setCustomParameters( * [ * { * "name": "X-GPS", * "value": "42,686032,23.344565" * } * ] * ); */ /** * Get custom parameters * * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#getCustomParameters * @function * @since 3.0.0 * @returns {Array.<{name: string, value:string}>} Custom SIP header parameters of the call * * @example * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * const customParameters = incomingCall.getCustomParameters(); */ /** * Sends the current custom parameters associated with a call to * the SPiDR service. * * This is a SPiDR service only method. * * @name fcs.call#IncomingCall#sendCustomParameters * @function * @since 3.0.0 * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * incomingCall.sendCustomParameters(); */ }; /** * This class is used to represent an outgoing call. * * This is a SPiDR and RCC service class. * Available for SPiDR since 3.0.0, and for RCC since 3.1.1. * * @name fcs.call#OutgoingCall * @class * @augments fcs.call.Call * @param {String} callid Unique identifier for the call * @param {String} callee Called party information. This is an RCC service parameter. Exists in received calls. Does not exist in rcc client started calls. * @param {String} caller Calling party information. This is an RCC service parameter. Exists in received calls. Does not exist in rcc client started calls. * @version @{spidr.jsl.version} */ this.OutgoingCall = function () { /** * Sets the handler for listening for media state changed * * This is a SPiDR service only event. * * @name fcs.call#OutgoingCall#onMediaStateChange * @event * @param {fcs.call.MediaStates} state Current state of the media negotiation. * **/ /** * Sets the handler for listening local video stream ready event. * * This is a SPiDR service only event. * * @name fcs.call#OutgoingCall#onLocalStreamAdded * @function * @since 3.0.0.1 * **/ /** * Sets the handler for listening remote video stream ready event. * * This is a SPiDR service only event. * * @name fcs.call#OutgoingCall#onStreamAdded * * @function * @since 2.0.0 * @param {?String} streamUrl remote video streamUrl * **/ /** * Are we able to send video. * Ex: Client may try to send video but video cam can be unplugged. Returns false in that case. * * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#canSendVideo * @function * @since 3.0.0 * @returns {Boolean} * * @example * * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.canSend(); */ /** * Are we able to send video. Checks the incoming SDP. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#canReceiveVideo * @function * @since 3.0.0 * @returns {Boolean} * * @example * * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.canReceiveVideo(); */ /** * Returns hold state of call. * * This is a SPiDR and RCC service method. * * @name fcs.call#OutgoingCall#getHoldState * @function * @returns {@link fcs.HoldStates} or undefined if call has not been put * on hold. * * @example * // Available since 3.0.4 for SPiDR service, and since 3.1.1 for RCC service. * // When an outgoingCall call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * outgoingCall.getHoldState(); */ /** * Gets called party. * * This is an RCC service method. This paremeter exists in received calls. Does not exist in rcc client started calls. * * @name fcs.call#OutgoingCall#getCalledParty * @function * @returns {calledParty} string describing the called party * * @example * // Available since 3.1.0 for RCC service. * * fcs.call.onOutgoingCall = onOutgoingCall; * function onOutgoingCall(call) { * console.log("Called party: " + call.getCalledParty()); * } */ /** * Gets calling party. * * This is an RCC service method. This paremeter exists in received calls. Does not exist in rcc client started calls. * * @name fcs.call#OutgoingCall#getCallingParty * @function * @returns {callingParty} string describing the calling party * * @example * // Available since 3.1.0 for RCC service. * * fcs.call.onOutgoingCall = onOutgoingCall; * function onOutgoingCall(call) { * console.log("Calling party: " + call.getCallingParty()); * } */ /** * Gets call id. * * This is a SPiDR and RCC service method. * * @name fcs.call#OutgoingCall#getId * @function * @returns {id} Unique identifier for the call * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.getId(); */ /** * Force the plugin to send a IntraFrame. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#sendIntraFrame * @function * @since 3.0.0 * * @example * * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.sendIntraFrame(); */ /** * Force the plugin to send a BlackFrame. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#sendBlackFrame * @function * @since 3.0.0 * * @example * * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.sendBlackFrame(); */ /** * Force the plugin to refresh video renderer * with this call's remote video stream. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#refreshVideoRenderer * @function * @since 3.0.0 * * @example * * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.refreshVideoRenderer(); */ /** * Puts the speaker into mute. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#mute * @function * @since 3.0.0 * * @example * * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.mute(); */ /** * Puts the speaker into unmute. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#unmute * @function * @since 3.0.0 * * @example * * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.unmute(); */ /** * End the call. * * `Starting with the SPiDR 4.0.0 JSL API this method fires fcs.call.States.ENDED state.` * * This is a SPiDR and RCC service method. * * @name fcs.call#OutgoingCall#end * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * @function * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * outgoingCall.end( * // onSuccess callback * function () { * console.log('Call is ended!'); * }, * // onFailure callback * function () { * console.log('Call could not be ended!'); * }); */ /** * Holds the call. * * This is a SPiDR and RCC service method. * * @name fcs.call#OutgoingCall#hold * @function * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * var holdCallOnSuccess = function(){ * console.log('Call is held!'); * }; * var holdCallOnFailure = function(err){ * console.log('Call could not be held!'); * }; * * outgoingCall.hold(holdCallOnSuccess, holdCallOnFailure); */ /** * Resume the call. * * This is a SPiDR and RCC service method. * * @name fcs.call#OutgoingCall#unhold * @function * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * var unholdCallOnSuccess = function(){ * console.log('Call is retrieved!'); * }; * var unholdCallOnFailure = function(err){ * console.log('Call could not be retrieved!'); * }; * * outgoingCall.unhold(unholdCallOnSuccess, unholdCallOnFailure); */ /** * Get WebRTC Statistics * * This is a SPiDR service method. * * @name fcs.call#OutgoingCall#getWebRtcStats * @function * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 4.0.0 for SPiDR service. * // A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * outgoingCall.getWebRtcStats(function(stats) { * // Stats returned successfully * logger.debug("Audio Packets Lost: " + stats.audio.packetsLost); * }, * function(error) { * // Error occured * logger.error("getWebRtcStats failed: " + error); * } * ); */ /** * Get Native WebRTC Statistics * * This is a SPiDR service method. * * @name fcs.call#OutgoingCall#getNativeWebRtcStats * @function * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 4.0.0 for SPiDR service. * // A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * outgoingCall.getNativeWebRtcStats(function(results) { * // Stats returned successfully * logger.debug("getNativeWebRtcStats returned successfully: " + results); * }, * function(error) { * // Error occured * logger.error("getNativeWebRtcStats failed: " + error); * } * ); */ /** * Start WebRtc Statistics Timer * * This is a SPiDR service method. * * @name fcs.call#OutgoingCall#startWebRtcStatsTimer * @function * @param {string} interval The interval is a parameter that determines how many seconds if necessary turning statistics(e.g. 10 seconds) * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 4.0.0 for SPiDR service. * // A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * outgoingCall.startWebRtcStatsTimer(interval, * function(stats) { * // Stats returned successfully * logger.debug("Audio Packets Lost: " + stats.audio.packetsLost); * }, * function(error) { * // Error occured * logger.error("startWebRtcStatsTimer failed: " + error); * } * ); */ /** * Stop WebRtc Statistics Timer * * This is a SPiDR service method. * * @name fcs.call#OutgoingCall#stopWebRtcStatsTimer * @function * * @example * // Available since 4.0.0 for SPiDR service. * // A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * outgoingCall.stopWebRtcStatsTimer(); */ /** * Directly transfers the existing call to another recipient. * * This is a SPiDR and RCC service method. * * @name fcs.call#OutgoingCall#directTransfer * @function * @param {string} address The address where the call is transferred (e.g. SIP URI) * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * var onSuccess = function(){ * console.log('Call is transferred!'); * }; * var onFailure = function(err){ * console.log('Call could not be transferred!'); * }; * * outgoingCall.directTransfer("user@domain.com", onSuccess, onFailure); */ /** * Transfers an existing call to another existing call. * * This is an RCC service only method. * * @name fcs.call#OutgoingCall#consultativeTransfer * @function * @since 3.1.1 * @param {string} transferredCallId The id of call which will be transferred into the current(outgoing) call * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * * // When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var incomingCall = {}; * fcs.call.onReceived = function(call) { * incomingCall = call; * }; * * // When an outgoing call is received, {@link fcs.call.event:onOutgoingCall} handler will be invoked. * * var outgoingCall = {}; * fcs.call.onOutgoingCall = function(call) { * outgoingCall = call; * }; * * outgoingCall.consultativeTransfer(incomingCall.getId(), onSuccess, onFailure); */ /** * Stop the video for this call after the call is established. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#videoStop * @function * @since 3.0.0 * @param {function} [onSuccess] The onSuccess() to be called when the video is stopped<br /> * function() * @param {function} [onFailure] The onFailure() to be called when the video could not be stopped<br /> * function() * * @example * * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * var videoStopOnSuccess = function(){ * //do something here * }; * var videoStopOnFailure = function(){ * //do something here * }; * * outgoingCall.videoStop(videoStopOnSuccess, videoStopOnFailure); */ /** * Start the video for this call after the call is established. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#videoStart * @function * @since 3.0.0 * @param {function} [onSuccess] The onSuccess() to be called when the video is started * @param {function} [onFailure] The onFailure() to be called when the video could not be started * @param {object} [videoResolution] Sets the quality of video. This is a SPiDR service only parameter. * @param {string} [videoResolution.width="320"] Specifies min & max width of video. * @param {string} [videoResolution.height="240"] Specifies min & maxheight of video. * @param {string} [videoResolution.minWidth="320"] Specifies min width of video. Overrides ({@link videoResolution.width}) * @param {string} [videoResolution.minHeight="240"] Specifies min height of video. Overrides ({@link videoResolution.height}) * @param {string} [videoResolution.maxWidth="320"] Specifies max width of video. Overrides ({@link videoResolution.width}) * @param {string} [videoResolution.maxHeight="240"] Specifies max height of video. Overrides ({@link videoResolution.height}) * * @example * * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * var videoStartOnSuccess = function(){ * //do something here * }; * var videoStartOnFailure = function(){ * //do something here * }; * * outgoingCall.videoStart(videoStopOnSuccess, videoStopOnFailure); */ /** * Join 2 calls. * You need two different calls to establish this functionality.<br> * * In SPiDR implementation: in order to join two calls both calls must * be put into hold state first.<br> * * In RCC implementation: in order to join two calls one call must * be in local hold state, and the other one must be in answered state. <br> * * If not call servers will not handle your request. * * This is a SPiDR and RCC service method. * * @name fcs.call#OutgoingCall#join * @function * @param {fcs.call#Call} anotherCall Call that we want the current call to be joined to. * @param {function} onSuccess The onSuccess({@link fcs.call#OutgoingCall}) to be called when the call have been joined provide the joined call as parameter * @param {function} [onFailure] The onFailure() to be called when media could not be join * @param {boolean} [isVideoEnabled] In order to join video calls set this to true. This is a SPiDR service only parameter. * @param {object} [videoResolution] Sets the quality of video. This is a SPiDR service only parameter. * @param {string} [videoResolution.width="320"] Specifies min & max width of video. * @param {string} [videoResolution.height="240"] Specifies min & maxheight of video. * @param {string} [videoResolution.minWidth="320"] Specifies min width of video. Overrides ({@link videoResolution.width}) * @param {string} [videoResolution.minHeight="240"] Specifies min height of video. Overrides ({@link videoResolution.height}) * @param {string} [videoResolution.maxWidth="320"] Specifies max width of video. Overrides ({@link videoResolution.width}) * @param {string} [videoResolution.maxHeight="240"] Specifies max height of video. Overrides ({@link videoResolution.height}) * * @example * // Available since 3.0.0 for SPiDR service, and since 3.1.1 for RCC service. * // A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * // And another {@link fcs.call#OutgoingCall} or {@link fcs.call#IncomingCall} is required which is going to be joined. * var anotherCall; // assume this is previosuly created. * * var joinOnSuccess = function(joinedCall){ * joinedCall // newly created. * console.log('Join success!'); * }; * var joinOnFailure = function(){ * console.log('Join failure!'); * }; * * outgoingCall.join(anotherCall, joinOnSuccess, joinOnFailure, isVideoEnabled, videoResolution); * * // When join() is successfuly completed, joinOnSuccess({@link fcs.call#OutgoingCall}) will be invoked. */ /** * Send Dual-tone multi-frequency signaling. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#sendDTMF * @function * @since 3.0.0 * @param {String} tone Tone to be send as dtmf. * * @example * * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * var videoStartOnSuccess = function(){ * //do something here * }; * var videoStartOnFailure = function(){ * //do something here * }; * * outgoingCall.sendDTMF("0"); */ /** * Returns the call is a join call or not * Do not use this function if you really dont need it. * This will be handled by the framework. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#getJoin * @function * @since 3.0.0 * @returns {Boolean} isJoin * * @example * * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * * var videoStartOnSuccess = function(){ * //do something here * }; * var videoStartOnFailure = function(){ * //do something here * }; * * outgoingCall.getJoin(); * * This method will return true if the outgoingCall is a previously joined call {@see {@link fcs.call#OutgoingCall#join}}. */ /** * Marks the call as a join call or not * Do not use this function if you really dont need it. * This will be handled by the framework. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#setJoin * @function * @since 3.0.0 * @param {String} join * * @example * * When an outgoing call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var outgoingCall = {}; * fcs.call.onReceived = function(call) { * outgoingCall = call; * }; * * outgoingCall.setJoin(true); */ /** * Returns the button is a disabled or not * You may want to disable your buttons while waiting for a response. * Ex: this will prevent clicking multiple times for hold button until first hold response is not recieved. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#getButtonDisabler * @function * @since 3.0.0 * @returns {Boolean} buttonDisabler * * @example * * When an outgoing call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var outgoingCall = {}; * fcs.call.onReceived = function(call) { * outgoingCall = call; * }; * * outgoingCall.getButtonDisabler(); */ /** * Clears the timer set with fcs.call#IncomingCall#setButtonDisabler. * You may want to disable your buttons while waiting for a response. * Ex: this will prevent clicking multiple times for hold button until first hold response is not recieved. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#clearBtnTimeout * @function * @since 3.0.0 * @param {bool} disable * * @example * * When an outgoing call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var outgoingCall = {}; * fcs.call.onReceived = function(call) { * outgoingCall = call; * }; * * outgoingCall.clearBtnTimeout(); */ /** * Clears the timer set with fcs.call#IncomingCall#setButtonDisabler. * You may want to disable your buttons while waiting for a response. * Ex: this will prevent clicking multiple times for hold button until first hold response is not recieved. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#clearBtnTimeout * @function * @since 3.0.0 * * @example * * When an outgoing call is received, {@link fcs.call#event:onReceived} handler will be invoked. * * var outgoingCall = {}; * fcs.call.onReceived = function(call) { * outgoingCall = call; * }; * * outgoingcall.clearBtnTimeout(); */ /** * Long call audit * Creates a timer after call is established. * This timer sends a "PUT" request to server. * This will continue until one request fails. * Handled by framework. You dont need to call this function. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#setAuditTimer * @function * @since 3.0.0 * @param {function} audit * * @example * * When an incoming call is received, {@link fcs.call#event:onReceived} handler will be invoked. * incomingCall.setAuditTimer(audit); */ /** * Clears the long call audit prior to clearing all call resources. * Handled by framework. you dont need to call this function. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#clearAuditTimer * @function * @since 3.0.0 * * @example * * When an outgoing call is received, {@link fcs.call#event:onReceived} handler will be invoked. */ /** * @deprecated DO NOT USE, use isVideoNegotiationAvailable instead * Returns video negotation availability. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#isVideoNegotationAvailable * @function * @since 3.0.1 * @param {String} id Unique identifier for the call * @example * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.isVideoNegotationAvailable(id); */ /** * Returns video negotiation availability. * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#isVideoNegotiationAvailable * @function * @since 3.1.0 * @example * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.isVideoNegotiationAvailable(); */ /** * Set custom parameters * * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#setCustomParameters * @function * @since 3.0.0 * @param {Array.<{name: string, value:string}>} customParameters Custom SIP header parameters for the call. * * @example * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.setCustomParameters( * [ * { * "name": "X-GPS", * "value": "42,686032,23.344565" * } * ] * ); */ /** * Get custom parameters * * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#getCustomParameters * @function * @since 3.0.0 * @returns {Array.<{name: string, value:string}>} Custom SIP header parameters of the call * * @example * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * const customParameters = outgoingCall.getCustomParameters(); */ /** * Send custom parameters * * Sends the current custom parameters associated with a call to * the SPiDR service. * * This is a SPiDR service only method. * * @name fcs.call#OutgoingCall#sendCustomParameters * @function * @since 3.0.0 * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * A previously created {@link fcs.call#OutgoingCall} is required. {@see {@link fcs.call#startCall}} for more details. * * var outgoingCall = {}; * fcs.call.startCall(..., ..., ..., onSuccess(outgoingCall), ..., ...); * outgoingCall.sendCustomParameters(); */ }; /** * This class is used to represent a local audio bridge. * * This is a SPiDR service only * * @name fcs.call#LocalAudioBridge * @class * @version @{spidr.jsl.version} */ this.LocalAudioBridge = function () { /** * Add a call to the local audio bridge * * This is a SPiDR service method. * * @name fcs.call#LocalAudioBridge#add * @function * @param {fcs.call.IncomingCall | fcs.call.OutgoingCall} call The call to be added to the audio local bridge * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * * A previously created {@link fcs.call#LocalAudioBridge} is required. {@see {@link fcs.call#createLocalAudioBridge}} for more details. * var incomingCall = {}; * var bridge = {}; * bridge.add(incomingCall); */ /** * Remove a call from the local audio bridge * * This is a SPiDR service method. * * @name fcs.call#LocalAudioBridge#remove * @function * @param {fcs.call.IncomingCall | fcs.call.OutgoingCall} call The call to be added to the audio local bridge * @param {function} onSuccess The onSuccess() callback function to be called * @param {function} onFailure The onFailure({@link fcs#Errors}) callback function to be called * * @example * * A previously created {@link fcs.call#LocalAudioBridge} is required. {@see {@link fcs.call#createLocalAudioBridge}} for more details. * var incomingCall = {}; * var bridge = {}; * bridge.add(incomingCall); * bridge.remove(incomingCall); */ /** * Closes the audio bridge, removing all of the calls. * * This is a SPiDR service method. * * @name fcs.call#LocalAudioBridge#close * @function * * @example * * A previously created {@link fcs.call#LocalAudioBridge} is required. {@see {@link fcs.call#createLocalAudioBridge}} for more details. * var bridge = {}; * bridge.close(); */ /** * Mute the local audio for all of the calls on the bridge * This is a SPiDR service only method. * * @name fcs.call#LocalAudioBridge#muteLocalAudio * @function * @since 3.0.0 * * @example * * A previously created {@link fcs.call#LocalAudioBridge} is required. {@see {@link fcs.call#createLocalAudioBridge}} for more details. * * var bridge = {}; * bridge.muteLocalAudio(); */ /** * Mute the local audio for all of the calls on the bridge * This is a SPiDR service only method. * * @name fcs.call#LocalAudioBridge#unmuteLocalAudio * @function * @since 3.0.0 * * @example * * A previously created {@link fcs.call#LocalAudioBridge} is required. {@see {@link fcs.call#createLocalAudioBridge}} for more details. * * var bridge = {}; * bridge.unmuteLocalAudio(); */ }; } /***/ }), /***/ "../fcs/src/js/call/module.js": /*!************************************!*\ !*** ../fcs/src/js/call/module.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _call = __webpack_require__(/*! ./call */ "../fcs/src/js/call/call.js"); exports.default = { Call: function Call(container) { return new _call.CallImpl(container); } }; /***/ }), /***/ "../fcs/src/js/call/rcc/module.js": /*!****************************************!*\ !*** ../fcs/src/js/call/rcc/module.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _rccFsm = __webpack_require__(/*! ./rccFsm */ "../fcs/src/js/call/rcc/rccFsm.js"); var _rccManager = __webpack_require__(/*! ./rccManager */ "../fcs/src/js/call/rcc/rccManager.js"); var _wamrcc = __webpack_require__(/*! ./wamrcc */ "../fcs/src/js/call/rcc/wamrcc.js"); exports.default = { RccFSM: function RccFSM(container) { return new _rccFsm.RccFSMImpl(container); }, RccManager: function RccManager(container) { return new _rccManager.RccManagerImpl(container); }, RccControlService: function RccControlService(container) { return new _wamrcc.RccControlServiceImpl(container); } }; /***/ }), /***/ "../fcs/src/js/call/rcc/rccFsm.js": /*!****************************************!*\ !*** ../fcs/src/js/call/rcc/rccFsm.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RccFSMImpl = RccFSMImpl; /* * Finite State machine that defines state transition of basic call model. * State machine fires events during state transitions. * Components should register to FSM in order to receive transition events * */ function RccFSMImpl(_ref) { var _logManager = _ref.LogManager; this.CallFSMState = { INIT: 'INIT', MAKING_CALL: 'MAKING_CALL', CALL_IN_PROGRESS: 'CALL_IN_PROGRESS', RINGING: 'RINGING', ANSWERED: 'ANSWERED', CALL_RECEIVED: 'CALL_RECEIVED', DEFLECTING_CALL: 'DEFLECTING_CALL', ENDING_CALL: 'ENDING_CALL', CALL_ENDED: 'CALL_ENDED', HOLDING_CALL: 'HOLDING_CALL', LOCAL_HOLD: 'LOCAL_HOLD', REMOTE_HOLD: 'REMOTE_HOLD', BOTH_HOLD: 'BOTH_HOLD', RETRIEVING_CALL: 'RETRIEVING_CALL', BLIND_TRANSFERING: 'BLIND_TRANSFERING', ANSWERING_CALL: 'ANSWERING_CALL', MAKING_CONSULTATIVE_TRANSFER: 'MAKING_CONSULTATIVE_TRANSFER', CONFERENCING_CALL: 'CONFERENCING_CALL', CONFERENCED_CALL: 'CONFERENCED_CALL' }; //CallFSM returns TransferEvent after state change this.TransferEvent = { unknownNotification_fsm: 'unknownNotification_fsm', makeCall_fsm: 'makeCall_fsm', callInProgress_fsm: 'callInProgress_fsm', ringing_fsm: 'ringing_fsm', answered_fsm: 'answered_fsm', callReceived_fsm: 'callReceived_fsm', callFailed_fsm: 'callFailed_fsm', callEnded_fsm: 'callEnded_fsm', endCall_fsm: 'endCall_fsm', blind_transfering_fsm: 'blind_transfering_fsm', holdCall_fsm: 'holdCall_fsm', callHeldLocally_fsm: 'callHeldLocally_fsm', callRetrievedLocally_fsm: 'callRetrievedLocally_fsm', callHeldRemotely_fsm: 'callHeldRemotely_fsm', callRetrievedRemotely_fsm: 'callRetrievedRemotely_fsm', callHeldBoth_fsm: 'callHeldBoth_fsm', answerCall_fsm: 'answerCall_fsm', deflectCall_fsm: 'deflectCall_fsm', consultativeTransfer_fsm: 'consultativeTransfer_fsm', redirected_fsm: 'redirected_fsm', callBlindTransferred_fsm: 'callBlindTransferred_fsm', callConsultativeTransferred_fsm: 'callConsultativeTransferred_fsm', callTransferred_fsm: 'callTransferred_fsm', conferencing_fsm: 'conferencing_fsm', conferenced_fsm: 'conferenced_fsm', blindTransferFailed_fsm: 'blindTransferFailed_fsm', consultativeTransferFailed_fsm: 'consultativeTransferFailed_fsm', conferenceCallFailed_fsm: 'conferenceCallFailed_fsm' }; //CallFSM receives NotificationEvent this.NotificationEvent = { unknowNotify: 'unknowNotify', callInProgress: 'callInProgress', ringing: 'ringing', answered: 'answered', callHeldRemotely: 'callHeldRemotely', callRetrievedRemotely: 'callRetrievedRemotely', callHeldLocally: 'callHeldLocally', callRetrievedLocally: 'callRetrievedLocally', callTransferred: 'callTransferred', callReceived: 'callReceived', redirected: 'redirected', callFailed: 'callFailed', callEnded: 'callEnded', makeCall_GUI: 'makeCall_GUI', deflectCall_GUI: 'deflectCall_GUI', endCall_GUI: 'endCall_GUI', holdCall_GUI: 'holdCall_GUI', blind_transfering_GUI: 'blind_transfering_GUI', retrieveCall_GUI: 'retrieveCall_GUI', answerCall_GUI: 'answerCall_GUI', consultativeTransfer_GUI: 'consultativeTransfer_GUI', conferenceCall_GUI: 'conferenceCall_GUI', conferenced: 'conferenced', blindTransferFailed: 'blindTransferFailed', consultativeTransferFailed: 'consultativeTransferFailed', conferenceCallFailed: 'conferenceCallFailed' }; var self = this, logger = _logManager.getLogger('rccFSM'); function FSM(call, event, onSuccess, onFailure) { //TODO move sessionProgress somewhere else? var callState = self.getCurrentState(call); switch (callState) { case self.CallFSMState.INIT: switch (event) { case self.NotificationEvent.makeCall_GUI: call.currentState = self.CallFSMState.MAKING_CALL; onSuccess(call, self.TransferEvent.makeCall_fsm); break; // This is server RCC wrong notification workaround code. // ringing implemantation for init call state case self.NotificationEvent.ringing: call.currentState = self.CallFSMState.RINGING; onSuccess(call, self.TransferEvent.ringing_fsm); break; case self.NotificationEvent.callInProgress: call.currentState = self.CallFSMState.CALL_IN_PROGRESS; onSuccess(call, self.TransferEvent.callInProgress_fsm); break; case self.NotificationEvent.callReceived: call.currentState = self.CallFSMState.CALL_RECEIVED; onSuccess(call, self.TransferEvent.callReceived_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.MAKING_CALL: switch (event) { case self.NotificationEvent.callInProgress: call.currentState = self.CallFSMState.CALL_IN_PROGRESS; onSuccess(call, self.TransferEvent.callInProgress_fsm); break; // This is server RCC wrong notification workaround code. // ringing implemantation for making call state case self.NotificationEvent.ringing: call.currentState = self.CallFSMState.RINGING; onSuccess(call, self.TransferEvent.ringing_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.CALL_IN_PROGRESS: switch (event) { case self.NotificationEvent.ringing: call.currentState = self.CallFSMState.RINGING; onSuccess(call, self.TransferEvent.ringing_fsm); break; case self.NotificationEvent.answered: call.currentState = self.CallFSMState.ANSWERED; onSuccess(call, self.TransferEvent.answered_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.RINGING: switch (event) { case self.NotificationEvent.answered: call.currentState = self.CallFSMState.ANSWERED; onSuccess(call, self.TransferEvent.answered_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.CALL_RECEIVED: switch (event) { case self.NotificationEvent.deflectCall_GUI: call.currentState = self.CallFSMState.DEFLECTING_CALL; onSuccess(call, self.TransferEvent.deflectCall_fsm); break; case self.NotificationEvent.redirected: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.redirected_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.answered: call.currentState = self.CallFSMState.ANSWERED; onSuccess(call, self.TransferEvent.answered_fsm); break; case self.NotificationEvent.answerCall_GUI: call.currentState = self.CallFSMState.ANSWERING_CALL; onSuccess(call, self.TransferEvent.answerCall_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.ANSWERING_CALL: switch (event) { case self.NotificationEvent.answered: call.currentState = self.CallFSMState.ANSWERED; onSuccess(call, self.TransferEvent.answered_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.CONFERENCING_CALL: switch (event) { case self.NotificationEvent.conferenced: call.currentState = self.CallFSMState.ANSWERED; onSuccess(call, self.TransferEvent.conferenced_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; case self.NotificationEvent.conferenceCallFailed: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.conferenceCallFailed_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.DEFLECTING_CALL: switch (event) { case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; case self.NotificationEvent.redirected: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.redirected_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.ANSWERED: switch (event) { case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.holdCall_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.HOLDING_CALL; onSuccess(call, self.TransferEvent.holdCall_fsm); break; case self.NotificationEvent.callHeldLocally: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_HOLD; onSuccess(call, self.TransferEvent.callHeldLocally_fsm); break; case self.NotificationEvent.blind_transfering_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.BLIND_TRANSFERING; onSuccess(call, self.TransferEvent.blind_transfering_fsm); break; case self.NotificationEvent.callHeldRemotely: call.currentState = self.CallFSMState.REMOTE_HOLD; onSuccess(call, self.TransferEvent.callHeldRemotely_fsm); break; case self.NotificationEvent.consultativeTransfer_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.MAKING_CONSULTATIVE_TRANSFER; onSuccess(call, self.TransferEvent.consultativeTransfer_fsm); break; case self.NotificationEvent.conferenceCall_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.CONFERENCING_CALL; onSuccess(call, self.TransferEvent.conferencing_fsm); break; case self.NotificationEvent.conferenced: call.currentState = self.CallFSMState.ANSWERED; onSuccess(call, self.TransferEvent.conferenced_fsm); break; case self.NotificationEvent.callTransferred: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callTransferred_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.ENDING_CALL: switch (event) { case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.BLIND_TRANSFERING: switch (event) { case self.NotificationEvent.callTransferred: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callBlindTransferred_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.blindTransferFailed: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.blindTransferFailed_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.REMOTE_HOLD: switch (event) { case self.NotificationEvent.callRetrievedRemotely: call.currentState = self.CallFSMState.ANSWERED; onSuccess(call, self.TransferEvent.callRetrievedRemotely_fsm); break; case self.NotificationEvent.blind_transfering_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.BLIND_TRANSFERING; onSuccess(call, self.TransferEvent.blind_transfering_fsm); break; case self.NotificationEvent.holdCall_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.HOLDING_CALL; onSuccess(call, self.TransferEvent.holdCall_fsm); break; case self.NotificationEvent.callHeldLocally: call.previousState = call.currentState; call.currentState = self.CallFSMState.BOTH_HOLD; onSuccess(call, self.TransferEvent.callHeldBoth_fsm); break; case self.NotificationEvent.callHeldRemotely: onSuccess(call, self.TransferEvent.callHeldRemotely_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.callTransferred: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callTransferred_fsm); break; case self.NotificationEvent.conferenced: call.currentState = self.CallFSMState.ANSWERED; onSuccess(call, self.TransferEvent.conferenced_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.HOLDING_CALL: switch (event) { case self.NotificationEvent.callHeldLocally: call.currentState = self.CallFSMState.LOCAL_HOLD; if (call.previousState === self.CallFSMState.REMOTE_HOLD) { call.currentState = self.CallFSMState.BOTH_HOLD; } call.previousState = callState; onSuccess(call, self.TransferEvent.callHeldLocally_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.LOCAL_HOLD: switch (event) { case self.NotificationEvent.retrieveCall_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.RETRIEVING_CALL; onSuccess(call, self.TransferEvent.retrieveCall_fsm); break; case self.NotificationEvent.callRetrievedLocally: call.currentState = self.CallFSMState.ANSWERED; onSuccess(call, self.TransferEvent.callRetrievedLocally_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.callHeldRemotely: call.currentState = self.CallFSMState.BOTH_HOLD; onSuccess(call, self.TransferEvent.callHeldBoth_fsm); break; case self.NotificationEvent.callHeldLocally: onSuccess(call, self.TransferEvent.callHeldLocally_fsm); break; case self.NotificationEvent.blind_transfering_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.BLIND_TRANSFERING; onSuccess(call, self.TransferEvent.blind_transfering_fsm); break; case self.NotificationEvent.callTransferred: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callTransferred_fsm); break; case self.NotificationEvent.conferenced: call.currentState = self.CallFSMState.ANSWERED; onSuccess(call, self.TransferEvent.conferenced_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.MAKING_CONSULTATIVE_TRANSFER: switch (event) { case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; case self.NotificationEvent.callTransferred: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callConsultativeTransferred_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.consultativeTransferFailed: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.consultativeTransferFailed_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.RETRIEVING_CALL: switch (event) { case self.NotificationEvent.callRetrievedLocally: call.currentState = self.CallFSMState.ANSWERED; if (call.previousState === self.CallFSMState.BOTH_HOLD) { call.currentState = self.CallFSMState.REMOTE_HOLD; } call.previousState = callState; onSuccess(call, self.TransferEvent.callRetrievedLocally_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.BOTH_HOLD: switch (event) { case self.NotificationEvent.callRetrievedRemotely: call.currentState = self.CallFSMState.LOCAL_HOLD; onSuccess(call, self.TransferEvent.callRetrievedRemotely_fsm); break; case self.NotificationEvent.callHeldLocally: onSuccess(call, self.TransferEvent.callHeldBoth_fsm); break; case self.NotificationEvent.retrieveCall_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.RETRIEVING_CALL; onSuccess(call, self.TransferEvent.retrieveCall_fsm); break; case self.NotificationEvent.callRetrievedLocally: call.currentState = self.CallFSMState.REMOTE_HOLD; onSuccess(call, self.TransferEvent.callRetrievedLocally_fsm); break; case self.NotificationEvent.callHeldRemotely: onSuccess(call, self.TransferEvent.callHeldBoth_fsm); break; case self.NotificationEvent.endCall_GUI: call.currentState = self.CallFSMState.ENDING_CALL; onSuccess(call, self.TransferEvent.endCall_fsm); break; case self.NotificationEvent.callEnded: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callEnded_fsm); break; case self.NotificationEvent.callFailed: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callFailed_fsm); break; case self.NotificationEvent.blind_transfering_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.BLIND_TRANSFERING; onSuccess(call, self.TransferEvent.blind_transfering_fsm); break; case self.NotificationEvent.callTransferred: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.callTransferred_fsm); break; case self.NotificationEvent.conferenced: call.currentState = self.CallFSMState.ANSWERED; onSuccess(call, self.TransferEvent.conferenced_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; } } self.getCurrentState = function (call) { return call.currentState ? call.currentState : self.CallFSMState.INIT; }; this.handleEvent = function (call, event, handler) { var initialCallState; if (call) { initialCallState = self.getCurrentState(call); logger.info('FSM received NotificationEvent: ' + event + ' @ ' + initialCallState + ' state' + '. Call Id: ' + call.id); FSM(call, event, function (call, transferEvent) { logger.debug('FSM handleEvent successful. (Call FSM) State Passed from ' + initialCallState + ' to ' + self.getCurrentState(call) + '. TransferEvent: ' + transferEvent + '. Call Id: ' + call.id); handler(call, transferEvent); }, function (call, transferEvent) { logger.error('FSM handleEvent failure: ' + transferEvent + ' @ ' + self.getCurrentState(call) + '. Call Id: ' + call.id); handler(call, transferEvent); }); } else { logger.info('Not a call object. Ignore this event. ' + event); } }; } /***/ }), /***/ "../fcs/src/js/call/rcc/rccManager.js": /*!********************************************!*\ !*** ../fcs/src/js/call/rcc/rccManager.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.RccManagerImpl = RccManagerImpl; var _errors = __webpack_require__(/*! ../../errors */ "../fcs/src/js/errors.js"); var _errors2 = _interopRequireDefault(_errors); var _constants = __webpack_require__(/*! ../../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); var _utils2 = __webpack_require__(/*! ../../utils */ "../fcs/src/js/utils/index.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function RccManagerImpl(_ref) { var _rccFSM = _ref.RccFSM, _rccControlService = _ref.RccControlService, _logManager = _ref.LogManager, _globalBroadcaster = _ref.GlobalBroadcaster, _utils = _ref.Utils, _core = _ref.Core, _config = _ref.Config, _notificationCallbacks = _ref.NotificationCallbacks; /* AUDIT_KICKOFF_TIMEOUT is the interval we use to kickoff call audit after the call is setup. * The timeout is there to ensure we do not hit call setup race conditions when we try to kickoff the call audit */ var calls = {}, logger = _logManager.getLogger('rccManager'), fsmNotificationEvent = _rccFSM.NotificationEvent, fsmState = _rccFSM.CallFSMState, self = this, CALL_STATES = { IN_CALL: 0, ON_HOLD: 1, RINGING: 2, ENDED: 3, REJECTED: 4, OUTGOING: 5, INCOMING: 6, ANSWERING: 7, JOINED: 8, RENEGOTIATION: 9, TRANSFERRED: 10, ON_REMOTE_HOLD: 11, CALL_IN_PROGRESS: 12, EARLY_MEDIA: 13, TRANSFER_FAILURE: 14 }, CALL_HOLD_STATES = { LOCAL_HOLD: 0, REMOTE_HOLD: 1, BOTH_HOLD: 2 }, extendMonitorDeviceTimer = null, isMonitorStarted = false, isSubscription = false, sessionParam = {}, onMonitorSessionLost, monitorSessionLostNotification = { monitorSessionRefreshed: 'monitorSessionRefreshed', monitorSessionTerminated: 'monitorSessionTerminated' }, onMonitorSessionRefreshed, onMonitorSessionTerminated; this.IncomingCall = function (callid, opts, callee, caller) { var id = callid, options = opts, sendVideo = true, isJoin = false, buttonDisabler = false, btnTimeout, auditTimer, calledParty = callee, callingParty = caller; this.notificationQueue = new _utils2.Queue(); this.onLocalStreamAdded = null; this.onStreamAdded = null; this.mute = function () { var param = { callid: id, mute: true }; return self.mute(param); }; this.unmute = function () { var param = { callid: id, mute: false }; return self.mute(param); }; this.answer = function (onSuccess, onFailure, isVideoEnabled, videoResolution) { var param = { callid: id, isVideoEnabled: isVideoEnabled, videoResolution: videoResolution }; if (options.answer) { return self.answer(param, onSuccess, onFailure); } else { onFailure(); } }; this.reject = function (onSuccess, onFailure) { var param = { callid: id }; if (options.reject) { return self.reject(param, onSuccess, onFailure); } else { onFailure(); } }; this.ignore = function (onSuccess, onFailure) { var param = { callid: id }; return self.ignore(param, onSuccess, onFailure); }; this.forward = function (address, onSuccess, onFailure) { var param = { callid: id, address: address }; if (options.forward) { return self.forward(param, onSuccess, onFailure); } else { onFailure(); } }; this.canReject = function () { return options.reject === true; }; this.canForward = function () { return options.forward === true; }; this.canAnswer = function () { return options.answer === true; }; this.canSendVideo = function () { var param = { callid: id }; return self.canOriginatorSendLocalVideo(param); }; this.canReceiveVideo = function () { var param = { callid: id }; return self.canOriginatorReceiveRemoteVideo(param); }; this.getHoldState = function () { var param = { callid: id }; return self.getHoldStateOfCall(param); }; this.getCalledParty = function () { return calledParty; }; this.getCallingParty = function () { return callingParty; }; this.getId = function () { return id; }; this.end = function (onSuccess, onFailure) { var param = { callid: id }; return self.end(param, onSuccess, onFailure); }; this.hold = function (onSuccess, onFailure) { var param = { callid: id }; return self.hold(param, onSuccess, onFailure); }; this.unhold = function (onSuccess, onFailure) { var param = { callid: id }; return self.unhold(param, onSuccess, onFailure); }; this.directTransfer = function (address, onSuccess, onFailure) { var param = { callid: id, address: address }; return self.directTransfer(param, onSuccess, onFailure); }; this.consultativeTransfer = function (transferredCallId, onSuccess, onFailure) { var param = { currentCallId: id, targetCallId: transferredCallId }; return self.consultativeTransfer(param, onSuccess, onFailure); }; this.videoStop = function (onSuccess, onFailure) { var param = { callid: id, isVideoStart: false }; return self.videoStopStart(param, onSuccess, onFailure); }; this.videoStart = function (onSuccess, onFailure, videoResolution) { var param = { callid: id, isVideoStart: true, videoResolution: videoResolution }; return self.videoStopStart(param, onSuccess, onFailure); }; this.join = function (anotherCall, onSuccess, onFailure) { var param = { callid1: id, callid2: anotherCall.getId() }; return self.join(param, onSuccess, onFailure); }; this.sendDTMF = function (tone) { var param = { callid: id, tone: tone }; return self.sendDTMF(param); }; this.sendIntraFrame = function () { var param = { callid: id }; if (sendVideo) { return self.sendIntraFrame(param); } }; this.sendBlackFrame = function () { var param = { callid: id }; return self.sendBlackFrame(param); }; this.refreshVideoRenderer = function () { var param = { callid: id }; return self.refreshVideoRenderer(param); }; this.getJoin = function () { return isJoin; }; this.setJoin = function (join) { isJoin = join; }; this.getButtonDisabler = function () { return buttonDisabler; }; this.setButtonDisabler = function (disable) { buttonDisabler = disable; if (buttonDisabler) { btnTimeout = setTimeout(function () { buttonDisabler = false; }, 4000); } }; this.clearBtnTimeout = function () { clearTimeout(btnTimeout); }; this.setAuditTimer = function (audit) { auditTimer = setInterval(function () { audit(); }, _config.callAuditTimer ? _config.callAuditTimer : 30000); }; this.clearAuditTimer = function () { clearInterval(auditTimer); }; this.isCallMuted = function () { var param = { callid: id }; return self.isCallMuted(param); }; /* DEPRECIATED */ this.isVideoNegotationAvailable = function (id) { var param = { callid: id }; return self.isVideoNegotationAvailable(param); }; this.isVideoNegotiationAvailable = function () { var param = { callid: id }; return self.isVideoNegotiationAvailable(param); }; }; this.OutgoingCall = function (callid, callee, caller) { var id = callid, sendVideo = true, isJoin = false, buttonDisabler = false, btnTimeout, auditTimer, calledParty = callee, callingParty = caller; this.notificationQueue = new _utils2.Queue(); this.onLocalStreamAdded = null; this.onStreamAdded = null; this.canSendVideo = function () { var param = { callid: id }; return self.canOriginatorSendLocalVideo(param); }; this.canReceiveVideo = function () { var param = { callid: id }; return self.canOriginatorReceiveRemoteVideo(param); }; this.getHoldState = function () { var param = { callid: id }; return self.getHoldStateOfCall(param); }; this.getId = function () { return id; }; this.getCalledParty = function () { return calledParty; }; this.getCallingParty = function () { return callingParty; }; this.sendIntraFrame = function () { var param = { callid: id }; if (sendVideo) { return self.sendIntraFrame(param); } }; this.sendBlackFrame = function () { var param = { callid: id }; return self.sendBlackFrame(param); }; this.refreshVideoRenderer = function () { var param = { callid: id }; return self.refreshVideoRenderer(param); }; this.mute = function () { var param = { callid: id, mute: true }; return self.mute(param); }; this.unmute = function () { var param = { callid: id, mute: false }; return self.mute(param); }; this.end = function (onSuccess, onFailure) { var param = { callid: id }; return self.end(param, onSuccess, onFailure); }; this.hold = function (onSuccess, onFailure) { var param = { callid: id }; return self.hold(param, onSuccess, onFailure); }; this.unhold = function (onSuccess, onFailure) { var param = { callid: id }; return self.unhold(param, onSuccess, onFailure); }; this.directTransfer = function (address, onSuccess, onFailure) { var param = { callid: id, address: address }; return self.directTransfer(param, onSuccess, onFailure); }; this.consultativeTransfer = function (transfaredCallId, onSuccess, onFailure) { var param = { currentCallId: id, targetCallId: transfaredCallId }; return self.consultativeTransfer(param, onSuccess, onFailure); }; this.videoStop = function (onSuccess, onFailure) { var param = { callid: id, isVideoStart: false }; return self.videoStopStart(param, onSuccess, onFailure); }; this.videoStart = function (onSuccess, onFailure, videoResolution) { var param = { callid: id, isVideoStart: true, videoResolution: videoResolution }; return self.videoStopStart(param, onSuccess, onFailure); }; this.join = function (anotherCall, onSuccess, onFailure) { var param = { callid1: id, callid2: anotherCall.getId() }; return self.join(param, onSuccess, onFailure); }; this.sendDTMF = function (tone) { var param = { callid: id, tone: tone }; return self.sendDTMF(param); }; this.getJoin = function () { return isJoin; }; this.setJoin = function (join) { isJoin = join; }; this.getButtonDisabler = function () { return buttonDisabler; }; this.setButtonDisabler = function (disable) { buttonDisabler = disable; if (buttonDisabler) { btnTimeout = setTimeout(function () { buttonDisabler = false; }, 4000); } }; this.clearBtnTimeout = function () { clearTimeout(btnTimeout); }; this.setAuditTimer = function (audit) { auditTimer = setInterval(function () { audit(); }, _config.callAuditTimer ? _config.callAuditTimer : 30000); }; this.clearAuditTimer = function () { clearInterval(auditTimer); }; this.isCallMuted = function () { var param = { callid: id }; return self.isCallMuted(param); }; /* DEPRECIATED */ this.isVideoNegotationAvailable = function (id) { var param = { callid: id }; return self.isVideoNegotationAvailable(param); }; this.isVideoNegotiationAvailable = function () { var param = { callid: id }; return self.isVideoNegotiationAvailable(param); }; }; self.mute = function () { return; }; self.reject = function () { return; }; self.ignore = function () { return; }; self.canOriginatorSendLocalVideo = function () { return; }; self.canOriginatorReceiveRemoteVideo = function () { return; }; self.videoStopStart = function () { return; }; self.sendDTMF = function () { return; }; self.sendIntraFrame = function () { return; }; self.sendBlackFrame = function () { return; }; self.refreshVideoRenderer = function () { return; }; self.isCallMuted = function () { return; }; /* DEPRECIATED */ self.isVideoNegotationAvailable = function () { return; }; self.isVideoNegotiationAvailable = function () { return; }; function setDeviceID(deviceid) { sessionParam.deviceID = deviceid; } function setSessionID(sessionid) { sessionParam.sessionID = sessionid; } function setExpiryTime(expirytime) { sessionParam.expiryTime = expirytime; } function setMonitorSessionParam(deviceid, sessionid, expirytime) { setDeviceID(deviceid); setSessionID(sessionid); setExpiryTime(expirytime); } function getMonitorSessionParam() { return sessionParam; } function removeMonitorSessionParam() { delete sessionParam.deviceID; delete sessionParam.sessionID; delete sessionParam.expiryTime; } /* * clear call resources * @param call call object * @param state state that will be returned to web part */ function clearResources(id) { delete calls[id]; } function clearAllResources() { var id; logger.info('Clear all call resource from JSL Api'); for (id in calls) { if (calls.hasOwnProperty(id)) { clearResources(id); logger.info('Clear call resource from JSL Api - ' + id); } } } function stopExtendMonitorDeviceTimer() { logger.info('extend monitor device subscription timer is stopped.'); isMonitorStarted = false; clearInterval(extendMonitorDeviceTimer); extendMonitorDeviceTimer = null; clearAllResources(); } function extendMonitorDeviceSubscription() { var param = { deviceID: getMonitorSessionParam().deviceID, sessionID: getMonitorSessionParam().sessionID }; _rccControlService.extendMonitor(param, function () { logger.info('extend monitor device subscription request success.'); }, function (e) { stopExtendMonitorDeviceTimer(); removeMonitorSessionParam(); _utils.callFunctionIfExist(onMonitorSessionLost, e); logger.info('extend monitor device subscription request failure.'); }); } function startExtendMonitorDeviceTimer(timer) { logger.info('extend monitor device subscription timer is started.'); isMonitorStarted = true; extendMonitorDeviceTimer = setInterval(extendMonitorDeviceSubscription, timer); } self.setOnMonitorSessionLost = function (data) { onMonitorSessionLost = data.callback; }; self.setOnMonitorSessionRefreshed = function (data) { onMonitorSessionRefreshed = data.callback; }; self.setOnMonitorSessionTerminated = function (data) { onMonitorSessionTerminated = data.callback; }; self.CALL_STATES = CALL_STATES; self.CALL_HOLD_STATES = CALL_HOLD_STATES; self.hasGotCalls = function () { var callid, internalCall; for (callid in calls) { if (calls.hasOwnProperty(callid)) { internalCall = calls[callid]; if (internalCall) { logger.info('has got call - id: ' + callid + ' - state: ' + _rccFSM.getCurrentState(internalCall)); return true; } } } return false; }; self.getCalls = function () { return calls; }; function isCall(id) { if (self.getCalls()[id]) { return true; } return false; } self.delegateToCallFSM = function (call, stateMessage) { _rccFSM.handleEvent(call, stateMessage, self.onStateChange); }; function monitorStarted() { return isMonitorStarted; } self.isSubscribed = function isSubscribed() { return isSubscription; }; function subscriptionStarted() { isSubscription = true; } function subscriptionStopped() { if (monitorStarted()) { stopExtendMonitorDeviceTimer(); removeMonitorSessionParam(); } isSubscription = false; } function isDeviceMonitor(deviceID) { return typeof deviceID === 'string' && deviceID.length > 0; } self.start = function (data, onSuccess, onFailure) { var internalCall = {}, param = { destination: data.to, deviceID: getMonitorSessionParam().deviceID, sessionID: getMonitorSessionParam().sessionID }; logger.info('start call... to: ' + data.to); if (!monitorStarted()) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } _rccControlService.makeCall(param, function (reponse) { internalCall.call = new self.OutgoingCall(reponse.rccCallResponse.callId); internalCall.id = reponse.rccCallResponse.callId; self.delegateToCallFSM(internalCall, fsmNotificationEvent.makeCall_GUI); calls[reponse.rccCallResponse.callId] = internalCall; _utils.callFunctionIfExist(onSuccess, internalCall.call); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }); }; self.startMonitorDevice = function (data, onSuccess, onFailure) { logger.info('Called start Monitor Device function with ' + data.deviceID); if (!self.isSubscribed()) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } // if string with length greater than 0 device monitor, otherwise // user monitor will be started. if (!isDeviceMonitor(data.deviceID)) { // null is used in internal logic for user monitor. data.deviceID = null; } var param = { deviceID: data.deviceID }; _rccControlService.startMonitor(param, function (response) { setMonitorSessionParam(data.deviceID, response.rccSessionResponse.sessionId, response.rccSessionResponse.expires); startExtendMonitorDeviceTimer(response.rccSessionResponse.expires / 2 * 1000); _utils.callFunctionIfExist(onSuccess); logger.info('Start monitor device request successfuly'); }, function (e) { _utils.callFunctionIfExist(onFailure, e); logger.info('Start monitor device request failure : ' + e); }); }; self.stopMonitorDevice = function (onSuccess, onFailure) { var param = { deviceID: getMonitorSessionParam().deviceID, sessionID: getMonitorSessionParam().sessionID }; logger.info('Called stop monitor device function'); if (!monitorStarted()) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } _rccControlService.stopMonitor(param, function () { stopExtendMonitorDeviceTimer(); removeMonitorSessionParam(); _utils.callFunctionIfExist(onSuccess); logger.info('Stop monitor device request successfuly'); }, function (e) { _utils.callFunctionIfExist(onFailure, e); logger.info('Stop monitor device request failure : ' + e); }); }; self.answer = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], currentCallState, param = { callId: data.callid, deviceID: getMonitorSessionParam().deviceID, sessionID: getMonitorSessionParam().sessionID }; logger.info('Called call answer function.Call id : ' + data.callid); if (!internalCall) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } // Answer call is supported for only device level monitoring if (!isDeviceMonitor(getMonitorSessionParam().deviceID)) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } currentCallState = _rccFSM.getCurrentState(internalCall); if (currentCallState === fsmState.CALL_RECEIVED) { internalCall.answerSuccessCallback = onSuccess; internalCall.answerFailureCallback = onFailure; //send answer call _rccControlService.answerCall(param, function () { // If monitered device does not support auto answer, SPiDR returns rest request success and // does not return any negative notifications. Server side solution was not available. // New design is as follows: In the RCC case, JSL shall not invoke success // or failure callback until established Event or endCall event is received. self.delegateToCallFSM(internalCall, fsmNotificationEvent.answerCall_GUI); logger.info('Call answer request successfuly.'); }, function (e) { logger.info('Call answer request failure. ' + e); }); } else { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); } }; self.hold = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], currentCallState, param = { callId: data.callid, deviceID: getMonitorSessionParam().deviceID, sessionID: getMonitorSessionParam().sessionID }; logger.info('Called call hold function.Call id : ' + data.callid); if (!internalCall) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } currentCallState = _rccFSM.getCurrentState(internalCall); if (currentCallState === fsmState.ANSWERED || currentCallState === fsmState.REMOTE_HOLD) { _rccControlService.holdCall(param, function () { self.delegateToCallFSM(internalCall, fsmNotificationEvent.holdCall_GUI); _utils.callFunctionIfExist(onSuccess); logger.info('Call hold request successfuly.'); }, function (e) { _utils.callFunctionIfExist(onFailure, e); logger.info('Call hold request failure. ' + e); }); } else { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); } }; self.unhold = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], currentCallState, param = { callId: data.callid, deviceID: getMonitorSessionParam().deviceID, sessionID: getMonitorSessionParam().sessionID }; logger.info('Called call unhold function.Call id : ' + data.callid); if (!internalCall) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } currentCallState = _rccFSM.getCurrentState(internalCall); if (currentCallState === fsmState.LOCAL_HOLD || currentCallState === fsmState.BOTH_HOLD) { _rccControlService.retrieveCall(param, function () { self.delegateToCallFSM(internalCall, fsmNotificationEvent.retrieveCall_GUI); _utils.callFunctionIfExist(onSuccess); logger.info('Call unhold request successfuly.'); }, function (e) { _utils.callFunctionIfExist(onFailure, e); logger.info('Call unhold request failure. ' + e); }); } else { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); } }; self.end = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], _currentState, param = { callId: data.callid, deviceID: getMonitorSessionParam().deviceID, sessionID: getMonitorSessionParam().sessionID }; logger.info('Called call end function.Call id : ' + data.callid); if (!internalCall) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } _currentState = _rccFSM.getCurrentState(internalCall); //check with the state machine if the current state would accept an endCall. if (_currentState === fsmState.INIT || _currentState === fsmState.ENDING_CALL) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); } else { _rccControlService.endCall(param, function () { self.delegateToCallFSM(internalCall, fsmNotificationEvent.endCall_GUI); _utils.callFunctionIfExist(onSuccess); logger.info('Call end request successfuly.'); }, function (e) { _utils.callFunctionIfExist(onFailure, e); logger.info('Call end request failure. ' + e); }); } }; self.forward = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], currentCallState, param = { callId: data.callid, destination: data.address, deviceID: getMonitorSessionParam().deviceID, sessionID: getMonitorSessionParam().sessionID }; logger.info('Called call forward function.Call id : ' + data.callid + ' ,address : ' + data.address); if (!internalCall) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } currentCallState = _rccFSM.getCurrentState(internalCall); if (currentCallState === fsmState.CALL_RECEIVED) { _rccControlService.deflectCall(param, function () { self.delegateToCallFSM(internalCall, fsmNotificationEvent.deflectCall_GUI); _utils.callFunctionIfExist(onSuccess); logger.info('Call forward request successfuly.'); }, function (e) { _utils.callFunctionIfExist(onFailure, e); logger.info('Call forward request failure. ' + e); }); } else { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); } }; self.consultativeTransfer = function (data, onSuccess, onFailure) { var currentInternalCall = calls[data.currentCallId], targetInternalCall = calls[data.targetCallId], currentCallState, targetCallState, param = { currentCallId: data.currentCallId, targetCallId: data.targetCallId, deviceID: getMonitorSessionParam().deviceID, sessionID: getMonitorSessionParam().sessionID }; logger.info('Called call consultativeTransfer function.Current Call Id : ' + data.currentCallId + ' ,Target Call Id : ' + data.targetCallId); if (!currentInternalCall || !targetInternalCall) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } currentCallState = _rccFSM.getCurrentState(currentInternalCall); targetCallState = _rccFSM.getCurrentState(targetInternalCall); if (currentCallState !== fsmState.ANSWERED) { logger.error('consultativeTransfer current call is not in correct state: ' + currentCallState); _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); } else if (targetCallState !== fsmState.LOCAL_HOLD && targetCallState !== fsmState.BOTH_HOLD) { logger.error('consultativeTransfer target call is not in correct state: ' + targetCallState); _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); } else { _rccControlService.consultativeTransfer(param, function () { self.delegateToCallFSM(currentInternalCall, fsmNotificationEvent.consultativeTransfer_GUI); _utils.callFunctionIfExist(onSuccess); logger.info('Call consultativeTransfer request successfuly.'); }, function (e) { _utils.callFunctionIfExist(onFailure, e); logger.info('Call consultativeTransfer request failure. ' + e); }); } }; self.join = function (data, onSuccess, onFailure) { var currentCall = calls[data.callid1], currentCallState, targetCallState, targetCall = calls[data.callid2], param = { currentCall: data.callid1, targetCall: data.callid2, deviceID: getMonitorSessionParam().deviceID, sessionID: getMonitorSessionParam().sessionID }; if (!currentCall && targetCall) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } currentCallState = _rccFSM.getCurrentState(currentCall); targetCallState = _rccFSM.getCurrentState(targetCall); if (currentCallState === fsmState.ANSWERED && (targetCallState === fsmState.LOCAL_HOLD || targetCallState === fsmState.BOTH_HOLD)) { logger.info('Called call join function. CallId1 : ' + data.callid1 + ' CallId2 : ' + data.callid2); _rccControlService.conferenceCall(param, function () { self.delegateToCallFSM(currentCall, fsmNotificationEvent.conferenceCall_GUI); _utils.callFunctionIfExist(onSuccess); logger.info('Join conference request successfly. '); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }); } else { logger.error('conference call is not in correct state: ' + currentCallState); _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); } }; self.getDeviceList = function (onSuccess, onFailure) { if (!self.isSubscribed()) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } logger.info('Called getDeviceList function.'); _rccControlService.getDeviceList(function (responseData) { _utils.callFunctionIfExist(onSuccess, responseData.rccDeviceResponse.deviceList); logger.info('GetDeviceList request successfuly.'); logger.debug('Response data: ' + (0, _stringify2.default)(responseData)); }, function (e) { _utils.callFunctionIfExist(onFailure, e); logger.info('GetDeviceList request failure.'); }); }; self.directTransfer = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], currentCallState, param = { callId: data.callid, destination: data.address, deviceID: getMonitorSessionParam().deviceID, sessionID: getMonitorSessionParam().sessionID }; logger.info('Called call directTransfer function.Call Id : ' + data.callid + ' ,Destination : ' + data.destination); if (!internalCall) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } currentCallState = _rccFSM.getCurrentState(internalCall); if (currentCallState === fsmState.LOCAL_HOLD || currentCallState === fsmState.REMOTE_HOLD || currentCallState === fsmState.ANSWERED || currentCallState === fsmState.BOTH_HOLD) { //TODO: force localhold - if the user is not on hold logger.info('[rccManager.directTransfer->sendTransfer : transfer target ]' + data.address); _rccControlService.blindTransfer(param, function () { self.delegateToCallFSM(internalCall, fsmNotificationEvent.blind_transfering_GUI); _utils.callFunctionIfExist(onSuccess); logger.info('[rccManager.directTransfer->sentTransfer : transfer target ]' + data.address); }, function (e) { logger.info('Call directTransfer request failure. ' + e); _utils.callFunctionIfExist(onFailure, e); }); } else { logger.error('directTransfer call is not in correct state: ' + currentCallState); _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); } }; //TODO sessionParams attributes self.onNotificationEvent = function (type, sessionParams) { var callid = sessionParams.callId, statusCode = sessionParams.statusCode, internalCall = calls[callid]; logger.debug('Notification received ' + type + ' callid:' + callid); if (internalCall) { internalCall.statusCode = statusCode; } self.delegateToCallFSM(internalCall, type); }; self.onStateChange = function (call, event) { var transferEvent = _rccFSM.TransferEvent; calls[call.id] = call; function triggerCallState(state, data) { logger.debug('triggerCallState: state = ' + state + ' call.statusCode = ' + call.statusCode + ' call.reasonText = ' + call.reasonText + ' data = ' + (0, _stringify2.default)(data)); call.call.callState = state; _utils.callFunctionIfExist(call.call.onStateChange, state, call.statusCode, call.reasonText, data); } function getCallerAndCalleeData(call) { return { calledParty: call.calledParty, callingParty: call.callingParty }; } logger.info('Transfer Event: ' + event + '. callId: ' + call.id); switch (event) { case transferEvent.makeCall_fsm: case transferEvent.endCall_fsm: case transferEvent.deflectCall_fsm: case transferEvent.blind_transfering_fsm: case transferEvent.holdCall_fsm: case transferEvent.retrieveCall_fsm: case transferEvent.answerCall_fsm: case transferEvent.consultativeTransfer_fsm: break; case transferEvent.callInProgress_fsm: triggerCallState(CALL_STATES.CALL_IN_PROGRESS, getCallerAndCalleeData(call)); break; case transferEvent.ringing_fsm: triggerCallState(CALL_STATES.RINGING, getCallerAndCalleeData(call)); break; case transferEvent.answered_fsm: triggerCallState(CALL_STATES.IN_CALL, getCallerAndCalleeData(call)); break; case transferEvent.conferenced_fsm: triggerCallState(CALL_STATES.JOINED); break; case transferEvent.callReceived_fsm: triggerCallState(CALL_STATES.INCOMING, getCallerAndCalleeData(call)); break; case transferEvent.callFailed_fsm: clearResources(call.id); triggerCallState(CALL_STATES.REJECTED); break; case transferEvent.blindTransferFailed_fsm: triggerCallState(CALL_STATES.TRANSFER_FAILURE); break; case transferEvent.consultativeTransferFailed_fsm: triggerCallState(CALL_STATES.TRANSFER_FAILURE); break; case transferEvent.conferenceCallFailed_fsm: triggerCallState(CALL_STATES.TRANSFER_FAILURE); break; case transferEvent.callEnded_fsm: clearResources(call.id); triggerCallState(CALL_STATES.ENDED); break; case transferEvent.callHeldLocally_fsm: case transferEvent.callHeldBoth_fsm: triggerCallState(CALL_STATES.ON_HOLD); break; case transferEvent.callHeldRemotely_fsm: triggerCallState(CALL_STATES.ON_REMOTE_HOLD); break; case transferEvent.callRetrievedRemotely_fsm: switch (_rccFSM.getCurrentState(call)) { case fsmState.LOCAL_HOLD: triggerCallState(CALL_STATES.ON_HOLD); break; case fsmState.ANSWERED: triggerCallState(CALL_STATES.IN_CALL); break; default: logger.error('Undefined transition event: ' + event + ' for ' + call.id); break; } break; case transferEvent.callRetrievedLocally_fsm: switch (_rccFSM.getCurrentState(call)) { case fsmState.REMOTE_HOLD: triggerCallState(CALL_STATES.ON_REMOTE_HOLD); break; case fsmState.ANSWERED: triggerCallState(CALL_STATES.IN_CALL); break; } break; case transferEvent.callBlindTransferred_fsm: case transferEvent.callConsultativeTransferred_fsm: case transferEvent.redirected_fsm: case transferEvent.callTransferred_fsm: clearResources(call.id); triggerCallState(CALL_STATES.TRANSFERRED); break; default: logger.error('Undefined transition event: ' + event + ' for ' + call.id); break; } }; self.getHoldStateOfCall = function (data) { var internalCall = calls[data.callid]; if (internalCall) { return CALL_HOLD_STATES[_rccFSM.getCurrentState(internalCall)]; } return undefined; }; //TODO data attributes sessionParams=>notificationMessage function handleCallControlNotification(type, data) { if (type && data) { self.onNotificationEvent(type, data); logger.info('RemoteCallControl notification received: ' + 'type:' + type); } } _notificationCallbacks.RemoteCallControl = function (data) { var rccEvent = data.rccNotificationParams.rccEvent, rccNotifyData = data.rccNotificationParams, rccNotifySecondData = {}, incomingCall = {}, newOutgoingCall = {}, options, internalCall = calls[rccNotifyData.callId]; rccNotifyData.statusCode = data.statusCode; logger.debug('rccNotifyData: ' + (0, _stringify2.default)(rccNotifyData)); if (isDeviceMonitor(getMonitorSessionParam().deviceID)) { options = { reject: false, forward: true, answer: true }; } else { options = { reject: false, forward: true, answer: false }; } //---------------------------------------------------------------// // This method workaround for RCC conferenced notify. // // Recaive Notify Example : {statusCode : 0,rccEvent: "conferenced",callId : "joined callId",endedCallId : "endedCallId"} // // Create new notify data for ended call and launch double handleCallControlNotification(). // For joined call : handleCallControlNotification(rccNotifyData). // For ended call : handleCallControlNotification(rccNotifySecondData); function copyNotifyDataForConferencedDoubleCallID(data) { rccNotifySecondData.rccEvent = 'callEnded'; rccNotifySecondData.callId = data.endedCallId; rccNotifySecondData.statusCode = data.statusCode; delete data.endedCallId; return rccNotifySecondData; } //----------------------------------------------------------------// function addCallerAndCalleeToTheCall(rccNotifyData) { internalCall = calls[rccNotifyData.callId]; if (internalCall) { internalCall.calledParty = rccNotifyData.calledParty; internalCall.callingParty = rccNotifyData.callingParty; } } switch (rccEvent) { case fsmNotificationEvent.callRetrievedRemotely: handleCallControlNotification(fsmNotificationEvent.callRetrievedRemotely, rccNotifyData); break; case fsmNotificationEvent.callHeldRemotely: handleCallControlNotification(fsmNotificationEvent.callHeldRemotely, rccNotifyData); break; case fsmNotificationEvent.callRetrievedLocally: handleCallControlNotification(fsmNotificationEvent.callRetrievedLocally, rccNotifyData); break; case fsmNotificationEvent.callHeldLocally: handleCallControlNotification(fsmNotificationEvent.callHeldLocally, rccNotifyData); break; case fsmNotificationEvent.callTransferred: handleCallControlNotification(fsmNotificationEvent.callTransferred, rccNotifyData); break; case fsmNotificationEvent.redirected: handleCallControlNotification(fsmNotificationEvent.redirected, rccNotifyData); break; case fsmNotificationEvent.callFailed: if (internalCall) { _utils.callFunctionIfExist(internalCall.answerFailureCallback, _errors2.default.CALL_FAILED); } handleCallControlNotification(fsmNotificationEvent.callFailed, rccNotifyData); break; case fsmNotificationEvent.answered: addCallerAndCalleeToTheCall(rccNotifyData); if (internalCall) { _utils.callFunctionIfExist(internalCall.answerSuccessCallback); // No need to trigger failure callback once answered successfully (answered event is received) if (internalCall.answerFailureCallback) { internalCall.answerFailureCallback = undefined; } } handleCallControlNotification(fsmNotificationEvent.answered, rccNotifyData); break; case fsmNotificationEvent.callReceived: incomingCall.call = new self.IncomingCall(rccNotifyData.callId, options, rccNotifyData.calledParty, rccNotifyData.callingParty); incomingCall.id = rccNotifyData.callId; calls[rccNotifyData.callId] = incomingCall; _utils.callFunctionIfExist(_core.call.onReceived, incomingCall.call); addCallerAndCalleeToTheCall(rccNotifyData); handleCallControlNotification(fsmNotificationEvent.callReceived, rccNotifyData); break; case fsmNotificationEvent.ringing: if (!isCall(rccNotifyData.callId)) { newOutgoingCall.call = new self.OutgoingCall(rccNotifyData.callId, rccNotifyData.calledParty, rccNotifyData.callingParty); newOutgoingCall.id = rccNotifyData.callId; calls[rccNotifyData.callId] = newOutgoingCall; _utils.callFunctionIfExist(_core.call.onOutgoingCall, newOutgoingCall.call); } addCallerAndCalleeToTheCall(rccNotifyData); handleCallControlNotification(fsmNotificationEvent.ringing, rccNotifyData); break; case fsmNotificationEvent.callInProgress: if (!isCall(rccNotifyData.callId)) { newOutgoingCall.call = new self.OutgoingCall(rccNotifyData.callId, rccNotifyData.calledParty, rccNotifyData.callingParty); newOutgoingCall.id = rccNotifyData.callId; calls[rccNotifyData.callId] = newOutgoingCall; _utils.callFunctionIfExist(_core.call.onOutgoingCall, newOutgoingCall.call); } addCallerAndCalleeToTheCall(rccNotifyData); handleCallControlNotification(fsmNotificationEvent.callInProgress, rccNotifyData); break; case fsmNotificationEvent.conferenced: handleCallControlNotification(fsmNotificationEvent.callEnded, copyNotifyDataForConferencedDoubleCallID(rccNotifyData)); handleCallControlNotification(fsmNotificationEvent.conferenced, rccNotifyData); break; case fsmNotificationEvent.callEnded: if (internalCall) { _utils.callFunctionIfExist(internalCall.answerFailureCallback, _errors2.default.CALL_ENDED); } handleCallControlNotification(fsmNotificationEvent.callEnded, rccNotifyData); break; case fsmNotificationEvent.blindTransferFailed: handleCallControlNotification(fsmNotificationEvent.blindTransferFailed, rccNotifyData); break; case fsmNotificationEvent.consultativeTransferFailed: handleCallControlNotification(fsmNotificationEvent.consultativeTransferFailed, rccNotifyData); break; case fsmNotificationEvent.conferenceCallFailed: handleCallControlNotification(fsmNotificationEvent.conferenceCallFailed, rccNotifyData); break; case monitorSessionLostNotification.monitorSessionRefreshed: _utils.callFunctionIfExist(onMonitorSessionRefreshed); break; case monitorSessionLostNotification.monitorSessionTerminated: stopExtendMonitorDeviceTimer(); removeMonitorSessionParam(); _utils.callFunctionIfExist(onMonitorSessionTerminated); break; default: handleCallControlNotification(fsmNotificationEvent.unknowNotify, rccNotifyData); break; } }; _globalBroadcaster.subscribe(_constants2.default.EVENT.DEVICE_SUBSCRIPTION_STARTED, subscriptionStarted); _globalBroadcaster.subscribe(_constants2.default.EVENT.DEVICE_SUBSCRIPTION_ENDED, subscriptionStopped); } /***/ }), /***/ "../fcs/src/js/call/rcc/wamrcc.js": /*!****************************************!*\ !*** ../fcs/src/js/call/rcc/wamrcc.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RccControlServiceImpl = RccControlServiceImpl; function RccControlServiceImpl(_ref) { var _server = _ref.Http; function genericErrorParser(jqXHR, property) { try { return JSON.parse(jqXHR.responseText)[property]; } catch (e) { return jqXHR.status; } } // the following 5 response syntaxes are defined in the REST API. function callRequestPostPutErrorParser(jqXHR) { return genericErrorParser(jqXHR, 'rccCallResponse'); } function callRequestDeleteErrorParser(jqXHR) { return genericErrorParser(jqXHR, 'rccCallResponse'); } function getDeviceListRequestErrorParser(jqXHR) { return genericErrorParser(jqXHR, 'rccDeviceResponse'); } function sessionRequestPostPutErrorParser(jqXHR) { return genericErrorParser(jqXHR, 'rccSessionResponse'); } function sessionRequestDeleteErrorParser(jqXHR) { return genericErrorParser(jqXHR, 'rccSessionResponse'); } // TODO: For now in rest error response cases, given error handler is // called with an empty argument list. Can be refactored to map to an fcs.Errors // if overall JSL rest error refactoring is being done. function isUserMonitor(deviceID) { return deviceID === null; } function rccToRccDevice() { return '/rcc/rccdevice'; } function rccToSession(deviceID) { if (isUserMonitor(deviceID)) { return '/rcc/session'; } else { return '/rcc/rccdevice/' + deviceID + '/session'; } } function rccToSessionID(deviceID, sessionID) { return rccToSession(deviceID) + '/' + sessionID; } function rccToCall(deviceID, sessionID) { return rccToSessionID(deviceID, sessionID) + '/call'; } function rccToCallID(deviceID, sessionID, callID) { return rccToCall(deviceID, sessionID) + '/' + callID; } this.startMonitor = function (requestData, onSuccess, onFailure) { var urlPostfix, data = { 'rccSessionRequest': { 'eventType': 'generic' } }; urlPostfix = rccToSession(requestData.deviceID); _server.sendPostRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': data }, onSuccess, function () { onFailure(); }, null, sessionRequestPostPutErrorParser); }; this.extendMonitor = function (requestData, onSuccess, onFailure) { var data = null, urlPostfix; urlPostfix = rccToSessionID(requestData.deviceID, requestData.sessionID); _server.sendPutRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': data }, onSuccess, function () { onFailure(); }, null, sessionRequestPostPutErrorParser); }; this.stopMonitor = function (requestData, onSuccess, onFailure) { var urlPostfix; urlPostfix = rccToSessionID(requestData.deviceID, requestData.sessionID); _server.sendDeleteRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': {} }, onSuccess, function () { onFailure(); }, null, sessionRequestDeleteErrorParser); }; this.makeCall = function (requestData, onSuccess, onFailure) { var urlPostfix, data = { 'rccCallRequest': { 'action': 'makeCall', 'destination': requestData.destination } }; urlPostfix = rccToCall(requestData.deviceID, requestData.sessionID); _server.sendPostRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': data }, onSuccess, function () { onFailure(); }, null, callRequestPostPutErrorParser); }; this.holdCall = function (requestData, onSuccess, onFailure) { var urlPostfix, data = { 'rccCallRequest': { 'action': 'holdCall' } }; urlPostfix = rccToCallID(requestData.deviceID, requestData.sessionID, requestData.callId); _server.sendPutRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': data }, onSuccess, function () { onFailure(); }, null, callRequestPostPutErrorParser); }; this.retrieveCall = function (requestData, onSuccess, onFailure) { var urlPostfix, data = { 'rccCallRequest': { 'action': 'retrieveCall' } }; urlPostfix = rccToCallID(requestData.deviceID, requestData.sessionID, requestData.callId); _server.sendPutRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': data }, onSuccess, function () { onFailure(); }, null, callRequestPostPutErrorParser); }; this.endCall = function (requestData, onSuccess, onFailure) { var urlPostfix; urlPostfix = rccToCallID(requestData.deviceID, requestData.sessionID, requestData.callId); _server.sendDeleteRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': {} }, onSuccess, function () { onFailure(); }, null, callRequestDeleteErrorParser); }; this.deflectCall = function (requestData, onSuccess, onFailure) { var urlPostfix, data = { 'rccCallRequest': { 'action': 'deflectCall', 'destination': requestData.destination } }; urlPostfix = rccToCallID(requestData.deviceID, requestData.sessionID, requestData.callId); _server.sendPutRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': data }, onSuccess, function () { onFailure(); }, null, callRequestPostPutErrorParser); }; this.blindTransfer = function (requestData, onSuccess, onFailure) { var urlPostfix, data = { 'rccCallRequest': { 'action': 'blindTransfer', 'destination': requestData.destination } }; urlPostfix = rccToCallID(requestData.deviceID, requestData.sessionID, requestData.callId); _server.sendPutRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': data }, onSuccess, function () { onFailure(); }, null, callRequestPostPutErrorParser); }; this.consultativeTransfer = function (requestData, onSuccess, onFailure) { var urlPostfix, data = { 'rccCallRequest': { 'action': 'consultativeTransfer', 'callId': requestData.targetCallId } }; urlPostfix = rccToCallID(requestData.deviceID, requestData.sessionID, requestData.currentCallId); _server.sendPutRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': data }, onSuccess, function () { onFailure(); }, null, callRequestPostPutErrorParser); }; this.answerCall = function (requestData, onSuccess, onFailure) { var urlPostfix, data = { 'rccCallRequest': { 'action': 'answerCall' } }; urlPostfix = rccToCallID(requestData.deviceID, requestData.sessionID, requestData.callId); _server.sendPutRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': data }, onSuccess, function () { onFailure(); }, null, callRequestPostPutErrorParser); }; this.conferenceCall = function (requestData, onSuccess, onFailure) { var urlPostfix, data = { 'rccCallRequest': { 'action': 'conferenceCall', 'callId': requestData.targetCall } }; urlPostfix = rccToCallID(requestData.deviceID, requestData.sessionID, requestData.currentCall); _server.sendPutRequest({ 'url': _server.getWAMUrl(1, urlPostfix), 'data': data }, onSuccess, onFailure, null, callRequestPostPutErrorParser); }; this.getDeviceList = function (onSuccess, onFailure) { var urlPostfix; urlPostfix = rccToRccDevice(); _server.sendGetRequest({ 'url': _server.getWAMUrl(1, urlPostfix) }, onSuccess, function () { onFailure(); }, null, getDeviceListRequestErrorParser); }; } /***/ }), /***/ "../fcs/src/js/call/wam/callFsm.js": /*!*****************************************!*\ !*** ../fcs/src/js/call/wam/callFsm.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CallFSMImpl = CallFSMImpl; /* * Finite State machine that defines state transition of basic call model. * State machine fires events during state transitions. * Components should register to FSM in order to receive transition events * */ function CallFSMImpl(_ref) { var _logManager = _ref.LogManager; this.CallFSMState = { INIT: 'INIT', RINGING: 'RINGING', TRYING: 'TRYING', ANSWERING: 'ANSWERING', COMPLETED: 'COMPLETED', RINGING_SLOW: 'RINGING_SLOW', LOCAL_HOLD: 'LOCAL_HOLD', LOCAL_HOLDING: 'LOCAL_HOLDING', LOCAL_UNHOLDING: 'LOCAL_UNHOLDING', LOCAL_VIDEO_STOP_START: 'LOCAL_VIDEO_STOP_START', REMOTE_OFFER: 'REMOTE_OFFER', REMOTE_HOLD: 'REMOTE_HOLD', REMOTE_HOLDING: 'REMOTE_HOLDING', REMOTE_UNHOLDING: 'REMOTE_UNHOLDING', BOTH_HOLD: 'BOTH_HOLD', JOINING: 'JOINING', PROVISIONRECEIVED: 'PROVISIONRECEIVED', REFER: 'REFER', TRANSFERING: 'TRANSFERING', LOCAL_SLOW_START_OFFER: 'LOCAL_SLOW_START_OFFER', LOCAL_REOFFER: 'LOCAL_REOFFER', REPLACING: 'REPLACING', LOCAL_REJECTING: 'LOCAL_REJECTING', LOCAL_ENDING: 'LOCAL_ENDING' }; //CallFSM returns TransferEvent after state change this.TransferEvent = { unknownNotification_fsm: 'unknownNotification_fsm', ignoredNotification_fsm: 'ignoredNotification_fsm', callStart_fsm: 'callStart_fsm', callReceived_fsm: 'callReceived_fsm', answer_fsm: 'answer_fsm', reject_GUI: 'reject_GUI', rejectWithoutClearCallObject_GUI: 'rejectWithoutClearCallObject_GUI', ignore_GUI: 'ignore_GUI', callCompleted_fsm: 'callCompleted_fsm', noAnswer_fsm: 'noAnswer_fsm', localEnding_fsm: 'localEnding_fsm', localEndingWithoutClearCallObject_fsm: 'localEndingWithoutClearCallObject_fsm', localEnd_fsm: 'localEnd_fsm', localReject_fsm: 'localReject_fsm', remoteEnd_fsm: 'remoteEnd_fsm', answeringRingingSlow_fsm: 'answeringRingingSlow_fsm', callCompletedAnswering_fsm: 'callCompletedAnswering_fsm', localHold_fsm: 'localHold_fsm', localHolding_fsm: 'localHolding_fsm', remoteHold_fsm: 'remoteHold_fsm', remoteHolding_fsm: 'remoteHolding_fsm', localUnHold_fsm: 'localUnHold_fsm', localUnHolding_fsm: 'localUnHolding_fsm', remoteUnHold_fsm: 'remoteUnHold_fsm', remoteUnHolding_fsm: 'remoteUnHolding_fsm', localVideoStopStart_fsm: 'localVideoStopStart_fsm', remoteOffer_fsm: 'remoteOffer_fsm', joining_fsm: 'joining_fsm', sessionComplete_fsm: 'sessionComplete_fsm', joiningSuccess_fsm: 'joiningSuccess_fsm', sessionFail_fsm: 'sessionFail_fsm', ringing_fsm: 'ringing_fsm', respondCallUpdate_fsm: 'respondCallUpdate_fsm', remoteCallUpdate_fsm: 'remoteCallUpdate_fsm', remotePranswer_fsm: 'remotePranswer_fsm', forward_fsm: 'forward_fsm', refer_fsm: 'refer_fsm', accepted_fsm: 'accepted_fsm', transfering_fsm: 'transfering_fsm', transferSuccess_fsm: 'transferSuccess_fsm', transferFail_fsm: 'transferFail_fsm', respondCallHoldUpdate_fsm: 'respondCallHoldUpdate_fsm', remoteOfferDuringLocalHold_fsm: 'remoteOfferDuringHold_fsm', renegotiationCompleted_fsm: 'renegotiationCompleted_fsm', slowStartOfferDuringRemoteHold_fsm: 'slowStartOfferDuringRemoteHold_fsm', slowStartOfferDuringOnCall_fsm: 'slowStartOfferDuringOnCall_fsm', stateReverted_fsm: 'stateReverted_fsm', glareCondition_fsm: 'glareCondition_fsm', slowStartOfferProcessed_fsm: 'slowStartOfferProcessed_fsm', performReconnectWorkaround_fsm: 'performReconnectWorkaround_fsm', consultativeTransfer_fsm: 'consultativeTransfer_fsm', performCreateNewPeerWorkaround_fsm: 'performCreateNewPeerWorkaround_fsm', startCallReplace_fsm: 'startCallReplace_fsm', startCallReplaceRejected_fsm: 'startCallReplaceRejected_fsm', respondedFromAnotherDevice_fsm: 'respondedFromAnotherDevice_fsm', deviceChange_fsm: 'deviceChange_fsm' }; //CallFSM receives NotificationEvent this.NotificationEvent = { callStart_GUI: 'callStart_GUI', callNotify: 'callNotify', ringing_Notify: 'ringing_Notify', answer_GUI: 'answer_GUI', end_GUI: 'end_GUI', respondCallUpdate_Notify: 'respondCallUpdate_Notify', respondCallUpdate_glareCondition_Notify: 'respondCallUpdate_glareCondition_Notify', callCompleted_fsm: 'callCompleted_fsm', callEnd_Notify: 'callEnd_Notify', callNotify_noSDP: 'callNotify_noSDP', startCallUpdate_slowStart_Notify: 'startCallUpdate_slowStart_Notify', startCallUpdate_remoteHold_Notify: 'startCallUpdate_remoteHold_Notify', startCallUpdate_remoteOffer_Notify: 'startCallUpdate_remoteOffer_Notify', joining_Notify: 'joining_Notify', sessionComplete_Notify: 'sessionComplete_Notify', joiningSuccess_Notify: 'joiningSuccess_Notify', sessionFail_Notify: 'sessionFail_Notify', hold_GUI: 'hold_GUI', unhold_GUI: 'unhold_GUI', videoStopStart_GUI: 'videoStopStart_GUI', sessionProgress: 'sessionProgress', callCancel_Notify: 'callCancel_Notify', forward_GUI: 'forward_GUI', refer_JSL: 'refer_JSL', accepted_Notify: 'accepted_Notify', transfering: 'transfering', requestFailure_JSL: 'requestFailure_JSL', webrtcFailure_JSL: 'webrtcFailure_JSL', remoteOfferProcessed_JSL: 'remoteOfferProcessed_JSL', remoteHoldProcessed_JSL: 'remoteHoldProcessed_JSL', remoteUnHoldProcessed_JSL: 'remoteUnHoldProcessed_JSL', slowStartOfferProcessed_JSL: 'slowStartOfferProcessed_JSL', performReconnectWorkaround_JSL: 'performReconnectWorkaround_JSL', consultativeTransfer_GUI: 'consultativeTransfer_GUI', performCreateNewPeerWorkaround_JSL: 'performCreateNewPeerWorkaround_JSL', startCallReplace_Notify: 'startCallReplace_Notify', endReject_GUI: 'endReject_GUI', endIgnore_GUI: 'endIgnore_GUI', revertState_JSL: 'revertState_JSL', deviceChange_GUI: 'deviceChange_GUI' }; var self = this, logger = _logManager.getLogger('callFsm'); function FSM(call, event, onSuccess, onFailure) { var callState = self.getCurrentState(call); switch (callState) { case self.CallFSMState.INIT: switch (event) { case self.NotificationEvent.callStart_GUI: call.currentState = self.CallFSMState.TRYING; onSuccess(call, self.TransferEvent.callStart_fsm); break; case self.NotificationEvent.callNotify: call.currentState = self.CallFSMState.RINGING; onSuccess(call, self.TransferEvent.callReceived_fsm); break; case self.NotificationEvent.callNotify_noSDP: call.currentState = self.CallFSMState.RINGING_SLOW; onSuccess(call, self.TransferEvent.callReceived_fsm); break; case self.NotificationEvent.joiningSuccess_Notify: call.currentState = self.CallFSMState.PROVISIONRECEIVED; onSuccess(call, self.TransferEvent.joiningSuccess_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.REPLACING: switch (event) { case self.NotificationEvent.startCallReplace_Notify: onSuccess(call, self.TransferEvent.startCallReplace_fsm); break; case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.startCallReplaceRejected_fsm); break; case self.NotificationEvent.callEnd_Notify: case self.NotificationEvent.callCancel_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.startCallReplaceRejected_fsm); break; case self.NotificationEvent.sessionProgress: case self.NotificationEvent.ringing_Notify: onSuccess(call, self.TransferEvent.ringing_fsm); break; case self.NotificationEvent.respondCallUpdate_Notify: call.currentState = self.CallFSMState.COMPLETED; onSuccess(call, self.TransferEvent.callCompleted_fsm); break; } break; case self.CallFSMState.RINGING: switch (event) { case self.NotificationEvent.answer_GUI: call.currentState = self.CallFSMState.COMPLETED; onSuccess(call, self.TransferEvent.answer_fsm); break; case self.NotificationEvent.endReject_GUI: call.currentState = self.CallFSMState.LOCAL_REJECTING; onSuccess(call, self.TransferEvent.rejectWithoutClearCallObject_GUI); break; case self.NotificationEvent.endIgnore_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.ignore_GUI); break; case self.NotificationEvent.callNotify_noSDP: call.currentState = self.CallFSMState.RINGING_SLOW; onSuccess(call, self.TransferEvent.callReceived_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.callCancel_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.respondedFromAnotherDevice_fsm); break; case self.NotificationEvent.forward_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.forward_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.RINGING_SLOW: switch (event) { case self.NotificationEvent.answer_GUI: call.currentState = self.CallFSMState.ANSWERING; onSuccess(call, self.TransferEvent.answerRingingSlow_fsm); break; case self.NotificationEvent.endReject_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.reject_GUI); break; case self.NotificationEvent.callEnd_Notify: case self.NotificationEvent.callCancel_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.forward_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.forward_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.ANSWERING: switch (event) { case self.NotificationEvent.respondCallUpdate_Notify: call.currentState = self.CallFSMState.COMPLETED; onSuccess(call, self.TransferEvent.callCompletedAnswering_fsm); break; case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.TRYING: switch (event) { case self.NotificationEvent.sessionProgress: call.currentState = self.CallFSMState.PROVISIONRECEIVED; onSuccess(call, self.TransferEvent.remotePranswer_fsm); break; case self.NotificationEvent.ringing_Notify: call.currentState = self.CallFSMState.PROVISIONRECEIVED; onSuccess(call, self.TransferEvent.ringing_fsm); break; case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.noAnswer_fsm); break; case self.NotificationEvent.respondCallUpdate_Notify: call.currentState = self.CallFSMState.COMPLETED; onSuccess(call, self.TransferEvent.callCompleted_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.PROVISIONRECEIVED: switch (event) { case self.NotificationEvent.respondCallUpdate_Notify: call.currentState = self.CallFSMState.COMPLETED; onSuccess(call, self.TransferEvent.callCompleted_fsm); break; case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.LOCAL_ENDING; onSuccess(call, self.TransferEvent.localEndingWithoutClearCallObject_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.ringing_Notify: onSuccess(call, self.TransferEvent.ringing_fsm); break; case self.NotificationEvent.sessionProgress: onSuccess(call, self.TransferEvent.remotePranswer_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.COMPLETED: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.startCallUpdate_remoteHold_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.REMOTE_HOLDING; onSuccess(call, self.TransferEvent.remoteHolding_fsm); break; case self.NotificationEvent.startCallUpdate_slowStart_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_SLOW_START_OFFER; onSuccess(call, self.TransferEvent.slowStartOfferDuringOnCall_fsm); break; case self.NotificationEvent.hold_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_HOLDING; onSuccess(call, self.TransferEvent.localHolding_fsm); break; case self.NotificationEvent.videoStopStart_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_VIDEO_STOP_START; onSuccess(call, self.TransferEvent.localVideoStopStart_fsm); break; case self.NotificationEvent.startCallUpdate_remoteOffer_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.REMOTE_OFFER; onSuccess(call, self.TransferEvent.remoteOffer_fsm); break; case self.NotificationEvent.transfering: call.previousState = call.currentState; call.currentState = self.CallFSMState.TRANSFERING; onSuccess(call, self.TransferEvent.transfering_fsm); break; case self.NotificationEvent.callCancel_Notify: onSuccess(call, self.TransferEvent.ignoredNotification_fsm); break; case self.NotificationEvent.performReconnectWorkaround_JSL: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_REOFFER; onSuccess(call, self.TransferEvent.performReconnectWorkaround_fsm); break; case self.NotificationEvent.performCreateNewPeerWorkaround_JSL: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_REOFFER; onSuccess(call, self.TransferEvent.performCreateNewPeerWorkaround_fsm); break; case self.NotificationEvent.deviceChange_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_REOFFER; onSuccess(call, self.TransferEvent.deviceChange_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.LOCAL_REOFFER: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.respondCallUpdate_Notify: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.respondCallUpdate_fsm); break; case self.NotificationEvent.webrtcFailure_JSL: case self.NotificationEvent.requestFailure_JSL: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.stateReverted_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.REMOTE_OFFER: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.remoteOfferProcessed_JSL: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.renegotiationCompleted_fsm); break; case self.NotificationEvent.requestFailure_JSL: case self.NotificationEvent.webrtcFailure_JSL: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.stateReverted_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.LOCAL_VIDEO_STOP_START: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.respondCallUpdate_Notify: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.respondCallUpdate_fsm); break; case self.NotificationEvent.requestFailure_JSL: case self.NotificationEvent.webrtcFailure_JSL: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.stateReverted_fsm); break; case self.NotificationEvent.respondCallUpdate_glareCondition_Notify: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.glareCondition_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.LOCAL_HOLDING: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.respondCallUpdate_Notify: call.currentState = self.CallFSMState.LOCAL_HOLD; if (call.previousState === self.CallFSMState.REMOTE_HOLD) { call.currentState = self.CallFSMState.BOTH_HOLD; } call.previousState = callState; onSuccess(call, self.TransferEvent.respondCallHoldUpdate_fsm); break; case self.NotificationEvent.requestFailure_JSL: case self.NotificationEvent.webrtcFailure_JSL: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.stateReverted_fsm); break; case self.NotificationEvent.respondCallUpdate_glareCondition_Notify: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.glareCondition_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.LOCAL_UNHOLDING: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.respondCallUpdate_Notify: call.currentState = self.CallFSMState.COMPLETED; if (call.previousState === self.CallFSMState.BOTH_HOLD) { call.currentState = self.CallFSMState.REMOTE_HOLD; } call.previousState = callState; onSuccess(call, self.TransferEvent.respondCallHoldUpdate_fsm); break; case self.NotificationEvent.requestFailure_JSL: case self.NotificationEvent.webrtcFailure_JSL: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.stateReverted_fsm); break; case self.NotificationEvent.respondCallUpdate_glareCondition_Notify: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.glareCondition_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.LOCAL_HOLD: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.startCallUpdate_remoteHold_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.REMOTE_HOLDING; onSuccess(call, self.TransferEvent.remoteHolding_fsm); break; case self.NotificationEvent.startCallUpdate_remoteOffer_Notify: onSuccess(call, self.TransferEvent.remoteOfferDuringLocalHold_fsm); break; case self.NotificationEvent.unhold_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_UNHOLDING; onSuccess(call, self.TransferEvent.localUnHolding_fsm); break; case self.NotificationEvent.joining_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.JOINING; onSuccess(call, self.TransferEvent.joining_fsm); break; case self.NotificationEvent.transfering: call.previousState = call.currentState; call.currentState = self.CallFSMState.TRANSFERING; onSuccess(call, self.TransferEvent.transfering_fsm); break; case self.NotificationEvent.performReconnectWorkaround_JSL: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_REOFFER; onSuccess(call, self.TransferEvent.performReconnectWorkaround_fsm); break; case self.NotificationEvent.consultativeTransfer_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.TRANSFERING; onSuccess(call, self.TransferEvent.transfering_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.REMOTE_HOLDING: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.remoteHoldProcessed_JSL: call.currentState = self.CallFSMState.REMOTE_HOLD; if (call.previousState === self.CallFSMState.LOCAL_HOLD) { call.currentState = self.CallFSMState.BOTH_HOLD; } call.previousState = callState; onSuccess(call, self.TransferEvent.remoteHold_fsm); break; case self.NotificationEvent.requestFailure_JSL: case self.NotificationEvent.webrtcFailure_JSL: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.stateReverted_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.REMOTE_UNHOLDING: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.remoteUnHoldProcessed_JSL: call.currentState = self.CallFSMState.COMPLETED; if (call.previousState === self.CallFSMState.BOTH_HOLD) { call.currentState = self.CallFSMState.LOCAL_HOLD; } call.previousState = callState; onSuccess(call, self.TransferEvent.remoteUnHold_fsm); break; case self.NotificationEvent.requestFailure_JSL: case self.NotificationEvent.webrtcFailure_JSL: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.stateReverted_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.REMOTE_HOLD: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.startCallUpdate_remoteHold_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.REMOTE_HOLDING; onSuccess(call, self.TransferEvent.remoteHolding_fsm); break; case self.NotificationEvent.startCallUpdate_remoteOffer_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.REMOTE_UNHOLDING; onSuccess(call, self.TransferEvent.remoteUnHolding_fsm); break; case self.NotificationEvent.startCallUpdate_slowStart_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_SLOW_START_OFFER; onSuccess(call, self.TransferEvent.slowStartOfferDuringRemoteHold_fsm); break; case self.NotificationEvent.hold_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_HOLDING; onSuccess(call, self.TransferEvent.localHolding_fsm); break; case self.NotificationEvent.joining_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.JOINING; onSuccess(call, self.TransferEvent.joining_fsm); break; case self.NotificationEvent.performReconnectWorkaround_JSL: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_REOFFER; onSuccess(call, self.TransferEvent.performReconnectWorkaround_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.BOTH_HOLD: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.startCallUpdate_remoteHold_Notify: case self.NotificationEvent.startCallUpdate_remoteOffer_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.REMOTE_UNHOLDING; onSuccess(call, self.TransferEvent.remoteUnHolding_fsm); break; case self.NotificationEvent.unhold_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_UNHOLDING; onSuccess(call, self.TransferEvent.localUnHolding_fsm); break; case self.NotificationEvent.joining_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.JOINING; onSuccess(call, self.TransferEvent.joining_fsm); break; case self.NotificationEvent.transfering: call.previousState = call.currentState; call.currentState = self.CallFSMState.TRANSFERING; onSuccess(call, self.TransferEvent.transfering_fsm); break; case self.NotificationEvent.performReconnectWorkaround_JSL: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_REOFFER; onSuccess(call, self.TransferEvent.performReconnectWorkaround_fsm); break; case self.NotificationEvent.consultativeTransfer_GUI: call.previousState = call.currentState; call.currentState = self.CallFSMState.TRANSFERING; onSuccess(call, self.TransferEvent.transfering_fsm); break; case self.NotificationEvent.startCallUpdate_slowStart_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.LOCAL_SLOW_START_OFFER; onSuccess(call, self.TransferEvent.slowStartOfferDuringRemoteHold_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.LOCAL_SLOW_START_OFFER: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.respondCallUpdate_Notify: call.previousState = call.currentState; call.currentState = self.CallFSMState.COMPLETED; onSuccess(call, self.TransferEvent.respondCallUpdate_fsm); break; case self.NotificationEvent.requestFailure_JSL: case self.NotificationEvent.webrtcFailure_JSL: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.stateReverted_fsm); break; case self.NotificationEvent.slowStartOfferProcessed_JSL: onSuccess(call, self.TransferEvent.slowStartOfferProcessed_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.JOINING: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.sessionComplete_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.sessionComplete_fsm); break; case self.NotificationEvent.sessionFail_Notify: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.sessionFail_fsm); break; case self.NotificationEvent.refer_JSL: call.currentState = self.CallFSMState.REFER; onSuccess(call, self.TransferEvent.refer_fsm); break; case self.NotificationEvent.revertState_JSL: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.stateReverted_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.REFER: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.sessionComplete_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.sessionComplete_fsm); break; case self.NotificationEvent.sessionFail_Notify: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.sessionFail_fsm); break; //TODO Tolga - talk with lale case self.NotificationEvent.accepted_Notify: onSuccess(call, self.TransferEvent.accepted_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.TRANSFERING: switch (event) { case self.NotificationEvent.end_GUI: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnding_fsm); break; case self.NotificationEvent.callEnd_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.remoteEnd_fsm); break; case self.NotificationEvent.sessionComplete_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.transferSuccess_fsm); break; case self.NotificationEvent.sessionFail_Notify: call.currentState = call.previousState; onSuccess(call, self.TransferEvent.transferFail_fsm); break; //TODO this notification is consumed for now - it is there for completeness case self.NotificationEvent.accepted_Notify: onSuccess(call, self.TransferEvent.accepted_fsm); break; case self.NotificationEvent.startCallUpdate_slowStart_Notify: case self.NotificationEvent.startCallUpdate_remoteHold_Notify: case self.NotificationEvent.startCallUpdate_remoteOffer_Notify: // Some client send hold during transfer onSuccess(call, self.TransferEvent.remoteCallUpdate_fsm); break; default: onFailure(call, self.TransferEvent.unknownNotification_fsm); break; } break; case self.CallFSMState.LOCAL_ENDING: switch (event) { case self.NotificationEvent.callEnd_Notify: case self.NotificationEvent.callCancel_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localEnd_fsm); break; } break; case self.CallFSMState.LOCAL_REJECTING: switch (event) { case self.NotificationEvent.callEnd_Notify: case self.NotificationEvent.callCancel_Notify: call.currentState = self.CallFSMState.INIT; onSuccess(call, self.TransferEvent.localReject_fsm); break; } } } self.getCurrentState = function (call) { return call.currentState ? call.currentState : self.CallFSMState.INIT; }; this.handleEvent = function (call, event, handler) { var initialCallState; if (call) { initialCallState = self.getCurrentState(call); logger.info('FSM received NotificationEvent: ' + event + ' @ ' + initialCallState + ' state' + '. Call Id: ' + call.id); FSM(call, event, function (call, transferEvent) { logger.debug('FSM handleEvent successful. (Call FSM) State Passed from ' + initialCallState + ' to ' + self.getCurrentState(call) + '. TransferEvent: ' + transferEvent + '. Call Id: ' + call.id); handler(call, transferEvent); }, function (call, transferEvent) { logger.error('FSM handleEvent failure: ' + transferEvent + ' @ ' + self.getCurrentState(call) + '. Call Id: ' + call.id); handler(call, transferEvent); }); } }; } /***/ }), /***/ "../fcs/src/js/call/wam/callManager.js": /*!*********************************************!*\ !*** ../fcs/src/js/call/wam/callManager.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.CallManagerImpl = CallManagerImpl; var _constants = __webpack_require__(/*! ../../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); var _utils2 = __webpack_require__(/*! ../../utils */ "../fcs/src/js/utils/index.js"); var _errors = __webpack_require__(/*! ../../errors */ "../fcs/src/js/errors.js"); var _errors2 = _interopRequireDefault(_errors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function CallManagerImpl(_ref) { var _webRtcManager = _ref.WebRtcManager, _callFSM = _ref.CallFSM, _callControlService = _ref.CallControlService, _sdpParser = _ref.SdpParser, _logManager = _ref.LogManager, _globalBroadcaster = _ref.GlobalBroadcaster, _utils = _ref.Utils, _core = _ref.Core, _config = _ref.Config, _cache = _ref.Cache, _notificationCallBacks = _ref.NotificationCallbacks; /* AUDIT_KICKOFF_TIMEOUT is the interval we use to kickoff call audit after the call is setup. * The timeout is there to ensure we do not hit call setup race conditions when we try to kickoff the call audit */ var calls = {}, bridges = [], logger = _logManager.getLogger('callManager'), AUDIT_KICKOFF_TIMEOUT = 3000, isReconnected = false, fsmNotificationEvent = _callFSM.NotificationEvent, fsmState = _callFSM.CallFSMState, self = this, isQueueEnabled = true, startCallInProgress = 0, startCallQueue = [], NOTIFICATION_STATE = { BUSY: 0, IDLE: 1 }, CALL_STATES = { IN_CALL: 0, ON_HOLD: 1, RINGING: 2, ENDED: 3, REJECTED: 4, OUTGOING: 5, INCOMING: 6, ANSWERING: 7, JOINED: 8, RENEGOTIATION: 9, TRANSFERRED: 10, ON_REMOTE_HOLD: 11, CALL_IN_PROGRESS: 12, EARLY_MEDIA: 13, TRANSFER_FAILURE: 14, REPLACING: 15 }, CALL_HOLD_STATES = { LOCAL_HOLD: 0, REMOTE_HOLD: 1, BOTH_HOLD: 2 }, LOCAL_STATUS_CODES = { STATUS_CODE_NOT_PROVIDED: '9900', ENDED_BY_LOCAL: '9901', REJECTED_BY_LOCAL: '9902', IGNORED_BY_LOCAL: '9903', RESPONDED_FROM_ANOTHER_DEVICE: '9904', SESSION_COMPLETED: '9905', JOIN_COMPLETED: '9906', TRANSFERRED: '9907' }, LOCAL_REASON_TEXTS = { STATUS_CODE_NOT_PROVIDED: 'Reason not provided', ENDED_BY_LOCAL: 'Ended by local user', REJECTED_BY_LOCAL: 'Rejected by local user', IGNORED_BY_LOCAL: 'Ignored by local user', RESPONDED_FROM_ANOTHER_DEVICE: 'Responded from another device', SESSION_COMPLETED: 'Session completed', JOIN_COMPLETED: 'Join operation has completed', TRANSFERRED: 'Transferred by remote user' }; this.IncomingCall = function (callid, data) { var id = callid, options = data, sendVideo = true, isJoin = false, buttonDisabler = false, btnTimeout, auditTimer; this.isOutgoing = false; this.notificationQueue = new _utils2.Queue(); this.onLocalStreamAdded = null; this.onStreamAdded = null; this.onMute = null; this.onStateChange = null; this.timestamp = Date.now(); this.getRemoteVideoState = function () { return self.getRemoteVideoState(callid); }; this.mute = function () { var param = { callid: id, mute: true }; return self.mute(param); }; this.unmute = function () { var param = { callid: id, mute: false }; return self.mute(param); }; this.answer = function (onSuccess, onFailure, sendInitialVideo, videoResolution, params) { var param = { callid: id, sendInitialVideo: sendInitialVideo, videoResolution: videoResolution }; param = (0, _utils2.extend)(param, params); if (options.answer) { return self.answer(param, onSuccess, onFailure); } else { _utils.callFunctionIfExist(onFailure, _core.Errors.NOT_ALLOWED_SERVICE); } }; this.reject = function (onSuccess, onFailure) { var param = { callid: id }; if (options.reject) { return self.reject(param, onSuccess, onFailure); } else { _utils.callFunctionIfExist(onFailure, _core.Errors.NOT_ALLOWED_SERVICE); } }; this.ignore = function (onSuccess, onFailure) { var param = { callid: id }; return self.ignore(param, onSuccess, onFailure); }; this.forward = function (address, onSuccess, onFailure) { var param = { callid: id, address: address }; if (options.forward) { return self.forward(param, onSuccess, onFailure); } else { _utils.callFunctionIfExist(onFailure, _core.Errors.NOT_ALLOWED_SERVICE); } }; this.canReject = function () { return options.reject === true; }; this.canForward = function () { return options.forward === true; }; this.canAnswer = function () { return options.answer === true; }; this.canSendVideo = function () { var param = { callid: id }; return self.canOriginatorSendLocalVideo(param); }; this.canReceiveVideo = function () { var param = { callid: id }; return self.canOriginatorReceiveRemoteVideo(param); }; this.getHoldState = function () { var param = { callid: id }; return self.getHoldStateOfCall(param); }; this.getCustomParameters = function () { var param = { callid: id }; return self.getCustomParametersOfCall(param); }; this.setCustomParameters = function (customParams) { var param = { callid: id, customParams: customParams }; return self.setCustomParametersOfCall(param); }; this.getId = function () { return id; }; this.end = function (onSuccess, onFailure) { var param = { callid: id }; return self.end(param, onSuccess, onFailure); }; this.hold = function (onSuccess, onFailure) { var param = { callid: id }; return self.hold(param, onSuccess, onFailure); }; this.unhold = function (onSuccess, onFailure) { var param = { callid: id }; return self.unhold(param, onSuccess, onFailure); }; this.getWebRtcStats = function (onSuccess, onFailure) { var param = { callid: id }; return self.getWebRtcStats(param, onSuccess, onFailure); }; this.getNativeWebRtcStats = function (onSuccess, onFailure) { var param = { callid: id }; return self.getNativeWebRtcStats(param, onSuccess, onFailure); }; this.startWebRtcStatsTimer = function (interval, onSuccess, onFailure) { var param = { callid: id, interval: interval }; return self.startWebRtcStatsTimer(param, onSuccess, onFailure); }; this.stopWebRtcStatsTimer = function () { var param = { callid: id }; return self.stopWebRtcStatsTimer(param); }; this.directTransfer = function (address, onSuccess, onFailure) { var param = { callid: id, address: address }; return self.directTransfer(param, onSuccess, onFailure); }; this.consultativeTransfer = function (transferredCallId, onSuccess, onFailure) { var param = { currentCallId: id, targetCallId: transferredCallId }; return self.consultativeTransfer(param, onSuccess, onFailure); }; this.videoStop = function (onSuccess, onFailure) { var param = { callid: id, isVideoStart: false }; return self.videoStopStart(param, onSuccess, onFailure); }; this.videoStart = function (onSuccess, onFailure, videoResolution) { var param = { callid: id, isVideoStart: true, videoResolution: videoResolution }; return self.videoStopStart(param, onSuccess, onFailure); }; this.getMediaStream = function () { return self.getMediaStream(id); }; /** * Start sharing the screen for this call after the call is established. * * @name fcs.call.IncomingCall#screenSharingStart * @function * @param {function} [onSuccess] The onSuccess() to be called when the screen sharing is started * @param {function} [onFailure] The onFailure() to be called when the screen sharing could not be started * @param {function} [onStopped] The onStopped() to be called when the user has clicked to stop sharing the screen. * @param {object} [options] The screen sharing options * @param {number} [options.width=1024] The width of the screen to request. * @param {number} [options.height=768] The height of the screen to request. * @param {number} [options.frameRate=15] The number of frames per second to request. */ this.screenSharingStart = function (onSuccess, onFailure, onStopped, options) { var param = { callid: id, isScreenStart: true, options: options }; self.screenStopStart(param, onSuccess, onFailure, onStopped); }; /** * Stop sharing the screen for this call after the call is established. * * @name fcs.call.OutgoingCall#screenSharingStop * @function * @param {function} [onSuccess] The onSuccess() to be called when the screen sharing is stopped. * @param {function} [onFailure] The onFailure() to be called when the screen sharing could not be stopped. */ this.screenSharingStop = function (onSuccess, onFailure) { var param = { callid: id, isScreenStart: false, options: {} }; self.screenStopStart(param, onSuccess, onFailure, null); }; this.join = function (anotherCall, onSuccess, onFailure, isVideoEnabled, videoResolution) { var param = { callid1: id, callid2: anotherCall.getId() }; return self.join(param, onSuccess, onFailure, isVideoEnabled, videoResolution); }; this.sendDTMF = function (tone) { var param = { callid: id, tone: tone }; return self.sendDTMF(param); }; this.sendCustomParameters = function (onSuccess, onFailure) { var param = { callid: id }; return self.sendCustomParameters(param, onSuccess, onFailure); }; this.sendIntraFrame = function () { var param = { callid: id }; if (sendVideo) { return self.sendIntraFrame(param); } }; this.sendBlackFrame = function () { var param = { callid: id }; return self.sendBlackFrame(param); }; this.refreshVideoRenderer = function () { var param = { callid: id }; return self.refreshVideoRenderer(param); }; this.getJoin = function () { return isJoin; }; this.setJoin = function (join) { isJoin = join; }; this.getButtonDisabler = function () { return buttonDisabler; }; this.setButtonDisabler = function (disable) { buttonDisabler = disable; if (buttonDisabler) { btnTimeout = setTimeout(function () { buttonDisabler = false; }, 4000); } }; this.clearBtnTimeout = function () { clearTimeout(btnTimeout); }; this.setAuditTimer = function (audit) { auditTimer = setInterval(function () { audit(); }, _config.callAuditTimer ? _config.callAuditTimer : 30000); }; this.clearAuditTimer = function () { clearInterval(auditTimer); }; this.isCallMuted = function () { var param = { callid: id }; return self.isCallMuted(param); }; /* DEPRECIATED */ this.isVideoNegotationAvailable = function (id) { var param = { callid: id }; return self.isVideoNegotationAvailable(param); }; this.isVideoNegotiationAvailable = function () { var param = { callid: id }; return self.isVideoNegotiationAvailable(param); }; this.changeDevices = function () { var param = { callid: id }; return self.changeDevices(param); }; }; this.OutgoingCall = function (callid) { var id = callid, sendVideo = true, isJoin = false, buttonDisabler = false, btnTimeout, auditTimer; this.isOutgoing = true; this.notificationQueue = new _utils2.Queue(); this.onLocalStreamAdded = null; this.onStreamAdded = null; this.onMute = null; this.onStateChange = null; this.timestamp = Date.now(); this.canSendVideo = function () { var param = { callid: id }; return self.canOriginatorSendLocalVideo(param); }; this.getRemoteVideoState = function () { return self.getRemoteVideoState(callid); }; this.canSendVideo = function () { var param = { callid: id }; return self.canOriginatorSendLocalVideo(param); }; this.canReceiveVideo = function () { var param = { callid: id }; return self.canOriginatorReceiveRemoteVideo(param); }; this.getHoldState = function () { var param = { callid: id }; return self.getHoldStateOfCall(param); }; this.getCustomParameters = function () { var param = { callid: id }; return self.getCustomParametersOfCall(param); }; this.setCustomParameters = function (customParams) { var param = { callid: id, customParams: customParams }; return self.setCustomParametersOfCall(param); }; this.getId = function () { return id; }; this.sendIntraFrame = function () { var param = { callid: id }; if (sendVideo) { return self.sendIntraFrame(param); } }; this.sendBlackFrame = function () { var param = { callid: id }; return self.sendBlackFrame(param); }; this.refreshVideoRenderer = function () { var param = { callid: id }; return self.refreshVideoRenderer(param); }; this.mute = function () { var param = { callid: id, mute: true }; return self.mute(param); }; this.unmute = function () { var param = { callid: id, mute: false }; return self.mute(param); }; this.end = function (onSuccess, onFailure) { var param = { callid: id }; return self.end(param, onSuccess, onFailure); }; this.hold = function (onSuccess, onFailure) { var param = { callid: id }; return self.hold(param, onSuccess, onFailure); }; this.unhold = function (onSuccess, onFailure) { var param = { callid: id }; return self.unhold(param, onSuccess, onFailure); }; this.getWebRtcStats = function (onSuccess, onFailure) { var param = { callid: id }; return self.getWebRtcStats(param, onSuccess, onFailure); }; this.getNativeWebRtcStats = function (onSuccess, onFailure) { var param = { callid: id }; return self.getNativeWebRtcStats(param, onSuccess, onFailure); }; this.startWebRtcStatsTimer = function (interval, onSuccess, onFailure) { var param = { callid: id, interval: interval }; return self.startWebRtcStatsTimer(param, onSuccess, onFailure); }; this.stopWebRtcStatsTimer = function () { var param = { callid: id }; return self.stopWebRtcStatsTimer(param); }; this.directTransfer = function (address, onSuccess, onFailure) { var param = { callid: id, address: address }; return self.directTransfer(param, onSuccess, onFailure); }; this.consultativeTransfer = function (transfaredCallId, onSuccess, onFailure) { var param = { currentCallId: id, targetCallId: transfaredCallId }; return self.consultativeTransfer(param, onSuccess, onFailure); }; this.videoStop = function (onSuccess, onFailure) { var param = { callid: id, isVideoStart: false }; return self.videoStopStart(param, onSuccess, onFailure); }; this.videoStart = function (onSuccess, onFailure, videoResolution) { var param = { callid: id, isVideoStart: true, videoResolution: videoResolution }; return self.videoStopStart(param, onSuccess, onFailure); }; this.getMediaStream = function () { return self.getMediaStream(id); }; /** * Start sharing the screen for this call after the call is established. * * @name fcs.call.OutgoingCall#screenSharingStart * @function * @param {function} [onSuccess] The onSuccess() to be called when the screen sharing is started * @param {function} [onFailure] The onFailure() to be called when the screen sharing could not be started * @param {function} [onStopped] The onStopped() to be called when the user has clicked to stop sharing the screen. * @param {object} [options] The screen sharing options * @param {number} [options.width=1024] The width of the screen to request. * @param {number} [options.height=768] The height of the screen to request. * @param {number} [options.frameRate=15] The number of frames per second to request. */ this.screenSharingStart = function (onSuccess, onFailure, onStopped, options) { var param = { callid: id, isScreenStart: true, options: options }; self.screenStopStart(param, onSuccess, onFailure, onStopped); }; /** * Stop sharing the screen for this call after the call is established. * * @name fcs.call.OutgoingCall#screenSharingStop * @function * @param {function} [onSuccess] The onSuccess() to be called when the screen sharing is stopped. * @param {function} [onFailure] The onFailure() to be called when the screen sharing could not be stopped. */ this.screenSharingStop = function (onSuccess, onFailure) { var param = { callid: id, isScreenStart: false, options: {} }; self.screenStopStart(param, onSuccess, onFailure, null); }; this.join = function (anotherCall, onSuccess, onFailure, isVideoEnabled, videoResolution) { var param = { callid1: id, callid2: anotherCall.getId() }; return self.join(param, onSuccess, onFailure, isVideoEnabled, videoResolution); }; this.sendDTMF = function (tone) { var param = { callid: id, tone: tone }; return self.sendDTMF(param); }; this.sendCustomParameters = function (onSuccess, onFailure) { var param = { callid: id }; return self.sendCustomParameters(param, onSuccess, onFailure); }; this.getJoin = function () { return isJoin; }; this.setJoin = function (join) { isJoin = join; }; this.getButtonDisabler = function () { return buttonDisabler; }; this.setButtonDisabler = function (disable) { buttonDisabler = disable; if (buttonDisabler) { btnTimeout = setTimeout(function () { buttonDisabler = false; }, 4000); } }; this.clearBtnTimeout = function () { clearTimeout(btnTimeout); }; this.setAuditTimer = function (audit) { auditTimer = setInterval(function () { audit(); }, _config.callAuditTimer ? _config.callAuditTimer : 30000); }; this.clearAuditTimer = function () { clearInterval(auditTimer); }; this.isCallMuted = function () { var param = { callid: id }; return self.isCallMuted(param); }; /* DEPRECIATED */ this.isVideoNegotationAvailable = function (id) { var param = { callid: id }; return self.isVideoNegotationAvailable(param); }; this.isVideoNegotiationAvailable = function () { var param = { callid: id }; return self.isVideoNegotiationAvailable(param); }; this.changeDevices = function () { var param = { callid: id }; return self.changeDevices(param); }; }; this.LocalAudioBridge = function () { var bridgedCalls = []; /** * This reserves a property name for a callback method which keeps * the state of the Kandy SDK informed about which active calls exist * in this bridge * * @type {Function} */ this.onCallsChange = null; this.muteLocalAudio = function () { bridgedCalls.forEach(function (bridgedCall) { _webRtcManager.muteAudioTrack(bridgedCall, true); }); }; this.unmuteLocalAudio = function () { bridgedCalls.forEach(function (bridgedCall) { _webRtcManager.muteAudioTrack(bridgedCall, false); }); }; this.add = function (call, onSuccess, onFailure) { var internalCall; if (!(call instanceof self.IncomingCall) && !(call instanceof self.OutgoingCall)) { logger.error('LocalAudioBridge failure to add a non call object'); _utils.callFunctionIfExist(onFailure, _errors2.default.INVALID_PARAMETER); return; } internalCall = calls[call.getId()]; if (!internalCall) { logger.error('LocalAudioBridge failure to add a call which does not exist'); _utils.callFunctionIfExist(onFailure, _errors2.default.INVALID_PARAMETER); return; } if (internalCall.currentState === fsmState.LOCAL_HOLD) { logger.error('LocalAudioBridge failure to add a call which is on hold'); _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } if (internalCall.bridge) { logger.error('LocalAudioBridge failure to add a call which is already bridged'); _utils.callFunctionIfExist(onFailure, _errors2.default.ENTRY_ALREADY_EXISTS); return; } logger.info('LocalAudioBridge adding call:' + internalCall.id); try { bridgedCalls.forEach(function (bridgedCall) { //verify if the call is not ended before merging if (bridgedCall.currentState && bridgedCall.currentState !== fsmState.INIT) { _webRtcManager.mergeAudioStream(bridgedCall, internalCall); } else { logger.debug('Cannot merge audio of calls with init State:' + bridgedCall.id); } }); } catch (e) { _utils.callFunctionIfExist(onFailure, e); return; } bridgedCalls.push(internalCall); internalCall.bridge = this; // Notify the SDK that the bridge's call list has changed, by accessing a callback method on the bridge _utils.callFunctionIfExist(this.onCallsChange, bridgedCalls); _utils.callFunctionIfExist(onSuccess); }; this.remove = function (call, onSuccess, onFailure) { var internalCall; if (!(call instanceof self.IncomingCall) && !(call instanceof self.OutgoingCall)) { logger.error('LocalAudioBridge failure to remove a non call object'); _utils.callFunctionIfExist(onFailure, _errors2.default.INVALID_PARAMETER); return; } internalCall = calls[call.getId()]; var bridgeIndex = bridgedCalls.indexOf(internalCall); if (bridgeIndex === -1) { logger.error('LocalAudioBridge failure to remove a call which is not in the bridge'); _utils.callFunctionIfExist(onFailure, _errors2.default.INVALID_PARAMETER); return; } logger.info('LocalAudioBridge removing call:' + internalCall.id); bridgedCalls.splice(bridgeIndex, 1); delete internalCall.bridge; // Notify the SDK that the bridge's call list has changed, by accessing a callback method on the bridge _utils.callFunctionIfExist(this.onCallsChange, bridgedCalls); try { bridgedCalls.forEach(function (bridgedCall) { if (bridgedCall.currentState && bridgedCall.currentState !== fsmState.INIT) { _webRtcManager.unMergeAudioStream(bridgedCall, internalCall); } }); } catch (e) { _utils.callFunctionIfExist(onFailure, e); } _utils.callFunctionIfExist(onSuccess); }; this.close = function () { var call; logger.info('Closing LocalAudioBridge'); while (bridgedCalls.length > 0) { call = bridgedCalls.pop(); if (call.currentState && call.currentState !== fsmState.INIT) { bridgedCalls.forEach(function (bridgedCall) { if (bridgedCall.currentState && bridgedCall.currentState !== fsmState.INIT) { try { _webRtcManager.unMergeAudioStream(bridgedCall, call); } catch (e) { logger.info('Could not unmerge stream for call:' + call.id); } } }); } delete call.bridge; } var bridgeIndex = bridges.indexOf(this); bridges.splice(bridgeIndex, 1); }; this.cleanInternalCall = function (internalCall) { logger.debug('Cleaning bridged call'); var callIndex = bridgedCalls.indexOf(internalCall); // This check used to compare for callIndex > 0, but it was determined that the call should be removed // even if it is the only call in the bridge if (callIndex > -1) { bridgedCalls.splice(callIndex, 1); delete internalCall.bridge; // Notify the SDK that the bridge's call list has changed, by accessing a callback method on the bridge _utils.callFunctionIfExist(this.onCallsChange, bridgedCalls); } }; }; self.consultativeTransfer = function (data, onSuccess, onFailure) { var internalCall = calls[data.currentCallId], targetCall = calls[data.targetCallId], currentCallState, targetCallState; internalCall.targetCallId = data.targetCallId; if (targetCall.callerNumber) { internalCall.targetAddress = targetCall.callerNumber; } else { internalCall.targetAddress = targetCall.call.callerNumber; } currentCallState = _callFSM.getCurrentState(internalCall); targetCallState = _callFSM.getCurrentState(targetCall); if ((currentCallState === fsmState.LOCAL_HOLD || currentCallState === fsmState.BOTH_HOLD) && (targetCallState === fsmState.LOCAL_HOLD || targetCallState === fsmState.BOTH_HOLD)) { _callControlService.transfer(internalCall.id, internalCall.targetAddress, internalCall.targetCallId, function () { logger.info('consultative transfer successful. callId: ' + internalCall.id); self.delegateToCallFSM(internalCall, fsmNotificationEvent.consultativeTransfer_GUI); _utils.callFunctionIfExist(onSuccess); }, function (e) { logger.error('consultative transfer failed. callId: ' + internalCall.id); _utils.callFunctionIfExist(onFailure, e); }); } else if (currentCallState === fsmState.LOCAL_HOLDING) { if (!internalCall.transferTrigger) { internalCall.transferTrigger = function () { self.consultativeTransfer(data, onSuccess, onFailure); delete this.transferTrigger; }; } else { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); } } else if (targetCallState === fsmState.LOCAL_HOLDING) { if (!targetCall.transferTrigger) { targetCall.transferTrigger = function () { self.consultativeTransfer(data, onSuccess, onFailure); delete this.transferTrigger; }; } else { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); } } else { logger.error('Cannot consultative transfer in INIT callstate :' + _core.Errors.STATE); _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); } }; /* * When connection re-establishes sets isReconnected flag true */ function onConnectionLost() { isReconnected = true; } /* * clear call resources * clear long call audit * clear webrtc resources * triger web part * * @param call call object * @param state state that will be returned to web part */ function clearResources(call, preserveCallObject) { var onSuccess, onFailure, callStats = call, bridge; if (call.call) { call.call.clearAuditTimer(); } if (call.pendingRequestTimer) { clearTimeout(call.pendingRequestTimer); } _webRtcManager.stopWebRtcStatsTimer(call); callStats.cache = true; _webRtcManager.getWebRtcStats(callStats, onSuccess, onFailure); //clear webRTC resources _webRtcManager.processEnd(call); bridge = call.bridge; if (bridge) { bridge.cleanInternalCall(call); } if (typeof preserveCallObject === 'undefined') { clearCallObject(call); } } function clearCallObject(call) { //clear call object delete calls[call.id]; } function setNotificationStateOfCallToBusy(internalCall) { logger.debug('Setting notification state to BUSY for call: ' + internalCall.id); internalCall.notificationState = NOTIFICATION_STATE.BUSY; } function setNotificationStateOfCallToIdle(internalCall) { logger.debug('Setting notification state to IDLE for call: ' + internalCall.id); internalCall.notificationState = NOTIFICATION_STATE.IDLE; } function isNotificationStateOfCallBusy(internalCall) { return internalCall.notificationState === NOTIFICATION_STATE.BUSY; } function triggerQueue(call) { if (!isQueueEnabled) { return; } logger.debug('NOTIFICATION_QUEUE: Process completed, notification queue state changed to IDLE'); setNotificationStateOfCallToIdle(call); if (call.call.notificationQueue.size() > 0) { logger.debug('NOTIFICATION_QUEUE: New notification found in queue, processing it!'); var notificationObj = call.call.notificationQueue.dequeue(); self.onNotificationEvent(notificationObj.type, notificationObj.sessionParams, notificationObj.callNotificationParams); } } function processStartCallQueue(internalCall) { //put the notification for the same call id that were received before the answer into the //call notificationQueue and remove any expired notifications. logger.info('Processing startCallQueue'); startCallQueue = startCallQueue.filter(function (notification) { if (notification.expires < Date.now()) { return false; } else if (notification.sessionParams.sessionData === internalCall.id) { internalCall.call.notificationQueue.enqueue(notification); return false; } return true; }); if (internalCall.call.notificationQueue.size() > 0) { setTimeout(function () { triggerQueue(internalCall); }, 1); } } function onSubscriptionReEstablished() { var id, internalCall; if (isReconnected) { isReconnected = false; for (id in calls) { if (calls.hasOwnProperty(id)) { internalCall = calls[id]; if (internalCall) { var defaultActiveCallTimeoutMS = 120000; // 2 minutes var activeCallTimeout = typeof _config.activeCallTimeoutMS !== 'undefined' ? _config.activeCallTimeoutMS : defaultActiveCallTimeoutMS; var callAge = Date.now() - internalCall.call.timestamp; // if there is a call, it's ringing, and it's old, end it. // Otherwise, process it. if (_callFSM.getCurrentState(internalCall) === fsmState.RINGING && callAge > activeCallTimeout) { // Send 0 to delete the call internalCall.call.onStateChange(CALL_STATES.ENDED, 0); clearResources(internalCall); } else { setNotificationStateOfCallToBusy(internalCall); self.delegateToCallFSM(internalCall, fsmNotificationEvent.performReconnectWorkaround_JSL); } } } } } } self.CALL_STATES = CALL_STATES; self.CALL_HOLD_STATES = CALL_HOLD_STATES; self.LOCAL_STATUS_CODES = LOCAL_STATUS_CODES; self.LOCAL_REASON_TEXTS = LOCAL_REASON_TEXTS; self.initMedia = function (data, onSuccess, onFailure) { _webRtcManager.initMedia(function () { _utils.callFunctionIfExist(onSuccess); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }, data.options); }; self.set_logSeverityLevel = function (data) { _webRtcManager.set_logSeverityLevel(data.level); }; self.enable_logCallback = function () { _webRtcManager.enable_logCallback(); }; self.disable_logCallback = function () { _webRtcManager.disable_logCallback(); }; self.get_audioInDeviceCount = function () { return _webRtcManager.get_audioInDeviceCount(); }; self.get_audioOutDeviceCount = function () { return _webRtcManager.get_audioOutDeviceCount(); }; self.get_videoDeviceCount = function () { return _webRtcManager.get_videoDeviceCount(); }; function mapGetUserMediaErrorToFcsError(e) { switch (e) { case _core.call.MediaErrors.NOT_FOUND: return _core.Errors.MEDIA_NOT_FOUND; case _core.call.MediaErrors.NOT_ALLOWED: return _core.Errors.MEDIA_NOT_ALLOWED; case _core.call.MediaErrors.INVALID_PARAMETER: return _core.Errors.INVALID_PARAMETER; default: return e; } } self.getUserMedia = function (data, onSuccess, onFailure) { if (data.privateStream) { _webRtcManager.privateGetUserMedia(onSuccess, function (e) { _utils.callFunctionIfExist(onFailure, mapGetUserMediaErrorToFcsError(e)); }, data); } else { _webRtcManager.getUserMedia(onSuccess, function (e) { _utils.callFunctionIfExist(onFailure, mapGetUserMediaErrorToFcsError(e)); }, data); } }; self.getWebRtcStats = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid]; return _webRtcManager.getWebRtcStats(internalCall, onSuccess, onFailure); }; self.getNativeWebRtcStats = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid]; return _webRtcManager.getNativeWebRtcStats(internalCall, onSuccess, onFailure); }; self.startWebRtcStatsTimer = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], interval; if (data.interval !== parseInt(data.interval, 10)) { return; } // Change interval value(seconds) to miliseconds interval = parseInt(data.interval) * 1000; return _webRtcManager.startWebRtcStatsTimer(internalCall, interval, onSuccess, onFailure); }; self.stopWebRtcStatsTimer = function (data) { var internalCall = calls[data.callid]; return _webRtcManager.stopWebRtcStatsTimer(internalCall); }; self.showSettingsWindow = function (data, onSuccess, onFailure) { _webRtcManager.showSettingsWindow(function () { _utils.callFunctionIfExist(onSuccess); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }, data.options); }; self.createStreamRenderer = function (data) { return _webRtcManager.createStreamRenderer(data.streamId, data.container, data.options); }; self.disposeStreamRenderer = function (data) { _webRtcManager.disposeStreamRenderer(data.container); }; self.createLocalAudioBridge = function (options, onSuccess, onFailure) { if (_webRtcManager.canMergeAudio()) { var bridge = new self.LocalAudioBridge(options); bridges.push(bridge); _utils.callFunctionIfExist(onSuccess, bridge); } else { logger.error('LocalAudioBridge not supported in this browser'); _utils.callFunctionIfExist(onFailure); } }; self.isPluginEnabled = function () { return _webRtcManager.isPluginEnabled(); }; self.hasGotCalls = function () { var callid, internalCall; for (callid in calls) { if (calls.hasOwnProperty(callid)) { internalCall = calls[callid]; if (internalCall) { logger.info('has got call - id: ' + callid + ' - state: ' + _callFSM.getCurrentState(internalCall)); return true; } } } return false; }; self.getCalls = function () { return calls; }; self.sendIntraFrame = function (data) { var internalCall = calls[data.callid]; if (internalCall) { _webRtcManager.sendIntraFrame(internalCall); } }; self.sendBlackFrame = function (data) { var internalCall = calls[data.callid]; if (internalCall) { _webRtcManager.sendBlackFrame(internalCall); } }; self.delegateToCallFSM = function (call, stateMessage) { _callFSM.handleEvent(call, stateMessage, self.onStateChange); }; self.setUpdateCandidateCallbackToCall = function (call) { call.updateCandidates = function (candidateArray) { _callControlService.updateIceCandidate({ id: call.id, iceCandidates: candidateArray }); }; }; self.answer = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], videoNegotiationAvailable = self.isVideoNegotiationAvailable(data), opts = { videoResolution: data.videoResolution }, offerToReceiveVideo; opts.isAudioEnabled = data.isAudioEnabled === false ? false : true; logger.info('Answering ' + (videoNegotiationAvailable ? 'video' : 'audio') + ' call with microphone ' + (opts.isAudioEnabled ? 'on' : 'off') + ' and camera' + (opts.sendInitialVideo ? 'on' : 'off')); if (internalCall) { if (internalCall.sdp) { //check with the state machine if the current state would accept an answer. if (_callFSM.getCurrentState(internalCall) !== fsmState.RINGING) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); } else { opts.isVideoEnabled = videoNegotiationAvailable === false ? false : data.sendInitialVideo; self.getUserMedia(opts, function getUserMediaSuccessCallback(mediaInfo) { internalCall.isVideoSourceAllowed = mediaInfo.video; internalCall.isVideoEnabled = data.sendInitialVideo; internalCall.customParameters = data.customParameters; _webRtcManager.storeLocalStreamToCall(internalCall, mediaInfo.id); _webRtcManager.createAnswer(internalCall, function createAnswerSuccessCallback(sdp) { logger.info('[callManager.answer : sdp ]' + sdp); //change call state self.delegateToCallFSM(internalCall, fsmNotificationEvent.answer_GUI); //send answer call _callControlService.answerCall(internalCall.id, sdp, function () { _utils.callFunctionIfExist(onSuccess); _webRtcManager.addLocalStream(internalCall); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }, data.customParameters); }, function createAnswerFailureCallback(e) { logger.error('[callManager.answer] Error : ' + e); //Change state when the call have failed //This will trigger send reject self.delegateToCallFSM(internalCall, fsmNotificationEvent.end_GUI); // Call the failure callback, so the application knows it was // an error that occurred. _utils.callFunctionIfExist(onFailure, e); }, data.sendInitialVideo); }, function getUserMediaFailureCallback(e) { _utils.callFunctionIfExist(onFailure, e); }); } } else { //slow start case if (_callFSM.getCurrentState(internalCall) !== fsmState.RINGING_SLOW) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); } else { offerToReceiveVideo = data.sendInitialVideo ? true : data.isVideoEnabled; opts.isVideoEnabled = data.sendInitialVideo; logger.info('[callManager.answer] Answering call in slow start scenario.'); self.getUserMedia(opts, function getUserMediaSuccessCallback(mediaInfo) { internalCall.isVideoSourceAllowed = mediaInfo.video; internalCall.isVideoEnabled = data.sendInitialVideo; internalCall.customParameters = data.customParameters; _webRtcManager.storeLocalStreamToCall(internalCall, mediaInfo.id); _webRtcManager.createOffer(internalCall, function createOfferSuccessCallback(sdp) { internalCall.sdp = sdp; self.delegateToCallFSM(internalCall, fsmNotificationEvent.answer_GUI); _callControlService.answerCall(internalCall.id, sdp, function () { _utils.callFunctionIfExist(onSuccess); _webRtcManager.addLocalStream(internalCall); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }, data.customParameters); }, function createOfferFailureCallback(e) { logger.error('[callManager.offer] Error : ' + e); //Change state when the call have failed //This will trigger send reject self.delegateToCallFSM(internalCall, fsmNotificationEvent.end_GUI); // Call the failure callback, so the application knows it was // an error that occurred. _utils.callFunctionIfExist(onFailure, e); }, data.sendInitialVideo, offerToReceiveVideo, true); }, function getUserMediaFailureCallback(e) { _utils.callFunctionIfExist(onFailure, e); }); } } } }; self.getIncomingCallById = function (data) { var call = null, cachedCall, internalCall; cachedCall = JSON.parse(_cache.getItem(data.callid)); if (cachedCall) { call = new self.IncomingCall(data.callid, { reject: cachedCall.optionReject, forward: cachedCall.optionForward, answer: cachedCall.optionAnswer }); call.canOrigReceiveVideo = _sdpParser.isSdpHasVideo(cachedCall.sdp); call.callerNumber = cachedCall.callerNumber; call.callerName = cachedCall.callerName; call.calleeNumber = cachedCall.calleeNumber; call.primaryContact = cachedCall.primaryContact; internalCall = { 'call': call, 'sdp': cachedCall.sdp, 'id': data.callid }; calls[data.callid] = internalCall; self.delegateToCallFSM(internalCall, fsmNotificationEvent.callNotify); } return call; }; function cacheCall(internalCall) { var callToCache = { 'sdp': internalCall.sdp, 'callerNumber': internalCall.call.callerNumber, 'callerName': internalCall.call.callerName, 'calleeNumber': internalCall.call.calleeNumber, 'primaryContact': internalCall.call.primaryContact, 'optionReject': internalCall.call.canReject(), 'optionForward': internalCall.call.canForward(), 'optionAnswer': internalCall.call.canAnswer() }; _cache.setItem(internalCall.id, (0, _stringify2.default)(callToCache)); } self.start = function (data, onSuccess, onFailure) { var internalCall = {}, screenShare = data.sendScreenShare, sendInitialVideo = data.sendInitialVideo || screenShare, offerToReceiveVideo = sendInitialVideo ? true : data.isVideoEnabled, opts = { isVideoEnabled: data.sendInitialVideo, videoResolution: data.videoResolution, isAudioEnabled: data.isAudioEnabled === false ? false : screenShare ? false : true, requestScreenShare: screenShare, mediaSourceId: data.mediaSourceId }; //We should not allow to make a call without media if (!opts.isAudioEnabled && !opts.isVideoEnabled && !screenShare) { logger.error('Cannot make a call without media.'); _utils.callFunctionIfExist(onFailure, _errors2.default.MEDIA_REQUIRED); return; } logger.info('start call... with data: ' + (0, _stringify2.default)(data)); self.getUserMedia(opts, function getUserMediaSuccessCallback(mediaInfo) { internalCall.isVideoSourceAllowed = mediaInfo.video ? true : false; internalCall.isVideoEnabled = sendInitialVideo; internalCall.isScreenShared = screenShare; _webRtcManager.storeLocalStreamToCall(internalCall, mediaInfo.id); self.setUpdateCandidateCallbackToCall(internalCall); _webRtcManager.createOffer(internalCall, function createOfferSuccessCallback(sdp) { logger.info('[callManager.start : sdp ]' + sdp); internalCall.sdp = sdp; startCallInProgress++; _callControlService.startCall((0, _utils2.parseAddress)(data.from, data.contact), (0, _utils2.parseAddress)(data.to), sdp, function (callid) { internalCall.call = new self.OutgoingCall(callid); internalCall.id = callid; internalCall.callerNumber = data.to; internalCall.customParameters = data.customParameters; // Track the remote participant for an outgoing call. internalCall.call.remoteParticipant = { displayNumber: data.to }; self.delegateToCallFSM(internalCall, fsmNotificationEvent.callStart_GUI); calls[callid] = internalCall; startCallInProgress--; if (startCallQueue.length > 0) { processStartCallQueue(internalCall); } // we need to wait until call variable to be created setTimeout(function () { _webRtcManager.addLocalStream(internalCall); }, 10); _utils.callFunctionIfExist(onSuccess, internalCall.call); }, function (e) { startCallInProgress--; //TODO: update call state _utils.callFunctionIfExist(onFailure, e); }, data.customParameters); }, function createOfferFailureCallback(e) { logger.error('[callManager.start] Error : ' + e); _utils.callFunctionIfExist(onFailure, e); }, sendInitialVideo, offerToReceiveVideo); }, function getUserMediaFailureCallback(e) { _utils.callFunctionIfExist(onFailure, e); }); }; self.reject = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid]; if (!internalCall) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } self.delegateToCallFSM(internalCall, fsmNotificationEvent.endReject_GUI); _callControlService.reject(data.callid, function () { _utils.callFunctionIfExist(onSuccess); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }); }; self.sendCustomParameters = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid]; if (!internalCall) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } var customParameters = internalCall.customParameters; if (customParameters) { _callControlService.sendCustomParameters(data.callid, customParameters, function () { _utils.callFunctionIfExist(onSuccess); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }); } else { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); } }; self.ignore = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid]; if (!internalCall) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } self.delegateToCallFSM(internalCall, fsmNotificationEvent.endIgnore_GUI); _utils.callFunctionIfExist(onSuccess); }; self.forward = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid]; if (!internalCall) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } _callControlService.forward(data.callid, data.address, function () { self.delegateToCallFSM(internalCall, fsmNotificationEvent.forward_GUI); _utils.callFunctionIfExist(onSuccess); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }); }; function handleFailure(internalCall, failureHandler, failureEvent, retry) { setNotificationStateOfCallToBusy(internalCall); _webRtcManager.revertRtcState(internalCall, triggerQueue, triggerQueue); if (failureEvent) { self.delegateToCallFSM(internalCall, failureEvent); } if (retry && retry.timeout) { internalCall.pendingRequestTimer = setTimeout(function () { internalCall.pendingRequestTimer = null; retry.args.push(true); retry.handler.apply(null, retry.args); }, retry.timeout * 1000); } else { if (failureHandler) { // TODO: need to add an error code _utils.callFunctionIfExist(failureHandler); } } } function handleRequestFailure(internalCall, failureHandler, retry) { handleFailure(internalCall, failureHandler, fsmNotificationEvent.requestFailure_JSL, retry); } function handleWebrtcFailure(internalCall, failureHandler) { handleFailure(internalCall, failureHandler, fsmNotificationEvent.webrtcFailure_JSL); } self.getMediaStream = function (callId) { var internalCall = calls[callId]; if (internalCall.localMedia) { return internalCall.localMedia.originalStream; } else { return null; } }; self.hold = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], currentCallState; if (!internalCall) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } if (isNotificationStateOfCallBusy(internalCall)) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } currentCallState = _callFSM.getCurrentState(internalCall); if (currentCallState !== fsmState.COMPLETED && currentCallState !== fsmState.REMOTE_HOLD) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } if (internalCall.pendingRequestTimer) { _utils.callFunctionIfExist(onFailure, _core.Errors.PENDING_REQUEST); return; } internalCall.lastUpdateRequest = { handler: self.hold, args: [data, onSuccess, onFailure] }; setNotificationStateOfCallToBusy(internalCall); self.delegateToCallFSM(internalCall, fsmNotificationEvent.hold_GUI); _webRtcManager.createHoldUpdate(internalCall, true, currentCallState === fsmState.REMOTE_HOLD, function (sdp) { logger.debug('[callManager.hold->createHoldUpdate : sdp ]' + sdp); _callControlService.hold(internalCall.id, sdp, function () { triggerQueue(internalCall); _utils.callFunctionIfExist(onSuccess); }, function (err) { handleRequestFailure(internalCall, onFailure, { handler: self.hold, args: [data, onSuccess, onFailure], timeout: err.retryAfter }); }, internalCall.customParameters); }, function () { handleWebrtcFailure(internalCall, onFailure); }); }; self.unhold = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], currentCallState; if (!internalCall) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } if (isNotificationStateOfCallBusy(internalCall)) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } currentCallState = _callFSM.getCurrentState(internalCall); if (currentCallState !== fsmState.LOCAL_HOLD && currentCallState !== fsmState.BOTH_HOLD) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } if (internalCall.pendingRequestTimer) { _utils.callFunctionIfExist(onFailure, _core.Errors.PENDING_REQUEST); return; } internalCall.lastUpdateRequest = { handler: self.unhold, args: [data, onSuccess, onFailure] }; setNotificationStateOfCallToBusy(internalCall); self.delegateToCallFSM(internalCall, fsmNotificationEvent.unhold_GUI); _webRtcManager.createHoldUpdate(internalCall, false, currentCallState === fsmState.BOTH_HOLD, function (sdp) { logger.debug('[callManager.unhold->createHoldUpdate : sdp ]' + sdp); _callControlService.unhold(internalCall.id, sdp, function () { triggerQueue(internalCall); _webRtcManager.addLocalStream(internalCall); _utils.callFunctionIfExist(onSuccess); }, function (err) { handleRequestFailure(internalCall, onFailure, { handler: self.unhold, args: [data, onSuccess, onFailure], timeout: err.retryAfter }); }, internalCall.customParameters); }, function () { handleWebrtcFailure(internalCall, onFailure); }); }; self.directTransfer = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], currentCallState; if (!internalCall) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } currentCallState = _callFSM.getCurrentState(internalCall); if (currentCallState === fsmState.LOCAL_HOLD || currentCallState === fsmState.BOTH_HOLD || currentCallState === fsmState.COMPLETED) { //TODO: force localhold - if the user is not on hold logger.info('[callManager.directTransfer->sendTransfer : transfer target ]' + data.address); _callControlService.transfer(internalCall.id, (0, _utils2.parseAddress)(data.address), undefined, function () { self.delegateToCallFSM(internalCall, fsmNotificationEvent.transfering); _utils.callFunctionIfExist(onSuccess); logger.info('[callManager.directTransfer->sentTransfer : transfer target ]' + data.address); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }); } else if (currentCallState === fsmState.LOCAL_HOLDING) { if (!internalCall.transferTrigger) { internalCall.transferTrigger = function () { self.directTransfer(data, onSuccess, onFailure); delete this.transferTrigger; }; } } else { logger.error('directTransfer call is not in correct state: ' + currentCallState); _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); } }; self.videoUpdate = function (data, onSuccess, onFailure, retryCallback) { var internalCall = calls[data.callid], isVideoStart; isVideoStart = internalCall.isVideoEnabled || internalCall.isScreenShared; self.delegateToCallFSM(internalCall, fsmNotificationEvent.videoStopStart_GUI); _webRtcManager.createUpdate(internalCall, function (sdp) { _callControlService.reinvite(internalCall.id, sdp, function () { setNotificationStateOfCallToIdle(internalCall); _webRtcManager.addLocalStream(internalCall); _utils.callFunctionIfExist(onSuccess); }, function (err) { handleRequestFailure(internalCall, onFailure, { handler: retryCallback, args: [data, onSuccess, onFailure], timeout: err.retryAfter }); }, internalCall.customParameters); }, function () { logger.error('reinvite->createUpdate '); handleWebrtcFailure(internalCall, onFailure); }, isVideoStart); }; self.videoStopStart = function (data, onSuccess, onFailure) { var internalCall = calls[data.callid], currentCallState, opts = { isVideoEnabled: true, videoResolution: data.videoResolution }; if (!internalCall) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } if (isNotificationStateOfCallBusy(internalCall)) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } currentCallState = _callFSM.getCurrentState(internalCall); if (currentCallState !== fsmState.COMPLETED) { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); return; } if (internalCall.pendingRequestTimer) { _utils.callFunctionIfExist(onFailure, _core.Errors.PENDING_REQUEST); return; } internalCall.lastUpdateRequest = { handler: self.videoStopStart, args: [data, onSuccess, onFailure] }; setNotificationStateOfCallToBusy(internalCall); if (!internalCall.isVideoSourceAllowed && data.isVideoStart) { self.getUserMedia(opts, function getUserMediaSuccessCallback(mediaInfo) { internalCall.isVideoSourceAllowed = true; internalCall.isVideoEnabled = true; _webRtcManager.storeLocalStreamToCall(internalCall, mediaInfo.id); // If the screen is shared, we don't need to do an update since the // video state won't have changed. if (!internalCall.isScreenShared) { self.videoUpdate(data, onSuccess, onFailure, self.videoStopStart); } }, function getUserMediaFailureCallback(e) { // Reset busy flag to be able to receive further notifications setNotificationStateOfCallToIdle(internalCall); _utils.callFunctionIfExist(onFailure, e); }); } else { internalCall.isVideoEnabled = data.isVideoStart; // If the screen is shared, we don't need to do an update since the // video state won't have changed. if (!internalCall.isScreenShared) { self.videoUpdate(data, onSuccess, onFailure, self.videoStopStart); } } }; self.screenStopStart = function (data, onSuccess, onFailure, onScreenStop) { var internalCall = calls[data.callid], currentCallState; if (!internalCall) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } if (isNotificationStateOfCallBusy(internalCall)) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } currentCallState = _callFSM.getCurrentState(internalCall); if (currentCallState !== fsmState.COMPLETED) { _utils.callFunctionIfExist(onFailure, _errors2.default.STATE); return; } if (internalCall.pendingRequestTimer) { _utils.callFunctionIfExist(onFailure, _errors2.default.PENDING_REQUEST); return; } if (data.isScreenStart) { // If we are already in the process of starting screensharing, don't // try again until it's done. if (internalCall.isStartingScreenMedia) { _utils.callFunctionIfExist(onFailure); return; } internalCall.isStartingScreenMedia = true; _webRtcManager.startScreenMedia(function (mediaInfo) { internalCall.isScreenShared = true; internalCall.isStartingScreenMedia = false; _webRtcManager.updateLocalStreamToCall(internalCall, mediaInfo.id); self.videoUpdate(data, onSuccess, onFailure, self.screenStopStart); }, function () { internalCall.isScreenShared = false; internalCall.isStartingScreenMedia = false; _utils.callFunctionIfExist(onFailure); }, data.options, function () { if (_callFSM.getCurrentState(internalCall) === fsmState.COMPLETED) { //Screen sharing video stream has been stopped, act as if someone called screenStopStart //but pass the result to onScreenStop instead. self.screenStopStart(data.callid, onScreenStop, function () { logger.error('Failed to stop screen properly after user stopped the stream via' + ' the browser controls'); }, false); } else if (internalCall.isScreenShared) { internalCall.isScreenShared = false; _webRtcManager.stopScreenMedia(); _utils.callFunctionIfExist(onScreenStop); } }); } else if (internalCall.isScreenShared) { internalCall.isScreenShared = false; _webRtcManager.stopScreenMedia(); self.videoUpdate(data, onSuccess, onFailure, self.screenStopStart); } }; self.mute = function (data) { var call = calls[data.callid]; if (call) { _webRtcManager.muteAudioTrack(call, data.mute); _utils.callFunctionIfExist(call.call.onMute, data.mute); } }; self.sendDTMF = function (data) { var internalCall = calls[data.callid]; if (internalCall) { _webRtcManager.sendDTMF(internalCall, data.tone); } }; self.join = function (data, onSuccess, onFailure, isVideoEnabled, videoResolution) { var internalCall1 = calls[data.callid1], internalCall2 = calls[data.callid2], newInternalCall = {}, currentCallState1, currentCallState2, opts = { isVideoEnabled: isVideoEnabled, videoResolution: videoResolution }; if (internalCall1 && internalCall2) { currentCallState1 = _callFSM.getCurrentState(internalCall1); currentCallState2 = _callFSM.getCurrentState(internalCall2); if (currentCallState1 === fsmState.LOCAL_HOLDING || currentCallState2 === fsmState.LOCAL_HOLDING) { _utils.callFunctionIfExist(onFailure, _core.Errors.PENDING_REQUEST); return; } if ((currentCallState1 === fsmState.LOCAL_HOLD || currentCallState1 === fsmState.REMOTE_HOLD || currentCallState1 === fsmState.BOTH_HOLD) && (currentCallState2 === fsmState.LOCAL_HOLD || currentCallState2 === fsmState.REMOTE_HOLD || currentCallState2 === fsmState.BOTH_HOLD)) { self.getUserMedia(opts, function (mediaInfo) { newInternalCall.isVideoSourceAllowed = mediaInfo.video; _webRtcManager.storeLocalStreamToCall(newInternalCall, mediaInfo.id); self.setUpdateCandidateCallbackToCall(newInternalCall); _webRtcManager.createOffer(newInternalCall, function (sdp) { logger.info('join->doOffer : sdp ' + sdp); newInternalCall.sdp = sdp; _callControlService.join(internalCall1.id, internalCall2.id, sdp, function (callid) { newInternalCall.call = new self.OutgoingCall(callid); newInternalCall.id = callid; // Mark the call as a joined call. newInternalCall.call.setJoin(true); // Since we setJoin(true), we need to pretend that this is a thing apparently. newInternalCall.call.onJoin = function () { logger.debug('Default onJoin called for call. ' + callid); }; newInternalCall.firstInternalCallId = internalCall1.id; newInternalCall.secondInternalCallId = internalCall2.id; // refer will be handled by client. We are going to need callID of partyB and partyC if (_config.clientControlled === 'true') { newInternalCall.isReferer = true; newInternalCall.refer1ID = internalCall1.id; newInternalCall.refer2ID = internalCall2.id; } self.delegateToCallFSM(internalCall1, fsmNotificationEvent.joining_Notify); self.delegateToCallFSM(internalCall2, fsmNotificationEvent.joining_Notify); self.delegateToCallFSM(newInternalCall, fsmNotificationEvent.joiningSuccess_Notify); calls[callid] = newInternalCall; _utils.callFunctionIfExist(onSuccess, newInternalCall.call); }, function (e) { logger.error('callControlService.join Failed!! sdp ' + sdp); _utils.callFunctionIfExist(onFailure, e); }, internalCall1.customParameters); }, function (e) { logger.error('doOffer Failed!!'); _utils.callFunctionIfExist(onFailure, e); }, isVideoEnabled); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }); } else { _utils.callFunctionIfExist(onFailure, _core.Errors.STATE); } } }; self.transfer = function () {}; self.end = function (data, onSuccess) { var internalCall = calls[data.callid]; if (internalCall) { //check with the state machine if the current state would accept an endCall. if (_callFSM.getCurrentState(internalCall) === fsmState.INIT) { logger.error('Cannot end call in INIT callstate :' + _core.Errors.STATE); } else { //send the end call to webrtc abstraction, change call state //this will trigger the send endcall or reject call self.delegateToCallFSM(internalCall, fsmNotificationEvent.end_GUI); clearResources(internalCall, true); _utils.callFunctionIfExist(onSuccess); } } }; self.clickToCall = function (data, onSuccess, onFailure) { _callControlService.clickToCall(data.callingParty, data.calledParty, function () { _utils.callFunctionIfExist(onSuccess); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }); }; self.getIMRN = function (data, onSuccess, onFailure) { _callControlService.getIMRN(data.realm, data.source, data.destination, function () { _utils.callFunctionIfExist(onSuccess); }, function (e) { _utils.callFunctionIfExist(onFailure, e); }); }; self.cerateIncomingCallInFSM = function (call, sdp) { logger.info('incomingCall : sdp = ' + sdp); var internalCall = { 'call': call, 'sdp': sdp, 'id': call.getId(), 'supportTrickle': _sdpParser.isSdpHasTrickle(sdp) && _config.trickleIceSupport !== _constants2.default.TRICKLE.NONE }; logger.info('incomingCall: ' + call.getId()); if (_config.continuity && call.canAnswer()) { cacheCall(internalCall); } self.setUpdateCandidateCallbackToCall(internalCall); calls[call.getId()] = internalCall; if (!sdp) { self.delegateToCallFSM(internalCall, fsmNotificationEvent.callNotify_noSDP); } else { self.delegateToCallFSM(internalCall, fsmNotificationEvent.callNotify); } }; self.onNotificationEvent = function (type, sessionParams, notificationParams) { var callid = sessionParams.sessionData, statusCode = sessionParams.statusCode, reasonText = sessionParams.reasonText, sdp = sessionParams.sdp, referTo = sessionParams.referTo, referredBy = sessionParams.referredBy, retryAfter = sessionParams.retryAfter, internalCall = calls[callid]; logger.debug('Notification received ' + type + ' callid:' + callid); logger.debug('onNotificationEvent : sdp ' + sdp); if (internalCall) { if (isQueueEnabled && isNotificationStateOfCallBusy(internalCall) && type !== fsmNotificationEvent.callEnd_Notify && type !== fsmNotificationEvent.callCancel_Notify) { logger.debug('NOTIFICATION_QUEUE: notification state is busy, adding process to the queue!'); internalCall.call.notificationQueue.enqueue({ type: type, sessionParams: sessionParams }); logger.debug('NOTIFICATION_QUEUE: queue size is now ' + internalCall.call.notificationQueue.size()); return; } if (isQueueEnabled) { setNotificationStateOfCallToBusy(internalCall); } if (sdp) { internalCall.prevRemoteSdp = internalCall.stableRemoteSdp; internalCall.supportTrickle = _sdpParser.isSdpHasTrickle(sdp) && _config.trickleIceSupport !== _constants2.default.TRICKLE.NONE; sdp = _sdpParser.deleteGoogleIceFromSdp(sdp); internalCall.sdp = sdp; } if (referTo && referredBy) { internalCall.referTo = referTo; internalCall.referredBy = referredBy; } if (notificationParams) { // Update the exposed call object so it has the remote participant info. if (internalCall.call.isOutgoing) { if (notificationParams.remoteDisplayNumber) { internalCall.call.calleeNumber = notificationParams.remoteDisplayNumber; } if (notificationParams.remoteName) { internalCall.call.calleeName = notificationParams.remoteName; } } else { if (notificationParams.remoteDisplayNumber) { internalCall.call.callerNumber = notificationParams.remoteDisplayNumber; } if (notificationParams.remoteName) { internalCall.call.callerName = notificationParams.remoteName; } } // Keep the remote participant info on the exposed call up-to-date if there is new info. if (notificationParams.remoteDisplayNumber) { internalCall.call.remoteParticipant.displayNumber = notificationParams.remoteDisplayNumber; if (notificationParams.remoteName) { internalCall.call.remoteParticipant.displayName = notificationParams.remoteName; } } } internalCall.retryAfter = retryAfter; internalCall.statusCode = statusCode; internalCall.reasonText = reasonText; self.delegateToCallFSM(internalCall, type); } else if (startCallInProgress > 0) { //If the call does not exist it could mean the event was received out of order, and that the call is not yet created. logger.info('Pushing event to startCallQueue'); startCallQueue.push({ type: type, sessionParams: sessionParams, expires: Date.now() + 30000 //lets expire in 30 seconds. }); } }; self.onStateChange = function (call, event) { var callStates = CALL_STATES, transferEvent = _callFSM.TransferEvent, i, isJoin, isLocalHold, auditTimerDelay, startAuditTimer, internalCall1, internalCall2; calls[call.id] = call; function triggerCallState(state, doNotTriggerQueue) { logger.debug('triggerCallState: state = ' + state + ' call.statusCode = ' + call.statusCode + ' call.reasonText = ' + call.reasonText); call.call.callState = state; _utils.callFunctionIfExist(call.call.onStateChange, state, call.statusCode, call.reasonText, { localStatusCode: call.localStatusCode, localReasonText: call.localReasonText }); if (!doNotTriggerQueue) { triggerQueue(call); } } function triggerCallStateWithoutQueue(state) { triggerCallState(state, true); } auditTimerDelay = function auditTimerDelay() { setTimeout(function () { if (_core.isConnected()) { _callControlService.audit(call.id, function () { logger.info('Audit kicked off: Success for: ' + call.id); }, function () { logger.error('Audit: Fail for: ' + call.id); // no need to end the call after audit fail }); } }, AUDIT_KICKOFF_TIMEOUT); }; startAuditTimer = function startAuditTimer() { call.call.setAuditTimer(function () { if (_core.isConnected()) { _callControlService.audit(call.id, function () { logger.info('Audit: Success for: ' + call.id); }, function () { logger.error('Audit: Fail for: ' + call.id); // no need to end the call after audit fail triggerQueue(call); }); } }); }; logger.info('Transfer Event: ' + event + '. callId: ' + call.id); switch (event) { case transferEvent.startCallReplace_fsm: triggerCallState(callStates.REPLACING); break; case transferEvent.joiningSuccess_fsm: // Emit a state change event for the new joined call. call.localStatusCode = LOCAL_STATUS_CODES.JOIN_COMPLETED; call.localReasonText = LOCAL_REASON_TEXTS.JOIN_COMPLETED; triggerCallState(callStates.IN_CALL); break; case transferEvent.callStart_fsm: case transferEvent.localHolding_fsm: case transferEvent.localUnHolding_fsm: case transferEvent.localVideoStopStart_fsm: case transferEvent.slowStartOfferProcessed_fsm: case transferEvent.rejectWithoutClearCallObject_GUI: break; case transferEvent.deviceChange_fsm: case transferEvent.ignoredNotification_fsm: case transferEvent.answeringRingingSlow_fsm: case transferEvent.localHold_fsm: case transferEvent.localUnHold_fsm: case transferEvent.answerRingingSlow_fsm: case transferEvent.transfering_fsm: triggerQueue(call); break; case transferEvent.ringing_fsm: triggerCallState(callStates.RINGING); break; case transferEvent.callReceived_fsm: //TODO maybe set that this is a slow start triggerCallState(callStates.INCOMING); break; case transferEvent.answer_fsm: auditTimerDelay(); startAuditTimer(); triggerCallState(callStates.IN_CALL); break; case transferEvent.ignore_GUI: call.localStatusCode = LOCAL_STATUS_CODES.IGNORED_BY_LOCAL; call.localReasonText = LOCAL_REASON_TEXTS.IGNORED_BY_LOCAL; clearCallObject(call); triggerCallState(callStates.ENDED); break; case transferEvent.respondedFromAnotherDevice_fsm: call.localStatusCode = LOCAL_STATUS_CODES.RESPONDED_FROM_ANOTHER_DEVICE; call.localReasonText = LOCAL_REASON_TEXTS.RESPONDED_FROM_ANOTHER_DEVICE; clearCallObject(call); triggerCallState(callStates.ENDED); break; case transferEvent.reject_GUI: case transferEvent.forward_fsm: clearResources(call); break; case transferEvent.sessionComplete_fsm: _callControlService.endCall(call.id, function () { logger.info('callControlService.endCall successful. callId: ' + call.id); }, function () { logger.error('callControlService.endCall FAILED!!.callId: ' + call.id); }); clearResources(call); // Emit a state change event with "transition" explanation. call.localStatusCode = LOCAL_STATUS_CODES.JOIN_COMPLETED; call.localReasonText = LOCAL_REASON_TEXTS.JOIN_COMPLETED; triggerCallState(callStates.ENDED); break; case transferEvent.sessionFail_fsm: case transferEvent.transferFail_fsm: call.forceNewPeer = true; triggerCallState(callStates.TRANSFER_FAILURE); break; case transferEvent.replaceCallCompleted_fsm: case transferEvent.callCompleted_fsm: // Workaround for webrtc dtls and firefox pranswer support bug. Can be removed when fixed by browsers. // dtls is enabled listened early media as answer. Now has to create a new peer for actual answer sdp, only if the sdp is different. if (_webRtcManager.isDtlsEnabled() && call.peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.STABLE) { if (_sdpParser.compareSDPForEarlyMedia(call.stableRemoteSdp, call.sdp)) { logger.info('Early Media with same sdp on DTLS'); auditTimerDelay(); startAuditTimer(); triggerCallState(callStates.IN_CALL); } else { logger.info('Handle answer sdp after session progress when dtls is enabled. Create new peer workaround.'); self.delegateToCallFSM(call, fsmNotificationEvent.performCreateNewPeerWorkaround_JSL); } break; } auditTimerDelay(); _webRtcManager.processAnswer(call, function () { startAuditTimer(); triggerCallState(callStates.IN_CALL); }, function (err) { if (err === _constants2.default.WEBRTC.ERROR.ICE_ICELITE) { logger.info('ice-lite - ice change. Create new peer workaround.'); self.delegateToCallFSM(call, fsmNotificationEvent.performCreateNewPeerWorkaround_JSL); } else { clearResources(call); triggerCallState(callStates.ENDED); } }); //if client is handling the refers, we need to trigger the refers for partyB and partyC from referer if (call.isReferer) { for (i in calls) { if (calls.hasOwnProperty(i)) { if (calls[i] && (calls[i].id === call.refer1ID || calls[i].id === call.refer2ID)) { calls[i].referCall(call.referTo, call.referredBy); } } } } break; case transferEvent.startCallReplaceRejected_fsm: case transferEvent.noAnswer_fsm: clearResources(call); triggerCallState(callStates.ENDED); break; case transferEvent.remoteEnd_fsm: if (call.firstInternalCallId && call.secondInternalCallId) { internalCall1 = calls[call.firstInternalCallId]; self.delegateToCallFSM(internalCall1, fsmNotificationEvent.revertState_JSL); internalCall2 = calls[call.secondInternalCallId]; self.delegateToCallFSM(internalCall2, fsmNotificationEvent.revertState_JSL); } // if call's previous call state is RINGING check replacingCallId value if (call.previousState === fsmState.RINGING && call.replacingCallId) { var replacingCall = calls[call.replacingCallId]; // if there us replacingCallId and replacing call 's state is active then unmute it if (replacingCall) { logger.info('[onStateChange] replacing call\'s state: ' + replacingCall.currentState); if (replacingCall.currentState === fsmState.COMPLETED) { logger.info('[onStateChange] replacing call has unmuted: ' + replacingCall.currentState); replacingCall.call.unmute(); } } else { logger.info('[onStateChange] replacing call has not found, replacingCallId: ' + call.replacingCallId); } } if (!call.localStatusCode && !call.localReasonText) { call.localStatusCode = LOCAL_STATUS_CODES.STATUS_CODE_NOT_PROVIDED; call.localReasonText = LOCAL_REASON_TEXTS.STATUS_CODE_NOT_PROVIDED; } clearResources(call); triggerCallState(callStates.ENDED); break; case transferEvent.localEnding_fsm: call.localStatusCode = LOCAL_STATUS_CODES.ENDED_BY_LOCAL; call.localReasonText = LOCAL_REASON_TEXTS.ENDED_BY_LOCAL; _callControlService.endCall(call.id, function () { logger.info('CallControlService endCall successful. callId: ' + call.id); }, function () { logger.error('Cannot callControlService endCall. callId: ' + call.id); }, call.localReasonText); clearCallObject(call); triggerCallState(callStates.ENDED); break; case transferEvent.localEndingWithoutClearCallObject_fsm: call.localStatusCode = LOCAL_STATUS_CODES.ENDED_BY_LOCAL; call.localReasonText = LOCAL_REASON_TEXTS.ENDED_BY_LOCAL; _callControlService.endCall(call.id, function () { logger.info('CallControlService endCall successful. callId: ' + call.id); }, function () { logger.error('Cannot callControlService endCall. callId: ' + call.id); }, call.localReasonText); break; case transferEvent.localEnd_fsm: call.localStatusCode = LOCAL_STATUS_CODES.ENDED_BY_LOCAL; call.localReasonText = LOCAL_REASON_TEXTS.ENDED_BY_LOCAL; clearCallObject(call); triggerCallState(callStates.ENDED); break; case transferEvent.localReject_fsm: call.localStatusCode = LOCAL_STATUS_CODES.REJECTED_BY_LOCAL; call.localReasonText = LOCAL_REASON_TEXTS.REJECTED_BY_LOCAL; clearCallObject(call); triggerCallState(callStates.ENDED); break; case transferEvent.callCompletedAnswering_fsm: logger.info('callManager: Call Completed Answering Event. callId: ' + call.id); var isRemoteHold; if (call.sdp) { _sdpParser.init(call.sdp); isRemoteHold = _sdpParser.isRemoteHold(); } _webRtcManager.processAnswer(call, function () { if (isRemoteHold) { call.currentState = fsmState.REMOTE_HOLD; triggerCallState(callStates.ON_REMOTE_HOLD); } else { triggerCallState(callStates.IN_CALL); } auditTimerDelay(); startAuditTimer(); }, function () { clearResources(call); triggerCallState(callStates.ENDED); }, true); break; case transferEvent.remoteHold_fsm: switch (_callFSM.getCurrentState(call)) { case fsmState.REMOTE_HOLD: triggerCallState(callStates.ON_REMOTE_HOLD); break; case fsmState.BOTH_HOLD: triggerCallState(callStates.ON_HOLD); break; default: triggerQueue(call); break; } break; case transferEvent.remoteUnHold_fsm: // If the remote user changed, then this unhold was due to a transfer. if (call.remoteParticipantChanged) { call.remoteEndPointChanged = undefined; call.localStatusCode = LOCAL_STATUS_CODES.TRANSFERRED; call.localReasonText = LOCAL_REASON_TEXTS.TRANSFERRED; } switch (_callFSM.getCurrentState(call)) { case fsmState.LOCAL_HOLD: triggerCallState(callStates.ON_HOLD); break; case fsmState.COMPLETED: triggerCallState(callStates.IN_CALL); break; default: triggerQueue(call); break; } break; case transferEvent.remoteHolding_fsm: isLocalHold = _callFSM.getCurrentState(call) === fsmState.LOCAL_HOLD || _callFSM.getCurrentState(call) === fsmState.BOTH_HOLD; _webRtcManager.processHold(call, true, isLocalHold, function (sdp) { logger.info('[callManager.onStateChange.transferEvent.remoteHold_fsm->processHold : sdp ]' + sdp); _callControlService.respondToRemoteHold(call.id, sdp, function () { logger.info('Remote Hold Transfer Event Successful. callId: ' + call.id); self.delegateToCallFSM(call, fsmNotificationEvent.remoteHoldProcessed_JSL); }, function (errorStr) { logger.error('Remote Hold Transfer Event FAILED!! - ' + errorStr); handleRequestFailure(call); }, call.customParameters); }, function (errorStr) { logger.error('Remote Hold FAILED!! - ' + errorStr); handleWebrtcFailure(call); }); break; case transferEvent.remoteOfferDuringLocalHold_fsm: _webRtcManager.processRemoteOfferOnLocalHold(call, function (sdp) { logger.info('onStateChange.transferEvent.remoteOfferDuringLocalHold_fsm : sdp ' + sdp); _callControlService.respondCallUpdate(call.id, sdp, function () { logger.info('Remote Offer During Local Hold Transfer Event successful. callId: ' + call.id); triggerQueue(call); }, function (errorStr) { handleRequestFailure(call); logger.error('Remote Offer During Local Hold Transfer Event FAILED!! - ' + errorStr); }, call.customParameters); }, function (errorStr) { logger.error('Remote Offer During Local Hold FAILED!! - ' + errorStr); handleWebrtcFailure(call); }); break; case transferEvent.slowStartOfferDuringOnCall_fsm: case transferEvent.slowStartOfferDuringRemoteHold_fsm: _webRtcManager.createReOffer(call, function (sdp) { logger.info('onStateChange.transferEvent.createReOffer: sdp ' + sdp); _callControlService.respondCallUpdate(call.id, sdp, function () { logger.info('Slow Start Offer respondCallUpdate successful. callId: ' + call.id); self.delegateToCallFSM(call, fsmNotificationEvent.slowStartOfferProcessed_JSL); triggerQueue(call); }, function (errorStr) { logger.error('Slow Start Offer respondCallUpdate FAILED!! - ' + errorStr); handleRequestFailure(call); }, call.customParameters); }, function (errorStr) { logger.error('Slow Start Offer createReOffer FAILED!! - ' + errorStr); handleWebrtcFailure(call); }, false); break; case transferEvent.performReconnectWorkaround_fsm: _webRtcManager.createReOffer(call, function createReOfferSuccessCallback(sdp) { logger.info('onStateChange.transferEvent.createReOffer : sdp ' + sdp); _callControlService.reinvite(call.id, sdp, function reInviteSuccessCallback() { setNotificationStateOfCallToIdle(call); _webRtcManager.addLocalStream(call); logger.info('callControlService.reinvite successful. callId: ' + call.id); }, function (e) { //statusCode 42 = RESOURCE_IDENTIFIER_DOES_NOT_EXIST if (e.statusCode === 42) { // Call object removed and onStateChange event triggered with ENDED state. // Because call session already ended on call server. // Operation can not be on this call. // Call object must be removed and should be given information to the web application side. logger.info('Call is ended.Because call session is not active. callId: ' + call.id); clearResources(call); triggerCallState(callStates.ENDED); } else { self.delegateToCallFSM(call, fsmNotificationEvent.requestFailure_JSL); } }, call.customParameters); }, function () { handleWebrtcFailure(call); }, true); break; case transferEvent.performCreateNewPeerWorkaround_fsm: logger.info('performCreateNewPeerWorkaround_fsm'); _webRtcManager.createReOffer(call, function createReOfferSuccessCallback(sdp) { logger.info('createReOfferSuccessCallback: sdp ' + sdp); _callControlService.reinvite(call.id, sdp, function reInviteSuccessCallback() { logger.info('reInviteSuccessCallback.'); _webRtcManager.addLocalStream(call); startAuditTimer(); triggerQueue(call); }, function reInviteFailureCallback() { logger.info('reInviteFailureCallback.'); self.end({ callid: call.id }, function () { logger.info('end success.'); clearResources(call); triggerCallState(callStates.ENDED); }); }, call.customParameters); }, function createReOfferFailureCallback() { self.end({ callid: call.id }, function () { logger.info('end success.'); clearResources(call); triggerCallState(callStates.ENDED); }); }, false); break; case transferEvent.remoteUnHolding_fsm: isLocalHold = call.previousState === fsmState.LOCAL_HOLD || call.previousState === fsmState.BOTH_HOLD; _webRtcManager.processHold(call, false, isLocalHold, function (sdp) { logger.info('onStateChange.transferEvent.remoteUnHold_fsm->processHold : sdp ' + sdp); _callControlService.respondToRemoteUnhold(call.id, sdp, function () { logger.info('Remote UnHold Transfer Event successful. callId: ' + call.id); self.delegateToCallFSM(call, fsmNotificationEvent.remoteUnHoldProcessed_JSL); }, function (errorStr) { logger.error('Remote UnHold Transfer Event FAILED!! - ' + errorStr); handleRequestFailure(call); }, call.customParameters); }, function (errorStr) { logger.error('Remote UnHold FAILED!! - ' + errorStr); handleWebrtcFailure(call); }); break; case transferEvent.renegotiationCompleted_fsm: triggerCallState(callStates.RENEGOTIATION); break; case transferEvent.remoteOffer_fsm: case transferEvent.remoteCallUpdate_fsm: _webRtcManager.processUpdate(call, function (sdp) { logger.info('onStateChange.transferEvent.remoteCallUpdate_fsm->processUpdate : sdp ' + sdp); _callControlService.respondCallUpdate(call.id, sdp, function () { logger.info('Remote Call Update Transfer Event Successful. callId: ' + call.id); self.delegateToCallFSM(call, fsmNotificationEvent.remoteOfferProcessed_JSL); }, function (errorStr) { logger.error('Remote Call Update Transfer Event FAILED!! - ' + errorStr); handleRequestFailure(call); }, call.customParameters); }, function (errorStr) { logger.error('Remote Call Update FAILED!! - ' + errorStr); handleWebrtcFailure(call); }, call.currentState === fsmState.LOCAL_HOLD ? true : false); break; case transferEvent.respondCallHoldUpdate_fsm: isJoin = call.call.getJoin(); _webRtcManager.processHoldRespond(call, function () { logger.info('Respond Call Hold Update Event Successful. callId: ' + call.id); switch (_callFSM.getCurrentState(call)) { case fsmState.REMOTE_HOLD: triggerCallState(callStates.ON_REMOTE_HOLD); break; case fsmState.LOCAL_HOLD: case fsmState.BOTH_HOLD: triggerCallState(callStates.ON_HOLD); if (typeof call.transferTrigger === 'function') { call.transferTrigger(); } break; case fsmState.COMPLETED: triggerCallState(callStates.IN_CALL); break; } }, function (e) { logger.error('Respond Call Hold Update Event FAILED: ' + e); triggerQueue(call); }, isJoin); //enable clicking call.call.setButtonDisabler(false); call.call.clearBtnTimeout(); if (isJoin === true) { call.call.onJoin(); } break; case transferEvent.respondCallUpdate_fsm: isJoin = call.call.getJoin(); //enable clicking call.call.setButtonDisabler(false); call.call.clearBtnTimeout(); //If this is a join call we need to send join request //onJoin() function is created at callController.js if (isJoin === true) { _webRtcManager.processRespond(call, function () { logger.info('Respond Call Update Event Successful. callId: ' + call.id); triggerCallState(callStates.RENEGOTIATION); }, function (e) { logger.error('Respond Call Update Event FAILED: ' + e); triggerQueue(call); }, isJoin); call.call.onJoin(); } else { _webRtcManager.processRespond(call, function () { logger.info('Respond Call Update Event Successful. callId: ' + call.id); switch (_callFSM.getCurrentState(call)) { case fsmState.REMOTE_HOLD: triggerCallState(callStates.ON_REMOTE_HOLD); break; case fsmState.BOTH_HOLD: triggerCallState(callStates.ON_HOLD); break; case fsmState.LOCAL_HOLD: triggerCallState(callStates.ON_HOLD); break; case fsmState.COMPLETED: triggerCallState(callStates.IN_CALL); break; } }, function (e) { logger.error('Respond Call Update Event FAILED: ' + e); triggerQueue(call); }, isJoin); } break; case transferEvent.remotePranswer_fsm: // Workaround for webrtc dtls and firefox pranswer support bug. Can be removed when fixed by browsers. // https://code.google.com/p/webrtc/issues/detail?id=3349 // https://bugzilla.mozilla.org/show_bug.cgi?id=1004510 if (_webRtcManager.isDtlsEnabled()) { if (call.peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.STABLE) { logger.info('Only first sessionProgress notification is processed, so ignoring this one.'); triggerQueue(call); } else { _webRtcManager.processAnswer(call, function () { triggerCallState(callStates.EARLY_MEDIA); }, function (e) { logger.error('Process answer for session progress FAILED: ' + e); triggerQueue(call); }); } } else { _webRtcManager.processPreAnswer(call, function () { triggerCallState(callStates.EARLY_MEDIA); }, function (e) { logger.error('Process pranswer FAILED: ' + e); triggerQueue(call); }); } break; case transferEvent.joining_fsm: //if client is handling the refers from referer we need to trigger the refers for partyB and partyC if (_config.clientControlled === 'true') { call.referCall = function (referTo, referredBy) { _callControlService.refer(call.id, referTo, referredBy, function () { logger.info('Joining Event Successful. callId: ' + call.id); self.delegateToCallFSM(call, fsmNotificationEvent.refer_JSL); }, function (errorStr) { logger.error('Joining Event FAILED!!' + errorStr); }); }; } triggerQueue(call); break; case transferEvent.transferSuccess_fsm: call.localStatusCode = LOCAL_STATUS_CODES.SESSION_COMPLETED; call.localReasonText = LOCAL_REASON_TEXTS.SESSION_COMPLETED; _callControlService.endCall(call.id, function () { logger.info('callControlService.endCall successful. callId: ' + call.id); }, function () { logger.error('callControlService.endCall FAILED!! callId: ' + call.id); }); clearResources(call); triggerCallState(callStates.TRANSFERRED); triggerCallState(callStates.ENDED); logger.info('endCall successful. callId: ' + call.id); break; case transferEvent.stateReverted_fsm: //enable clicking call.call.setButtonDisabler(false); call.call.clearBtnTimeout(); switch (_callFSM.getCurrentState(call)) { case fsmState.REMOTE_HOLD: triggerCallStateWithoutQueue(callStates.ON_REMOTE_HOLD); break; case fsmState.BOTH_HOLD: triggerCallStateWithoutQueue(callStates.ON_HOLD); break; case fsmState.LOCAL_HOLD: triggerCallStateWithoutQueue(callStates.ON_HOLD); break; case fsmState.COMPLETED: triggerCallStateWithoutQueue(callStates.IN_CALL); break; default: logger.error('CANNOT REVERT THE STATE: ' + _callFSM.getCurrentState(call) + '. callId: ' + call.id); break; } break; case transferEvent.glareCondition_fsm: handleFailure(call, null, null, { handler: call.lastUpdateRequest.handler, args: call.lastUpdateRequest.args, timeout: call.retryAfter }); break; default: logger.error('Undefined transition event: ' + event + ' for ' + call.id); triggerQueue(call); break; } }; self.refreshVideoRenderer = function (data) { var internalCall = calls[data.callid]; if (internalCall) { _webRtcManager.refreshVideoRenderer(internalCall); } }; self.hasVideoDevice = function () { return _webRtcManager.isVideoSourceAvailable(); }; self.hasAudioDevice = function () { return _webRtcManager.isAudioSourceAvailable(); }; self.hasScreenSharing = function () { return _webRtcManager.isScreenSourceAvailable(); }; self.getLocalVideoResolutions = function () { return _webRtcManager.getLocalVideoResolutions(); }; self.getRemoteVideoResolutions = function () { return _webRtcManager.getRemoteVideoResolutions(); }; self.isCallMuted = function (data) { return _webRtcManager.isAudioMuted(calls[data.callid]); }; /* DEPRECIATED */ self.isVideoNegotationAvailable = function (data) { var call = calls[data.callid]; if (call.sdp) { return _sdpParser.isSdpHasVideo(call.sdp); } else { return false; } }; self.isVideoNegotiationAvailable = function (data) { var call = calls[data.callid]; if (call.sdp) { return _sdpParser.isSdpHasVideo(call.sdp); } else { return false; } }; self.getRemoteVideoState = function (callid) { var call = calls[callid]; if (call.sdp) { return call.remoteVideoState; } else { return false; } }; self.isSendInitialVideoEnabled = function (data) { var call = calls[data.callid]; if (call.sdp) { return _sdpParser.isSdpVideoSendEnabled(call.sdp); } else { return false; } }; self.getHoldStateOfCall = function (data) { var internalCall = calls[data.callid]; if (internalCall) { return CALL_HOLD_STATES[_callFSM.getCurrentState(internalCall)]; } return undefined; }; self.getCustomParametersOfCall = function (data) { var internalCall = calls[data.callid]; if (internalCall && internalCall.customParameters) { return internalCall.customParameters; } return []; }; self.setCustomParametersOfCall = function (data) { var internalCall = calls[data.callid]; if (internalCall) { internalCall.customParameters = data.customParams; return true; } return false; }; self.canOriginatorSendLocalVideo = function (data) { var call = calls[data.callid]; if (call) { return _webRtcManager.canOriginatorSendLocalVideo(call); } return false; }; self.canOriginatorReceiveRemoteVideo = function (data) { var call = calls[data.callid]; if (call) { return _webRtcManager.canOriginatorReceiveRemoteVideo(call); } return false; }; self.getStreamById = function (data) { return _webRtcManager.getStreamById(data.streamId); }; self.removeStreamById = function (data) { _webRtcManager.removeStreamById(data.streamId); }; self.setSelectedMicrophoneId = function (data) { _webRtcManager.setSelectedMicrophoneId(data.microphoneId); }; self.setSelectedSpeakerId = function (data, onSuccess, onFailure) { _webRtcManager.setSelectedSpeakerId(data.speakerId, onSuccess, onFailure); }; self.setSelectedCameraId = function (data) { _webRtcManager.setSelectedCameraId(data.cameraId); }; self.getCameraList = function (params) { _webRtcManager.getCameraList(function (cameraList) { _utils.callFunctionIfExist(params.onSuccess, cameraList); }); }; self.getMicrophoneList = function (params) { _webRtcManager.getMicrophoneList(function (microphoneList) { _utils.callFunctionIfExist(params.onSuccess, microphoneList); }); }; self.getSpeakerList = function (params) { _webRtcManager.getSpeakerList(function (speakerList) { _utils.callFunctionIfExist(params.onSuccess, speakerList); }); }; self.changeDevices = function (data, onSuccess, onFailure) { var internalCall, internalCallId; function reInviteFailureCallback() { logger.info('reInviteFailureCallback.'); setNotificationStateOfCallToIdle(internalCall); self.end({ callid: internalCall.id }, function () { logger.info('end success.'); }); } function reInviteSuccessCallback() { logger.info('reInviteSuccessCallback.'); self.delegateToCallFSM(internalCall, fsmNotificationEvent.deviceChange_GUI); setNotificationStateOfCallToIdle(internalCall); _webRtcManager.addLocalStream(internalCall); _utils.callFunctionIfExist(onSuccess); } function createReOfferSuccessCallback(sdp) { internalCall.sdp = sdp; logger.info('createReOfferSuccessCallback: sdp ' + sdp); setNotificationStateOfCallToBusy(internalCall); _callControlService.reinvite(internalCall.id, sdp, reInviteSuccessCallback, reInviteFailureCallback, internalCall.customParameters); } function createReOfferFailureCallback(e) { logger.error('[callManager.offer] Error : ' + e); } function getUserMediaFailureCallback(e) { logger.error('[getUserMedia] Error : ' + e); _utils.callFunctionIfExist(onFailure, e); } function getUserMediaSuccessCallback(mediaInfo) { internalCall.isVideoSourceAllowed = mediaInfo.video; _webRtcManager.storeLocalStreamToCall(internalCall, mediaInfo.id); _webRtcManager.createReOffer(internalCall, createReOfferSuccessCallback, createReOfferFailureCallback, true); } function replaceStream(call) { var opts = { isVideoEnabled: self.isVideoNegotiationAvailable({ callid: call.id }) }; // below line is added as a workaround for mobile clients. // there must be one active camera stream on mobile, // that's why the old one must be deleted before getting access to the new one. _webRtcManager.deleteLocalStream(call); self.getUserMedia(opts, getUserMediaSuccessCallback, getUserMediaFailureCallback); } if (data.callid) { internalCall = calls[data.callid]; replaceStream(internalCall); } else { for (internalCallId in calls) { if (internalCallId) { internalCall = calls[internalCallId]; replaceStream(internalCall); } } } }; /** * Forward the function call to the webRtcManager. */ self.changeSpeaker = function (params, onSuccess, onFailure) { _webRtcManager.changeSpeaker(params.speakerId, onSuccess, onFailure); }; self.handleIncomingIceCandidate = function (data) { logger.debug('handleIncomingIceCandidate '); var sessionParams = data.sessionParams; if (!data.sessionParams) { logger.warn('incomingIceCandidate received without any parameters'); return; } var internalCall = calls[sessionParams.sessionData], candidates = sessionParams.iceCandidates; if (!internalCall || !candidates) { logger.warn('incomingIceCandidate received without a call id or any candidates '); return; } _webRtcManager.addRemoteCandidates(internalCall, candidates); }; _notificationCallBacks.call = function handleIncomingCall(data) { // disabling the notifications for verizon demo if (!_config.anonymous) { var sdp, actions, params, calls, call = null, callid = null, options = {}, callParams = data.callNotificationParams, dispositionParams = data.callDispositionParams, sessionParams = data.sessionParams, callerName, callerNumber, calleeNumber, primaryContact; //Since session also include disposition use it as default params = sessionParams ? sessionParams : dispositionParams ? dispositionParams : null; logger.info('params: ' + params); // send ringing notify to Spidr once a call is received if (_config.ringingFeedback) { _callControlService.ringing(params.sessionData); } if (params) { actions = params.actions; logger.info('actions: ' + actions); if (params.sessionData) { callid = params.sessionData; calls = self.getCalls(); if (calls[callid] !== undefined) { logger.info('call already exists: ' + callid); return; } logger.info('sessionData: ' + callid); } if (actions) { options.reject = actions.indexOf('reject', 0) > -1; options.forward = actions.indexOf('forward', 0) > -1; options.answer = actions.indexOf('answer', 0) > -1; } if (params.sdp) { sdp = params.sdp; } } call = new self.IncomingCall(callid, options); //Let's not overwrite values that are undefined callerNumber = (0, _utils2.getProperty)(callParams, 'callerDisplayNumber'); if (callerNumber) { call.callerNumber = callerNumber; } callerName = (0, _utils2.getProperty)(callParams, 'callerName'); if (callerName) { call.callerName = callerName; } calleeNumber = (0, _utils2.getProperty)(callParams, 'calleeDisplayNumber'); if (calleeNumber) { call.calleeNumber = calleeNumber; } primaryContact = (0, _utils2.getProperty)(callParams, 'primaryContact'); if (primaryContact) { call.primaryContact = primaryContact.split(';')[0]; } // Track the remote participant information when a call is received. call.remoteParticipant = { displayNumber: (0, _utils2.getProperty)(callParams, 'callerDisplayNumber'), displayName: (0, _utils2.getProperty)(callParams, 'callerName') }; // Note: Some of our clients (KCS) need access to all the custom parameters received on an // incoming call. Here we add a catch-all rawParameters that includes everything passed in. call.rawParameters = params; self.cerateIncomingCallInFSM(call, sdp); //notify the callback _utils.callFunctionIfExist(_core.call.onReceived, call); } }; function handleCallControlNotification(type, data) { var sessionParams = data.sessionParams; var callNotificationParams = data.callNotificationParams; logger.info('CallControl notification received ' + type + ' sessionData:' + sessionParams.sessionData); if (sessionParams.referTo) { logger.info('CallControl notification received: ' + 'referTo:' + sessionParams.referTo + ' referredBy: ' + sessionParams.referredBy); } if (sessionParams) { self.onNotificationEvent(type, sessionParams, callNotificationParams); } } self.handleReplacesFailure = function (newlyCreatedCall) { self.delegateToCallFSM(newlyCreatedCall, fsmNotificationEvent.callEnd_Notify); self.sendRejectCallReplace(newlyCreatedCall); }; self.handleReplacesWebrtcFailure = function (newlyCreatedCall) { handleWebrtcFailure(newlyCreatedCall); self.sendRejectCallReplace(newlyCreatedCall); }; self.sendRejectCallReplace = function (newlyCreatedCall) { _callControlService.rejectCallReplace(newlyCreatedCall, function () { logger.info('[NotificationCallBacks.startCallReplace] rejectCallReplace has sent'); }, function () { logger.info('[NotificationCallBacks.startCallReplace] rejectCallReplace could not sent'); }); }; self.createNewCall = function (notificationWithSdp, newlyCreatedCallId) { if (notificationWithSdp) { // notification with sdp is received, need to process the sdp and create an answer return new self.IncomingCall(newlyCreatedCallId); } else { // slow start notification is received, need to create a new offer return new self.OutgoingCall(newlyCreatedCallId); } }; self.handleStartCallReplaceNotification = function (data) { var newlyCreatedSessionParams = data.sessionParams, // newly created session params transferredCallId = data.replaces, // old session params that is being replaced by sessionParams newlyCreatedCall = {}, remoteParty = data.remoteParty, newlyCreatedCallId = newlyCreatedSessionParams.sessionData, // getting transfer target address notificationWithSdp = !!newlyCreatedSessionParams.sdp; newlyCreatedCall.call = self.createNewCall(notificationWithSdp, newlyCreatedCallId); if (transferredCallId !== null && remoteParty !== null) { logger.info('[NotificationCallBacks.handleStartCallReplaceNotification] notification received sessionData:' + newlyCreatedCallId); var calls = self.getCalls(); // getting callid that is newly created if (calls[newlyCreatedCallId] === undefined && calls[transferredCallId] !== undefined) { // can be getting call object that is about to transferring var transferredCall = calls[transferredCallId], transferredCallState = _callFSM.getCurrentState(transferredCall), isSendInitialVideo = self.isSendInitialVideoEnabled({ 'callid': transferredCallId }); newlyCreatedCall.id = newlyCreatedCallId; newlyCreatedCall.sdp = newlyCreatedSessionParams.sdp; newlyCreatedCall.currentState = fsmState.REPLACING; _utils.callFunctionIfExist(_core.call.onCallReplaceReceived, newlyCreatedCall, transferredCall); self.delegateToCallFSM(newlyCreatedCall, fsmNotificationEvent.startCallReplace_Notify); if (transferredCallState === fsmState.COMPLETED || transferredCallState === fsmState.REMOTE_HOLD) { var opts = { isVideoEnabled: isSendInitialVideo }, successCallback = function successCallback() { // if previous call is an active call, mute it if (transferredCallState === fsmState.COMPLETED) { transferredCall.call.mute(); } _callControlService.acceptCallReplace(newlyCreatedCall, function () { logger.info('[NotificationCallBacks.startCallReplace] onSuccess'); newlyCreatedCall.callerNumber = remoteParty; newlyCreatedCall.replacingCallId = transferredCallId; // this will be used for unmuting previous call, when there occurs error while replacing call calls[newlyCreatedCallId] = newlyCreatedCall; setTimeout(function () { _webRtcManager.addLocalStream(newlyCreatedCall); }, 10); }, function () { logger.info('[NotificationCallBacks.startCallReplace] onFailure'); // unmute previousCall if previous call is active call, unmute it if (transferredCallState === fsmState.COMPLETED) { transferredCall.call.unmute(); } self.handleReplacesFailure(newlyCreatedCall); }, data.customParameters); }, failureCallback = function failureCallback() { logger.error('[NotificationCallBacks.handleStartCallReplaceNotification] webrtc error'); self.handleReplacesWebrtcFailure(newlyCreatedCall); }; self.getUserMedia(opts, function getUserMediaSuccessCallback(mediaInfo) { newlyCreatedCall.isVideoSourceAllowed = mediaInfo.video; _webRtcManager.storeLocalStreamToCall(newlyCreatedCall, mediaInfo.id); if (notificationWithSdp) { _webRtcManager.createAnswer(newlyCreatedCall, successCallback, failureCallback, isSendInitialVideo); } else { _webRtcManager.createOffer(newlyCreatedCall, successCallback, failureCallback, isSendInitialVideo); } }, function getUserMediaFailureCallback() { logger.error('[NotificationCallBacks.handleStartCallReplaceNotification] getUserMediaFailureCallback Error'); self.handleReplacesFailure(newlyCreatedCall); }); } else { logger.info('[NotificationCallBacks.handleStartCallReplaceNotification] transferredCall is not in appropriate state: ' + transferredCallState); self.handleReplacesFailure(newlyCreatedCall); } } else { logger.info('[NotificationCallBacks.handleStartCallReplaceNotification] newlyCreatedCallId already exists: ' + newlyCreatedCallId + ' or transferredCallId does not exists: ' + transferredCallId); self.handleReplacesFailure(newlyCreatedCall); } } else { logger.info('[NotificationCallBacks.handleStartCallReplaceNotification] replaces or remoteParty values is null'); self.handleReplacesFailure(newlyCreatedCall); } }; _notificationCallBacks.ringing = function (data) { handleCallControlNotification(fsmNotificationEvent.ringing_Notify, data); }; _notificationCallBacks.sessionProgress = function (data) { //We are discarding the sessionProgress if the SDP is empty if (data.sessionParams.sdp !== '') { handleCallControlNotification(fsmNotificationEvent.sessionProgress, data); } else { logger.info('Warning: SDP of sessionProgress is empty.'); } }; _notificationCallBacks.startCallUpdate = function handleStartCallUpdateNotification(data) { var sdp = data.sessionParams.sdp, notificationEvent = fsmNotificationEvent.startCallUpdate_slowStart_Notify, callid = data.sessionParams.sessionData, callParams = data.callNotificationParams, internalCall = calls[callid], remoteCallParams = { RemoteDisplayName: '', RemoteDisplayNumber: '' }; if (sdp) { _sdpParser.init(sdp); if (_sdpParser.isRemoteHold()) { notificationEvent = fsmNotificationEvent.startCallUpdate_remoteHold_Notify; } else { notificationEvent = fsmNotificationEvent.startCallUpdate_remoteOffer_Notify; } } if (internalCall) { if (!internalCall.remoteDisplayNumber) { internalCall.remoteDisplayNumber = (0, _utils2.getProperty)(callParams, 'callerDisplayNumber'); } if (internalCall.remoteDisplayNumber !== (0, _utils2.getProperty)(callParams, 'callerDisplayNumber')) { remoteCallParams.RemoteDisplayName = (0, _utils2.getProperty)(callParams, 'callerName'); remoteCallParams.RemoteDisplayNumber = (0, _utils2.getProperty)(callParams, 'callerDisplayNumber'); logger.info('Remote User has changed from :' + internalCall.call.callerName + '<' + internalCall.call.callerNumber + '> to ' + remoteCallParams.RemoteDisplayName + '<' + remoteCallParams.RemoteDisplayNumber + '>'); internalCall.remoteDisplayNumber = (0, _utils2.getProperty)(callParams, 'callerDisplayNumber'); //This is for consultative transfer with slow start internalCall.remoteEndPointChanged = true; // Update the exposed call as well. internalCall.call.calleeNumber = (0, _utils2.getProperty)(callParams, 'calleeDisplayNumber'); internalCall.call.callerName = (0, _utils2.getProperty)(callParams, 'callerName'); internalCall.call.callerNumber = (0, _utils2.getProperty)(callParams, 'callerDisplayNumber'); _utils.callFunctionIfExist(_core.call.onRemoteEndPointChange, remoteCallParams); } // eslint-disable-next-line no-inner-declarations function getCallerInfo(callParams) { var userId = callParams.callerDisplayNumber; if (userId.indexOf('@') === -1) { // Make sure the userId has a domain. userId += _core.getDomain(); } return { // callParams has both number and name for caller. displayNumber: userId, displayName: callParams.callerName }; } // eslint-disable-next-line no-inner-declarations function getCalleeInfo(callParams) { var userId = callParams.calleeDisplayNumber; if (userId.indexOf('@') === -1) { // Make sure the userId has a domain. userId += _core.getDomain(); } return { // callParams only has number for callee. displayNumber: userId }; } var currentUser = _core.getUser(); var remoteParticipant; // Outgoing call means the remote pariticpant is the callee. if (internalCall.call.isOutgoing) { // Double check that current user is the caller ...SPiDR switches // them during a transfer operation. if (currentUser.indexOf(callParams.callerDisplayNumber) > -1) { remoteParticipant = getCalleeInfo(callParams); } else { remoteParticipant = getCallerInfo(callParams); } } else { // Incoming call means the remote participant is the caller. // Double check that current user is the callee ...SPiDR switches // them during a transfer operation. if (currentUser.indexOf(callParams.calleeDisplayNumber) > -1) { remoteParticipant = getCallerInfo(callParams); } else { remoteParticipant = getCalleeInfo(callParams); } } logger.info('Call remote participant:', remoteParticipant); // If the remote participant changed, update it and notify the application. if (remoteParticipant.displayNumber !== internalCall.call.remoteParticipant.displayNumber) { // Edge-case: In a transfer operation, SPiDR switches the caller and callee users, // which triggers the "changed remote" logic. Ignore that case. if (currentUser !== remoteParticipant.displayNumber) { internalCall.call.remoteParticipant = remoteParticipant; // Set a flag on the call to be used by the FSM. internalCall.remoteParticipantChanged = true; _utils.callFunctionIfExist(internalCall.call.onRemoteEndPointChange, remoteParticipant); } } } handleCallControlNotification(notificationEvent, data); }; _notificationCallBacks.respondCallUpdate = function handleRespondCallUpdateNotification(data) { if (data.sessionParams && data.sessionParams.retryAfter) { handleCallControlNotification(fsmNotificationEvent.respondCallUpdate_glareCondition_Notify, data); } else { handleCallControlNotification(fsmNotificationEvent.respondCallUpdate_Notify, data); } }; _notificationCallBacks.sessionComplete = function handleSssionCompleteNotification(data) { handleCallControlNotification(fsmNotificationEvent.sessionComplete_Notify, data); }; _notificationCallBacks.sessionFail = function handleSessionFailNotification(data) { handleCallControlNotification(fsmNotificationEvent.sessionFail_Notify, data); }; _notificationCallBacks.callEnd = function handleCallEndNotification(data) { handleCallControlNotification(fsmNotificationEvent.callEnd_Notify, data); }; _notificationCallBacks.trying = function handleTryingNotification(data) { handleCallControlNotification(fsmNotificationEvent.trying_Notify, data); }; _notificationCallBacks.callCancel = function handleCallCancelNotification(data) { handleCallControlNotification(fsmNotificationEvent.callCancel_Notify, data); }; _notificationCallBacks.accepted = function handleAcceptedNotification(data) { handleCallControlNotification(fsmNotificationEvent.accepted_Notify, data); }; // here make parsing operations and then send sessionParams to the callManeger _notificationCallBacks.startCallReplace = function (data) { logger.debug('startCallReplace received: sdp: ' + data.sessionParams.sdp); self.handleStartCallReplaceNotification(data); }; _notificationCallBacks.IceCandidate = function (data) { self.handleIncomingIceCandidate(data); }; _globalBroadcaster.subscribe(_constants2.default.EVENT.DEVICE_SUBSCRIPTION_STARTED, onSubscriptionReEstablished); _globalBroadcaster.subscribe(_constants2.default.EVENT.CONNECTION_REESTABLISHED, onConnectionLost); _globalBroadcaster.subscribe(_constants2.default.EVENT.NOTIFICATION_CHANNEL_LOST, onConnectionLost); //@{test-methods} self.setCalls = function (_calls) { calls = _calls; }; self.setNotificationState = function (_notificationState) { this.notificationState = _notificationState; }; self.getStartCallQueue = function () { return startCallQueue; }; //@{test-methods} } /***/ }), /***/ "../fcs/src/js/call/wam/module.js": /*!****************************************!*\ !*** ../fcs/src/js/call/wam/module.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _callFsm = __webpack_require__(/*! ./callFsm */ "../fcs/src/js/call/wam/callFsm.js"); var _callManager = __webpack_require__(/*! ./callManager */ "../fcs/src/js/call/wam/callManager.js"); var _wamcall = __webpack_require__(/*! ./wamcall */ "../fcs/src/js/call/wam/wamcall.js"); exports.default = { CallFSM: function CallFSM(container) { return new _callFsm.CallFSMImpl(container); }, CallManager: function CallManager(container) { return new _callManager.CallManagerImpl(container); }, CallControlService: function CallControlService(container) { return new _wamcall.CallControlServiceImpl(container); } }; /***/ }), /***/ "../fcs/src/js/call/wam/wamcall.js": /*!*****************************************!*\ !*** ../fcs/src/js/call/wam/wamcall.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CallControlServiceImpl = CallControlServiceImpl; var _utils = __webpack_require__(/*! ../../utils */ "../fcs/src/js/utils/index.js"); var _constants = __webpack_require__(/*! ../../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function CallControlServiceImpl(_ref) { var _server = _ref.Http, _logManager = _ref.LogManager, _cache = _ref.Cache, _config = _ref.Config, _sdpPipeline = _ref.SdpPipeline; var logger = _logManager.getLogger('callControlService'); function runSdpPipeline(callid, sdp, operation, type) { return _sdpPipeline(callid, sdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SEND_LOCAL, type); } function addNotificationChannel(data) { if (_config.anonymous && _cache.getItem('NotificationId')) { data.callMeRequest.notifyChannelId = _cache.getItem('NotificationId'); } } function errorParser(jqXHR) { if (jqXHR && jqXHR.responseText) { return JSON.parse(jqXHR.responseText).callControlResponse; } } this.startCall = function (from, to, sdp, onSuccess, onFailure, customParameters) { var modifiedSdp = runSdpPipeline(undefined, sdp, _constants2.default.WEBRTC.SDP.OPERATION.START_CALL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); logger.info('Call Start Function: ' + from + ' --> ' + to); // response of the startCall contains callid/sessionData // callMe and callControl returns same response but object types have different namse function parseCallStart(data) { var callid, response = _config.anonymous ? data.callMeResponse : data.callControlResponse; if (response) { callid = response.sessionData; } return callid; } function dataType() { var data; if (_config.anonymous) { data = { 'callMeRequest': { 'type': 'callStart', 'from': from, 'to': to, 'sdp': modifiedSdp } }; if (customParameters) { data.callMeRequest.customParameters = customParameters; } } else { data = { 'callControlRequest': { 'type': 'callStart', 'from': from, 'to': to, 'sdp': modifiedSdp } }; if (customParameters) { data.callControlRequest.customParameters = customParameters; } if (_config.earlyMedia === true || _config.callReplace === true) { data.callControlRequest.supported = []; } if (_config.earlyMedia === true) { data.callControlRequest.supported.push('earlymedia'); } if (_config.callReplace === true) { data.callControlRequest.supported.push('replacecall'); } } return data; } var data = dataType(), realm = _config.realm; addNotificationChannel(data); _server.sendPostRequest({ 'url': _server.getWAMUrl(1, _config.anonymous ? '/callMe' + (realm ? '?tokenrealm=' + realm : '') : '/callControl'), 'data': data }, onSuccess, onFailure, parseCallStart, errorParser); }; this.audit = function (callid, onSuccess, onFailure) { var data, realm = _config.realm; if (_config.anonymous) { data = { 'callMeRequest': { 'type': 'audit' } }; } else { data = { 'callControlRequest': { 'type': 'audit' } }; } //TODO JF verify if we need to always do that and not only for callme realm; if (realm) { callid = callid.split('%0A')[0]; } _server.sendPutRequest({ 'url': _server.getWAMUrl(1, (_config.anonymous ? '/callme/callSessions/' : '/callControl/callSessions/') + callid + (realm ? '?tokenrealm=' + realm : '')), 'data': data }, onSuccess, onFailure, null, errorParser); }; this.hold = function (callid, sdp, onSuccess, onFailure, customParameters) { var modifiedSdp = runSdpPipeline(callid, sdp, _constants2.default.WEBRTC.SDP.OPERATION.HOLD, _constants2.default.WEBRTC.SDP.TYPE.OFFER); logger.info('Hold Function : sdp : ' + modifiedSdp); var data, realm = _config.realm; if (_config.anonymous) { data = { 'callMeRequest': { 'type': 'startCallUpdate', 'sdp': modifiedSdp } }; if (customParameters) { data.callMeRequest.customParameters = customParameters; } } else { data = { 'callControlRequest': { 'type': 'startCallUpdate', 'sdp': modifiedSdp } }; if (customParameters) { data.callControlRequest.customParameters = customParameters; } } _server.sendPutRequest({ 'url': _server.getWAMUrl(1, (_config.anonymous ? '/callme/callSessions/' : '/callControl/callSessions/') + callid + (realm ? '?tokenrealm=' + realm : '')), 'data': data }, onSuccess, onFailure, null, errorParser); }; this.unhold = function (callid, sdp, onSuccess, onFailure, customParameters) { var modifiedSdp = runSdpPipeline(callid, sdp, _constants2.default.WEBRTC.SDP.OPERATION.UNHOLD, _constants2.default.WEBRTC.SDP.TYPE.OFFER); logger.info('UnHold Function : sdp : ' + modifiedSdp); var data, realm = _config.realm; if (_config.anonymous) { data = { 'callMeRequest': { 'type': 'startCallUpdate', 'sdp': modifiedSdp } }; if (customParameters) { data.callMeRequest.customParameters = customParameters; } } else { data = { 'callControlRequest': { 'type': 'startCallUpdate', 'sdp': modifiedSdp } }; if (customParameters) { data.callControlRequest.customParameters = customParameters; } } _server.sendPutRequest({ 'url': _server.getWAMUrl(1, (_config.anonymous ? '/callme/callSessions/' : '/callControl/callSessions/') + callid + (realm ? '?tokenrealm=' + realm : '')), 'data': data }, onSuccess, onFailure, null, errorParser); }; this.reinvite = function (callid, sdp, onSuccess, onFailure, customParameters) { var modifiedSdp = runSdpPipeline(callid, sdp, _constants2.default.WEBRTC.SDP.OPERATION.UPDATE, _constants2.default.WEBRTC.SDP.TYPE.OFFER); logger.info('reinvite Function : sdp : ' + modifiedSdp); var data, realm = _config.realm; if (_config.anonymous) { data = { 'callMeRequest': { 'type': 'startCallUpdate', 'sdp': modifiedSdp } }; if (customParameters) { data.callMeRequest.customParameters = customParameters; } } else { data = { 'callControlRequest': { 'type': 'startCallUpdate', 'sdp': modifiedSdp } }; if (customParameters) { data.callControlRequest.customParameters = customParameters; } } _server.sendPutRequest({ 'url': _server.getWAMUrl(1, (_config.anonymous ? '/callme/callSessions/' : '/callControl/callSessions/') + callid + (realm ? '?tokenrealm=' + realm : '')), 'data': data }, onSuccess, onFailure, null, errorParser); }; this.respondCallUpdate = function (callid, sdp, onSuccess, onFailure, customParameters) { var operation = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : _constants2.default.WEBRTC.SDP.OPERATION.UPDATE; var modifiedSdp = runSdpPipeline(callid, sdp, operation, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); logger.info('Respond Call Update Function : sdp : ' + modifiedSdp); var data, realm = _config.realm; if (_config.anonymous) { data = { 'callMeRequest': { 'type': 'respondCallUpdate', 'sdp': modifiedSdp } }; if (customParameters) { data.callMeRequest.customParameters = customParameters; } } else { data = { 'callControlRequest': { 'type': 'respondCallUpdate', 'sdp': modifiedSdp } }; if (customParameters) { data.callControlRequest.customParameters = customParameters; } } _server.sendPutRequest({ 'url': _server.getWAMUrl(1, (_config.anonymous ? '/callme/callSessions/' : '/callControl/callSessions/') + callid + (realm ? '?tokenrealm=' + realm : '')), 'data': data }, onSuccess, onFailure, null, errorParser); }; this.respondToRemoteHold = function (callid, sdp, onSuccess, onFailure, customParameters) { this.respondCallUpdate(callid, sdp, onSuccess, onFailure, customParameters, _constants2.default.WEBRTC.SDP.OPERATION.HOLD); }; this.respondToRemoteUnhold = function (callid, sdp, onSuccess, onFailure, customParameters) { this.respondCallUpdate(callid, sdp, onSuccess, onFailure, customParameters, _constants2.default.WEBRTC.SDP.OPERATION.UNHOLD); }; this.join = function (firstSessionData, secondSessionData, sdp, onSuccess, onFailure, customParameters) { var modifiedSdp = runSdpPipeline(undefined, sdp, _constants2.default.WEBRTC.SDP.OPERATION.UPDATE, _constants2.default.WEBRTC.SDP.TYPE.OFFER); logger.info('Join Function : sdp : ' + modifiedSdp); function parseJoin(data) { var callid, response = data.callControlResponse; if (response) { callid = response.sessionData; } return callid; } var data = { 'callControlRequest': { 'type': 'join', 'firstSessionData': firstSessionData, 'secondSessionData': secondSessionData, 'sdp': modifiedSdp } }; if (customParameters) { data.callControlRequest.customParameters = customParameters; } if (_config.clientControlled === 'true') { data.callControlRequest.clientControlled = 'true'; } _server.sendPostRequest({ 'url': _server.getWAMUrl(1, '/callControl/'), 'data': data }, onSuccess, onFailure, parseJoin, errorParser); }; this.refer = function (callid, referTo, referredBy, onSuccess, onFailure) { logger.info('Refer Function : refer to: ' + referTo); var data = { 'callControlRequest': { 'type': 'refer', 'from': referredBy, 'to': referTo } }; _server.sendPutRequest({ 'url': _server.getWAMUrl(1, '/callControl/callSessions/' + callid), 'data': data }, onSuccess, onFailure, null, errorParser); }; this.endCall = function (callid, onSuccess, onFailure, localReasonText) { var realm = _config.realm; logger.info('endCall Function: ' + callid); var endUrl = (_config.anonymous ? '/callme/callSessions/' : '/callControl/callSessions/') + callid; var queryString = localReasonText ? '?reasonText=' + localReasonText : ''; if (realm) { var delimiter = queryString ? '&' : '?'; queryString += realm ? delimiter + 'tokenrealm=' + realm : ''; } _server.sendDeleteRequest({ 'url': _server.getWAMUrl(1, endUrl + queryString), 'data': {} }, onSuccess, onFailure, null, errorParser); }; this.answerCall = function (callid, sdp, onSuccess, onFailure, customParameters) { var modifiedSdp = runSdpPipeline(callid, sdp, _constants2.default.WEBRTC.SDP.OPERATION.ANSWER_CALL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); logger.info('Answer Call Function : sdp : ' + modifiedSdp); var data = { 'callControlRequest': { 'type': 'callAnswer', 'sdp': modifiedSdp } }; if (customParameters) { data.callControlRequest.customParameters = customParameters; } if (_config.callReplace === true) { data.callControlRequest.supported = ['replacecall']; } _server.sendPutRequest({ 'url': _server.getWAMUrl(1, '/callControl/callSessions/' + callid), 'data': data }, onSuccess, onFailure, null, errorParser); }; function makeRequest(action, sessionData, onSuccess, onFailure, address) { logger.info('makeRequest Function with action : ' + action); var data = { 'callDispositionRequest': { 'action': action, 'sessionData': sessionData } }; if (address) { data.callDispositionRequest.address = address; } _server.sendPostRequest({ 'url': _server.getWAMUrl(1, '/calldisposition'), 'data': data }, onSuccess, onFailure, null, errorParser); } this.sendCustomParameters = function (callid, customParameters, onSuccess, onFailure) { logger.info('sendCustomParameters Function with parameters : ' + customParameters); var data, realm = _config.realm; if (_config.anonymous) { data = { 'callMeRequest': { 'type': 'sendCustomHeaders', 'customParameters': customParameters } }; } else { data = { 'callControlRequest': { 'type': 'sendCustomHeaders', 'customParameters': customParameters } }; } _server.sendPutRequest({ 'url': _server.getWAMUrl(1, (_config.anonymous ? '/callme/callSessions/' : '/callControl/callSessions/') + callid + (realm ? '?tokenrealm=' + realm : '')), 'data': data }, onSuccess, onFailure, null, errorParser); }; this.reject = function (callid, onSuccess, onFailure) { var dummy; logger.info('Reject Function: ' + callid); makeRequest('reject', callid, onSuccess, onFailure, dummy); }; this.forward = function (callid, address, onSuccess, onFailure) { logger.info('Forward Function : address: ' + address); makeRequest('forward', callid, onSuccess, onFailure, address); }; this.transfer = function (callid, address, sessiondataToTransfer, onSuccess, onFailure) { logger.info('Call Transfer Function : target address: ' + address); var data = { 'callControlRequest': { 'type': 'transfer', 'address': address, 'sessionData': sessiondataToTransfer } }; _server.sendPutRequest({ 'url': _server.getWAMUrl(1, '/callControl/callSessions/' + callid), 'data': data }, onSuccess, onFailure, null, errorParser); }; this.clickToCall = function (callingParty, calledParty, onSuccess, onFailure) { var data = { 'clickToCallRequest': { 'callingParty': callingParty, 'calledParty': calledParty } }; _server.sendPostRequest({ 'url': _server.getWAMUrl(1, '/clicktocall'), 'data': data }, onSuccess, onFailure); }; this.getIMRN = function (realm, source, destination, onSuccess, onFailure) { logger.info('(Wam Call) getIMRN Function '); function parseIMRNResponse(IMRNdata) { var receivedIMRN; if (IMRNdata && IMRNdata.imrnResponse) { receivedIMRN = (0, _utils.getProperty)(IMRNdata.imrnResponse, 'imrn'); } return receivedIMRN; } if (destination.match('@')) { if (destination.split(':')[0] !== 'sip') { destination = 'sip:' + destination; } } var data = { 'imrnRequest': { 'realm': realm, 'sourceAddress': source, 'destinationAddress': destination } }; _server.sendPostRequest({ 'url': _server.getWAMUrl(1, '/imrn'), 'data': data }, onSuccess, onFailure, parseIMRNResponse); }; this.acceptCallReplace = function (callData, onSuccess, onFailure, customParameters) { function parseAcceptCallReplaceData(data) { logger.info('acceptCallReplace.data: ' + data); return data; } function dataType() { var data; data = { 'callControlRequest': { 'type': 'acceptCallReplace', 'sdp': callData.sdp } }; if (customParameters) { data.callControlRequest.customParameters = customParameters; } return data; } var data = dataType(); _server.sendPutRequest({ 'url': _server.getWAMUrl(1, '/callControl/callSessions/' + callData.id), 'data': data }, onSuccess, onFailure, parseAcceptCallReplaceData, errorParser); }; this.rejectCallReplace = function (callData, onSuccess, onFailure) { function parseRejectCallReplaceData(data) { logger.info('rejectCallReplace.data: ' + data); return data; } function dataType() { var data; data = { 'callControlRequest': { 'type': 'rejectCallReplace' } }; return data; } var data = dataType(); _server.sendPutRequest({ 'url': _server.getWAMUrl(1, '/callControl/callSessions/' + callData.id), 'data': data }, onSuccess, onFailure, parseRejectCallReplaceData, errorParser); }; this.ringing = function (callid) { _server.sendPutRequest({ 'url': _server.getWAMUrl(1, '/callControl/callSessions/' + callid), 'data': { 'callControlRequest': { 'type': 'ringing' } } }, null, null, null, errorParser); }; this.updateIceCandidate = function (callData, onSuccess, onFailure) { var realm = _config.realm; _server.sendPutRequest({ 'url': _server.getWAMUrl(1, (_config.anonymous ? '/callme/callSessions/' : '/callControl/callSessions/') + callData.id + (realm ? '?tokenrealm=' + realm : '')), 'data': { 'callControlRequest': { 'type': 'updateIceCandidate', 'iceCandidates': callData.iceCandidates } } }, onSuccess, onFailure, null, errorParser); }; } /***/ }), /***/ "../fcs/src/js/challenge.js": /*!**********************************!*\ !*** ../fcs/src/js/challenge.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ChallengeManagerFactory = ChallengeManagerFactory; var _once = __webpack_require__(/*! lodash/once */ "../../node_modules/lodash/once.js"); var _once2 = _interopRequireDefault(_once); var _promiscuous = __webpack_require__(/*! promiscuous */ "../../node_modules/promiscuous/promiscuous.js"); var _promiscuous2 = _interopRequireDefault(_promiscuous); var _utils = __webpack_require__(/*! ./utils */ "../fcs/src/js/utils/index.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function ChallengeManagerFactory() { var challengeManager = {}; /* * Set the challenge handler which is a function that will receive challenges. * @param {Function} handler A function which will receive authentication challenges. * @param {Function} handler.retry A function which once called, will give resume the execution queue where it left * off before the challenge using the answer to the challenge. * @param {any} handler.retry.answer The challenge answer to pass to the retry function that will resolve the challenge. * @param {Function} handler.cancel A function which once called with resume the execution where it left of but will * let it down the error path since the challenge was not answered. */ challengeManager.setChallengeHandler = function (handler) { if (typeof handler !== 'function') { throw new TypeError('Challenge handler is not a function.'); } challengeManager.challengeHandler = handler; }; /* * Sets an answer handler to give a chance for the anybody using challenges to get notified whenever * a challenge gets answered. This allows to store the challenge answer by the app. * * @param {Function} handler Answer handler which will be called whenever a challenge is answered. * @param {any} handler.answer The answer to the challenge. */ challengeManager.setAnswerHandler = function (handler) { if (typeof handler !== 'function') { throw new TypeError('Challenge handler is not a function.'); } challengeManager.challengeAnswerHandler = handler; }; /* * Starts a challenge to the application. A challenge can be anything that the application needs to provide * for execution to continue. A challenge creates a promise for an answer. At which point it is up * to the challenger to interpret the result of the challenge. * * @return {Promise} A promise for an answer to the challenge. The promise will reject if the challenge is * canceled by the application. */ challengeManager.challenge = function () { if (challengeManager.challengeSuspensions > 0) { return new _promiscuous2.default.reject(); } // If we don't already have a challenge to the application in progress, create one. if (!challengeManager.currentChallenge) { challengeManager.currentChallenge = (0, _utils.always)(new _promiscuous2.default(function (resolve, reject) { if (challengeManager.challengeHandler) { var retry = (0, _once2.default)(function (params) { if (challengeManager.challengeAnswerHandler) { challengeManager.challengeAnswerHandler(params); } // Resolve the challenge and allow continuation of paused requests. resolve(params); }); var cancel = (0, _once2.default)(function () { // Reject the challenge reject(); }); challengeManager.challengeHandler(retry, cancel); } else { reject(); } }), function () { return challengeManager.currentChallenge = undefined; }); } return challengeManager.currentChallenge; }; /* * Temporarily suspend any challenges. * @param {Promise} waitOn Promise on which to wait for being settled before resuming challenges * @return {Promise} Continuation of the original promise which will resolve once the challenges * have been resumed. */ challengeManager.suspendChallenges = function (waitOn) { challengeManager.challengeSuspensions++; return (0, _utils.always)(waitOn, function () { return challengeManager.challengeSuspensions -= 1; }); }; challengeManager.challengeSuspensions = 0; return challengeManager; } /***/ }), /***/ "../fcs/src/js/config.js": /*!*******************************!*\ !*** ../fcs/src/js/config.js ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Config = Config; var _constants = __webpack_require__(/*! ./constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Config() { return { polling: 30, iceCandidateCollectionTimeoutInterval: 3000, pluginMode: { mode: 'auto', h264: true }, sdpHandlers: [], bundlePolicy: _constants2.default.WEBRTC.SDP.BUNDLE_POLICY.DISABLED }; } /***/ }), /***/ "../fcs/src/js/constants.js": /*!**********************************!*\ !*** ../fcs/src/js/constants.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { 'WEBRTC': { 'PLUGIN_ID': 'fcsPlugin', 'MEDIA_STATE': { NOT_FOUND: 'notfound', SEND_RECEIVE: 'sendrecv', SEND_ONLY: 'sendonly', RECEIVE_ONLY: 'recvonly', INACTIVE: 'inactive' }, 'RTC_SIGNALING_STATE': { STABLE: 'stable', HAVE_LOCAL_OFFER: 'have-local-offer', HAVE_REMOTE_OFFER: 'have-remote-offer', HAVE_LOCAL_PRANSWER: 'have-local-pranswer', HAVE_REMOTE_PRANSWER: 'have-remote-pranswer', CLOSED: 'closed' }, SDP: { TYPE: { 'OFFER': 'offer', 'ANSWER': 'answer', 'PRANSWER': 'pranswer' }, OPERATION: { 'START_CALL': 'START_CALL', 'ANSWER_CALL': 'ANSWER_CALL', 'HOLD': 'HOLD', 'UNHOLD': 'UNHOLD', 'UPDATE': 'UPDATE', 'RESPOND': 'RESPOND', 'REOFFER': 'REOFFER', 'DATA_CHANNEL': 'DATA_CHANNEL' }, STEP: { 'PRE_SET_LOCAL': 'PRE_SET_LOCAL', 'PRE_SET_REMOTE': 'PRE_SET_REMOTE', 'PRE_SEND_LOCAL': 'PRE_SEND_LOCAL' }, BUNDLE_POLICY: { MAX_COMPAT: 'max-compat', MAX_BUNDLE: 'max-bundle', BALANCED: 'balanced', DISABLED: 'DISABLED' } }, 'ERROR': { 'ICE_ICELITE': 'ICE_ICELITE' } }, 'STRING': { 'NEW_LINE': '\n', 'CARRIAGE_RETURN': '\r', 'VIDEO': 'video', 'AUDIO': 'audio' }, 'SDP': { 'A_LINE': 'a=', 'M_LINE': 'm=', 'CRYPTO': 'crypto', 'FINGERPRINT': 'fingerprint', 'ICE_UFRAG': 'ice-ufrag:', 'ICE_PWD': 'ice-pwd:', 'NACK': 'nack', 'NACKPLI': 'nack pli', 'SETUP_ACTIVE': 'a=setup:active', 'SETUP_PASSIVE': 'a=setup:passive', 'SETUP_ACTPASS': 'a=setup:actpass', 'BANDWIDTH': { 'MAXPLAYBACKRATE': 'maxplaybackrate', 'MAXAVERAGEBITRATE': 'maxaveragebitrate', 'FEC': 'useinbandfec', 'DTX': 'usedtx', 'PTIME': 'ptime' } }, 'HTTP_METHOD': { 'GET': 'GET', 'POST': 'POST', 'PUT': 'PUT', 'DELETE': 'DELETE', 'OPTIONS': 'OPTIONS' }, 'WEBSOCKET': { 'PROTOCOL': { 'SECURE': 'wss', 'NONSECURE': 'ws' }, 'DEFAULT_PORT': '8581', 'STATUS': { 'OPENED': 1, 'ALREADY_OPENED': 2, 'CREATE_ERROR': 3, 'CONNECTION_ERROR': 4, 'NOT_FOUND': 5, 'CONNECTION_CLOSED': 6 }, 'FOREGROUND_INTERVAL': 10000, 'BACKGROUND_INTERVAL': 60000 }, 'LONG_POLLING': { 'STATUS': { 'TRIGGERED_CONNECT': 1 } }, 'NOTIFICATION': { 'STATUS': { 'NOT_STARTED': 3, 'CONFIGURATION_ERROR': 4, 'STOP_FOR_LP_TO_WS_UPGRADE': 5 } }, 'EVENT': { 'XHR_REQUEST_NOT_INITIALIZED': 'XHR_REQUEST_NOT_INITIALIZED', 'DEVICE_SUBSCRIPTION_STARTED': 'DEVICE_SUBSCRIPTION_STARTED', 'DEVICE_SUBSCRIPTION_STOPPED': 'DEVICE_SUBSCRIPTION_STOPPED', 'DEVICE_SUBSCRIPTION_ENDED': 'DEVICE_SUBSCRIPTION_ENDED', 'CONNECTION_REESTABLISHED': 'CONNECTION_REESTABLISHED', 'CONNECTION_LOST': 'CONNECTION_LOST', 'TOKEN_AUTH_STARTED': 'TOKEN_AUTH_STARTED', 'BASIC_AUTH_STARTED': 'BASIC_AUTH_STARTED', 'TOKEN_NOT_FOUND': 'TOKEN_NOT_FOUND', 'SESSION_EXPIRED': 'SESSION_EXPIRED', 'NOTIFICATION_CHANNEL_LOST': 'NOTIFICATION_CHANNEL_LOST', 'FCS_SETUP_COMPLETED': 'FCS_SETUP_COMPLETED', 'WEBSOCKET_CONNECTED': 'WEBSOCKET_CONNECTED', 'WEBSOCKET_ERROR': 'WEBSOCKET_ERROR', 'WEBSOCKET_DISCONNECTED': 'WEBSOCKET_DISCONNECTED', 'WEBSOCKET_CONNECTIVITY_CHECK': 'WEBSOCKET_CONNECTIVITY_CHECK', 'NETWORK_ERROR': 'NETWORK_ERROR', 'NETWORK_CHANGED': 'NETWORK_CHANGED', 'SERVER_CHANGED': 'SERVER_CHANGED' }, 'SUBSCRIPTION_EVENT': { 'TOKEN_OR_SESSION_LOSS': 'TOKEN_OR_SESSION_LOSS', 'SUBSCRIPTION_SUCCESS': 'SUBSCRIPTION_SUCCESS', 'EXTEND_SUCCESS': 'EXTEND_SUCCESS', 'EXTEND_FAILURE': 'EXTEND_FAILURE', 'REGULAR_EXTEND_PROCESSING': 'REGULAR_EXTEND_PROCESSING', 'STOP_SUCCESS': 'STOP_SUCCESS', 'STOP_FAILURE': 'STOP_FAILURE', 'CONNECTION_LOSS': 'CONNECTION_LOSS', 'SET_NOTIFICATION_ONERROR': 'SET_NOTIFICATION_ONERROR', 'SET_NOTIFICATION_ONSUCCESS': 'SET_NOTIFICATION_ONSUCCESS', 'TRIGGER_LONG_POLLING': 'TRIGGER_LONG_POLLING', 'RESTART_SUBSCRIPTION_REQUEST': 'RESTART_SUBSCRIPTION_REQUEST' }, 'NOTIFICATION_EVENT': { 'NOTIFICATION_SUCCESS': 'NOTIFICATION_SUCCESS', 'NOTIFICATION_FAILURE': 'NOTIFICATION_FAILURE' }, 'CACHE': { 'NOTIFYURL': 'NotificationUrl', 'NOTIFYID': 'NotificationId', 'SUBSCRIBEURL': 'SubscriptionUrl', 'SUBSCRIBEEXPIRY': 'SubscriptionExpiry', 'SUBSCRIBEEXTENDINTERVAL': 'SubscriptionExtendInterval', 'SESSION': 'SESSION' }, 'TIMEOUT': { 'STAGGERED_MAX': 5000, 'STAGGERED_MIN': 300, 'CHECK_INTERVAL': 10000, 'RETRY_START': 10000, 'RETRY_LIMIT': 640000, 'RETRY_MULTIPLIER': 2, 'WS_ERROR': 0 }, 'PLATFORM': { 'IOS': 'iOS' }, 'TRICKLE': { 'NONE': 'none', 'HALF': 'half', 'FULL': 'full' } }; /***/ }), /***/ "../fcs/src/js/core.js": /*!*****************************!*\ !*** ../fcs/src/js/core.js ***! \*****************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _values = __webpack_require__(/*! babel-runtime/core-js/object/values */ "../../node_modules/babel-runtime/core-js/object/values.js"); var _values2 = _interopRequireDefault(_values); var _keys = __webpack_require__(/*! babel-runtime/core-js/object/keys */ "../../node_modules/babel-runtime/core-js/object/keys.js"); var _keys2 = _interopRequireDefault(_keys); exports.CoreImpl = CoreImpl; var _constants = __webpack_require__(/*! ./constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); var _errors = __webpack_require__(/*! ./errors */ "../fcs/src/js/errors.js"); var _errors2 = _interopRequireDefault(_errors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * @name fcs * @namespace * @param _server * @param _globalBroadcaster */ function CoreImpl(_ref) { var _globalBroadcaster = _ref.GlobalBroadcaster, _config = _ref.Config; var dev = null, pluginVer = null, services = {}, un = null, tkn = null, authorizationName = null, connected = true, tokenRealm = null, kandyUAT = null, DEFAULT_SUBSCRIPTION_EXPIRY_VALUE = 3600, MIN_SUBSCRIPTION_EXPIRY_VALUE = 60; /** * This function creates a new instance of the library. This allows multiple users to be logged in an using * the library at the same time. * * @name fcs#createInstance * @function * @returns {fcs} * * @example * var fcs2 = fcs.createInstance(); * fcs2.setup(...); * fcs2.call.startCall(...); */ /** * This function returns value of async paramater of $.ajax requests * * @name fcs#isAsync * @function * @returns {Boolean} true/false * @deprecated * @since 3.0.0 * * @example * fcs.isAsync(); */ this.isAsync = function () {}; /** * This function sets async option of $.ajax() requests. * If It is set to false, ajax requests will be sent synchronously * otherwise ajax requests will be sent asynchronously. * * @name fcs#setAsync * @function * @param {Boolean} value * @return {Boolean} true/false * @deprecated * @since 3.0.0 * * @example * fcs.setAsync(false); */ this.setAsync = function () {}; /** * This function returns username of authenticated user in user@domain format. * * @name fcs#getUser * @function * @returns {string} Username of current user * @since 3.0.0 * * @example * fcs.getUser(); */ this.getUser = function () { return un; }; /** * This function returns authorization name of authenticated user * * @name fcs#getAuthUser * @function * @returns {String} Authorization name of current user * @since 3.0.0 * * @example * fcs.getAuthUser(); */ this.getAuthUser = function () { if (authorizationName) { return authorizationName; } else { return un; } }; /** * This function returns current domain name of authenticated user * * @name fcs#getDomain * @function * @returns {string} Current domain name * @since 3.0.0 * * @example * fcs.getDomain(); */ this.getDomain = function () { return un.split('@')[1]; }; /** * This function returns the version of the JSL-API * * @name fcs#getVersion * @function * @returns {string} Version of the JSL-API * @since 3.0.0 * * @example * fcs.getVersion(); */ this.getVersion = function () { return '@{spidr.jsl.version}'; }; /** * This fucntion returns current device. * * @name fcs#getDevice * @function * @returns {string} Device specified for communicating with the server * @since 3.0.0 * * @example * fcs.getDevice(); */ this.getDevice = function () { return dev; }; /** * This function sets the user as authentication mode and cancels device authentication (if such exists), * as user and device modes are mutually exclusive. * authname parameter is optional. * * @name fcs#setUserAuth * @function * @param {string} user User name to be used for communicating with the server * @param {string} password Password to be used for communicating with the server * @param {string} authname If provided authname is used instead of user name for authentication * * @since 3.0.0 * * @example * fcs.setUserAuth("Username", "Password","Authname"); */ this.setUserAuth = function (user, password, authname) { un = user; dev = null; var data = { 'username': user, 'password': password }; if (typeof authname === 'string' && authname.trim().length > 0) { data.authname = authname; authorizationName = authname; } else { authorizationName = null; } _globalBroadcaster.publish(_constants2.default.EVENT.BASIC_AUTH_STARTED, data); }; /** * This function sets the user as token mode authentication and cancels user authentication or/and device authentication (if such exists), * token authentication has priority over other authentications * * @name fcs#setTokenAuth * @function * @param {string} user to be used for communicating with the server * @param {string} token to be used for communicating with the server * * @since 3.0.0 * * @example * fcs.setTokenAuth("Username", "Token"); */ this.setTokenAuth = function (user, token) { un = user; tkn = token; _globalBroadcaster.publish(_constants2.default.EVENT.TOKEN_AUTH_STARTED, { 'username': user, 'token': token }); }; this.getTokenAuth = function () { return tkn; }; /** * This function sets the device as authentication mode and cancels user authentication (if such exists), * as user and device modes are mutually exclusive. * * @name fcs#setDeviceAuth * @function * @since 3.0.0 * @param {string} deviceID The device to be used for communicating with the server * * @example * fcs.setDeviceAuth("DeviceID"); */ this.setDeviceAuth = function (deviceID) { dev = deviceID; un = null; }; /** * This function sets the authentication realm for time limited token authentication. * * @name fcs.setRealm * @function * @since 3.0.4 * @param {string} realm The realm for the time limited token auth * * @example * fcs.setRealm("realmname"); */ this.setRealm = function (realm) { tokenRealm = realm; }; /** * This function gets the authentication realm for time limited token authentication. * * @name fcs.getRealm * @function * @since 3.0.4 * @returns {string} The realm for the time limited token auth * * @example * var realm = fcs.getRealm(); */ this.getRealm = function () { return tokenRealm; }; /** * This function sets the authentication UAT for kandy Authentication. * * @name fcs.setKandyUAT * @function * @since 3.0.4 * @param {string} uat The User Access Token * * @example * fcs.setKandyUAT("uat"); */ this.setKandyUAT = function (uat) { kandyUAT = uat; }; /** * This function gets the authentication UAT for kandy Authentication. * * @name fcs.getKandyUAT * @function * @since 3.0.4 * @returns {string} The User Access Token * * @example * var uat = fcs.getKandyUAT(); */ this.getKandyUAT = function () { return kandyUAT; }; /** * List of Authentication Types. * @see setDeviceAuth * @see setUserAuth * @name fcs#AuthenticationType * @property {number} USER User authentication * @property {number} DEVICE Device authentication * @readonly */ this.AuthenticationType = { USER: 1, DEVICE: 2 }; /** * List of Error Types * * @name fcs#Errors * @property {number} NETWORK Network failures * @property {number} AUTH Authentication / Authorization failures * @property {number} STATE Invalid state * @property {number} PRIV Privilege failures * @property {number} UNKNOWN Unknown failures * @property {number} LOGIN_LIMIT Login limit exceeded * @property {number} INCORRECT_LOGIN_PASS Incorrect identifier * @property {number} INVALID_LOGIN Invalid username * @property {number} TOKEN_NOT_FOUND Token provided is not valid * @property {number} SESSION_EXPIRED Session generated from token is expired * @property {number} VIDEO_SESSION_NOT_AVAILABLE Video Session is not available * @property {number} PENDING_REQUEST There is a pending request. * @property {number} NOT_ALLOWED_SERVICE Service is not allowed. * @property {number} NOT_ALLOWED_METHOD Method is not allowed. * @property {number} NOT_ALLOWED_INSTANCE Instance is not allowed. * @property {number} INVALID_PARAMETER Parameter is invalid. * @property {number} CONNECTION_ISSUE Connection problem. * @property {number} MEDIA_NOT_FOUND Media not found error. * @property {number} MEDIA_NOT_ALLOWED Media not allowed error. * @property {number} CALL_FAILED Call failed. * @property {number} CALL_ENDED Call ended. * @property {number} MAXIMUM_ENTRIES Maximum entries error. * @property {number} ENTRY_ALREADY_EXISTS Entry already exists error. * @property {number} SERVICE_NOT_AUTHORIZED Service authorization error. * @property {number} DB_EXCEPTION Database exception Error. * @property {number} INSUFFICIENT_INFO Insufficient error. * @property {number} NOT_FOUND Not Found error. * @property {number} INTERNAL_SERVER_ERROR Internal server error. * @property {number} SERVICE_UNAVAILABLE Service unavaible error. * @property {number} SESSION_NOT_FOUND The device's session was not found. * @property {number} CANNOT_SUBSCRIBE Device cannot subscribe. * @property {number} MEDIA_REQUIRED The call media to use was not specified. * * @readonly * @example * if (e === fcs.Errors.AUTH) * { * console.log("Authentication error occured") * } */ this.Errors = _errors2.default; /** * @typedef modifiedValues * @type Object * @property {number} url Modified url to replace xhr original url * @property {object} headers Mofied headers object to replace original xhr headers * @since 3.1.2 */ /** * Ajax hook to intercept outgoing xhr request to modify url and headers * * @since 3.1.2 * * @callback ajaxHook * @param {Object} xhr XMLHttpRequest object * @param {window} window window object * @param {object} params object containing parameters * @param {string} [params.type] The HTTP method to use, such as "GET", "POST", "PUT", "DELETE", etc * @param {string} [params.url] The URL to send the request to * @param {string} [params.headers] Request headers * @param {string} [params.data] Request body * * @return {modifiedValues} object containing modified url and headers * */ /** * Establishes bandwidth control functionalities based on provided audio codecs and values * @typedef opusConfig * @type Object * * @property {string} [maxPlaybackRate] value between 8000 and 48000 * @property {string} [maxAverageBitrate] value between 6000 and 510000 * @property {string} [fec] 0 or 1 * @property {string} [dtx] 0 or 1 * @property {string} [ptime] integer value between 2.5 and 120 * * @example * * opusConfig: { * maxPlaybackRate: 16000, * maxAverageBitrate: 20000, * fec: 1, * dtx: 1, * ptime: 40 * } */ /** * Configures plugin mode (as 'webrtc' or 'auto') and h264 status as browser-specific with version restriction (for Chrome and Firefox) or as general default values. * @typedef {Object} fcsSetupConfigParamsPluginMode * @property {string} [mode="auto"] General plugin mode. 'webrtc' for default webrtc plugin, 'auto' for the usage of native chrome and firefox or the usage of default webrtc plugin for the others. * @property {boolean} [h264=true] General H264 codec status. * @property {object} [chrome] Chrome-specific configurations * @property {string} [chrome.mode] Chrome-specific plugin mode. Overrides the general one. * @property {boolean} [chrome.h264] Chrome-specific H264 codec status. Overrides the general one. * @property {string} [chrome.version] Version lowerbound for Chrome configurations. Ex: "40+". Includes all the versions if not given. * @property {object} [firefox] Firefox-specific configurations * @property {string} [firefox.mode] Firefox-specific plugin mode. Overrides the general one. * @property {boolean} [firefox.h264] Firefox-specific H264 codec status. Overrides the general one. * @property {string} [firefox.version] Version lowerbound for Firefox configurations. Ex: "40+". Includes all the versions if not given. * * @example * * pluginMode: { * mode: 'webrtc', * h264: true, * chrome: { * mode: 'auto' * },firefox: { * version: '38+', * mode: 'auto' * } * } */ /** * Array of servers to be tried to for notification subscription. * @typedef {Object[]} fcsSetupConfigParamsServers * * @property {string} [protocol=window.location.protocol] HTTP protocol to be used. Ex: Http, Https * @property {string} [restUrl=window.location.hostname] The URL of REST server http://ip:port. * @property {string} [restPort=window.location.port] The port of REST server http://ip:port. * @property {string} [websocketProtocol=ws] Determines if the websocketProtocol is secure or non-secure. * @property {string} [websocketIP=window.location.hostname] Holds the websocket connection's IP adress. * @property {string} [websocketPort=8581] Holds the websocket connection's port value. By defult, it is 8581. * * @example * "servers": [{ * "protocol": "https", * "restUrl": "spidrdomain.com", * "restPort": "443", * "websocketProtocol": "wss", * "websocketIP": "spidrdomain.com", * "websocketPort": "443" * }], */ /** * A handler function that is given a chance to make modificaitons to a given SDP before and/or after a local and/or remote description is set. * * @callback sdpHandler * @param {Object} params The object of parameters for the function. * @param {Object} params.currentSdp The current SDP provided by the last handler which may be modified from the original SDP. You can check if currentSdp has been modified by comparing it against originalSdp for referential equality. You cannot modify this object. * @param {Object} params.originalSdp The original SDP provided to the pipeline of handlers. You cannot modify this object. * @param {string} params.operation The call operation being done that requires the SDP. Values are in fcs.SDP_CONSTANTS.OPERATION. * @param {string} params.step The step at which the pipeline is being called. Values are in fcs.SDP_CONSTANTS.STEP. * @param {string} params.type The type of sdp. Values are in fcs.SDP_CONSTANTS.TYPE. * @param {string} params.callId The Id of the call this Sdp is for. It may be undefined if this is a start call operation since it will not have an Id yet. * @param {function} params.next Handlers should return the value of calling `next` with the modified SDP as its only parameter. If no modifications are made, the handler should return the value of calling next with `currentSdp`. Not calling `next` will force the pipeline to ignore the rest of the handlers. * @example * ``` javascript * function forceH264({next, currentSDP, originalSDP, operation, step, type, callId}) { * const nextSDP = Object.assign({}, currentSDP, {propertyName: 'value'}); * * return next(nextSDP); * * // or, if you want to end the pipeline * return nextSDP; * } * ``` */ /** * JSL library setup * @typedef {Object} fcsSetupConfigParams * @property {string} [notificationType=LONGPOLLING] The notification type to be used {@link fcs.notification#NotificationTypes} * @property {string} [serverRetryNumber=5] Server retry number is used when websocket failure. The current websocket will be tried for the given parameter (Between 0 and 10) * @property {string} [serverRetryInterval] Server retry time interval is the current failed websocket retry interval. Default value is 5000. (Between 1000 and 10000) * @property {Object[]} [servers=[]] servers config {@link fcsSetupConfigParamsServers}. * @property {string} [restUrl] Deprecated. please use {@link fcsSetupConfigParamsServers} * @property {string} [restPort] Deprecated. please use {@link fcsSetupConfigParamsServers} * @property {string} [websocketProtocol] Deprecated. please use {@link fcsSetupConfigParamsServers} * @property {string} [websocketIP] Deprecated. please use {@link fcsSetupConfigParamsServers} * @property {string} [websocketPort] Deprecated. please use {@link fcsSetupConfigParamsServers} * @property {string} [protocol] Deprecated. please use {@link fcsSetupConfigParamsServers} * @property {string} [polling=30] Polling time value in seconds. * @property {number} [expires=3600] Expire time value in seconds.Default value is 3600.(60 and bigger than 60 ). * @property {string} [codecsToRemove] Audio codesc to be removed. * @property {string} [codecsToRemoveForVideo] Video codesc to be removed. * @property {Object} [opusConfig] Bandwidth controls to add for Opus audio codec * @property {string} [callAuditTimer=30000] Audit time value for calls. * @property {boolean} [cors=false] True if Cross-Origin Request Sharing supported. * @property {string} [services="IM, Presence, Call"] Defines the enabled services for client. * @property {boolean} [serverProvidedTurnCredentials=false] Provide TURN server credentials from server or not. * @property {number} [iceCandidateCollectionTimeoutInterval=3000] When provided (in milliseconds), ice candidate collection assumed to be completed if at least one candidate is received within the interval. * @property {number} [relayCandidateCollectionTimeoutCycle] When provided, iceCandidateCollectionTimeoutInterval is restarted until receiving first relay candidate. if the provided cycle limit is reached, ice candidate collection assumed to be completed. * @property {boolean} [useRelayOnly] Forces the ICE Agent to only use relay candidate by setting the iceTransportPolicy to relay * @property {Object} [pluginMode] plugin mode config {@link fcsSetupConfigParamsPluginMode}. * @property {string} [connectivityInterval=10000] Connectivity check interval time value. If it is 0 connectivity check is diabled. Recommended to use values greater than 10000, due to performance issues. * @property {string} [connectivityLostRetry=false] Connectivity check will retry when the connectivity fails until it succeed on the following default patern 10s, 20s, 40s, 80s, ... 640s, 640s, ... * @property {string} [connectivityRetryStart=10000] Initial time (ms) after the connectity is retried. * @property {string} [connectivityRetryLimit=640000] Maximum time (ms) between retries. * @property {string} [connectivityRetryMultiplier=2] Multiplier that will be applied for the next retry. * @property {string} [websocketInterval=10000] Websocket health check interval. If the websocketInterval parameter value is 0, websocket health check will be disabled. * @property {string} [backgroundWebsocketInterval=60000] Websocket health check interval for mobile when the device is running in the background. * @property {string} [pluginLogLevel="2"] The log level of webrtc plugin * @property {string} [staggeredTimerMin="300"] Minimum value for staggered timer. (Timer used to prevent all devices to reconnect at the same time) * @property {string} [staggeredTimerMax="5000"] Maximum value for staggered timer. * @property {string} [videoContainer] html node in which to inject the video * @property {string} [remoteVideoContainer] html node in which to inject the remote video * @property {string} [localVideoContainer] html node in which to inject the preview of the user camera * @property {string} [iceserver=""] ice server ip address * @property {boolean} [webrtcdtls=false] webrtc dtls status * @property {boolean} [dscpEnabled=false] Enabled experimental DSCP markings on supported platforms (Chrome only). * @property {string} [language="en"] language setting of the plugin * @property {ajaxHook} [ajaxHook] ajax hook to intercept outgoing xhr request to modify url and headers * @property {boolean} [callReplace=false] When enabled, inform Spidr that replaceCall is supported * @property {boolean} [ringingFeedback=false] When enabled, inform Spidr that RingingFeedback is supported * @property {boolean} [trickleIceSupport="none"] Specifies trickle ice support. "none" is default value and trickle ice isn't supported. "half" means half trickle is supported. "full" means full trickle is supported. * @property {string} [cachePrefix=""] Allows the user to specify a unique prefix for keys stored in localStorage. * @property {boolean} [forceDisableMediaOnHold=false] Disables any type of media (e.g. Comfort Noise) from transmitting when call is held locally. * @property {sdpHandler[]} [sdpHandlers=[]] The array of handlers for SDP manipulations. * @property {string} [bundlePolicy=DISABLED] The bundle policy to use for peer connections. Value can be fcs.SDP_CONSTANTS.BUNDLE_POLICY.MAX_COMPAT, fcs.SDP_CONSTANTS.BUNDLE_POLICY.MAX_BUNDLE, fcs.SDP_CONSTANTS.BUNDLE_POLICY.BALANCED or fcs.SDP_CONSTANTS.BUNDLE_POLICY.DISABLED. The DISABLED option means that bundle group lines will be removed from every SDP. * @property {Object} [callConstraints] Custom RTCPeerConnection constraints to use for calls. Will cause errors if malformed. * @property {Object} [callConstraints.chrome] Custom constraints to be used on Google Chrome. * @property {Object} [callConstraints.firefox] Custom constraints to be used on Mozilla Firefox. * @property {Object} [callConstraints.plugin] Custom constraints to be used with the WebRTC Plugin. */ /** * This function is used to set up JSL library * * @name fcs#setup * @function * @param {fcsSetupConfigParams} config configuration parameters * @since 3.0.0 * @example * * fcs.setup( * { * notificationType: fcs.notification.NotificationTypes.WEBSOCKET, * "servers": [{ * "protocol": "https", * "restUrl": "spidrdomain.com", * "restPort": "443", * "websocketProtocol": "wss", * "websocketIP": "spidrdomain.com", * "websocketPort": "443" * }], * callAuditTimer: 30000, * clientControlled : true, * pluginMode: { * mode: 'webrtc', * h264: true, * chrome: { * mode: 'auto' * }, * firefox: { * version: '38+', * mode: 'auto' * } * }, * connectivityInterval: '20000', * "iceserver": [{ * "urls": "turns:turn1.spidrdomain.com:443?transport=tcp", * "credential": "" * }, { * "urls": "turns:turn2.spidrdomain.com:443?transport=tcp", * "credential": "" * }], * webrtcdtls: true, * videoContainer: document.getElementById("defaultVideoContainer") * } * ); * * // example for multiple server * * fcs.setup( * { * notificationType: fcs.notification.NotificationTypes.WEBSOCKET_ONLY, * servers: [{protocol: 'http', * restUrl: '1.1.1.1', * restPort: '8580', * websocketProtocol: 'ws', * websocketIP: '1.1.1.1', * websocketPort: '8578'}, * {protocol: 'http', * restUrl: '1.1.1.1', * restPort: '8580', * websocketProtocol: 'ws', * websocketIP: '1.1.1.1', * websocketPort: '8581'}], * serverRetryNumber: '2', * serverRetryInterval: '3000', * pluginMode: { * mode: 'webrtc', * h264: true, * chrome: { * mode: 'auto' * }, * firefox: { * version: '38+', * mode: 'auto' * } * }, * connectivityInterval: '20000' * websocketInterval: '20000', * iceserver: [{"urls":"stun:206.165.51.69:3478"}, * {"urls":"turn:206.165.51.69:3478", * "credential":"dummyCredential", * "password":"dummyPwd"}] * webrtcdtls: true, * videoContainer: document.getElementById("defaultVideoContainer") * } * ); * * */ this.setup = function (configParams, delayInitMedia) { delayInitMedia = delayInitMedia === undefined ? false : delayInitMedia; var param, i, j, codecsToReplaceDefaultFound, paramFields; for (param in configParams) { if (configParams.hasOwnProperty(param)) { if (param === 'codecsToReplace') { if (typeof _config[param] === 'undefined') { _config[param] = []; } for (i in configParams[param]) { if (configParams[param].hasOwnProperty(i)) { codecsToReplaceDefaultFound = false; for (j in _config[param]) { if (_config[param].hasOwnProperty(j) && _config[param][j].name === configParams[param][i].name) { codecsToReplaceDefaultFound = true; _config[param][j].value = configParams[param][i].value; } } if (!codecsToReplaceDefaultFound) { _config[param].push(configParams[param][i]); } } } } else if (param === 'pluginMode') { paramFields = (0, _keys2.default)(configParams[param]); for (i in paramFields) { if (paramFields.hasOwnProperty(i)) { _config[param][paramFields[i]] = configParams[param][paramFields[i]]; } } } else { _config[param] = configParams[param]; } } } // This function checks the expiration date. // It should not be a very small value. // Otherwise, the api enters the loop.There is no upper limit. var handleValidSubscriptionExpiryTimerValue = function handleValidSubscriptionExpiryTimerValue(time) { if (time && parseInt(time) >= MIN_SUBSCRIPTION_EXPIRY_VALUE) { return time; } else { return DEFAULT_SUBSCRIPTION_EXPIRY_VALUE; } }; _config.trickleIceSupport = (0, _values2.default)(_constants2.default.TRICKLE).indexOf(_config.trickleIceSupport) !== -1 ? _config.trickleIceSupport : 'none'; _config.expires = handleValidSubscriptionExpiryTimerValue(configParams ? configParams.expires : undefined); if (!delayInitMedia) { _globalBroadcaster.publish(_constants2.default.EVENT.FCS_SETUP_COMPLETED, _config); } }; /** * This is an object of constants for advanced use only. Use these constants in your SDP handlers. See fcs.setup() to see how to set SDP handlers. * * @name fcs#SDP_CONSTANTS * @property {Object} SDP_CONSTANTS The object of constants for use in SDP handlers. * @property {Object} SDP_CONSTANTS.TYPE The type of SDP. * @property {string} SDP_CONSTANTS.TYPE.OFFER Offer sdp type. * @property {string} SDP_CONSTANTS.TYPE.ANSWER Answer sdp type. * @property {string} SDP_CONSTANTS.TYPE.PRANSWER Pranswer sdp type. * @property {Object} SDP_CONSTANTS.OPERATION The operation for which the sdp will be used. * @property {string} SDP_CONSTANTS.OPERATION.START_CALL A call start operation. * @property {string} SDP_CONSTANTS.OPERATION.ANSWER_CALL A call answer operation. * @property {string} SDP_CONSTANTS.OPERATION.HOLD A hold operation. * @property {string} SDP_CONSTANTS.OPERATION.UPDATE An update operation. * @property {string} SDP_CONSTANTS.OPERATION.REOFFER A reoffer operation. * @property {string} SDP_CONSTANTS.OPERATION.RESPOND A respond operation. * @property {string} SDP_CONSTANTS.OPERATION.DATA_CHANNEL A data channel operation. * @property {Object} SDP_CONSTANTS.STEP The step in the process that the SDP is at. * @property {string} SDP_CONSTANTS.STEP.PRE_SET_LOCAL The local SDP is about to be set. * @property {string} SDP_CONSTANTS.STEP.PRE_SET_REMOTE The remote SDP is about to be set. * @property {string} SDP_CONSTANTS.STEP.PRE_SEND_LOCAL The local SDP is about to be sent to the other peer. */ this.SDP_CONSTANTS = _constants2.default.WEBRTC.SDP; /** * Plugin required event will be fired in case that plug-in not found or version is outdated * * @name fcs#onPluginRequired * @event * @param {fcs.call#MediaErrors} event media initialization error * @since 3.0.0 * @example * * fcs.onPluginRequired = function(error) { * switch (error) { * case fcs.call.MediaErrors.WRONG_VERSION: * // Media Plugin Version Not Supported * // Download plugin * break; * case fcs.call.MediaErrors.NEW_VERSION_WARNING: * // New Media Version Available Wanrning * break; * case fcs.call.MediaErrors.NOT_INITIALIZED: * // Media couldn't be initialized * break; * case fcs.call.MediaErrors.NOT_FOUND: * // Plugin couldn't be found! * // Download plugin * break; * } * } */ /** * This function sets version of plugin * * @name fcs#setPluginVersion * @function * @param {string} version * @since 3.0.0 * @example * * fcs.setPluginVersion(version); */ this.setPluginVersion = function (version) { pluginVer = version; }; /** * This function returns version of plugin * * @name fcs#getPluginVersion * @function * @returns {String} Version of Current Plugin * @since 3.0.0 * @example * * fcs.getPluginVersion(); */ this.getPluginVersion = function () { return pluginVer; }; /** * This function returns assigned services of authenticated user. * * @name fcs#getServices * @function * @returns {object} The assigned services of authenticated user * @since 3.0.0 * @example * * fcs.getServices(); */ this.getServices = function () { return services; }; /** * This function assigns determined services to current user * * @name fcs#setServices * @function * @param {array} serviceParam The list of assigned services for the user * @since 3.0.0 * @example * fcs.setServices(["CallControl", "RestfulClient"]); */ this.setServices = function (serviceParam) { var i; // for each element in serviceParam array, we create the service with value "true" in "services" object if (serviceParam) { services = {}; for (i = 0; i < serviceParam.length; i++) { switch (serviceParam[i]) { case 'CallDisplay': services.callDisplay = true; break; case 'CallDisposition': services.callDisposition = true; break; case 'RestfulClient': services.restfulClient = true; break; case 'call': services.callControl = true; services.remoteCallControl = false; break; case 'CallControl': services.callControl = true; services.remoteCallControl = false; break; case 'RCC': services.callControl = false; services.remoteCallControl = true; break; case 'CallMe': services.callMe = true; break; case 'Directory': services.directory = true; break; case 'ClickToCall': services.clickToCall = true; break; case 'Presence': services.presence = true; break; case 'AddressBook': services.contacts = true; break; case 'CallLog': services.history = true; break; case 'Custom': services.custom = true; break; case 'IM': services.IM = true; break; case 'Route': services.routes = true; break; case 'DataChannel': services.dataChannel = true; break; default: break; } } } }; /** * Returns network connectivity status. * * @name fcs#isConnected * @function * * @returns {Boolean}, true if connection is up otherwise false. */ this.isConnected = function () { return connected; }; this.setConnected = function (connectionStatus) { connected = connectionStatus === true ? true : false; }; } /***/ }), /***/ "../fcs/src/js/errors.js": /*!*******************************!*\ !*** ../fcs/src/js/errors.js ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { NETWORK: 1, AUTH: 2, STATE: 3, PRIV: 4, UNKNOWN: 9, LOGIN_LIMIT_CLIENT: 10, INCORRECT_LOGIN_PASS: 11, INVALID_LOGIN: 12, // smartoffice2.0 specific FORCE_LOGOUT_ERROR: 13, // smartoffice2.0 specific LOGIN_LIMIT_TABLET: 14, TOKEN_NOT_FOUND: 15, SESSION_EXPIRED: 16, VIDEO_SESSION_NOT_AVAILABLE: 17, PENDING_REQUEST: 18, NOT_ALLOWED_SERVICE: 19, NOT_ALLOWED_METHOD: 20, NOT_ALLOWED_INSTANCE: 21, INVALID_PARAMETER: 22, CONNECTION_ISSUE: 23, MEDIA_NOT_FOUND: 24, MEDIA_NOT_ALLOWED: 25, CALL_FAILED: 26, CALL_ENDED: 27, MAXIMUM_ENTRIES: 28, ENTRY_ALREADY_EXISTS: 29, SERVICE_NOT_AUTHORIZED: 30, DB_EXCEPTION: 31, INSUFFICIENT_INFO: 32, NOT_FOUND: 33, INTERNAL_SERVER_ERROR: 34, SERVICE_UNAVAILABLE: 35, SESSION_NOT_FOUND: 36, CANNOT_SUBSCRIBE: 37, MEDIA_REQUIRED: 38 }; /***/ }), /***/ "../fcs/src/js/globalbroadcaster/globalBroadcaster.js": /*!************************************************************!*\ !*** ../fcs/src/js/globalbroadcaster/globalBroadcaster.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GlobalBroadcaster = GlobalBroadcaster; function GlobalBroadcaster() { var MAX_PRIORITY = 10, MIN_PRIORITY = 1, topics = {}, subUid = -1; function unsubscribeFromTopic(token) { var m, i, j; for (m in topics) { if (topics[m] && topics.hasOwnProperty(m)) { j = topics[m].length; for (i = 0; i < j; i++) { if (topics[m][i].token === token) { topics[m].splice(i, 1); return token; } } } } return false; } function subscribeToTopic(topic, func, priority, temporary) { var token, prio = MAX_PRIORITY, temp = false; if (typeof topic !== 'string') { throw new Error('First parameter must be a string topic name.'); } if (typeof func !== 'function') { throw new Error('Second parameter must be a function.'); } if (typeof priority !== 'undefined') { if (typeof priority !== 'number') { throw new Error('Priority must be a number.'); } else { if (priority > MAX_PRIORITY || priority < MIN_PRIORITY) { throw new Error('Priority must be between 1-10.'); } else { prio = priority; } } } if (temporary === true) { temp = temporary; } if (!topics[topic]) { topics[topic] = []; } token = (++subUid).toString(); topics[topic].push({ token: token, prio: prio, func: func, temp: temp }); topics[topic].sort(function (a, b) { return parseFloat(b.prio) - parseFloat(a.prio); }); return token; } function publishTopic() { var subscribers, len, _args, _topic; if (arguments.length === 0) { throw new Error('First parameter must be a string topic name.'); } _args = Array.prototype.slice.call(arguments); _topic = _args.shift(); subscribers = topics[_topic]; len = subscribers ? subscribers.length : 0; while (len--) { subscribers[len].func.apply(null, _args); if (subscribers[len].temp) { unsubscribeFromTopic(subscribers[len].token); } } } /* * * Publish events of interest * with a specific topic name and arguments * such as the data to pass along * * @param {string} topic - Topic name. * @param {...*} [args] - arguments. * * @returns {undefined} */ this.publish = publishTopic; /* * * Subscribe to events of interest * with a specific topic name and a * callback function, to be executed * when the topic/event is observed. * Default priority 10. * Priority must be between 1-10. * Functions with lower priority * will be executed first. * * @param {string} topic - Topic name. * @param {type} func - function to be executed when the topic/event is observed * @param {number} [priority] - function with higher priority will be executed first * @param {boolean} [temporary] - if set to true, subscriber will unsubcribe automatically after first execution. * * @returns {string} token - reference to subscription */ this.subscribe = subscribeToTopic; /* * * Unsubscribe from a specific * topic, based on a tokenized reference * to the subscription * * @param {string} token - reference to subscription * * @returns {false|string} - returns token if successfull, * otherwise returns false. */ this.unsubscribe = unsubscribeFromTopic; } /***/ }), /***/ "../fcs/src/js/globalbroadcaster/module.js": /*!*************************************************!*\ !*** ../fcs/src/js/globalbroadcaster/module.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _globalBroadcaster = __webpack_require__(/*! ./globalBroadcaster */ "../fcs/src/js/globalbroadcaster/globalBroadcaster.js"); exports.default = { GlobalBroadcaster: function GlobalBroadcaster() { return new _globalBroadcaster.GlobalBroadcaster(); } }; /***/ }), /***/ "../fcs/src/js/http/http.js": /*!**********************************!*\ !*** ../fcs/src/js/http/http.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HttpImpl = HttpImpl; var _constants = __webpack_require__(/*! ../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); var _base = __webpack_require__(/*! ../../lib/base64 */ "../fcs/src/lib/base64.js"); var _errors = __webpack_require__(/*! ../errors */ "../fcs/src/js/errors.js"); var _errors2 = _interopRequireDefault(_errors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function HttpImpl(_ref) { var _xhr = _ref.XHR, _globalBroadcaster = _ref.GlobalBroadcaster, _core = _ref.Core, _config = _ref.Config; var REQUEST_TYPE_PUT = 'PUT', REQUEST_TYPE_POST = 'POST', REQUEST_TYPE_GET = 'GET', REQUEST_TYPE_DELETE = 'DELETE', username, password, session, authname; function onSubscriptionStarted(data) { session = data.session; } // In order to delete previous session function onSubscriptionEnded() { session = null; } function onTokenAuth(data) { username = data.username; } function onBasicAuth(data) { username = data.username; password = data.password; authname = data.authname; } function manipulateHeader(header) { if (!header) { header = {}; } if (!header.Accept) { header.Accept = 'application/json'; } if (!header['Content-Type']) { header['Content-Type'] = 'application/json'; } if (!_core.getKandyUAT()) { //Check whether auth or basic auth if (session) { header['x-session'] = session; delete header.Authorization; } else { if (authname && password) { header.Authorization = 'basic ' + (0, _base.base64_encode)(authname + ':' + password); } else if (username && password) { header.Authorization = 'basic ' + (0, _base.base64_encode)(username + ':' + password); } delete header['x-session']; } } return header; } function sendRequest(method, callParams, successHandler, errorHandler, successParser, errorParser, responseType, header) { var kandyUAT = _core.getKandyUAT(); var failureHandler = function failureHandler(statusCode) { if (statusCode === _errors2.default.TOKEN_NOT_FOUND) { _globalBroadcaster.publish(_constants2.default.EVENT.TOKEN_NOT_FOUND); session = null; } else if (statusCode === _errors2.default.SESSION_EXPIRED) { _globalBroadcaster.publish(_constants2.default.EVENT.SESSION_EXPIRED); session = null; } if (errorHandler && typeof errorHandler === 'function') { errorHandler(statusCode); } }; if (kandyUAT) { if (callParams.url.indexOf('?') === -1) { callParams.url += '?key=' + kandyUAT; } else { callParams.url += '&key=' + kandyUAT; } } return _xhr.call(method, callParams, successHandler, failureHandler, successParser, errorParser, responseType, header); } function sendPostRequestTokenAuth(callParams, successHandler, errorHandler, successParser, errorParser, responseType, header, token) { if (!header) { header = {}; } if (!header.Accept) { header.Accept = 'application/json'; } if (!header['Content-Type']) { header['Content-Type'] = 'application/json'; } //Check whether auth or basic auth if (header['x-session']) { delete header['x-session']; } if (header.Authorization) { delete header.Authorization; } if (!header['x-token']) { header['x-token'] = token; } return sendRequest(REQUEST_TYPE_POST, callParams, successHandler, errorHandler, successParser, errorParser, responseType, header); } this.call = function (method, callParams, successHandler, errorHandler, successParser, errorParser, responseType, header) { header = manipulateHeader(header); return sendRequest(method, callParams, successHandler, errorHandler, successParser, errorParser, responseType, header); }; this.sendPostRequest = function (callParams, successHandler, errorHandler, successParser, errorParser, responseType, header, token) { if (token) { return sendPostRequestTokenAuth(callParams, successHandler, errorHandler, successParser, errorParser, responseType, header, token); } else { header = manipulateHeader(header); return sendRequest(REQUEST_TYPE_POST, callParams, successHandler, errorHandler, successParser, errorParser, responseType, header); } }; this.sendGetRequest = function (callParams, successHandler, errorHandler, successParser, errorParser, responseType, header) { header = manipulateHeader(header); return sendRequest(REQUEST_TYPE_GET, callParams, successHandler, errorHandler, successParser, errorParser, responseType, header); }; this.sendDeleteRequest = function (callParams, successHandler, errorHandler, successParser, errorParser, responseType, header) { header = manipulateHeader(header); return sendRequest(REQUEST_TYPE_DELETE, callParams, successHandler, errorHandler, successParser, errorParser, responseType, header); }; this.sendPutRequest = function (callParams, successHandler, errorHandler, successParser, errorParser, responseType, header) { header = manipulateHeader(header); return sendRequest(REQUEST_TYPE_PUT, callParams, successHandler, errorHandler, successParser, errorParser, responseType, header); }; this.getUrl = function () { var url = ''; if (!_config.protocol || !_config.restUrl || !_config.restPort) { return url; } return url + _config.protocol + '://' + _config.restUrl + ':' + _config.restPort; }; this.getWAMUrl = function (version, url, authNeeded) { if (authNeeded === false) { // Authentcation is not needed. return this.getUrl() + '/rest/version/' + (version ? version : 'latest') + url; } else { // Authentcation is needed for the rest request if (_core.notification || _config.anonymous) { return this.getUrl() + '/rest/version/' + (version ? version : 'latest') + (_config.anonymous ? '/anonymous/' : '/user/') + _core.getUser() + url; } else { return this.getUrl() + '/rest/version/' + (version ? version : 'latest') + '/user/' + _core.getUser() + url; } } }; _globalBroadcaster.subscribe(_constants2.default.EVENT.TOKEN_AUTH_STARTED, onTokenAuth, 9); _globalBroadcaster.subscribe(_constants2.default.EVENT.BASIC_AUTH_STARTED, onBasicAuth, 10); _globalBroadcaster.subscribe(_constants2.default.EVENT.DEVICE_SUBSCRIPTION_STARTED, onSubscriptionStarted); _globalBroadcaster.subscribe(_constants2.default.EVENT.DEVICE_SUBSCRIPTION_ENDED, onSubscriptionEnded); //@{test-methods} this.manipulateHeader = manipulateHeader; this.setSession = function (value) { session = value; }; this.setUsernamePassword = function (user, pass, auth) { username = user; password = pass; authname = auth; }; //@{test-methods} } /***/ }), /***/ "../fcs/src/js/http/module.js": /*!************************************!*\ !*** ../fcs/src/js/http/module.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _http = __webpack_require__(/*! ./http */ "../fcs/src/js/http/http.js"); var _xhr = __webpack_require__(/*! ./xhr */ "../fcs/src/js/http/xhr.js"); exports.default = { XHR: function XHR(container) { return new _xhr.XHRImpl(container); }, Http: function Http(container) { return new _http.HttpImpl(container); } }; /***/ }), /***/ "../fcs/src/js/http/xhr.js": /*!*********************************!*\ !*** ../fcs/src/js/http/xhr.js ***! \*********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.XHRImpl = XHRImpl; var _errors = __webpack_require__(/*! ../errors */ "../fcs/src/js/errors.js"); var _errors2 = _interopRequireDefault(_errors); var _utils2 = __webpack_require__(/*! ../utils */ "../fcs/src/js/utils/index.js"); var _constants = __webpack_require__(/*! ../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function XHRImpl(_ref) { var _core = _ref.Core, _globalBroadcaster = _ref.GlobalBroadcaster, _logManager = _ref.LogManager, _config = _ref.Config, _utils = _ref.Utils, _challenger = _ref.ChallengeManager; var DEFAULT_LONGPOLLING_TOLERANCE = 30000, DEFAULT_AJAX_TIMEOUT = 40000, XHR_READY_STATE = { REQUEST_NOT_INITIALIZED: 0, REQUEST_DONE: 4 }, self = this; function getLogger() { return _logManager.getLogger('jQrestful'); } function composeAjaxRequestResponseLog(context, xhr, errorThrown, data) { var responseLog = context; if (data) { responseLog.data = data; } if (errorThrown) { responseLog.errorThrown = errorThrown; } if (xhr) { responseLog.status = xhr.status; responseLog.statusText = xhr.statusText; responseLog.responseText = xhr.responseText; responseLog.readyState = xhr.readyState; } return responseLog; } function parseError(x, e) { var returnResult, statusCode; getLogger().error('parseError:\'' + e + '\' Status:\'' + x.status + '\' ResponseText:\'' + x.responseText + '\''); if (x.responseText && x.responseText.search('statusCode') !== -1) { if (JSON.parse(x.responseText).subscribeResponse !== undefined) { statusCode = JSON.parse(x.responseText).subscribeResponse.statusCode; } else if (JSON.parse(x.responseText).authorizationResponse !== undefined) { statusCode = JSON.parse(x.responseText).authorizationResponse.statusCode; } } statusCode = statusCode ? statusCode : x.status; switch (statusCode) { case 401: returnResult = _errors2.default.AUTH; break; case 403: returnResult = _errors2.default.INCORRECT_LOGIN_PASS; break; case 19: returnResult = _errors2.default.LOGIN_LIMIT_CLIENT; break; case 20: returnResult = _errors2.default.LOGIN_LIMIT_TABLET; break; case 39: returnResult = _errors2.default.SESSION_NOT_FOUND; break; case 44: returnResult = _errors2.default.FORCE_LOGOUT_ERROR; break; case 46: returnResult = _errors2.default.TOKEN_NOT_FOUND; break; case 47: returnResult = _errors2.default.SESSION_EXPIRED; break; default: returnResult = _errors2.default.NETWORK; } return returnResult; } // TODO tolga: remove parseError when all of the responseTypes are added function parseErrorStatusCode(x, e, responseType) { getLogger().error('parseErrorStatusCode:\'' + e + '\' Status:\'' + x.status + '\' ResponseText:\'' + x.responseText + '\''); if (x.responseText && x.responseText.search('statusCode') !== -1 && JSON.parse(x.responseText)[responseType] !== undefined) { return JSON.parse(x.responseText)[responseType].statusCode; } return x.status === 401 || x.status === 403 ? x.status : 400; } /* * @ignore */ self.call = function (method, callParams, successHandler, errorHandler, successParser, errorParser, responseType, headers) { var data, timeout = DEFAULT_AJAX_TIMEOUT, url = callParams.url, origHeaders = headers, urlWithoutRestVersion = url.split('/rest/version/')[1], resourceString, logger = getLogger(), xhr, queryString, finalHeaders, headerKey, responseLogContext, handleSuccess, handleError, isSuccess, modValues; if (callParams && callParams.data) { data = callParams.data; } if (_config.polling) { timeout = _config.polling * 1000; if (_config.longpollingTolerans) { timeout = timeout + _config.longpollingTolerans; } else { timeout = timeout + DEFAULT_LONGPOLLING_TOLERANCE; } } // do not log isAlive requests if (urlWithoutRestVersion && urlWithoutRestVersion.indexOf('isAlive') === -1) { // extracting rest resource from url. // ".../rest/version/<ver>/<user/anonymous>/<userName>/restResource/..." resourceString = urlWithoutRestVersion.split('/')[3]; if (!resourceString) { // rest resource string not found, get last string in the url resourceString = url.substring(url.lastIndexOf('/') + 1, url.length); } // remove "?" if exists resourceString = resourceString.split('?')[0]; if (data && !data.imRequest) { logger.info('Send ajax request: ' + resourceString, data); } else { logger.info('Send ajax request: ' + resourceString); } } if (method === 'GET') { // Take the data parameters and append them to the URL. queryString = (0, _utils2.serialize)(data); if (queryString.length > 0) { if (url.indexOf('?') === -1) { url += '?' + queryString; } else { url += '&' + queryString; } } // Remove data so that we don't add it to the body. data = null; } xhr = new XMLHttpRequest(); // TODO: Kadir Goktas // listeners below are functional expect for IE9. // we can replace xhr.onstatechange handler // accordingly, once IE9 is deprecated. xhr.onload = function () { handleSuccess(xhr); }; xhr.onabort = function () { logger.trace('Ajax request aborted internally. not calling failure callback'); }; xhr.onerror = function () { logger.error('Ajax request error! Handle the error'); handleError(xhr); }; // ajax hook to modify url and headers if (_config.ajaxHook) { modValues = _utils.callFunctionIfExist(_config.ajaxHook, xhr, window, { type: method, url: url, headers: headers, data: data }); if (modValues) { url = modValues.url ? modValues.url : url; headers = modValues.headers ? modValues.headers : headers; } } xhr.open(method, url); xhr.withCredentials = _config.cors ? true : false; xhr.timeout = timeout; finalHeaders = { // Old implementation used jQuery without changing content type. Doing the same here for // backwards compatibility. 'Content-Type': 'application/x-www-form-urlencoded', // JQuery always adds this header by default. Adding here for backwards compatibility. 'X-Requested-With': 'XMLHttpRequest' }; finalHeaders = (0, _utils2.extend)(finalHeaders, headers); // Set the headers. for (headerKey in finalHeaders) { if (finalHeaders.hasOwnProperty(headerKey)) { xhr.setRequestHeader(headerKey, finalHeaders[headerKey]); } } if (typeof data !== 'string') { data = (0, _stringify2.default)(data); } xhr.send(data); // Used for logging information, responseLogContext = { type: method, url: url, dataType: 'json', async: true, jsonp: false, crossDomain: _config.cors ? true : false, timeout: timeout }; function checkIE9HackForAbortedAjaxRequest(xhr) { // IE9 hack: identifying internally aborted ajax requests. try { isSuccess = xhr.status >= 200 && xhr.status < 300 || xhr.status === 304; } catch (err) { // when an ajax request is aborted by javascript, accessing xhr.status will throw // exception. "c00c023f" is the exact code that IE9 throws. // but all exceptions are considered as same. if (err instanceof Error) { if (err.description === 'Could not complete the operation due to error c00c023f.') { logger.trace('Ajax request aborted internally. not calling failure callback'); } } return -1; } return isSuccess; } handleSuccess = function handleSuccess(xhr) { if (xhr.readyState === XHR_READY_STATE.REQUEST_DONE) { isSuccess = checkIE9HackForAbortedAjaxRequest(xhr); if (isSuccess === -1) { return; } // onload hack: need to handle both success and failure in xhr load event if (!isSuccess) { handleError(xhr); return; } var val = {}; try { // Make sure that the response isn't empty before parsing. Empty is considered // an empty object. if (typeof xhr.responseText === 'string' && xhr.responseText.length) { val = JSON.parse(xhr.responseText); } // do not log success response for isAlive requests if (typeof xhr.responseURL === 'string' && xhr.responseURL.indexOf('isAlive') === -1) { logger.info('ajax success: ' + xhr.status + ' ' + xhr.statusText, composeAjaxRequestResponseLog(responseLogContext, xhr, undefined, val)); } } catch (e) { if (e instanceof SyntaxError) { logger.error('Failed to parse json ajax response into object:' + xhr.responseText, composeAjaxRequestResponseLog(responseLogContext, xhr, undefined, val)); } else { logger.error('Unknown error:' + xhr.status + ' ' + xhr.statusText, composeAjaxRequestResponseLog(responseLogContext, xhr, undefined, val)); } handleError(xhr); return; } if (successParser && typeof successParser === 'function') { val = successParser(val); } if (successHandler && typeof successHandler === 'function') { successHandler(val); } } }; handleError = function handleError(xhr) { // TODO: Error Thrown logger.error('ajax error: ' + xhr.status + ' ' + xhr.statusText, composeAjaxRequestResponseLog(responseLogContext, xhr, xhr.statusText)); var reportError = function reportError() { if (xhr.status === 410) { logger.error('410 Gone received'); _utils.callFunctionIfExist(_core.notification.onGoneReceived); return; } if (xhr.readyState === XHR_READY_STATE.REQUEST_NOT_INITIALIZED) { _globalBroadcaster.publish(_constants2.default.EVENT.XHR_REQUEST_NOT_INITIALIZED); logger.debug('Ajax request cannot be sent, this is a connection problem.'); } if (errorHandler && typeof errorHandler === 'function') { //TODO after unit tests moved to addressbook class, responseType parameter should be removed if (responseType === 'addressBookResponse') { errorHandler(parseErrorStatusCode(xhr, xhr.statusText, responseType)); } else { if (errorParser && typeof errorParser === 'function') { errorHandler(errorParser(xhr, xhr.statusText)); } else { errorHandler(parseError(xhr, xhr.statusText)); } } } else { logger.trace('Error handler is not defined or not a function'); } }; if (xhr.status === 403 && _core.getKandyUAT() && _config.enableAuthChallenge) { _challenger.challenge().then(function (newUAT) { // Replace the key parameter with the new user access token. callParams.url = callParams.url.replace(/([\?\&]key=)uat[0-9a-f]{32}/gi, '$1' + newUAT); self.call(method, callParams, successHandler, errorHandler, successParser, errorParser, responseType, origHeaders); }).catch(reportError); } else { reportError(); } }; if (xhr.readyState === 4) { // If the request already completed, just fire the callback asynchronously setTimeout(function () { handleSuccess(xhr); }); } else { // sucess and fail scenarios are handled with "load" and "error" event listeners // onreadystatechange is only need for IE9 hack xhr.onreadystatechange = function () { if (checkIE9HackForAbortedAjaxRequest(xhr) === -1) { return; } }; } return xhr; }; } /***/ }), /***/ "../fcs/src/js/locale.js": /*!*******************************!*\ !*** ../fcs/src/js/locale.js ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LocaleService = LocaleService; function LocaleService(_ref) { var _server = _ref.Http, _utils = _ref.Utils; this.getUserLocale = function (onSuccess, onFailure) { _server.sendGetRequest({ 'url': _server.getWAMUrl(1, '/localization', false) }, function (data) { _utils.callFunctionIfExist(onSuccess, data); }, onFailure); }; } /***/ }), /***/ "../fcs/src/js/logmanager/logManager.js": /*!**********************************************!*\ !*** ../fcs/src/js/logmanager/logManager.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LogManagerImpl = LogManagerImpl; /** * * LogManager provides javascript logging framework.<br /> * * <br />The logging level strategy is as follows:<br /> * * <br />DEBUG: Used for development and detailed debugging logs<br /> * INFO: Messages that provide information about the high level flow<br /> * through. Contain basic information about the actions being performed<br /> * by the user and/or the system<br /> * WARN: Things that shouldn't happen but don't have any immediate effect, and should be flagged<br /> * ERROR: Errors and Exceptions<br /> * FATAL: Anything that causes the system to enter into an unstable and unusable state<br /> * * * @name logManager * @namespace * @memberOf fcs * * @version @{spidr.jsl.version} * @since 3.0.0 * */ function LogManagerImpl(_ref) { var _core = _ref.Core; var loggers = {}, enabled = false, Level = { OFF: 'OFF', FATAL: 'FATAL', ERROR: 'ERROR', WARN: 'WARN', INFO: 'INFO', DEBUG: 'DEBUG', TRACE: 'TRACE', ALL: 'ALL' }, _logHandler = null; /** * * Log object. * * @typedef {Object} logObject * @readonly * @since 3.0.0 * * @property {String} user - the user registered to fcs library. * @property {String} timestamp - the time stamp of the log. * @property {String} logger - the name of the logger. * @property {String} level - the level of message. * @property {String} message - the message string. * @property {Object} args - the arguments. * */ /** * * Log handler function. * * @typedef {function} logHandler * @param {string} loggerName Name of the logger * @param {string} level Level of message * @param {logObject} logObject Log object * @since 3.0.0 */ /** * * Initializes logging using user-provided log handler. * @name fcs.logManager#initLogging * @since 3.0.0 * @function * * @param {logHandler} logHandler, Function that will receive log entries * @param {boolean} enableDebug, Flag defining whether debugging should be enabled or not * @returns {undefined} * * @example * * function jslLogHandler(loggerName, level, logObject) { * var LOG_LEVEL = fcs.logManager.Level, * msg = logObject.timestamp + " - " + loggerName + " - " + level + " - " + logObject.message; * * switch(level) { * case LOG_LEVEL.DEBUG: * window.console.debug(msg, logObject.args); * break; * case LOG_LEVEL.INFO: * window.console.info(msg, logObject.args); * break; * case LOG_LEVEL.ERROR: * window.console.error(msg, logObject.args); * break; * default: * window.console.log(msg, logObject.args); * } * } * * fcs.logManager.initLogging(jslLogHandler, true); */ this.initLogging = function (logHandler, enableDebug) { if (!logHandler || typeof logHandler !== 'function') { return false; } _logHandler = logHandler; enabled = enableDebug === true ? true : false; return true; }; /** * * Enumerates all possible log levels. * @name fcs.logManager#Level * @enum {string} * @since 3.0.0 * @readonly * @property {string} [OFF=OFF] string representation of the Off level. * @property {string} [FATAL=FATAL] string representation of the Fatal level. * @property {string} [ERROR=ERROR] string representation of the Error level. * @property {string} [WARN=WARN] string representation of the Warn level. * @property {string} [INFO=INFO] string representation of the Info level. * @property {string} [DEBUG=DEBUG] string representation of the Debug level. * @property {string} [TRACE=TRACE] string representation of the Trace level. * @property {string} [ALL=ALL] string representation of the All level. */ this.Level = Level; /** * Returns true or false depending on whether logging is enabled. * * @name fcs.logManager#isEnabled * @function * * @returns {Boolean} * @since 3.0.0 * * @example * * fcs.logManager.isEnabled(); * */ this.isEnabled = function () { return enabled; }; function Logger(loggerName) { var name = loggerName; this.getName = function () { return name; }; function log(level, message, argument) { if (enabled) { var logObject = {}; logObject.user = _core.getUser(); logObject.timestamp = new Date().getTime(); logObject.logger = name; logObject.level = level; logObject.message = message; logObject.args = argument; if (_logHandler) { try { _logHandler(logObject.logger, logObject.level, logObject); } catch (e) { return undefined; } } } return false; } this.trace = function trace(msg, argument) { return log(Level.TRACE, msg, argument); }; this.debug = function debug(msg, argument) { return log(Level.DEBUG, msg, argument); }; this.info = function info(msg, argument) { return log(Level.INFO, msg, argument); }; this.warn = function warn(msg, argument) { return log(Level.WARN, msg, argument); }; this.error = function error(msg, argument) { return log(Level.ERROR, msg, argument); }; this.fatal = function fatal(msg, argument) { return log(Level.FATAL, msg, argument); }; } this.getLogger = function (loggerName) { var logger, _loggerName; _loggerName = loggerName ? loggerName.trim().length !== 0 ? loggerName : 'Default' : 'Default'; if (loggers[_loggerName]) { logger = loggers[_loggerName]; } else { logger = new Logger(_loggerName); loggers[logger.getName()] = logger; } return logger; }; } /***/ }), /***/ "../fcs/src/js/module.js": /*!*******************************!*\ !*** ../fcs/src/js/module.js ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _logManager = __webpack_require__(/*! ./logmanager/logManager */ "../fcs/src/js/logmanager/logManager.js"); var _utils = __webpack_require__(/*! ./utils */ "../fcs/src/js/utils/index.js"); var _config = __webpack_require__(/*! ./config */ "../fcs/src/js/config.js"); var _cache = __webpack_require__(/*! ./cache */ "../fcs/src/js/cache.js"); var _sdpparser = __webpack_require__(/*! ./sdpparser */ "../fcs/src/js/sdpparser/index.js"); var _challenge = __webpack_require__(/*! ./challenge */ "../fcs/src/js/challenge.js"); var _core = __webpack_require__(/*! ./core */ "../fcs/src/js/core.js"); var _locale = __webpack_require__(/*! ./locale */ "../fcs/src/js/locale.js"); var _module = __webpack_require__(/*! ./http/module */ "../fcs/src/js/http/module.js"); var _module2 = _interopRequireDefault(_module); var _module3 = __webpack_require__(/*! ./globalbroadcaster/module */ "../fcs/src/js/globalbroadcaster/module.js"); var _module4 = _interopRequireDefault(_module3); var _module5 = __webpack_require__(/*! ./turncredentials/module */ "../fcs/src/js/turncredentials/module.js"); var _module6 = _interopRequireDefault(_module5); var _module7 = __webpack_require__(/*! ./sdp/module */ "../fcs/src/js/sdp/module.js"); var _module8 = _interopRequireDefault(_module7); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _extends3.default)({}, _module2.default, _module4.default, _module6.default, _module8.default, { Config: function Config() { return (0, _config.Config)(); }, LogManager: function LogManager(container) { return new _logManager.LogManagerImpl(container); }, Utils: function Utils(container) { return new _utils.Utils(container); }, Cache: function Cache(container) { return new _cache.Cache(container); }, SdpParser: function SdpParser(container) { return new _sdpparser.SdpParserImpl(container); }, LocaleService: function LocaleService(container) { return new _locale.LocaleService(container); }, ChallengeManager: _challenge.ChallengeManagerFactory, Core: function Core(container) { return new _core.CoreImpl(container); }, NotificationCallbacks: function NotificationCallbacks() { return {}; }, // Some globals Navigator: function Navigator() { return navigator; }, Global: function Global() { return window; } }); /***/ }), /***/ "../fcs/src/js/sdp/bundleHandler.js": /*!******************************************!*\ !*** ../fcs/src/js/sdp/bundleHandler.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createBundleHandler; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _constants = __webpack_require__(/*! ../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Our ice candidate timeout logic does not support bundling. There are cases // where we should be interupting ice candidate collection but restart the // timeout instead because the vide mline does not have any candidates. In a // case where the browser is bundling, you would expect that there wouldn't // be any candidates in the video mline. Removing the bundle line from the SDP // ensures that we never bundle candidates. This shouldn't be necessary when we // support trickle ICE since you wouldn't expect the SDP to have all of its // candidates up front anyways. function createBundleHandler(getConfig) { return function bundleHandler(_ref) { var next = _ref.next, currentSdp = _ref.currentSdp; if (getConfig().bundlePolicy !== _constants2.default.WEBRTC.SDP.BUNDLE_POLICY.DISABLED) { return next(currentSdp); } var newSdp = (0, _fp.cloneDeep)(currentSdp); delete newSdp.groups; return next(newSdp); }; } /***/ }), /***/ "../fcs/src/js/sdp/codecRemover.js": /*!*****************************************!*\ !*** ../fcs/src/js/sdp/codecRemover.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createCodecRemover; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); /** * returns a function with params object * @param {Array} An array of strings or objects representing the desired codecs to be removed, * can be passed in as a string or as objects with the following signature: * [{ * name: 'codecname', * fmtpParams: 'specific ftmp parameter target' * }] * @return {Function} [description] * * INSTRUCTIONS FOR EXPOSING FUNCTION TO CPAAS VERSION OF THE SDK: * the following code will need to be added to the appropriate index files (ie: kandy.cpaas.js) * this will expose the createCodecRemover function in the browser import createCodecRemover from '../../fcs/src/js/sdp/codecRemover'; kandy.sdpHandlers = { createCodecRemover }; module.exports = kandy; * INSTRUCTIONS USING RUNNING FUNCTION ONCE EXPOSED * From the browser Devtools run the following: * const codecRemover = createKandy.sdpHandlers.createCodecRemover(['VP8', 'VP9']) * const newSdp = codecRemover(<SDP Object>); // the incoming SDP object * console.log(newSdp) */ function createCodecRemover(config) { if (!config) { config = []; } // We allow the user to pass in a config of objects or strings, so here we format the strings into objects for uniformity. config = config.map(function (item) { return typeof item === 'string' ? { name: item } : item; }); return function (params) { var newSdp = (0, _fp.cloneDeep)(params.currentSdp); // This is an array of strings representing codec names we want to remove. var codecStringsToRemove = config.map(function (codec) { return codec.name; }); newSdp.media.forEach(function (media) { // This is an array of just the codes (codec payloads) that we FOR SURE want to remove. var finalRemoveList = []; // This is an array of RTP objects who have codecs that are the same as strings passed in via config. var filteredRtp = []; // If the current rtp.codec is in the codecStringsToRemove list, add the rtp to filteredRtp filteredRtp = media.rtp.filter(function (rtp) { return codecStringsToRemove.includes(rtp.codec); }); filteredRtp.forEach(function (rtp) { // We grab the relevantCodec config object from the passed in config, based on the name string. var relevantCodec = config.find(function (codec) { return codec.name === rtp.codec; }); // We check the relevantCodec. If it is not present, then we have no config info for this specific rtp. if (relevantCodec) { // If fmtpParams doesnt exist or is of length 0 then we assume we can remove all instances of this codec if (!relevantCodec.fmtpParams || relevantCodec.fmtpParams && relevantCodec.fmtpParams.length === 0) { // We want to delete this codec no matter what, since no fmtp params were included. finalRemoveList.push(rtp.payload); } else { // There are fmtp values for this codec. Therefore we have to check each media.fmtp object to see if it is the right one. // Then when we find the right fmtp object, we check its config to see if it has the parameters specified in the input. media.fmtp.forEach(function (fmtp) { // We check each iteration to see if we found the right fmtp object. if (fmtp.payload === rtp.payload) { // If we found the right fmtp object, we have to make sure each config param is in the fmtp.config. if (relevantCodec.fmtpParams.every(function (c) { return fmtp.config.includes(c); })) { finalRemoveList.push(rtp.payload); } } }); } } }); // At this point we should have an array (finalRemoveList) that contains all ORIGINAL codec payloads that we need to remove. // We now need to check fmtp for all rtx payloads ASSOCIATED with the original codec payload. media.fmtp.forEach(function (fmtp) { // Check if the config contains apt=, which indicates this fmtp is associated with another. if (fmtp.config.includes('apt=')) { // If so, lets grab the whole string WITHOUT the apt= part, and convet it into an integer. This should be a payload number. var payload = parseInt(fmtp.config.replace('apt=', '')); // Check if the finalRemoveList contains the payload that this fmtp is associated with. if (finalRemoveList.includes(payload)) { // If so, then we need to add this fmtp.payload to the finalRemoveList finalRemoveList.push(fmtp.payload); } } }); // We assume past this point that the finalRemoveList is all powerful. // For each codec in the media.payloads string, if it is in our finalRemoveList list, we remove it. var isNumber = false; if (typeof media.payloads === 'number') { media.payloads = media.payloads.toString(); isNumber = true; } if (media.payloads) { media.payloads = media.payloads.split(' ').filter(function (payload) { return !finalRemoveList.includes(parseInt(payload)); }).join(' '); } if (media.payloads && isNumber) { media.payloads = parseInt(media.payloads); } // For each codec object, if the payload is in our filteredCodes list, we remove the object. if (media.rtp) { media.rtp = media.rtp.filter(function (rtp) { return !finalRemoveList.includes(rtp.payload); }); } if (media.fmtp) { media.fmtp = media.fmtp.filter(function (fmtp) { return !finalRemoveList.includes(fmtp.payload); }); } if (media.rtcpFb) { media.rtcpFb = media.rtcpFb.filter(function (rtcpFb) { return !finalRemoveList.includes(rtcpFb.payload); }); } }); return params.next(newSdp); }; } /***/ }), /***/ "../fcs/src/js/sdp/logger.js": /*!***********************************!*\ !*** ../fcs/src/js/sdp/logger.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.default = createSdpLogger; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createSdpLogger(logger) { return function sdpLogger(_ref) { var next = _ref.next, currentSdp = _ref.currentSdp, originalSdp = _ref.originalSdp, operation = _ref.operation, step = _ref.step, type = _ref.type, callId = _ref.callId; logger.info('Call Id: ' + callId); logger.info('SDP step: ' + step); logger.info('SDP operation: ' + operation); logger.info('SDP type: ' + type); if (currentSdp === originalSdp) { logger.info('Unmodified SDP: ' + (0, _stringify2.default)(currentSdp)); } else { logger.info('Original SDP: ' + (0, _stringify2.default)(originalSdp)); logger.info('Modified SDP: ' + (0, _stringify2.default)(currentSdp)); } return next(currentSdp); }; } /***/ }), /***/ "../fcs/src/js/sdp/module.js": /*!***********************************!*\ !*** ../fcs/src/js/sdp/module.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _toConsumableArray2 = __webpack_require__(/*! babel-runtime/helpers/toConsumableArray */ "../../node_modules/babel-runtime/helpers/toConsumableArray.js"); var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2); var _pipeline = __webpack_require__(/*! ./pipeline */ "../fcs/src/js/sdp/pipeline.js"); var _logger = __webpack_require__(/*! ./logger */ "../fcs/src/js/sdp/logger.js"); var _logger2 = _interopRequireDefault(_logger); var _bundleHandler = __webpack_require__(/*! ./bundleHandler */ "../fcs/src/js/sdp/bundleHandler.js"); var _bundleHandler2 = _interopRequireDefault(_bundleHandler); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { SdpPipeline: function SdpPipeline(container) { var builtinHandlers = [(0, _bundleHandler2.default)(function () { return container.Config; })]; return (0, _pipeline.createConvertedSdpPipeline)(function () { return [].concat((0, _toConsumableArray3.default)(container.Config.sdpHandlers), builtinHandlers); }, (0, _logger2.default)(container.LogManager.getLogger('sdpLogger'))); } }; /***/ }), /***/ "../fcs/src/js/sdp/parser.js": /*!***********************************!*\ !*** ../fcs/src/js/sdp/parser.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sdpParse = sdpParse; exports.sdpWrite = sdpWrite; var _sdpTransform = __webpack_require__(/*! sdp-transform */ "../../node_modules/sdp-transform/lib/index.js"); var _sdpTransform2 = _interopRequireDefault(_sdpTransform); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* * This library is wrapped by functions in this module so that we can change * the way that SDP is parsed later if we need to. */ function sdpParse(sdpString) { return _sdpTransform2.default.parse(sdpString); } function sdpWrite(sdpObject) { return _sdpTransform2.default.write(sdpObject); } /***/ }), /***/ "../fcs/src/js/sdp/pipeline.js": /*!*************************************!*\ !*** ../fcs/src/js/sdp/pipeline.js ***! \*************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _freeze = __webpack_require__(/*! babel-runtime/core-js/object/freeze */ "../../node_modules/babel-runtime/core-js/object/freeze.js"); var _freeze2 = _interopRequireDefault(_freeze); exports.createSdpPipeline = createSdpPipeline; exports.createConvertedSdpPipeline = createConvertedSdpPipeline; var _parser = __webpack_require__(/*! ./parser */ "../fcs/src/js/sdp/parser.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* * @method createSdpPipeline * @param {function[]} handlers An array of sdp handlers. These are functions that are given the sdp and a change to return a modified sdp. * @param {function} sdpLogger The logger for the sdp pipeline. This function is called like a handler, with the same params, but is guaranteed to be called at the end of the pipeline. * @returns {function} sdpPipeline The sdpPipeline that will call all of the handlers in order */ function createSdpPipeline(getHandlers, sdpLogger) { /* * @method sdpPipeline * @param {Object} sdp The sdp to put through the pipeline * @param {string} operation The operation this sdp will be used for. Values can be found in js/webrtc/adaptor/constants.js * @param {string} step The step at which the pipeline is being called. Can be 'PRE_LOCAL', 'POST_LOCAL', 'PRE_REMOTE' and 'POST_REMOTE'. * @param {string} type The type of sdp. Can be 'offer' or 'answer'. * @returns {Object} sdp The possibly modified sdp. */ return function (callId, sdp, operation, step, type) { var handlers = getHandlers(); var originalSdp = (0, _freeze2.default)(sdp); var newSdp = originalSdp; // Function that is provided to handlers that needs to be called // to enable the next handler to be called. var nextCalled = false; function next(sdp) { nextCalled = true; return sdp; } function callHandler(handler) { return handler({ next: next, originalSdp: originalSdp, currentSdp: newSdp, operation: operation, step: step, type: type, callId: callId }); } for (var i = 0; i < handlers.length; i++) { // Rest the flag back for each handler nextCalled = false; newSdp = callHandler(handlers[i]); if (!newSdp) { throw new Error('An SDP handler failed to return an sdp'); } // If the next function was not called, we exit the pipeline if (!nextCalled) { break; } } newSdp = callHandler(sdpLogger); return newSdp; }; } // This is a utility function that wraps the sdp pipeline. The wrapper will // convert an sdp string to provide an sdp object to the pipeline and it will // convert the return value back to a string. function createConvertedSdpPipeline(getHandlers, sdpLogger) { var pipeline = createSdpPipeline(getHandlers, sdpLogger); return function (callId, sdpString, operation, step, type) { var sdpObject = (0, _parser.sdpParse)(sdpString); var newSdp = pipeline(callId, sdpObject, operation, step, type); // Optimization: no need to write the string if the sdp hasn't changed if (sdpObject === newSdp) { return sdpString; } return (0, _parser.sdpWrite)(newSdp); }; } /***/ }), /***/ "../fcs/src/js/sdpparser/index.js": /*!****************************************!*\ !*** ../fcs/src/js/sdpparser/index.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SdpParserImpl = SdpParserImpl; var _constants = __webpack_require__(/*! ../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function SdpParserImpl(_ref) { var _logManager = _ref.LogManager, _fcsConfig = _ref.Config; var logger = _logManager.getLogger('sdpParser'), self, nl = '\n', lf = '\r'; this.init = function (sdpData) { self = this; self.sessionDescription = {}; self.mediaDescriptions = []; self.sdp = sdpData; self.parseSDP(); self.setSessionDescriptionAttributes(); self.setMediaDescriptionsAttributes(); }; this.parseSDP = function () { var descriptions = [], index = 1, mediaDescription; descriptions = self.sdp.split(/^(?=m=)/m); self.sessionDescription.data = descriptions[0]; for (index; index < descriptions.length; index++) { mediaDescription = {}; mediaDescription.data = descriptions[index]; self.mediaDescriptions.push(mediaDescription); } }; this.setSessionDescriptionAttributes = function () { var line = 0, sessionDescriptions = self.sessionDescription.data.split(/\r\n|\r|\n/), connectionData; for (line; line < sessionDescriptions.length; line++) { if (sessionDescriptions[line].match('^e=')) { self.sessionDescription.email = sessionDescriptions[line].split('=')[1]; } else if (sessionDescriptions[line].match('^c=')) { connectionData = sessionDescriptions[line].split('=')[1]; self.sessionDescription.connection = connectionData; self.sessionDescription.ip = connectionData.split(' ')[2]; } } }; this.setMediaDescriptionsAttributes = function () { var line = 0, mediaDescriptionIndex, mediaDescriptionAttributes, mediaData, connectionData; for (mediaDescriptionIndex in self.mediaDescriptions) { if (self.mediaDescriptions.hasOwnProperty(mediaDescriptionIndex)) { mediaDescriptionAttributes = self.mediaDescriptions[mediaDescriptionIndex].data.split(/\r\n|\r|\n/); this.mediaDescriptions[mediaDescriptionIndex].direction = 'sendrecv'; for (line in mediaDescriptionAttributes) { if (mediaDescriptionAttributes.hasOwnProperty(line)) { //direction default sendrcv setle if (mediaDescriptionAttributes[line].match('^m=')) { mediaData = mediaDescriptionAttributes[line].split('=')[1]; self.mediaDescriptions[mediaDescriptionIndex].media = mediaData; self.mediaDescriptions[mediaDescriptionIndex].port = mediaData.split(' ')[1]; } else if (mediaDescriptionAttributes[line].match('^a=sendrecv') || mediaDescriptionAttributes[line].match('^a=sendonly') || mediaDescriptionAttributes[line].match('^a=recvonly') || mediaDescriptionAttributes[line].match('^a=inactive')) { self.mediaDescriptions[mediaDescriptionIndex].direction = mediaDescriptionAttributes[line].split('=')[1]; } else if (mediaDescriptionAttributes[line].match('^c=')) { connectionData = mediaDescriptionAttributes[line].split('=')[1]; self.mediaDescriptions[mediaDescriptionIndex].connection = connectionData; self.mediaDescriptions[mediaDescriptionIndex].ip = connectionData.split(' ')[2]; } } } } } }; this.isHold = function (isRemote) { var isHold = false, ip, media_index = 0, mediaDesc; for (media_index in self.mediaDescriptions) { if (self.mediaDescriptions.hasOwnProperty(media_index)) { mediaDesc = this.mediaDescriptions[media_index]; if (mediaDesc.ip) { ip = mediaDesc.ip; } else { if (self.sessionDescription.ip) { ip = self.sessionDescription.ip; } } // some time ago port was set to 0 if sdp didn't have any candidates // now port is set to 9 // adding port != 9 check, will prevent issues while trickle ice is enabled if (mediaDesc.port !== '0' && mediaDesc.port !== '9') { if (mediaDesc.direction === 'inactive' || mediaDesc.direction === 'sendonly' && isRemote || mediaDesc.direction === 'recvonly' && !isRemote || ip === '0.0.0.0') { isHold = true; } else { isHold = false; break; } } } } return isHold; }; this.isRemoteHold = function () { return this.isHold(true); }; this.isLocalHold = function () { return this.isHold(false); }; this.getSessionDescription = function () { return self.sessionDescription; }; this.getMediaDescriptions = function () { return self.mediaDescriptions; }; this.isSdpHas = function (pSdp, type) { var result = false; if (pSdp === null || pSdp === undefined) { return result; } if (pSdp.indexOf(_constants2.default.SDP.M_LINE + type) !== -1) { result = true; return result; } return result; }; this.isSdpHasAudio = function (pSdp) { return this.isSdpHas(pSdp, _constants2.default.STRING.AUDIO); }; this.isSdpHasVideo = function (pSdp) { return this.isSdpHas(pSdp, _constants2.default.STRING.VIDEO); }; this.isSdpHasUfrag = function (pSdp) { var result = false; if (pSdp === null || pSdp === undefined) { return result; } if (pSdp.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.SDP.ICE_UFRAG) !== -1) { result = true; return result; } return result; }; this.isSdpHasMediaWithExpectedPort = function (pSdp, type, port) { if (pSdp === null || pSdp === undefined) { return false; } return pSdp.indexOf(_constants2.default.SDP.M_LINE + type + ' ' + port) !== -1; }; this.isSdpHasAudioWithZeroPort = function (pSdp) { return this.isSdpHasMediaWithExpectedPort(pSdp, _constants2.default.STRING.AUDIO, 0); }; this.isSdpHasVideoWithZeroPort = function (pSdp) { return this.isSdpHasMediaWithExpectedPort(pSdp, _constants2.default.STRING.VIDEO, 0); }; this.isSdpHasAudioWithOnePort = function (pSdp) { return this.isSdpHasMediaWithExpectedPort(pSdp, _constants2.default.STRING.AUDIO, 1); }; this.isSdpHasVideoWithOnePort = function (pSdp) { return this.isSdpHasMediaWithExpectedPort(pSdp, _constants2.default.STRING.VIDEO, 1); }; this.isSdpHasAudioWithNinePort = function (pSdp) { return this.isSdpHasMediaWithExpectedPort(pSdp, _constants2.default.STRING.AUDIO, 9); }; this.isSdpHasVideoWithNinePort = function (pSdp) { return this.isSdpHasMediaWithExpectedPort(pSdp, _constants2.default.STRING.VIDEO, 9); }; this.replaceZeroVideoPortWithOne = function (pSdp) { if (pSdp === null || pSdp === undefined) { return pSdp; } if (this.isSdpHasVideoWithZeroPort(pSdp)) { pSdp = pSdp.replace(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' 0 ', _constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' 1 '); } return pSdp; }; this.getSdpDirection = function (pSdp, type) { var substr = '', descriptions = [], index, direction = _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE, logmsg; logmsg = function logmsg(state) { logger.info('getSdpDirection: type= ' + type + ' state= ' + state); }; if (!this.isSdpHas(pSdp, type)) { logmsg(direction); return direction; } if (this.isSdpHasMediaWithExpectedPort(pSdp, type, 0)) { // return if media port is 0 logmsg(direction); return direction; } descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (substr.indexOf(_constants2.default.SDP.M_LINE + type) !== -1) { if (substr.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) !== -1) { direction = _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE; logmsg(direction); return direction; } else if (substr.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY) !== -1) { direction = _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY; logmsg(direction); return direction; } else if (substr.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) !== -1) { direction = _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY; logmsg(direction); return direction; } else if (substr.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) !== -1) { logmsg(direction); return direction; } direction = _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE; return direction; } } direction = _constants2.default.WEBRTC.MEDIA_STATE.NOT_FOUND; logmsg(direction); return direction; }; this.getAudioSdpDirection = function (pSdp) { return this.getSdpDirection(pSdp, _constants2.default.STRING.AUDIO); }; this.getVideoSdpDirection = function (pSdp) { return this.getSdpDirection(pSdp, _constants2.default.STRING.VIDEO); }; this.isAudioSdpDirectionInactive = function (pSdp) { return this.getAudioSdpDirection(pSdp) === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE; }; this.isAudioSdpDirectionSendrecv = function (pSdp) { return this.getAudioSdpDirection(pSdp) === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE; }; this.isAudioSdpDirectionSendonly = function (pSdp) { return this.getAudioSdpDirection(pSdp) === _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY; }; this.isAudioSdpDirectionRecvonly = function (pSdp) { return this.getAudioSdpDirection(pSdp) === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY; }; this.isSdpContainsAudioDirection = function (pSdp) { return this.getAudioSdpDirection(pSdp) !== _constants2.default.WEBRTC.MEDIA_STATE.NOT_FOUND; }; this.isVideoSdpDirectionInactive = function (pSdp) { return this.getVideoSdpDirection(pSdp) === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE; }; this.isVideoSdpDirectionSendrecv = function (pSdp) { return this.getVideoSdpDirection(pSdp) === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE; }; this.isVideoSdpDirectionSendonly = function (pSdp) { return this.getVideoSdpDirection(pSdp) === _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY; }; this.isVideoSdpDirectionRecvonly = function (pSdp) { return this.getVideoSdpDirection(pSdp) === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY; }; this.isSdpContainsVideoDirection = function (pSdp) { return this.getVideoSdpDirection(pSdp) !== _constants2.default.WEBRTC.MEDIA_STATE.NOT_FOUND; }; this.changeDirection = function (pSdp, directionBefore, directionAfter, type) { var sdp = '', substr, descriptions = [], index; if (!type) { logger.error('changeDirection: called without a type.'); } if (directionBefore === directionAfter) { //no need to change direction return pSdp; } if (directionBefore !== this.getSdpDirection(pSdp, type)) { //Ignore changing the direction if the "directionBefore" and existing directions do not match return pSdp; } descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (substr.indexOf(_constants2.default.SDP.M_LINE + type) !== -1) { if (substr.indexOf(_constants2.default.SDP.A_LINE + directionBefore) === -1) { substr = substr.concat(_constants2.default.SDP.A_LINE + directionAfter + lf + nl); } else { substr = substr.replace(_constants2.default.SDP.A_LINE + directionBefore, _constants2.default.SDP.A_LINE + directionAfter); } } sdp = sdp + substr; } return sdp; }; this.updateSdpDirection = function (pSdp, type, direction) { logger.info('updateSdpDirection: type= ' + type + ' direction= ' + direction); var beforeDirection = this.getSdpDirection(pSdp, type); return this.changeDirection(pSdp, beforeDirection, direction, type); }; this.updateAudioSdpDirection = function (pSdp, direction) { logger.info('updateSdpDirection: type= ' + _constants2.default.STRING.AUDIO + ' direction= ' + direction); var beforeDirection = this.getSdpDirection(pSdp, _constants2.default.STRING.AUDIO); return this.changeDirection(pSdp, beforeDirection, direction, _constants2.default.STRING.AUDIO); }; this.updateVideoSdpDirection = function (pSdp, direction) { logger.info('updateSdpDirection: type= ' + _constants2.default.STRING.VIDEO + ' direction= ' + direction); var beforeDirection = this.getSdpDirection(pSdp, _constants2.default.STRING.VIDEO); return this.changeDirection(pSdp, beforeDirection, direction, _constants2.default.STRING.VIDEO); }; this.updateAudioSdpDirectionToInactive = function (pSdp) { return this.updateAudioSdpDirection(pSdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); }; this.updateVideoSdpDirectionToInactive = function (pSdp) { return this.updateVideoSdpDirection(pSdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); }; this.isSdpHasDirection = function (pSdp) { var sr_indx, so_indx, ro_indx, in_indx; if (pSdp === null || pSdp === undefined) { return false; } sr_indx = pSdp.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, 0); so_indx = pSdp.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, 0); ro_indx = pSdp.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY, 0); in_indx = pSdp.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE, 0); return sr_indx + 1 + (so_indx + 1) + (ro_indx + 1) + (in_indx + 1) === 0 ? false : true; }; this.isSdpEnabled = function (pSdp, type) { var direction, msg = 'isSdpEnabled for type ' + type + ': ', result = false; if (pSdp === null || pSdp === undefined) { return false; } if (this.isSdpHasMediaWithExpectedPort(pSdp, type, 0)) { // return if media port is 0 logger.info(msg + result); return result; } if (type === _constants2.default.STRING.VIDEO) { direction = this.getVideoSdpDirection(pSdp); if (direction === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY || direction === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { logger.info(msg + result); return result; } } if (this.isSdpHas(pSdp, type)) { result = true; } logger.info(msg + result); return result; }; this.isAudioSdpEnabled = function (pSdp) { return this.isSdpEnabled(pSdp, _constants2.default.STRING.AUDIO); }; this.isVideoSdpEnabled = function (pSdp) { return this.isSdpEnabled(pSdp, _constants2.default.STRING.VIDEO); }; this.isSdpVideoReceiveEnabled = function (pSdp) { var direction, msg = 'isSdpVideoReceiveEnabled: ', result = false; if (pSdp === null || pSdp === undefined) { return false; } if (pSdp.indexOf(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' 0') !== -1) { logger.info(msg + result); return result; } direction = this.getVideoSdpDirection(pSdp); if (direction === _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY || direction === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { logger.info(msg + result); return result; } if (pSdp.indexOf(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO) !== -1) { result = true; logger.info(msg + result); return result; } logger.info(msg + result); return result; }; this.updateH264Level = function (pSdp) { var sdp = '', substr = '', descriptions = [], index, reg = /\r\n|\r|\n/m, video_arr, i, new_substr = '', elm, elm_array; descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (substr.indexOf(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO) !== -1) { video_arr = substr.split(reg); for (i = 0; i < video_arr.length; i++) { elm = video_arr[i]; if (elm && elm.indexOf('a=rtpmap:') !== -1 && elm.indexOf('H264') !== -1) { elm_array = elm.split(/\:| /m); elm = elm + _constants2.default.STRING.CARRIAGE_RETURN + _constants2.default.STRING.NEW_LINE; elm = elm + 'a=fmtp:' + elm_array[1] + ' profile-level-id=428014;'; elm = elm + _constants2.default.STRING.CARRIAGE_RETURN + _constants2.default.STRING.NEW_LINE; // Workaround for issue 1603. } else if (elm && elm !== '') { elm = elm + _constants2.default.STRING.CARRIAGE_RETURN + _constants2.default.STRING.NEW_LINE; } new_substr = new_substr + elm; } substr = new_substr; } sdp = sdp + substr; } return sdp; }; /* * Firefox only accepts 42E0xx and above profile-id-level. * In order not to get setRemoteDescription failure we fix the H264 level * This snippet changes all H264 levels with 4280xx to 42E0xx */ this.updateH264LevelTo42E01F = function (pSdp, isH264Enabled) { if (pSdp === null || pSdp === undefined) { return pSdp; } if (isH264Enabled) { logger.debug('Updating the H264 profile-level-id to 42e01f'); pSdp = pSdp.replace(/profile-level-id=.{4}/g, 'profile-level-id=42e0'); } return pSdp; }; this.isSdpVideoCandidateEnabled = function (pSdp) { var msg = 'isSdpVideoCandidateEnabled: ', result = false; if (this.isSdpHasVideoWithZeroPort(pSdp) || this.isVideoSdpDirectionInactive(pSdp)) { logger.info(msg + result); return result; } else if (!this.isSdpHasVideo(pSdp)) { result = true; logger.info(msg + result); return true; } logger.info(msg + result); return result; }; this.deleteFingerprintFromSdp = function (sdp, isDtlsEnabled) { if (sdp === null || sdp === undefined) { return sdp; } if (isDtlsEnabled) { return sdp; } while (sdp.indexOf('a=fingerprint:') !== -1) { sdp = sdp.replace(/(a=fingerprint:[\w\W]*?(:\r|\n))/, ''); } while (sdp.indexOf('a=setup:') !== -1) { sdp = sdp.replace(/(a=setup:[\w\W]*?(:\r|\n))/, ''); } return sdp; }; this.getFingerprintFromSdp = function (sdp) { var fingerprint; if (sdp === null || sdp === undefined) { return; } if (sdp.indexOf('a=fingerprint:') !== -1) { fingerprint = /a=fingerprint:([\w\W]*?)(:\r|\n)/g.exec(sdp)[1]; logger.debug('SDP fingerprint:' + fingerprint); return fingerprint; } return; }; this.deleteCryptoFromSdp = function (sdp, isDtlsEnabled) { if (sdp === null || sdp === undefined) { return; } if (!isDtlsEnabled) { return sdp; } while (sdp.indexOf('a=crypto:') !== -1) { sdp = sdp.replace(/(a=crypto:[\w\W]*?(:\r|\n))/, ''); } return sdp; }; this.deleteCryptoZeroFromSdp = function (sdp) { if (sdp === null || sdp === undefined) { return sdp; } while (sdp.indexOf('a=crypto:0') !== -1) { sdp = sdp.replace(/(a=crypto:0[\w\W]*?(:\r|\n))/, ''); } return sdp; }; /* * updateAudioCodec: removes codecs listed in config file from codec list. * @param {type} pSdp */ this.updateAudioCodec = function (pSdp) { var sdp = '', substr = '', descriptions = [], index, reg = /\r\n|\r|\n/m, audio_arr, i, new_substr = '', attrLine, partialMLine, remcodec, regExpCodec, codecsToRemove = [], j; codecsToRemove = _fcsConfig.codecsToRemove; if (codecsToRemove === undefined) { return pSdp; } descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (this.isSdpHasAudio(substr)) { audio_arr = substr.split(reg); for (i = 0; i < audio_arr.length; i++) { attrLine = audio_arr[i]; for (j = 0; j < codecsToRemove.length; j++) { remcodec = codecsToRemove[j]; if (attrLine && this.isSdpHasAudio(attrLine)) { // remove audio codecs given in config file from m=audio line regExpCodec = new RegExp(' ' + remcodec + '($| )', 'm'); partialMLine = attrLine.split(/(\m=audio+)\s(\w+)/); attrLine = attrLine.replace(/(\m=audio+)\s(\w+)/, ''); attrLine = attrLine.trim(); attrLine = attrLine.replace(regExpCodec, ' '); attrLine = partialMLine[1] + ' ' + partialMLine[2] + ' ' + attrLine + lf + nl; } else if (attrLine && attrLine.indexOf('a=fmtp:' + remcodec) !== -1) { attrLine = attrLine.replace(/a=fmtp[\w\W]*/, ''); } else if (attrLine && attrLine.indexOf('a=rtcp-fb:' + remcodec) !== -1) { attrLine = attrLine.replace(/a=rtcp-fb[\w\W]*/, ''); } else if (attrLine && attrLine.indexOf('a=rtpmap:' + remcodec) !== -1) { attrLine = attrLine.replace(/a=rtpmap[\w\W]*/, ''); } else if (attrLine && attrLine !== '' && j === 0) { attrLine = attrLine + lf + nl; } } new_substr = new_substr + attrLine; } substr = new_substr; } sdp = sdp + substr; } return sdp; }; /* * updateVideoCodec: removes codecs listed in config file from codec list. * @param {type} pSdp */ this.updateVideoCodec = function (pSdp) { var sdp = '', substr = '', descriptions = [], index, reg = /\r\n|\r|\n/m, video_arr, i, new_substr = '', attrLine, partialMLine, remcodec, regExpCodec, codecsToRemoveForVideo = [], j; codecsToRemoveForVideo = _fcsConfig.codecsToRemoveForVideo; if (codecsToRemoveForVideo === undefined) { return pSdp; } descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (this.isSdpHasVideo(substr)) { video_arr = substr.split(reg); for (i = 0; i < video_arr.length; i++) { attrLine = video_arr[i]; for (j = 0; j < codecsToRemoveForVideo.length; j++) { remcodec = codecsToRemoveForVideo[j]; if (attrLine && this.isSdpHasVideo(attrLine)) { // remove video codecs given in config file from m=video line regExpCodec = new RegExp(' ' + remcodec + '($| )', 'm'); partialMLine = attrLine.split(/(\m=video+)\s(\w+)/); attrLine = attrLine.replace(/(\m=video+)\s(\w+)/, ''); attrLine = attrLine.trim(); attrLine = attrLine.replace(regExpCodec, ' '); attrLine = partialMLine[1] + ' ' + partialMLine[2] + ' ' + attrLine + lf + nl; } else if (attrLine && attrLine.indexOf('a=fmtp:' + remcodec) !== -1) { attrLine = attrLine.replace(/a=fmtp[\w\W]*/, ''); } else if (attrLine && attrLine.indexOf('a=rtcp-fb:' + remcodec) !== -1) { attrLine = attrLine.replace(/a=rtcp-fb[\w\W]*/, ''); } else if (attrLine && attrLine.indexOf('a=rtpmap:' + remcodec) !== -1) { attrLine = attrLine.replace(/a=rtpmap[\w\W]*/, ''); } else if (attrLine && attrLine !== '' && j === 0) { attrLine = attrLine + lf + nl; } } new_substr = new_substr + attrLine; } substr = new_substr; } sdp = sdp + substr; } return sdp; }; /* * removeAudioCodec: removes given codec type from sdp. * @param {type} pSdp * @param {type} codecToRemove */ this.removeAudioCodec = function (pSdp, codecToRemove) { var sdp = '', substr = '', descriptions = [], index, reg = /\r\n|\r|\n/m, audio_arr, i, new_substr = '', elm, elm2, regExpCodec; descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (this.isSdpHasAudio(substr)) { audio_arr = substr.split(reg); for (i = 0; i < audio_arr.length; i++) { elm = audio_arr[i]; if (elm && this.isSdpHasAudio(elm)) { // remove given audio codec from m=audio line regExpCodec = new RegExp(' ' + codecToRemove + '($| )', 'm'); elm2 = audio_arr[i].split(/RTP[\w\W]*/); elm = elm.replace(/(\m=audio+)\s(\w+)/, ''); elm = elm.trim(); elm = elm.replace(regExpCodec, ' '); elm = elm2[0] + elm + lf + nl; // Workaround for issue 1603. } else if (elm && elm.indexOf('a=fmtp:' + codecToRemove) !== -1) { elm = elm.replace(/a=fmtp[\w\W]*/, ''); } else if (elm && elm.indexOf('a=rtpmap:' + codecToRemove) !== -1) { elm = elm.replace(/a=rtpmap[\w\W]*/, ''); } else if (elm && elm.indexOf('a=rtcp-fb:' + codecToRemove) !== -1) { elm = elm.replace(/a=rtcp-fb[\w\W]*/, ''); } else if (elm && elm !== '') { elm = elm + lf + nl; } new_substr = new_substr + elm; } substr = new_substr; } sdp = sdp + substr; } return sdp; }; /* * removeRTXCodec: this function will remove rtx video codec */ this.removeRTXCodec = function (pSdp) { var rtxPayloadType, vp8SSRC, rtxSSRC; if (pSdp === null || pSdp === undefined) { return pSdp; } vp8SSRC = this.getVp8Ssrc(pSdp); logger.debug('vp8SSRC = ' + vp8SSRC); rtxSSRC = this.getRtxSsrc(pSdp); logger.debug('rtxSSRC = ' + rtxSSRC); pSdp = this.removeSsrcId(pSdp, rtxSSRC); pSdp = pSdp.replace(/(a=ssrc-group:FID[\w\W]*?(:\r|\n))/g, ''); if (pSdp.indexOf('rtx/90000') === -1) { return pSdp; } rtxPayloadType = this.getRTXPayloadType(pSdp); logger.debug('removeRTXCodec : Removing rtx video codec ' + rtxPayloadType); pSdp = this.removeVideoCodec(pSdp, rtxPayloadType); return pSdp; }; this.getVp8Ssrc = function (pSdp) { var splitArray, ssrcGroupArray, ssrcArray, i, reg = /\r\n|\r|\n/m; if (pSdp === null || pSdp === undefined) { return -1; } if (pSdp.indexOf('a=ssrc-group:FID ') === -1) { return -1; } splitArray = pSdp.split('a=ssrc-group:FID '); ssrcGroupArray = splitArray[1].split(reg); ssrcArray = ssrcGroupArray[0].split(' '); for (i = 0; i < ssrcArray.length; i++) { logger.debug('ssrcArray[' + i + '] : ' + ssrcArray[i]); } return ssrcArray[0]; }; this.getRtxSsrc = function (pSdp) { var splitArray, ssrcGroupArray, ssrcArray, i, reg = /\r\n|\r|\n/m; if (pSdp === null || pSdp === undefined) { return -1; } if (pSdp.indexOf('a=ssrc-group:FID ') === -1) { return -1; } splitArray = pSdp.split('a=ssrc-group:FID '); ssrcGroupArray = splitArray[1].split(reg); ssrcArray = ssrcGroupArray[0].split(' '); for (i = 0; i < ssrcArray.length; i++) { logger.debug('ssrcArray[' + i + '] : ' + ssrcArray[i]); } return ssrcArray[1]; }; /* * removeSsrcId: removes given SSRC ID from sdp. */ this.removeSsrcId = function (pSdp, ssrcId) { var sdp = '', reg = /\r\n|\r|\n/m, ssrc_arr, i, new_substr = '', elm; if (pSdp === null || pSdp === undefined) { return pSdp; } ssrc_arr = pSdp.split(reg); for (i = 0; i < ssrc_arr.length; i++) { elm = ssrc_arr[i]; if (elm && elm.indexOf('a=ssrc:' + ssrcId) !== -1) { elm = elm.replace(/a=ssrc:[\w\W]*/, ''); } else if (elm && elm !== '') { elm = elm + lf + nl; } new_substr = new_substr + elm; } sdp = new_substr; return sdp; }; /* * removeG722Codec: this function will remove G722 audio codec * @param {type} pSdp */ this.removeG722Codec = function (pSdp) { return pSdp; }; this.getPayloadTypeOf = function (codecString, pSdp) { var rtpMapNumber, rtpMapArray, payloadTypeArray = [], index; if (pSdp.indexOf(codecString) === -1) { return -1; } rtpMapArray = pSdp.match(/(a=rtpmap[\w\W]*?(:\r|\n))/g); for (index = 0; index < rtpMapArray.length; index++) { if (rtpMapArray[index].search(new RegExp(codecString, 'i')) !== -1) { /*jslint regexp: false*/ rtpMapNumber = rtpMapArray[index].match(/^[^\d]*(\d+)/g); rtpMapNumber = rtpMapNumber[0].split(':'); payloadTypeArray.push(rtpMapNumber[1]); /*jslint regexp: true*/ } } logger.debug('getPayloadTypeOf(' + codecString + ') = ' + payloadTypeArray[0]); if (payloadTypeArray.length < 2) { // if codec has just one match, then returns it as String for compatibility of old methods return payloadTypeArray[0]; } else { return payloadTypeArray; } }; /* * Replaces new telephone event code in pSdp with the oldCode * This is needed for WebRTC engine compatibility * If an offer has a different telephone event code than what is already negotiated in that session, webrtc engine gives error * Ex: Negotitation is firstly done with 126, but then the call server sends an offer with 96 * @param {type} pSdp * @param {type} oldCode * @param {type} newCode */ this.replaceTelephoneEventPayloadType = function (pSdp, oldCode, newCode) { var finalsdp, regex, matches, tempAudioLine, descriptions, index, substr, partialsdp = '', number = ''; if (!pSdp || pSdp.indexOf('telephone-event') === -1) { return pSdp; } regex = /^\.*(a=rtpmap:)(\d*)( telephone-event[ \w+ ]*[ \/+ ]*[ \w+ ]*)\r\n?/m; /* example: matches= ["a=rtpmap:96 telephone-event/8000\r\n", "a=rtpmap:", "96", " telephone-event/8000"] */ if (oldCode === newCode) { // telephone event has not changed // nothing has changed, return without any changes return pSdp; } // telephone event has changed finalsdp = pSdp; // replace rtpmap regex = new RegExp('^\\.*a=rtpmap:' + newCode + ' telephone-event[ \\/+ ]*([ \\w+ ]*)\\r\n', 'm'); matches = finalsdp.match(regex); if (matches !== null && matches.length >= 2 && matches[1] !== '') { number = matches[1]; } else { number = 8000; } finalsdp = finalsdp.replace(regex, 'a=rtpmap:' + oldCode + ' telephone-event/' + number + '\r\n'); // replace audio line regex = new RegExp('^\\.*(m=audio )[ \\w+ ]*[ \\/+ ]*[ \\w+ ]*( ' + newCode + ')', 'mg'); matches = finalsdp.match(regex); if (matches !== null && matches.length >= 1 && matches[0] !== '') { tempAudioLine = matches[0]; tempAudioLine = tempAudioLine.replace(newCode, oldCode); finalsdp = finalsdp.replace(regex, tempAudioLine); } // replace fmtp // only audio section needs to be considered, do not change video section descriptions = finalsdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (this.isSdpHasAudio(substr)) { regex = new RegExp('^\\.*a=fmtp:' + newCode, 'mg'); substr = substr.replace(regex, 'a=fmtp:' + oldCode); } partialsdp = partialsdp + substr; } if (partialsdp !== '') { finalsdp = partialsdp; } logger.debug('replaceTelephoneEventPayloadType: newcode ' + newCode + ' is replaced with oldcode ' + oldCode); return finalsdp; }; /* * Replaces opus codec in pSdp with the default codec number 109 * (TODO: get the codec from config.json) * This is needed for trancoder enabled peer-to-peer scenarios * transcoder only accepts opus codec that it offers * @param {type} pSdp */ this.replaceOpusCodec = function (pSdp) { var regex, matches, tempAudioLine, oldCodecNumber = '', defaultCodecNumber = 109, descriptions, index, substr, partialsdp = ''; if (!pSdp || pSdp.indexOf('opus') === -1) { return pSdp; } regex = /^\.*(a=rtpmap:)(\d*)( opus)/m; /* example: matches= ["a=rtpmap:109 opus/48000/2\r\n", "a=rtpmap:", "111", " opus/48000/2"] */ matches = pSdp.match(regex); if (matches !== null && matches.length >= 3 && matches[2] !== '') { oldCodecNumber = matches[2]; } else { logger.warn('sdp has opus without codec number'); } // replace rtpmap pSdp = pSdp.replace(regex, 'a=rtpmap:' + defaultCodecNumber + ' opus'); // replace audio line regex = new RegExp('^\\.*(m=audio )[ \\w+ ]*[ \\/+ ]*[ \\w+ ]*( ' + oldCodecNumber + ')', 'mg'); matches = pSdp.match(regex); if (matches !== null && matches.length >= 1 && matches[0] !== '') { tempAudioLine = matches[0]; tempAudioLine = tempAudioLine.replace(oldCodecNumber, defaultCodecNumber); pSdp = pSdp.replace(regex, tempAudioLine); } // replace fmtp // only audio section needs to be considered, do not change video section descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (this.isSdpHasAudio(substr)) { regex = new RegExp('^\\.*a=fmtp:' + oldCodecNumber, 'mg'); substr = substr.replace(regex, 'a=fmtp:' + defaultCodecNumber); } partialsdp = partialsdp + substr; } if (partialsdp !== '') { pSdp = partialsdp; } logger.debug('replaceOpusCodec: new codec= ' + defaultCodecNumber); return pSdp; }; this.updateOpusConfig = function (pSdp, opusConfig) { if (opusConfig === undefined) { logger.debug('No control values for bandwidth control were added. Proceeding...'); return pSdp; } else { if (!pSdp || pSdp === undefined) { return pSdp; } var opusBandwidthLine = '', opusPayload = this.getOpusPayloadType(pSdp), searchParam = 'a=fmtp:' + opusPayload, untilFtmpLine = '', opusFmtpLine = '', aFmtp = ''; // fmtpLine format: a=fmtp:111 minptime=10;useinbandfec=1 // aFmtp format: a=fmtp:111 // values are set via the fcsConfig var maxPlaybackRate = opusConfig.maxPlaybackRate, maxAverageBitrate = opusConfig.maxAverageBitrate, fec = opusConfig.fec, dtx = opusConfig.dtx, ptime = opusConfig.ptime; // if the fmtp line with the opus payload exists, parse it to obtain the line with the opus codec if (pSdp.indexOf(searchParam) !== -1) { untilFtmpLine = pSdp.substring(pSdp.indexOf(searchParam), pSdp.length); opusFmtpLine = untilFtmpLine.substring(0, untilFtmpLine.indexOf(lf + nl)); // fmtp line format is now a=fmtp:111 minptime=10;useinbandfec=1 aFmtp = opusFmtpLine.split(' ')[0]; opusBandwidthLine = aFmtp + ' '; // bandwidthLine starts with a=fmtp:[codec value] // append the audio controls opusBandwidthLine += this.createControlText(_constants2.default.SDP.BANDWIDTH.MAXPLAYBACKRATE, maxPlaybackRate); opusBandwidthLine += this.createControlText(_constants2.default.SDP.BANDWIDTH.MAXAVERAGEBITRATE, maxAverageBitrate); opusBandwidthLine += this.createControlText(_constants2.default.SDP.BANDWIDTH.FEC, fec); opusBandwidthLine += this.createControlText(_constants2.default.SDP.BANDWIDTH.DTX, dtx); // bandwidthLine.endsWith(';') workaround for IE if (opusBandwidthLine.lastIndexOf(';') === opusBandwidthLine.length - 1) { opusBandwidthLine = opusBandwidthLine.slice(0, -1); } if (this.isValidOpusControl(_constants2.default.SDP.BANDWIDTH.PTIME, ptime)) { var ptimeSearchParam = 'a=' + _constants2.default.SDP.BANDWIDTH.PTIME; // check if ptime property is already in sdp if (pSdp.indexOf(ptimeSearchParam) !== -1) { var ptimeAndRest = pSdp.substring(pSdp.indexOf(ptimeSearchParam), pSdp.length); var ptimeLine = ptimeAndRest.substring(0, ptimeAndRest.indexOf(lf + nl)); // format: a=ptime:40 pSdp = pSdp.replace(ptimeLine, ptimeSearchParam + ':' + ptime); } else { opusBandwidthLine += lf + nl + 'a=' + _constants2.default.SDP.BANDWIDTH.PTIME + ':' + ptime; } } // if there are more than 1 equal signs, then at least one of the provided control values were valid // and we should replace the fmtp line for opus. otherwise the line should stay as default if (opusBandwidthLine.split('=').length - 1 > 1) { pSdp = pSdp.replace(opusFmtpLine, opusBandwidthLine); logger.debug('Bandwidth control handled. Opus codec control values are updated.'); } else { logger.debug('Provided control parameters were invalid. Keeping default opus codec control values.'); } } else { logger.debug('Search parameter ' + searchParam + ' not found in sdp.'); } } return pSdp; }; this.createControlText = function (audioControlPropertyName, audioControlPropertyValue) { var controlLine = ''; // if a value for a control was set, use it. otherwise discard the control value if (typeof audioControlPropertyValue !== 'undefined') { if (this.isValidOpusControl(audioControlPropertyName, audioControlPropertyValue)) { controlLine = audioControlPropertyName + '=' + audioControlPropertyValue + ';'; } } return controlLine; }; this.isValidOpusControl = function (controlName, controlValue) { var val = parseInt(controlValue); switch (controlName) { case _constants2.default.SDP.BANDWIDTH.MAXPLAYBACKRATE: return 8000 <= val && val <= 48000; case _constants2.default.SDP.BANDWIDTH.MAXAVERAGEBITRATE: return 6000 <= val && val <= 510000; case _constants2.default.SDP.BANDWIDTH.FEC: case _constants2.default.SDP.BANDWIDTH.DTX: return val === 0 || val === 1; case _constants2.default.SDP.BANDWIDTH.PTIME: return 2.5 < val && val <= 120; default: return false; } }; this.getG7228000PayloadType = function (pSdp) { return this.getPayloadTypeOf('G722/8000', pSdp); }; this.getVP8PayloadType = function (pSdp) { return this.getPayloadTypeOf('VP8/90000', pSdp); }; this.getG72216000PayloadType = function (pSdp) { return this.getPayloadTypeOf('G722/16000', pSdp); }; this.getRTXPayloadType = function (pSdp) { return this.getPayloadTypeOf('rtx/90000', pSdp); }; this.getH264PayloadType = function (pSdp) { return this.getPayloadTypeOf('H264/90000', pSdp); }; this.getOpusPayloadType = function (pSdp) { return this.getPayloadTypeOf('opus/48000', pSdp); }; this.isSdpHasTelephoneEventWithRate = function (pSdp, rate) { if (pSdp === null || pSdp === undefined) { return false; } return pSdp.indexOf('telephone-event/' + rate) !== -1; }; this.isSdpHasTelephoneEvent = function (pSdp) { if (pSdp === null || pSdp === undefined) { return false; } return pSdp.indexOf('telephone-event/') !== -1; }; this.isSdpHasVP8Codec = function (pSdp) { if (pSdp === null || pSdp === undefined) { return false; } return pSdp.indexOf('VP8/90000') !== -1; }; this.isSdpHasH264Codec = function (pSdp) { if (pSdp === null || pSdp === undefined) { return false; } return pSdp.indexOf('H264/90000') !== -1; }; /* * checkSupportedVideoCodecs * * checks video codec support status and remove video m-line if no supported video codec is available * @param {type} pSdp * @param {type} localOfferSdp */ this.checkSupportedVideoCodecs = function (pSdp, localOfferSdp, isH264Enabled) { var newSdp; if (pSdp === null || pSdp === undefined) { return pSdp; } if (this.isVideoCodecsSupported(pSdp, isH264Enabled)) { return pSdp; } else { if (localOfferSdp) { newSdp = this.removeAllVideoCodecs(pSdp); newSdp = this.addVP8Codec(newSdp, localOfferSdp); newSdp = this.updateSdpVideoPort(newSdp, false); newSdp = this.performVideoPortZeroWorkaround(newSdp); } else { //****************************************************** //Changing video port to 0 when there is no supported //video codecs is not working in webrtc library //****************************************************** if (!this.isSdpHasVP8Codec(pSdp)) { if (pSdp.indexOf(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' 0 ', 0) !== -1) { newSdp = this.addVP8Codec(pSdp, newSdp); } else { //this is required for PCC and meetme with video newSdp = this.updateSdpVideoPort(pSdp, false); newSdp = this.addVP8Codec(newSdp, newSdp); } } else { //this is required for PCC and meetme with video newSdp = this.removeVideoDescription(pSdp); } } return newSdp; } }; /* * isVideoCodecsSupported: this function checks supported video codecs are listed in m=video line * Supported video codecs are : * VP8 default supported codec * H264 if h264 is enabled with plugin * @param {type} pSdp */ this.isVideoCodecsSupported = function (pSdp, isH264Enabled) { if (this.isSdpHasVP8Codec(pSdp)) { return true; } if (isH264Enabled) { if (this.isSdpHasH264Codec(pSdp)) { return true; } } return false; }; this.removeAllVideoCodecs = function (pSdp) { var regex, matches, codecs, newSdp, index; if (pSdp === null || pSdp === undefined) { return pSdp; } //TODO: The RegExp below has invalid control character of \n. Don't think we should have that // but i'm leaving it for now since it might be dangerous to fix. Also need to disable the eslint. // //eslint-disable-next-line no-control-regex regex = new RegExp('^\\.*(m=video )(\\d*)( RTP/SAVPF )([ \\w+ ]*[ \\/+ ]*[ \\w+ ])\\r\n', 'm'); newSdp = pSdp; matches = newSdp.match(regex); if (matches !== null && matches.length >= 5 && matches[0] !== '') { codecs = matches[4].split(' '); for (index = 0; index < codecs.length; index++) { logger.debug('codec[' + index + '] : ' + codecs[index]); newSdp = this.removeVideoCodec(newSdp, codecs[index]); } } return newSdp; }; /* * removeVideoCodec: removes given codec type from sdp. * @param {type} pSdp * @param {type} codecToRemove */ this.removeVideoCodec = function (pSdp, codecToRemove) { var sdp = '', substr = '', descriptions = [], index, reg = /\r\n|\r|\n/m, video_arr, i, new_substr = '', elm, regExpCodec; if (pSdp === null || pSdp === undefined || !codecToRemove) { return pSdp; } descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (this.isSdpHasVideo(substr)) { video_arr = substr.split(reg); for (i = 0; i < video_arr.length; i++) { elm = video_arr[i]; if (elm && this.isSdpHasVideo(elm)) { // remove given video codec from m=video line regExpCodec = new RegExp(' ' + codecToRemove, 'g'); elm = elm.replace(regExpCodec, ''); elm = elm + lf + nl; // Workaround for issue 1603. } else if (elm && elm.indexOf('a=fmtp:' + codecToRemove) !== -1) { elm = elm.replace(/a=fmtp[\w\W]*/, ''); } else if (elm && elm.indexOf('a=rtpmap:' + codecToRemove) !== -1) { elm = elm.replace(/a=rtpmap[\w\W]*/, ''); } else if (elm && elm.indexOf('a=rtcp-fb:' + codecToRemove) !== -1) { elm = elm.replace(/a=rtcp-fb[\w\W]*/, ''); } else if (elm && elm !== '') { elm = elm + lf + nl; } new_substr = new_substr + elm; } substr = new_substr; } sdp = sdp + substr; } return sdp; }; /* * addVP8Codec: adds missing VP8 Codec * @param {type} pSdp * @param {type} offerSdp */ this.addVP8Codec = function (pSdp, offerSdp) { var sdp = '', substr = '', descriptions = [], index, reg = /\r\n|\r|\n/m, video_arr, i, new_substr = '', vp8PayloadType, codecType, elm, videoUFRAGParam, videoPWDParam, ice_ufrag, ice_pwd; if (this.isSdpHasVP8Codec(pSdp)) { return pSdp; } descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (this.isSdpHasVideo(substr)) { if (offerSdp && this.isSdpHasVideo(offerSdp) && this.isSdpHasVP8Codec(offerSdp)) { vp8PayloadType = this.getVP8PayloadType(offerSdp); if (substr.indexOf('a=rtpmap:' + vp8PayloadType) !== -1) { this.removeSdpLineContainingText(substr, 'a=rtpmap:' + vp8PayloadType); } } else { codecType = 100; while (substr.indexOf('a=rtpmap:' + codecType) !== -1) { codecType = codecType + 1; } vp8PayloadType = codecType; } video_arr = substr.split(reg); for (i = 0; i < video_arr.length; i++) { elm = video_arr[i]; if (elm && this.isSdpHasVideo(elm)) { if (elm.indexOf(vp8PayloadType) === -1) { elm = elm + ' ' + vp8PayloadType; } elm = elm + lf + nl + 'a=rtpmap:' + vp8PayloadType + ' VP8/90000' + lf + nl; } else if (elm && elm !== '') { elm = elm + lf + nl; } new_substr = new_substr + elm; } substr = new_substr; } sdp = sdp + substr; } videoUFRAGParam = this.checkICEParams(sdp, 'video', _constants2.default.SDP.ICE_UFRAG); if (videoUFRAGParam < 2) { ice_ufrag = this.getICEParams(sdp, _constants2.default.SDP.ICE_UFRAG, false); if (ice_ufrag) { sdp = this.restoreICEParams(sdp, 'video', _constants2.default.SDP.ICE_UFRAG, ice_ufrag); } } videoPWDParam = this.checkICEParams(sdp, 'video', _constants2.default.SDP.ICE_PWD); if (videoPWDParam < 2) { ice_pwd = this.getICEParams(sdp, _constants2.default.SDP.ICE_PWD, false); if (ice_pwd) { sdp = this.restoreICEParams(sdp, 'video', _constants2.default.SDP.ICE_PWD, ice_pwd); } } return sdp; }; this.removeSdpLineContainingText = function (pSdp, containing_text) { var i, splitArray; if (pSdp === null || pSdp === undefined || !containing_text) { return pSdp; } splitArray = pSdp.split(nl); pSdp = splitArray[0] + nl; for (i = 1; i < splitArray.length - 1; i++) { if (splitArray[i].indexOf(containing_text) !== -1) { logger.debug('removed line which contains ' + containing_text); } else { pSdp += splitArray[i] + nl; } } return pSdp; }; this.removeVideoDescription = function (pSdp) { var sdp = '', substr = '', descriptions = [], index; if (pSdp === null || pSdp === undefined) { return pSdp; } descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (!this.isSdpHasVideo(substr)) { sdp = sdp + substr; } else { logger.debug('removeVideoDescription : m=video description removed'); } } return sdp; }; /* * updateSdpVideoPort * @param {type} pSdp * @param {type} status */ this.updateSdpVideoPort = function (pSdp, status) { var r_sdp, port_text; if (pSdp === null || pSdp === undefined) { return pSdp; } logger.debug('updateSdpVideoPort: status= ' + status); r_sdp = pSdp; if (status) { port_text = _constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' 1'; } else { port_text = _constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' 0'; r_sdp = this.updateSdpDirection(r_sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } if (this.isSdpHasVideo(r_sdp)) { r_sdp = r_sdp.replace(/m=video [0-9]+/, port_text); } return r_sdp; }; /* * performVideoPortZeroWorkaround - apply this when term side sends an answer with video port 0 * @param {type} pSdp */ this.performVideoPortZeroWorkaround = function (pSdp) { if (pSdp === null || pSdp === undefined) { return pSdp; } if (!this.isSdpHasVideoWithZeroPort(pSdp)) { return pSdp; } pSdp = this.addSdpMissingCryptoLine(pSdp); pSdp = this.replaceZeroVideoPortWithOne(pSdp); //chrome38 fix pSdp = this.updateVideoSdpDirectionToInactive(pSdp); return pSdp; }; // Issue : Meetme conference failed due to a webrtc bug // When video is sent in SDP with 0 without a=crypto line(SDES) in SDP, // hold scenario for meetme failed. // Workaround : Add dummy a=crypto or a=fingerprint line to solve the issue with a workaround // Note : fingerprint(DTLS enabled) may still fails on meetme. This is known issue as below: // https://code.google.com/p/webrtc/issues/detail?id=2316 // Check with Chrome 37 this.addSdpMissingCryptoLine = function (sdp) { var mediaSplit, audioLines, cryptLine = null, reg = /\r\n|\r|\n/m, i; // If there is no "m=video 0" line, sdp should not be modified if (sdp.indexOf(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' 0 ', 0) === -1) { return sdp; } mediaSplit = sdp.split(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO); audioLines = mediaSplit[0].split(reg); for (i = 0; i < audioLines.length; i++) { if (audioLines[i].indexOf(_constants2.default.SDP.A_LINE + _constants2.default.SDP.CRYPTO) !== -1 || audioLines[i].indexOf(_constants2.default.SDP.A_LINE + _constants2.default.SDP.FINGERPRINT) !== -1) { cryptLine = audioLines[i]; break; } } if (cryptLine === null) { return sdp; } if (mediaSplit[0].indexOf(_constants2.default.SDP.A_LINE + _constants2.default.SDP.CRYPTO) !== -1) { if (mediaSplit[1].indexOf(_constants2.default.SDP.A_LINE + _constants2.default.SDP.CRYPTO, 0) === -1) { mediaSplit[1] += cryptLine + '\n'; logger.debug('addSdpMissingCryptoLine : crypto line is added : ' + cryptLine); } } else if (mediaSplit[0].indexOf(_constants2.default.SDP.A_LINE + _constants2.default.SDP.FINGERPRINT, 0) !== -1) { if (mediaSplit[1].indexOf(_constants2.default.SDP.A_LINE + _constants2.default.SDP.FINGERPRINT, 0) === -1) { //DTLS is enabled, even adding fingerprint line in SDP, //meetme scenario fails. This is known issue and followed //by webrtc for DTLS enabled scenarios : //https://code.google.com/p/webrtc/issues/detail?id=2316 mediaSplit[1] += cryptLine + '\na=setup:passive\n'; logger.debug('addSdpMissingCryptoLine : dtls lines are added : ' + cryptLine + 'and a=setup:passive'); logger.debug('dtls enabled: known issue by webrtc may be fixed! Check it'); } } sdp = mediaSplit.join(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO); return sdp; }; this.checkICEParams = function (pSdp, mediaType, type) { var parse1, parse2; if (pSdp === null || pSdp === undefined) { return 0; } parse1 = pSdp.split('m=video'); if (parse1.length < 2) { return 0; } switch (type) { case _constants2.default.SDP.ICE_UFRAG: if (mediaType === 'audio') { parse2 = parse1[0].split('a=ice-ufrag:'); } else { parse2 = parse1[1].split('a=ice-ufrag:'); } break; case _constants2.default.SDP.ICE_PWD: if (mediaType === 'audio') { parse2 = parse1[0].split('a=ice-pwd:'); } else { parse2 = parse1[1].split('a=ice-pwd:'); } break; default: return 0; } return parse2.length; }; this.getICEParams = function (pSdp, type, isVideo) { var parse1, parse2, parse3, param; if (pSdp === null || pSdp === undefined) { return; } switch (type) { case _constants2.default.SDP.ICE_UFRAG: parse1 = pSdp.split('a=ice-ufrag:'); break; case _constants2.default.SDP.ICE_PWD: parse1 = pSdp.split('a=ice-pwd:'); break; default: return undefined; } if (isVideo) { if (parse1[2] !== undefined) { /*"....a=ice-....a=ice-...."*/ parse2 = parse1[2]; parse3 = parse2.split('a='); param = parse3[0]; return param; /*return video ice params*/ } else { return undefined; } } else { if (parse1[1] !== undefined) { /*"....a=ice-....a=ice-...."*/ parse2 = parse1[1]; parse3 = parse2.split('a='); param = parse3[0]; return param; } else { return undefined; } } }; this.restoreICEParams = function (pSdp, mediaType, type, new_value) { var sdp = '', substr, index, parse1; if (pSdp === null || pSdp === undefined) { return pSdp; } parse1 = pSdp.split('m=video'); if (parse1.length < 2) { return pSdp; } for (index = 0; index < parse1.length; index++) { substr = parse1[index]; if (index === 0) { if (mediaType === 'audio') { substr = substr + 'a=' + type + new_value; } sdp = sdp + substr; } if (index === 1) { if (mediaType === 'video') { substr = substr + 'a=' + type + new_value; } sdp = sdp + 'm=video' + substr; } } return sdp; }; this.updateICEParams = function (pSdp, type, new_value) { var sdp = '', subsdp = '', substr, index, num, parse1, parse2; if (pSdp === null || pSdp === undefined) { return pSdp; } switch (type) { case _constants2.default.SDP.ICE_UFRAG: parse1 = pSdp.split('a=ice-ufrag:'); break; case _constants2.default.SDP.ICE_PWD: parse1 = pSdp.split('a=ice-pwd:'); break; default: return pSdp; } for (index = 0; index < parse1.length; index++) { substr = parse1[index]; if (index === 2) { parse2 = substr.split('a='); for (num = 0; num < parse2.length; num++) { if (num === 0) { parse2[num] = new_value; subsdp = subsdp + parse2[num]; } else { subsdp = subsdp + 'a=' + parse2[num]; } } substr = subsdp; sdp = sdp + substr; } else { sdp = sdp + substr + 'a=' + type; } } return sdp; }; this.checkIceParamsLengths = function (newSdp, oldSdp) { var ice_ufrag, ice_pwd; ice_ufrag = this.getICEParams(newSdp, _constants2.default.SDP.ICE_UFRAG, true); ice_pwd = this.getICEParams(newSdp, _constants2.default.SDP.ICE_PWD, true); if (ice_ufrag && ice_ufrag.length < 4) { /*RFC 5245 the ice-ufrag attribute can be 4 to 256 bytes long*/ ice_ufrag = this.getICEParams(oldSdp, _constants2.default.SDP.ICE_UFRAG, true); if (ice_ufrag) { newSdp = this.updateICEParams(newSdp, _constants2.default.SDP.ICE_UFRAG, ice_ufrag); } } if (ice_pwd && ice_pwd.length < 22) { /*RFC 5245 the ice-pwd attribute can be 22 to 256 bytes long*/ ice_pwd = this.getICEParams(oldSdp, _constants2.default.SDP.ICE_PWD, true); if (ice_pwd) { newSdp = this.updateICEParams(newSdp, _constants2.default.SDP.ICE_PWD, ice_pwd); } } return newSdp; }; /* * isSdpVideoSendEnabled * @param {type} pSdp */ this.isSdpVideoSendEnabled = function (pSdp) { var direction, msg = 'isSdpVideoSendEnabled: ', result = false; if (pSdp === null || pSdp === undefined) { return false; } if (!this.isSdpEnabled(pSdp, _constants2.default.STRING.VIDEO)) { logger.debug(msg + result); return result; } direction = this.getSdpDirectionLogging(pSdp, _constants2.default.STRING.VIDEO, false); if (direction === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE || direction === _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY) { result = true; logger.debug(msg + result); return result; } logger.debug(msg + result); return result; }; this.getSdpDirectionLogging = function (pSdp, type, logging) { var substr = '', descriptions = [], index, direction = _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE, logmsg; logmsg = function logmsg(state) { if (logging) { logger.debug('getSdpDirection: type= ' + type + ' state= ' + state); } }; if (pSdp.indexOf(_constants2.default.SDP.M_LINE + type) === -1) { logmsg(direction); return direction; } if (pSdp.indexOf(_constants2.default.SDP.M_LINE + type + ' 0') !== -1) { logmsg(direction); return direction; } descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (substr.indexOf(_constants2.default.SDP.M_LINE + type) !== -1) { if (substr.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) !== -1) { direction = _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE; logmsg(direction); return direction; } else if (substr.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY) !== -1) { direction = _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY; logmsg(direction); return direction; } else if (substr.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) !== -1) { direction = _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY; logmsg(direction); return direction; } else if (substr.indexOf(_constants2.default.SDP.A_LINE + _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) !== -1) { logmsg(direction); return direction; } direction = _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE; return direction; } } direction = _constants2.default.WEBRTC.MEDIA_STATE.NOT_FOUND; logmsg(direction); return direction; }; /* * remove only video ssrc from the sdp * this is a workaround to hear audio in a peer-to-peer call * @param {type} pSdp */ this.deleteInactiveVideoSsrc = function (pSdp) { var videoSdp = []; if (this.isSdpHas(pSdp, _constants2.default.STRING.VIDEO)) { videoSdp = pSdp.split(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO); if (videoSdp[1] !== null) { videoSdp[1] = this.deleteSsrcFromSdp(videoSdp[1]); } } else { return pSdp; } return videoSdp[0] + _constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + videoSdp[1]; }; /* * deleteSsrcFromSdp - delete ssrc from the sdp, use it when there is video continuity issue * @param {type} sdp */ this.deleteSsrcFromSdp = function (sdp) { if (sdp === null || sdp === undefined) { return sdp; } while (sdp.indexOf('a=ssrc') !== -1) { sdp = sdp.replace(/(a=ssrc[\w\W]*?(:\r|\n))/, ''); } return sdp; }; this.getTcpSetupAttribute = function (sdp) { if (sdp === null || sdp === undefined) { return; } if (sdp.indexOf(_constants2.default.SDP.SETUP_ACTIVE) !== -1) { return 'active'; } else if (sdp.indexOf(_constants2.default.SDP.SETUP_PASSIVE) !== -1) { return 'passive'; } else if (sdp.indexOf(_constants2.default.SDP.SETUP_ACTPASS) !== -1) { return 'actpass'; } }; this.setTcpSetupAttribute = function (sdp, newSetupAttribute) { if (sdp === null || sdp === undefined) { return sdp; } if (newSetupAttribute !== 'active') { while (sdp.indexOf(_constants2.default.SDP.SETUP_ACTIVE) !== -1) { logger.debug('a=setup:active to ' + newSetupAttribute); sdp = sdp.replace(_constants2.default.SDP.SETUP_ACTIVE, 'a=setup:' + newSetupAttribute); } } if (newSetupAttribute !== 'passive') { while (sdp.indexOf(_constants2.default.SDP.SETUP_PASSIVE) !== -1) { logger.debug('a=setup:passive to ' + newSetupAttribute); sdp = sdp.replace(_constants2.default.SDP.SETUP_PASSIVE, 'a=setup:' + newSetupAttribute); } } if (newSetupAttribute !== 'actpass') { while (sdp.indexOf(_constants2.default.SDP.SETUP_ACTPASS) !== -1) { logger.debug('a=setup:actpass to ' + newSetupAttribute); sdp = sdp.replace(_constants2.default.SDP.SETUP_ACTPASS, 'a=setup:' + newSetupAttribute); } } return sdp; }; /* * * @param {type} pSdp * @param {type} oSdp * @returns pSdp */ this.checkAndRestoreICEParams = function (pSdp, oSdp) { var audioUFRAGParam, audioPWDParam, videoUFRAGParam, videoPWDParam, ice_ufrag, ice_pwd; audioUFRAGParam = this.checkICEParams(pSdp, _constants2.default.STRING.AUDIO, _constants2.default.SDP.ICE_UFRAG); if (audioUFRAGParam < 2) { ice_ufrag = this.getICEParams(oSdp, _constants2.default.SDP.ICE_UFRAG, false); if (ice_ufrag) { pSdp = this.restoreICEParams(pSdp, _constants2.default.STRING.AUDIO, _constants2.default.SDP.ICE_UFRAG, ice_ufrag); } } audioPWDParam = this.checkICEParams(pSdp, _constants2.default.STRING.AUDIO, _constants2.default.SDP.ICE_PWD); if (audioPWDParam < 2) { ice_pwd = this.getICEParams(oSdp, _constants2.default.SDP.ICE_PWD, false); if (ice_pwd) { pSdp = this.restoreICEParams(pSdp, _constants2.default.STRING.AUDIO, _constants2.default.SDP.ICE_PWD, ice_pwd); } } videoUFRAGParam = this.checkICEParams(pSdp, _constants2.default.STRING.VIDEO, _constants2.default.SDP.ICE_UFRAG); if (videoUFRAGParam < 2) { ice_ufrag = this.getICEParams(oSdp, _constants2.default.SDP.ICE_UFRAG, false); if (ice_ufrag) { pSdp = this.restoreICEParams(pSdp, _constants2.default.STRING.VIDEO, _constants2.default.SDP.ICE_UFRAG, ice_ufrag); } } videoPWDParam = this.checkICEParams(pSdp, _constants2.default.STRING.VIDEO, _constants2.default.SDP.ICE_PWD); if (videoPWDParam < 2) { ice_pwd = this.getICEParams(oSdp, _constants2.default.SDP.ICE_PWD, false); if (ice_pwd) { pSdp = this.restoreICEParams(pSdp, _constants2.default.STRING.VIDEO, _constants2.default.SDP.ICE_PWD, ice_pwd); } } return pSdp; }; this.incrementVersion = function (pSdp) { var oLineAsArray = [], newoLine = '', index, version, actualoLine; logger.debug('incrementVersion'); if (pSdp === null || pSdp === undefined) { return pSdp; } // o=- 937770930552268055 2 IN IP4 127.0.0.1 // o=mozilla...THIS_IS_SDPARTA-37.0.1 4294967295 0 IN IP4 0.0.0.0 // get o line actualoLine = pSdp.match(/(o=[\w\W]*?(:\r|\n))/); if (!actualoLine) { return pSdp; } // get o line oLineAsArray = actualoLine[0].split(' '); //getting version and convering it to int version = +oLineAsArray[2]; //incrementing the version version = version + 1; for (index = 0; index < oLineAsArray.length; index++) { if (index !== 0) { // prevents adding unnecessary space before the o line newoLine = newoLine + ' '; } if (index === 2) { // 2nd index is version index newoLine = newoLine + version; } else { newoLine = newoLine + oLineAsArray[index]; } } pSdp = pSdp.replace(actualoLine[0], newoLine); return pSdp; }; /* * escalateSdpDirection for type:audio or video * @param {type} pSdp * @param {type} type */ this.escalateSdpDirection = function (pSdp, type) { var direction = this.getSdpDirectionLogging(pSdp, type, false); logger.debug('escalateSdpDirection: type= ' + type + ' direction= ' + direction); if (direction === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) { return this.changeDirection(pSdp, direction, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, type); } else if (direction === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { return this.changeDirection(pSdp, direction, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, type); } return pSdp; }; /* * deescalateSdpDirection for type:audio or video * @param {type} pSdp * @param {type} type */ this.deescalateSdpDirection = function (pSdp, type) { var direction = this.getSdpDirectionLogging(pSdp, type, false); logger.debug('deescalateSdpDirection: type= ' + type + ' direction= ' + direction); if (direction === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) { return this.changeDirection(pSdp, direction, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY, type); } else if (direction === _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY) { return this.changeDirection(pSdp, direction, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE, type); } return pSdp; }; this.isIceLite = function (pSdp) { if (pSdp === null || pSdp === undefined) { return false; } if (pSdp && pSdp.indexOf('a=ice-lite') !== -1) { return true; } return false; }; this.getSessionIdFromSdp = function (sdp) { var oLine; if (!sdp) { return -1; } oLine = sdp.match(/(o=[\w\W]*?(:\r|\n))/); if (!oLine) { return -1; } oLine = oLine[0].split(' '); if (oLine[1]) { logger.info('getSessionIdFromSdp = ' + oLine[1]); return oLine[1]; } else { logger.warn('getSessionIdFromSdp called with wrong sdp!!'); return -1; } }; /* * Updates the version in tosdp with the one retrieved from fromsdp with incrementing */ this.updateVersion = function (fromSdp, toSdp) { var fromOline = [], toOline = [], newoLine = '', index, version, actualtoOline = ''; if (fromSdp === null || fromSdp === undefined) { return toSdp; } logger.debug(' updateVersion called...'); // o=- 937770930552268055 2 IN IP4 127.0.0.1 // get o line fromOline = fromSdp.match(/(o=[\w\W]*?(:\r|\n))/); if (!fromOline) { return toSdp; } fromOline = fromOline[0].split(' '); // get o line actualtoOline = toSdp.match(/(o=[\w\W]*?(:\r|\n))/); toOline = actualtoOline[0].split(' '); if (fromOline) { version = fromOline[2]; } else { logger.warn('updateVersion called with wrong fromSdp!!'); return toSdp; } // convert to int and increment version = +version + 1; logger.debug(' updateVersion fromVersion incremented: ' + version); for (index = 0; index < toOline.length; index++) { if (index !== 0) { // prevents adding unnecessary space before the o line newoLine = newoLine + ' '; } if (index === 2) { // 2nd index is version index newoLine = newoLine + version; } else { newoLine = newoLine + toOline[index]; } } toSdp = toSdp.replace(actualtoOline[0], newoLine); return toSdp; }; // TODO: Method below assumes to receive only one video m-line, need to correct this logic. this.copyCandidatesToTheNewLocalSdp = function (oldSdp, newSdp) { var oldSplitSdp = [], newSplitSdp = [], oldVideoSdp, newVideoSdp, oldAudioSdp, newAudioSdp; oldSplitSdp = oldSdp.split(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO); newSplitSdp = newSdp.split(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO); oldAudioSdp = oldSplitSdp[0]; oldVideoSdp = oldSplitSdp[1] !== undefined ? _constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + oldSplitSdp[1] : undefined; newAudioSdp = newSplitSdp[0]; newVideoSdp = newSplitSdp[1] !== undefined ? _constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + newSplitSdp[1] : undefined; newAudioSdp = this.copyCandidates(oldAudioSdp, newAudioSdp); if (oldVideoSdp !== undefined && newVideoSdp !== undefined) { newVideoSdp = this.copyCandidates(oldVideoSdp, newVideoSdp); } if (newVideoSdp !== undefined) { return newAudioSdp + newVideoSdp; } else { return newAudioSdp; } }; this.copyCandidates = function (oldSdp, newSdp) { var mediaLines, reg = /\r\n|\r|\n/m, i, port; mediaLines = oldSdp.split(reg); for (i = 0; i < mediaLines.length; i++) { if (mediaLines[i].indexOf('a=candidate') !== -1 && newSdp.indexOf('a=candidate' === -1)) { newSdp += mediaLines[i] + '\r\n'; } else if (mediaLines[i].indexOf('c=IN') !== -1 && newSdp.indexOf('c=IN IP4 0.0.0.0' !== -1)) { newSdp = newSdp.replace(/(c=[\w\W]*?(:\r|\n))/, mediaLines[i] + '\r\n'); } else if (mediaLines[i].indexOf('m=audio') !== -1 && (newSdp.indexOf(_constants2.default.SDP.M_LINE + _constants2.default.STRING.AUDIO + ' 1 ') !== -1 || newSdp.indexOf(_constants2.default.SDP.M_LINE + _constants2.default.STRING.AUDIO + ' 9 ') !== -1)) { port = mediaLines[i].split(' ')[1]; newSdp = newSdp.replace(/m=audio \d/, _constants2.default.SDP.M_LINE + _constants2.default.STRING.AUDIO + ' ' + port); } else if (mediaLines[i].indexOf('m=video') !== -1 && (newSdp.indexOf(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' 1 ') !== -1 || newSdp.indexOf(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' 9 ') !== -1)) { port = mediaLines[i].split(' ')[1]; newSdp = newSdp.replace(/m=video \d/, _constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' ' + port); } } return newSdp; }; /* * getSdpFromObject * There is a webrtc bug in Plugin. * sendrecv direction changed to recvonly for offer type sdps * This function is the workaround solution to get the correct sdp from the object * until webrtc bug in plugin is fixed. */ this.getSdpFromObject = function (oSdp) { var sdp; sdp = oSdp.sdp; return sdp; }; /* * deleteGoogleIceFromSdp - delete google-ice option from the sdp */ this.deleteGoogleIceFromSdp = function (sdp) { if (sdp === null || sdp === undefined) { return sdp; } sdp = sdp.replace(/(a=ice-options:google-ice[\w\W]*?(:\r|\n))/g, ''); return sdp; }; this.respondToRemoteSdpDirections = function (localSdp, remoteSdp) { localSdp = this.respondToRemoteMediaSdpDirection(localSdp, remoteSdp, _constants2.default.STRING.AUDIO); localSdp = this.respondToRemoteMediaSdpDirection(localSdp, remoteSdp, _constants2.default.STRING.VIDEO); return localSdp; }; this.respondToRemoteMediaSdpDirection = function (localSdp, remoteSdp, type) { var remoteDirection; if (this.isSdpHas(remoteSdp, type)) { remoteDirection = this.getSdpDirection(remoteSdp, type); if (this.hasZeroConnectionIP(remoteSdp)) { if (remoteDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) { localSdp = this.updateSdpDirection(localSdp, type, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { localSdp = this.updateSdpDirection(localSdp, type, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } else { if (remoteDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY) { logger.debug(type + ' sendonly -> recvonly'); localSdp = this.updateSdpDirection(localSdp, type, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } else if (remoteDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) { logger.debug(type + ' recvonly -> sendonly'); localSdp = this.updateSdpDirection(localSdp, type, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else if (remoteDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) { logger.debug(type + ' sendrecv -> sendrecv'); localSdp = this.updateSdpDirection(localSdp, type, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else if (remoteDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { logger.debug(type + ' inactive -> inactive'); localSdp = this.updateSdpDirection(localSdp, type, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } } return localSdp; }; this.hasCandidates = function (sdp, relayCandidateCycle, relayCandidateConfigCycle) { var audioArray, videoArray, candidateParser; if (this.checkRelayCandidateCollectionTimeout(relayCandidateCycle, relayCandidateConfigCycle)) { return true; } candidateParser = this.getCandidateType(relayCandidateCycle, relayCandidateConfigCycle); if (this.isSdpHasAudio(sdp)) { audioArray = sdp.split('m=audio'); if (audioArray[1].indexOf(candidateParser) === -1) { return false; } else if (this.isSdpHasVideo(sdp) && !this.isVideoSdpDirectionInactive(sdp) && !this.isVideoSdpDirectionRecvonly(sdp)) { videoArray = sdp.split('m=video'); if (videoArray[1].indexOf(candidateParser) === -1) { return false; } else { return true; } } else { return true; } } return false; }; this.getCandidateType = function (relayCandidateCycle, relayCandidateConfigCycle) { var candidateParser; if (relayCandidateCycle) { if (relayCandidateCycle <= relayCandidateConfigCycle) { candidateParser = 'relay'; } else { candidateParser = 'a=candidate'; } } else { candidateParser = 'a=candidate'; } return candidateParser; }; this.checkRelayCandidateCollectionTimeout = function (relayCandidateCycle, relayCandidateConfigCycle) { if (relayCandidateCycle) { if (relayCandidateCycle > relayCandidateConfigCycle) { return true; } } return false; }; // spidr sends both fingerprint and crypto at incoming call to the term side // delete the unnecessary one before setting remote description this.deleteFingerprintOrCrypto = function (sdp, isDtlsEnabled) { if (sdp === null || sdp === undefined) { return sdp; } if (sdp.indexOf('a=crypto:') === -1 || sdp.indexOf('a=fingerprint:') === -1) { return sdp; } sdp = this.deleteCryptoFromSdp(sdp, isDtlsEnabled); sdp = this.deleteFingerprintFromSdp(sdp, isDtlsEnabled); return sdp; }; function addRtpmapForCodec(sdp, payload, rtpmapString) { var audioCodecList; if (sdp === null || sdp === undefined) { return; } audioCodecList = sdp.match(/m=audio [\w\W]*?(\r|\n)/); if (!audioCodecList) { return sdp; } audioCodecList = audioCodecList[0].split(' '); // shift "m=audio" out // shift audio port out // shift RTP/SAVPF out audioCodecList.shift(); audioCodecList.shift(); audioCodecList.shift(); if (audioCodecList.indexOf(payload) === -1) { return sdp; } if (sdp.indexOf(rtpmapString) !== -1) { return sdp; } sdp = sdp.split(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO); sdp[0] = sdp[0] + rtpmapString + lf + nl; if (sdp[1]) { sdp = sdp[0] + _constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + sdp[1]; } else { sdp = sdp[0]; } return sdp; } /* * This is only required for Firefox Native webrtc. * If PCMU exists in codec list but its rtpmap is missing in sdp, * firefox native webrtc does not collect ice canditates. * Scenario: C2C when FF is originating client * (Broker without Transcoder config) */ this.addRtpmapForPCMU = function (sdp) { return addRtpmapForCodec(sdp, '0', 'a=rtpmap:0 PCMU/8000'); }; /* * This is only required for Firefox Native webrtc. * If PCMA exists in codec list but its rtpmap is missing in sdp, * firefox native webrtc does not collect ice canditates. * Scenario: C2C when FF is originating client * (Broker without Transcoder config) */ this.addRtpmapForPCMA = function (sdp) { return addRtpmapForCodec(sdp, '8', 'a=rtpmap:8 PCMA/8000'); }; /* * This is only required for Firefox Native webRTC. * Firefox native adds curly brackets to msid and cname properties(maybe more) * This leads to problem in multi - peer to peer configurated lab. * TODO : Unit test cases should be written */ this.deleteCurlyBracketsSDP = function (sdp) { if (sdp === null || sdp === undefined) { return sdp; } logger.debug('Deleting curly brackets from sdp'); sdp = sdp.replace(/(\{|\})/g, ''); return sdp; }; /* * If inactive video m-line has bandwith attribute in SDP(occurs in Chrome to PCC call), * Chrome's webRTC Engine rejects it * This workaround removes the b:AS line * TODO : Unit test cases should be written */ this.deleteBandwidthLineFromSdp = function (sdp) { if (sdp === null || sdp === undefined) { return sdp; } if (this.isVideoSdpDirectionInactive(sdp)) { logger.debug('Deleting b:AS line from SDP'); sdp = sdp.replace(/(b=AS:[\w\W]*?(:\r|\n))/g, ''); } return sdp; }; /* * Firefox 38.0.1 does not accept uppercase opus codec and cause basic call problem with GCFIOS. * The following is a workaround for this problem. * Feel free to remove it when Firefox 38.0.1 is updated to 38.0.5. */ this.setOpusCodecToLowerCase = function (sdp) { if (sdp === null || sdp === undefined) { return sdp; } logger.debug('Setting OPUS codec to lower case'); return sdp.replace('OPUS', 'opus'); }; /* * Replaces audio m line of codec * @sdp Sdp to be processed * @prevValue previous telephony event value * @newValue new telephony event value * @returns processed SDP */ this.replaceAudioMlineOfCodec = function (sdp, prevValue, newValue) { if (this.isSdpHasAudio(sdp)) { sdp = this.replaceMlineOfCodec(sdp, _constants2.default.STRING.AUDIO, prevValue, newValue); } return sdp; }; /* * Replaces video m line of codec * @sdp Sdp to be processed * @prevValue previous telephony event value * @newValue new telephony event value * @returns processed SDP */ this.replaceVideoMlineOfCodec = function (sdp, prevValue, newValue) { if (this.isSdpHasVideo(sdp)) { sdp = this.replaceMlineOfCodec(sdp, _constants2.default.STRING.VIDEO, prevValue, newValue); } return sdp; }; /* * Replaces m line of codec * @sdp Sdp to be processed * @option m line to be processed * @prevValue previous telephony event value * @newValue new telephony event value * @returns processed SDP */ this.replaceMlineOfCodec = function (sdp, option, prevValue, newValue) { var prevMline, newMline = '', mLineRegex, index; mLineRegex = new RegExp('m=' + option + ' [\\w\\W]*?(\\r|\\n)', 'g'); prevMline = sdp.match(mLineRegex); prevMline = prevMline[0].split(' '); for (index = 0; index < prevMline.length; index++) { // index[1] is actual port and we should not change it. if (index !== 1 && prevMline[index] && prevMline[index].indexOf(prevValue) !== -1) { prevMline[index] = prevMline[index].replace(prevValue, newValue); } // This if check is necessary in order not to put an space at the end of m line if (index === prevMline.length - 1) { newMline += prevMline[index]; } else { newMline += prevMline[index] + ' '; } } return sdp.replace(mLineRegex, newMline); }; /* * Replaces RTPMap of codec * @sdp Sdp to be processed * @prevValue previous telephony event value * @newValue new telephony event value * @returns processed SDP */ this.replaceRTPMapOfCodec = function (sdp, prevValue, newValue) { var regex = new RegExp('a=rtpmap:' + prevValue, 'g'); return sdp.replace(regex, 'a=rtpmap:' + newValue); }; /* * Replaces RTCP of codec * @sdp Sdp to be processed * @prevValue previous telephony event value * @newValue new telephony event value * @returns processed SDP */ this.replaceRTCPOfCodec = function (sdp, prevValue, newValue) { var regex = new RegExp('a=rtcp-fb:' + prevValue, 'g'); return sdp.replace(regex, 'a=rtcp-fb:' + newValue); }; /* * Replaces FMTP of codec * @sdp Sdp to be processed * @prevValue previous telephony event value * @newValue new telephony event value * @returns processed SDP */ this.replaceFMTPOfCodec = function (sdp, prevValue, newValue) { var regex = new RegExp('a=fmtp:' + prevValue, 'g'); return sdp.replace(regex, 'a=fmtp:' + newValue); }; /* * Replaces the codec with new value * @sdp Sdp to be processed * @codec Codec to be replaced * @newValue new value of codec */ this.replaceCodecValue = function (sdp, codec, newValue) { var payloadType, prevValue; payloadType = this.getPayloadTypeOf(codec, sdp); if (payloadType) { // If multiple payload types returned, change first of them if (Array.isArray(payloadType)) { prevValue = payloadType[0]; } else { prevValue = payloadType; } // Since we don't know which m-line contains this codec, we apply in both m-lines // If an m line does not have this codec, then it will simply return the sdp itself sdp = this.replaceAudioMlineOfCodec(sdp, prevValue, newValue); sdp = this.replaceVideoMlineOfCodec(sdp, prevValue, newValue); sdp = this.replaceRTPMapOfCodec(sdp, prevValue, newValue); sdp = this.replaceRTCPOfCodec(sdp, prevValue, newValue); sdp = this.replaceFMTPOfCodec(sdp, prevValue, newValue); } return sdp; }; /* * Replaces codecs * @sdp Sdp to be used * @codecMap codecMap to be replaced * @returns processed SDP */ this.replaceCodecs = function (sdp, codecMap) { var index; if (codecMap && codecMap.length) { for (index = 0; index < codecMap.length; index++) { sdp = this.replaceCodecValue(sdp, codecMap[index].name, codecMap[index].value); } } return sdp; }; /* * Removes H264 codec from SDP * @sdp Sdp to be used * @returns processed SDP */ this.removeH264Codec = function (pSdp) { if (pSdp === null || pSdp === undefined) { return pSdp; } logger.debug('Removing H264 codec from SDP'); var h264PayloadType, index; if (pSdp.indexOf('H264/90000') === -1) { return pSdp; } h264PayloadType = this.getH264PayloadType(pSdp); if (h264PayloadType !== -1) { for (index = 0; index < h264PayloadType.length; index++) { logger.debug('removeH264Codec : Removing H264/90000 video codec ' + h264PayloadType[index]); pSdp = this.removeVideoCodec(pSdp, h264PayloadType[index]); } } return pSdp; }; this.hasZeroConnectionIP = function (pSdp) { if (pSdp === null || pSdp === undefined) { return false; } if (pSdp.indexOf('c=IN IP4 0.0.0.0') !== -1) { return true; } return false; }; this.findZeroConnectionIPandModify = function (pSdp) { var sdp = '', substr = '', descriptions = [], index, type; logger.debug('findZeroConnectionIPandModify received SDP: ' + pSdp); if (pSdp === null || pSdp === undefined) { return pSdp; } descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (this.isSdpHasVideo(substr)) { type = _constants2.default.STRING.VIDEO; } else { type = _constants2.default.STRING.AUDIO; } if (this.hasZeroConnectionIP(substr) && this.getSdpDirection(pSdp, type) !== _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { substr = substr.replace('c=IN IP4 0.0.0.0', 'c=IN IP4 1.1.1.1'); } sdp = sdp + substr; } logger.debug('findZeroConnectionIPandModify updated SDP: ' + sdp); return sdp; }; // this is needed to check // if telephone-event payload changed // fixed scenario: meetme is sending a different TE payload after call setup this.hasCodecPayloadChanged = function (oldSdp, newSdp) { if (!oldSdp || !newSdp) { return false; } if (!this.isSdpHasTelephoneEvent(oldSdp) || !this.isSdpHasTelephoneEvent(newSdp)) { return false; } var oldTEPayloadCodec = this.getPayloadTypeOf('telephone-event/8000', oldSdp), newTEPayloadCodec = this.getPayloadTypeOf('telephone-event/8000', newSdp); return oldTEPayloadCodec !== newTEPayloadCodec; }; this.isVideoHasSsrc = function (sdp) { var mLineRegex = new RegExp('m=[\\w\\W]*?(?=(m=|$))', 'g'), mLines, videoLine, i; if (!sdp) { return false; } mLines = sdp.match(mLineRegex); for (i = 0; i < mLines.length; i++) { if (this.isSdpHasVideo(mLines[i])) { videoLine = mLines[i]; break; } } if (!videoLine) { return false; } if (videoLine.indexOf('ssrc') !== -1) { return true; } return false; }; /* * Checks and replaces APT value. Remove after Chrome 51 release. * @sdp Sdp to be processed * @option m line to be processed * @returns processed SDP */ this.checkandReplaceAPTValue = function (pSdp) { var sdp = '', substr = '', descriptions = [], index, reg = /\r\n|\r|\n/m, substr_arr, i, new_substr = '', elm, option, numOfAPT, APTIndex = 0, mLineRegex, sdpMline, splitArray, APTValue; descriptions = pSdp.split(/^(?=m=)/m); for (index = 0; index < descriptions.length; index++) { substr = descriptions[index]; if (substr.indexOf('apt=') !== -1) { if (this.isSdpHasAudio(substr)) { option = 'audio'; } else if (this.isSdpHasVideo(substr)) { option = 'video'; } numOfAPT = substr.split('apt=').length - 1; mLineRegex = new RegExp('m=' + option + ' [\\w\\W]*?(\\r|\\n)', 'g'); sdpMline = pSdp.match(mLineRegex); sdpMline = sdpMline[0].split(' '); substr_arr = substr.split(reg); for (i = 0; i < substr_arr.length; i++) { elm = substr_arr[i]; if (elm && elm.indexOf('apt=') !== -1) { APTIndex++; splitArray = elm.split('apt='); APTValue = splitArray[1]; for (index = 0; index < sdpMline.length; index++) { // index[1] is actual port and we should not check it. if (index !== 1 && sdpMline[index] && sdpMline[index].indexOf(APTValue) !== -1) { // APT value is found in codec list. Return the original SDP. return pSdp; } } if (APTIndex === numOfAPT) { elm = elm.replace('apt=' + APTValue, 'apt=' + sdpMline[3] + lf + nl); } } else if (elm && elm !== '') { elm = elm + lf + nl; } new_substr = new_substr + elm; } substr = new_substr; } sdp = sdp + substr; } return sdp; }; /* * Checks if trickle is enabled in sdp * @sdp Sdp to be inspected * @returns trickle status */ this.isSdpHasTrickle = function (sdp) { if (!sdp) { return false; } if (sdp.indexOf('a=ice-options:trickle') !== -1) { return true; } return false; }; /* * Checks and sets trickle option in sdp * @sdp Sdp to be processed * @addTrickle Whether the trickle ICE option should be added or removed. * @returns processed SDP */ this.setTrickleOption = function (sdp, addTrickle) { logger.debug('Setting trickle ICE option?: ' + !!addTrickle); if (!sdp) { // No SDP was provided. return sdp; } else if (addTrickle) { // Option should be added. if (this.isSdpHasTrickle(sdp)) { return sdp; } else { logger.debug('Adding trickle ICE option to SDP.'); var descriptions = sdp.split(/^(?=m=)/m); // descriptions will be ['v=0 s=123...', 'm=audio 9 ...'] or // it will be ['v=0 s=123...', 'm=audio 9 ...', 'm=video 9 ...'] if video is enabled // add trickle option before media descriptions into the session description return descriptions[0] + 'a=ice-options:trickle' + lf + nl + descriptions.slice(1).join(''); } } else { // Option should be removed. if (this.isSdpHasTrickle(sdp)) { logger.debug('Removing trickle ICE option from SDP.'); return sdp.replace(/a=ice-options:trickle\r\n/g, ''); } else { return sdp; } } }; /* * Compare the SDP from the current stable remote sdp, with the newly sdp received * @sdp1 the call stable remote sdp * @sdp2 the new sdp that was received * @returns true if the SDP didn't change except for the sendrecv and the session id */ this.compareSDPForEarlyMedia = function (sdp1, sdp2) { var lineIndex = 0, originalLines = sdp1.split('\n'), newLines = sdp2.split('\n'); for (lineIndex; lineIndex < originalLines.length; lineIndex++) { if (originalLines[lineIndex].indexOf('o=') === -1) { if (sdp2.indexOf(originalLines[lineIndex]) === -1) { return false; } } } lineIndex = 0; for (lineIndex; lineIndex < newLines.length; lineIndex++) { if (newLines[lineIndex].indexOf('o=') === -1) { if (sdp1.indexOf(newLines[lineIndex]) === -1 && newLines[lineIndex].trim() !== 'a=sendrecv') { return false; } } } return true; }; this.isRemoteEndFirefox = function (sdp) { if (!sdp) { return false; } return sdp.indexOf('SDPARTA') !== -1; }; } /***/ }), /***/ "../fcs/src/js/turncredentials/module.js": /*!***********************************************!*\ !*** ../fcs/src/js/turncredentials/module.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _turnCredentialsManager = __webpack_require__(/*! ./turnCredentialsManager */ "../fcs/src/js/turncredentials/turnCredentialsManager.js"); exports.default = { TurnCredentialsManager: function TurnCredentialsManager(container) { return new _turnCredentialsManager.TurnCredentialsManagerImpl(container); } }; /***/ }), /***/ "../fcs/src/js/turncredentials/turnCredentialsManager.js": /*!***************************************************************!*\ !*** ../fcs/src/js/turncredentials/turnCredentialsManager.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.TurnCredentialsManagerImpl = TurnCredentialsManagerImpl; var _base = __webpack_require__(/*! ../../lib/base64 */ "../fcs/src/lib/base64.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function TurnCredentialsManagerImpl(_ref) { var _cache = _ref.Cache, _utils = _ref.Utils; var self = this, CREDENTIALS_CACHE_KEY = 'JSL/VHVybkNyZWRlbnRpYWxz'; self.get = function () { return JSON.parse((0, _base.base64_decode)(_cache.getItem(CREDENTIALS_CACHE_KEY))); }; self.save = function (data) { _cache.setItem(CREDENTIALS_CACHE_KEY, (0, _base.base64_encode)((0, _stringify2.default)(data))); _utils.callFunctionIfExist(self.onCredentialsReceived); }; self.remove = function () { _cache.removeItem(CREDENTIALS_CACHE_KEY); }; } /***/ }), /***/ "../fcs/src/js/utils/index.js": /*!************************************!*\ !*** ../fcs/src/js/utils/index.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _promise = __webpack_require__(/*! babel-runtime/core-js/promise */ "../../node_modules/babel-runtime/core-js/promise.js"); var _promise2 = _interopRequireDefault(_promise); exports.getProperty = getProperty; exports.compose = compose; exports.getTimestamp = getTimestamp; exports.parseAddress = parseAddress; exports.getInteger = getInteger; exports.Queue = Queue; exports.serialize = serialize; exports.extend = extend; exports.always = always; exports.Utils = Utils; exports.makeSafeForCSS = makeSafeForCSS; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getProperty(obj, property) { return typeof obj[property] === 'undefined' ? null : obj[property]; } //WARNING: This function probably does not do what you think. function compose(base, extendme) { var prop; for (prop in base) { if (typeof base[prop] === 'function' && !extendme[prop]) { extendme[prop] = base[prop].bind(base); } } } function getTimestamp() { return new Date().getTime(); } function parseAddress(address, contact) { var displayName = ''; if (address.indexOf('sip:', 0) > -1) { address = address.replace('sip:', ''); } if (contact === undefined || contact === null) { return address.indexOf('@', 0) > -1 ? 'sip:' + address : address; } if (contact.firstName && contact.firstName !== '') { displayName += contact.firstName; } if (contact.lastName && contact.lastName !== '') { if (displayName === '') { displayName += contact.lastName; } else { displayName += ' ' + contact.lastName; } } if (displayName === '') { return address.indexOf('@', 0) > -1 ? 'sip:' + address : address; } return displayName + '<' + (address.indexOf('@', 0) > -1 ? 'sip:' + address : address) + '>'; } function getInteger(val) { if (isNaN(val) || val === null || val === undefined) { return 0; } return parseInt(val); } function Queue() { var items; this.enqueue = function (item) { if (typeof items === 'undefined') { items = []; } items.push(item); }; this.dequeue = function () { return items.shift(); }; this.peek = function () { return items[0]; }; this.size = function () { return typeof items === 'undefined' ? 0 : items.length; }; } /* * Similar to http://api.jquery.com/jquery.param/ */ function serialize(object) { var encodedString = '', prop; for (prop in object) { if (object.hasOwnProperty(prop)) { if (encodedString.length > 0) { encodedString += '&'; } encodedString += encodeURI(prop + '=' + object[prop]); } } return encodedString; } function extend(target, object) { var prop; for (prop in object) { if (object.hasOwnProperty(prop)) { target[prop] = object[prop]; } } return target; } /* * Always is a Promise.finally replacement helper. Will call the handler as part of the promise chain without * affecting the result of the promise. * * @param {Promise} promise The promise to attach the finally handler to. * @param {Function} handler A function which will be called when the passed in promise is settled (resolved or rejected) * @return {Promise} The new Promise with the handler attached. */ function always(promise, handler) { return promise.then( // Success path, attach the always handler and then just a continuation of the param. function (param) { return new _promise2.default(function (resolve) { return resolve(handler()); }).then(function () { return param; }); }, // Failure path, attach the always handler and then just a continuation with the re-thrown error. function (error) { return new _promise2.default(function (resolve) { return resolve(handler()); }).then(function () { throw error; }); }); } function Utils(_ref) { var _logManager = _ref.LogManager; var logger; this.callFunctionIfExist = function callFunctionIfExist() { // Get the logger on first usage, instead of on LogManager instantiation. // Avoids dependency issues while testing. if (!logger) { logger = _logManager.getLogger('utils'); } var args = Array.prototype.slice.call(arguments), func; func = args.shift(); if (typeof func === 'function') { try { return func.apply(null, args); } catch (e) { logger.error('Exception occured: ' + e.message + '\n' + e.stack); } } }; } function makeSafeForCSS(name) { if (!name) { return name; } else { return name.replace(/[^a-z0-9]/g, function (s) { var c = s.charCodeAt(0); if (c === 32) { return '-'; } if (c >= 65 && c <= 90) { return '_' + s.toLowerCase(); } return '__' + ('000' + c.toString(16)).slice(-4); }); } } /***/ }), /***/ "../fcs/src/js/utils/map.js": /*!**********************************!*\ !*** ../fcs/src/js/utils/map.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Map; function Map() { var items = {}, length = 0; this.size = function () { return length; }; this.add = function (key, value) { length++; items[key] = value; return this; }; this.get = function (key) { return items[key]; }; this.remove = function (key) { length--; return delete items[key]; }; this.clear = function () { var variableKey; for (variableKey in items) { if (items.hasOwnProperty(variableKey)) { if (delete items[variableKey]) { length--; } } } }; this.entries = function () { return items; }; } /***/ }), /***/ "../fcs/src/js/webrtc/adaptor/module.js": /*!**********************************************!*\ !*** ../fcs/src/js/webrtc/adaptor/module.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _webRtcAdaptor = __webpack_require__(/*! ./webRtcAdaptor */ "../fcs/src/js/webrtc/adaptor/webRtcAdaptor.js"); var _webRtcChromeAdaptor = __webpack_require__(/*! ./webRtcChromeAdaptor */ "../fcs/src/js/webrtc/adaptor/webRtcChromeAdaptor.js"); var _webRtcContainerAdaptor = __webpack_require__(/*! ./webRtcContainerAdaptor */ "../fcs/src/js/webrtc/adaptor/webRtcContainerAdaptor.js"); var _webRtcFirefoxAdaptor = __webpack_require__(/*! ./webRtcFirefoxAdaptor */ "../fcs/src/js/webrtc/adaptor/webRtcFirefoxAdaptor.js"); var _webRtcFirefoxEsrAdaptor = __webpack_require__(/*! ./webRtcFirefoxEsrAdaptor */ "../fcs/src/js/webrtc/adaptor/webRtcFirefoxEsrAdaptor.js"); var _webRtcPluginAdaptor = __webpack_require__(/*! ./webRtcPluginAdaptor */ "../fcs/src/js/webrtc/adaptor/webRtcPluginAdaptor.js"); var _webRtcPluginv22Adaptor = __webpack_require__(/*! ./webRtcPluginv22Adaptor */ "../fcs/src/js/webrtc/adaptor/webRtcPluginv22Adaptor.js"); var _webRtcPluginv31Adaptor = __webpack_require__(/*! ./webRtcPluginv31Adaptor */ "../fcs/src/js/webrtc/adaptor/webRtcPluginv31Adaptor.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { WebRtcAdaptorBaseFactory: function WebRtcAdaptorBaseFactory(container) { return function (decorator, model) { return new _webRtcAdaptor.WebRtcAdaptorImpl((0, _extends3.default)({ decorator: decorator, model: model }, container)); }; }, WebRtcChromeAdaptorFactory: function WebRtcChromeAdaptorFactory(container) { return function (base, decorator, model) { decorator = decorator || container.WebRtcChromeDecoratorFactory; model = model || container.WebRtcChromeAdaptorModelFactory(); base = base || container.WebRtcAdaptorBaseFactory(decorator, model); return new _webRtcChromeAdaptor.WebRtcChromeAdaptorImpl((0, _extends3.default)({ base: base, decorator: decorator, model: model }, container)); }; }, WebRtcContainerAdaptorFactory: function WebRtcContainerAdaptorFactory(container) { return function (base, decorator, model) { decorator = decorator || container.WebRtcChromeDecoratorFactory; model = model || container.WebRtcChromeAdaptorModelFactory(); base = base || container.WebRtcAdaptorBaseFactory(decorator, model); return new _webRtcContainerAdaptor.WebRtcContainerAdaptorImpl((0, _extends3.default)({ base: base, decorator: decorator, model: model }, container)); }; }, WebRtcFirefoxAdaptorFactory: function WebRtcFirefoxAdaptorFactory(container) { return function (base, decorator, model) { decorator = decorator || container.WebRtcFirefoxDecoratorFactory; model = model || container.WebRtcFirefoxAdaptorModelFactory(); base = base || container.WebRtcAdaptorBaseFactory(decorator, model); return new _webRtcFirefoxAdaptor.WebRtcFirefoxAdaptorImpl((0, _extends3.default)({ base: base, decorator: decorator, model: model }, container)); }; }, WebRtcFirefoxEsrAdaptorFactory: function WebRtcFirefoxEsrAdaptorFactory(container) { return function (base, decorator, model) { decorator = decorator || container.WebRtcFirefoxDecoratorFactory; model = model || container.WebRtcFirefoxAdaptorModelFactory(); base = base || container.WebRtcFirefoxAdaptorFactory(undefined, decorator, model); return new _webRtcFirefoxEsrAdaptor.WebRtcFirefoxEsrAdaptorImpl((0, _extends3.default)({ base: base, decorator: decorator, model: model }, container)); }; }, WebRtcPluginAdaptorFactory: function WebRtcPluginAdaptorFactory(container) { return function (base, decorator, model) { decorator = decorator || container.WebRtcDecoratorFactory; model = model || container.WebRtcPluginAdaptorModelFactory(); base = base || container.WebRtcAdaptorBaseFactory(decorator, model); return new _webRtcPluginAdaptor.WebRtcPluginAdaptorImpl((0, _extends3.default)({ base: base, decorator: decorator, model: model }, container)); }; }, WebRtcPluginv22AdaptorFactory: function WebRtcPluginv22AdaptorFactory(container) { return function (base, decorator, model) { decorator = decorator || container.WebRtcDecoratorFactory; model = model || container.WebRtcPluginAdaptorModelFactory(); base = base || container.WebRtcPluginAdaptorFactory(decorator, model); return new _webRtcPluginv22Adaptor.WebRtcPluginv22AdaptorImpl((0, _extends3.default)({ base: base, decorator: decorator, model: model }, container)); }; }, WebRtcPluginv31AdaptorFactory: function WebRtcPluginv31AdaptorFactory(container) { return function (base, decorator, model) { decorator = decorator || container.WebRtcDecoratorFactory; model = model || container.WebRtcPluginAdaptorModelFactory(); base = base || container.WebRtcPluginAdaptorFactory(base, decorator, model); return new _webRtcPluginv31Adaptor.WebRtcPluginv31AdaptorImpl((0, _extends3.default)({ base: base, decorator: decorator, model: model }, container)); }; } }; /***/ }), /***/ "../fcs/src/js/webrtc/adaptor/webRtcAdaptor.js": /*!*****************************************************!*\ !*** ../fcs/src/js/webrtc/adaptor/webRtcAdaptor.js ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.WebRtcAdaptorImpl = WebRtcAdaptorImpl; var _constants = __webpack_require__(/*! ../../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); var _call = __webpack_require__(/*! ../../call/call */ "../fcs/src/js/call/call.js"); var _utils2 = __webpack_require__(/*! ../../utils */ "../fcs/src/js/utils/index.js"); var _errors = __webpack_require__(/*! ../../errors */ "../fcs/src/js/errors.js"); var _errors2 = _interopRequireDefault(_errors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function WebRtcAdaptorImpl(_ref) { var _decorator = _ref.decorator, _model = _ref.model, _logManager = _ref.LogManager, _utils = _ref.Utils, _sdpParser = _ref.SdpParser, _cache = _ref.Cache, _fcs = _ref.Core, _config = _ref.Config, _sdpPipeline = _ref.SdpPipeline; /* * ABE-832: On MAC OS, Safari browser version 6.1 doesn't recognize array * indices of integer type. Therefore, all [0] calls are changed to ["0"]. * All other browser types function correctly with both integer and string * indices. * * Right now, this only affects arrays coming from the plugin. * * That's why we use zero = "0". Using "0" directly didn't work because * minification replaces it with 0. */ var self = this, logger = _logManager.getLogger('WebRtcAdaptorImpl'), zero = '0'; logger.debug('WebRtcAdaptor initializing'); (0, _utils2.compose)(_model, self); self.performSdpWorkaroundsBeforeProcessingIncomingSdp = function (sdp) { sdp = _sdpParser.updateH264LevelTo42E01F(sdp, self.isH264Enabled()); sdp = _sdpParser.deleteBandwidthLineFromSdp(sdp); sdp = _sdpParser.removeG722Codec(sdp); return sdp; }; self.setRemoteDescription = function (operation, call, peer, type, sdp, onSuccess, onFailure) { var remoteDesc; function storeRemoteSdp() { call.stableRemoteSdp = sdp; logger.debug('stored stable remote sdp'); if (typeof onSuccess === 'function') { onSuccess(); } } if (peer) { if (operation) { sdp = _sdpPipeline(call.id, sdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_REMOTE, type); } remoteDesc = self.getRtcLibrary().createRTCSessionDescription(type, sdp); peer.setRemoteDescription(remoteDesc, storeRemoteSdp, onFailure); } else { storeRemoteSdp(); } }; self.isVideoDirectionsSendRecv = function (localSdp, remoteSdp) { return _sdpParser.isVideoSdpDirectionSendrecv(localSdp) && _sdpParser.isVideoSdpDirectionSendrecv(remoteSdp); }; self.isAudioDirectionsSendRecv = function (localSdp, remoteSdp) { return _sdpParser.isAudioSdpDirectionSendrecv(localSdp) && _sdpParser.isAudioSdpDirectionSendrecv(remoteSdp); }; self.isSdpDirectionsSendRecv = function (localSdp, remoteSdp) { var isAudioSdpDirectionsSendRecv = self.isAudioDirectionsSendRecv(localSdp, remoteSdp); if (_sdpParser.isSdpHasVideo(localSdp)) { return isAudioSdpDirectionsSendRecv && self.isVideoDirectionsSendRecv(localSdp, remoteSdp); } return isAudioSdpDirectionsSendRecv; }; self.oldSolutionNeeded = function (oldSdp, newSdp) { var oldVideoLine = _sdpParser.isSdpHasVideo(oldSdp), newVideoLine = _sdpParser.isSdpHasVideo(newSdp), oldSessionId = _sdpParser.getSessionIdFromSdp(oldSdp), newSessionId = _sdpParser.getSessionIdFromSdp(newSdp), telephoneEventPayloadChanged = _sdpParser.hasCodecPayloadChanged(oldSdp, newSdp); logger.debug('telephoneEventPayloadChanged: ' + telephoneEventPayloadChanged + ' session changed: ' + (oldSessionId !== newSessionId) + ' video line changed: ' + (oldVideoLine !== newVideoLine)); if (telephoneEventPayloadChanged || oldSessionId !== newSessionId || oldVideoLine !== newVideoLine) { return true; } else { return false; } }; self.iceCredentialsChanged = function (oldSdp, newSdp) { var oldVideoUfrag = _sdpParser.getICEParams(oldSdp, _constants2.default.SDP.ICE_UFRAG, true), newVideoUfrag = _sdpParser.getICEParams(newSdp, _constants2.default.SDP.ICE_UFRAG, true); logger.debug('ufrag changed: ' + (oldVideoUfrag !== newVideoUfrag)); if (oldVideoUfrag !== newVideoUfrag) { return true; } else { return false; } }; /* * update codecs accordingly */ self.updateCodecs = function (call, oSdp) { oSdp = _sdpParser.replaceCodecs(oSdp, call.codecsToReplace ? call.codecsToReplace : _config.codecsToReplace); oSdp = _sdpParser.updateAudioCodec(oSdp); oSdp = _sdpParser.updateVideoCodec(oSdp); return oSdp; }; /* * Overrides configured codec values with originators value, in this case, webRtc is terminator side */ self.overrideConfiguredCodecValues = function (call, sdp) { var index, newValue; call.codecsToReplace = call.codecsToReplace ? call.codecsToReplace : JSON.parse((0, _stringify2.default)(_config.codecsToReplace)); if (call.codecsToReplace) { for (index = 0; index < call.codecsToReplace.length; index++) { newValue = _sdpParser.getPayloadTypeOf(call.codecsToReplace[index].name, sdp); if (newValue && newValue !== -1) { // getPayloadTypeOf method could return // either array or string // In such case, arrays first element will be used if (Array.isArray(newValue)) { newValue = newValue[0]; } call.codecsToReplace[index].value = newValue; } } } }; //This function is called internally when we make a new call or hold/unhold scenario // Native implementation lies on webRtcAdaptor.js self.addLocalStream = function (internalCall) { var streamUrl, fireEvent = false, isSendingLocalVideo = self.canOriginatorSendLocalVideo(internalCall); if (internalCall.localMedia && internalCall.localMedia.stream) { if (isSendingLocalVideo) { streamUrl = self.getRtcLibrary().getURLFromStream(internalCall.localMedia.stream); if (streamUrl) { if (self.getDefaultVideoContainer()) { fireEvent = self.useDefaultRenderer(streamUrl, true, true); } else if (self.getLocalVideoContainer()) { fireEvent = self.createStreamRenderer(streamUrl, self.getLocalVideoContainer(), { muted: true, video: true, split: true }); } else { internalCall.call.localStreamURL = streamUrl; fireEvent = true; } } } else { if (self.getDefaultVideoContainer()) { if (self.getDefaultVideoContainer().lastElementChild) { self.disposeStreamRenderer(self.getDefaultVideoContainer().lastElementChild); } } else if (self.getLocalVideoContainer()) { self.disposeStreamRenderer(self.getLocalVideoContainer()); } } logger.debug('onLocalStreamAdded: ' + streamUrl); if (fireEvent) { self.fireOnLocalStreamAddedEvent(internalCall, streamUrl); } } }; // Native implementation lies on webRtcAdaptor.js self.fireOnLocalStreamAddedEvent = function (call, streamUrl) { if (call && call.call && call.call.onLocalStreamAdded) { _utils.callFunctionIfExist(call.call.onLocalStreamAdded, streamUrl); } }; self.storeLocalStreamToCall = function (call, localStreamId) { logger.debug('assigning local stream [' + localStreamId + '] to call: ' + call.id); if (call.localMedia) { self.endLocalMedia(call.localMedia); } self.updateLocalStreamToCall(call, localStreamId); }; self.updateLocalStreamToCall = function (call, localStreamId) { call.localMedia = self.getLocalStreamMap().get(localStreamId); }; /* * createNativeReOffer */ self.createReOffer = function (call, onSuccess, onFailure, usePreviousMediaDirection) { var peer = call.peer, localDescObj, localAudioDirection, localVideoDirection, prevLocalSdp = call.stableLocalSdp, deleteVideoStream = false; logger.debug('createReOffer:' + call.id); if (!usePreviousMediaDirection) { deleteVideoStream = !call.initialVideoState && _sdpParser.isSdpHasVideo(call.stableLocalSdp); } //TODO Why does a ReOffer absolutelty needs a new peer? There was no check here if (self.createNewPeerForCall(call, deleteVideoStream)) { peer = call.peer; } peer.createOffer(function createReOfferCreateOfferSuccessCallback(oSdp) { if (usePreviousMediaDirection) { localAudioDirection = _sdpParser.getAudioSdpDirection(prevLocalSdp); oSdp.sdp = _sdpParser.updateAudioSdpDirection(oSdp.sdp, localAudioDirection); localVideoDirection = _sdpParser.getVideoSdpDirection(prevLocalSdp); oSdp.sdp = _sdpParser.updateVideoSdpDirection(oSdp.sdp, localVideoDirection); } oSdp.sdp = _sdpParser.deleteCryptoZeroFromSdp(oSdp.sdp); oSdp.sdp = _sdpParser.removeG722Codec(oSdp.sdp); oSdp.sdp = _sdpParser.deleteCryptoFromSdp(oSdp.sdp, self.isDtlsEnabled()); oSdp.sdp = _sdpParser.updateVersion(prevLocalSdp, oSdp.sdp); oSdp.sdp = self.updateCodecs(call, oSdp.sdp); oSdp.sdp = _sdpParser.updateOpusConfig(oSdp.sdp, _config.opusConfig); oSdp.sdp = _sdpParser.setTrickleOption(oSdp.sdp, _config.trickleIceSupport !== _constants2.default.TRICKLE.NONE); oSdp.sdp = _sdpPipeline(call.id, oSdp.sdp, _constants2.default.WEBRTC.SDP.OPERATION.REOFFER, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); localDescObj = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, oSdp.sdp); logger.trace('createReOffer: Setting local description with (offer) SDP: ' + oSdp.sdp); peer.setLocalDescription(localDescObj, function createReOfferSetLocalDescriptionSuccessCallback() { logger.debug('createReOffer: setLocalDescription success' + call.id); if (_config.trickleIceSupport === _constants2.default.TRICKLE.FULL) { _utils.callFunctionIfExist(onSuccess, oSdp.sdp); } }, function createReOfferSetLocalDescriptionFailureCallback(e) { logger.debug('createReOffer: setLocalDescription failed!!' + e + call.id); _utils.callFunctionIfExist(onFailure); }); }, function createReOfferCreateOfferFailureCallback(e) { logger.error('createReOffer: createOffer failed!! ' + e); _utils.callFunctionIfExist(onFailure); }); }; // Native implementation lies on webRtcAdaptor.js self.getLocalAudioTrack = function (peer) { logger.debug('getLocalAudioTrack'); var audioTracks; if (peer.getSenders) { /** * RTCPeerConnection.getLocalStreams is being deprecated. * Prefer to use RTCPeerConnection.getSenders if present. */ // Retrieve the relevant RTCRtpSender objects. var audioSenders = peer.getSenders().filter(function (sender) { return sender.track.kind === 'audio'; }); // Retrieve the tracks from the audio senders. audioTracks = audioSenders.map(function (sender) { return sender.track; }); if (audioTracks && audioTracks.length > 0) { return audioTracks[0]; } } else if (peer.getLocalStreams) { var streams = peer.getLocalStreams(); if (streams && streams.length > 0) { audioTracks = streams[zero].getAudioTracks(); if (audioTracks && audioTracks.length > 0) { return audioTracks[zero]; } } } return null; }; // Native implementation lies on webRtcAdaptor.js self.getLocalVideoTrack = function (peer) { logger.debug('getLocalVideoTrack'); var streams, videoTracks; if (peer.getSenders) { /** * RTCPeerConnection.getLocalStreams is being deprecated. * Prefer to use RTCPeerConnection.getSenders if present. */ // Retrieve the relevant RTCRtpSender objects. var videoSenders = peer.getSenders().filter(function (sender) { return sender.track.kind === 'video'; }); // Retrieve the tracks from the audio senders. videoTracks = videoSenders.map(function (sender) { return sender.track; }); if (videoTracks && videoTracks.length > 0) { return videoTracks[0]; } } else if (peer.getLocalStreams) { streams = peer.getLocalStreams(); if (streams && streams.length > 0) { videoTracks = streams[zero].getVideoTracks(); if (videoTracks && videoTracks.length > 0) { return videoTracks[zero]; } } } return null; }; self.getRemoteVideoTrack = function (peer) { logger.debug('getRemoteVideoTrack'); var streams; if (peer.getRemoteStreams) { streams = peer.getRemoteStreams(); if (streams && streams[zero]) { return streams[zero].getVideoTracks(); } } return []; }; self.muteAudioTrack = function (call, mute, userAction) { if (!self.isInitialized()) { logger.warn('muteAudioTrack: Plugin is not installed'); return; } if (!call.peer) { return; } if (call.localMedia) { var newMuteState = call.audioMuted; // Mute both the audio gain node and the original track. This will help in some cases // where muting the track doesn't work. if (call.localMedia.audioGain) { logger.info('Setting mute state [' + mute + '] on gain node for call [' + call.id + ']'); call.localMedia.audioGain.gain.value = mute ? 0 : 1; newMuteState = mute; } if (call.localMedia.originalStream) { var audioTracks = call.localMedia.originalStream.getAudioTracks(); var localAudioTrack; if (audioTracks && audioTracks.length > 0) { localAudioTrack = audioTracks[zero]; } if (localAudioTrack) { logger.info('mute Audio Track [' + localAudioTrack.id + '], call [' + call.id + '] mute=' + mute); localAudioTrack.enabled = !mute; newMuteState = mute; } } call.audioMuted = newMuteState; if (userAction) { call.fcsUserAudioMuteState = newMuteState; } } }; self.muteVideoTrack = function (call, mute, userAction) { var localVideoTrack, videoTracks; if (!self.isInitialized()) { logger.warn('muteVideoTrack: Plugin is not installed'); return; } if (!call.peer) { return; } if (call.localMedia && call.localMedia.originalStream) { videoTracks = call.localMedia.originalStream.getVideoTracks(); } if (videoTracks && videoTracks.length > 0) { localVideoTrack = videoTracks[zero]; } if (localVideoTrack) { logger.info('mute Video Track [' + localVideoTrack.id + '], call [' + call.id + '] mute=' + mute); localVideoTrack.enabled = !mute; call.videoMuted = mute; if (userAction) { call.fcsUserVideoMuteState = mute; } } }; self.isAudioMuted = function (call) { if (call && call.audioMuted) { return call.audioMuted; } return false; }; self.restoreMuteStateOfCall = function (call) { var previousMuteStateOfAudio = false, previousMuteStateOfVideo = false; if (!call.peer) { return; } if (call.fcsUserAudioMuteState) { previousMuteStateOfAudio = call.fcsUserAudioMuteState; } if (call.fcsUserVideoMuteState) { previousMuteStateOfVideo = call.fcsUserVideoMuteState; } logger.debug('previous audio mute state of call: ' + previousMuteStateOfAudio); logger.debug('previous video mute state of call: ' + previousMuteStateOfVideo); self.muteAudioTrack(call, previousMuteStateOfAudio); self.muteVideoTrack(call, previousMuteStateOfVideo); }; /* * Native implementation lies on webRtcAdaptor.js * Mutes audio and video tracks (to be used during Hold) * * @ignore * @name rtc.mute * @function * @param {Object} call internalCall * @param {boolean} mute true to mute, false to unmute */ self.muteOnHold = function (call, mute) { self.muteAudioTrack(call, mute); self.muteVideoTrack(call, mute); }; // Native implementation lies on webRtcAdaptor.js // initNativeMedia self.initMedia = function (onSuccess, onFailure, options) { self.setInitialized(true); _decorator(self.getRtcLibrary()); function setMediaSources() { self.getRtcLibrary().checkMediaSourceAvailability(function mediaSourceCallback(mediaSourceInfo) { self.setMediaSources(mediaSourceInfo); }); } self.getRtcLibrary().initScreenSharing(function () { // Regardless of success or error, set the media sources. setMediaSources(); _utils.callFunctionIfExist(onSuccess); }, function (error) { // Regardless of success or error, set the media sources. setMediaSources(); _utils.callFunctionIfExist(onFailure, error); }, options); }; /* * Native implementation lies on webRtcAdaptor.js * performNativeVideoStartWorkaround - term side cannot see orig's video */ self.performVideoStartWorkaround = function (operation, call, onSuccess, onFail) { var peer = call.peer, remoteAudioState, remoteVideoState, localSdp; //disable the workaround by default, as it is not necessairy in current version of Chrome if (!_config.performVideoStartWorkaround) { onSuccess(); return; } if (!_sdpParser.isSdpHasVideo(call.sdp)) { self.setRemoteDescription(operation, call, null, null, call.sdp, onSuccess, onFail); return; } logger.debug('Workaround to play video'); localSdp = call.stableLocalSdp ? call.stableLocalSdp : call.peer.localDescription.sdp; call.sdp = _sdpParser.addSdpMissingCryptoLine(call.sdp); remoteAudioState = _sdpParser.getAudioSdpDirection(call.sdp); remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); call.sdp = _sdpParser.updateAudioSdpDirectionToInactive(call.sdp); call.sdp = _sdpParser.updateVideoSdpDirectionToInactive(call.sdp); //TODO: not sure if needed since we don't do pvwa anymore call.sdp = _sdpParser.setTcpSetupAttribute(call.sdp, 'actpass'); logger.trace('performVideoStartWorkaround: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(null, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function pvswFirstSetRemoteDescriptionSuccessCallback() { logger.debug('performVideoStartWorkaround: first setRemoteDescription success'); // restore original values call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, remoteAudioState); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, remoteVideoState); logger.trace('performVideoStartWorkaround: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(operation, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function pvswSecondSetRemoteDescriptionSuccessCallback() { logger.debug('performVideoStartWorkaround: second setRemoteDescription success'); peer.createAnswer(function pvswCreateAnswerSuccessCallback(obj) { if (remoteAudioState === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { obj.sdp = _sdpParser.updateAudioSdpDirectionToInactive(obj.sdp); } if (remoteVideoState === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { obj.sdp = _sdpParser.updateVideoSdpDirectionToInactive(obj.sdp); } else if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } obj.sdp = _sdpParser.checkAndRestoreICEParams(obj.sdp, call.sdp); //Set role to what we should be obj.sdp = _sdpParser.setTcpSetupAttribute(obj.sdp, call.dtlsRole); obj.sdp = _sdpParser.updateVersion(localSdp, obj.sdp); obj.sdp = _sdpParser.updateOpusConfig(obj.sdp, _config.opusConfig); obj.sdp = _sdpPipeline(call.id, obj.sdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); logger.trace('performVideoStartWorkaround: Setting local description with (answer) SDP: ' + obj.sdp); peer.setLocalDescription(self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, obj.sdp), function pvswSetLocalDescriptionSuccessCallback() { logger.debug('performVideoStartWorkaround: setlocalDescription success'); _utils.callFunctionIfExist(onSuccess); }, function pvswSetLocalDescriptionFailureCallback(e) { logger.debug('performVideoStartWorkaround: setlocalDescription failed!!' + e); _utils.callFunctionIfExist(onFail, 'performVideoStartWorkaround: setlocalDescription failed!!'); }); }, function pvswCreateAnswerFailureCallback(e) { logger.debug('performVideoStartWorkaround: createAnswer failed!! ' + e); _utils.callFunctionIfExist(onFail, 'Session cannot be created'); }); }, function pvswSecondSetRemoteDescriptionFailureCallback(e) { logger.debug('performVideoStartWorkaround: second setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(onFail, 'performVideoStartWorkaround: second setRemoteDescription failed!!'); }); }, function pvswFirstSetRemoteDescriptionFailureCallback(e) { logger.debug('performVideoStartWorkaround: first setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(onFail, 'performVideoStartWorkaround: first setRemoteDescription failed!!'); }); }; self.createAudioContext = function () { window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.oAudioContext || window.msAudioContext; // Only create the audioContext if needed to avoid creating multiple ones as Chrome limits them to 6 if (self.audioContext === undefined || self.audioContext.state !== 'running') { try { self.audioContext = new window.AudioContext(); } catch (e) { logger.debug('Failed to create AudioContext:' + e); } } return self.audioContext; }; /* * Native implementation lies on webRtcAdaptor.js */ self.getUserMedia = function (params) { self.getRtcLibrary().checkMediaSourceAvailability(function mediaSourceCallback(mediaSourceInfo) { var mediaInfo, mediaStreamSource, mediaStreamDestination, constraints = { audio: false, video: false }, localMedia; self.setMediaSources(mediaSourceInfo); if (mediaSourceInfo) { if (!mediaSourceInfo.audioSourceAvailable) { logger.debug('Failed to get access to local media.'); _utils.callFunctionIfExist(params.onFailure, _call.mediaErrors.NOT_FOUND); return; } } var audioContext = self.createAudioContext(); if (!audioContext) { logger.info('Failed to initialize AudioContext.'); _utils.callFunctionIfExist(params.onFailure, _call.mediaErrors.NOT_INITIALIZED); return; } if (self.getVideoSourceAvailable()) { constraints.video = params.options.videoConstraints; } if (self.getAudioSourceAvailable()) { constraints.audio = params.options.audioConstraints; } logger.debug('getUserMedia - constraints: ', constraints); self.getRtcLibrary().getUserMedia(constraints, function getUserMediaSuccessCallback(stream) { var audioGain; mediaStreamDestination = audioContext.createMediaStreamDestination(); if (stream.getAudioTracks() && stream.getAudioTracks()[zero]) { mediaStreamSource = audioContext.createMediaStreamSource(stream); audioGain = audioContext.createGain(); mediaStreamSource.connect(audioGain); audioGain.connect(mediaStreamDestination); } if (stream.getVideoTracks() && stream.getVideoTracks()[zero]) { mediaStreamDestination.stream.addTrack(stream.getVideoTracks()[zero]); } localMedia = { audioContext: audioContext, audioGain: audioGain, mediaStreamDestination: mediaStreamDestination, stream: mediaStreamDestination.stream, mediaStreamSource: mediaStreamSource, mergedSources: {}, originalStream: stream }; self.setLocalMedia(localMedia); self.getLocalStreamMap().add(localMedia.stream.id, localMedia); self.setInitialized(true); mediaInfo = { audio: constraints.audio, video: constraints.video, id: localMedia.stream.id, originalStream: stream, streamURL: self.getRtcLibrary().getURLFromStream(stream) }; logger.debug('user has granted access to local media: ', localMedia); _utils.callFunctionIfExist(params.onSuccess, mediaInfo); }, function getUserMediaFailureCallback(error) { logger.debug('Failed to get access to local media. Error: ', error); _utils.callFunctionIfExist(params.onFailure, _call.mediaErrors.NOT_ALLOWED); }); }); }; self.replaceVideoStream = function (targetStream, sourceStream) { if (targetStream && typeof targetStream.getVideoTracks === 'function') { var targetVideoTracks = targetStream.getVideoTracks(); for (var i = 0; i < targetVideoTracks.length; ++i) { targetStream.removeTrack(targetVideoTracks[i]); } if (sourceStream && typeof sourceStream.getVideoTracks === 'function') { var sourceVideoTracks = sourceStream.getVideoTracks(); if (sourceVideoTracks && sourceVideoTracks.length) { targetStream.addTrack(sourceVideoTracks[zero]); } } } return { id: targetStream.id }; }; self.mergeAudioStream = function (call1, call2) { var remoteStream1, remoteStream2, source1, source2; logger.info('Merging Audio Streams for Calls: ' + call1.id + ' and :' + call2.id); remoteStream1 = call1.peer.getRemoteStreams()[0]; remoteStream2 = call2.peer.getRemoteStreams()[0]; if (typeof remoteStream1 === 'undefined' || typeof remoteStream2 === 'undefined') { logger.debug('Failed to get access to audio media.'); throw _errors2.default.MEDIA_NOT_FOUND; } source1 = call2.localMedia.audioContext.createMediaStreamSource(remoteStream1); source2 = call1.localMedia.audioContext.createMediaStreamSource(remoteStream2); source1.connect(call2.localMedia.mediaStreamDestination); source2.connect(call1.localMedia.mediaStreamDestination); call1.localMedia.mergedSources[call2.id] = source2; call2.localMedia.mergedSources[call1.id] = source1; }; self.unMergeAudioStream = function (call1, call2) { var source1, source2; logger.info('unMerging Audio Streams for Calls: ' + call1.id + ' and :' + call2.id); source2 = call1.localMedia.mergedSources[call2.id]; if (source2) { source2.disconnect(); } delete call1.localMedia.mergedSources[call2.id]; source1 = call2.localMedia.mergedSources[call1.id]; if (source1) { source1.disconnect(); } delete call2.localMedia.mergedSources[call1.id]; }; /* * Native implementation lies on webRtcAdaptor.js */ self.startScreenMedia = function (onSuccess, onFailure, onEnded) { self.getRtcLibrary().checkMediaSourceAvailability(function mediaSourceCallback(mediaSourceInfo) { var video_constraints; self.setMediaSources(mediaSourceInfo); if (self.getScreenSourceAvailable()) { video_constraints = { mandatory: { 'maxFrameRate': self.getScreenFrameRate(), 'maxWidth': self.getScreenWidth(), 'maxHeight': self.getScreenHeight() }, mediaSource: 'screen' }; self.getRtcLibrary().getUserMedia({ video: video_constraints, audio: false }, function (stream) { //TODO: This seems wrong since we are modifying the last stream and not the stream from the call, we should use call.localMedia.stream var mediaInfo = self.replaceVideoStream(self.getLocalMedia().stream, stream), oldStream = self.getScreenStream(); // If there is an old screen stream, just stop it but prevent the stop from happening if (oldStream) { oldStream.getVideoTracks()[0].onended = null; self.getRtcLibrary().stopStream(oldStream); } stream.getVideoTracks()[0].onended = onEnded; self.setScreenStream(stream); logger.debug('user granted access to local media.'); _utils.callFunctionIfExist(onSuccess, mediaInfo); }, function () { logger.debug('Failed to get access to screen media.'); _utils.callFunctionIfExist(onFailure, _call.mediaErrors.NOT_ALLOWED); }, onEnded); } else { _utils.callFunctionIfExist(onFailure, _call.mediaErrors.NOT_FOUND); } }); }; self.stopScreenMedia = function () { var screenStream = self.getScreenStream(); //TODO: This seems wrong since we are modifying the last stream and not the stream from the call, we should use call.localMedia.stream and call.localMedia.originalStream self.replaceVideoStream(self.getLocalMedia().stream, self.getLocalMedia().originalStream); if (screenStream) { self.getRtcLibrary().stopStream(screenStream); self.setScreenStream(null); } }; self.createDataChannelOffer = function (call, successCallback, failureCallback) { logger.debug('createDataChannelOffer: state= ' + call.peer.signalingState); var peer = call.peer, localDesc; peer.createOffer(function (oSdp) { oSdp.sdp = _sdpPipeline(call.id, oSdp.sdp, _constants2.default.WEBRTC.SDP.OPERATION.DATA_CHANNEL, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); localDesc = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, oSdp.sdp); logger.trace('createDataChannelOffer: Setting local description with (offer) SDP: ' + oSdp.sdp); peer.setLocalDescription(localDesc, function () { //Due to stun requests, successCallback will be called by onIceCandidate() }, function (error) { logger.error('createDataChannelOffer: setLocalDescription failed : ' + error); _utils.callFunctionIfExist(failureCallback, 'createDataChannelOffer: setLocalDescription failed'); }); }, function (e) { logger.error('createDataChannelOffer: createOffer failed!! ' + e); _utils.callFunctionIfExist(failureCallback); }); }; self.createDataChannelAnswer = function (call, successCallback, failureCallback) { logger.debug('createDataChannelAnswer: state= ' + call.peer.signalingState); var peer = call.peer, remoteDesc, localDesc; call.sdp = _sdpPipeline(call.id, call.sdp, _constants2.default.WEBRTC.SDP.OPERATION.DATA_CHANNEL, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_REMOTE, _constants2.default.WEBRTC.SDP.TYPE.OFFER); remoteDesc = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp); peer.setRemoteDescription(remoteDesc, function () { peer.createAnswer(function (oSdp) { oSdp.sdp = _sdpPipeline(call.id, oSdp.sdp, _constants2.default.WEBRTC.SDP.OPERATION.DATA_CHANNEL, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); localDesc = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, oSdp.sdp); logger.trace('createDataChannelAnswer: Setting local description with (answer) SDP: ' + oSdp.sdp); peer.setLocalDescription(localDesc, function () { //Due to stun requests, successCallback will be called by onIceCandidate() }, function (e) { logger.error('createDataChannelAnswer: setLocalDescription failed : ' + e); _utils.callFunctionIfExist(failureCallback, 'createDataChannelAnswer setLocalDescription failed'); }); }, function (e) { logger.error('createDataChannelAnswer: failed!! Error: ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function (e) { logger.error('createDataChannelAnswer: setRemoteDescription failed!! Error: ' + e); }); }; self.processDataChannelAnswer = function (call, successCallback, failureCallback) { logger.debug('processDataChannelAnswer: state= ' + call.peer.signalingState); var peer = call.peer, remoteDesc; call.sdp = _sdpPipeline(call.id, call.sdp, _constants2.default.WEBRTC.SDP.OPERATION.DATA_CHANNEL, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_REMOTE, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); remoteDesc = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp); peer.setRemoteDescription(remoteDesc, function () { logger.debug('processDataChannelAnswer: setRemoteDescription success'); _utils.callFunctionIfExist(successCallback); }, function (e) { logger.error('processDataChannelAnswer: setRemoteDescription failed: ' + e); _utils.callFunctionIfExist(failureCallback); }); }; // createNativeOffer, Native implementation lies on webRtcAdaptor.js self.createOffer = function (call, successCallback, failureCallback, sendInitialVideo, offerToReceiveVideo, isAnswer) { logger.debug('createOffer: sendInitialVideo= ' + sendInitialVideo + ' state= ' + call.peer.signalingState); var peer = call.peer; if (call.localMedia && call.localMedia.stream) { call.peer.addStream(call.localMedia.stream); } peer.createOffer(function createOfferSuccessCallback(oSdp) { sendInitialVideo = sendInitialVideo && self.getVideoSourceAvailable(); if (sendInitialVideo) { oSdp.sdp = _sdpParser.updateVideoSdpDirection(oSdp.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { oSdp.sdp = _sdpParser.updateVideoSdpDirection(oSdp.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } oSdp.sdp = _sdpParser.deleteCryptoZeroFromSdp(oSdp.sdp); oSdp.sdp = _sdpParser.removeG722Codec(oSdp.sdp); oSdp.sdp = _sdpParser.deleteCryptoFromSdp(oSdp.sdp, self.isDtlsEnabled()); oSdp.sdp = self.updateCodecs(call, oSdp.sdp); oSdp.sdp = _sdpParser.updateOpusConfig(oSdp.sdp, _config.opusConfig); oSdp.sdp = _sdpParser.setTrickleOption(oSdp.sdp, _config.trickleIceSupport !== _constants2.default.TRICKLE.NONE); // If it was specified that this SDP operation is a call answer operation, then // provide that to the SDP pipeline. This occurs during slow start scenarios, // but createOffer is most often a call start operation. var operation = isAnswer ? _constants2.default.WEBRTC.SDP.OPERATION.ANSWER_CALL : _constants2.default.WEBRTC.SDP.OPERATION.START_CALL; oSdp.sdp = _sdpPipeline(call.id, oSdp.sdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); logger.trace('createOffer: Setting local description with (offer) SDP: ' + oSdp.sdp); peer.setLocalDescription(self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, oSdp.sdp), function createOfferSetLocalDescriptionSuccessCallback() { if (_config.trickleIceSupport === _constants2.default.TRICKLE.FULL) { _utils.callFunctionIfExist(successCallback, oSdp.sdp); } // ELSE due to stun requests, successCallback will be called by onIceCandidate() }, function createOfferSetLocalDescriptionFailureCallback(error) { logger.error('createOffer: setLocalDescription failed : ' + error); _utils.callFunctionIfExist(failureCallback, 'createOffer: setLocalDescription failed'); }); }, function createOfferFailureCallback(e) { logger.error('createOffer: createOffer failed!! ' + e); _utils.callFunctionIfExist(failureCallback); }, { offerToReceiveVideo: offerToReceiveVideo ? 1 : 0 }); }; /* * Native implementation lies on webRtcAdaptor.js * createNativeAnswer to be used when native webrtc is enabled. * @param {type} call * @param {type} successCallback * @param {type} failureCallback * @param {type} isVideoEnabled */ self.createAnswer = function (call, successCallback, failureCallback, isVideoEnabled) { logger.debug('createAnswer: isVideoEnabled = ' + isVideoEnabled + ', state= ' + call.peer.signalingState); var peer = call.peer; call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); if (call.localMedia && call.localMedia.stream) { call.peer.addStream(call.localMedia.stream); } call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, null, self.isH264Enabled()); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); call.sdp = _sdpParser.deleteFingerprintOrCrypto(call.sdp, self.isDtlsEnabled()); logger.trace('createAnswer: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.ANSWER_CALL, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function createAnswerSetRemoteDescriptionSuccessCallback() { call.remoteVideoState = _sdpParser.getSdpDirection(call.sdp, _constants2.default.STRING.VIDEO); peer.createAnswer(function (oSdp) { isVideoEnabled = isVideoEnabled && self.getVideoSourceAvailable() && _sdpParser.isSdpHasVideo(call.sdp); oSdp.sdp = _sdpParser.updateOpusConfig(oSdp.sdp, _config.opusConfig); if (isVideoEnabled) { if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { oSdp.sdp = _sdpParser.updateSdpDirection(oSdp.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { if (_sdpParser.getVideoSdpDirection(call.sdp) !== _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { oSdp.sdp = _sdpParser.updateSdpDirection(oSdp.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { oSdp.sdp = _sdpParser.updateSdpDirection(oSdp.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } } else { if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { oSdp.sdp = _sdpParser.updateSdpDirection(oSdp.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } else { oSdp.sdp = _sdpParser.updateSdpDirection(oSdp.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } self.muteOnHold(call, false); // createAnswer generates an sdp without ice params // copy ice params to the local sdp // scenario: incoming video call from pcc in brokeronly config oSdp.sdp = _sdpParser.checkAndRestoreICEParams(oSdp.sdp, call.sdp); oSdp.sdp = _sdpParser.setTrickleOption(oSdp.sdp, _config.trickleIceSupport !== _constants2.default.TRICKLE.NONE); oSdp.sdp = _sdpPipeline(call.id, oSdp.sdp, _constants2.default.WEBRTC.SDP.OPERATION.ANSWER_CALL, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); logger.trace('createAnswer: Setting local description with (answer) SDP: ' + oSdp.sdp); peer.setLocalDescription(self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, oSdp.sdp), function createAnswerSetLocalDescriptionSuccessCallback() { if (_config.trickleIceSupport !== _constants2.default.TRICKLE.NONE && call.supportTrickle) { _utils.callFunctionIfExist(successCallback, oSdp.sdp); } // ELSE due to stun requests, successCallback will be called by onIceCandidate() }, function createAnswerSetLocalDescriptionFailureCallback(e) { logger.error('createAnswer: setLocalDescription failed : ' + e); _utils.callFunctionIfExist(failureCallback, 'createNativeAnswer setLocalDescription failed'); }); }, function createAnswerFailureCallback(e) { logger.error('createAnswer: failed!! Error: ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function createAnswerSetRemoteDescriptionFailureCallback(e) { logger.error('createAnswer: setremotedescription failed!! Error: ' + e); _utils.callFunctionIfExist(failureCallback, 'createAnswer setRemoteDescription failed'); }); }; /* * Native implementation lies on webRtcAdaptor.js * createNativeUpdate to be used when the video start or stop */ self.createUpdate = function (call, successCallback, failureCallback, isVideoStart) { logger.debug('createUpdate: isVideoStart= ' + isVideoStart + ' state= ' + call.peer.signalingState); var peer, localDesc, localSdp = call.stableLocalSdp; if (self.needNewPeer(call, true)) { self.createNewPeerForCall(call); } peer = call.peer; self.getRtcLibrary().updateStream(peer, call); peer.createOffer(function createUpdateCreateOfferSuccessCallback(obj) { isVideoStart = isVideoStart && self.getVideoSourceAvailable(); if (isVideoStart) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { if (_sdpParser.isVideoSdpDirectionInactive(call.stableRemoteSdp)) { obj.sdp = _sdpParser.updateVideoSdpDirectionToInactive(obj.sdp); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } obj.sdp = self.updateCodecs(call, obj.sdp); obj.sdp = _sdpParser.updateVersion(localSdp, obj.sdp); obj.sdp = _sdpParser.deleteCryptoZeroFromSdp(obj.sdp); obj.sdp = _sdpParser.removeG722Codec(obj.sdp); obj.sdp = _sdpParser.deleteCryptoFromSdp(obj.sdp, self.isDtlsEnabled()); obj.sdp = _sdpParser.updateOpusConfig(obj.sdp, _config.opusConfig); obj.sdp = _sdpParser.setTrickleOption(obj.sdp, call.supportTrickle); obj.sdp = _sdpPipeline(call.id, obj.sdp, _constants2.default.WEBRTC.SDP.OPERATION.UPDATE, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); localDesc = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, obj.sdp); var createUpdateCreateOfferSetLocalDescriptionSuccessCallback = function createUpdateCreateOfferSetLocalDescriptionSuccessCallback() { logger.debug('createUpdate setLocalDescription success. iceConnectionState: ' + peer.iceConnectionState + ' iceGatheringState: ' + peer.iceGatheringState); // The above process un-mutes the client. We must ensure it continues to be muted if necessary. if (call.audioMuted) { logger.debug('video started while muted, re-mute the microphone'); self.muteAudioTrack(call, true, false); } if (call.supportTrickle) { logger.debug('Call supports Trickle ice not waiting for candidates'); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } else if (peer.iceGatheringState === 'complete') { if (call.successCallback) { logger.debug('createUpdate iceGatheringState completed ' + peer.localDescription.sdp); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } } }; logger.trace('createUpdate: Setting local description with (offer) SDP: ' + obj.sdp); peer.setLocalDescription(localDesc, function () { // This is a workaround to prevent an issue with ordering of events in Chrome // We add a delay so that the iceGatheringState reflects the real state. // https://bugs.chromium.org/p/webrtc/issues/detail?id=1873 setTimeout(createUpdateCreateOfferSetLocalDescriptionSuccessCallback, 10); }, function crateUpdateCreateOfferSetLocalDescriptionFailureCallback(e) { logger.debug('createUpdate: createOffer setLocalDescription failed: ' + e); _utils.callFunctionIfExist(failureCallback); }); }, function createUpdateCrateOfferFailureCallback(e) { logger.debug('createUpdate: createOffer failed!!: ' + e); failureCallback(); }); }; /* * Reverts RTC engine's state */ self.revertRtcState = function (call, successCallback, failureCallback) { var peer = call.peer, obj, localSdp = call.stableLocalSdp, remoteSdp = call.stableRemoteSdp, rtcState = peer.signalingState; remoteSdp = _sdpParser.deleteGoogleIceFromSdp(remoteSdp); switch (rtcState) { case _constants2.default.WEBRTC.RTC_SIGNALING_STATE.STABLE: case _constants2.default.WEBRTC.RTC_SIGNALING_STATE.HAVE_LOCAL_OFFER: //TODO what should we do here? localSdp = _sdpParser.setTcpSetupAttribute(localSdp, 'actpass'); obj = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, localSdp); logger.trace('revertRtcState[stable|local_offer]: Setting local description with (offer) SDP: ' + localSdp); peer.setLocalDescription(obj, function revertRtcStateLocalDescriptionSuccessCallback() { logger.debug('revertRtcState[stable|local_offer]: setLocalDescription success'); //TODO what should we do here? that seems to be the only place where the remoteTcpSetupAttribute is used. // it seems would so use the stable remote sdp to lookup or the stable local //remoteSdp = _sdpParser.setTcpSetupAttribute(remoteSdp, call.remoteTcpSetupAttribute); logger.trace('revertRtcState[stable|local_offer]: Setting remote description with (answer) SDP: ' + remoteSdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.REVERT_RTC_STATE, call, peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, remoteSdp, function revertRtcStateRemoteDescriptionSuccessCallback() { logger.debug('revertRtcState[stable|local_offer]: setRemoteDescription success'); if (peer.iceGatheringState === 'complete') { _utils.callFunctionIfExist(successCallback); } }, function revertRtcStateRemoteDescriptionFailureCallback(error) { logger.error('revertRtcState[stable|local_offer]: setRemoteDescription failed: ' + error); _utils.callFunctionIfExist(failureCallback, call); }); }, function revertRtcStateLocalDescriptionFailureCallback(error) { logger.error('revertRtcState[stable|local_offer]: setLocalDescription failed: ' + error); _utils.callFunctionIfExist(failureCallback, call); }); break; case _constants2.default.WEBRTC.RTC_SIGNALING_STATE.HAVE_REMOTE_OFFER: //TODO what should we do here? remoteSdp = _sdpParser.setTcpSetupAttribute(remoteSdp, 'actpass'); logger.trace('revertRtcState[remote_offer]: Setting remote description with (offer) SDP: ' + remoteSdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.REVERT_RTC_STATE, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, remoteSdp, function revertRtcStateRemoteDescriptionSuccessCallback() { logger.debug('revertRtcState[remote_offer]: setRemoteDescription success'); //TODO what should we do here? localSdp = _sdpParser.setTcpSetupAttribute(localSdp, call.dtlsRole); obj = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, localSdp); logger.trace('revertRtcState[remote_offer]: Setting local description with (answer) SDP: ' + localSdp); peer.setLocalDescription(obj, function revertRtcStateLocalDescriptionSuccessCallback() { logger.debug('revertRtcState[remote_offer]: setLocalDescription success'); if (peer.iceGatheringState === 'complete') { _utils.callFunctionIfExist(successCallback); } }, function revertRtcStateLocalDescriptionFailureCallback(error) { logger.error('revertRtcState[remote_offer]: setRemoteDescription failed: ' + error); _utils.callFunctionIfExist(failureCallback, call); }); }, function revertRtcStateRemoteDescriptionFailureCallback(error) { logger.error('revertRtcState[remote_offer]: setLocalDescription failed: ' + error); _utils.callFunctionIfExist(failureCallback, call); }); break; default: logger.debug('revertRtcState: not applicible for state: ' + rtcState); } }; /* * Native implementation lies on webRtcAdaptor.js * createNativeHoldUpdate to be used when native webrtc is enabled */ self.createHoldUpdate = function (call, hold, remote_hold_status, successCallback, failureCallback) { logger.debug('createHoldUpdate: local hold= ' + hold + ' remote hold= ' + remote_hold_status + ' state= ' + call.peer.signalingState); var peer, localDescObj, localSdp; var operation = hold ? _constants2.default.WEBRTC.SDP.OPERATION.HOLD : _constants2.default.WEBRTC.SDP.OPERATION.UNHOLD; localSdp = call.stableLocalSdp; if (self.needNewPeer(call, true)) { self.createNewPeerForCall(call); } peer = call.peer; peer.createOffer(function createHoldUpdateCreateOfferSuccessCallback(obj) { if (hold) { if (!remote_hold_status) { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateAudioSdpDirectionToInactive(obj.sdp); obj.sdp = _sdpParser.updateVideoSdpDirectionToInactive(obj.sdp); } } else if (remote_hold_status) { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } obj.sdp = self.updateCodecs(call, obj.sdp); obj.sdp = _sdpParser.updateVersion(localSdp, obj.sdp); obj.sdp = _sdpParser.deleteCryptoZeroFromSdp(obj.sdp); obj.sdp = _sdpParser.updateOpusConfig(obj.sdp, _config.opusConfig); //ABE-11044 workaround. Remove after Chrome 51 release. obj.sdp = _sdpParser.checkandReplaceAPTValue(obj.sdp); obj.sdp = _sdpParser.setTrickleOption(obj.sdp, call.supportTrickle); obj.sdp = _sdpPipeline(call.id, obj.sdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); localDescObj = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, obj.sdp); logger.trace('createHoldUpdate: Setting local description with (offer) SDP: ' + obj.sdp); peer.setLocalDescription(localDescObj, function createHoldUpdateSetLocalDescriptionSuccessCallback() { logger.debug('createHoldUpdate setLocalDescription success. iceConnectionState: ' + peer.iceConnectionState + ' iceGatheringState: ' + peer.iceGatheringState); if (call.supportTrickle) { _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } else if (peer.iceGatheringState === 'complete') { if (call.successCallback) { logger.debug('createHoldUpdate iceGatheringState completed ' + peer.localDescription.sdp); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } } }, function createHoldUpdateSetLocalDescriptionFailureCallback(error) { logger.error('createHoldUpdate: setLocalDescription failed: ' + error.message); _utils.callFunctionIfExist(failureCallback); }); }, function createHoldUpdateCreateOfferFailureCallback(error) { logger.error('createHoldUpdate: createOffer failed: ' + error.message); _utils.callFunctionIfExist(failureCallback); }); }; // Native implementation lies on webRtcAdaptor.js // processNativeHold self.processHold = function (call, hold, local_hold_status, successCallback, failureCallback) { logger.debug('processHold: local hold= ' + local_hold_status + ' remote hold= ' + hold + ' state= ' + call.peer.signalingState); var peer, audioDirection, videoDirection, peerLocalSdp, inactiveRemoteSdp, remoteSdp; peerLocalSdp = call.stableLocalSdp; var operation = hold ? _constants2.default.WEBRTC.SDP.OPERATION.HOLD : _constants2.default.WEBRTC.SDP.OPERATION.UNHOLD; call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); audioDirection = _sdpParser.getAudioSdpDirection(call.sdp); videoDirection = _sdpParser.getVideoSdpDirection(call.sdp); if (!local_hold_status && !hold) { self.muteOnHold(call, false); } //we need to do something in this case because the remove might offer active or passive but chrome does not allow that call.sdp = _sdpParser.setTcpSetupAttribute(call.sdp, 'actpass'); // This is required for PCC and meetme with video. // PCC and meetme(Media Server) not supperted VP8/VP9 codec. // so video calls can not be established // local video should be set to false if (!_sdpParser.isVideoCodecsSupported(call.sdp, self.isH264Enabled()) && !_sdpParser.isSdpHasVP8Codec(call.sdp) && call.sdp.indexOf(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' 0 ', 0) === -1) { self.setOriginatorSendLocalVideo(call, call.sdp, false); } call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, null, self.isH264Enabled()); call.sdp = _sdpParser.performVideoPortZeroWorkaround(call.sdp); call.sdp = _sdpParser.checkAndRestoreICEParams(call.sdp, peerLocalSdp); // chrome38 fix inactiveRemoteSdp = _sdpParser.updateAudioSdpDirectionToInactive(call.sdp); inactiveRemoteSdp = _sdpParser.updateVideoSdpDirectionToInactive(inactiveRemoteSdp); if (self.needNewPeer(call, true, true)) { self.createNewPeerForCall(call); } peer = call.peer; if (_sdpParser.isSdpHasVideo(call.prevRemoteSdp) && !_sdpParser.isSdpHasVideo(call.sdp)) { self.setOriginatorSendLocalVideo(call, call.sdp, false); } // 1st setRemoteDescription to make webrtc remove the audio and/or video streams // 2nd setRemote will add the audio stream back so that services like MOH can work // This code will also run in UnHold scenario, and it will remove & add video stream logger.trace('processHold: Setting remote description with (offer) SDP: ' + inactiveRemoteSdp); self.setRemoteDescription(null, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, inactiveRemoteSdp, function processHoldSetFirstRemoteDescriptionSuccessCallback() { remoteSdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); logger.trace('processHold: Setting remote description with (offer) SDP: ' + remoteSdp); self.setRemoteDescription(operation, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, remoteSdp, function processHoldSetSecondRemoteDescriptionSuccessCallback() { if (!hold && !local_hold_status && videoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { call.remoteVideoState = _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY; } else { call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); } peer.createAnswer(function processHoldCreateAnswerSuccessCallback(obj) { logger.debug('processHold: isSdpEnabled audio= ' + _sdpParser.isAudioSdpEnabled(obj.sdp)); logger.debug('processHold: isSdpEnabled video= ' + _sdpParser.isVideoSdpEnabled(obj.sdp)); if (hold) { logger.debug('processHold: Remote HOLD'); obj.sdp = _sdpParser.respondToRemoteSdpDirections(obj.sdp, call.sdp); } else if (!local_hold_status) { logger.debug('processHold: Remote UNHOLD: direction left as it is'); if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } else { if (self.canOriginatorSendLocalVideo(call) && !_sdpParser.isVideoSdpDirectionInactive(call.sdp)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } //change audio's direction to sendrecv for ssl attendees in a 3wc obj.sdp = _sdpParser.changeDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); } else if (local_hold_status && !hold) { logger.debug('processHold: Remote UNHOLD on local hold'); if (audioDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { obj.sdp = _sdpParser.updateAudioSdpDirectionToInactive(obj.sdp); } else { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateVideoSdpDirectionToInactive(obj.sdp); } } obj.sdp = _sdpParser.updateOpusConfig(obj.sdp, _config.opusConfig); obj.sdp = _sdpParser.updateVersion(peerLocalSdp, obj.sdp); obj.sdp = _sdpParser.checkIceParamsLengths(obj.sdp, call.sdp); obj.sdp = _sdpParser.checkAndRestoreICEParams(obj.sdp, call.sdp); if (_sdpParser.isSdpHasVideoWithZeroPort(obj.sdp) && self.getDefaultVideoContainer()) { self.useDefaultRenderer(false, false, false); } //This one is important because the remote party might have offered pasive or active, but we had set it to actpass so that chrome works. obj.sdp = _sdpParser.setTcpSetupAttribute(obj.sdp, call.dtlsRole); obj.sdp = _sdpParser.setTrickleOption(obj.sdp, call.supportTrickle); logger.trace('processHold: Setting local description with SDP: ' + obj.sdp); obj.sdp = _sdpPipeline(call.id, obj.sdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); peer.setLocalDescription(obj, function processHoldSetLocalDescriptionSuccessCallback() { logger.debug('processHold: setLocalDescription success!! ' + 'iceConnectionState: ' + peer.iceConnectionState + ' iceGatheringState: ' + peer.iceGatheringState); if (call.supportTrickle) { _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } else if (peer.iceGatheringState === 'complete') { if (call.successCallback) { logger.debug('processHold iceGatheringState completed ' + peer.localDescription.sdp); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } } }, function processHoldSetLocalDescriptionFailureCallback(e) { logger.error('processHold: setLocalDescription failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processHoldCreateAnswerFailureCallback(e) { logger.error('processHold: createAnswer failed!!: ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processHoldSetSecondRemoteDescriptionFailureCallback(e) { logger.error('processHold: second setRemoteDescription failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processHoldSetFirstRemoteDescriptionFailureCallback(e) { logger.debug('processHold: first setRemoteDescription failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }; // Native implementation lies on webRtcAdaptor.js // processNativeUpdate self.processUpdate = function (call, successCallback, failureCallback) { logger.debug('processUpdate: state= ' + call.peer.signalingState); var peer, remoteAudioState, remoteVideoState, remoteVideoDirection, localDescObj, peerLocalSdp; peerLocalSdp = call.stableLocalSdp; call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); // Meetme workaround call.sdp = _sdpParser.addSdpMissingCryptoLine(call.sdp); call.sdp = _sdpParser.checkAndRestoreICEParams(call.sdp, peerLocalSdp); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); if (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE && call.currentState === 'COMPLETED') { switch (call.remoteVideoState) { case _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE: case _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY: call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); break; case _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE: call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); break; } } call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.VIDEO); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, null, self.isH264Enabled()); //this part is a work-around for webrtc bug //set remote description with inactive media lines first. //then set remote description with original media lines. //keep original values of remote audio and video states remoteAudioState = _sdpParser.getAudioSdpDirection(call.sdp); remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); if (self.needNewPeer(call, true, true)) { self.createNewPeerForCall(call); } peer = call.peer; //Since Chrome does not support offer with anything else than actpass, we need to set it. call.sdp = _sdpParser.setTcpSetupAttribute(call.sdp, 'actpass'); //set media lines with inactive state for workaround call.sdp = _sdpParser.updateAudioSdpDirectionToInactive(call.sdp); call.sdp = _sdpParser.updateVideoSdpDirectionToInactive(call.sdp); logger.trace('processUpdate: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(null, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function processUpdateWorkaroundSetRemoteDescriptionSuccessCallback() { logger.debug('processUpdate: workaround setRemoteDescription success'); //restore original values call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, remoteAudioState); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, remoteVideoState); logger.trace('processUpdate: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.UPDATE, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function processUpdateSetRemoteDescriptionSuccessCallback() { logger.debug('processUpdate: setRemoteDescription success'); call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); peer.createAnswer(function processUpdateCreateAnswerSuccessCallback(obj) { logger.debug('processUpdate: isSdpEnabled audio= ' + _sdpParser.isAudioSdpEnabled(obj.sdp)); logger.debug('processUpdate: isSdpEnabled video= ' + _sdpParser.isVideoSdpEnabled(obj.sdp)); if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } else { if (self.canOriginatorSendLocalVideo(call) && !_sdpParser.isVideoSdpDirectionInactive(call.sdp)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } obj.sdp = _sdpParser.updateVersion(peerLocalSdp, obj.sdp); obj.sdp = _sdpParser.checkIceParamsLengths(obj.sdp, call.sdp); //This is important because we changed the remote role to actpass for chrome. obj.sdp = _sdpParser.setTcpSetupAttribute(obj.sdp, call.dtlsRole); obj.sdp = _sdpParser.updateOpusConfig(obj.sdp, _config.opusConfig); obj.sdp = _sdpParser.setTrickleOption(obj.sdp, call.supportTrickle); obj.sdp = _sdpPipeline(call.id, obj.sdp, _constants2.default.WEBRTC.SDP.OPERATION.UPDATE, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); localDescObj = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, obj.sdp); var processUpdateSetLocalDescriptionSuccessCallback = function processUpdateSetLocalDescriptionSuccessCallback() { logger.debug('processUpdate setLocalDescription success. iceConnectionState: ' + peer.iceConnectionState + ' iceGatheringState: ' + peer.iceGatheringState); if (call.supportTrickle) { _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } else if (peer.iceGatheringState === 'complete') { if (call.successCallback) { logger.debug('processUpdate iceGatheringState completed ' + peer.localDescription.sdp); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } } }; logger.trace('processUpdate: Setting local description with (answer) SDP: ' + obj.sdp); peer.setLocalDescription(localDescObj, function () { // This is a workaround to prevent an issue with ordering of events in Chrome // We add a delay so that the iceGatheringState reflects the real state. // https://bugs.chromium.org/p/webrtc/issues/detail?id=1873 setTimeout(processUpdateSetLocalDescriptionSuccessCallback, 10); }, function processUpdateSetLocalDescriptionSuccessCallback(e) { logger.debug('processUpdate: setlocalDescription failed!!' + e); _utils.callFunctionIfExist(failureCallback, 'processUpdate: setlocalDescription failed!!'); }); }, function processUpdateCreateAnswerFailureCallback(e) { logger.debug('processUpdate: createAnswer failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processUpdateSetRemoteDescriptionSuccessCallback(e) { logger.debug('processUpdate: setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(failureCallback, 'processUpdate: setRemoteDescription failed!!'); }); }, function processUpdateWorkaroundSetRemoteDescriptionSuccessCallback(e) { logger.debug('processUpdate: workaround setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(failureCallback, 'processUpdate: workaround setRemoteDescription failed!!'); }); }; // Native implementation lies on webRtcAdaptor.js // processNativeAnswer self.processAnswer = function (call, onSuccess, onFail, isAnswer) { logger.debug('processAnswer: state= ' + call.peer.signalingState); var onSuccessAfterWorkarounds, setRemoteDescription, remoteVideoDirection, localVideoDirection, peer = call.peer, origSdp; // If it was specified that this SDP operation is a call answer operation, then // provide that to the SDP pipeline. This occurs during slow start scenarios, // but processAnswer is most often a call start operation. var callOperation = isAnswer ? _constants2.default.WEBRTC.SDP.OPERATION.ANSWER_CALL : _constants2.default.WEBRTC.SDP.OPERATION.START_CALL; onSuccessAfterWorkarounds = function onSuccessAfterWorkarounds() { call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); _utils.callFunctionIfExist(onSuccess); }; setRemoteDescription = function setRemoteDescription(operation, call, onSuccess, onFailure) { logger.trace('processAnswer: Setting remote description with (answer) SDP: ' + call.sdp); self.setRemoteDescription(operation, call, peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function () { logger.debug('processAnswer: setRemoteDescription success'); onSuccess(); }, function (e) { logger.error('processAnswer: setRemoteDescription failed: ' + e); onFailure(); }); }; call.sdp = _sdpParser.updateH264LevelTo42E01F(call.sdp, self.isH264Enabled()); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, peer.localDescription.sdp, self.isH264Enabled()); call.sdp = _sdpParser.performVideoPortZeroWorkaround(call.sdp); if (peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.HAVE_REMOTE_PRANSWER) { if (_sdpParser.isIceLite(call.prevRemoteSdp) !== _sdpParser.isIceLite(call.sdp)) { logger.debug('ice - ice-lite change.'); onFail(_constants2.default.WEBRTC.ERROR.ICE_ICELITE); return; } origSdp = call.sdp; call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); logger.debug('call processPrAnswer again to trigger on remote stream added with updated sdp.'); self.processPreAnswer(call, function () { call.sdp = origSdp; logger.debug('processPrAnswer success callback. Restore original sdp.'); setRemoteDescription(callOperation, call, onSuccessAfterWorkarounds, onFail); }, function () { call.sdp = origSdp; logger.debug('processPrAnswer failure callback. Restore original sdp.'); setRemoteDescription(callOperation, call, onSuccessAfterWorkarounds, onFail); }); return; } remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); localVideoDirection = _sdpParser.getVideoSdpDirection(call.peer.localDescription.sdp); // this is needed for buggy webrtc api. when term answers with video to audio only call // this scenario does not work without converting to sendrecv logger.debug('processAnswer: ice-lite: do remote video escalation'); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.VIDEO); if ((localVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY || localVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) && (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY)) { // Audio <--> Audio : apply workaround step 1 setRemoteDescription(callOperation, call, onSuccessAfterWorkarounds, onFail); } else if (localVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY && (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY || remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE)) { // Audio <--> Audio-Video setRemoteDescription(null, call, function () { self.performVideoStartWorkaround(callOperation, call, onSuccessAfterWorkarounds, onFail); }, onFail); } else { // Audio <--> Audio // Or // Audio-Video <--> Audio-Video // there is remote video, no need for orig side workaround setRemoteDescription(callOperation, call, onSuccessAfterWorkarounds, onFail); } }; // Native implementation lies on webRtcAdaptor.js // processNativePreAnswer self.processPreAnswer = function (call, onSuccess, onFailure) { logger.debug('processPreAnswer: state= ' + call.peer.signalingState); var peer = call.peer; call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, call.peer.localDescription.sdp, self.isH264Enabled()); logger.trace('processPreAnswer: Setting remote description with (pranswer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, peer, _constants2.default.WEBRTC.SDP.TYPE.PRANSWER, call.sdp, function processPreAnswerSetRemoteDescriptionSuccessCallback() { self.setOriginatorReceiveRemoteVideo(call); call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); onSuccess(); logger.debug('processPreAnswer: setRemoteDescription success'); }, function processPreAnswerSetRemoteDescriptionFailureCallback(e) { logger.error('processPreAnswer: setRemoteDescription failed: ' + e); onFailure(e); }); }; // Native implementation lies on webRtcAdaptor.js // processNativeRespond self.processRespond = function (call, onSuccess, onFail, isJoin) { var remoteVideoDirection, peer = call.peer, remoteSdpHasVideo = false; logger.debug('processRespond: state= ' + call.peer.signalingState); call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); if (call.peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.STABLE) { //if we are in stable state we should not change remotedescription self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, null, null, call.sdp, onSuccess, onFail); return; } remoteSdpHasVideo = _sdpParser.isSdpHasVideo(call.sdp); if (remoteSdpHasVideo) { call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, call.stableLocalSdp, self.isH264Enabled()); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); if (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE && call.currentState === 'COMPLETED') { switch (call.remoteVideoState) { case _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE: case _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY: call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); break; } } call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.VIDEO); } if (isJoin) { call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); self.muteOnHold(call, false); } logger.trace('processRespond: Setting remote description with (answer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.RESPOND, call, peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function () { logger.debug('processRespond: setRemoteDescription success'); var onSuccessAfterWorkarounds = function onSuccessAfterWorkarounds() { call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); _utils.callFunctionIfExist(onSuccess); }; self.performVideoStartWorkaround(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); }, function (e) { logger.debug('processRespond: setRemoteDescription failed: ' + e); _utils.callFunctionIfExist(onFail); }); }; /* * Native implementation lies on webRtcAdaptor.js * processNativeHoldRespond */ self.processHoldRespond = function (call, onSuccess, onFailure, isJoin) { var remoteAudioDirection, remoteVideoDirection, onSuccessAfterWorkaround, localHoldFlag = false, remoteHoldFlag = false; onSuccessAfterWorkaround = function onSuccessAfterWorkaround() { //call.remoteVideoState = getSdpDirection(call.sdp, video); _utils.callFunctionIfExist(onSuccess); }; //TODO why not FF check here if (self.needNewPeer(call, false)) { self.createNewPeerForCall(call); } logger.debug('processHoldRespond: state= ' + call.peer.signalingState + ' call.currentState= ' + call.currentState); call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); if (call.peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.STABLE) { //if we are in stable state we should not change remotedescription logger.trace('processHoldRespond: onRemoteStreamAdded'); self.onRemoteStreamAdded(call); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.HOLD, call, null, null, call.sdp, onSuccess, onFailure); return; } call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, call.stableLocalSdp, self.isH264Enabled()); _sdpParser.init(call.sdp); remoteHoldFlag = _sdpParser.isRemoteHold(); localHoldFlag = call.currentState === 'LOCAL_HOLD'; remoteAudioDirection = _sdpParser.getAudioSdpDirection(call.sdp); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); call.remoteVideoState = remoteVideoDirection; logger.debug('processHoldRespond: localHold= ' + localHoldFlag + ' remoteHold= ' + remoteHoldFlag); /* Required for MOH - start */ if (remoteHoldFlag === false) { if (remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE && call.currentState === 'REMOTE_HOLD') { logger.debug('set current web state to COMPLETED'); call.previousState = call.currentState; call.currentState = 'COMPLETED'; } } else { if (call.currentState === 'COMPLETED') { logger.debug('set current web state to REMOTE_HOLD'); call.previousState = call.currentState; call.currentState = 'REMOTE_HOLD'; } } if (localHoldFlag || remoteHoldFlag) { logger.debug('processHoldRespond: ' + call.currentState + ' : video -> inactive'); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } if (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE && call.currentState === 'COMPLETED') { logger.debug('processHoldRespond: video inactive -> recvonly'); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } /* Required for MOH - end */ if (isJoin) { self.muteOnHold(call, false); } // this is required for displaying remote video when direction is send only call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.VIDEO); if (localHoldFlag && remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) { logger.debug('processHoldRespond: Mute Remote Audio'); call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); remoteAudioDirection = _sdpParser.getAudioSdpDirection(call.sdp); } if (localHoldFlag && remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) { logger.debug('processHoldRespond: Mute Remote Video'); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); } // If we have a configuration to force disable media on hold we tell chrome that the other side is inactive this will // prevent chrome from sending noise even after being muted. if (localHoldFlag && _config.forceDisableMediaOnHold && remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) { logger.debug('processHoldRespond: Changing remote direction from recvonly to inactive'); call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); remoteAudioDirection = _sdpParser.getAudioSdpDirection(call.sdp); } if (remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) { logger.trace('processHoldRespond: Setting remote description with (answer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.HOLD, call, call.peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function processHoldRespondSetRemoteDescriptionSuccessCallback() { logger.debug('processHoldRespond: setRemoteDescription typeAns success'); onSuccessAfterWorkaround(); }, function processHoldRespondSetRemoteDescriptionFailureCallback(e) { logger.debug('processHoldRespond: setRemoteDescription typeAns failed: ' + e); _utils.callFunctionIfExist(onFailure); }); } else { self.setRemoteDescription(null, call, call.peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function processHoldRespondSetRemoteDescriptionSuccessCallback() { logger.debug('processHoldRespond: setRemoteDescription typeAns success'); self.performVideoStartWorkaround(_constants2.default.WEBRTC.SDP.OPERATION.UNHOLD, call, onSuccessAfterWorkaround, onFailure); }, function processHoldRespondSetRemoteDescriptionFailureCallback(e) { logger.debug('processHoldRespond: setRemoteDescription typeAns failed: ' + e); _utils.callFunctionIfExist(onFailure); }); } }; // Native implementation lies on webRtcAdaptor.js self.processRemoteOfferOnLocalHold = function (call, successCallback, failureCallback) { logger.info('processRemoteOfferOnLocalHold'); if (call.peer) { _utils.callFunctionIfExist(successCallback, call.stableLocalSdp); } else { _utils.callFunctionIfExist(failureCallback, 'we dont have a peer object somehow'); } }; self.removeJslIdFromContainer = function () { if (self.getDefaultVideoContainer()) { self.getDefaultVideoContainer().removeAttribute('jsl-id'); self.disposeStreamRenderer(self.getDefaultVideoContainer().lastElementChild); } else if (self.getLocalVideoContainer()) { self.getLocalVideoContainer().removeAttribute('jsl-id'); self.disposeStreamRenderer(self.getLocalVideoContainer()); } }; self.clearLocalMediaProperties = function (localMedia) { localMedia.stream = null; localMedia.originalStream = null; localMedia.audioContext = null; localMedia.audioGain = null; localMedia.mediaStreamDestination = null; }; self.endLocalMedia = function (localMedia) { if (localMedia && localMedia.stream && !localMedia.privateStream) { logger.info('stopping local media ' + localMedia.stream.id); self.getLocalStreamMap().remove(localMedia.stream.id); self.getRtcLibrary().detachWebAudioContextFromLocalMedia(localMedia); self.getRtcLibrary().stopLocalMedia(localMedia); self.clearLocalMediaProperties(localMedia); } }; /* * Native implementation lies on webRtcAdaptor.js * process the end call that was received * * @ignore * @name rtc.processEnd.stop */ self.processEnd = function (call) { var id, localStreamEntries, streams; self.clearIceCandidateCollectionTimer(call); self.clearUpdateCandidateInterval(call); self.clearWebrtcLogCollectionInterval(call); if (call.peer) { logger.info('close peer connection ' + call.id); if (call.peer.getRemoteStreams) { streams = call.peer.getRemoteStreams(); if (streams && streams[0]) { self.onRemoteStreamRemoved(call, { stream: streams[0] }); } } if (call.peer.signalingState !== 'closed') { call.peer.close(); } self.endLocalMedia(call.localMedia); self.setPeerCount(self.getPeerCount() - 1); if (self.getPeerCount() <= 0) { self.removeJslIdFromContainer(); localStreamEntries = self.getLocalStreamMap().entries(); for (id in localStreamEntries) { if (localStreamEntries.hasOwnProperty(id)) { self.endLocalMedia(self.getLocalStreamMap().get(id)); } } } } }; // Native implementation lies on webRtcAdaptor.js self.onSessionConnecting = function () { logger.debug('onSessionConnecting'); }; // Native implementation lies on webRtcAdaptor.js self.onSessionOpened = function () { logger.debug('onSessionOpened'); }; // Native implementation lies on webRtcAdaptor.js self.onSignalingStateChange = function (call) { //TODO may need to move the state changes for webrtc here logger.debug('Signalling state changed: state= ' + call.peer.signalingState); }; // Native implementation lies on webRtcAdaptor.js self.useDefaultRenderer = function (streamUrl, local, isVideoTrackAvailable, streamId) { var videoContainer; if (self.getDefaultVideoContainer() && self.getDefaultVideoContainer().children.length === 0) { // Create divs for the remote and local self.getDefaultVideoContainer().innerHTML = '<div style=\'height:100%;width:100%\'></div><div style=\'position:absolute;bottom:10px;right:10px;height:30%; width:30%;\'></div>'; } if (local) { videoContainer = self.getDefaultVideoContainer().lastElementChild; } else { videoContainer = self.getDefaultVideoContainer().firstElementChild; videoContainer.style.width = '100%'; } return self.createStreamRenderer(streamUrl, videoContainer, { muted: local, video: isVideoTrackAvailable, id: streamId, split: true }); }; // Native implementation lies on webRtcAdaptor.js self.createStreamRenderer = function (streamUrl, container, options) { var videoRenderer, renderer, video = true, muted = false, split = false, safeStreamId; if (!streamUrl || !container) { return; } if (options) { video = options.video === false ? false : true; muted = options.muted; split = options.split; safeStreamId = (0, _utils2.makeSafeForCSS)(options.id); } if (video) { videoRenderer = container.querySelector('video'); if (!videoRenderer) { videoRenderer = document.createElement('video'); container.appendChild(videoRenderer); } videoRenderer.src = streamUrl; videoRenderer.style.width = '100%'; videoRenderer.style.height = '100%'; videoRenderer.autoplay = 'true'; if (muted || split) { videoRenderer.muted = 'true'; } //This seems requiried on Android, as changing an existing video element does not trigger the autoplay var playPromise = videoRenderer.play(); if (playPromise !== undefined) { // `.play()` is async and returns a promise in some browsers. playPromise.catch(function (error) { logger.debug('Autoplay video was prevented.', error); }); } } if (!muted && split) { if (safeStreamId) { renderer = container.querySelector('#stream-id-' + safeStreamId); if (!renderer) { renderer = document.createElement('audio'); renderer.id = 'stream-id-' + safeStreamId; container.appendChild(renderer); } } renderer.autoplay = 'true'; renderer.src = streamUrl; } else { renderer = videoRenderer; } // Set call speaker if a default is set and it's supported. var speakerId = self.getSelectedSpeakerId(); if (speakerId && typeof renderer.setSinkId !== 'undefined') { renderer.setSinkId(speakerId).then(function () { logger.debug('Default speaker set.', speakerId); }).catch(function (error) { logger.debug('Could not set default speaker. ' + speakerId, error); }); } return renderer; }; // Native implementation lies on webRtcAdaptor.js self.addCallIdInPluginContainer = function (call) { logger.info('addCallIdInPluginContainer Call ID= ' + call.id); if (self.getDefaultVideoContainer()) { self.getDefaultVideoContainer().setAttribute('jsl-id', call.id); } else if (self.getRemoteVideoContainer()) { self.getRemoteVideoContainer().setAttribute('jsl-id', call.id); } }; // Native implementation lies on webRtcAdaptor.js self.isActiveCallInVideoContainer = function (container, call) { logger.info('isActiveCallInVideoContainer Call ID= ' + call.id); if (container.getAttribute('jsl-id') !== 'undefined') { logger.info('isActiveCallInVideoContainer Jsl Id= ' + container.getAttribute('jsl-id')); if (call.id !== container.getAttribute('jsl-id')) { return false; } } return true; }; // nativeOnRemoteStreamAdded self.onRemoteStreamAdded = function (call, event) { var fireEvent, remoteVideoTracks = [], isVideoTrackAvailable = false; if (self.getDefaultVideoContainer()) { if (!self.isActiveCallInVideoContainer(self.getDefaultVideoContainer(), call)) { logger.debug('onRemoteStreamAdded: It is not active call. Call Id: ' + call.id); return; } } else if (self.getRemoteVideoContainer()) { if (!self.isActiveCallInVideoContainer(self.getRemoteVideoContainer(), call)) { logger.debug('onRemoteStreamAdded: It is not active call. Call Id: ' + call.id); return; } } if (event && event.stream) { call.remoteStreamUrl = self.getRtcLibrary().getURLFromStream(event.stream); call.remoteStreamId = event.stream.id; event.stream.onaddtrack = function () { logger.debug('onaddtrack for stream ' + event.stream.id); self.onRemoteStreamAdded(call); }; remoteVideoTracks = event.stream.getVideoTracks(); } else { remoteVideoTracks = self.getRemoteVideoTrack(call.peer); } if (remoteVideoTracks && _sdpParser.isVideoSdpEnabled(call.sdp)) { if (remoteVideoTracks.length > 0) { isVideoTrackAvailable = true; } } if (call.mergedCall) { var source = call.mergedCall.localMedia.audioContext.createMediaStreamSource(event.stream); source.connect(call.mergedCall.localMedia.mediaStreamDestination); call.mergedCall.localMedia.mergedSource = source; } if (self.getDefaultVideoContainer()) { fireEvent = self.useDefaultRenderer(call.remoteStreamUrl, false, isVideoTrackAvailable, call.remoteStreamId); } else if (self.getRemoteVideoContainer()) { fireEvent = self.createStreamRenderer(call.remoteStreamUrl, self.getRemoteVideoContainer(), { video: isVideoTrackAvailable, id: call.remoteStreamId, split: true }); } else { fireEvent = true; } logger.debug('onRemoteStreamAdded: ' + call.remoteStreamUrl); if (fireEvent) { self.fireOnStreamAddedEvent(call, call.remoteStreamUrl); } }; // Native implementation lies on webRtcAdaptor.js self.fireOnStreamAddedEvent = function (call, streamUrl) { if (call && call.call && call.call.onStreamAdded) { self.setOriginatorReceiveRemoteVideo(call); _utils.callFunctionIfExist(call.call.onStreamAdded, streamUrl); } }; // Native implementation lies on webRtcAdaptor.js self.onRemoteStreamRemoved = function (call, event) { var container; logger.info('removing stream ' + event.stream.id); if (self.getDefaultVideoContainer()) { container = self.getDefaultVideoContainer().firstElementChild; } else if (self.getRemoteVideoContainer()) { container = self.getRemoteVideoContainer(); } self.disposeStreamRenderer(container, event.stream.id); }; // Native implementation lies on webRtcAdaptor.js self.clearUpdateCandidateInterval = function (call) { clearInterval(call.updateCandidateInterval); call.updateCandidateInterval = null; }; // Native implementation lies on webRtcAdaptor.js self.clearIceCandidateCollectionTimer = function (call) { //This method wasn't implemented in webrtc.js clearTimeout(call.iceCandidateCollectionTimer); call.iceCandidateCollectionTimer = null; }; // Native implementation lies on webRtcAdaptor.js self.onIceCandidate = function (call, event) { var sdp; if (event.candidate === null) { logger.debug('Null candidate received.'); if (call.successCallback) { sdp = call.peer.localDescription.sdp; if (_sdpParser.hasCandidates(sdp, call.relayCandidateCycle, _config.relayCandidateCollectionTimeoutCycle)) { self.clearIceCandidateCollectionTimer(call); logger.debug('Candidates received, invoking successCallback.'); call.successCallback(sdp); } else { logger.trace('Sdp does not have candidates.'); } } } else { logger.debug('ICE candidate received: sdpMLineIndex = ' + event.candidate.sdpMLineIndex + ', candidate = ' + event.candidate.candidate + ' for call : ' + call.id); // if successCallback haven't been cleared, candidates will be sent via successCallback // otherwise candidates will be sent via updateIceCandidates request if (!call.successCallback) { if (!call.candidateArray) { call.candidateArray = []; } call.candidateArray.push(event.candidate); self.updateCandidates(call); } } }; // Native implementation lies on webRtcAdaptor.js self.onIceComplete = function (call) { var sdp; logger.debug('All ICE candidates received for call : ' + call.id); self.clearIceCandidateCollectionTimer(call); if (call.successCallback) { sdp = call.peer.localDescription.sdp; logger.trace('onIceComplete sdp : ' + sdp); call.successCallback(sdp); } }; self.onDataChannel = function (dataChannelWrapperObj, event) { dataChannelWrapperObj.dataChannel = event.channel; _utils.callFunctionIfExist(dataChannelWrapperObj.onDataChannel, dataChannelWrapperObj); }; // Native implementation lies on webRtcAdaptor.js self.iceCandidateCollectionTimeoutHandler = function (call) { var sdp = call.peer.localDescription.sdp; self.clearIceCandidateCollectionTimer(call); if (_config.relayCandidateCollectionTimeoutCycle) { call.relayCandidateCycle++; } // set timeout if there is no ice candidate available or // when audio, video port assignment isn't complete if (!_sdpParser.hasCandidates(sdp, call.relayCandidateCycle, _config.relayCandidateCollectionTimeoutCycle)) { logger.debug('Re-setting ice candidate collection timeout: ' + _config.iceCandidateCollectionTimeoutInterval); call.iceCandidateCollectionTimer = setTimeout(function () { self.iceCandidateCollectionTimeoutHandler(call); }, _config.iceCandidateCollectionTimeoutInterval); return; } if (call.successCallback) { logger.debug('Ice candidate collection interrupted after given timeout, invoking successCallback.'); call.successCallback(sdp); } }; // Native implementation lies on webRtcAdaptor.js self.setupIceCandidateCollectionTimer = function (call) { if (_config.iceCandidateCollectionTimeoutInterval) { if (!call.iceCandidateCollectionTimer) { logger.debug('Setting ice candidate collection timeout: ' + _config.iceCandidateCollectionTimeoutInterval); if (_config.relayCandidateCollectionTimeoutCycle) { call.relayCandidateCycle = 1; } call.iceCandidateCollectionTimer = setTimeout(function () { self.iceCandidateCollectionTimeoutHandler(call); }, _config.iceCandidateCollectionTimeoutInterval); } else { logger.trace('Ice candidate collection timer exists.'); } } }; self.getNativeWebRtcStats = function (call, onSuccess, onFailure) { try { if (call) { logger.debug('getNativeWebRtcStats called'); call.peer.getStats(function (stats) { if (stats !== undefined && stats !== null) { var results = stats.result(); _utils.callFunctionIfExist(onSuccess, results); } }); } } catch (err) { logger.error('Failed to get all WebRTC Statistics: ' + err.message); _utils.callFunctionIfExist(onFailure, err); } }; self.getWebRtcStats = function (call, onSuccess, onFailure) { try { if (call) { logger.debug('getWebRtcStats called'); self.collectWebRtcStats(call.sdp, call.peer, function (stats) { var accumulatedStats = self.getAccumulatedWebRtcStats(call.stats, stats, call.cache); _utils.callFunctionIfExist(onSuccess, accumulatedStats); }, onFailure); } else { var cacheWebRtcStats = JSON.parse(_cache.getItem(_fcs.getUser() + '_stats')); _utils.callFunctionIfExist(onSuccess, cacheWebRtcStats); } } catch (err) { logger.error('Failed to get WebRTC Statistics: ' + err.message); _utils.callFunctionIfExist(onFailure, err); } return self.getStats(); }; self.getAccumulatedWebRtcStats = function (statsList, currentStats, callCache) { var i, accumulatedStats = { audio: { packetsSent: 0, bytesSent: 0, bytesReceived: 0, peerAddress: null, codec: null, packetsLost: 0, jitter: null, rtt: null }, video: { packetsSent: 0, bytesSent: 0, bytesReceived: 0, peerAddress: null, codec: null, packetsLost: 0, rtt: null } }; if (statsList !== undefined) { for (i = 0; i < statsList.length; i++) { self.accumulateStats(accumulatedStats.audio, statsList[i].audio); self.accumulateStats(accumulatedStats.video, statsList[i].video); } } self.accumulateStats(accumulatedStats.audio, currentStats.audio); accumulatedStats.audio.peerAddress = currentStats.audio.peerAddress; accumulatedStats.audio.codec = currentStats.audio.codec; accumulatedStats.audio.jitter = currentStats.audio.jitter; accumulatedStats.audio.rtt = currentStats.audio.rtt; self.accumulateStats(accumulatedStats.video, currentStats.video); accumulatedStats.video.peerAddress = currentStats.video.peerAddress; accumulatedStats.video.codec = currentStats.video.codec; accumulatedStats.video.rtt = currentStats.video.rtt; if (callCache) { _cache.setItem(_fcs.getUser() + '_stats', (0, _stringify2.default)(accumulatedStats)); } return accumulatedStats; }; self.accumulateStats = function (accumulatedStatsObj, statsObj) { accumulatedStatsObj.packetsSent += (0, _utils2.getInteger)(statsObj.packetsSent); accumulatedStatsObj.bytesSent += (0, _utils2.getInteger)(statsObj.bytesSent); accumulatedStatsObj.bytesReceived += (0, _utils2.getInteger)(statsObj.bytesReceived); accumulatedStatsObj.packetsLost += (0, _utils2.getInteger)(statsObj.packetsLost) === -1 ? 0 : (0, _utils2.getInteger)(statsObj.packetsLost); }; self.collectWebRtcStats = function (statsSdp, peer, onSuccess, onFailure) { try { if (peer) { logger.debug('collectWebRtcStats called'); peer.getStats(function (stats) { if (stats !== undefined && stats !== null) { var results = stats.result(); self.setWebRtcStats(results, statsSdp); _utils.callFunctionIfExist(onSuccess, self.getStats()); } }); } } catch (err) { logger.error('Failed to collectWebRtcStats: ' + err.message); _utils.callFunctionIfExist(onFailure, err); } return self.getStats(); }; self.setWebRtcStats = function (results, statsSdp) { var i, j, res, names, mediaDescriptions, sdpAudioPort, sdpVideoPort, transportId, googChannelId, googCodecName, alwaysMediaOnBroker, stats = { audio: { packetsSent: null, bytesSent: null, bytesReceived: null, peerAddress: '', codec: null, packetsLost: null, jitter: null, rtt: null }, video: { packetsSent: null, bytesSent: null, bytesReceived: null, peerAddress: null, codec: null, packetsLost: null, rtt: null } }; if (_sdpParser.isIceLite(statsSdp)) { alwaysMediaOnBroker = true; } else { alwaysMediaOnBroker = false; } if (statsSdp !== undefined && statsSdp !== null && results !== undefined && results !== null) { _sdpParser.init(statsSdp); _sdpParser.parseSDP(statsSdp); mediaDescriptions = _sdpParser.getMediaDescriptions(); if (mediaDescriptions !== undefined) { if (mediaDescriptions[0] !== undefined) { sdpAudioPort = mediaDescriptions[0].port; } if (mediaDescriptions[1] !== undefined) { sdpVideoPort = mediaDescriptions[1].port; } } for (i = 0; i < results.length; i++) { res = results[i]; names = res.names(); if (names !== undefined) { for (j = 0; j < names.length; j++) { googChannelId = res.stat('googChannelId'); transportId = res.stat('transportId'); googCodecName = res.stat('googCodecName'); if (transportId !== undefined && transportId.indexOf('audio') > -1 || googChannelId !== undefined && googChannelId.indexOf('audio') > -1) { if (googCodecName === 'VP8' || googCodecName === 'H264') { self.fillStats(stats.video, res, names, j, sdpVideoPort, alwaysMediaOnBroker); } else { self.fillStats(stats.audio, res, names, j, sdpAudioPort, alwaysMediaOnBroker); } } else if (transportId !== undefined && transportId.indexOf('video') > -1 || googChannelId !== undefined && googChannelId.indexOf('video') > -1) { self.fillStats(stats.video, res, names, j, sdpVideoPort, alwaysMediaOnBroker); } } if (!alwaysMediaOnBroker && sdpVideoPort !== undefined) { stats.video.peerAddress = stats.audio.peerAddress.split(':')[0]; } self.setStats(stats); } } } }; self.fillStats = function (statsObj, res, names, index, sdpRemotePort, alwaysMediaOnBroker) { var remotePort, remoteAddress; if (res.stat('googActiveConnection') === 'true' && alwaysMediaOnBroker) { remoteAddress = res.stat('googRemoteAddress'); if (remoteAddress !== undefined) { if (remoteAddress.split(':') !== undefined && remoteAddress.split(':')[1] !== undefined) { remotePort = remoteAddress.split(':')[1]; } if (remotePort === sdpRemotePort) { statsObj.peerAddress = remoteAddress; if (names[index] === 'bytesReceived') { statsObj.bytesReceived = res.stat(names[index]); } if (names[index] === 'packetsSent') { statsObj.packetsSent = res.stat(names[index]); } if (names[index] === 'bytesSent') { statsObj.bytesSent = res.stat(names[index]); } } } } if (res.stat('googActiveConnection') === 'true' && !alwaysMediaOnBroker) { remoteAddress = res.stat('googRemoteAddress'); statsObj.peerAddress = remoteAddress; } if (res.type === 'ssrc') { if (names[index] === 'packetsLost') { statsObj.packetsLost = res.stat(names[index]); } if (names[index] === 'googCodecName') { statsObj.codec = res.stat(names[index]); } if (names[index] === 'googJitterReceived') { statsObj.jitter = res.stat(names[index]); } if (names[index] === 'googRtt') { statsObj.rtt = res.stat(names[index]); } if (!alwaysMediaOnBroker) { if (names[index] === 'bytesReceived') { statsObj.bytesReceived = res.stat(names[index]); } if (names[index] === 'packetsSent') { statsObj.packetsSent = res.stat(names[index]); } if (names[index] === 'bytesSent') { statsObj.bytesSent = res.stat(names[index]); } } } }; self.clearWebrtcLogCollectionInterval = function (call) { //This method wasn't implemented in webrtc.js clearInterval(call.webrtcLogCollectionInterval); call.webrtcLogCollectionInterval = null; }; self.webrtcLogCollectionTimeoutHandler = function (call) { if (call && call.peer && call.peer.signalingState !== 'closed') { call.peer.getStats(function (stats) { var results = stats.result(), i, j, res, names, statObj, resultLength, namesLength; resultLength = results.length; for (i = 0; i < resultLength; ++i) { res = results[i]; if (!res.local || res.local === res) { statObj = {}; statObj.timestamp = res.timestamp; if (res.id) { statObj.id = res.id; } if (res.type) { statObj.type = res.type; } if (res.names) { names = res.names(); namesLength = names.length; for (j = 0; j < namesLength; ++j) { statObj[names[j]] = res.stat(names[j]); } } else { if (res.stat('audioOutputLevel')) { statObj.audioOutputLevel = res.stat('audioOutputLevel'); } } logger.trace('Peer connection stats, report[' + i + ']: ', statObj); } } }); } else { self.clearWebrtcLogCollectionInterval(call); } }; self.setupWebrtcLogCollectionTimer = function (call) { if (_config.webrtcLogCollectionInterval) { self.clearWebrtcLogCollectionInterval(call); var logCollectionInterval = _config.webrtcLogCollectionInterval * 1000; logger.debug('Setting webrtc log collection interval: ' + logCollectionInterval); call.webrtcLogCollectionInterval = setInterval(function () { self.webrtcLogCollectionTimeoutHandler(call); }, logCollectionInterval); } }; self.oniceconnectionstatechange = function (call) { var state, mediaStates = _fcs.call.MediaStates, iceConnectionState = call.peer.iceConnectionState; logger.debug('ICE connection state change : ' + iceConnectionState); if (iceConnectionState === 'new') { state = mediaStates.NEW; } else if (iceConnectionState === 'checking') { state = mediaStates.CHECKING; } else if (iceConnectionState === 'connected') { state = mediaStates.CONNECTED; } else if (iceConnectionState === 'completed') { state = mediaStates.COMPLETED; } else if (iceConnectionState === 'failed') { state = mediaStates.FAILED; } else if (iceConnectionState === 'disconnected') { state = mediaStates.DISCONNECTED; } else if (iceConnectionState === 'closed') { state = mediaStates.CLOSED; } else { logger.debug('ICE connection state was not recognized'); } if (state) { _utils.callFunctionIfExist(call.call.onMediaStateChange, state); } }; self.createDataChannel = function (dataChannelWrapperObj, onSuccess, onFailure, options) { try { dataChannelWrapperObj.dataChannel = dataChannelWrapperObj.peer.createDataChannel(options); onSuccess(dataChannelWrapperObj); } catch (error) { logger.error('Failed to create data channel, exception: ' + error.message); onFailure(error); } }; // Native implementation lies on webRtcAdaptor.js self.createPeer = function (call) { try { var pc, constraints = {}, i, servers = [], iceServerUrl, config, useIceServer; useIceServer = !_config.ignoreIceParamsForServices || _config.ignoreIceParamsForServices.indexOf('call') !== -1; logger.info('useIceServer: ' + useIceServer); if (useIceServer) { iceServerUrl = self.getIceServerUrl(); } if (iceServerUrl instanceof Array) { for (i = 0; i < iceServerUrl.length; i++) { servers[i] = iceServerUrl[i]; } } else if (!iceServerUrl || iceServerUrl === '') { servers = []; } else { servers[0] = iceServerUrl; } config = { iceServers: servers, // NOTE: This is added temporarily because Chrome and Firefox have required set // by default and the media broker doesn't support multiplexing. ADG-14986 rtcpMuxPolicy: 'negotiate' }; // If present, take the call constraints provided as config. if (_config.callConstraints && _config.callConstraints.chrome) { // If any constraint is malformed, the RTCPeerConnection will fail to be created. logger.debug('Using custom peer constraints for call.', _config.callConstraints.chrome); constraints = _config.callConstraints.chrome; } constraints.optional = constraints.optional || []; constraints.optional.push({ 'DtlsSrtpKeyAgreement': self.isDtlsEnabled() }); if (self.isDscpEnabled() !== undefined) { constraints.optional.push({ 'googDscp': true }); } //Add iceTransportPolicy:relay in order to force TURN if (_config.useRelayOnly) { config.iceTransportPolicy = 'relay'; } if (_config.bundlePolicy !== _constants2.default.WEBRTC.SDP.BUNDLE_POLICY.DISABLED) { config.bundlePolicy = _config.bundlePolicy; } pc = self.getRtcLibrary().createRTCPeerConnection(config, constraints); self.setPeerCount(self.getPeerCount() + 1); call.peer = pc; pc.onconnecting = function (event) { self.onSessionConnecting(call, event); }; pc.onopen = function (event) { self.onSessionOpened(call, event); }; pc.onsignalingstatechange = function (event) { self.onSignalingStateChange(call, event); }; pc.onaddstream = function (event) { self.onRemoteStreamAdded(call, event); }; pc.onremovestream = function (event) { self.onRemoteStreamRemoved(call, event); }; pc.onicecandidate = function (event) { if (pc.iceGatheringState === 'complete') { logger.debug('ice gathering complete'); self.onIceComplete(call); } else { self.setupIceCandidateCollectionTimer(call); self.onIceCandidate(call, event); } }; pc.onicecomplete = function () { self.onIceComplete(call); }; pc.oniceconnectionstatechange = function (event) { self.oniceconnectionstatechange(call, event); }; pc.ondatachannel = function (event) { self.onDataChannel(call, event); }; pc.onicegatheringstatechange = function () { logger.debug('ice gathering state change:' + pc.iceGatheringState); }; logger.info('create PeerConnection successfully.'); self.setupWebrtcLogCollectionTimer(call); return true; } catch (err) { logger.error('Failed to create PeerConnection, exception: ' + err.message); } return false; }; self.needNewPeer = function (call, checkFireFox, incomingSDP) { if (call.forceNewPeer) { call.forceNewPeer = false; return true; } if (checkFireFox) { _sdpParser.isRemoteEndFirefox(call.sdp); } //We only want to compare those when this is an incoming SDP, not when we create an update if (incomingSDP && call.prevRemoteSdp && call.sdp) { if (_sdpParser.getSessionIdFromSdp(call.prevRemoteSdp) !== _sdpParser.getSessionIdFromSdp(call.sdp)) { logger.debug('New peer needed as session id has changed'); return true; } if (_sdpParser.getFingerprintFromSdp(call.prevRemoteSdp) !== _sdpParser.getFingerprintFromSdp(call.sdp)) { logger.debug('New peer needed as DTLS Fingerprint has changed'); return true; } if (_sdpParser.hasCodecPayloadChanged(call.prevRemoteSdp, call.sdp)) { logger.debug('New peer needed as Codec Payload has changed'); return true; } } return false; }; self.createNewPeerForCall = function (call, deleteVideoStream) { var isNewPeerCreated = false, oldPeer, videoTrack; if (call.peer) { oldPeer = call.peer; self.collectWebRtcStats(call.sdp, oldPeer, function (stats) { logger.debug('collectWebRtcStats successfull'); if (call.stats === undefined) { call.stats = []; } call.stats.push(stats); if (oldPeer.signalingState !== 'closed') { oldPeer.close(); } self.setPeerCount(self.getPeerCount() - 1); call.dtmfSender = null; }, function () { logger.debug('collectWebRtcStats failed'); if (oldPeer.signalingState !== 'closed') { oldPeer.close(); } self.setPeerCount(self.getPeerCount() - 1); call.dtmfSender = null; }); } logger.trace('Creating new peer for call: ' + call.id); if (self.createPeer(call)) { logger.trace('New peer has created for call: ' + call.id); if (call.localMedia && call.localMedia.stream) { if (deleteVideoStream) { videoTrack = call.localMedia.stream.getVideoTracks()[0]; if (videoTrack) { call.localMedia.stream.removeTrack(videoTrack); } else { logger.debug('Designated to remove track after new' + ' peer creation, but no video track found.'); } } call.peer.addStream(call.localMedia.stream); } isNewPeerCreated = true; } else { logger.error('New peer creation has failed!: ' + call.id); if (call.stats) { call.stats.pop(); } } return isNewPeerCreated; }; /* * Gets remote video resolutions with the order below * remoteVideoHeight-remoteVideoWidth * * Native implementation lies on webRtcAdaptor.js */ self.getRemoteVideoResolutions = function () { var remoteResolution = [], remoteVideoHeight, remoteVideoWidth; if (self.getRemoteVideoContainer()) { if (!self.getRemoteVideoContainer().firstChild) { return remoteResolution; } remoteVideoHeight = self.getRemoteVideoContainer().firstChild.videoHeight; remoteVideoWidth = self.getRemoteVideoContainer().firstChild.videoWidth; } else { if (!self.getDefaultVideoContainer().firstElementChild.firstChild) { return remoteResolution; } remoteVideoHeight = self.getDefaultVideoContainer().firstElementChild.firstChild.videoHeight; remoteVideoWidth = self.getDefaultVideoContainer().firstElementChild.firstChild.videoWidth; } logger.debug('remote video resolutions of plugin webrtc...'); logger.debug('remoteVideoWidth : ' + remoteVideoWidth); logger.debug('remoteVideoHeight : ' + remoteVideoHeight); remoteResolution.push(remoteVideoHeight); remoteResolution.push(remoteVideoWidth); self.getLocalVideoResolutions(); return remoteResolution; }; /* * Gets local video resolutions with the order below * localVideoHeight-localVideoWidth * * Native implementation lies on webRtcAdaptor.js */ self.getLocalVideoResolutions = function () { var localResolution = [], localVideoHeight, localVideoWidth; if (self.getLocalVideoContainer()) { if (!self.getLocalVideoContainer().firstChild) { return localResolution; } localVideoHeight = self.getLocalVideoContainer().firstChild.videoHeight; localVideoWidth = self.getLocalVideoContainer().firstChild.videoWidth; } else { if (!self.getDefaultVideoContainer().lastElementChild.firstChild) { return localResolution; } localVideoHeight = self.getDefaultVideoContainer().lastElementChild.firstChild.videoHeight; localVideoWidth = self.getDefaultVideoContainer().lastElementChild.firstChild.videoWidth; } logger.debug('local video resolutions of plugin webrtc...'); logger.debug('localVideoWidth : ' + localVideoWidth); logger.debug('localVideoHeight : ' + localVideoHeight); localResolution.push(localVideoHeight); localResolution.push(localVideoWidth); return localResolution; }; // Native implementation lies on webRtcAdaptor.js self.refreshVideoRenderer = function () { return; }; // Native implementation lies on webRtcAdaptor.js self.sendIntraFrame = function () { return; }; // Native implementation lies on webRtcAdaptor.js self.sendBlackFrame = function () { return; }; // Native implementation lies on webRtcAdaptor.js self.disposeStreamRenderer = function (container) { var id = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var safeId = (0, _utils2.makeSafeForCSS)(id); logger.info('disposeStreamRenderer'); if (container) { if (safeId) { var renderer = container.querySelector('#stream-id-' + safeId); if (renderer) { container.removeChild(renderer); } } else { container.innerHTML = ''; } } }; self.sendInbandDTMF = function (call, tone, audioContext) { var oscillator1, oscillator2, freq1, freq2, gainNode, mediaStreamDestination; if (call.localMedia && call.localMedia.mediaStreamDestination) { mediaStreamDestination = call.localMedia.mediaStreamDestination; } else { logger.error('could not send DTMF as there is no media'); return; } logger.info('sending inband DTMF tone: ' + tone); if (tone === '1') { freq1 = '697'; freq2 = '1209'; } if (tone === '2') { freq1 = '697'; freq2 = '1336'; } if (tone === '3') { freq1 = '697'; freq2 = '1477'; } if (tone === '4') { freq1 = '770'; freq2 = '1209'; } if (tone === '5') { freq1 = '770'; freq2 = '1336'; } if (tone === '6') { freq1 = '770'; freq2 = '1477'; } if (tone === '7') { freq1 = '852'; freq2 = '1209'; } if (tone === '8') { freq1 = '852'; freq2 = '1336'; } if (tone === '9') { freq1 = '852'; freq2 = '1477'; } if (tone === '*') { freq1 = '941'; freq2 = '1209'; } if (tone === '0') { freq1 = '941'; freq2 = '1336'; } if (tone === '#') { freq1 = '941'; freq2 = '1477'; } oscillator1 = audioContext.createOscillator(); oscillator1.type = 'sine'; oscillator1.frequency.value = freq1; gainNode = audioContext.createGain ? audioContext.createGain() : audioContext.createGainNode(); oscillator1.connect(gainNode, 0, 0); gainNode.connect(mediaStreamDestination); gainNode.gain.value = 0.1; oscillator1.start(); oscillator2 = audioContext.createOscillator(); oscillator2.type = 'sine'; oscillator2.frequency.value = freq2; gainNode = audioContext.createGain ? audioContext.createGain() : audioContext.createGainNode(); oscillator2.connect(gainNode); gainNode.connect(mediaStreamDestination); gainNode.gain.value = 0.1; oscillator2.start(); setTimeout(function () { oscillator1.disconnect(); oscillator2.disconnect(); }, 100); }; /** * Send DTMF tone * Native implementation lies on webRtcAdaptor.js * * @ignore * @name rtc.sendDTMF * @function * @param {Object} call internalCall * @param {String} tone DTMF tone */ self.sendDTMF = function (call, tone) { var audioContext, localAudioTrack; if (!_sdpParser.isSdpHasTelephoneEvent(call.peer.remoteDescription.sdp)) { audioContext = call.localMedia.audioContext; self.sendInbandDTMF(call, tone, audioContext); } else { logger.info('sending outband DTMF tone: ' + tone); if (!call.dtmfSender) { localAudioTrack = self.getLocalAudioTrack(call.peer); if (!localAudioTrack) { return; } call.dtmfSender = call.peer.createDTMFSender(localAudioTrack); if (!call.dtmfSender) { return; } } if (call.dtmfSender.canInsertDTMF === true) { call.dtmfSender.insertDTMF(tone, 400); } else { logger.error('Failed to execute \'insertDTMF\' on \'RTCDTMFSender\': The \'canInsertDTMF\' attribute is false: this sender cannot send DTMF'); } } }; self.showSettingsWindow = function () { self.getRtcLibrary().showSettingsWindow(); }; self.set_logSeverityLevel = function (level) { self.getRtcLibrary().set_logSeverityLevel(level); }; self.enable_logCallback = function () { var pluginLogger = _logManager.getLogger('rtcPlugin'); self.getRtcLibrary().enable_logCallback(pluginLogger); }; self.disable_logCallback = function () { self.getRtcLibrary().disable_logCallback(); }; self.get_audioInDeviceCount = function () { return self.getRtcLibrary().get_audioInDeviceCount(); }; self.get_audioOutDeviceCount = function () { return self.getRtcLibrary().get_audioOutDeviceCount(); }; self.get_videoDeviceCount = function () { return self.getRtcLibrary().get_videoDeviceCount(); }; // set local client's video send status self.setOriginatorSendLocalVideo = function (call, tSdp, status) { var videoSendEnabled = _sdpParser.isVideoSdpEnabled(tSdp); call.canOrigSendVideo = status && videoSendEnabled; }; // check if local client sends video self.canOriginatorSendLocalVideo = function (call) { return call.canOrigSendVideo; }; // set local client's video receive status self.setOriginatorReceiveRemoteVideo = function (call) { call.canOrigReceiveVideo = _sdpParser.isVideoSdpEnabled(call.sdp); }; // check if local client receives video self.canOriginatorReceiveRemoteVideo = function (call) { return call.canOrigReceiveVideo; }; self.setDTLSRoleFromStableLocalSDP = function (call) { call.dtlsRole = _sdpParser.getTcpSetupAttribute(call.stableLocalSdp); }; self.handleDTLSRoleFromRemoteSDP = function (call) { if (!self.isDtlsEnabled()) { return; } var remote_role = _sdpParser.getTcpSetupAttribute(call.sdp), local_role = 'active'; //if we already have a role we don't want to chane it. if ((call.dtlsRole === 'active' || call.dtlsRole === 'passive') && remote_role === 'actpass') { logger.debug('Setting local DTLS role from remote SDP : keeping existing role'); return; } //if we detect a conflict where both ends says they are actpass use fingerprint comparaison and modify the incoming sdp if (call.dtlsRole === 'actpass' && remote_role === 'actpass') { if (_sdpParser.getFingerprintFromSdp(call.lastLocalSdp) < _sdpParser.getFingerprintFromSdp(call.sdp)) { local_role = 'passive'; } else { local_role = 'active'; } call.sdp = _sdpParser.setTcpSetupAttribute(call.sdp, local_role === 'active' ? 'passive' : 'active', true); logger.debug('Setting local DTLS role from remote SDP : ' + local_role + ' baed on fingerprint comparaison'); } if (remote_role === 'active') { local_role = 'passive'; } logger.debug('Setting local DTLS role from remote SDP : ' + local_role); call.dtlsRole = local_role; }; self.setDTLSRole = function (call, role) { call.dtlsRole = role; }; /* * TODO: add selected speaker to the audio constraint, after chrome implementation */ self.prepareAudioConstraints = function (data) { var mediaConstraints = self.getUserMediaContraints(), selectedMicrophoneId = self.getSelectedMicrophoneId(); if (data && (data.isAudioEnabled === false || data.requestScreenShare || data.mediaSourceId)) { return false; } else { if (selectedMicrophoneId) { if (typeof mediaConstraints.audio === 'boolean') { mediaConstraints.audio = {}; } mediaConstraints.audio.deviceId = selectedMicrophoneId; } return mediaConstraints.audio; } }; var updateVideoConstraints = function updateVideoConstraints(videoConstraints, videoResolutionArray, deviceId) { // If the constraint is a boolean, leave it as such if no resolution or deviceId was specified if (typeof videoConstraints === 'boolean') { if (!videoResolutionArray && !deviceId) { return videoConstraints; } videoConstraints = {}; } if (videoResolutionArray && videoResolutionArray.length) { videoConstraints.height = { max: videoResolutionArray[1], min: videoResolutionArray[3] }; videoConstraints.width = { max: videoResolutionArray[0], min: videoResolutionArray[2] }; } videoConstraints.deviceId = deviceId; return videoConstraints; }; self.prepareVideoConstraints = function (data) { var mediaConstraints, videoResolutionArray, selectedCameraId = self.getSelectedCameraId(), isVideoEnabled, videoResolution, requestScreenShare, mediaSourceId, frameRate; if (!data) { data = {}; } isVideoEnabled = data.isVideoEnabled; videoResolution = data.videoResolution; requestScreenShare = data.requestScreenShare; mediaSourceId = data.mediaSourceId; frameRate = data.frameRate; if (!isVideoEnabled && !requestScreenShare && !mediaSourceId) { return false; } if (videoResolution) { if (typeof videoResolution === 'string') { // First and third elements of array will be Width and second and fourth elements will be Height videoResolutionArray = videoResolution.split('x'); // we need an array with 4 elements videoResolutionArray = videoResolutionArray.concat(videoResolutionArray); logger.warn('Deprecated usage of video resolution!!'); logger.warn('Pass video resolution as an object. Please see documentation for more information.'); } else { // videoResolution is an object in this case videoResolutionArray = [videoResolution.minWidth ? videoResolution.minWidth : videoResolution.width, videoResolution.minHeight ? videoResolution.minHeight : videoResolution.height, videoResolution.maxWidth ? videoResolution.maxWidth : videoResolution.width, videoResolution.maxHeight ? videoResolution.maxHeight : videoResolution.height]; } } if (isVideoEnabled) { mediaConstraints = self.getUserMediaContraints(); mediaConstraints.video = updateVideoConstraints(mediaConstraints.video, videoResolutionArray, selectedCameraId); } //We need to handle specific resolution constraints for screen sharing. if (requestScreenShare || mediaSourceId) { //Need to use the default as we cannot mediaConstraints = { video: { mandatory: { 'maxFrameRate': 15, 'maxWidth': 1024, 'maxHeight': 768 }, mediaSource: 'screen' } }; if (frameRate) { mediaConstraints.video.mandatory.maxFrameRate = frameRate; } if (videoResolution) { mediaConstraints.video.mandatory.maxWidth = videoResolution.maxWidth ? videoResolution.maxWidth : videoResolution.width; mediaConstraints.video.mandatory.maxHeight = videoResolution.maxHeight ? videoResolution.maxHeight : videoResolution.height; } if (mediaSourceId) { mediaConstraints.video.mandatory = { chromeMediaSourceId: mediaSourceId }; } } return mediaConstraints.video; }; /* * Native implementation lies on webRtcAdaptor.js */ self.privateGetUserMedia = function (params) { self.getRtcLibrary().checkMediaSourceAvailability(function mediaSourceCallback() { var mediaInfo, privateMedia, constraints = { audio: params.options.audioConstraints, video: params.options.videoConstraints }; self.getRtcLibrary().getUserMedia(constraints, function privateGetUserMediaSuccessCallback(stream) { privateMedia = { stream: stream, privateStream: params.options.privateStream }; self.getPrivateStreamMap().add(stream.id, privateMedia); mediaInfo = { id: stream.id, stream: stream, streamURL: self.getRtcLibrary().getURLFromStream(stream) }; _utils.callFunctionIfExist(params.onSuccess, mediaInfo); }, function privateGetUserMediaFailureCallback() { _utils.callFunctionIfExist(params.onFailure, _call.mediaErrors.NOT_ALLOWED); }); }); }; /* * Native implementation lies on webRtcAdaptor.js */ self.getCameraList = function (onSuccess) { var index, cameraList = [], sourceList = []; self.getRtcLibrary().checkMediaSourceAvailability(function mediaSourceCallback(mediaSourceInfo) { sourceList = mediaSourceInfo.sourceList; for (index = 0; index < sourceList.length; index++) { if (sourceList[index].kind === 'video' || sourceList[index].kind === 'videoinput') { cameraList.push(sourceList[index]); } } _utils.callFunctionIfExist(onSuccess, cameraList); }); }; /* * Native implementation lies on webRtcAdaptor.js */ self.getMicrophoneList = function (onSuccess) { var index, microphoneList = [], sourceList = []; self.getRtcLibrary().checkMediaSourceAvailability(function mediaSourceCallback(mediaSourceInfo) { sourceList = mediaSourceInfo.sourceList; for (index = 0; index < sourceList.length; index++) { if (sourceList[index].kind === 'audio' || sourceList[index].kind === 'audioinput') { microphoneList.push(sourceList[index]); } } _utils.callFunctionIfExist(onSuccess, microphoneList); }); }; /* * Native implementation lies on webRtcAdaptor.js */ self.getSpeakerList = function (onSuccess) { var index, speakerList = [], sourceList = []; self.getRtcLibrary().checkMediaSourceAvailability(function mediaSourceCallback(mediaSourceInfo) { sourceList = mediaSourceInfo.sourceList; for (index = 0; index < sourceList.length; index++) { if (sourceList[index].kind === 'audiooutput') { speakerList.push(sourceList[index]); } } _utils.callFunctionIfExist(onSuccess, speakerList); }); }; self.removeStreamById = function (id) { var localStream = self.getStreamById(id); if (localStream) { self.getRtcLibrary().stopStream(localStream.stream); self.removeStreamFromMap(id); } }; self.updateCandidates = function (call) { // check if peer has remote description // if not it means call isn't established yet and // updateIceCandidate requests will be rejected from Spidr if (call.peer.remoteDescription && call.peer.remoteDescription.sdp) { logger.debug('updateCandidates is called with: ', call.candidateArray); _utils.callFunctionIfExist(call.updateCandidates, call.candidateArray); call.candidateArray = []; self.clearUpdateCandidateInterval(call); } else { logger.warn('remote party is not ready to receive candidates'); if (!call.updateCandidateInterval) { call.updateCandidateInterval = setInterval(function () { self.updateCandidates(call); }, 1000); } } }; self.addRemoteCandidates = function (call, candidateArray) { var peer = call.peer, candidate, length = candidateArray.length; for (var i = 0; i < length; i++) { // update candidate parameter type from Object to RTCIceCandidate, Firefox can only work with RTCIceCandidate candidate = self.getRtcLibrary().createRTCIceCandidate(candidateArray[i]); logger.debug('candidate to be added: ', candidate); peer.addIceCandidate(candidate).then(function () { logger.debug('addIceCandidate success: '); }).catch(function (e) { logger.error('Error: Failure during addIceCandidate : ', e); }); } }; /** * Changes the sinkId for the current call's video element. * This changes the speaker used for audio. The "sink Id" is the speaker Id. */ self.setContainerSinkId = function (speakerId, onSuccess, onFailure) { if (!speakerId) { _utils.callFunctionIfExist(onFailure, 'No speaker ID provided.'); return; } logger.debug('Setting container\'s speaker id.', speakerId); var videoEl; if (self.getDefaultVideoContainer()) { // DefaultVideoContainer has both remote and local video elements. videoEl = self.getDefaultVideoContainer().children[0].firstChild; } else if (self.getRemoteVideoContainer()) { // RemoteVideoContainer is only the remote video element. videoEl = self.getRemoteVideoContainer().children[0]; } else { logger.debug('No video container found.'); _utils.callFunctionIfExist(onFailure, 'No video container found.'); return; } if (videoEl && typeof videoEl.sinkId !== 'undefined') { logger.debug('Changing sinkId for element:', videoEl); videoEl.setSinkId(speakerId).then(function () { logger.debug('Speaker successfully changed.', speakerId); _utils.callFunctionIfExist(onSuccess); }).catch(function (error) { logger.debug('Failed to change speaker.', error); _utils.callFunctionIfExist(onFailure, 'Failed to change speaker.'); }); } else { logger.warn('Changing speaker not supported for this browser.'); _utils.callFunctionIfExist(onFailure, 'Not supported.'); } }; logger.debug('WebRtcAdaptor initialized'); } /***/ }), /***/ "../fcs/src/js/webrtc/adaptor/webRtcChromeAdaptor.js": /*!***********************************************************!*\ !*** ../fcs/src/js/webrtc/adaptor/webRtcChromeAdaptor.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebRtcChromeAdaptorImpl = WebRtcChromeAdaptorImpl; var _call = __webpack_require__(/*! ../../call/call.js */ "../fcs/src/js/call/call.js"); var _utils2 = __webpack_require__(/*! ../../utils */ "../fcs/src/js/utils/index.js"); function WebRtcChromeAdaptorImpl(_ref) { var _super = _ref.base, _model = _ref.model, _logManager = _ref.LogManager, _utils = _ref.Utils; var self = this, logger = _logManager.getLogger('WebRtcChromeAdaptorImpl'); logger.debug('WebRtcChromeAdaptor initializing'); /* * Native implementation lies on webRtcAdaptor.js * Most of this function is identitical to the native implementation. */ self.startScreenMedia = function (onSuccess, onFailure, onEnded) { self.getRtcLibrary().checkMediaSourceAvailability(function mediaSourceCallback(mediaSourceInfo) { var video_constraints; self.setMediaSources(mediaSourceInfo); if (self.getScreenSourceAvailable()) { video_constraints = { mandatory: { 'maxFrameRate': self.getScreenFrameRate(), 'maxWidth': self.getScreenWidth(), 'maxHeight': self.getScreenHeight() }, mediaSource: 'screen' }; // This if statement is the only change from the default adaptor. if (self.getMediaSourceId()) { video_constraints.mandatory.chromeMediaSourceId = self.getMediaSourceId(); } self.getRtcLibrary().getUserMedia({ video: video_constraints }, function (stream) { var mediaInfo = self.replaceVideoStream(self.getLocalMedia().stream, stream), oldStream = self.getScreenStream(); // If there is an old screen stream, just stop it but prevent the stop from happening if (oldStream) { oldStream.getVideoTracks()[0].onended = null; self.getRtcLibrary().stopStream(oldStream); } stream.getVideoTracks()[0].onended = onEnded; self.setScreenStream(stream); logger.debug('user granted access to local media.'); _utils.callFunctionIfExist(onSuccess, mediaInfo); }, function () { logger.debug('Failed to get access to screen media.'); _utils.callFunctionIfExist(onFailure, _call.mediaErrors.NOT_ALLOWED); }, onEnded); } else { _utils.callFunctionIfExist(onFailure, _call.mediaErrors.NOT_FOUND); } }); }; (0, _utils2.compose)(_super, self); (0, _utils2.compose)(_model, self); logger.debug('WebRtcChromeAdaptor initialized'); } /***/ }), /***/ "../fcs/src/js/webrtc/adaptor/webRtcContainerAdaptor.js": /*!**************************************************************!*\ !*** ../fcs/src/js/webrtc/adaptor/webRtcContainerAdaptor.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebRtcContainerAdaptorImpl = WebRtcContainerAdaptorImpl; var _constants = __webpack_require__(/*! ../../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); var _utils2 = __webpack_require__(/*! ../../utils */ "../fcs/src/js/utils/index.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function WebRtcContainerAdaptorImpl(_ref) { var _super = _ref.base, _model = _ref.model, _logManager = _ref.LogManager, _utils = _ref.Utils, _sdpParser = _ref.SdpParser, _config = _ref.Config, _sdpPipeline = _ref.SdpPipeline; var self = this, logger = _logManager.getLogger('WebRtcContainerAdaptorImpl'); logger.debug('WebRtcContainerAdaptor initializing'); (0, _utils2.compose)(_super, self); (0, _utils2.compose)(_model, self); // Container implementation lies on webRtcContainerAdaptor.js self.performVideoStartWorkaround = function (operation, call, onSuccess, onFail) { var peer = call.peer, remoteAudioState, remoteVideoState, callSdpWithNoSsrc, localSdp; //disable the workaround by default, as it is not necessairy in current version of Chrome if (!_config.performVideoStartWorkaround) { onSuccess(); return; } if (!_sdpParser.isSdpHasVideo(call.sdp)) { self.setRemoteDescription(operation, call, null, null, call.sdp, onSuccess, onFail); return; } logger.debug('Workaround to play video'); localSdp = call.stableLocalSdp ? call.stableLocalSdp : call.peer.localDescription.sdp; call.sdp = _sdpParser.addSdpMissingCryptoLine(call.sdp); remoteAudioState = _sdpParser.getAudioSdpDirection(call.sdp); remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); call.sdp = _sdpParser.updateAudioSdpDirectionToInactive(call.sdp); call.sdp = _sdpParser.updateVideoSdpDirectionToInactive(call.sdp); call.sdp = _sdpParser.setTcpSetupAttributeToActpass(call.sdp, self.isDtlsEnabled()); // In Peer-Peer call, in order to remove remote stream properly, // ssrc lines should be deleted so that workaround below will // first remove the remote stream and then re-add it according to // actuall call sdp. // In Non Peer-Peer call, ther is no ssrc line in sdp so it is safe // to keep method below. callSdpWithNoSsrc = _sdpParser.deleteSsrcFromSdp(call.sdp); logger.trace('performVideoStartWorkaround: Setting remote description with (offer) SDP: ' + callSdpWithNoSsrc); self.setRemoteDescription(null, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, callSdpWithNoSsrc, function pvswFirstSetRemoteDescriptionSuccessCallback() { logger.debug('performVideoStartWorkaround: first setRemoteDescription success'); // restore original values call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, remoteAudioState); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, remoteVideoState); logger.trace('performVideoStartWorkaround: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(operation, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function pvswSecondSetRemoteDescriptionSuccessCallback() { logger.debug('performVideoStartWorkaround: second setRemoteDescription success'); peer.createAnswer(function pvswCreateAnswerSuccessCallback(obj) { if (remoteAudioState === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { obj.sdp = _sdpParser.updateAudioSdpDirectionToInactive(obj.sdp); } if (remoteVideoState === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { obj.sdp = _sdpParser.updateVideoSdpDirectionToInactive(obj.sdp); } else if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } obj.sdp = _sdpParser.checkAndRestoreICEParams(obj.sdp, call.sdp); obj.sdp = _sdpParser.setTcpSetupAttributeTo(obj.sdp, call.localTcpSetupAttribute, self.isDtlsEnabled()); obj.sdp = _sdpParser.updateVersion(localSdp, obj.sdp); obj.sdp = _sdpPipeline(call.id, obj.sdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); logger.trace('performVideoStartWorkaround: Setting local description with (answer) SDP: ' + obj.sdp); peer.setLocalDescription(self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, obj.sdp), function pvswSetLocalDescriptionSuccessCallback() { logger.debug('performVideoStartWorkaround: setlocalDescription success'); _utils.callFunctionIfExist(onSuccess); }, function pvswSetLocalDescriptionFailureCallback(e) { logger.debug('performVideoStartWorkaround: setlocalDescription failed!!' + e); _utils.callFunctionIfExist(onFail, 'performVideoStartWorkaround: setlocalDescription failed!!'); }); }, function pvswCreateAnswerFailureCallback(e) { logger.debug('performVideoStartWorkaround: createAnswer failed!! ' + e); _utils.callFunctionIfExist(onFail, 'Session cannot be created'); }); }, function pvswSecondSetRemoteDescriptionFailureCallback(e) { logger.debug('performVideoStartWorkaround: second setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(onFail, 'performVideoStartWorkaround: second setRemoteDescription failed!!'); }); }, function pvswFirstSetRemoteDescriptionFailureCallback(e) { logger.debug('performVideoStartWorkaround: first setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(onFail, 'performVideoStartWorkaround: first setRemoteDescription failed!!'); }); }; // Container implementation lies on webRtcContainerAdaptor.js self.createAnswer = function (call, successCallback, failureCallback, isVideoEnabled) { logger.debug('createAnswer: isVideoEnabled= ' + isVideoEnabled + ' state= ' + call.peer.signalingState); var peer = call.peer; if (call.localMedia && call.localMedia.stream) { call.peer.addStream(call.localMedia.stream); } call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, null, self.isH264Enabled()); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); call.sdp = _sdpParser.deleteFingerprintOrCrypto(call.sdp, self.isDtlsEnabled()); if (!_sdpParser.isSdpVideoSendEnabled(call.sdp)) { // delete ssrc only from video, keep audio ssrc to hear audio call.sdp = _sdpParser.deleteInactiveVideoSsrc(call.sdp); } logger.trace('createAnswer: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function createAnswerSetRemoteDescriptionSuccessCallback() { call.remoteVideoState = _sdpParser.getSdpDirection(call.sdp, _constants2.default.STRING.VIDEO); peer.createAnswer(function (oSdp) { isVideoEnabled = isVideoEnabled && self.getVideoSourceAvailable() && _sdpParser.isSdpHasVideo(call.sdp); if (isVideoEnabled) { if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { oSdp.sdp = _sdpParser.updateSdpDirection(oSdp.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { if (_sdpParser.getVideoSdpDirection(call.sdp) !== _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { oSdp.sdp = _sdpParser.updateSdpDirection(oSdp.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { oSdp.sdp = _sdpParser.updateSdpDirection(oSdp.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } } else { if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { oSdp.sdp = _sdpParser.updateSdpDirection(oSdp.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } else { oSdp.sdp = _sdpParser.updateSdpDirection(oSdp.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } self.muteOnHold(call, false); // createAnswer generates an sdp without ice params // copy ice params to the local sdp // scenario: incoming video call from pcc in brokeronly config oSdp.sdp = _sdpParser.checkAndRestoreICEParams(oSdp.sdp, call.sdp); oSdp.sdp = _sdpParser.setTrickleOption(oSdp.sdp, _config.trickleIceSupport !== _constants2.default.TRICKLE.NONE); logger.trace('createAnswer: Setting local description with (answer) SDP: ' + oSdp.sdp); oSdp.sdp = _sdpPipeline(call.id, oSdp.sdp, _constants2.default.WEBRTC.SDP.OPERATION.ANSWER_CALL, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); peer.setLocalDescription(self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, oSdp.sdp), function createAnswerSetLocalDescriptionSuccessCallback() { if (_config.trickleIceSupport !== _constants2.default.TRICKLE.NONE && call.supportTrickle) { _utils.callFunctionIfExist(successCallback, oSdp.sdp); } // ELSE due to stun requests, successCallback will be called by onIceCandidate() }, function createAnswerSetLocalDescriptionFailureCallback(e) { logger.error('createAnswer: setLocalDescription failed : ' + e); _utils.callFunctionIfExist(failureCallback, 'createNativeAnswer setLocalDescription failed'); }); }, function createAnswerFailureCallback(e) { logger.error('createAnswer: failed!! Error: ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function createAnswerSetRemoteDescriptionFailureCallback(e) { logger.error('createAnswer: setremotedescription failed!! Error: ' + e); _utils.callFunctionIfExist(failureCallback, 'createAnswer setRemoteDescription failed'); }); }; // Container implementation lies on webRtcContainerAdaptor.js self.processHold = function (call, hold, local_hold_status, successCallback, failureCallback) { logger.debug('processHold: local hold= ' + local_hold_status + ' remote hold= ' + hold + ' state= ' + call.peer.signalingState); var peer = call.peer, audioDirection, videoDirection, peerLocalSdp, inactiveRemoteSdp, remoteSdp, data; peerLocalSdp = call.stableLocalSdp; var operation = hold ? _constants2.default.WEBRTC.SDP.OPERATION.HOLD : _constants2.default.WEBRTC.SDP.OPERATION.UNHOLD; audioDirection = _sdpParser.getAudioSdpDirection(call.sdp); videoDirection = _sdpParser.getVideoSdpDirection(call.sdp); if (!local_hold_status && !hold) { self.muteOnHold(call, false); } call.sdp = _sdpParser.setTcpSetupAttributeToActpass(call.sdp, self.isDtlsEnabled()); // This is required for PCC and meetme with video. // PCC and meetme(Media Server) not supperted VP8/VP9 codec. // so video calls can not be established // local video should be set to false if (!_sdpParser.isVideoCodecsSupported(call.sdp, self.isH264Enabled()) && !_sdpParser.isSdpHasVP8Codec(call.sdp) && call.sdp.indexOf(_constants2.default.SDP.M_LINE + _constants2.default.STRING.VIDEO + ' 0 ', 0) === -1) { self.setOriginatorSendLocalVideo(call, call.sdp, false); } call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, null, self.isH264Enabled()); call.sdp = _sdpParser.performVideoPortZeroWorkaround(call.sdp); call.sdp = _sdpParser.checkAndRestoreICEParams(call.sdp, peerLocalSdp); // chrome38 fix inactiveRemoteSdp = _sdpParser.updateAudioSdpDirectionToInactive(call.sdp); inactiveRemoteSdp = _sdpParser.updateVideoSdpDirectionToInactive(inactiveRemoteSdp); data = { call: call, mustCreatePeer: call.isRemoteEndFirefox, oldSdp: call.prevRemoteSdp, newSdp: call.sdp }; if (self.createNewPeerForCall(data)) { peer = call.peer; self.setTcpSetupAttiributesOnProcessAnswer(call, call.sdp); } if (_sdpParser.isSdpHasVideo(call.prevRemoteSdp) && !_sdpParser.isSdpHasVideo(call.sdp)) { self.setOriginatorSendLocalVideo(call, call.sdp, false); } inactiveRemoteSdp = _sdpParser.deleteSsrcFromSdp(inactiveRemoteSdp); // 1st setRemoteDescription to make webrtc remove the audio and/or video streams // 2nd setRemote will add the audio stream back so that services like MOH can work // This code will also run in UnHold scenario, and it will remove & add video stream logger.trace('processHold: Setting remote description with (offer) SDP: ' + inactiveRemoteSdp); self.setRemoteDescription(null, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, inactiveRemoteSdp, function processHoldSetFirstRemoteDescriptionSuccessCallback() { remoteSdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); if (_sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || _sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) { remoteSdp = _sdpParser.deleteInactiveVideoSsrc(remoteSdp); } logger.trace('processHold: Setting remote description with (offer) SDP: ' + remoteSdp); self.setRemoteDescription(operation, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, remoteSdp, function processHoldSetSecondRemoteDescriptionSuccessCallback() { if (!hold && !local_hold_status && videoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { call.remoteVideoState = _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY; } else { call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); } peer.createAnswer(function processHoldCreateAnswerSuccessCallback(obj) { logger.debug('processHold: isSdpEnabled audio= ' + _sdpParser.isAudioSdpEnabled(obj.sdp)); logger.debug('processHold: isSdpEnabled video= ' + _sdpParser.isVideoSdpEnabled(obj.sdp)); if (hold) { logger.debug('processHold: Remote HOLD'); obj.sdp = _sdpParser.respondToRemoteSdpDirections(obj.sdp, call.sdp); } else if (!local_hold_status) { logger.debug('processHold: Remote UNHOLD: direction left as it is'); if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } else { if (self.canOriginatorSendLocalVideo(call) && !_sdpParser.isVideoSdpDirectionInactive(call.sdp)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } //change audio's direction to sendrecv for ssl attendees in a 3wc obj.sdp = _sdpParser.changeDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); } else if (local_hold_status && !hold) { logger.debug('processHold: Remote UNHOLD on local hold'); if (audioDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { obj.sdp = _sdpParser.updateAudioSdpDirectionToInactive(obj.sdp); } else { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateVideoSdpDirectionToInactive(obj.sdp); } } obj.sdp = _sdpParser.updateVersion(peerLocalSdp, obj.sdp); obj.sdp = _sdpParser.checkIceParamsLengths(obj.sdp, call.sdp); obj.sdp = _sdpParser.checkAndRestoreICEParams(obj.sdp, call.sdp); if (_sdpParser.isSdpHasVideoWithZeroPort(obj.sdp) && self.getDefaultVideoContainer()) { self.useDefaultRenderer(false, false, false); } obj.sdp = _sdpParser.setTcpSetupAttributeTo(obj.sdp, call.localTcpSetupAttribute, self.isDtlsEnabled()); obj.sdp = _sdpParser.setTrickleOption(obj.sdp, call.supportTrickle); obj.sdp = _sdpPipeline(call.id, obj.sdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, obj.type); logger.trace('processHold: Setting local description with SDP: ' + obj.sdp); peer.setLocalDescription(obj, function processHoldSetLocalDescriptionSuccessCallback() { logger.debug('processHold: setLocalDescription success!! ' + 'iceConnectionState: ' + peer.iceConnectionState + ' iceGatheringState: ' + peer.iceGatheringState); if (call.supportTrickle) { _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } else if (peer.iceGatheringState === 'complete') { if (call.successCallback) { logger.debug('processHold iceGatheringState completed ' + peer.localDescription.sdp); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } } }, function processHoldSetLocalDescriptionFailureCallback(e) { logger.error('processHold: setLocalDescription failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processHoldCreateAnswerFailureCallback(e) { logger.error('processHold: createAnswer failed!!: ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processHoldSetSecondRemoteDescriptionFailureCallback(e) { logger.error('processHold: second setRemoteDescription failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processHoldSetFirstRemoteDescriptionFailureCallback(e) { logger.debug('processHold: first setRemoteDescription failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }; // Container implementation lies on webRtcContainerAdaptor.js self.processUpdate = function (call, successCallback, failureCallback) { logger.debug('processUpdate: state= ' + call.peer.signalingState); var peer = call.peer, remoteAudioState, remoteVideoState, remoteVideoDirection, callSdpWithNoSsrc, localDescObj, peerLocalSdp, data; peerLocalSdp = call.stableLocalSdp; // Meetme workaround call.sdp = _sdpParser.addSdpMissingCryptoLine(call.sdp); call.sdp = _sdpParser.checkAndRestoreICEParams(call.sdp, peerLocalSdp); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); if (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE && call.currentState === 'COMPLETED') { switch (call.remoteVideoState) { case _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE: case _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY: call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); break; case _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE: call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); break; } } call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.VIDEO); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, null, self.isH264Enabled()); //this part is a work-around for webrtc bug //set remote description with inactive media lines first. //then set remote description with original media lines. //keep original values of remote audio and video states remoteAudioState = _sdpParser.getAudioSdpDirection(call.sdp); remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); //This is highly required for meetme on DTLS call.sdp = _sdpParser.setTcpSetupAttributeToActpass(call.sdp, self.isDtlsEnabled()); // delete all ssrc lines from the sdp before setting first remote description // set second remote description with all ssrc lines included if (remoteVideoState === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || remoteVideoState === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) { call.sdp = _sdpParser.deleteInactiveVideoSsrc(call.sdp); } data = { call: call, mustCreatePeer: call.isRemoteEndFirefox, oldSdp: call.prevRemoteSdp, newSdp: call.sdp }; if (self.createNewPeerForCall(data)) { peer = call.peer; self.setTcpSetupAttiributesOnProcessAnswer(call, call.sdp); } //This is highly required for meetme on DTLS call.sdp = _sdpParser.setTcpSetupAttributeToActpass(call.sdp, self.isDtlsEnabled()); //set media lines with inactive state for workaround call.sdp = _sdpParser.updateAudioSdpDirectionToInactive(call.sdp); call.sdp = _sdpParser.updateVideoSdpDirectionToInactive(call.sdp); callSdpWithNoSsrc = _sdpParser.deleteSsrcFromSdp(call.sdp); logger.trace('processUpdate: Setting remote description with (offer) SDP: ' + callSdpWithNoSsrc); self.setRemoteDescription(null, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, callSdpWithNoSsrc, function processUpdateWorkaroundSetRemoteDescriptionSuccessCallback() { logger.debug('processUpdate: workaround setRemoteDescription success'); //restore original values call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, remoteAudioState); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, remoteVideoState); logger.trace('processUpdate: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.UPDATE, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function processUpdateSetRemoteDescriptionSuccessCallback() { logger.debug('processUpdate: setRemoteDescription success'); call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); peer.createAnswer(function processUpdateCreateAnswerSuccessCallback(obj) { logger.debug('processUpdate: isSdpEnabled audio= ' + _sdpParser.isAudioSdpEnabled(obj.sdp)); logger.debug('processUpdate: isSdpEnabled video= ' + _sdpParser.isVideoSdpEnabled(obj.sdp)); if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } else { if (self.canOriginatorSendLocalVideo(call) && !_sdpParser.isVideoSdpDirectionInactive(call.sdp)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } obj.sdp = _sdpParser.updateVersion(peerLocalSdp, obj.sdp); obj.sdp = _sdpParser.checkIceParamsLengths(obj.sdp, call.sdp); obj.sdp = _sdpParser.setTcpSetupAttributeTo(obj.sdp, call.localTcpSetupAttribute, self.isDtlsEnabled()); obj.sdp = _sdpParser.setTrickleOption(obj.sdp, call.supportTrickle); obj.sdp = _sdpPipeline(call.id, obj.sdp, _constants2.default.WEBRTC.SDP.OPERATION.UPDATE, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); localDescObj = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, obj.sdp); logger.trace('processUpdate: Setting local description with (answer) SDP: ' + obj.sdp); peer.setLocalDescription(localDescObj, function processUpdateSetLocalDescriptionSuccessCallback() { logger.debug('processUpdate setLocalDescription success. iceConnectionState: ' + peer.iceConnectionState + ' iceGatheringState: ' + peer.iceGatheringState); if (call.supportTrickle) { _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } else if (peer.iceGatheringState === 'complete') { if (call.successCallback) { logger.debug('processUpdate iceGatheringState completed ' + peer.localDescription.sdp); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } } }, function processUpdateSetLocalDescriptionSuccessCallback(e) { logger.debug('processUpdate: setlocalDescription failed!!' + e); _utils.callFunctionIfExist(failureCallback, 'processUpdate: setlocalDescription failed!!'); }); }, function processUpdateCreateAnswerFailureCallback(e) { logger.debug('processUpdate: createAnswer failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processUpdateSetRemoteDescriptionSuccessCallback(e) { logger.debug('processUpdate: setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(failureCallback, 'processUpdate: setRemoteDescription failed!!'); }); }, function processUpdateWorkaroundSetRemoteDescriptionSuccessCallback(e) { logger.debug('processUpdate: workaround setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(failureCallback, 'processUpdate: workaround setRemoteDescription failed!!'); }); }; // Container implementation lies on webRtcContainerAdaptor.js self.processAnswer = function (call, onSuccess, onFail) { logger.debug('processAnswer: state= ' + call.peer.signalingState); var onSuccessAfterWorkarounds, setRemoteDescription, remoteVideoDirection, localVideoDirection, peer = call.peer, origSdp; onSuccessAfterWorkarounds = function onSuccessAfterWorkarounds() { call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); _utils.callFunctionIfExist(onSuccess); }; setRemoteDescription = function setRemoteDescription(operation, call, onSuccess, onFailure) { logger.trace('processAnswer: Setting remote description with (answer) SDP: ' + call.sdp); self.setRemoteDescription(operation, call, peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function () { logger.debug('processAnswer: setRemoteDescription success'); onSuccess(); }, function (e) { logger.error('processAnswer: setRemoteDescription failed: ' + e); onFailure(); }); }; call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, peer.localDescription.sdp, self.isH264Enabled()); call.sdp = _sdpParser.performVideoPortZeroWorkaround(call.sdp); if (peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.HAVE_REMOTE_PRANSWER) { if (_sdpParser.isIceLite(call.prevRemoteSdp) !== _sdpParser.isIceLite(call.sdp)) { logger.debug('ice - ice-lite change.'); onFail(_constants2.default.WEBRTC.ERROR.ICE_ICELITE); return; } origSdp = call.sdp; call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); logger.debug('call processPrAnswer again to trigger on remote stream added with updated sdp.'); self.processPreAnswer(call, function () { call.sdp = origSdp; logger.debug('processPrAnswer success callback. Restore original sdp.'); setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); }, function () { call.sdp = origSdp; logger.debug('processPrAnswer failure callback. Restore original sdp.'); setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); }); return; } remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); localVideoDirection = _sdpParser.getVideoSdpDirection(call.peer.localDescription.sdp); // this is needed for buggy webrtc api. when term answers with video to audio only call // this scenario does not work without converting to sendrecv logger.debug('processAnswer: ice-lite: do remote video escalation'); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.VIDEO); if ((localVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY || localVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) && (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY)) { // delete ssrc only from video, keep audio ssrc to hear audio call.sdp = _sdpParser.deleteInactiveVideoSsrc(call.sdp); // Audio <--> Audio : apply workaround step 1 setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); } else if (localVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY && (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY || remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE)) { // Audio <--> Audio-Video setRemoteDescription(null, call, function () { self.performVideoStartWorkaround(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); }, onFail); } else { // Audio-Video <--> Audio-Video // there is remote video, no need for orig side workaround setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); } }; // Container implementation lies on webRtcContainerAdaptor.js self.processRespond = function (call, onSuccess, onFail, isJoin) { var remoteVideoDirection, callSdpWithNoSsrc, peer = call.peer, remoteSdpHasVideo = false; logger.debug('processRespond: state= ' + call.peer.signalingState); if (call.peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.STABLE) { //if we are in stable state we should not change remotedescription self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, null, null, call.sdp, onSuccess, onFail); return; } remoteSdpHasVideo = _sdpParser.isSdpHasVideo(call.sdp); if (remoteSdpHasVideo) { call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, call.stableLocalSdp, self.isH264Enabled()); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); if (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE && call.currentState === 'COMPLETED') { switch (call.remoteVideoState) { case _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE: case _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY: call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); break; } } call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.VIDEO); } if (isJoin) { call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); self.muteOnHold(call, false); } // delete all ssrc lines from the sdp before setting first remote description // set second remote description with all ssrc lines included if (remoteSdpHasVideo && (_sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || _sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY)) { call.sdp = _sdpParser.deleteInactiveVideoSsrc(call.sdp); } callSdpWithNoSsrc = _sdpParser.deleteSsrcFromSdp(call.sdp); logger.trace('processRespond: Setting remote description with (answer) SDP: ' + callSdpWithNoSsrc); self.setRemoteDescription(null, call, peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, callSdpWithNoSsrc, function () { logger.debug('processRespond: setRemoteDescription success'); var onSuccessAfterWorkarounds = function onSuccessAfterWorkarounds() { call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); _utils.callFunctionIfExist(onSuccess); }; self.performVideoStartWorkaround(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); }, function (e) { logger.debug('processRespond: setRemoteDescription failed: ' + e); _utils.callFunctionIfExist(onFail); }); }; // Container implementation lies on webRtcContainerAdaptor.js self.processHoldRespond = function (call, onSuccess, onFailure, isJoin) { var remoteAudioDirection, remoteVideoDirection, onSuccessAfterWorkaround, localHoldFlag = false, remoteHoldFlag = false, data; onSuccessAfterWorkaround = function onSuccessAfterWorkaround() { //call.remoteVideoState = getSdpDirection(call.sdp, video); _utils.callFunctionIfExist(onSuccess); }; data = { call: call }; if (self.createNewPeerForCall(data)) { self.setTcpSetupAttiributesOnProcessAnswer(call, call.sdp); } logger.debug('processHoldRespond: state= ' + call.peer.signalingState + ' call.currentState= ' + call.currentState); _sdpParser.init(call.sdp); remoteAudioDirection = _sdpParser.getAudioSdpDirection(call.sdp); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); var isHold = remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY; var operation = isHold ? _constants2.default.WEBRTC.SDP.OPERATION.HOLD : _constants2.default.WEBRTC.SDP.OPERATION.UNHOLD; if (call.peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.STABLE) { //if we are in stable state we should not change remotedescription self.onRemoteStreamAdded(call); self.setRemoteDescription(operation, call, null, null, call.sdp, onSuccess, onFailure); return; } call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, call.stableLocalSdp, self.isH264Enabled()); remoteHoldFlag = _sdpParser.isRemoteHold(); localHoldFlag = call.currentState === 'LOCAL_HOLD'; call.remoteVideoState = remoteVideoDirection; logger.debug('processHoldRespond: localHold= ' + localHoldFlag + ' remoteHold= ' + remoteHoldFlag); /* Required for MOH - start */ if (remoteHoldFlag === false) { if (remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE && call.currentState === 'REMOTE_HOLD') { logger.debug('set current web state to COMPLETED'); call.previousState = call.currentState; call.currentState = 'COMPLETED'; } } else { if (call.currentState === 'COMPLETED') { logger.debug('set current web state to REMOTE_HOLD'); call.previousState = call.currentState; call.currentState = 'REMOTE_HOLD'; } } if (localHoldFlag || remoteHoldFlag) { logger.debug('processHoldRespond: ' + call.currentState + ' : video -> inactive'); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } if (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE && call.currentState === 'COMPLETED') { logger.debug('processHoldRespond: video inactive -> recvonly'); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } /* Required for MOH - end */ if (isJoin) { self.muteOnHold(call, false); } // this is required for displaying remote video when direction is send only call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.VIDEO); if (_sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || _sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) { call.sdp = _sdpParser.deleteInactiveVideoSsrc(call.sdp); } if (localHoldFlag && remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) { logger.debug('processHoldRespond: Mute Remote Audio'); call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); remoteAudioDirection = _sdpParser.getAudioSdpDirection(call.sdp); } if (localHoldFlag && remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) { logger.debug('processHoldRespond: Mute Remote Video'); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); } // If we have a configuration to force disable media on hold we tell chrome that the other side is inactive this will // prevent chrome from sending noise even after being muted. if (localHoldFlag && _config.forceDisableMediaOnHold && remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) { logger.debug('processHoldRespond: Changing remote direction from recvonly to inactive'); call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); remoteAudioDirection = _sdpParser.getAudioSdpDirection(call.sdp); } if (isHold) { logger.debug('processHoldRespond: Setting remote description with (answer) SDP: ' + call.sdp); self.setRemoteDescription(operation, call, call.peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function processHoldRespondSetRemoteDescriptionSuccessCallback() { logger.debug('processHoldRespond: setRemoteDescription typeAns success'); onSuccessAfterWorkaround(); }, function processHoldRespondSetRemoteDescriptionFailureCallback(e) { logger.debug('processHoldRespond: setRemoteDescription typeAns failed: ' + e); _utils.callFunctionIfExist(onFailure); }); } else { self.setRemoteDescription(null, call, call.peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function processHoldRespondSetRemoteDescriptionSuccessCallback() { logger.debug('processHoldRespond: setRemoteDescription typeAns success'); self.performVideoStartWorkaround(operation, call, onSuccessAfterWorkaround, onFailure); }, function processHoldRespondSetRemoteDescriptionFailureCallback(e) { logger.debug('processHoldRespond: setRemoteDescription typeAns failed: ' + e); _utils.callFunctionIfExist(onFailure); }); } }; logger.debug('WebRtcContainerAdaptor initialized'); } /***/ }), /***/ "../fcs/src/js/webrtc/adaptor/webRtcFirefoxAdaptor.js": /*!************************************************************!*\ !*** ../fcs/src/js/webrtc/adaptor/webRtcFirefoxAdaptor.js ***! \************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebRtcFirefoxAdaptorImpl = WebRtcFirefoxAdaptorImpl; var _constants = __webpack_require__(/*! ../../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); var _utils2 = __webpack_require__(/*! ../../utils */ "../fcs/src/js/utils/index.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function WebRtcFirefoxAdaptorImpl(_ref) { var _super = _ref.base, _model = _ref.mode, _logManager = _ref.LogManager, _utils = _ref.Utils, _sdpParser = _ref.SdpParser, _config = _ref.Config, _sdpPipeline = _ref.SdpPipeline; var self = this, logger = _logManager.getLogger('WebRtcFirefoxAdaptorImpl'); logger.debug('WebRtcFirefoxAdaptor initializing'); (0, _utils2.compose)(_super, self); (0, _utils2.compose)(_model, self); // firefoxPerformSdpWorkaroundsBeforeProcessingIncomingSdp self.performSdpWorkaroundsBeforeProcessingIncomingSdp = function (sdp) { sdp = _sdpParser.updateH264LevelTo42E01F(sdp, self.isH264Enabled()); sdp = _sdpParser.deleteBandwidthLineFromSdp(sdp); sdp = _sdpParser.addRtpmapForPCMU(sdp); sdp = _sdpParser.addRtpmapForPCMA(sdp); sdp = _sdpParser.removeG722Codec(sdp); sdp = _sdpParser.setOpusCodecToLowerCase(sdp); return sdp; }; // firefoxCreateOffer self.createOffer = function (call, successCallback, failureCallback, sendInitialVideo, offerToReceiveVideo) { logger.debug('createOffer: sendInitialVideo= ' + sendInitialVideo + ' state= ' + call.peer.signalingState); var peer = call.peer; if (call.localMedia && call.localMedia.stream) { call.peer.addStream(call.localMedia.stream); } peer.createOffer(function createOfferSuccessCallback(oSdp) { sendInitialVideo = sendInitialVideo && self.getVideoSourceAvailable(); if (sendInitialVideo) { oSdp.sdp = _sdpParser.updateVideoSdpDirection(oSdp.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { oSdp.sdp = _sdpParser.updateVideoSdpDirection(oSdp.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } oSdp.sdp = _sdpParser.deleteCryptoZeroFromSdp(oSdp.sdp); oSdp.sdp = _sdpParser.removeG722Codec(oSdp.sdp); oSdp.sdp = _sdpParser.deleteCryptoFromSdp(oSdp.sdp, self.isDtlsEnabled()); oSdp.sdp = _sdpParser.setTcpSetupAttributeToActpass(oSdp.sdp, self.isDtlsEnabled()); oSdp.sdp = self.updateCodecs(call, oSdp.sdp); oSdp.sdp = _sdpParser.updateOpusConfig(oSdp.sdp, _config.opusConfig); oSdp.sdp = _sdpParser.setTrickleOption(oSdp.sdp, _config.trickleIceSupport !== _constants2.default.TRICKLE.NONE); oSdp.sdp = _sdpPipeline(call.id, oSdp.sdp, _constants2.default.WEBRTC.SDP.OPERATION.START_CALL, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); logger.trace('createOffer: Setting local description with (offer) SDP: ' + oSdp.sdp); peer.setLocalDescription(self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, oSdp.sdp), function createOfferSetLocalDescriptionSuccessCallback() { if (_config.trickleIceSupport === _constants2.default.TRICKLE.FULL) { _utils.callFunctionIfExist(successCallback, oSdp.sdp); } // ELSE due to stun requests, successCallback will be called by onIceCandidate() }, function createOfferSetLocalDescriptionFailureCallback(error) { logger.error('createOffer: setLocalDescription failed : ' + error); _utils.callFunctionIfExist(failureCallback, 'createOffer: setLocalDescription failed'); }); }, function createOfferFailureCallback(e) { logger.error('createOffer: createOffer failed!! ' + e); _utils.callFunctionIfExist(failureCallback); }, { offerToReceiveVideo: offerToReceiveVideo ? 1 : 0 }); }; // firefoxCreateReOffer self.createReOffer = function (call, onSuccess, onFailure, usePreviousMediaDirection) { var peer = call.peer, localDescObj, localAudioDirection, localVideoDirection, prevLocalSdp = call.stableLocalSdp, deleteVideoStream = false, data; logger.debug('createReOffer:' + call.id); if (!usePreviousMediaDirection) { deleteVideoStream = !call.initialVideoState && _sdpParser.isSdpHasVideo(call.stableLocalSdp); } data = { call: call, mustCreatePeer: true, deleteVideoStream: deleteVideoStream }; if (self.createNewPeerForCall(data)) { peer = call.peer; } peer.createOffer(function createReOfferCreateOfferSuccessCallback(oSdp) { if (usePreviousMediaDirection) { localAudioDirection = _sdpParser.getAudioSdpDirection(prevLocalSdp); oSdp.sdp = _sdpParser.updateAudioSdpDirection(oSdp.sdp, localAudioDirection); localVideoDirection = _sdpParser.getVideoSdpDirection(prevLocalSdp); oSdp.sdp = _sdpParser.updateVideoSdpDirection(oSdp.sdp, localVideoDirection); } oSdp.sdp = _sdpParser.deleteCryptoZeroFromSdp(oSdp.sdp); oSdp.sdp = _sdpParser.removeG722Codec(oSdp.sdp); oSdp.sdp = _sdpParser.deleteCryptoFromSdp(oSdp.sdp, self.isDtlsEnabled()); oSdp.sdp = _sdpParser.setTcpSetupAttributeToActpass(oSdp.sdp, self.isDtlsEnabled()); oSdp.sdp = _sdpParser.updateVersion(prevLocalSdp, oSdp.sdp); oSdp.sdp = self.updateCodecs(call, oSdp.sdp); oSdp.sdp = _sdpParser.updateOpusConfig(oSdp.sdp, _config.opusConfig); oSdp.sdp = _sdpParser.setTrickleOption(oSdp.sdp, _config.trickleIceSupport !== _constants2.default.TRICKLE.NONE); oSdp.sdp = _sdpPipeline(call.id, oSdp.sdp, _constants2.default.WEBRTC.SDP.OPERATION.REOFFER, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); localDescObj = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, oSdp.sdp); logger.trace('createReOffer: Setting local description with (offer) SDP: ' + oSdp.sdp); peer.setLocalDescription(localDescObj, function createReOfferSetLocalDescriptionSuccessCallback() { logger.debug('createReOffer: setLocalDescription success' + call.id); if (_config.trickleIceSupport === _constants2.default.TRICKLE.FULL) { _utils.callFunctionIfExist(onSuccess, oSdp.sdp); } }, function createReOfferSetLocalDescriptionFailureCallback(e) { logger.debug('createReOffer: setLocalDescription failed!!' + e + call.id); _utils.callFunctionIfExist(onFailure); }); }, function createReOfferCreateOfferFailureCallback(e) { logger.error('createReOffer: createOffer failed!! ' + e); _utils.callFunctionIfExist(onFailure); }); }; // firefoxProcessAnswer self.processAnswer = function (call, successCallback, failureCallback) { var peer = call.peer; logger.debug('processAnswer: state= ' + peer.signalingState); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, peer.localDescription.sdp, self.isH264Enabled()); call.sdp = _sdpParser.performVideoPortZeroWorkaround(call.sdp); call.sdp = _sdpPipeline(call.id, call.sdp, _constants2.default.WEBRTC.SDP.OPERATION.ANSWER_CALL, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_REMOTE, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); logger.trace('processAnswer: Setting remote description with (answer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.ANSWER_CALL, call, peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function processAnswerSetRemoteDescriptionSuccessCallback() { logger.debug('processAnswer: setRemoteDescription success'); call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); _utils.callFunctionIfExist(successCallback); }, function processAnswerSetRemoteDescriptionFailureCallback(e) { logger.error('processAnswer: setRemoteDescription failed: ' + e.message); _utils.callFunctionIfExist(failureCallback); }); }; // firefoxRevertRtcState self.revertRtcState = function (call, successCallback) { //no need to create new peer to handle revertRtc case. Peer will be handled after retryAfter period. // TODO: Setting timeout to 0 skips the problem of successive holds without glare condition // A real solution have to be found setTimeout(function () { _utils.callFunctionIfExist(successCallback, call); }, 0); }; // firefoxCreateHoldUpdate self.createHoldUpdate = function (call, hold, remote_hold_status, successCallback, failureCallback, useIceServer) { logger.debug('createHoldUpdate: local hold= ' + hold + ' remote hold= ' + remote_hold_status + ' state= ' + call.peer.signalingState); var peer = call.peer, localDescObj, localSdp, createHoldUpdate, hasActiveVideo; var operation = hold ? _constants2.default.WEBRTC.SDP.OPERATION.HOLD : _constants2.default.WEBRTC.SDP.OPERATION.UNHOLD; createHoldUpdate = function createHoldUpdate() { localSdp = call.stableLocalSdp; if (self.createNewPeerForCall({ call: call, mustCreatePeer: true, useIceServer: useIceServer })) { peer = call.peer; } peer.createOffer(function createHoldUpdateCreateOfferSuccessCallback(obj) { if (hold) { if (!remote_hold_status) { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateAudioSdpDirectionToInactive(obj.sdp); obj.sdp = _sdpParser.updateVideoSdpDirectionToInactive(obj.sdp); } } else if (remote_hold_status) { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } obj.sdp = self.updateCodecs(call, obj.sdp); obj.sdp = _sdpParser.updateVersion(localSdp, obj.sdp); obj.sdp = _sdpParser.deleteCryptoZeroFromSdp(obj.sdp); obj.sdp = _sdpParser.setTcpSetupAttributeToActpass(obj.sdp, self.isDtlsEnabled()); obj.sdp = _sdpParser.updateOpusConfig(obj.sdp, _config.opusConfig); obj.sdp = _sdpParser.setTrickleOption(obj.sdp, call.supportTrickle); obj.sdp = _sdpPipeline(call.id, obj.sdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); localDescObj = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, obj.sdp); logger.trace('createHoldUpdate: Setting local description with (offer) SDP: ' + obj.sdp); peer.setLocalDescription(localDescObj, function createHoldUpdateSetLocalDescriptionSuccessCallback() { logger.debug('createHoldUpdate setLocalDescription success. iceConnectionState: ' + peer.iceConnectionState + ' iceGatheringState: ' + peer.iceGatheringState); if (call.supportTrickle) { _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } else if (peer.iceGatheringState === 'complete') { if (call.successCallback) { logger.debug('createHoldUpdate iceGatheringState completed ' + peer.localDescription.sdp); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } } }, function createHoldUpdateSetLocalDescriptionFailureCallback(error) { logger.error('createHoldUpdate: setLocalDescription failed: ' + error.message); _utils.callFunctionIfExist(failureCallback); }); }, function createHoldUpdateCreateOfferFailureCallback(error) { logger.error('createHoldUpdate: createOffer failed: ' + error.message); _utils.callFunctionIfExist(failureCallback); }); }; hasActiveVideo = _sdpParser.isSdpHasVideo(call.sdp) && !_sdpParser.isVideoSdpDirectionInactive(call.stableLocalSdp); if (!call.isVideoSourceAllowed && hasActiveVideo) { // TODO: This should not be done here just for code consistency self.getUserMedia({ onSuccess: function onSuccess(mediaInfo) { self.storeLocalStreamToCall(call, mediaInfo.id); call.isVideoSourceAllowed = mediaInfo.video; createHoldUpdate(); }, onFailure: function onFailure() { _utils.callFunctionIfExist(failureCallback); }, options: { audioConstraints: true, videoConstraints: true } }); } else { if (hasActiveVideo) { call.isVideoSourceAllowed = true; } createHoldUpdate(); } }; // firefoxProcessHold self.processHold = function (call, hold, local_hold_status, successCallback, failureCallback) { logger.debug('processHold: local hold= ' + local_hold_status + ' remote hold= ' + hold + ' state= ' + call.peer.signalingState); var peer = call.peer, audioDirection = _sdpParser.getAudioSdpDirection(call.sdp); if (!local_hold_status && !hold) { self.muteOnHold(call, false); } call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, null); call.sdp = _sdpParser.performVideoPortZeroWorkaround(call.sdp); call.sdp = _sdpParser.setTcpSetupAttributeToActpass(call.sdp, self.isDtlsEnabled()); if (self.createNewPeerForCall({ call: call, mustCreatePeer: true })) { peer = call.peer; self.setTcpSetupAttiributesOnProcessAnswer(call, call.sdp); } logger.trace('processHold: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.HOLD, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function processHoldSetRemoteDescriptionSuccessCallback() { peer.createAnswer(function (obj) { if (hold) { logger.debug('processHold: Remote HOLD'); obj.sdp = _sdpParser.respondToRemoteSdpDirections(obj.sdp, call.sdp); } else if (!local_hold_status) { logger.debug('processHold: Remote UNHOLD: direction left as it is'); if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } else { if (self.canOriginatorSendLocalVideo(call) && !_sdpParser.isVideoSdpDirectionInactive(call.sdp)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } //change audio's direction to sendrecv for ssl attendees in a 3wc obj.sdp = _sdpParser.changeDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); } else if (local_hold_status && !hold) { logger.debug('processHold: Remote UNHOLD on local hold'); if (audioDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { obj.sdp = _sdpParser.updateAudioSdpDirectionToInactive(obj.sdp); } else { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateVideoSdpDirectionToInactive(obj.sdp); } } obj.sdp = _sdpParser.setTcpSetupAttributeTo(obj.sdp, call.localTcpSetupAttribute, self.isDtlsEnabled()); obj.sdp = _sdpParser.updateOpusConfig(obj.sdp, _config.opusConfig); obj.sdp = _sdpParser.setTrickleOption(obj.sdp, call.supportTrickle); obj.sdp = _sdpPipeline(call.id, obj.sdp, _constants2.default.WEBRTC.SDP.OPERATION.HOLD, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, obj.type); logger.trace('processHold: Setting local description with SDP: ' + obj.sdp); peer.setLocalDescription(obj, function processHoldSetLocalDescriptionSuccessCallback() { logger.debug('processHold: setLocalDescription succeeded'); if (call.supportTrickle) { _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } }, function processHoldSetLocalDescriptionFailureCallback(e) { logger.error('processHold: setLocalDescription failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function () { logger.debug('processHold: createAnswer failed!!'); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processHoldSetRemoteDescriptionFailureCallback(e) { logger.error('processHold: setRemoteDescription failed: ' + e.message); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }; // firefoxProcessHoldRespond self.processHoldRespond = function (call, onSuccess, onFailure, isJoin) { var remoteAudioDirection, remoteVideoDirection, localHoldFlag = false, remoteHoldFlag = false, data; logger.debug('processHoldRespond: state= ' + call.peer.signalingState + ' call.currentState= ' + call.currentState); data = { call: call }; if (self.createNewPeerForCall(data)) { self.setTcpSetupAttiributesOnProcessAnswer(call, call.sdp); } call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); if (call.peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.STABLE) { //if we are in stable state we should not change remotedescription self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.HOLD, call, null, null, call.sdp, onSuccess, onFailure); return; } call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, call.stableLocalSdp, self.isH264Enabled()); _sdpParser.init(call.sdp); remoteHoldFlag = _sdpParser.isRemoteHold(); localHoldFlag = call.currentState === 'LOCAL_HOLD'; remoteAudioDirection = _sdpParser.getAudioSdpDirection(call.sdp); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); call.remoteVideoState = remoteVideoDirection; logger.debug('processHoldRespond: localHold= ' + localHoldFlag + ' remoteHold= ' + remoteHoldFlag); /* Required for MOH - start */ if (remoteHoldFlag === false) { if (remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE && call.currentState === 'REMOTE_HOLD') { logger.debug('set current web state to COMPLETED'); call.previousState = call.currentState; call.currentState = 'COMPLETED'; } } else { if (call.currentState === 'COMPLETED') { logger.debug('set current web state to REMOTE_HOLD'); call.previousState = call.currentState; call.currentState = 'REMOTE_HOLD'; } } if (localHoldFlag || remoteHoldFlag) { logger.debug('processHoldRespond: ' + call.currentState + ' : video -> inactive'); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } /* Required for MOH - end */ if (isJoin) { self.muteOnHold(call, false); } // this is required for displaying remote video when direction is send only // call.sdp = _sdpParser.changeDirection(call.sdp, CONSTANTS.WEBRTC.MEDIA_STATE.SEND_ONLY, CONSTANTS.WEBRTC.MEDIA_STATE.SEND_RECEIVE, video); if (localHoldFlag && remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) { logger.debug('processHoldRespond: Mute Remote Audio'); call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } if (localHoldFlag && remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) { logger.debug('processHoldRespond: Mute Remote Video'); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } logger.trace('processHoldRespond: Setting remote description with (answer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.HOLD, call, call.peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function processHoldRespondSetRemoteDescriptionSuccessCallback() { logger.debug('processHoldRespond: setRemoteDescription typeAns success'); _utils.callFunctionIfExist(onSuccess); }, function processHoldRespondSetRemoteDescriptionFailureCallback(e) { logger.debug('processHoldRespond: setRemoteDescription typeAns failed: ' + e); _utils.callFunctionIfExist(onFailure); }); }; // firefoxCreateUpdate self.createUpdate = function (call, successCallback, failureCallback, isVideoStart) { logger.debug('createUpdate: isVideoStart= ' + isVideoStart + ' state= ' + call.peer.signalingState); var peer = call.peer, localDesc; if (self.createNewPeerForCall({ call: call, mustCreatePeer: true })) { peer = call.peer; self.setTcpSetupAttiributesOnProcessAnswer(call, call.sdp); } peer.createOffer(function createUpdateCreateOfferSuccessCallback(obj) { isVideoStart = isVideoStart && self.getVideoSourceAvailable(); if (isVideoStart) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { if (_sdpParser.isVideoSdpDirectionInactive(call.stableRemoteSdp)) { obj.sdp = _sdpParser.updateVideoSdpDirectionToInactive(obj.sdp); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } obj.sdp = self.updateCodecs(call, obj.sdp); obj.sdp = _sdpParser.updateVersion(call.stableLocalSdp, obj.sdp); obj.sdp = _sdpParser.setTcpSetupAttributeToActpass(obj.sdp, self.isDtlsEnabled()); obj.sdp = _sdpParser.deleteCryptoZeroFromSdp(obj.sdp); obj.sdp = _sdpParser.removeG722Codec(obj.sdp); obj.sdp = _sdpParser.deleteCryptoFromSdp(obj.sdp, self.isDtlsEnabled()); obj.sdp = _sdpParser.updateOpusConfig(obj.sdp, _config.opusConfig); obj.sdp = _sdpParser.setTrickleOption(obj.sdp, call.supportTrickle); obj.sdp = _sdpPipeline(call.id, obj.sdp, _constants2.default.WEBRTC.SDP.OPERATION.UPDATE, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); localDesc = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, obj.sdp); logger.trace('createUpdate: Setting local description with (offer) SDP: ' + obj.sdp); peer.setLocalDescription(localDesc, function createUpdateCreateOfferSetLocalDescriptionSuccessCallback() { logger.debug('createUpdate: createOffer setLocalDescription success '); // The above process un-mutes the client. We must ensure it continues to be muted if necessary. if (call.audioMuted) { logger.debug('video started while muted, re-mute the microphone'); self.muteAudioTrack(call, true, false); } if (call.supportTrickle) { _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } // ELSE since the candidates have changed we will call the successCallback at onIceCandidate }, function crateUpdateCreateOfferSetLocalDescriptionFailureCallback(e) { logger.debug('createUpdate: createOffer setLocalDescription failed: ' + e); _utils.callFunctionIfExist(failureCallback); }); }, function createUpdateCrateOfferFailureCallback(e) { logger.debug('createUpdate: createOffer failed!!: ' + e); _utils.callFunctionIfExist(failureCallback); }); }; // firefoxProcessUpdate self.processUpdate = function (call, successCallback, failureCallback) { logger.debug('processUpdate: state= ' + call.peer.signalingState); var peer = call.peer, localDescObj, peerLocalSdp; peerLocalSdp = call.stableLocalSdp; call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); // Meetme workarounds call.sdp = _sdpParser.addSdpMissingCryptoLine(call.sdp); call.sdp = _sdpParser.checkAndRestoreICEParams(call.sdp, peerLocalSdp); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, null, self.isH264Enabled()); call.sdp = _sdpParser.setTcpSetupAttributeToActpass(call.sdp, self.isDtlsEnabled()); if (self.createNewPeerForCall({ call: call, mustCreatePeer: true })) { peer = call.peer; self.setTcpSetupAttiributesOnProcessAnswer(call, call.sdp); } //This is highly required for meetme on DTLS call.sdp = _sdpParser.setTcpSetupAttributeToActpass(call.sdp, self.isDtlsEnabled()); logger.trace('processUpdate: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.UPDATE, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function processUpdateSetRemoteDescriptionSuccessCallback() { logger.debug('processUpdate: setRemoteDescription success'); call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); peer.createAnswer(function processUpdateCreateAnswerSuccessCallback(obj) { if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } else { if (self.canOriginatorSendLocalVideo(call) && !_sdpParser.isVideoSdpDirectionInactive(call.sdp)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } obj.sdp = _sdpParser.updateVersion(peerLocalSdp, obj.sdp); obj.sdp = _sdpParser.checkIceParamsLengths(obj.sdp, call.sdp); obj.sdp = _sdpParser.setTcpSetupAttributeTo(obj.sdp, call.localTcpSetupAttribute, self.isDtlsEnabled()); obj.sdp = _sdpParser.updateOpusConfig(obj.sdp, _config.opusConfig); obj.sdp = _sdpParser.setTrickleOption(obj.sdp, call.supportTrickle); obj.sdp = _sdpPipeline(call.id, obj.sdp, _constants2.default.WEBRTC.SDP.OPERATION.UPDATE, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); localDescObj = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, obj.sdp); logger.trace('processUpdate: Setting local description with (answer) SDP: ' + obj.sdp); peer.setLocalDescription(localDescObj, function processUpdateSetLocalDescriptionSuccessCallback() { logger.debug('processUpdate: setlocalDescription success'); if (call.supportTrickle) { _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } // ELSE since the candidates have changed we will call the successCallback at onIceCandidate }, function processUpdateSetLocalDescriptionSuccessCallback(e) { logger.debug('processUpdate: setlocalDescription failed!!' + e); _utils.callFunctionIfExist(failureCallback, 'processUpdate: setlocalDescription failed!!'); }); }, function processUpdateCreateAnswerFailureCallback(e) { logger.debug('processUpdate: createAnswer failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processUpdateSetRemoteDescriptionSuccessCallback(e) { logger.debug('processUpdate: setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(failureCallback, 'processUpdate: setRemoteDescription failed!!'); }); }; // firefoxProcessRespond self.processRespond = function (call, onSuccess, onFail, isJoin) { var peer = call.peer; logger.debug('processRespond: state= ' + call.peer.signalingState); call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); if (call.peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.STABLE) { //if we are in stable state we should not change remotedescription self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, null, null, call.sdp, onSuccess, onFail); return; } call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, call.stableLocalSdp, self.isH264Enabled()); if (isJoin) { call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); self.muteOnHold(call, false); } logger.trace('processRespond: Setting remote description with (answer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function processRespondSetRemoteDescriptionSuccessCallback() { logger.debug('processRespond: setRemoteDescription success'); call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); _utils.callFunctionIfExist(onSuccess); }, function processRespondSetRemoteDescriptionSuccessCallback(e) { logger.debug('processRespond: setRemoteDescription failed: ' + e); _utils.callFunctionIfExist(onFail); }); }; // firefoxSendDTMF self.sendDTMF = function (call, tone) { var audioContext, senders, dtmfSender; if (!_sdpParser.isSdpHasTelephoneEvent(call.peer.remoteDescription.sdp)) { if (call.localMedia && call.localMedia.audioContext) { audioContext = call.localMedia.audioContext; self.sendInbandDTMF(call, tone, audioContext); } else { logger.debug('No local media to send DTMF'); } } else { senders = call.peer.getSenders(); if (senders) { dtmfSender = senders[0].dtmf; if (!dtmfSender) { logger.debug('Couldn\'t find dtmf sender'); } else { dtmfSender.insertDTMF(tone, 400); } } else { logger.debug('Senders in peer connection couldn\'t be found'); } } }; // firefoxIceCandidateCollectionTimeoutHandler self.iceCandidateCollectionTimeoutHandler = function (call) { var sdp = call.peer.localDescription.sdp; self.clearIceCandidateCollectionTimer(call); if (_config.relayCandidateCollectionTimeoutCycle) { call.relayCandidateCycle++; } sdp = _sdpParser.findZeroConnectionIPandModify(sdp); // set timeout if there is no ice candidate available or // when audio, video port assignment isn't complete if (!_sdpParser.hasCandidates(sdp, call.relayCandidateCycle, _config.relayCandidateCollectionTimeoutCycle)) { logger.debug('Re-setting ice candidate collection timeout: ' + _config.iceCandidateCollectionTimeoutInterval); call.iceCandidateCollectionTimer = setTimeout(function () { self.iceCandidateCollectionTimeoutHandler(call); }, _config.iceCandidateCollectionTimeoutInterval); return; } if (call.successCallback) { logger.debug('Ice candidate collection interrupted after given timeout, invoking successCallback.'); sdp = _sdpParser.deleteCurlyBracketsSDP(sdp); if (!self.isH264Enabled()) { sdp = _sdpParser.removeH264Codec(sdp); } if (!_sdpParser.isSdpHasUfrag(sdp)) { sdp = _sdpParser.checkAndRestoreICEParams(sdp, call.stableLocalSdp); logger.debug('Absent ufrag due to inactive video direction is restored from that in stable local sdp'); } call.successCallback(sdp); } }; // firefoxSetupIceCandidateCollectionTimer self.setupIceCandidateCollectionTimer = function (call) { if (_config.iceCandidateCollectionTimeoutInterval) { if (!call.iceCandidateCollectionTimer) { logger.debug('Setting ice candidate collection timeout: ' + _config.iceCandidateCollectionTimeoutInterval); if (_config.relayCandidateCollectionTimeoutCycle) { call.relayCandidateCycle = 1; } call.iceCandidateCollectionTimer = setTimeout(function () { self.iceCandidateCollectionTimeoutHandler(call); }, _config.iceCandidateCollectionTimeoutInterval); } else { logger.trace('Ice candidate collection timer exists.'); } } }; // firefoxOnIceCandidate self.onIceCandidate = function (call, event) { var sdp; if (event.candidate === null) { logger.debug('Null candidate received.'); if (call.successCallback) { sdp = call.peer.localDescription.sdp; self.clearIceCandidateCollectionTimer(call); logger.debug('Candidates received, invoking successCallback.'); sdp = _sdpParser.deleteCurlyBracketsSDP(sdp); if (!self.isH264Enabled()) { sdp = _sdpParser.removeH264Codec(sdp); } if (!_sdpParser.isSdpHasUfrag(sdp)) { sdp = _sdpParser.checkAndRestoreICEParams(sdp, call.stableLocalSdp); logger.debug('Absent ufrag due to inactive video direction is restored from that in stable local sdp'); } call.successCallback(sdp); } } else { logger.debug('ICE candidate received: sdpMLineIndex = ' + event.candidate.sdpMLineIndex + ', candidate = ' + event.candidate.candidate + ' for call : ' + call.id); // if successCallback haven't been cleared, candidates will be sent via successCallback // otherwise candidates will be sent via updateIceCandidates request if (!call.successCallback) { if (!call.candidateArray) { call.candidateArray = []; } call.candidateArray.push(event.candidate); self.updateCandidates(call); } } }; // firefoxOnIceComplete self.onIceComplete = function (call) { var sdp; logger.debug('All ICE candidates received for call : ' + call.id); self.clearIceCandidateCollectionTimer(call); if (call.successCallback) { sdp = call.peer.localDescription.sdp; sdp = _sdpParser.deleteCurlyBracketsSDP(sdp); if (!self.isH264Enabled()) { sdp = _sdpParser.removeH264Codec(sdp); } if (!_sdpParser.isSdpHasUfrag(sdp)) { sdp = _sdpParser.checkAndRestoreICEParams(sdp, call.stableLocalSdp); logger.debug('Absent ufrag due to inactive video direction is restored from that in stable local sdp'); } logger.trace('onIceComplete sdp : ' + sdp); call.successCallback(sdp); } }; self.createDataChannel = function (dataChannelWrapperObj, onSuccess, onFailure, options) { try { dataChannelWrapperObj.dataChannel = dataChannelWrapperObj.peer.createDataChannel(options); onSuccess(dataChannelWrapperObj); } catch (error) { logger.error('Failed to create data channel, exception: ' + error.message); onFailure(error); } }; // firefoxCreateNewPeerForCall self.createNewPeerForCall = function (data) { var call = data.call, mustCreatePeer = data.mustCreatePeer, sessionIdChanged = _sdpParser.getSessionIdFromSdp(data.oldSdp) !== _sdpParser.getSessionIdFromSdp(data.newSdp), isNewPeerCreated = false, oldPeer, videoTrack, useIceServer, telephoneEventPayloadChanged = _sdpParser.hasCodecPayloadChanged(data.oldSdp, data.newSdp), isDTLSFingerprintChanged = false; if (_config.ignoreIceParamsForServices && _config.ignoreIceParamsForServices.indexOf('call') !== -1) { useIceServer = false; } else { useIceServer = true; } if (data.call && data.call.sdp && data.call.prevRemoteSdp) { isDTLSFingerprintChanged = _sdpParser.getFingerprintFromSdp(data.call.prevRemoteSdp) !== _sdpParser.getFingerprintFromSdp(data.call.sdp); } if (mustCreatePeer || telephoneEventPayloadChanged || isDTLSFingerprintChanged || sessionIdChanged) { if (call.peer) { oldPeer = call.peer; self.collectWebRtcStats(oldPeer, function (stats) { logger.debug('collectWebRtcStats successfull mozilla'); if (call.stats === undefined) { call.stats = []; } call.stats.push(stats); if (oldPeer.signalingState !== 'closed') { oldPeer.close(); } self.setPeerCount(self.getPeerCount() - 1); call.dtmfSender = null; }, function () { logger.debug('collectWebRtcStats failed mozilla'); if (oldPeer.signalingState !== 'closed') { oldPeer.close(); } self.setPeerCount(self.getPeerCount() - 1); call.dtmfSender = null; }); } logger.trace('Creating new peer for call: ' + call.id); self.createPeer(call, useIceServer, function createPeerSuccessCallback() { logger.trace('New peer has created for call: ' + call.id); if (data.deleteVideoStream) { if (call.localMedia && call.localMedia.stream) { videoTrack = call.localMedia.stream.getVideoTracks()[0]; if (videoTrack) { call.localMedia.stream.removeTrack(videoTrack); } } } call.peer.addStream(call.localMedia.stream); //clearing those since we are using a new peer self.clearTcpSetupParameters(call); isNewPeerCreated = true; }, function createPeerFailureCallback() { logger.error('New peer creation has failed!: ' + call.id); if (call.stats) { call.stats.pop(); } }); } return isNewPeerCreated; }; // firefoxCreatePeer self.createPeer = function (call, useIceServer, onSuccess, onFailure) { try { var pc, constraints = {}, i, servers = [], iceServerUrl, config; logger.info('useIceServer: ' + useIceServer); if (useIceServer) { iceServerUrl = self.getIceServerUrl(); } if (iceServerUrl instanceof Array) { for (i = 0; i < iceServerUrl.length; i++) { iceServerUrl[i].urls = iceServerUrl[i].urls.replace('turns', 'turn'); servers[i] = iceServerUrl[i]; } } else if (!iceServerUrl || iceServerUrl === '') { servers = []; } else { servers[0] = iceServerUrl; } config = { iceServers: servers, // NOTE: This is added temporarily because Chrome and Firefox have required set // by default and the media broker doesn't support multiplexing. ADG-14986 rtcpMuxPolicy: 'negotiate' }; // If present, take the call constraints provided as config. if (_config.callConstraints && _config.callConstraints.firefox) { // If any constraint is malformed, the RTCPeerConnection will fail to be created. logger.debug('Using custom peer constraints for call.', _config.callConstraints.firefox); constraints = _config.callConstraints.firefox; } constraints.optional = constraints.optional || []; constraints.optional.push({ 'DtlsSrtpKeyAgreement': self.isDtlsEnabled() }); //Add iceTransportPolicy:relay in order to force TURN if (_config.useRelayOnly) { config.iceTransportPolicy = 'relay'; } if (_config.bundlePolicy !== _constants2.default.WEBRTC.SDP.BUNDLE_POLICY.DISABLED) { config.bundlePolicy = _config.bundlePolicy; } pc = self.getRtcLibrary().createRTCPeerConnection(config, constraints); self.setPeerCount(self.getPeerCount() + 1); call.peer = pc; pc.onconnecting = function (event) { self.onSessionConnecting(call, event); }; pc.onopen = function (event) { self.onSessionOpened(call, event); }; pc.onsignalingstatechange = function (event) { self.onSignalingStateChange(call, event); }; pc.onaddstream = function (event) { self.onRemoteStreamAdded(call, event); }; pc.onremovestream = function (event) { self.onRemoteStreamRemoved(call, event); }; pc.onicecandidate = function (event) { if (event.currentTarget.iceGatheringState === 'complete') { logger.debug('ice gathering complete'); self.onIceComplete(call); } else { self.setupIceCandidateCollectionTimer(call); self.onIceCandidate(call, event); } }; pc.onicecomplete = function () { self.onIceComplete(call); }; pc.oniceconnectionstatechange = function (event) { self.oniceconnectionstatechange(call, event); }; pc.ondatachannel = function (event) { self.onDataChannel(call, event); }; logger.info('create PeerConnection successfully.'); // Will be commented-in after decision of necessary stats // self.setupWebrtcLogCollectionTimer(call); onSuccess(call); } catch (err) { logger.error('Failed to create PeerConnection, exception: ' + err.message); onFailure(); } }; // firefoxgetCameraList self.getCameraList = function () { return; }; // firefoxgetMicrophoneList self.getMicrophoneList = function () { return; }; // firefoxgetSpeakerList self.getSpeakerList = function () { return; }; self.getNativeWebRtcStats = function (call, onSuccess, onFailure) { try { if (call) { logger.debug('getNativeWebRtcStats called mozilla'); call.peer.getStats(undefined, function (stats) { if (stats !== undefined && stats !== null) { _utils.callFunctionIfExist(onSuccess, stats); } }, self.statsCallback); } } catch (err) { logger.error('Failed to get all WebRTC Statistics: ' + err.message); _utils.callFunctionIfExist(onFailure, err); } }; self.statsCallback = function (error) { logger.debug('Mozilla statsCallback:' + error); }; self.getWebRtcStats = function (call, onSuccess, onFailure) { try { if (call) { logger.debug('getWebRtcStats called mozilla'); self.collectWebRtcStats(call.peer, function (stats) { var accumulatedStats = self.getAccumulatedWebRtcStats(call.stats, stats); _utils.callFunctionIfExist(onSuccess, accumulatedStats); }, onFailure); } } catch (err) { logger.error('Failed to get WebRTC Statistics: ' + err.message); _utils.callFunctionIfExist(onFailure, err); } return self.getStats(); }; self.getAccumulatedWebRtcStats = function (statsList, currentStats) { var i, accumulatedStats = { audio: { packetsSent: 0, bytesSent: 0, bytesReceived: 0, peerAddress: null, codec: null, packetsLost: 0, jitter: null, rtt: null }, video: { packetsSent: 0, bytesSent: 0, bytesReceived: 0, peerAddress: null, codec: null, packetsLost: 0, rtt: null } }; if (statsList !== undefined) { for (i = 0; i < statsList.length; i++) { self.accumulateStats(accumulatedStats.audio, statsList[i].audio); self.accumulateStats(accumulatedStats.video, statsList[i].video); } } self.accumulateStats(accumulatedStats.audio, currentStats.audio); accumulatedStats.audio.peerAddress = currentStats.audio.peerAddress; accumulatedStats.audio.codec = currentStats.audio.codec; accumulatedStats.audio.jitter = currentStats.audio.jitter; accumulatedStats.audio.rtt = currentStats.audio.rtt; self.accumulateStats(accumulatedStats.video, currentStats.video); accumulatedStats.video.peerAddress = currentStats.video.peerAddress; accumulatedStats.video.codec = currentStats.video.codec; accumulatedStats.video.rtt = currentStats.video.rtt; return accumulatedStats; }; self.accumulateStats = function (accumulatedStatsObj, statsObj) { accumulatedStatsObj.packetsSent += (0, _utils2.getInteger)(statsObj.packetsSent); accumulatedStatsObj.bytesSent += (0, _utils2.getInteger)(statsObj.bytesSent); accumulatedStatsObj.bytesReceived += (0, _utils2.getInteger)(statsObj.bytesReceived); accumulatedStatsObj.packetsLost += (0, _utils2.getInteger)(statsObj.packetsLost) === -1 ? 0 : (0, _utils2.getInteger)(statsObj.packetsLost); }; self.collectWebRtcStats = function (peer, onSuccess, onFailure) { try { if (peer) { logger.debug('collectWebRtcStats called mozilla'); peer.getStats(undefined, function (stats) { if (stats !== undefined && stats !== null) { self.setWebRtcStats(stats); _utils.callFunctionIfExist(onSuccess, self.getStats()); } }, self.statsCallback); } } catch (err) { logger.error('Failed to collectWebRtcStats: ' + err.message); _utils.callFunctionIfExist(onFailure, err); } return self.getStats(); }; self.setWebRtcStats = function (results) { var stats = { audio: { packetsSent: null, bytesSent: null, bytesReceived: null, peerAddress: null, codec: null, packetsLost: null, jitter: null, rtt: null }, video: { packetsSent: null, bytesSent: null, bytesReceived: null, peerAddress: null, codec: null, packetsLost: null, rtt: null } }; results.forEach(function (result) { if (result.type === 'remotecandidate') { // The results from RTCPeerConnection.getStats need to be treated in a // map-like fashion. Other usage has been deprecated. // See: http://w3c.github.io/webrtc-pc/#rtcstatsreport-object var currentStat = results.get(result.id); if (currentStat.componentId !== undefined) { if (currentStat.componentId.indexOf('aLevel=0') > -1) { stats.audio.peerAddress = currentStat.ipAddress + ':' + currentStat.portNumber; } else if (currentStat.componentId.indexOf('aLevel=1') > -1) { stats.video.peerAddress = currentStat.ipAddress + ':' + currentStat.portNumber; } } } }); if (stats.video.peerAddress === undefined || stats.video.peerAddress === null) { stats.video.peerAddress = stats.audio.peerAddress; } //audio if (results.get('inbound_rtp_audio_0') !== undefined) { stats.audio.bytesReceived = results.get('inbound_rtp_audio_0').bytesReceived; stats.audio.packetsLost = results.get('inbound_rtp_audio_0').packetsLost; stats.audio.jitter = results.get('inbound_rtp_audio_0').jitter; } if (results.get('outbound_rtp_audio_0') !== undefined) { stats.audio.packetsSent = results.get('outbound_rtp_audio_0').packetsSent; stats.audio.bytesSent = results.get('outbound_rtp_audio_0').bytesSent; } if (results.get('outbound_rtcp_audio_0') !== undefined) { stats.audio.rtt = results.get('outbound_rtcp_audio_0').mozRtt; } if (results.get('inbound_rtp_video_1') !== undefined) { stats.video.bytesReceived = results.get('inbound_rtp_video_1').bytesReceived; stats.video.packetsLost = results.get('inbound_rtp_video_1').packetsLost; } if (results.get('outbound_rtp_video_1') !== undefined) { stats.video.packetsSent = results.get('outbound_rtp_video_1').packetsSent; stats.video.bytesSent = results.get('outbound_rtp_video_1').bytesSent; } if (results.get('outbound_rtcp_video_1') !== undefined) { stats.video.rtt = results.get('outbound_rtcp_video_1').mozRtt; } self.setStats(stats); }; logger.debug('WebRtcFirefoxAdaptor initialized'); } /***/ }), /***/ "../fcs/src/js/webrtc/adaptor/webRtcFirefoxEsrAdaptor.js": /*!***************************************************************!*\ !*** ../fcs/src/js/webrtc/adaptor/webRtcFirefoxEsrAdaptor.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebRtcFirefoxEsrAdaptorImpl = WebRtcFirefoxEsrAdaptorImpl; var _utils2 = __webpack_require__(/*! ../../utils */ "../fcs/src/js/utils/index.js"); var _call = __webpack_require__(/*! ../../call/call */ "../fcs/src/js/call/call.js"); function WebRtcFirefoxEsrAdaptorImpl(_ref) { var _super = _ref.base, _model = _ref.model, _logManager = _ref.LogManager, _utils = _ref.Utils; var self = this, logger = _logManager.getLogger('WebRtcFirefoxEsrAdaptorImpl'); logger.debug('WebRtcFirefoxEsrAdaptor initializing'); (0, _utils2.compose)(_super, self); (0, _utils2.compose)(_model, self); // firefoxEsrGetUserMedia self.getUserMedia = function (params) { self.getRtcLibrary().checkMediaSourceAvailability(function mediaSourceCallback(mediaSourceInfo) { var mediaInfo, constraints = { audio: false, video: false }, localMedia; self.setMediaSources(mediaSourceInfo); if (mediaSourceInfo) { if (!mediaSourceInfo.audioSourceAvailable) { logger.debug('Failed to get access to local media.'); _utils.callFunctionIfExist(params.onFailure, _call.mediaErrors.NOT_FOUND); return; } } if (self.getVideoSourceAvailable()) { constraints.video = params.options.videoConstraints; } if (self.getAudioSourceAvailable()) { constraints.audio = params.options.audioConstraints; } logger.debug('getUserMedia - constraints: ', constraints); self.getRtcLibrary().getUserMedia(constraints, function getUserMediaSuccessCallback(stream) { localMedia = { audioContext: { close: function close() {} }, mediaStreamDestination: { disconnect: function disconnect() {} }, stream: stream, originalStream: stream }; self.setLocalMedia(localMedia); self.getLocalStreamMap().add(localMedia.stream.id, localMedia); self.setInitialized(true); mediaInfo = { audio: constraints.audio, video: constraints.video, id: localMedia.stream.id, originalStream: stream, streamURL: self.getRtcLibrary().getURLFromStream(stream) }; logger.debug('user has granted access to local media: ', localMedia); _utils.callFunctionIfExist(params.onSuccess, mediaInfo); }, function getUserMediaFailureCallback(error) { logger.debug('Failed to get access to local media. Error: ', error); _utils.callFunctionIfExist(params.onFailure, _call.mediaErrors.NOT_ALLOWED); }); }); }; // firefoxEsrSendDTMF self.sendDTMF = function () { logger.debug('DMTF IS ONLY SUPPORTED FOR FIREFOX 40 AND NEWER VERSIONS'); }; logger.debug('WebRtcFirefoxEsrAdaptor initialized'); } /***/ }), /***/ "../fcs/src/js/webrtc/adaptor/webRtcPluginAdaptor.js": /*!***********************************************************!*\ !*** ../fcs/src/js/webrtc/adaptor/webRtcPluginAdaptor.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.WebRtcPluginAdaptorImpl = WebRtcPluginAdaptorImpl; var _utils2 = __webpack_require__(/*! ../../utils */ "../fcs/src/js/utils/index.js"); var _constants = __webpack_require__(/*! ../../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); var _call = __webpack_require__(/*! ../../call/call */ "../fcs/src/js/call/call.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function WebRtcPluginAdaptorImpl(_ref) { var _super = _ref.base, _decorator = _ref.decorator, _model = _ref.model, _logManager = _ref.LogManager, _utils = _ref.Utils, _sdpParser = _ref.SdpParser, _cache = _ref.Cache, _fcs = _ref.Core, _config = _ref.Config, _sdpPipeline = _ref.SdpPipeline; var self = this, logger = _logManager.getLogger('WebRtcPluginAdaptorImpl'); logger.debug('WebRtcPluginAdaptor initializing'); (0, _utils2.compose)(_super, self); (0, _utils2.compose)(_model, self); self.setPluginEnabled(true); // Enabler implementation lies on webRtcPluginAdaptor.js self.getLocalAudioTrack = function (peer) { logger.debug('getLocalAudioTrack'); if (peer.localStreams && peer.localStreams.length > 0 && peer.localStreams.item(0).audioTracks) { if (peer.localStreams.item(0).audioTracks.length > 0) { return peer.localStreams.item(0).audioTracks.item(0); } } return null; }; // Enabler implementation lies on webRtcPluginAdaptor.js self.getLocalVideoTrack = function (peer) { logger.debug('getLocalVideoTrack'); if (peer.localStreams && peer.localStreams.length > 0 && peer.localStreams.item(0).videoTracks) { if (peer.localStreams.item(0).videoTracks.length > 0) { return peer.localStreams.item(0).videoTracks.item(0); } } return null; }; // Enabler implementation lies on webRtcPluginAdaptor.js self.getRemoteVideoTrack = function (peer) { logger.debug('getRemoteVideoTrack'); if (peer.remoteStreams && peer.remoteStreams.item(0)) { return peer.remoteStreams.item(0).videoTracks; } return []; }; //This function is called internally when we make a new call or hold/unhold scenario // Enabler implementation lies on webRtcPluginAdaptor.js self.addLocalStream = function (internalCall) { var streamUrl, fireEvent = false, isSendingLocalVideo = self.canOriginatorSendLocalVideo(internalCall); if (internalCall.localMedia && internalCall.localMedia.stream) { if (isSendingLocalVideo) { streamUrl = self.getRtcLibrary().getURLFromStream(internalCall.localMedia.stream); if (streamUrl) { if (self.getDefaultVideoContainer()) { fireEvent = self.useDefaultRenderer(streamUrl, true); } else if (self.getLocalVideoContainer()) { fireEvent = self.createStreamRenderer(streamUrl, self.getLocalVideoContainer(), { muted: true }); } else { internalCall.call.localStreamURL = streamUrl; fireEvent = true; } } } else { if (self.getDefaultVideoContainer()) { if (self.getDefaultVideoContainer().lastElementChild) { self.disposeStreamRenderer(self.getDefaultVideoContainer().lastElementChild); } } else if (self.getLocalVideoContainer()) { self.disposeStreamRenderer(self.getLocalVideoContainer()); } } logger.debug('onLocalStreamAdded: ' + streamUrl); if (fireEvent) { self.fireOnLocalStreamAddedEvent(internalCall, streamUrl); } } }; // Enabler implementation lies on webRtcPluginAdaptor.js self.muteAudioTrack = function (call, mute, userAction) { var localAudioTrack; if (!self.isInitialized()) { logger.warn('muteAudioTrack: Plugin is not installed'); return; } if (!call.peer) { return; } localAudioTrack = self.getLocalAudioTrack(call.peer); if (localAudioTrack) { logger.info('mute Audio Track [' + localAudioTrack.id + '], call [' + call.id + '] mute=' + mute); localAudioTrack.enabled = !mute; call.audioMuted = mute; if (userAction) { call.fcsUserAudioMuteState = mute; } } }; // Enabler implementation lies on webRtcPluginAdaptor.js self.muteVideoTrack = function (call, mute, userAction) { var localVideoTrack; if (!self.isInitialized()) { logger.warn('muteVideoTrack: Plugin is not installed'); return; } if (!call.peer) { return; } localVideoTrack = self.getLocalVideoTrack(call.peer); if (localVideoTrack) { logger.info('mute Video Track [' + localVideoTrack.id + '], call [' + call.id + '] mute=' + mute); localVideoTrack.enabled = !mute; call.videoMuted = mute; if (userAction) { call.fcsUserVideoMuteState = mute; } } }; // Enabler implementation lies on webRtcPluginAdaptor.js self.restoreMuteStateOfCall = function (call) { var previousMuteStateOfAudio = false, previousMuteStateOfVideo = false; if (!call.peer) { return; } if (call.fcsUserAudioMuteState) { previousMuteStateOfAudio = call.fcsUserAudioMuteState; } if (call.fcsUserVideoMuteState) { previousMuteStateOfVideo = call.fcsUserVideoMuteState; } logger.debug('previous audio mute state of call: ' + previousMuteStateOfAudio); logger.debug('previous video mute state of call: ' + previousMuteStateOfVideo); self.muteAudioTrack(call, previousMuteStateOfAudio); self.muteVideoTrack(call, previousMuteStateOfVideo); }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * Mutes audio and video tracks (to be used during Hold) * * @ignore * @name rtc.mute * @function * @param {Object} call internalCall * @param {boolean} mute true to mute, false to unmute */ self.muteOnHold = function (call, mute) { self.muteAudioTrack(call, mute); self.muteVideoTrack(call, mute); }; // Enabler implementation lies on webRtcPluginAdaptor.js // initEnablerMedia self.initMedia = function (onSuccess, onFailure, options) { var mainContainer = document.body, rtcPlugin = {}, verifyPlugin = true, onloadParam, size = '1px', pluginid = 'fcsPlugin', applicationType = 'application/x-gcfwenabler', configuredPluginVersion = self.getPluginVersion(), currentPluginVersion, currentPluginVersionString; logger.debug('Configured plugin version: ' + configuredPluginVersion.major + '.' + configuredPluginVersion.minor + '.' + configuredPluginVersion.current_revision); if (options) { if (options.pluginLogLevel) { self.setLogLevel(options.pluginLogLevel); } if (options.language) { self.setLanguage(options.language); } } //Callback for when the plugin is loaded self.onFCSPLoaded = function () { self.setRtcLibrary(_decorator(rtcPlugin)); if (self.isH264Enabled()) { self.getRtcLibrary().enableH264(); } self.getRtcLibrary().checkMediaSourceAvailability(function mediaSourceCallback(mediaSourceInfo) { self.setMediaSources(mediaSourceInfo); }); self.getRtcLibrary().setH264CodecStateChangeHandler(function onH264CodecStateChangeHandler(event) { self.setH264Enabled(event.state); }); currentPluginVersion = self.getRtcLibrary().getCurrentPluginVersionObject(); currentPluginVersionString = self.getRtcLibrary().getVersion(); // prevent multiple init calls if (self.isInitialized()) { // If the plugin is already initialized, it should call successCallback with persion _utils.callFunctionIfExist(onSuccess, { 'pluginVersion': rtcPlugin.version }); } if (!verifyPlugin) { return; } verifyPlugin = false; logger.debug('Plugin callback'); _fcs.setPluginVersion(currentPluginVersionString); logger.debug('Installed plugin version: ' + currentPluginVersionString); if (currentPluginVersionString.length < 1 || currentPluginVersion.major !== configuredPluginVersion.major || currentPluginVersion.minor !== configuredPluginVersion.minor || currentPluginVersion.revision < configuredPluginVersion.min_revision || currentPluginVersion.revision === configuredPluginVersion.min_revision && currentPluginVersion.build < configuredPluginVersion.min_build) { logger.debug('Plugin version not supported'); _utils.callFunctionIfExist(onFailure, _call.mediaErrors.WRONG_VERSION); _utils.callFunctionIfExist(_fcs.onPluginRequired, _call.mediaErrors.WRONG_VERSION); } else { self.setInitialized(true); if (currentPluginVersion.revision < configuredPluginVersion.current_revision || currentPluginVersion.revision === configuredPluginVersion.current_revision && currentPluginVersion.build < configuredPluginVersion.current_build) { logger.debug('New plugin version warning'); _utils.callFunctionIfExist(onFailure, _call.mediaErrors.NEW_VERSION_WARNING); _utils.callFunctionIfExist(_fcs.onPluginRequired, _call.mediaErrors.NEW_VERSION_WARNING); } else { _utils.callFunctionIfExist(onSuccess, { 'pluginVersion': rtcPlugin.version }); } self.getRtcLibrary().setLang(self.getLanguage()); } self.getRtcLibrary().checkMediaSourceAvailability(); }; // only check if the function exists, not its type, because in IE it is "object" (host object) if (typeof mainContainer.appendChild === 'undefined') { logger.debug('Could not inject plugin in container'); _utils.callFunctionIfExist(onFailure, _call.mediaErrors.OPTIONS); _utils.callFunctionIfExist(_fcs.onPluginRequired, _call.mediaErrors.OPTIONS); return; } rtcPlugin = document.createElement('object'); onloadParam = document.createElement('param'); onloadParam.setAttribute('name', 'onload'); onloadParam.setAttribute('value', 'onFCSPLoaded'); rtcPlugin.appendChild(onloadParam); rtcPlugin.id = pluginid; rtcPlugin.width = rtcPlugin.height = size; // Order matters for the following: // For IE you need to append first so the dom is available when IE loads the plugin, which happens when the type is set. // For FF you need to set the type and then append or the plugin won't load. // Chrome seems happy either way. try { if (navigator.appName === 'Microsoft Internet Explorer') { mainContainer.appendChild(rtcPlugin); rtcPlugin.type = applicationType; } else { rtcPlugin.type = applicationType; mainContainer.appendChild(rtcPlugin); } } catch (e) { verifyPlugin = false; _utils.callFunctionIfExist(onFailure, _call.mediaErrors.NOT_FOUND); _utils.callFunctionIfExist(_fcs.onPluginRequired, _call.mediaErrors.NOT_FOUND); } if (verifyPlugin) { if (typeof document.getElementById(pluginid).createPeerConnection !== 'undefined') { self.onFCSPLoaded(); } else { //if the plugin is not initialized within 7 sec fail setTimeout(function () { // for createPeerConnection, only check if it exists. It is "function" in FireFox and "object" in Chrome and IE if (!self.isInitialized()) { if (typeof document.getElementById(pluginid).createPeerConnection === 'undefined') { _utils.callFunctionIfExist(onFailure, _call.mediaErrors.NOT_FOUND); _utils.callFunctionIfExist(_fcs.onPluginRequired, _call.mediaErrors.NOT_FOUND); } else { self.onFCSPLoaded(); } } }, 7000); } } }; // Enabler implementation lies on webRtcPluginAdaptor.js self.getUserMedia = function (params) { self.getRtcLibrary().checkMediaSourceAvailability(function getUserMediaCallback(mediaSourceInfo) { var mediaInfo, constraints = { audio: false, video: false }, localMedia; self.setMediaSources(mediaSourceInfo); if (mediaSourceInfo) { if (!mediaSourceInfo.audioSourceAvailable) { logger.debug('Failed to get access to local media.'); _utils.callFunctionIfExist(params.onFailure, _call.mediaErrors.NOT_FOUND); return; } } if (self.getVideoSourceAvailable()) { constraints.video = params.options.videoConstraints; } if (self.getAudioSourceAvailable()) { constraints.audio = params.options.audioConstraints; } logger.debug('Plugin version:' + self.getRtcLibrary().version); logger.debug('getUserMedia - constraints: ', constraints); self.getRtcLibrary().getUserMedia(constraints, function getUserMediaSuccessCallback(stream) { localMedia = { audioContext: { close: function close() {} }, mediaStreamDestination: { disconnect: function disconnect() {} }, stream: stream, originalStream: stream }; self.setLocalMedia(localMedia); self.getLocalStreamMap().add(localMedia.stream.label, localMedia); self.setInitialized(true); mediaInfo = { audio: constraints.audio, video: constraints.video, id: localMedia.stream.label, originalStream: stream, streamURL: self.getRtcLibrary().getURLFromStream(stream) }; logger.debug('user has granted access to local media: ', localMedia); _utils.callFunctionIfExist(params.onSuccess, mediaInfo); }, function getUserMediaFailureCallback(error) { logger.debug('Failed to get access to local media. Error: ', error); _utils.callFunctionIfExist(params.onFailure, _call.mediaErrors.NOT_ALLOWED); }); }); }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * createEnablerOffer to be used when the enabler plugin is enabled. */ self.createOffer = function (call, successCallback, failureCallback, sendInitialVideo, offerToReceiveVideo) { logger.debug('createOffer: sendInitialVideo= ' + sendInitialVideo + ' state= ' + call.peer.signalingState); var peer = call.peer; if (call.localMedia && call.localMedia.stream) { call.peer.addStream(call.localMedia.stream); } peer.createOffer(function createOfferSuccessCallback(oSdp) { sendInitialVideo = sendInitialVideo && self.getVideoSourceAvailable(); if (sendInitialVideo) { oSdp.sdp = _sdpParser.updateVideoSdpDirection(oSdp.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { oSdp.sdp = _sdpParser.updateVideoSdpDirection(oSdp.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } oSdp.sdp = _sdpParser.deleteCryptoZeroFromSdp(oSdp.sdp); oSdp.sdp = _sdpParser.removeG722Codec(oSdp.sdp); oSdp.sdp = _sdpParser.deleteCryptoFromSdp(oSdp.sdp, self.isDtlsEnabled()); oSdp.sdp = _sdpParser.setTcpSetupAttributeToActpass(oSdp.sdp, self.isDtlsEnabled()); oSdp.sdp = self.updateCodecs(call, oSdp.sdp); oSdp.sdp = _sdpParser.updateOpusConfig(oSdp.sdp, _config.opusConfig); self.muteOnHold(call, false); oSdp.sdp = _sdpPipeline(call.id, oSdp.sdp, _constants2.default.WEBRTC.SDP.OPERATION.START_CALL, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); logger.trace('createOffer: Setting local description with (offer) SDP: ' + oSdp.sdp); peer.setLocalDescription(self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, oSdp.sdp), function createOfferSetLocalDescriptionSuccessCallback() { // Due to stun requests, successCallback will be called by onIceCandidate() }, function createOfferSetLocalDescriptionFailureCallback(error) { logger.error('createOffer: setLocalDescription failed : ' + error); _utils.callFunctionIfExist(failureCallback, 'createOffer: setLocalDescription failed'); }); }, function createOfferFailureCallback(error) { logger.error('createOffer: createOffer failed!! ' + error); _utils.callFunctionIfExist(failureCallback); }, { optional: { OfferToReceiveVideo: offerToReceiveVideo } }); }; /* * createEnablerAnswer to be used when the enabler plugin is enabled * Enabler implementation lies on webRtcPluginAdaptor.js */ self.createAnswer = function (call, successCallback, failureCallback, isVideoEnabled) { logger.debug('createAnswer: isVideoEnabled= ' + isVideoEnabled + ' state= ' + call.peer.signalingState); var peer = call.peer, newSdp; call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, null, self.isH264Enabled()); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); call.sdp = _sdpParser.deleteFingerprintOrCrypto(call.sdp, self.isDtlsEnabled()); if (!_sdpParser.isSdpVideoSendEnabled(call.sdp)) { // delete ssrc only from video, keep audio ssrc to hear audio call.sdp = _sdpParser.deleteInactiveVideoSsrc(call.sdp); } logger.trace('createAnswer: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function createAnswerSetRemoteDescriptionSuccessCallback() { if (call.localMedia && call.localMedia.stream) { call.peer.addStream(call.localMedia.stream); } call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); // set answer SDP to localDescriptor for the offer peer.createAnswer(peer.remoteDescription, function createAnswerSuccessCallback(oSdp) { newSdp = _sdpParser.getSdpFromObject(oSdp); oSdp = null; isVideoEnabled = isVideoEnabled && self.getVideoSourceAvailable() && _sdpParser.isSdpHasVideo(call.sdp); newSdp = _sdpParser.updateOpusConfig(newSdp, _config.opusConfig); if (isVideoEnabled) { if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { newSdp = _sdpParser.updateVideoSdpDirection(newSdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { if (_sdpParser.getVideoSdpDirection(call.sdp) !== _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { newSdp = _sdpParser.updateVideoSdpDirection(newSdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { newSdp = _sdpParser.updateVideoSdpDirection(newSdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } } else { if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { newSdp = _sdpParser.updateVideoSdpDirection(newSdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } else { newSdp = _sdpParser.updateVideoSdpDirection(newSdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } logger.debug('doAnswer(plugin) - isSdpEnabled audio : ' + _sdpParser.isAudioSdpEnabled(newSdp)); logger.debug('doAnswer(plugin) - isSdpEnabled video : ' + _sdpParser.isVideoSdpEnabled(newSdp)); if (_sdpParser.isSdpHasAudio(newSdp) || _sdpParser.isSdpHasVideo(newSdp)) { // createAnswer generates an sdp without ice params // copy ice params to the local sdp // scenario: incoming video call from pcc in brokeronly config newSdp = _sdpParser.checkAndRestoreICEParams(newSdp, call.sdp); self.muteOnHold(call, false); newSdp = _sdpPipeline(call.id, newSdp, _constants2.default.WEBRTC.SDP.OPERATION.START_CALL, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); logger.trace('createAnswer: Setting local description with (answer) SDP: ' + newSdp); peer.setLocalDescription(self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, newSdp), function createAnswerSetLocalDescriptionSuccessCallback() { // Due to stun requests, successCallback will be called by onIceCandidate() }, function createAnswerSetLocalDescriptionFailureCallback(e) { logger.error('createAnswer: setLocalDescription failed : ' + e); _utils.callFunctionIfExist(failureCallback, 'createAnswer setLocalDescription failed'); }); } else { logger.error('createrAnswer: createAnswer failed!!'); _utils.callFunctionIfExist(failureCallback, 'No codec negotiation'); } }, function createAnswerFailureCallback(e) { logger.error('createAnswer: failed!!' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created '); }); }, function createAnswerSetRemoteDescriptionFailureCallback(e) { logger.error('createAnswer setRemoteDescription failed : ' + e); _utils.callFunctionIfExist(failureCallback, 'createAnswer setRemoteDescription failed'); }); }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * createEnablerUpdate to be used when the video start or stop */ self.createUpdate = function (call, successCallback, failureCallback, isVideoStart) { logger.debug('createEnablerUpdate: isVideoStart= ' + isVideoStart + ' state= ' + call.peer.signalingState); var peer = call.peer, localDesc, localSdp = call.stableLocalSdp; if (self.createNewPeerForCall({ call: call, mustCreatePeer: call.isRemoteEndFirefox })) { peer = call.peer; self.setTcpSetupAttiributesOnProcessAnswer(call, call.sdp); } self.getRtcLibrary().updateStream(peer, call); peer.createOffer(function createUpdateCreateOfferSuccessCallback(obj) { isVideoStart = isVideoStart && self.getVideoSourceAvailable(); if (isVideoStart) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { if (_sdpParser.isVideoSdpDirectionInactive(call.stableRemoteSdp)) { obj.sdp = _sdpParser.updateVideoSdpDirectionToInactive(obj.sdp); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } obj.sdp = self.updateCodecs(call, obj.sdp); obj.sdp = _sdpParser.updateH264Level(obj.sdp); obj.sdp = _sdpParser.updateVersion(localSdp, obj.sdp); obj.sdp = _sdpParser.setTcpSetupAttributeToActpass(obj.sdp, self.isDtlsEnabled()); obj.sdp = _sdpParser.deleteCryptoZeroFromSdp(obj.sdp); obj.sdp = _sdpParser.removeG722Codec(obj.sdp); obj.sdp = _sdpParser.deleteCryptoFromSdp(obj.sdp, self.isDtlsEnabled()); obj.sdp = _sdpParser.updateOpusConfig(obj.sdp, _config.opusConfig); obj.sdp = _sdpPipeline(call.id, obj.sdp, _constants2.default.WEBRTC.SDP.OPERATION.UPDATE, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); localDesc = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, obj.sdp); logger.trace('createUpdate: Setting local description with (offer) SDP: ' + obj.sdp); peer.setLocalDescription(localDesc, function createUpdateCreateOfferSetLocalDescriptionSuccessCallback() { logger.debug('createUpdate setLocalDescription success. iceConnectionState: ' + peer.iceConnectionState + ' iceGatheringState: ' + peer.iceGatheringState); // The above process un-mutes the client. We must ensure it continues to be muted if necessary. if (call.audioMuted) { logger.debug('video started while muted, re-mute the microphone'); self.muteAudioTrack(call, true, false); } if (peer.iceGatheringState === 'complete') { if (call.successCallback) { logger.debug('createUpdate iceGatheringState completed ' + peer.localDescription.sdp); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } } }, function crateUpdateCreateOfferSetLocalDescriptionFailureCallback(e) { logger.debug('createUpdate: createOffer setLocalDescription failed: ' + e); _utils.callFunctionIfExist(failureCallback); }); }, function createUpdateCrateOfferFailureCallback(e) { logger.debug('createUpdate: createOffer failed!!: ' + e); _utils.callFunctionIfExist(failureCallback); }); }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * createEnablerHoldUpdate to be used when the enabler plugin is enabled */ self.createHoldUpdate = function (call, hold, remote_hold_status, successCallback, failureCallback, useIceServer) { logger.debug('createHoldUpdate: local hold= ' + hold + ' remote hold= ' + remote_hold_status + ' state= ' + call.peer.signalingState); var peer = call.peer, localDescObj, localSdp; var operation = hold ? _constants2.default.WEBRTC.SDP.OPERATION.HOLD : _constants2.default.WEBRTC.SDP.OPERATION.UNHOLD; localSdp = call.stableLocalSdp; if (self.createNewPeerForCall({ call: call, mustCreatePeer: call.isRemoteEndFirefox, useIceServer: useIceServer })) { peer = call.peer; } peer.createOffer(function createHoldUpdateCreateOfferSuccessCallback(obj) { if (hold) { if (!remote_hold_status) { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateAudioSdpDirectionToInactive(obj.sdp); obj.sdp = _sdpParser.updateVideoSdpDirectionToInactive(obj.sdp); } } else if (remote_hold_status) { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateAudioSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } obj.sdp = self.updateCodecs(call, obj.sdp); obj.sdp = _sdpParser.updateH264Level(obj.sdp); obj.sdp = _sdpParser.updateVersion(localSdp, obj.sdp); obj.sdp = _sdpParser.deleteCryptoZeroFromSdp(obj.sdp); obj.sdp = _sdpParser.setTcpSetupAttributeToActpass(obj.sdp, self.isDtlsEnabled()); obj.sdp = _sdpParser.updateOpusConfig(obj.sdp, _config.opusConfig); obj.sdp = _sdpPipeline(call.id, obj.sdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); localDescObj = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, obj.sdp); logger.trace('createHoldUpdate: Setting local description with (offer) SDP: ' + obj.sdp); peer.setLocalDescription(localDescObj, function createHoldUpdateSetLocalDescriptionSuccessCallback() { logger.debug('createHoldUpdate setLocalDescription success. iceConnectionState: ' + peer.iceConnectionState + ' iceGatheringState: ' + peer.iceGatheringState); if (peer.iceGatheringState === 'complete') { if (call.successCallback) { logger.debug('createHoldUpdate iceGatheringState completed ' + peer.localDescription.sdp); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } } }, function createHoldUpdateSetLocalDescriptionFailureCallback(error) { logger.error('createHoldUpdate: setLocalDescription failed: ' + error.message); _utils.callFunctionIfExist(failureCallback); }); }, function createHoldUpdateCreateOfferFailureCallback(error) { logger.error('createHoldUpdate: createOffer failed: ' + error.message); _utils.callFunctionIfExist(failureCallback); }); }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * processEnabler30Update to be used when the enabler plugin is enabled. (based on processEnabler30Update) */ self.processUpdate = function (call, successCallback, failureCallback, local_hold_status) { logger.debug('processUpdate: state= ' + call.peer.signalingState); var peer = call.peer, localSdp, remoteAudioState, remoteVideoState, peerLocalSdp, remoteVideoDirection, callSdpWithNoSsrc, remoteDescriptionMainProcess, data; peerLocalSdp = call.stableLocalSdp; call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); // Meetme workaround. This workaround is added into native function call.sdp = _sdpParser.addSdpMissingCryptoLine(call.sdp); call.sdp = _sdpParser.checkAndRestoreICEParams(call.sdp, peerLocalSdp); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); if (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE && call.currentState === 'COMPLETED') { switch (call.remoteVideoState) { case _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE: case _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY: call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); break; case _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE: call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); break; } } call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.VIDEO); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, null, self.isH264Enabled()); //this part is a work-around for webrtc bug //set remote description with inactive media lines first. //then set remote description with original media lines. //keep original values of remote audio and video states remoteAudioState = _sdpParser.getAudioSdpDirection(call.sdp); remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); if (_sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || _sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) { call.sdp = _sdpParser.deleteInactiveVideoSsrc(call.sdp); } call.sdp = _sdpParser.setTcpSetupAttributeToActpass(call.sdp, self.isDtlsEnabled()); // delete all ssrc lines from the sdp before setting first remote description // set second remote description with all ssrc lines included // TODO: Not sure about this line. It used to store the result but the result was unused. Kept the call // around for safety in case it has side effects. self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, call.prevRemoteSdp); data = { call: call, mustCreatePeer: call.isRemoteEndFirefox, oldSdp: call.prevRemoteSdp, newSdp: call.sdp }; if (self.createNewPeerForCall(data)) { peer = call.peer; self.setTcpSetupAttiributesOnProcessAnswer(call, call.sdp); } //This is highly required for meetme on DTLS call.sdp = _sdpParser.setTcpSetupAttributeToActpass(call.sdp, self.isDtlsEnabled()); remoteDescriptionMainProcess = function remoteDescriptionMainProcess() { logger.trace('processUpdate: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.UPDATE, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function processUpdateSetRemoteDescriptionSuccessCallback() { logger.debug('processUpdate: setRemoteDescription success'); call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); peer.createAnswer(peer.remoteDescription, function processUpdateCreateAnswerSuccessCallback(obj) { logger.debug('processUpdate: isSdpEnabled audio= ' + _sdpParser.isAudioSdpEnabled(obj.sdp)); logger.debug('processUpdate: isSdpEnabled video= ' + _sdpParser.isVideoSdpEnabled(obj.sdp)); if (_sdpParser.isAudioSdpEnabled(obj.sdp) || _sdpParser.isVideoSdpEnabled(obj.sdp)) { if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { if (self.canOriginatorSendLocalVideo(call)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } else { if (self.canOriginatorSendLocalVideo(call) && !_sdpParser.isVideoSdpDirectionInactive(call.sdp)) { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { obj.sdp = _sdpParser.updateVideoSdpDirection(obj.sdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } //TODO: Since there is no setter method for obj.sdp from the plugin side, // we create a temporary local variable and pass obj.sdp's value into it. // Rewrite the below part of code when the setter method is applied to the plugin side localSdp = _sdpParser.getSdpFromObject(obj); obj = null; localSdp = _sdpParser.updateVersion(peerLocalSdp, localSdp); localSdp = _sdpParser.checkIceParamsLengths(localSdp, call.sdp); localSdp = _sdpParser.setTcpSetupAttributeTo(localSdp, call.localTcpSetupAttribute, self.isDtlsEnabled()); localSdp = _sdpParser.updateOpusConfig(localSdp, _config.opusConfig); localSdp = _sdpPipeline(call.id, localSdp, _constants2.default.WEBRTC.SDP.OPERATION.UPDATE, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); logger.trace('processUpdate: Setting local description with (answer) SDP: ' + localSdp); peer.setLocalDescription(self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, localSdp), function processUpdateSetLocalDescriptionSuccessCallback() { logger.debug('processUpdate setLocalDescription success. iceConnectionState: ' + peer.iceConnectionState + ' iceGatheringState: ' + peer.iceGatheringState); if (peer.iceGatheringState === 'complete') { if (call.successCallback) { logger.debug('processUpdate iceGatheringState completed ' + peer.localDescription.sdp); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } } }, function processUpdateSetLocalDescriptionFailureCallback(e) { logger.debug('processUpdate: setLocalDescription failed: ' + e); _utils.callFunctionIfExist(failureCallback, 'processUpdate: setlocalDescription failed!!'); }); } else { logger.debug('processUpdate: createAnswer failed!!'); _utils.callFunctionIfExist(failureCallback, 'No codec negotiation'); } }, function processUpdateCreateAnswerFailureCallback(e) { logger.debug('processUpdate: createAnswer failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processUpdateSetRemoteDescriptionSuccessCallback(e) { logger.debug('processUpdate: setRemoteDescription failed: ' + e); _utils.callFunctionIfExist(failureCallback, 'processUpdate: setRemoteDescription failed!!'); }); }; if (_sdpParser.isSdpHasVideo(call.prevRemoteSdp) || _sdpParser.isIceLite(call.sdp) || local_hold_status) { //set media lines with sendonly state for work-around call.sdp = _sdpParser.updateAudioSdpDirectionToInactive(call.sdp); call.sdp = _sdpParser.updateVideoSdpDirectionToInactive(call.sdp); callSdpWithNoSsrc = _sdpParser.deleteSsrcFromSdp(call.sdp); logger.trace('processUpdate: Setting remote description with (offer) SDP: ' + callSdpWithNoSsrc); self.setRemoteDescription(null, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, callSdpWithNoSsrc, function processUpdateWorkaroundSetRemoteDescriptionSuccessCallback() { logger.debug('processUpdate: workaround setRemoteDescription success'); //restore original values call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, remoteAudioState); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, remoteVideoState); remoteDescriptionMainProcess(); }, function processUpdateWorkaroundSetRemoteDescriptionFailureCallback(e) { logger.debug('processUpdate: workaround setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(failureCallback, 'processUpdate: workaround setRemoteDescription failed!!'); }); } else { remoteDescriptionMainProcess(); } }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * processEnabler30Answer to be used when the enabler plugin is enabled */ self.processAnswer = function (call, onSuccess, onFail) { logger.debug('processAnswer: state= ' + call.peer.signalingState); var onSuccessAfterWorkarounds, setRemoteDescription, remoteVideoDirection, localVideoDirection, peer = call.peer, origSdp; onSuccessAfterWorkarounds = function onSuccessAfterWorkarounds() { call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); _utils.callFunctionIfExist(onSuccess); }; setRemoteDescription = function setRemoteDescription(operation, call, onSuccess, onFailure) { logger.trace('processAnswer: Setting remote description with (answer) SDP: ' + call.sdp); self.setRemoteDescription(operation, call, call.peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function () { logger.debug('processAnswer: setRemoteDescription success'); onSuccess(); }, function (e) { logger.error('processAnswer: setRemoteDescription failed: ' + e); onFailure(); }); }; call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, _sdpParser.getSdpFromObject(call.peer.localDescription), self.isH264Enabled()); call.sdp = _sdpParser.performVideoPortZeroWorkaround(call.sdp); if (peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.HAVE_REMOTE_PRANSWER) { if (_sdpParser.isIceLite(call.prevRemoteSdp) !== _sdpParser.isIceLite(call.sdp)) { logger.debug('ice - ice-lite change.'); onFail(_constants2.default.WEBRTC.ERROR.ICE_ICELITE); return; } origSdp = call.sdp; call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); logger.debug('call processPrAnswer again to trigger on remote stream added with updated sdp.'); self.processPreAnswer(call, function () { call.sdp = origSdp; logger.debug('processPrAnswer sucess callback. Restore original sdp.'); setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); }, function () { call.sdp = origSdp; logger.debug('processPrAnswer failure callback. Restore original sdp.'); setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); }); return; } remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); localVideoDirection = _sdpParser.getVideoSdpDirection(_sdpParser.getSdpFromObject(call.peer.localDescription)); // this is needed for buggy webrtc api. when term answers with video to audio only call // this scenario does not work without converting to sendrecv logger.debug('processAnswer: ice-lite: do remote video escalation'); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.VIDEO); if ((localVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY || localVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) && (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY)) { // Audio <--> Audio : apply workaround step 1 // delete ssrc only from video, keep audio ssrc to hear audio call.sdp = _sdpParser.deleteInactiveVideoSsrc(call.sdp); setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); } else if (localVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY && (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY || remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE)) { // Audio <--> Audio-Video setRemoteDescription(null, call, function () { self.performVideoStartWorkaround(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); }, onFail); } else { // Audio-Video <--> Audio-Video // there is remote video, no need for orig side workaround setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, onSuccessAfterWorkarounds, onFail); } }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * performEnablerVideoStartWorkaround - term side cannot see orig's video */ self.performVideoStartWorkaround = function (operation, call, onSuccess, onFail) { var peer = call.peer, remoteAudioState, remoteVideoState, callSdpWithNoSsrc, peerLocalSdp; //disable the workaround by default, as it is not necessairy in current version of Chrome if (!_config.performVideoStartWorkaround) { onSuccess(); return; } if (!_sdpParser.isSdpHasVideo(call.sdp)) { self.setRemoteDescription(operation, call, null, null, call.sdp, onSuccess, onFail); return; } logger.debug('Workaround to play video'); peerLocalSdp = call.stableLocalSdp ? call.stableLocalSdp : call.peer.localDescription.sdp; call.sdp = _sdpParser.addSdpMissingCryptoLine(call.sdp); remoteAudioState = _sdpParser.getSdpDirectionLogging(call.sdp, _constants2.default.STRING.AUDIO, false); remoteVideoState = _sdpParser.getSdpDirectionLogging(call.sdp, _constants2.default.STRING.VIDEO, false); call.sdp = _sdpParser.updateSdpDirection(call.sdp, _constants2.default.STRING.AUDIO, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); call.sdp = _sdpParser.updateSdpDirection(call.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); call.sdp = _sdpParser.setTcpSetupAttributeToActpass(call.sdp, self.isDtlsEnabled()); callSdpWithNoSsrc = _sdpParser.deleteSsrcFromSdp(call.sdp); logger.trace('performVideoStartWorkaround: Setting remote description with (offer) SDP: ' + callSdpWithNoSsrc); self.setRemoteDescription(null, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, callSdpWithNoSsrc, function () { logger.debug('performVideoStartWorkaround: first setRemoteDescription success'); // restore original values call.sdp = _sdpParser.updateSdpDirection(call.sdp, _constants2.default.STRING.AUDIO, remoteAudioState); call.sdp = _sdpParser.updateSdpDirection(call.sdp, _constants2.default.STRING.VIDEO, remoteVideoState); logger.trace('performVideoStartWorkaround: Setting remote description with (offer) SDP: ' + call.sdp); self.setRemoteDescription(operation, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, call.sdp, function () { logger.debug('performVideoStartWorkaround: second setRemoteDescription success'); peer.createAnswer(peer.remoteDescription, function (obj) { var localSdp = _sdpParser.getSdpFromObject(obj); if (_sdpParser.getSdpDirectionLogging(call.sdp, _constants2.default.STRING.AUDIO, false) === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { localSdp = _sdpParser.updateSdpDirection(localSdp, _constants2.default.STRING.AUDIO, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } if (call.remoteVideoState === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { localSdp = _sdpParser.updateSdpDirection(localSdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } else if (self.canOriginatorSendLocalVideo(call)) { localSdp = _sdpParser.updateSdpDirection(localSdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { localSdp = _sdpParser.updateSdpDirection(localSdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } localSdp = _sdpParser.checkAndRestoreICEParams(localSdp, call.sdp); localSdp = _sdpParser.setTcpSetupAttributeTo(localSdp, call.localTcpSetupAttribute, self.isDtlsEnabled()); localSdp = _sdpParser.updateVersion(peerLocalSdp, localSdp); localSdp = _sdpPipeline(call.id, localSdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); logger.trace('performVideoStartWorkaround: Setting local description with (answer) SDP: ' + localSdp); peer.setLocalDescription(self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, localSdp), function () { logger.debug('performVideoStartWorkaround: setlocalDescription success'); _utils.callFunctionIfExist(onSuccess); }, function (e) { logger.debug('performVideoStartWorkaround: setlocalDescription failed!!' + e); _utils.callFunctionIfExist(onFail, 'performVideoStartWorkaround: setlocalDescription failed!!'); }); }, function (e) { logger.debug('performVideoStartWorkaround: createAnswer failed!! ' + e); _utils.callFunctionIfExist(onFail, 'Session cannot be created'); }); }, function (e) { logger.debug('performVideoStartWorkaround: second setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(onFail, 'performVideoStartWorkaround: second setRemoteDescription failed!!'); }); }, function (e) { logger.debug('performVideoStartWorkaround: first setRemoteDescription failed!!' + e); _utils.callFunctionIfExist(onFail, 'performVideoStartWorkaround: first setRemoteDescription failed!!'); }); }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * processPreAnswer to be used when the enabler plugin is enabled */ self.processPreAnswer = function (call, onSuccess, onFailure) { logger.debug('processPreAnswer: state= ' + call.peer.signalingState); call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, _sdpParser.getSdpFromObject(call.peer.localDescription), self.isH264Enabled()); logger.trace('processPreAnswer: Setting remote description with (pranswer) SDP: ' + call.sdp); self.setRemoteDescription(_constants2.default.WEBRTC.SDP.OPERATION.START_CALL, call, call.peer, _constants2.default.WEBRTC.SDP.TYPE.PRANSWER, call.sdp, function processPreAnswerSetRemoteDescriptionSuccessCallback() { self.setOriginatorReceiveRemoteVideo(call); call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); onSuccess(); logger.debug('processPreAnswer: setRemoteDescription success'); }, function processPreAnswerSetRemoteDescriptionFailureCallback(e) { logger.error('processPreAnswer: setRemoteDescription failed: ' + e); onFailure(e); }); }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * processEnablerRespond */ self.processRespond = function (call, onSuccess, onFailure, isJoin) { var operation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _constants2.default.WEBRTC.SDP.OPERATION.START_CALL; var remoteVideoDirection; logger.debug('processRespond: state= ' + call.peer.signalingState); if (call.peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.STABLE) { //if we are in stable state we should not change remotedescription self.setRemoteDescription(operation, call, null, null, call.sdp, onSuccess, onFailure); return; } call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, _sdpParser.getSdpFromObject(call.stableLocalSdp), self.isH264Enabled()); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); if (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE && call.currentState === 'COMPLETED') { switch (call.remoteVideoState) { case _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE: case _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY: call.sdp = _sdpParser.updateSdpDirection(call.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); break; } } call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.VIDEO); if (isJoin) { call.sdp = _sdpParser.changeDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); self.muteOnHold(call, false); } if (_sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || _sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) { call.sdp = _sdpParser.deleteInactiveVideoSsrc(call.sdp); } logger.trace('processRespond: Setting remote description with (answer) SDP: ' + call.sdp); self.setRemoteDescription(null, call, call.peer, _constants2.default.WEBRTC.SDP.TYPE.ANSWER, call.sdp, function () { logger.debug('processRespond: setRemoteDescription success'); var onSuccessAfterWorkaround = function onSuccessAfterWorkaround() { call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); _utils.callFunctionIfExist(onSuccess); }; // _utils.callFunctionIfExist(onSuccessAfterWorkaround); self.performVideoStartWorkaround(operation, call, onSuccessAfterWorkaround, onFailure); }, function (e) { logger.debug('processRespond: setRemoteDescription failed: ' + e); _utils.callFunctionIfExist(onFailure); }); }; /* * createPluginReOffer */ self.createReOffer = function (call, successCallback, failureCallback, usePreviousMediaDirection) { var peer = call.peer, localDescObj, localAudioDirection, localVideoDirection, prevLocalSdp = call.stableLocalSdp, deleteVideoStream = false, data; logger.debug('createReOffer:' + call.id); if (!usePreviousMediaDirection) { deleteVideoStream = !call.initialVideoState && _sdpParser.isSdpHasVideo(call.stableLocalSdp); } data = { call: call, mustCreatePeer: true, deleteVideoStream: deleteVideoStream }; if (self.createNewPeerForCall(data)) { peer = call.peer; } peer.createOffer(function createReOfferCreateOfferSuccessCallback(oSdp) { if (usePreviousMediaDirection) { localAudioDirection = _sdpParser.getAudioSdpDirection(prevLocalSdp); oSdp.sdp = _sdpParser.updateAudioSdpDirection(oSdp.sdp, localAudioDirection); localVideoDirection = _sdpParser.getVideoSdpDirection(prevLocalSdp); oSdp.sdp = _sdpParser.updateVideoSdpDirection(oSdp.sdp, localVideoDirection); } oSdp.sdp = _sdpParser.deleteCryptoZeroFromSdp(oSdp.sdp); oSdp.sdp = _sdpParser.removeG722Codec(oSdp.sdp); oSdp.sdp = _sdpParser.deleteCryptoFromSdp(oSdp.sdp, self.isDtlsEnabled()); oSdp.sdp = _sdpParser.setTcpSetupAttributeToActpass(oSdp.sdp, self.isDtlsEnabled()); oSdp.sdp = _sdpParser.updateVersion(prevLocalSdp, oSdp.sdp); oSdp.sdp = self.updateCodecs(call, oSdp.sdp); oSdp.sdp = _sdpParser.updateOpusConfig(oSdp.sdp, _config.opusConfig); oSdp.sdp = _sdpPipeline(call.id, oSdp.sdp, _constants2.default.WEBRTC.SDP.OPERATION.REOFFER, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.OFFER); localDescObj = self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.OFFER, oSdp.sdp); logger.trace('createReOffer: Setting local description with (offer) SDP: ' + oSdp.sdp); peer.setLocalDescription(localDescObj, function createReOfferSetLocalDescriptionSuccessCallback() { logger.debug('createReOffer: setLocalDescription success' + call.id); }, function createReOfferSetLocalDescriptionFailureCallback(e) { logger.debug('createReOffer: setLocalDescription failed!!' + e + call.id); _utils.callFunctionIfExist(failureCallback); }); }, function createReOfferCreateOfferFailureCallback(e) { logger.error('createReOffer: createOffer failed!! ' + e); _utils.callFunctionIfExist(failureCallback); }); }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * processEnablerHold to be used when the enabler plugin 30 is enabled. */ self.processHold = function (call, hold, local_hold_status, successCallback, failureCallback) { logger.debug('processHold: local hold= ' + local_hold_status + ' remote hold= ' + hold + ' state= ' + call.peer.signalingState); var peer = call.peer, audioDirection, videoDirection, inactiveRemoteSdp, peerLocalSdp, localSdp, remoteSdp, data; peerLocalSdp = call.stableLocalSdp; var operation = hold ? _constants2.default.WEBRTC.SDP.OPERATION.HOLD : _constants2.default.WEBRTC.SDP.OPERATION.UNHOLD; audioDirection = _sdpParser.getAudioSdpDirection(call.sdp); videoDirection = _sdpParser.getVideoSdpDirection(call.sdp); if (!local_hold_status && !hold) { self.muteOnHold(call, false); } call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); call.sdp = _sdpParser.setTcpSetupAttributeToActpass(call.sdp, self.isDtlsEnabled()); call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, null, self.isH264Enabled()); call.sdp = _sdpParser.performVideoPortZeroWorkaround(call.sdp); call.sdp = _sdpParser.checkAndRestoreICEParams(call.sdp, _sdpParser.getSdpFromObject(call.peer.localDescription)); // chrome38 fix inactiveRemoteSdp = _sdpParser.updateAudioSdpDirectionToInactive(call.sdp); inactiveRemoteSdp = _sdpParser.updateVideoSdpDirectionToInactive(inactiveRemoteSdp); data = { call: call, mustCreatePeer: call.isRemoteEndFirefox, oldSdp: call.prevRemoteSdp, newSdp: call.sdp }; if (self.createNewPeerForCall(data)) { peer = call.peer; self.setTcpSetupAttiributesOnProcessAnswer(call, call.sdp); } inactiveRemoteSdp = _sdpParser.deleteSsrcFromSdp(inactiveRemoteSdp); // 1st setRemoteDescription to make webrtc remove the audio and/or video streams // 2nd setRemote will add the audio stream back so that services like MOH can work // This code will also run in UnHold scenario, and it will remove & add video stream logger.trace('processHold: Setting remote description with (offer) SDP: ' + inactiveRemoteSdp); self.setRemoteDescription(null, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, inactiveRemoteSdp, function processHoldSetFirstRemoteDescriptionSuccessCallback() { remoteSdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); if (_sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || _sdpParser.getVideoSdpDirection(call.sdp) === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY) { remoteSdp = _sdpParser.deleteInactiveVideoSsrc(remoteSdp); } logger.trace('processHold: Setting remote description with (offer) SDP: ' + remoteSdp); self.setRemoteDescription(operation, call, peer, _constants2.default.WEBRTC.SDP.TYPE.OFFER, remoteSdp, function processHoldSetSecondRemoteDescriptionSuccessCallback() { if (!hold && !local_hold_status && videoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { call.remoteVideoState = _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY; } else { call.remoteVideoState = _sdpParser.getVideoSdpDirection(call.sdp); } peer.createAnswer(peer.remoteDescription, function processHoldCreateAnswerSuccessCallback(obj) { localSdp = _sdpParser.getSdpFromObject(obj); logger.debug('processHold: isSdpEnabled audio= ' + _sdpParser.isAudioSdpEnabled(obj.sdp)); logger.debug('processHold: isSdpEnabled video= ' + _sdpParser.isVideoSdpEnabled(obj.sdp)); obj = null; if (hold) { logger.debug('processHold: Remote HOLD'); localSdp = _sdpParser.respondToRemoteSdpDirections(localSdp, call.sdp); } else if (!local_hold_status) { logger.debug('processHold: Remote UNHOLD: direction left as it is'); if (_sdpParser.isSdpVideoSendEnabled(call.sdp)) { if (self.canOriginatorSendLocalVideo(call)) { localSdp = _sdpParser.updateVideoSdpDirection(localSdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE); } else { localSdp = _sdpParser.updateVideoSdpDirection(localSdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } } else { if (self.canOriginatorSendLocalVideo(call) && !_sdpParser.isVideoSdpDirectionInactive(call.sdp)) { localSdp = _sdpParser.updateVideoSdpDirection(localSdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { localSdp = _sdpParser.updateVideoSdpDirection(localSdp, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } } //change audio's direction to sendrecv for ssl attendees in a 3wc localSdp = _sdpParser.changeDirection(localSdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY, _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE, _constants2.default.STRING.AUDIO); } else if (local_hold_status && !hold) { logger.debug('processHold: Remote UNHOLD on local hold'); if (audioDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE) { localSdp = _sdpParser.updateAudioSdpDirectionToInactive(localSdp); } else { localSdp = _sdpParser.updateAudioSdpDirection(localSdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } if (self.canOriginatorSendLocalVideo(call)) { localSdp = _sdpParser.updateVideoSdpDirection(localSdp, _constants2.default.WEBRTC.MEDIA_STATE.SEND_ONLY); } else { localSdp = _sdpParser.updateVideoSdpDirectionToInactive(localSdp); } } localSdp = _sdpParser.updateVersion(peerLocalSdp, localSdp); localSdp = _sdpParser.checkIceParamsLengths(localSdp, call.sdp); localSdp = _sdpParser.checkAndRestoreICEParams(localSdp, call.sdp); if (_sdpParser.isSdpHasVideoWithZeroPort(localSdp) && self.getDefaultVideoContainer()) { self.useDefaultRenderer(false, false, false); } localSdp = _sdpParser.setTcpSetupAttributeTo(localSdp, call.localTcpSetupAttribute, self.isDtlsEnabled()); localSdp = _sdpParser.updateH264Level(localSdp); localSdp = _sdpParser.updateOpusConfig(localSdp, _config.opusConfig); localSdp = _sdpPipeline(call.id, localSdp, operation, _constants2.default.WEBRTC.SDP.STEP.PRE_SET_LOCAL, _constants2.default.WEBRTC.SDP.TYPE.ANSWER); logger.trace('processHold: Setting local description with (answer) SDP: ' + localSdp); peer.setLocalDescription(self.getRtcLibrary().createRTCSessionDescription(_constants2.default.WEBRTC.SDP.TYPE.ANSWER, localSdp), function processHoldSetLocalDescriptionSuccessCallback() { logger.debug('processHold: setLocalDescription success!! ' + 'iceConnectionState: ' + peer.iceConnectionState + ' iceGatheringState: ' + peer.iceGatheringState); if (peer.iceGatheringState === 'complete') { if (call.successCallback) { logger.debug('processHold iceGatheringState completed ' + peer.localDescription.sdp); _utils.callFunctionIfExist(successCallback, peer.localDescription.sdp); } } }, function processHoldSetLocalDescriptionFailureCallback(e) { logger.error('processHold: setLocalDescription failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processHoldCreateAnswerFailureCallback(e) { logger.error('processHold: createAnswer failed!!: ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processHoldSetSecondRemoteDescriptionFailureCallback(e) { logger.error('processHold: second setRemoteDescription failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }, function processHoldSetFirstRemoteDescriptionFailureCallback(e) { logger.debug('processHold: first setRemoteDescription failed!! ' + e); _utils.callFunctionIfExist(failureCallback, 'Session cannot be created'); }); }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * processHoldRespond to be used when the enabler plugin is enabled */ self.processHoldRespond = function (call, onSuccess, onFailure, isJoin) { var remoteAudioDirection, remoteVideoDirection, localHoldFlag = false, remoteHoldFlag = false, data; logger.debug('processHoldRespond: state= ' + call.peer.signalingState + ' call.currentState= ' + call.currentState); data = { call: call }; if (self.createNewPeerForCall(data)) { self.setTcpSetupAttiributesOnProcessAnswer(call, call.sdp); } call.sdp = self.performSdpWorkaroundsBeforeProcessingIncomingSdp(call.sdp); _sdpParser.init(call.sdp); remoteAudioDirection = _sdpParser.getAudioSdpDirection(call.sdp); remoteVideoDirection = _sdpParser.getVideoSdpDirection(call.sdp); var isHold = remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE || remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY; var operation = isHold ? _constants2.default.WEBRTC.SDP.OPERATION.HOLD : _constants2.default.WEBRTC.SDP.OPERATION.UNHOLD; if (call.peer.signalingState === _constants2.default.WEBRTC.RTC_SIGNALING_STATE.STABLE) { //if we are in stable state we should not change remotedescription self.onRemoteStreamAdded(call); self.setRemoteDescription(operation, call, null, null, call.sdp, onSuccess, onFailure); return; } call.sdp = _sdpParser.checkSupportedVideoCodecs(call.sdp, _sdpParser.getSdpFromObject(call.stableLocalSdp), self.isH264Enabled()); remoteHoldFlag = _sdpParser.isRemoteHold(); localHoldFlag = call.currentState === 'LOCAL_HOLD'; logger.debug('processHoldRespond: localHold= ' + localHoldFlag + ' remoteHold= ' + remoteHoldFlag); /* Required for MOH - start */ if (remoteHoldFlag === false) { if (remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE && call.currentState === 'REMOTE_HOLD') { call.previousState = call.currentState; call.currentState = 'COMPLETED'; } } else { if (call.currentState === 'COMPLETED') { call.previousState = call.currentState; call.currentState = 'REMOTE_HOLD'; } } if (localHoldFlag || remoteHoldFlag) { logger.debug('processHoldRespond: ' + call.currentState + ' : video -> inactive'); call.sdp = _sdpParser.updateSdpDirection(call.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE); } if (remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.INACTIVE && call.currentState === 'COMPLETED') { logger.debug('processHoldRespond: video inactive -> recvonly'); call.sdp = _sdpParser.updateSdpDirection(call.sdp, _constants2.default.STRING.VIDEO, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } /* Required for MOH - end */ if (localHoldFlag && remoteAudioDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) { logger.debug('processHoldRespond: Mute Remote Audio'); call.sdp = _sdpParser.updateAudioSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } if (localHoldFlag && remoteVideoDirection === _constants2.default.WEBRTC.MEDIA_STATE.SEND_RECEIVE) { logger.debug('processHoldRespond: Mute Remote Video'); call.sdp = _sdpParser.updateVideoSdpDirection(call.sdp, _constants2.default.WEBRTC.MEDIA_STATE.RECEIVE_ONLY); } self.processRespond(call, onSuccess, onFailure, isJoin, operation); }; // createEnablerDataChannel self.createDataChannel = function (dataChannelWrapperObj, onSuccess, onFailure, options) { try { if (options) { dataChannelWrapperObj.dataChannel = dataChannelWrapperObj.peer.createDataChannel('Label', options); } else { dataChannelWrapperObj.dataChannel = dataChannelWrapperObj.peer.createDataChannel('Label'); } onSuccess(dataChannelWrapperObj); } catch (error) { logger.error('Failed to create data channel, exception: ' + error.message); onFailure(error); } }; // Enabler implementation lies on webRtcPluginAdaptor.js self.createPeer = function (call, useIceServer, onsuccess, onfailure) { try { var pc, constraints = {}, i, servers = [], iceServerUrl, config; logger.info('useIceServer: ' + useIceServer); if (useIceServer) { iceServerUrl = self.getIceServerUrl(); } if (iceServerUrl instanceof Array) { for (i = 0; i < iceServerUrl.length; i++) { servers[i] = iceServerUrl[i]; } } else if (!iceServerUrl || iceServerUrl === '') { servers = []; } else { servers[0] = iceServerUrl; } config = { iceServers: servers, // NOTE: This is added temporarily because Chrome and Firefox have required set // by default and the media broker doesn't support multiplexing. ADG-14986 rtcpMuxPolicy: 'negotiate' }; // If present, take the call constraints provided as config. if (_config.callConstraints && _config.callConstraints.plugin) { // If any constraint is malformed, the RTCPeerConnection will fail to be created. logger.debug('Using custom peer constraints for call.', _config.callConstraints.plugin); constraints = _config.callConstraints.plugin; } constraints.optional = constraints.optional || []; constraints.optional.push({ 'DtlsSrtpKeyAgreement': self.isDtlsEnabled() }); if (_config.bundlePolicy !== _constants2.default.WEBRTC.SDP.BUNDLE_POLICY.DISABLED) { config.bundlePolicy = _config.bundlePolicy; } pc = self.getRtcLibrary().createRTCPeerConnection(config, constraints); self.setPeerCount(self.getPeerCount() + 1); call.peer = pc; pc.onconnecting = function (event) { self.onSessionConnecting(call, event); }; pc.onopen = function (event) { self.onSessionOpened(call, event); }; pc.onsignalingstatechange = function (event) { self.onSignalingStateChange(call, event); }; pc.onaddstream = function (event) { self.onRemoteStreamAdded(call, event); }; pc.onremovestream = function (event) { self.onRemoteStreamRemoved(call, event); }; pc.onicecandidate = function (event) { self.setupIceCandidateCollectionTimer(call); self.onIceCandidate(call, event); }; pc.onicecomplete = function () { self.onIceComplete(call); }; pc.oniceconnectionstatechange = function (event) { self.oniceconnectionstatechange(call, event); }; pc.ondatachannel = function (event) { self.onDataChannel(call, event); }; logger.info('create PeerConnection successfully.'); self.setupWebrtcLogCollectionTimer(call); _utils.callFunctionIfExist(onsuccess); } catch (err) { logger.error('Failed to create PeerConnection, exception: ' + err.message); _utils.callFunctionIfExist(onfailure); } }; self.createNewPeerForCall = function (data) { var call = data.call, mustCreatePeer = data.mustCreatePeer, sessionIdChanged = _sdpParser.getSessionIdFromSdp(data.oldSdp) !== _sdpParser.getSessionIdFromSdp(data.newSdp), isNewPeerCreated = false, oldPeer, useIceServer, telephoneEventPayloadChanged = _sdpParser.hasCodecPayloadChanged(data.oldSdp, data.newSdp), isDTLSFingerprintChanged = false; if (_config.ignoreIceParamsForServices && _config.ignoreIceParamsForServices.indexOf('call') !== -1) { useIceServer = false; } else { useIceServer = true; } if (data.call && data.call.sdp && data.call.prevRemoteSdp) { isDTLSFingerprintChanged = _sdpParser.getFingerprintFromSdp(data.call.prevRemoteSdp) !== _sdpParser.getFingerprintFromSdp(data.call.sdp); } if (mustCreatePeer || telephoneEventPayloadChanged || isDTLSFingerprintChanged || sessionIdChanged) { if (call.peer) { oldPeer = call.peer; self.collectWebRtcStats(call.sdp, oldPeer, function (stats) { logger.debug('Plugin collectWebRtcStats successfull'); if (call.stats === undefined) { call.stats = []; } call.stats.push(stats); if (oldPeer.signalingState !== 'closed') { oldPeer.close(); } self.setPeerCount(self.getPeerCount() - 1); call.dtmfSender = null; }, function () { logger.debug('Plugin collectWebRtcStats failed'); if (oldPeer.signalingState !== 'closed') { oldPeer.close(); } self.setPeerCount(self.getPeerCount() - 1); call.dtmfSender = null; }); } logger.trace('Creating new peer for call: ' + call.id); self.createPeer(call, useIceServer, function createPeerSuccessCallback() { logger.trace('New peer has created for call: ' + call.id); // // add commented out lines below // after plugin implementation // //if (data.deleteVideoStream) { // videoTrack = call.localMedia.stream.getVideoTracks()[0]; // call.localMedia.stream.removeTrack(videoTrack); //} // if (call.localMedia && call.localMedia.stream) { call.peer.addStream(call.localMedia.stream); } //clearing those since we are using a new peer self.clearTcpSetupParameters(call); isNewPeerCreated = true; }, function createPeerFailureCallback() { logger.error('New peer creation has failed!: ' + call.id); if (call.stats) { call.stats.pop(); } }); } return isNewPeerCreated; }; // pluginOnRemoteStreamAdded self.onRemoteStreamAdded = function (call, event) { var fireEvent, remoteVideoTracks = [], isVideoTrackAvailable = false; if (self.getDefaultVideoContainer()) { if (!self.isActiveCallInVideoContainer(self.getDefaultVideoContainer(), call)) { logger.debug('onRemoteStreamAdded: It is not active call. Call Id: ' + call.id); return; } } else if (self.getRemoteVideoContainer()) { if (!self.isActiveCallInVideoContainer(self.getRemoteVideoContainer(), call)) { logger.debug('onRemoteStreamAdded: It is not active call. Call Id: ' + call.id); return; } } if (event && event.stream) { call.remoteStreamUrl = self.getRtcLibrary().getURLFromStream(event.stream); remoteVideoTracks = event.stream.getVideoTracks(); } else { remoteVideoTracks = self.getRemoteVideoTrack(call.peer); } if (remoteVideoTracks) { if (remoteVideoTracks.length > 0) { isVideoTrackAvailable = true; } } if (self.getDefaultVideoContainer()) { fireEvent = self.useDefaultRenderer(call.remoteStreamUrl, false, isVideoTrackAvailable); } else if (self.getRemoteVideoContainer()) { fireEvent = self.createStreamRenderer(call.remoteStreamUrl, self.getRemoteVideoContainer()); } else { fireEvent = true; } logger.debug('onRemoteStreamAdded: ' + call.remoteStreamUrl); if (fireEvent) { self.fireOnStreamAddedEvent(call, call.remoteStreamUrl); } }; self.iceCandidateCollectionTimeoutHandler = function (call) { var sdp = call.peer.localDescription.sdp; self.clearIceCandidateCollectionTimer(call); if (_config.relayCandidateCollectionTimeoutCycle) { call.relayCandidateCycle++; } // set timeout if there is no ice candidate available or // when audio, video port assignment isn't complete if (!_sdpParser.hasCandidates(sdp, call.relayCandidateCycle, _config.relayCandidateCollectionTimeoutCycle)) { logger.debug('Re-setting ice candidate collection timeout: ' + _config.iceCandidateCollectionTimeoutInterval); call.iceCandidateCollectionTimer = setTimeout(function () { self.iceCandidateCollectionTimeoutHandler(call); }, _config.iceCandidateCollectionTimeoutInterval); return; } if (call.successCallback) { logger.debug('Ice candidate collection interrupted after given timeout, invoking successCallback.'); sdp = _sdpParser.updateH264Level(sdp); call.successCallback(sdp); } }; self.setupIceCandidateCollectionTimer = function (call) { if (_config.iceCandidateCollectionTimeoutInterval) { if (!call.iceCandidateCollectionTimer) { logger.debug('Setting ice candidate collection timeout: ' + _config.iceCandidateCollectionTimeoutInterval); if (_config.relayCandidateCollectionTimeoutCycle) { call.relayCandidateCycle = 1; } call.iceCandidateCollectionTimer = setTimeout(function () { self.iceCandidateCollectionTimeoutHandler(call); }, _config.iceCandidateCollectionTimeoutInterval); } else { logger.trace('Ice candidate collection timer exists.'); } } }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * onIceCandidate to be called when the enabler plugin is enabled */ self.onIceCandidate = function (call, event) { var sdp; if (event.candidate === null) { logger.debug('Null candidate received.'); if (call.successCallback) { sdp = _sdpParser.getSdpFromObject(call.peer.localDescription); if (_sdpParser.hasCandidates(sdp, call.relayCandidateCycle, _config.relayCandidateCollectionTimeoutCycle)) { self.clearIceCandidateCollectionTimer(call); logger.debug('Candidates received, invoking successCallback.'); sdp = _sdpParser.updateH264Level(sdp); call.successCallback(sdp); } else { logger.trace('Sdp does not have candidates.'); } } } else { logger.debug('ICE candidate received : sdpMLineIndex = ' + event.candidate.sdpMLineIndex + ', candidate = ' + event.candidate.candidate + ' for call : ' + call.id); } }; /* * Enabler implementation lies on webRtcPluginAdaptor.js * onIceComplete to be called when the enabler plugin is enabled */ self.onIceComplete = function (call) { var sdp; logger.debug('All ICE candidates received for call : ' + call.id); self.clearIceCandidateCollectionTimer(call); if (call.successCallback) { sdp = call.peer.localDescription.sdp; sdp = _sdpParser.updateH264Level(sdp); logger.trace('onIceComplete sdp : ' + sdp); call.successCallback(sdp); } }; // Enabler implementation lies on webRtcPluginAdaptor.js self.useDefaultRenderer = function (streamUrl, local, isVideoTrackAvailable) { var videoContainer; if (self.getDefaultVideoContainer() && self.getDefaultVideoContainer().children.length === 0) { // Create divs for the remote and local self.getDefaultVideoContainer().innerHTML = '<div style=\'height:100%;width:100%\'></div><div style=\'position:absolute;bottom:10px;right:10px;height:30%; width:30%;\'></div>'; } if (local) { videoContainer = self.getDefaultVideoContainer().lastElementChild; } else { videoContainer = self.getDefaultVideoContainer().firstElementChild; if (!isVideoTrackAvailable) { videoContainer.style.width = '0%'; } else { videoContainer.style.width = '100%'; } } return self.createStreamRenderer(streamUrl, videoContainer, { muted: local }); }; // Enabler implementation lies on webRtcPluginAdaptor.js self.createStreamRenderer = function (streamUrl, container) { if (!streamUrl || !container) { return; } container.innerHTML = '<object width=\'100%\' height=\'100%\' type=\'application/x-gcfwenabler-video\'><param name=\'autoplay\' value=\'true\' /><param name=\'videosrc\' value=\'' + streamUrl + '\' /></object>'; return true; }; // Enabler implementation lies on webRtcPluginAdaptor.js self.sendIntraFrame = function (call) { if (!call.peer) { return; } if (self.canOriginatorSendLocalVideo(call)) { call.peer.sendIntraFrame(); } else { //call.peer.sendBlackFrame(); //sendBlackFrame is removed from plugin return; } }; // Enabler implementation lies on webRtcPluginAdaptor.js self.sendBlackFrame = function (call) { if (!call.peer) { return; } //call.peer.sendBlackFrame(); //TODO: This function will be completely removed since sendBlackFrame is removed from plugin return; }; /** * Send DTMF tone * Enabler implementation lies on webRtcPluginAdaptor.js * * @ignore * @name rtc.sendDTMF * @function * @param {Object} call internalCall * @param {String} tone DTMF tone */ self.sendDTMF = function (call, tone) { var localAudioTrack; if (!call.dtmfSender) { localAudioTrack = self.getLocalAudioTrack(call.peer); if (!localAudioTrack) { return; } call.dtmfSender = call.peer.createDTMFSender(localAudioTrack); if (!call.dtmfSender) { return; } } if (call.dtmfSender.canInsertDTMF === true) { call.dtmfSender.insertDTMF(tone, 400); logger.info('sending outband DTMF tone: ' + tone); } else { logger.error('Failed to execute \'insertDTMF\' on \'RTCDTMFSender\': The \'canInsertDTMF\' attribute is false: this sender cannot send DTMF'); } }; /* * Enabler implementation lies on webRtcPluginAdaptor.js */ self.getCameraList = function () { return; }; /* * Enabler implementation lies on webRtcPluginAdaptor.js */ self.getMicrophoneList = function () { return; }; /* * Enabler implementation lies on webRtcPluginAdaptor.js */ self.getSpeakerList = function () { return; }; self.getNativeWebRtcStats = function (call, onSuccess, onFailure) { try { if (call) { logger.debug('getNativeWebRtcStats called'); call.peer.getStats(function (stats) { if (stats !== undefined && stats !== null) { var results = stats.result(); _utils.callFunctionIfExist(onSuccess, results); } }); } } catch (err) { logger.error('Failed to get all WebRTC Statistics: ' + err.message); _utils.callFunctionIfExist(onFailure, err); } }; self.getWebRtcStats = function (call, onSuccess, onFailure) { try { if (call) { logger.debug('getWebRtcStats called'); self.collectWebRtcStats(call.sdp, call.peer, function (stats) { var accumulatedStats = self.getAccumulatedWebRtcStats(call.stats, stats, call.cache); _utils.callFunctionIfExist(onSuccess, accumulatedStats); }, onFailure); } else { var cacheWebRtcStats = JSON.parse(_cache.getItem(_fcs.getUser() + '_stats')); _utils.callFunctionIfExist(onSuccess, cacheWebRtcStats); } } catch (err) { logger.error('Failed to get WebRTC Statistics: ' + err.message); _utils.callFunctionIfExist(onFailure, err); } return self.getStats(); }; self.getAccumulatedWebRtcStats = function (statsList, currentStats, callCache) { var i, accumulatedStats = { audio: { packetsSent: 0, bytesSent: 0, bytesReceived: 0, peerAddress: null, codec: null, packetsLost: 0, jitter: null, rtt: null }, video: { packetsSent: 0, bytesSent: 0, bytesReceived: 0, peerAddress: null, codec: null, packetsLost: 0, rtt: null } }; if (statsList !== undefined) { for (i = 0; i < statsList.length; i++) { self.accumulateStats(accumulatedStats.audio, statsList[i].audio); self.accumulateStats(accumulatedStats.video, statsList[i].video); } } self.accumulateStats(accumulatedStats.audio, currentStats.audio); accumulatedStats.audio.peerAddress = currentStats.audio.peerAddress; accumulatedStats.audio.codec = currentStats.audio.codec; accumulatedStats.audio.jitter = currentStats.audio.jitter; accumulatedStats.audio.rtt = currentStats.audio.rtt; self.accumulateStats(accumulatedStats.video, currentStats.video); accumulatedStats.video.peerAddress = currentStats.video.peerAddress; accumulatedStats.video.codec = currentStats.video.codec; accumulatedStats.video.rtt = currentStats.video.rtt; if (callCache) { _cache.setItem(_fcs.getUser() + '_stats', (0, _stringify2.default)(accumulatedStats)); } return accumulatedStats; }; self.accumulateStats = function (accumulatedStatsObj, statsObj) { accumulatedStatsObj.packetsSent += (0, _utils2.getInteger)(statsObj.packetsSent); accumulatedStatsObj.bytesSent += (0, _utils2.getInteger)(statsObj.bytesSent); accumulatedStatsObj.bytesReceived += (0, _utils2.getInteger)(statsObj.bytesReceived); accumulatedStatsObj.packetsLost += (0, _utils2.getInteger)(statsObj.packetsLost) === -1 ? 0 : (0, _utils2.getInteger)(statsObj.packetsLost); }; self.collectWebRtcStats = function (statsSdp, peer, onSuccess, onFailure) { try { if (peer) { logger.debug('collectWebRtcStats called'); peer.getStats(function (stats) { if (stats !== undefined && stats !== null) { var results = stats.result(); self.setWebRtcStats(results, statsSdp); _utils.callFunctionIfExist(onSuccess, self.getStats()); } }); } } catch (err) { logger.error('Failed to collectWebRtcStats: ' + err.message); _utils.callFunctionIfExist(onFailure, err); } return self.getStats(); }; self.setWebRtcStats = function (results, statsSdp) { var i, j, res, names, mediaDescriptions, sdpAudioPort, sdpVideoPort, transportId, googChannelId, googCodecName, alwaysMediaOnBroker, stats = { audio: { packetsSent: null, bytesSent: null, bytesReceived: null, peerAddress: '', codec: null, packetsLost: null, jitter: null, rtt: null }, video: { packetsSent: null, bytesSent: null, bytesReceived: null, peerAddress: null, codec: null, packetsLost: null, rtt: null } }; if (_sdpParser.isIceLite(statsSdp)) { alwaysMediaOnBroker = true; } else { alwaysMediaOnBroker = false; } if (statsSdp !== undefined && statsSdp !== null && results !== undefined && results !== null) { _sdpParser.init(statsSdp); _sdpParser.parseSDP(statsSdp); mediaDescriptions = _sdpParser.getMediaDescriptions(); if (mediaDescriptions !== undefined) { if (mediaDescriptions[0] !== undefined) { sdpAudioPort = mediaDescriptions[0].port; } if (mediaDescriptions[1] !== undefined) { sdpVideoPort = mediaDescriptions[1].port; } } for (i = 0; i < results.length; i++) { res = results[i]; names = res.names(); if (names !== undefined) { for (j = 0; j < names.length; j++) { googChannelId = res.stat('googChannelId'); transportId = res.stat('transportId'); googCodecName = res.stat('googCodecName'); if (transportId !== undefined && transportId.indexOf('audio') > -1 || googChannelId !== undefined && googChannelId.indexOf('audio') > -1) { if (googCodecName === 'VP8' || googCodecName === 'H264') { self.fillStats(stats.video, res, names, j, sdpVideoPort, alwaysMediaOnBroker); } else { self.fillStats(stats.audio, res, names, j, sdpAudioPort, alwaysMediaOnBroker); } } else if (transportId !== undefined && transportId.indexOf('video') > -1 || googChannelId !== undefined && googChannelId.indexOf('video') > -1) { self.fillStats(stats.video, res, names, j, sdpVideoPort, alwaysMediaOnBroker); } } if (!alwaysMediaOnBroker && sdpVideoPort !== undefined) { stats.video.peerAddress = stats.audio.peerAddress.split(':')[0]; } self.setStats(stats); } } } }; self.fillStats = function (statsObj, res, names, index, sdpRemotePort, alwaysMediaOnBroker) { var remotePort, remoteAddress; if (res.stat('googActiveConnection') === 'true' && alwaysMediaOnBroker) { remoteAddress = res.stat('googRemoteAddress'); if (remoteAddress !== undefined) { if (remoteAddress.split(':') !== undefined && remoteAddress.split(':')[1] !== undefined) { remotePort = remoteAddress.split(':')[1]; } if (remotePort === sdpRemotePort) { statsObj.peerAddress = remoteAddress; if (names[index] === 'bytesReceived') { statsObj.bytesReceived = res.stat(names[index]); } if (names[index] === 'packetsSent') { statsObj.packetsSent = res.stat(names[index]); } if (names[index] === 'bytesSent') { statsObj.bytesSent = res.stat(names[index]); } } } } if (res.stat('googActiveConnection') === 'true' && !alwaysMediaOnBroker) { remoteAddress = res.stat('googRemoteAddress'); statsObj.peerAddress = remoteAddress; } if (res.type === 'ssrc' || res.id.indexOf('ssrc') > -1) { if (names[index] === 'packetsLost') { statsObj.packetsLost = res.stat(names[index]); } if (names[index] === 'googCodecName') { statsObj.codec = res.stat(names[index]); } if (names[index] === 'googJitterReceived') { statsObj.jitter = res.stat(names[index]); } if (names[index] === 'googRtt') { statsObj.rtt = res.stat(names[index]); } if (!alwaysMediaOnBroker) { if (names[index] === 'bytesReceived') { statsObj.bytesReceived = res.stat(names[index]); } if (names[index] === 'packetsSent') { statsObj.packetsSent = res.stat(names[index]); } if (names[index] === 'bytesSent') { statsObj.bytesSent = res.stat(names[index]); } } } }; self.addRemoteCandidates = function () { logger.warn('addIceCandidates does not work on plugin'); return; }; //Plugin does not support merging audio streams self.mergeAudioStream = false; logger.debug('WebRtcPluginAdaptor initialized'); } /***/ }), /***/ "../fcs/src/js/webrtc/adaptor/webRtcPluginv22Adaptor.js": /*!**************************************************************!*\ !*** ../fcs/src/js/webrtc/adaptor/webRtcPluginv22Adaptor.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebRtcPluginv22AdaptorImpl = WebRtcPluginv22AdaptorImpl; var _utils = __webpack_require__(/*! ../../utils */ "../fcs/src/js/utils/index.js"); function WebRtcPluginv22AdaptorImpl(_ref) { var _super = _ref.base, _model = _ref.model, _logManager = _ref.LogManager; var self = this, webRtcPlugin22Version = { major: 2, minor: 2, min_revision: 477, min_build: 0, current_revision: 477, current_build: 0 }, logger = _logManager.getLogger('WebRtcPluginv22AdaptorImpl'); logger.debug('WebRtcPluginv22Adaptor initializing'); (0, _utils.compose)(_super, self); (0, _utils.compose)(_model, self); self.setPluginVersion(webRtcPlugin22Version); logger.debug('WebRtcPluginv22Adaptor initialized'); } /***/ }), /***/ "../fcs/src/js/webrtc/adaptor/webRtcPluginv31Adaptor.js": /*!**************************************************************!*\ !*** ../fcs/src/js/webrtc/adaptor/webRtcPluginv31Adaptor.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebRtcPluginv31AdaptorImpl = WebRtcPluginv31AdaptorImpl; var _utils = __webpack_require__(/*! ../../utils */ "../fcs/src/js/utils/index.js"); function WebRtcPluginv31AdaptorImpl(_ref) { var _super = _ref.base, _model = _ref.model, _logManager = _ref.LogManager, _sdpParser = _ref.SdpParser; var self = this, webRtcPlugin31Version = { major: 3, minor: 1, min_revision: 520, min_build: 0, current_revision: 524, current_build: 0 }, logger = _logManager.getLogger('WebRtcPluginv31AdaptorImpl'); logger.debug('WebRtcPluginv31Adaptor initializing'); (0, _utils.compose)(_super, self); (0, _utils.compose)(_model, self); self.setPluginVersion(webRtcPlugin31Version); /** * Send DTMF tone * Enabler implementation lies on webRtcPluginv31Adaptor.js * * @ignore * @name rtc.sendDTMF * @function * @param {Object} call internalCall * @param {String} tone DTMF tone */ self.sendDTMF = function (call, tone) { var localAudioTrack; if (!call.dtmfSender) { localAudioTrack = self.getLocalAudioTrack(call.peer); if (!localAudioTrack) { return; } call.dtmfSender = call.peer.createDTMFSender(localAudioTrack); if (!call.dtmfSender) { return; } } if (!_sdpParser.isSdpHasTelephoneEvent(call.peer.remoteDescription.sdp)) { call.dtmfSender.insertDTMF(tone, 400, 100, true); logger.info('sending inband DTMF tone: ' + tone); } else { if (call.dtmfSender.canInsertDTMF === true) { call.dtmfSender.insertDTMF(tone, 400); logger.info('sending outband DTMF tone: ' + tone); } else { logger.error('Failed to execute \'insertDTMF\' on \'RTCDTMFSender\': The \'canInsertDTMF\' attribute is false: this sender cannot send DTMF'); } } }; logger.debug('WebRtcPluginv31Adaptor initialized'); } /***/ }), /***/ "../fcs/src/js/webrtc/decorator/module.js": /*!************************************************!*\ !*** ../fcs/src/js/webrtc/decorator/module.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _webRtcLibraryDecorator = __webpack_require__(/*! ./webRtcLibraryDecorator */ "../fcs/src/js/webrtc/decorator/webRtcLibraryDecorator.js"); var _webRtcLibraryChromeDecorator = __webpack_require__(/*! ./webRtcLibraryChromeDecorator */ "../fcs/src/js/webrtc/decorator/webRtcLibraryChromeDecorator.js"); var _webRtcLibraryFirefoxDecorator = __webpack_require__(/*! ./webRtcLibraryFirefoxDecorator */ "../fcs/src/js/webrtc/decorator/webRtcLibraryFirefoxDecorator.js"); exports.default = { WebRtcDecoratorFactory: function WebRtcDecoratorFactory(container) { return function (target) { return (0, _webRtcLibraryDecorator.webRtcLibraryDecoratorImpl)(target, container.Utils); }; }, WebRtcChromeDecoratorFactory: function WebRtcChromeDecoratorFactory(container) { return function (target) { return (0, _webRtcLibraryChromeDecorator.webRtcLibraryChromeDecoratorImpl)(target, container.Global, container.Navigator, container.Utils, container.LogManager); }; }, WebRtcFirefoxDecoratorFactory: function WebRtcFirefoxDecoratorFactory(container) { return function (target) { return (0, _webRtcLibraryFirefoxDecorator.webRtcLibraryFirefoxDecoratorImpl)(target, container.WebRtcChromeDecoratorFactory, container.Global, container.Navigator); }; } }; /***/ }), /***/ "../fcs/src/js/webrtc/decorator/webRtcLibraryChromeDecorator.js": /*!**********************************************************************!*\ !*** ../fcs/src/js/webrtc/decorator/webRtcLibraryChromeDecorator.js ***! \**********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.webRtcLibraryChromeDecoratorImpl = webRtcLibraryChromeDecoratorImpl; var _call = __webpack_require__(/*! ../../call/call.js */ "../fcs/src/js/call/call.js"); function webRtcLibraryChromeDecoratorImpl(target, _window, _navigator, _utils, _logManager) { var logger = _logManager.getLogger('webRtcLibraryChromeDecoratorImpl'), screenShareExtensionLoaded = false, screenShareExtensionId; target.getUserMedia = function (constraints, successCallback, failureCallback) { function getSourceMedia(mediaSourceId) { if (!constraints.video.mandatory) { constraints.video.mandatory = {}; } if (mediaSourceId) { constraints.video.mandatory.chromeMediaSourceId = mediaSourceId; } constraints.video.mandatory.chromeMediaSource = 'desktop'; _navigator.webkitGetUserMedia(constraints, successCallback, failureCallback); } var isScreensharing = constraints.video && constraints.video.mediaSource === 'screen'; if (isScreensharing) { // This isn't a real constraint; remove it before using the constraints. delete constraints.video['mediaSource']; if (constraints.video.mandatory.chromeMediaSourceId) { /* * Screenshare Scenario #1: * A mediaSourceId was provided as an option when starting screenshare. */ getSourceMedia(); } else if (screenShareExtensionLoaded) { /* * Screenshare Scenario #2: * The app provided an extension Id on setup, so we need to talk with * that extension to retrieve a mediaSourceId. */ _window.chrome.runtime.sendMessage(screenShareExtensionId, { message: 'chooseDesktopMedia' }, // sendMessage success callback. function (response) { if (response && response.mediaSourceId) { getSourceMedia(response.mediaSourceId); } else { _utils.callFunctionIfExist(failureCallback); } }); } else { // Neither screensharing method worked. logger.debug('No extension ID or media source ID provided.'); _utils.callFunctionIfExist(failureCallback); } } else { // Regular getUserMedia. _navigator.webkitGetUserMedia(constraints, successCallback, failureCallback); } }; target.initScreenSharing = function (onSuccess, onFailure, options) { var screenSharingOpts = options.screenSharing; if (screenSharingOpts && screenSharingOpts.chromeExtensionId) { screenShareExtensionId = screenSharingOpts.chromeExtensionId; try { _window.chrome.runtime.sendMessage(screenShareExtensionId, { message: 'version' }, function (response) { if (response && response.version) { screenShareExtensionLoaded = true; _utils.callFunctionIfExist(onSuccess); } else { _utils.callFunctionIfExist(onFailure, _call.mediaErrors.NO_SCREENSHARING_WARNING); } }); } catch (error) { _utils.callFunctionIfExist(onFailure, _call.mediaErrors.NO_SCREENSHARING_WARNING); } } else { // If there is no screensharing extension, screensharing can still work if the application // provides the media source id on it's own. Consider this else case a success, since // we don't want to say screensharing is not available. _utils.callFunctionIfExist(onSuccess); } }; target.showSettingsWindow = function () { return; }; target.createRTCSessionDescription = function (type, sdp) { return new _window.RTCSessionDescription({ 'type': type, 'sdp': sdp }); }; target.createRTCIceCandidate = function (candidate) { return new _window.RTCIceCandidate(candidate); }; target.getURLFromStream = function (stream) { return _window.URL.createObjectURL(stream); }; target.createRTCPeerConnection = function (config, constraints) { if (_window.RTCPeerConnection) { // Non-prefixed API is available in Chrome 56+. return new _window.RTCPeerConnection(config, constraints); } else { return new _window.webkitRTCPeerConnection(config, constraints); } }; target.checkMediaSourceAvailability = function (callback) { var i, videoSourceAvailable, audioSourceAvailable, sources = []; function executeCallback(videoSourceAvailable, audioSourceAvailable) { _utils.callFunctionIfExist(callback, { videoSourceAvailable: videoSourceAvailable, audioSourceAvailable: audioSourceAvailable, sourceList: sources, // Hardcode screensharing to be available, since there is // no initialization needed for screensharing to be available. screenSourceAvailable: true }); } function processMediaDevices(mediaSources) { for (i = 0; i < mediaSources.length; i++) { if (mediaSources[i].kind === 'videoinput' || mediaSources[i].kind === 'video') { // Video source is available such as webcam videoSourceAvailable = true; } else if (mediaSources[i].kind === 'audioinput' || mediaSources[i].kind === 'audio') { // audio source is available such as mic audioSourceAvailable = true; } sources.push({ id: mediaSources[i].deviceId || mediaSources[i].id, kind: mediaSources[i].kind, label: mediaSources[i].label, groupId: mediaSources[i].groupId }); } executeCallback(videoSourceAvailable, audioSourceAvailable); } if (_navigator.mediaDevices && _navigator.mediaDevices.enumerateDevices) { _navigator.mediaDevices.enumerateDevices().then(processMediaDevices).catch(function (error) { logger.error('Failed to enumerate devices. Error name: ' + error.name + 'Error message: ' + error.message); executeCallback(false, false); }); } else { _window.MediaStreamTrack.getSources(processMediaDevices); } }; target.detachWebAudioContextFromLocalMedia = function (localMedia) { if (localMedia && localMedia.mediaStreamDestination && localMedia.mediaStreamDestination.numberOfOutputs > 0) { localMedia.mediaStreamDestination.disconnect(); } }; target.stopLocalMedia = function (localMedia) { if (localMedia) { if (localMedia.stream) { target.stopStream(localMedia.stream); } if (localMedia.originalStream) { target.stopStream(localMedia.originalStream); } } }; target.stopStream = function (stream) { var i, tracks = []; if (stream && stream.getTracks) { tracks = stream.getTracks(); } for (i in tracks) { if (tracks.hasOwnProperty(i)) { tracks[i].stop(); } } }; target.get_audioInDeviceCount = function () { // Not Applicable for Chrome Native return 1; }; target.get_audioOutDeviceCount = function () { // Not Applicable for Chrome Native return 1; }; target.get_videoDeviceCount = function () { // Not Applicable for Chrome Native return 1; }; target.set_logSeverityLevel = function () { // Not Applicable for Chrome Native return false; }; target.get_logSeverityLevel = function () { // Not Applicable for Chrome Native return; }; target.enable_logCallback = function () { // Not Applicable for Chrome Native return; }; target.disable_logCallback = function () { // Not Applicable for Chrome Native return; }; target.updateStream = function (peer, call) { var localStreams = peer.getLocalStreams(); if (localStreams && localStreams.length > 0) { peer.removeStream(peer.getLocalStreams()[0]); } peer.addStream(call.localMedia.stream); }; } /***/ }), /***/ "../fcs/src/js/webrtc/decorator/webRtcLibraryDecorator.js": /*!****************************************************************!*\ !*** ../fcs/src/js/webrtc/decorator/webRtcLibraryDecorator.js ***! \****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.webRtcLibraryDecoratorImpl = webRtcLibraryDecoratorImpl; function webRtcLibraryDecoratorImpl(target, _utils) { var libraryObjWrapper = {}; libraryObjWrapper.getUserMedia = target.getUserMedia; libraryObjWrapper.showSettingsWindow = target.showSettingsWindow; libraryObjWrapper.getURLFromStream = target.getURLFromStream; libraryObjWrapper.enableH264 = target.enableH264; libraryObjWrapper.createRTCSessionDescription = function (type, sdp) { return target.createSessionDescription(type, sdp); }; libraryObjWrapper.createRTCIceCandidate = function (candidate, type, number) { return target.createIceCandidate(candidate, type, number); }; libraryObjWrapper.createRTCPeerConnection = function (config, constraints) { return target.createPeerConnection(config, constraints); }; libraryObjWrapper.setLang = function (lang) { target.setLanguage(lang || 'en'); }; libraryObjWrapper.checkMediaSourceAvailability = function (callback) { _utils.callFunctionIfExist(callback, { videoSourceAvailable: target.getVideoDeviceNames().length > 0 ? true : false, audioSourceAvailable: target.getAudioInDeviceNames().length > 0 ? true : false, sourceList: [], screenSourceAvailable: false }); }; libraryObjWrapper.get_audioInDeviceCount = function () { return target.getAudioInDeviceNames().length; }; libraryObjWrapper.get_audioOutDeviceCount = function () { return target.getAudioOutDeviceNames().length; }; libraryObjWrapper.get_videoDeviceCount = function () { return target.getVideoDeviceNames().length; }; libraryObjWrapper.set_logSeverityLevel = function (level) { target.logSeverityLevel = level; return true; }; libraryObjWrapper.get_logSeverityLevel = function () { return target.logSeverityLevel; }; libraryObjWrapper.enable_logCallback = function (handler) { target.logCallback = handler; return true; }; libraryObjWrapper.disable_logCallback = function () { target.logCallback = null; }; libraryObjWrapper.setType = function (applicationType) { target.type = applicationType; }; libraryObjWrapper.getType = function () { return target.type; }; libraryObjWrapper.getVersion = function () { return target.version; }; libraryObjWrapper.setH264CodecStateChangeHandler = function (handler) { target.onh264codecstatechange = handler; }; libraryObjWrapper.getCurrentPluginVersionObject = function () { var splittedPluginVersion = target.version.split('.'), currentPluginVersion; currentPluginVersion = { major: parseInt(splittedPluginVersion[0], 10), minor: parseInt(splittedPluginVersion[1], 10), revision: parseInt(splittedPluginVersion[2], 10), build: parseInt(splittedPluginVersion[3], 10) }; return currentPluginVersion; }; libraryObjWrapper.detachWebAudioContextFromLocalMedia = function (localMedia) { localMedia.mediaStreamDestination.disconnect(); }; libraryObjWrapper.stopLocalMedia = function (localMedia) { if (localMedia) { libraryObjWrapper.stopStream(localMedia.stream); libraryObjWrapper.stopStream(localMedia.originalStream); } }; libraryObjWrapper.stopStream = function (stream) { if (stream && stream.stop) { stream.stop(); } }; libraryObjWrapper.updateStream = function (peer, call) { var localStreams = peer.localStreams; if (localStreams && localStreams.length > 0) { peer.removeStream(localStreams.item(0)); } peer.addStream(call.localMedia.stream); }; return libraryObjWrapper; } /***/ }), /***/ "../fcs/src/js/webrtc/decorator/webRtcLibraryFirefoxDecorator.js": /*!***********************************************************************!*\ !*** ../fcs/src/js/webrtc/decorator/webRtcLibraryFirefoxDecorator.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.webRtcLibraryFirefoxDecoratorImpl = webRtcLibraryFirefoxDecoratorImpl; function webRtcLibraryFirefoxDecoratorImpl(target, _super, _window, _navigator) { _super(target); target.getUserMedia = function (constraints, successCallback, failureCallback) { if (_navigator.mediaDevices && _navigator.mediaDevices.getUserMedia) { _navigator.mediaDevices.getUserMedia(constraints).then(successCallback).catch(failureCallback); } else { _navigator.mozGetUserMedia(constraints, successCallback, failureCallback); } }; target.createRTCSessionDescription = function (type, sdp) { if (_window.RTCSessionDescription) { return new _window.RTCSessionDescription({ 'type': type, 'sdp': sdp }); } else { return new _window.mozRTCSessionDescription({ 'type': type, 'sdp': sdp }); } }; target.createRTCIceCandidate = function (candidate) { if (_window.RTCIceCandidate) { return new _window.RTCIceCandidate(candidate); } else { return new _window.mozRTCIceCandidate(candidate); } }; target.createRTCPeerConnection = function (config, constraints) { if (_window.RTCPeerConnection) { return new _window.RTCPeerConnection(config, constraints); } else { return new _window.mozRTCPeerConnection(config, constraints); } }; target.stopLocalMedia = function (localMedia) { if (localMedia) { target.stopStream(localMedia.stream); target.stopStream(localMedia.originalStream); } }; target.stopStream = function (stream) { var i, tracks = []; if (stream && stream.getTracks) { tracks = stream.getTracks(); } for (i in tracks) { if (tracks.hasOwnProperty(i)) { tracks[i].stop(); } } }; target.updateStream = function () { return; // peer.removeTrack(peer.getSenders()[0]); // peer.addStream(call.localMedia.stream); }; } /***/ }), /***/ "../fcs/src/js/webrtc/model/module.js": /*!********************************************!*\ !*** ../fcs/src/js/webrtc/model/module.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _webRtcAdaptorModel = __webpack_require__(/*! ./webRtcAdaptorModel */ "../fcs/src/js/webrtc/model/webRtcAdaptorModel.js"); var _webRtcChromeAdaptorModel = __webpack_require__(/*! ./webRtcChromeAdaptorModel */ "../fcs/src/js/webrtc/model/webRtcChromeAdaptorModel.js"); var _webRtcFirefoxAdaptorModel = __webpack_require__(/*! ./webRtcFirefoxAdaptorModel */ "../fcs/src/js/webrtc/model/webRtcFirefoxAdaptorModel.js"); var _webRtcPluginAdaptorModel = __webpack_require__(/*! ./webRtcPluginAdaptorModel */ "../fcs/src/js/webrtc/model/webRtcPluginAdaptorModel.js"); exports.default = { WebRtcAdaptorModelFactory: function WebRtcAdaptorModelFactory() { return _webRtcAdaptorModel.WebRtcAdaptorModel; }, WebRtcChromeAdaptorModelFactory: function WebRtcChromeAdaptorModelFactory() { return _webRtcChromeAdaptorModel.WebRtcChromeAdaptorModel; }, WebRtcFirefoxAdaptorModelFactory: function WebRtcFirefoxAdaptorModelFactory() { return _webRtcFirefoxAdaptorModel.WebRtcFirefoxAdaptorModel; }, WebRtcPluginAdaptorModelFactory: function WebRtcPluginAdaptorModelFactory() { return _webRtcPluginAdaptorModel.WebRtcPluginAdaptorModel; } }; /***/ }), /***/ "../fcs/src/js/webrtc/model/webRtcAdaptorModel.js": /*!********************************************************!*\ !*** ../fcs/src/js/webrtc/model/webRtcAdaptorModel.js ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebRtcAdaptorModel = WebRtcAdaptorModel; var _map = __webpack_require__(/*! ../../utils/map */ "../fcs/src/js/utils/map.js"); var _map2 = _interopRequireDefault(_map); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function WebRtcAdaptorModel() { var self = {}, dtlsEnabled = false, dscpEnabled, iceServerUrl = '', containers = { video: null, localVideo: null, remoteVideo: null, defaultVideo: null }, mediaSources = { video: { available: false }, audio: { available: false }, screen: { available: false, width: '1024', height: '768', rate: 15 } }, stats = {}, initialized = false, rtcLibrary = {}, language, logLevel = 4, peerCount = 0, pluginEnabled = false, h264Enabled = false, screenStream, localStreamMap = new _map2.default(), privateStreamMap = new _map2.default(), localMedia = {}, selectedMicrophoneId, selectedSpeakerId, selectedCameraId, mediaSourceList; self.getLocalMedia = function () { return localMedia; }; self.setLocalMedia = function (media) { localMedia = media; }; self.getLocalStreamMap = function () { return localStreamMap; }; self.getScreenStream = function () { return screenStream; }; self.setScreenStream = function (stream) { screenStream = stream; }; self.isH264Enabled = function () { return h264Enabled; }; self.setH264Enabled = function (enabled) { h264Enabled = enabled === true ? true : false; }; self.getIceServerUrl = function () { return iceServerUrl; }; self.setIceServerUrl = function (url) { iceServerUrl = url; }; self.isDtlsEnabled = function () { return dtlsEnabled; }; self.setDtlsEnabled = function (enabled) { dtlsEnabled = enabled; }; self.isDscpEnabled = function () { return dscpEnabled; }; self.setDscpEnabled = function (enabled) { dscpEnabled = enabled; }; self.getVideoContainer = function () { return containers.video; }; self.setVideoContainer = function (container) { containers.video = container; }; self.getLocalVideoContainer = function () { return containers.localVideo; }; self.setLocalVideoContainer = function (container) { containers.localVideo = container; }; self.getRemoteVideoContainer = function () { return containers.remoteVideo; }; self.setRemoteVideoContainer = function (container) { containers.remoteVideo = container; }; self.getDefaultVideoContainer = function () { return containers.defaultVideo; }; self.setDefaultVideoContainer = function (container) { containers.defaultVideo = container; }; self.isInitialized = function () { return initialized; }; self.setInitialized = function (value) { initialized = value === true ? true : false; }; self.getRtcLibrary = function () { return rtcLibrary; }; self.setRtcLibrary = function (library) { rtcLibrary = library; }; self.getLogLevel = function () { return logLevel; }; self.setLogLevel = function (level) { logLevel = level; }; self.getLanguage = function () { return language; }; self.setLanguage = function (lang) { language = lang; }; self.getVideoWidth = function () { return mediaSources.video.width; }; self.setVideoWidth = function (_videoWidth) { mediaSources.video.width = _videoWidth; }; self.getVideoHeight = function () { return mediaSources.video.height; }; self.setVideoHeight = function (_videoHeight) { mediaSources.video.height = _videoHeight; }; self.getVideoSourceAvailable = function () { return mediaSources.video.available || mediaSources.screen.available; }; self.setVideoSourceAvailable = function (_videoSourceAvailable) { mediaSources.video.available = _videoSourceAvailable; }; self.getAudioSourceAvailable = function () { return mediaSources.audio.available; }; self.setAudioSourceAvailable = function (_audioSourceAvailable) { mediaSources.audio.available = _audioSourceAvailable; }; self.setMediaSources = function (mediaSourceInfo) { if (mediaSourceInfo) { self.setVideoSourceAvailable(mediaSourceInfo.videoSourceAvailable); self.setAudioSourceAvailable(mediaSourceInfo.audioSourceAvailable); self.setScreenSourceAvailable(mediaSourceInfo.screenSourceAvailable); self.setMediaSourceList(mediaSourceInfo.sourceList); } }; self.getScreenSourceAvailable = function () { return mediaSources.screen.available; }; self.setScreenSourceAvailable = function (_videoSourceAvailable) { mediaSources.screen.available = _videoSourceAvailable; }; self.getScreenWidth = function () { return mediaSources.screen.width; }; self.setScreenWidth = function (_screenWidth) { mediaSources.screen.width = _screenWidth; }; self.getScreenHeight = function () { return mediaSources.screen.height; }; self.setScreenHeight = function (_screenHeight) { mediaSources.screen.height = _screenHeight; }; self.getScreenFrameRate = function () { return mediaSources.screen.rate; }; self.setScreenFrameRate = function (_screenRate) { mediaSources.screen.rate = _screenRate; }; self.getPeerCount = function () { return peerCount; }; self.setPeerCount = function (_peerCount) { peerCount = _peerCount; }; self.isPluginEnabled = function () { return pluginEnabled; }; self.setPluginEnabled = function (_isPluginEnabled) { pluginEnabled = _isPluginEnabled; }; self.setSelectedMicrophoneId = function (_selectedMicrophoneId) { selectedMicrophoneId = _selectedMicrophoneId; }; self.getSelectedMicrophoneId = function () { return selectedMicrophoneId; }; self.setSelectedSpeakerId = function (_selectedSpeakerId) { selectedSpeakerId = _selectedSpeakerId; }; self.getSelectedSpeakerId = function () { return selectedSpeakerId; }; self.setSelectedCameraId = function (_selectedCameraId) { selectedCameraId = _selectedCameraId; }; self.getSelectedCameraId = function () { return selectedCameraId; }; self.getStreamById = function (id) { return privateStreamMap.get(id); }; self.removeStreamFromMap = function (id) { privateStreamMap.remove(id); }; self.getPrivateStreamMap = function () { return privateStreamMap; }; self.setMediaSourceList = function (_mediaSourceList) { mediaSourceList = _mediaSourceList; }; self.getMediaSourceList = function () { return mediaSourceList; }; self.getStats = function () { return stats; }; self.setStats = function (_stats) { stats = _stats; }; self.getUserMediaContraints = function () { return { audio: true, video: true }; }; return self; } /***/ }), /***/ "../fcs/src/js/webrtc/model/webRtcChromeAdaptorModel.js": /*!**************************************************************!*\ !*** ../fcs/src/js/webrtc/model/webRtcChromeAdaptorModel.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _assign = __webpack_require__(/*! babel-runtime/core-js/object/assign */ "../../node_modules/babel-runtime/core-js/object/assign.js"); var _assign2 = _interopRequireDefault(_assign); exports.WebRtcChromeAdaptorModel = WebRtcChromeAdaptorModel; var _webRtcAdaptorModel = __webpack_require__(/*! ./webRtcAdaptorModel */ "../fcs/src/js/webrtc/model/webRtcAdaptorModel.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function WebRtcChromeAdaptorModel() { var self = {}, mediaSourceId; var base = (0, _webRtcAdaptorModel.WebRtcAdaptorModel)(); (0, _assign2.default)(self, base); self.getMediaSourceId = function () { return mediaSourceId; }; self.setMediaSourceId = function (sourceId) { mediaSourceId = sourceId; }; return self; } /***/ }), /***/ "../fcs/src/js/webrtc/model/webRtcFirefoxAdaptorModel.js": /*!***************************************************************!*\ !*** ../fcs/src/js/webrtc/model/webRtcFirefoxAdaptorModel.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _assign = __webpack_require__(/*! babel-runtime/core-js/object/assign */ "../../node_modules/babel-runtime/core-js/object/assign.js"); var _assign2 = _interopRequireDefault(_assign); exports.WebRtcFirefoxAdaptorModel = WebRtcFirefoxAdaptorModel; var _webRtcAdaptorModel = __webpack_require__(/*! ./webRtcAdaptorModel */ "../fcs/src/js/webrtc/model/webRtcAdaptorModel.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function WebRtcFirefoxAdaptorModel() { var self = {}, // Since Firefox supports H264 by default, this attribute set as true h264Enabled = true, mediaSourceId; var base = (0, _webRtcAdaptorModel.WebRtcAdaptorModel)(); (0, _assign2.default)(self, base); self.isH264Enabled = function () { return h264Enabled; }; self.setH264Enabled = function (enabled) { h264Enabled = enabled === true ? true : false; }; self.getMediaSourceId = function () { return mediaSourceId; }; self.setMediaSourceId = function (sourceId) { mediaSourceId = sourceId; }; return self; } /***/ }), /***/ "../fcs/src/js/webrtc/model/webRtcPluginAdaptorModel.js": /*!**************************************************************!*\ !*** ../fcs/src/js/webrtc/model/webRtcPluginAdaptorModel.js ***! \**************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _assign = __webpack_require__(/*! babel-runtime/core-js/object/assign */ "../../node_modules/babel-runtime/core-js/object/assign.js"); var _assign2 = _interopRequireDefault(_assign); exports.WebRtcPluginAdaptorModel = WebRtcPluginAdaptorModel; var _webRtcAdaptorModel = __webpack_require__(/*! ./webRtcAdaptorModel */ "../fcs/src/js/webrtc/model/webRtcAdaptorModel.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function WebRtcPluginAdaptorModel() { var self = {}, //this variable will be always set by a plugin adaptor. pluginVersion = { major: 0, minor: 0, min_revision: 0, min_build: 0, current_revision: 0, current_build: 0 }; var base = (0, _webRtcAdaptorModel.WebRtcAdaptorModel)(); (0, _assign2.default)(self, base); self.getPluginVersion = function () { return pluginVersion; }; self.setPluginVersion = function (version) { pluginVersion = version; }; self.getUserMediaContraints = function () { return { audio: true, video: true }; }; return self; } /***/ }), /***/ "../fcs/src/js/webrtc/module.js": /*!**************************************!*\ !*** ../fcs/src/js/webrtc/module.js ***! \**************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _module = __webpack_require__(/*! ./adaptor/module */ "../fcs/src/js/webrtc/adaptor/module.js"); var _module2 = _interopRequireDefault(_module); var _module3 = __webpack_require__(/*! ./decorator/module */ "../fcs/src/js/webrtc/decorator/module.js"); var _module4 = _interopRequireDefault(_module3); var _module5 = __webpack_require__(/*! ./model/module */ "../fcs/src/js/webrtc/model/module.js"); var _module6 = _interopRequireDefault(_module5); var _webRtcManager = __webpack_require__(/*! ./webRtcManager */ "../fcs/src/js/webrtc/webRtcManager.js"); var _webRtcAdaptorFactory = __webpack_require__(/*! ./webRtcAdaptorFactory */ "../fcs/src/js/webrtc/webRtcAdaptorFactory.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _extends3.default)({}, _module2.default, _module4.default, _module6.default, { WebRtcAdaptorFactory: function WebRtcAdaptorFactory(container) { return new _webRtcAdaptorFactory.WebRtcAdaptorFactory(container); }, WebRtcManager: function WebRtcManager(container) { return new _webRtcManager.WebRtcManager(container); } }); /***/ }), /***/ "../fcs/src/js/webrtc/webRtcAdaptorFactory.js": /*!****************************************************!*\ !*** ../fcs/src/js/webrtc/webRtcAdaptorFactory.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebRtcAdaptorFactory = WebRtcAdaptorFactory; function WebRtcAdaptorFactory(_ref) { var _navigator = _ref.Navigator, _logManager = _ref.LogManager, _config = _ref.Config, _WebRtcChromeAdaptor = _ref.WebRtcChromeAdaptorFactory, _WebRtcContainerAdaptor = _ref.WebRtcContainerAdaptorFactory, _WebRtcFirefoxAdaptor = _ref.WebRtcFirefoxAdaptorFactory, _WebRtcFirefoxEsrAdaptor = _ref.WebRtcFirefoxEsrAdaptorFactory, _WebRtcPluginv22Adaptor = _ref.WebRtcPluginv22AdaptorFactory, _WebRtcPluginv31Adaptor = _ref.WebRtcPluginv31AdaptorFactory; var logger = _logManager.getLogger('WebRtcAdaptorFactory'), NAVIGATOR_TYPES = { CHROME: 'chrome', FIREFOX: 'firefox', 'PLUGIN': 'plugin', CONTAINER: 'container' }, PLUGIN_MODES = { // 3.0 Enabler Plugin WEBRTCH264: 'webrtch264', // 2.2 Enabler Plugin WEBRTC22: 'webrtc22', // Default Enabler Plugin WEBRTC: 'webrtc', // Native For Chrome Browser and Default Enabler Plugin for other Browsers AUTO: 'auto', // Native For Chrome Browser and Default Enabler Plugin for other Browsers AUTO22: 'auto22', // Native For Chrome Browser and 3.0 Enabler Plugin for other Browsers AUTOH264: 'autoh264', // Native For Chrome AND Firefox Browser and Enabler Plugin for other Browsers AUTOFIREFOX: 'autofirefox' }, DEFAULT_RTC_PLUGIN_MODE = PLUGIN_MODES.WEBRTCH264, DEFAULT_RTC_ADAPTOR = _WebRtcPluginv31Adaptor, PLUGIN_MODE_LOOKUP_TABLE = { chrome: { webrtc: DEFAULT_RTC_PLUGIN_MODE, autofirefox: PLUGIN_MODES.AUTO, autoh264: PLUGIN_MODES.AUTO, webrtch264: PLUGIN_MODES.WEBRTCH264 }, firefox: { webrtc: DEFAULT_RTC_PLUGIN_MODE, auto: DEFAULT_RTC_PLUGIN_MODE, auto22: PLUGIN_MODES.WEBRTC22, autoh264: PLUGIN_MODES.WEBRTCH264, autofirefox: PLUGIN_MODES.AUTO }, plugin: { auto: DEFAULT_RTC_PLUGIN_MODE, auto22: PLUGIN_MODES.WEBRTC22, autoh264: PLUGIN_MODES.WEBRTCH264, autofirefox: DEFAULT_RTC_PLUGIN_MODE, webrtc: DEFAULT_RTC_PLUGIN_MODE } }, ADAPTOR_LOOKUP_TABLE = { chrome: { auto: _WebRtcChromeAdaptor, autoh264: _WebRtcChromeAdaptor, webrtc22: _WebRtcPluginv22Adaptor, webrtch264: _WebRtcPluginv31Adaptor }, firefox: { auto: _WebRtcFirefoxAdaptor, autoesr: _WebRtcFirefoxEsrAdaptor, webrtc22: _WebRtcPluginv22Adaptor, webrtch264: _WebRtcPluginv31Adaptor }, plugin: { webrtc22: _WebRtcPluginv22Adaptor, webrtch264: _WebRtcPluginv31Adaptor }, container: { auto: _WebRtcContainerAdaptor, autoh264: _WebRtcContainerAdaptor, webrtc22: _WebRtcContainerAdaptor, webrtch264: _WebRtcContainerAdaptor } }, COMPOSIT_PLUGIN_MODES = { // Default Enabler Plugin WEBRTC: 'webrtc', // Native For Chrome And Firefox Browser and Default Enabler Plugin for other Browsers AUTO: 'auto' }, COMPOSIT_ADAPTOR_LOOKUP_TABLE = { chrome: { auto: _WebRtcChromeAdaptor, webrtc: DEFAULT_RTC_ADAPTOR }, firefox: { auto: _WebRtcFirefoxAdaptor, autoesr: _WebRtcFirefoxEsrAdaptor, webrtc: DEFAULT_RTC_ADAPTOR }, plugin: { auto: DEFAULT_RTC_ADAPTOR, webrtc: DEFAULT_RTC_ADAPTOR }, container: { auto: _WebRtcContainerAdaptor, webrtc: _WebRtcContainerAdaptor } }, pluginMode; function getNavigatorType() { var type, version, regex; if (_navigator.userAgent && _navigator.userAgent.indexOf('GENBANDOmni') !== -1 && _navigator.userAgent.indexOf('Chrome') === -1) { /* Special case: Handle the OmniContainer used by SO explicitly. Use the userAgent of the client to determine which adaptor to use. - Desktop: - 1.1 requires the Container adaptor. - 1.2+ should use the Chrome adaptor. - Android: Is not handled by this if case (doesn't enter it). - iOS: Uses to the Container adaptor for now. TODO: Remove this special case once they've set their versions. */ // Check the version of the OmniContainer being used. // Mobile clients don't specify version, so default to undefined value if not found. var omniRegex = new RegExp(/GENBANDOmni\.(\d\.\d)/); var omniVersion = (_navigator.userAgent.match(omniRegex) || []).pop(); // Version 1.1 and iOS require the Container Adaptor. if (omniVersion === '1.1' || typeof omniVersion === 'undefined') { type = NAVIGATOR_TYPES.CONTAINER; } else { // Other desktop versions should use the Chrome adaptor. type = NAVIGATOR_TYPES.CHROME; } } else if (_navigator.webkitGetUserMedia) { type = NAVIGATOR_TYPES.CHROME; regex = new RegExp(/\Chrome\/(\d*)/); } else if (_navigator.mozGetUserMedia) { type = NAVIGATOR_TYPES.FIREFOX; regex = new RegExp(/\Firefox\/(\d*)/); } else { type = NAVIGATOR_TYPES.PLUGIN; } if (regex && _navigator.userAgent) { version = parseInt(_navigator.userAgent.match(regex).pop(), 10); } logger.debug('Navigator type determined to be ' + type); return { type: type, version: version }; } function identifyPluginMode(options) { var i; if (!options || !options.pluginMode) { return PLUGIN_MODES.AUTO; } for (i in PLUGIN_MODES) { if (PLUGIN_MODES[i] === options.pluginMode) { return PLUGIN_MODES[i]; } } return PLUGIN_MODES.AUTO; } function getPluginModeForComposition(navigatorType) { var pluginMode = PLUGIN_MODES.AUTO, validPluginMode = false, h264Enabled, pluginModeBrowser = _config.pluginMode[navigatorType.type], pluginModeBrowserVersion, browserVersion, i, regex; if (pluginModeBrowser) { regex = new RegExp(/^\d+\+$/); if (pluginModeBrowser.version && regex.test(pluginModeBrowser.version)) { pluginModeBrowserVersion = parseInt(pluginModeBrowser.version.replace(/\+/, ''), 10); } browserVersion = navigatorType.version; if (pluginModeBrowser.mode && (!pluginModeBrowserVersion || browserVersion >= pluginModeBrowserVersion)) { pluginMode = pluginModeBrowser.mode; } else if (_config.pluginMode.mode) { pluginMode = _config.pluginMode.mode; } if (typeof pluginModeBrowser.h264 !== 'undefined' && (!pluginModeBrowserVersion || browserVersion >= pluginModeBrowserVersion)) { h264Enabled = pluginModeBrowser.h264; } else { h264Enabled = _config.pluginMode.h264; } } else { pluginMode = _config.pluginMode.mode; h264Enabled = _config.pluginMode.h264; } // plugin mode validity check for (i in COMPOSIT_PLUGIN_MODES) { if (COMPOSIT_PLUGIN_MODES[i] === pluginMode) { validPluginMode = true; } } if (!validPluginMode) { pluginMode = PLUGIN_MODES.AUTO; } // h264 validity check if (h264Enabled !== true && h264Enabled !== false) { h264Enabled = undefined; } return { pluginMode: pluginMode, h264Enabled: h264Enabled }; } function getPluginMode(options, navigatorType) { var pluginMode = identifyPluginMode(options); return PLUGIN_MODE_LOOKUP_TABLE[navigatorType.type][pluginMode] || pluginMode; } this.getWebRtcAdaptor = function (options) { var adaptorFactory, navigatorType = getNavigatorType(), adaptor, pluginModeAndH264Bundle, h264Enabled; if (_config.pluginMode) { pluginModeAndH264Bundle = getPluginModeForComposition(navigatorType); pluginMode = pluginModeAndH264Bundle.pluginMode; h264Enabled = pluginModeAndH264Bundle.h264Enabled; if (pluginMode === 'auto' && navigatorType.type === 'firefox' && navigatorType.version < 40) { pluginMode = 'autoesr'; } adaptorFactory = COMPOSIT_ADAPTOR_LOOKUP_TABLE[navigatorType.type][pluginMode]; } else { pluginMode = getPluginMode(options, navigatorType); if (pluginMode === 'auto' && navigatorType.type === 'firefox' && navigatorType.version < 40) { pluginMode = 'autoesr'; } adaptorFactory = ADAPTOR_LOOKUP_TABLE[navigatorType.type][pluginMode]; } if (!adaptorFactory) { // This seems unnecessary, still keeping it just in case of a weird // condition logger.debug('Invalid Plugin Mode Detected, Treated as WEBRTC'); pluginMode = DEFAULT_RTC_PLUGIN_MODE; adaptorFactory = DEFAULT_RTC_ADAPTOR; } if (navigatorType.type === 'firefox' && (pluginMode === PLUGIN_MODES.WEBRTCH264 || pluginMode === PLUGIN_MODES.WEBRTC22 || pluginMode === PLUGIN_MODES.WEBRTC)) { logger.error('Plugins for firefox are no longer supported.'); } logger.debug('Adaptor initializing from ' + navigatorType + ' browser and ' + pluginMode + ' plugIn mode'); adaptor = adaptorFactory(); //TODO: set h264Enabled for adaptor if (typeof h264Enabled !== 'undefined') { adaptor.setH264Enabled(h264Enabled); } return adaptor; }; // Used for tests. this.getLastPluginMode = function () { return pluginMode; }; this.getPluginModes = function () { return PLUGIN_MODES; }; this.getDefaultRtcPluginMode = function () { return DEFAULT_RTC_PLUGIN_MODE; }; this.getDefaultRtcAdaptor = function () { return DEFAULT_RTC_ADAPTOR; }; //@{test-methods} this.getNavigatorType = getNavigatorType; //@{test-methods} } /***/ }), /***/ "../fcs/src/js/webrtc/webRtcManager.js": /*!*********************************************!*\ !*** ../fcs/src/js/webrtc/webRtcManager.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.WebRtcManager = WebRtcManager; var _constants = __webpack_require__(/*! ../constants */ "../fcs/src/js/constants.js"); var _constants2 = _interopRequireDefault(_constants); var _call = __webpack_require__(/*! ../call/call */ "../fcs/src/js/call/call.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function WebRtcManager(_ref) { var _webRtcAdaptorFactory = _ref.WebRtcAdaptorFactory, _logManager = _ref.LogManager, _turnCredentialsManager = _ref.TurnCredentialsManager, _navigator = _ref.Navigator, _utils = _ref.Utils, _globalBroadcaster = _ref.GlobalBroadcaster; var self = this, rtcAdaptor, logger = _logManager.getLogger('WebRtcManager'); function setSuccessCallbacktoCall(call, successCallback) { call.successCallback = successCallback; } function clearSuccessParametersFromCall(call) { call.successCallback = null; } self.onCredentialsReceived = function () { if (rtcAdaptor) { rtcAdaptor.setIceServerUrl(self.addTurnCredentialsToUrl()); } }; _turnCredentialsManager.onCredentialsReceived = self.onCredentialsReceived; self.addTurnCredentialsToUrl = function () { var i, serverType, iceServerUrl = rtcAdaptor.getIceServerUrl(), turnCredentials = _turnCredentialsManager.get(); if (turnCredentials) { logger.info('Turn credentials are avaliable.'); if (iceServerUrl instanceof Array) { for (i = 0; i < iceServerUrl.length; i++) { serverType = iceServerUrl[i].urls.substring(0, iceServerUrl[i].urls.indexOf(':')); if (serverType === 'turn' || serverType === 'turns') { iceServerUrl[i].credential = turnCredentials.credential; iceServerUrl[i].username = turnCredentials.username; } } } } return iceServerUrl; }; self.canOriginatorSendLocalVideo = function (call) { return rtcAdaptor.canOriginatorSendLocalVideo(call); }; self.canOriginatorReceiveRemoteVideo = function (call) { return rtcAdaptor.canOriginatorReceiveRemoteVideo(call); }; self.onFcsSetupCompleted = function (fcsConfig) { logger.debug('FCS Config updated: ' + (0, _stringify2.default)(fcsConfig)); self.initMedia(null, null, fcsConfig); }; self.initMedia = function (onSuccess, onFailure, options) { logger.info('Initializing media for call'); if (!rtcAdaptor) { rtcAdaptor = _webRtcAdaptorFactory.getWebRtcAdaptor(options); } if (options) { if (options.iceserver) { // RTCIceServer.url is deprecated; should use .urls instead. // Update the passed-in options for backwards compatibility. for (var i = 0; i < options.iceserver.length; i++) { if (options.iceserver[i].url) { options.iceserver[i].urls = options.iceserver[i].url; delete options.iceserver[i].url; } } // Adding raw iceserver config to adaptor // to make addTurnCredentialsToUrl method work properly rtcAdaptor.setIceServerUrl(options.iceserver); rtcAdaptor.setIceServerUrl(self.addTurnCredentialsToUrl(options.iceserver)); } if (options.webrtcdtls !== undefined) { rtcAdaptor.setDtlsEnabled(options.webrtcdtls); } if (options.dscpEnabled !== undefined) { rtcAdaptor.setDscpEnabled(options.dscpEnabled); } if (options.localVideoContainer) { rtcAdaptor.setLocalVideoContainer(options.localVideoContainer); } if (options.remoteVideoContainer) { rtcAdaptor.setRemoteVideoContainer(options.remoteVideoContainer); } if (options.videoContainer) { rtcAdaptor.setDefaultVideoContainer(options.videoContainer); } } if (rtcAdaptor.isInitialized()) { _utils.callFunctionIfExist(onSuccess); } else { rtcAdaptor.initMedia(onSuccess, onFailure, options); } }; self.privateGetUserMedia = function (onSuccess, onFailure, data) { var audioConstraints = rtcAdaptor.prepareAudioConstraints(), videoConstraints = rtcAdaptor.prepareVideoConstraints({ isVideoEnabled: true }), returnParams = { onSuccess: onSuccess, onFailure: onFailure }; if (data.options) { if (data.options.audio !== undefined) { audioConstraints = data.options.audio; } if (data.options.video !== undefined) { videoConstraints = data.options.video; } } if (!audioConstraints && !videoConstraints) { _utils.callFunctionIfExist(onFailure, _call.mediaErrors.INVALID_PARAMETER); return; } returnParams.options = { audioConstraints: audioConstraints, videoConstraints: videoConstraints, privateStream: data.privateStream }; rtcAdaptor.privateGetUserMedia(returnParams); }; self.getWebRtcStats = function (call, onSuccess, onFailure) { rtcAdaptor.getWebRtcStats(call, onSuccess, onFailure); }; self.getNativeWebRtcStats = function (call, onSuccess, onFailure) { rtcAdaptor.getNativeWebRtcStats(call, onSuccess, onFailure); }; self.startWebRtcStatsTimer = function (call, interval, onSuccess, onFailure) { self.stopWebRtcStatsTimer(call); call.statsTimer = setInterval(function () { rtcAdaptor.getWebRtcStats(call, onSuccess, onFailure); }, interval); }; self.stopWebRtcStatsTimer = function (call) { if (call.statsTimer) { clearInterval(call.statsTimer); call.statsTimer = undefined; } }; self.canMergeAudio = function () { if (rtcAdaptor) { return rtcAdaptor.mergeAudioStream; } else { logger.debug('Media not initiliazed yet.'); return false; } }; self.mergeAudioStream = function (call1, call2) { rtcAdaptor.mergeAudioStream(call1, call2); }; self.unMergeAudioStream = function (call1, call2) { rtcAdaptor.unMergeAudioStream(call1, call2); }; self.getUserMedia = function (onSuccess, onFailure, options) { var audioConstraints = rtcAdaptor.prepareAudioConstraints(options), videoConstraints = rtcAdaptor.prepareVideoConstraints(options), returnParams = { onSuccess: onSuccess, onFailure: onFailure }; if (!audioConstraints && !videoConstraints) { //no need to reach the adaptor if we are not asking for audio or video onSuccess({ video: false, audio: false }); return; } returnParams.options = { audioConstraints: audioConstraints, videoConstraints: videoConstraints }; logger.info('getting user media - userAgent: ' + _navigator.userAgent + ' constraints: ' + (0, _stringify2.default)({ audio: audioConstraints, video: videoConstraints })); rtcAdaptor.getUserMedia(returnParams); }; /* * Forward the function call to the rtcAdaptor. */ self.changeSpeaker = function (speakerId, onSuccess, onFailure) { // If media has not been initialized yet, rtcAdaptor will be undefined. if (rtcAdaptor) { rtcAdaptor.setContainerSinkId(speakerId, onSuccess, onFailure); } else { _utils.callFunctionIfExist(onFailure, 'Media not initialized.'); } }; self.startScreenMedia = function (onSuccess, onFailure, options, onEnded) { logger.info('getting screen media for call: started - userAgent: ' + _navigator.userAgent); if (options) { if (options.width) { rtcAdaptor.setScreenWidth(options.width); } if (options.height) { rtcAdaptor.setScreenHeight(options.height); } if (options.frameRate) { rtcAdaptor.setScreenFrameRate(options.frameRate); } if (options.mediaSourceId) { rtcAdaptor.setMediaSourceId(options.mediaSourceId); } } rtcAdaptor.startScreenMedia(onSuccess, onFailure, onEnded); }; self.stopScreenMedia = function () { // If media source id was set via options, unset it. if (rtcAdaptor.getMediaSourceId()) { rtcAdaptor.setMediaSourceId(''); } rtcAdaptor.stopScreenMedia(); }; self.createDataChannelOffer = function (dataChannelWrapperObj, successCallback, failureCallback) { var successCallbackWrapper = function successCallbackWrapper(sdp) { clearSuccessParametersFromCall(dataChannelWrapperObj); _utils.callFunctionIfExist(successCallback, sdp); }; setSuccessCallbacktoCall(dataChannelWrapperObj, successCallbackWrapper); if (rtcAdaptor.createPeer(dataChannelWrapperObj)) { rtcAdaptor.createDataChannel(dataChannelWrapperObj, function createDataChannelSuccessCallback() { rtcAdaptor.createDataChannelOffer(dataChannelWrapperObj, successCallbackWrapper, function createOfferFailureCallback(error) { clearSuccessParametersFromCall(dataChannelWrapperObj); _utils.callFunctionIfExist(failureCallback, error); }); }, function createDataChannelFailureCallback(error) { _utils.callFunctionIfExist(failureCallback, error); }); } else { _utils.callFunctionIfExist(failureCallback); } }; self.createDataChannelAnswer = function (dataChannelWrapperObj, successCallback, failureCallback) { var successCallbackWrapper = function successCallbackWrapper(sdp) { clearSuccessParametersFromCall(dataChannelWrapperObj); _utils.callFunctionIfExist(successCallback, sdp); }; setSuccessCallbacktoCall(dataChannelWrapperObj, successCallbackWrapper); if (rtcAdaptor.createPeer(dataChannelWrapperObj)) { rtcAdaptor.createDataChannelAnswer(dataChannelWrapperObj, successCallbackWrapper, function createDataChannelAnswerFailureCallback(error) { clearSuccessParametersFromCall(dataChannelWrapperObj); _utils.callFunctionIfExist(failureCallback, error); }); } else { _utils.callFunctionIfExist(failureCallback); } }; self.createOffer = function (call, successCallback, failureCallback, sendInitialVideo, offerToReceiveVideo, isAnswer) { logger.info('create offer SDP: sendInitialVideo= ' + sendInitialVideo); var successCallbackWrapper = function successCallbackWrapper(sdp) { clearSuccessParametersFromCall(call); call.initialVideoState = sendInitialVideo; rtcAdaptor.setDTLSRole(call, 'actpass'); call.lastLocalSdp = sdp; rtcAdaptor.restoreMuteStateOfCall(call); rtcAdaptor.setOriginatorSendLocalVideo(call, sdp, sendInitialVideo); if (typeof successCallback === 'function') { successCallback(sdp); } }; setSuccessCallbacktoCall(call, successCallbackWrapper); if (!call.peer) { if (rtcAdaptor.createPeer(call)) { rtcAdaptor.createOffer(call, successCallbackWrapper, function (err) { clearSuccessParametersFromCall(call); if (typeof failureCallback === 'function') { failureCallback(err); } }, sendInitialVideo, offerToReceiveVideo, isAnswer); } else { _utils.callFunctionIfExist(failureCallback, 2); } } }; self.createAnswer = function (call, successCallback, failureCallback, sendInitialVideo) { logger.info('creating answer SDP: callid= ' + call.id); logger.info('creating answer SDP: sendInitialVideo= ' + sendInitialVideo); var successCallbackWrapper = function successCallbackWrapper(sdp) { clearSuccessParametersFromCall(call); call.initialVideoState = sendInitialVideo; call.stableLocalSdp = sdp; rtcAdaptor.setOriginatorSendLocalVideo(call, sdp, sendInitialVideo); rtcAdaptor.setOriginatorReceiveRemoteVideo(call); rtcAdaptor.setDTLSRoleFromStableLocalSDP(call); if (typeof successCallback === 'function') { successCallback(sdp); } }; setSuccessCallbacktoCall(call, successCallbackWrapper); rtcAdaptor.addCallIdInPluginContainer(call); if (!call.peer) { if (rtcAdaptor.createPeer(call)) { rtcAdaptor.createAnswer(call, successCallbackWrapper, function (err) { clearSuccessParametersFromCall(call); if (typeof failureCallback === 'function') { failureCallback(err); } }, sendInitialVideo); } else { _utils.callFunctionIfExist(failureCallback, 2); } } }; self.processDataChannelAnswer = function (call, successCallback, failureCallback) { if (call.peer) { var successCallbackWrapper = function successCallbackWrapper() { clearSuccessParametersFromCall(call); if (typeof successCallback === 'function') { successCallback(); } }; setSuccessCallbacktoCall(call, successCallbackWrapper); rtcAdaptor.processDataChannelAnswer(call, successCallbackWrapper, function (err) { clearSuccessParametersFromCall(call); if (typeof failureCallback === 'function') { failureCallback(err); } }); } }; self.processAnswer = function (call, successCallback, failureCallback, isAnswer) { if (call.peer) { var successCallbackWrapper = function successCallbackWrapper() { clearSuccessParametersFromCall(call); call.stableLocalSdp = call.lastLocalSdp; rtcAdaptor.restoreMuteStateOfCall(call); rtcAdaptor.setOriginatorReceiveRemoteVideo(call); if (typeof successCallback === 'function') { successCallback(); } }; setSuccessCallbacktoCall(call, successCallbackWrapper); rtcAdaptor.handleDTLSRoleFromRemoteSDP(call); rtcAdaptor.addCallIdInPluginContainer(call); rtcAdaptor.processAnswer(call, successCallbackWrapper, function (err) { clearSuccessParametersFromCall(call); if (typeof failureCallback === 'function') { failureCallback(err); } }, isAnswer); } }; self.processRespond = function (call, successCallback, failureCallback, isJoin) { if (call.peer) { var successCallbackWrapper = function successCallbackWrapper() { clearSuccessParametersFromCall(call); call.stableLocalSdp = call.lastLocalSdp; rtcAdaptor.setOriginatorReceiveRemoteVideo(call); if (typeof successCallback === 'function') { successCallback(); } }; setSuccessCallbacktoCall(call, successCallbackWrapper); rtcAdaptor.handleDTLSRoleFromRemoteSDP(call); rtcAdaptor.addCallIdInPluginContainer(call); rtcAdaptor.processRespond(call, successCallbackWrapper, function (err) { clearSuccessParametersFromCall(call); if (typeof failureCallback === 'function') { failureCallback(err); } }, isJoin); } }; self.createUpdate = function (call, successCallback, failureCallback, isVideoStart) { logger.info('createUpdate: isVideoStart= ' + isVideoStart); if (call.peer) { var successCallbackWrapper = function successCallbackWrapper(sdp) { clearSuccessParametersFromCall(call); call.lastLocalSdp = sdp; rtcAdaptor.muteVideoTrack(call, !isVideoStart, true); rtcAdaptor.setOriginatorSendLocalVideo(call, sdp, isVideoStart); if (typeof successCallback === 'function') { successCallback(sdp); } }; setSuccessCallbacktoCall(call, successCallbackWrapper); rtcAdaptor.createUpdate(call, successCallbackWrapper, failureCallback, isVideoStart); } }; self.processUpdate = function (call, successCallback, failureCallback, local_hold_status) { logger.info('processUpdate: local_hold_status:' + local_hold_status); if (call.peer) { var successCallbackWrapper = function successCallbackWrapper(sdp) { clearSuccessParametersFromCall(call); call.stableLocalSdp = sdp; rtcAdaptor.restoreMuteStateOfCall(call); rtcAdaptor.setOriginatorReceiveRemoteVideo(call); if (typeof successCallback === 'function') { successCallback(sdp); } }; setSuccessCallbacktoCall(call, successCallbackWrapper); rtcAdaptor.addCallIdInPluginContainer(call); rtcAdaptor.processUpdate(call, successCallbackWrapper, function (err) { clearSuccessParametersFromCall(call); if (typeof failureCallback === 'function') { failureCallback(err); } }, local_hold_status); } }; self.createReOffer = function (call, successCallback, failureCallback, usePreviousMediaDirection) { if (call.peer) { var successCallbackWrapper = function successCallbackWrapper(sdp) { clearSuccessParametersFromCall(call); call.lastLocalSdp = sdp; rtcAdaptor.restoreMuteStateOfCall(call); rtcAdaptor.setDTLSRole(call, 'actpass'); if (typeof successCallback === 'function') { successCallback(sdp); } }; setSuccessCallbacktoCall(call, successCallbackWrapper); rtcAdaptor.createReOffer(call, successCallbackWrapper, function (err) { clearSuccessParametersFromCall(call); if (typeof failureCallback === 'function') { failureCallback(err); } }, usePreviousMediaDirection); } }; self.createHoldUpdate = function (call, hold, remote_hold_status, successCallback, failureCallback) { logger.info('create hold update local hold= ' + hold + ' remote hold= ' + remote_hold_status); if (call.peer) { var successCallbackWrapper = function successCallbackWrapper(sdp) { clearSuccessParametersFromCall(call); call.lastLocalSdp = sdp; if (hold || remote_hold_status) { rtcAdaptor.muteOnHold(call, true); } else { rtcAdaptor.restoreMuteStateOfCall(call); } if (typeof successCallback === 'function') { successCallback(sdp); } }; setSuccessCallbacktoCall(call, successCallbackWrapper); rtcAdaptor.createHoldUpdate(call, hold, remote_hold_status, successCallbackWrapper, function (err) { clearSuccessParametersFromCall(call); if (typeof failureCallback === 'function') { failureCallback(err); } }); } }; self.processRemoteOfferOnLocalHold = function (call, successCallback, failureCallback) { if (call.peer) { var successCallbackWrapper = function successCallbackWrapper(sdp) { clearSuccessParametersFromCall(call); rtcAdaptor.restoreMuteStateOfCall(call); if (typeof successCallback === 'function') { successCallback(sdp); } }; setSuccessCallbacktoCall(call, successCallbackWrapper); rtcAdaptor.processRemoteOfferOnLocalHold(call, successCallbackWrapper, function (err) { clearSuccessParametersFromCall(call); if (typeof failureCallback === 'function') { failureCallback(err); } }); } }; self.processEnd = function (call) { if (call.peer) { rtcAdaptor.processEnd(call); } }; self.processHold = function (call, hold, local_hold_status, successCallback, failureCallback) { logger.info('processHold: local hold= ' + local_hold_status + ' remote hold= ' + hold); if (call.peer) { var successCallbackWrapper = function successCallbackWrapper(sdp) { clearSuccessParametersFromCall(call); call.stableLocalSdp = sdp; if (!local_hold_status && !hold) { rtcAdaptor.restoreMuteStateOfCall(call); rtcAdaptor.setOriginatorSendLocalVideo(call, sdp, true); } if (!call.call.isVideoNegotiationAvailable()) { rtcAdaptor.muteVideoTrack(call, true, true); rtcAdaptor.setOriginatorSendLocalVideo(call, sdp, false); } rtcAdaptor.setOriginatorReceiveRemoteVideo(call); if (typeof successCallback === 'function') { successCallback(sdp); } }; rtcAdaptor.handleDTLSRoleFromRemoteSDP(call); setSuccessCallbacktoCall(call, successCallbackWrapper); rtcAdaptor.addCallIdInPluginContainer(call); rtcAdaptor.processHold(call, hold, local_hold_status, successCallbackWrapper, function (err) { clearSuccessParametersFromCall(call); if (typeof failureCallback === 'function') { failureCallback(err); } }); } }; self.processHoldRespond = function (call, successCallback, failureCallback, isJoin) { logger.info('Processing response to hold offer sent'); if (call.peer) { var successCallbackWrapper = function successCallbackWrapper() { clearSuccessParametersFromCall(call); call.stableLocalSdp = call.lastLocalSdp; rtcAdaptor.setOriginatorReceiveRemoteVideo(call); if (typeof successCallback === 'function') { successCallback(); } }; setSuccessCallbacktoCall(call, successCallbackWrapper); rtcAdaptor.handleDTLSRoleFromRemoteSDP(call); rtcAdaptor.addCallIdInPluginContainer(call); rtcAdaptor.processHoldRespond(call, successCallbackWrapper, function (err) { clearSuccessParametersFromCall(call); if (typeof failureCallback === 'function') { failureCallback(err); } }, isJoin); } }; self.processPreAnswer = function (call, successCallback, failureCallback) { logger.info('processing preanswer from the offer we sent'); if (call.peer) { rtcAdaptor.processPreAnswer(call, function () { if (typeof successCallback === 'function') { successCallback(); } }, function (err) { if (typeof failureCallback === 'function') { failureCallback(err); } }); } }; self.isDtlsEnabled = function () { return rtcAdaptor.isDtlsEnabled(); }; self.revertRtcState = function (call, successCallback, failureCallback) { // The adapter doesn't pass the call along whenever calling the callback. We bind to it // here to ensure we get the proper callback parameter. var successCallbackWrapper = successCallback && successCallback.bind(undefined, call); clearSuccessParametersFromCall(call); rtcAdaptor.revertRtcState(call, successCallbackWrapper, failureCallback); }; self.getRemoteVideoResolutions = function () { return rtcAdaptor.getRemoteVideoResolutions(); }; self.getLocalVideoResolutions = function () { return rtcAdaptor.getLocalVideoResolutions(); }; self.isAudioSourceAvailable = function () { return rtcAdaptor.getAudioSourceAvailable(); }; self.isVideoSourceAvailable = function () { return rtcAdaptor.getVideoSourceAvailable(); }; self.refreshVideoRenderer = function () { rtcAdaptor.refreshVideoRenderer(); }; self.sendIntraFrame = function (internalCall) { rtcAdaptor.sendIntraFrame(internalCall); }; self.sendBlackFrame = function (internalCall) { rtcAdaptor.sendBlackFrame(internalCall); }; self.muteAudioTrack = function (call, mute) { return rtcAdaptor.muteAudioTrack(call, mute, true); }; self.isAudioMuted = function (call) { return rtcAdaptor.isAudioMuted(call); }; self.addLocalStream = function (call) { rtcAdaptor.addLocalStream(call); }; self.isPluginEnabled = function () { return rtcAdaptor.isPluginEnabled(); }; self.sendDTMF = function (call, tone) { rtcAdaptor.sendDTMF(call, tone); }; self.showSettingsWindow = function () { rtcAdaptor.showSettingsWindow(); }; self.createStreamRenderer = function (streamId, container, options) { return rtcAdaptor.createStreamRenderer(streamId, container, options); }; self.disposeStreamRenderer = function (container) { rtcAdaptor.disposeStreamRenderer(container); }; self.set_logSeverityLevel = function (level) { rtcAdaptor.set_logSeverityLevel(level); }; self.enable_logCallback = function () { rtcAdaptor.enable_logCallback(); }; self.disable_logCallback = function () { rtcAdaptor.disable_logCallback(); }; self.get_audioInDeviceCount = function () { return rtcAdaptor.get_audioInDeviceCount(); }; self.get_audioOutDeviceCount = function () { return rtcAdaptor.get_audioOutDeviceCount(); }; self.get_videoDeviceCount = function () { return rtcAdaptor.get_videoDeviceCount(); }; self.storeLocalStreamToCall = function (call, localStreamId) { rtcAdaptor.storeLocalStreamToCall(call, localStreamId); }; self.updateLocalStreamToCall = function (call, localStreamId) { rtcAdaptor.updateLocalStreamToCall(call, localStreamId); }; self.deleteLocalStream = function (call) { rtcAdaptor.endLocalMedia(call.localMedia); }; self.getStreamById = function (id) { return rtcAdaptor.getStreamById(id); }; self.removeStreamById = function (id) { rtcAdaptor.removeStreamById(id); }; self.setSelectedMicrophoneId = function (_selectedMicrophoneId) { rtcAdaptor.setSelectedMicrophoneId(_selectedMicrophoneId); }; self.setSelectedSpeakerId = function (_selectedSpeakerId, onSuccess, onFailure) { // If media has not been initialized yet, rtcAdaptor will be undefined. if (rtcAdaptor) { rtcAdaptor.setSelectedSpeakerId(_selectedSpeakerId); _utils.callFunctionIfExist(onSuccess); } else { _utils.callFunctionIfExist(onFailure, 'Media not initialized.'); } }; self.setSelectedCameraId = function (_selectedCameraId) { rtcAdaptor.setSelectedCameraId(_selectedCameraId); }; self.getCameraList = function (onSuccess) { rtcAdaptor.getCameraList(function (cameraList) { _utils.callFunctionIfExist(onSuccess, cameraList); }); }; self.getMicrophoneList = function (onSuccess) { rtcAdaptor.getMicrophoneList(function (microphoneList) { _utils.callFunctionIfExist(onSuccess, microphoneList); }); }; self.getSpeakerList = function (onSuccess) { rtcAdaptor.getSpeakerList(function (speakerList) { _utils.callFunctionIfExist(onSuccess, speakerList); }); }; self.addRemoteCandidates = function (call, candidateArray) { rtcAdaptor.addRemoteCandidates(call, candidateArray); }; _globalBroadcaster.subscribe(_constants2.default.EVENT.FCS_SETUP_COMPLETED, self.onFcsSetupCompleted); //@{test-methods} self.setRtcLibrary = function (_rtcLibrary) { rtcAdaptor = _rtcLibrary; }; //@{test-methods} } /***/ }), /***/ "../fcs/src/lib/base64.js": /*!********************************!*\ !*** ../fcs/src/lib/base64.js ***! \********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.base64_encode = base64_encode; exports.base64_decode = base64_decode; // Base64 by Kevin van Zonneveld - Public Domain // Original Source: http://kevin.vanzonneveld.net/ function base64_encode(data) { // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Bayron Guevara // + improved by: Thunder.m // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // - depends on: utf8_encode // * example 1: base64_encode('Kevin van Zonneveld'); // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' // mozilla has this native // - but breaks in 2.0.0.12! //if (typeof this.window['atob'] == 'function') { // return atob(data); //} var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc = '', tmp_arr = []; if (!data) { return data; } data = utf8_encode(data + ''); do { // pack three octets into four hexets o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1 << 16 | o2 << 8 | o3; h1 = bits >> 18 & 0x3f; h2 = bits >> 12 & 0x3f; h3 = bits >> 6 & 0x3f; h4 = bits & 0x3f; // use hexets to index into b64, and append result to encoded string tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); enc = tmp_arr.join(''); switch (data.length % 3) { case 1: enc = enc.slice(0, -2) + '=='; break; case 2: enc = enc.slice(0, -1) + '='; break; } return enc; } function base64_decode(data) { // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Thunder.m // + input by: Aman Gupta // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // - depends on: utf8_decode // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA=='); // * returns 1: 'Kevin van Zonneveld' // mozilla has this native // - but breaks in 2.0.0.12! //if (typeof this.window['btoa'] == 'function') { // return btoa(data); //} var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = '', tmp_arr = []; if (!data) { return data; } data += ''; do { // unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 === 64) { tmp_arr[ac++] = String.fromCharCode(o1); } else if (h4 === 64) { tmp_arr[ac++] = String.fromCharCode(o1, o2); } else { tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i < data.length); dec = tmp_arr.join(''); dec = utf8_decode(dec); return dec; } function utf8_encode(argString) { // http://kevin.vanzonneveld.net // + original by: Webtoolkit.info (http://www.webtoolkit.info/) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: sowberry // + tweaked by: Jack // + bugfixed by: Onno Marsman // + improved by: Yves Sucaet // + bugfixed by: Onno Marsman // + bugfixed by: Ulrich // * example 1: utf8_encode('Kevin van Zonneveld'); // * returns 1: 'Kevin van Zonneveld' var string = argString + ''; // .replace(/\r\n/g, "\n").replace(/\r/g, "\n"); var utftext = ''; var start, end; var stringl = 0; start = end = 0; stringl = string.length; for (var n = 0; n < stringl; n++) { var c1 = string.charCodeAt(n); var enc = null; if (c1 < 128) { end++; } else if (c1 > 127 && c1 < 2048) { enc = String.fromCharCode(c1 >> 6 | 192) + String.fromCharCode(c1 & 63 | 128); } else { enc = String.fromCharCode(c1 >> 12 | 224) + String.fromCharCode(c1 >> 6 & 63 | 128) + String.fromCharCode(c1 & 63 | 128); } if (enc !== null) { if (end > start) { utftext += string.substring(start, end); } utftext += enc; start = end = n + 1; } } if (end > start) { utftext += string.substring(start, string.length); } return utftext; } function utf8_decode(str_data) { // http://kevin.vanzonneveld.net // + original by: Webtoolkit.info (http://www.webtoolkit.info/) // + input by: Aman Gupta // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Norman "zEh" Fuchs // + bugfixed by: hitwork // + bugfixed by: Onno Marsman // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: utf8_decode('Kevin van Zonneveld'); // * returns 1: 'Kevin van Zonneveld' var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0; str_data += ''; while (i < str_data.length) { c1 = str_data.charCodeAt(i); if (c1 < 128) { tmp_arr[ac++] = String.fromCharCode(c1); i++; } else if (c1 > 191 && c1 < 224) { c2 = str_data.charCodeAt(i + 1); tmp_arr[ac++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63); i += 2; } else { c2 = str_data.charCodeAt(i + 1); c3 = str_data.charCodeAt(i + 2); tmp_arr[ac++] = String.fromCharCode((c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63); i += 3; } } return tmp_arr.join(''); } /***/ }), /***/ "../fcs/src/loadModule.js": /*!********************************!*\ !*** ../fcs/src/loadModule.js ***! \********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = loadModule; /** * Mixin function for loading a module into a factory container. The function expects 'this' to be bound * to the container that supports an interface like so: * ``` * { * factory: (name: string, factoryFunction: (container) => any) => void * defer: ((data: any) => any) => void * } * ``` * * @param {Object} module An where the keys are the name of services, and the values are factory functions. Also supports * a special key `$defer` that allows registering deffered functions. */ function loadModule(module) { for (var service in module) { if (module.hasOwnProperty(service)) { if (service === '$init') { this.defer(module[service]); } else { this.factory(service, module[service]); } } } return this; } /***/ }), /***/ "./src/auth/constants.js": /*!*******************************!*\ !*** ./src/auth/constants.js ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Possible subscription states. * @type {Object} */ var SUBSCRIPTION_STATE = exports.SUBSCRIPTION_STATE = { FULL: 'FULL', PARTIAL: 'PARTIAL', NONE: 'NONE' }; /***/ }), /***/ "./src/auth/interface/actionTypes.js": /*!*******************************************!*\ !*** ./src/auth/interface/actionTypes.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var prefix = '@@KANDY/'; var CONNECT = exports.CONNECT = prefix + 'CONNECT'; var CONNECTION_OCCURRED = exports.CONNECTION_OCCURRED = prefix + 'CONNECTION_OCCURRED'; var CONNECT_FINISHED = exports.CONNECT_FINISHED = prefix + 'CONNECT_FINISHED'; var GET_USER_DETAILS = exports.GET_USER_DETAILS = prefix + 'GET_USER_DETAILS'; var USER_DETAILS_RECEIVED = exports.USER_DETAILS_RECEIVED = prefix + 'USER_DETAILS_RECEIVED'; var DISCONNECT = exports.DISCONNECT = prefix + 'DISCONNECT'; var DISCONNECT_FINISHED = exports.DISCONNECT_FINISHED = prefix + 'DISCONNECT_FINISHED'; var RESUBSCRIPTION_FINISHED = exports.RESUBSCRIPTION_FINISHED = prefix + 'RESUBSCRIPTION_FINISHED'; var REFRESH_TOKENS = exports.REFRESH_TOKENS = prefix + 'REFRESH_TOKENS'; var REFRESH_TOKENS_FINISHED = exports.REFRESH_TOKENS_FINISHED = prefix + 'REFRESH_TOKENS_FINISHED'; var UPDATE_SUBSCRIPTION = exports.UPDATE_SUBSCRIPTION = prefix + 'UPDATE_SUBSCRIPTION'; var UPDATE_SUBSCRIPTION_FINISH = exports.UPDATE_SUBSCRIPTION_FINISH = prefix + 'UPDATE_SUBSCRIPTION_FINISH'; var SET_TOKEN = exports.SET_TOKEN = prefix + 'SET_TOKEN'; /***/ }), /***/ "./src/auth/interface/actions.js": /*!***************************************!*\ !*** ./src/auth/interface/actions.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.connect = connect; exports.connectionOccured = connectionOccured; exports.connectFinished = connectFinished; exports.getUserDetails = getUserDetails; exports.userDetailsReceived = userDetailsReceived; exports.disconnect = disconnect; exports.disconnectFinished = disconnectFinished; exports.resubscribeFinished = resubscribeFinished; exports.refreshTokens = refreshTokens; exports.refreshTokensFinished = refreshTokensFinished; exports.updateSubscription = updateSubscription; exports.updateSubscriptionFinished = updateSubscriptionFinished; exports.setToken = setToken; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/auth/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Creates a connect action that takes a credentials object. * * @method connect * @param {Object} credentials The credentials to pass to the connect action. * @return {Object} A flux standard action. */ function connect(credentials) { return { type: actionTypes.CONNECT, payload: { credentials: credentials }, meta: { isSensitive: true } }; } /** * Connection Occured action. * Signifies that a connection has been made to a service, but that the connection * workflow has not finished yet. Intended for use in scenarios where the * workflow connects to multiple services, to represent the "intermediate" * connections. * * @method connectionOccured * @param {Object} $0 * @param {Object} $0.subscription * @param {Object} $0.connection * @param {Object} [$0.error] An error message. Only present if an error occured. * @param {string} platform The backend platform used for the connection. * @return {Object} A flux standard action. */ function connectionOccured(_ref, platform) { var subscription = _ref.subscription, connection = _ref.connection, error = _ref.error; var action = { type: actionTypes.CONNECTION_OCCURRED, meta: { platform: platform } }; if (error) { action.error = true; action.payload = error; } else { action.payload = { subscription: subscription, connection: connection }; } return action; } /** * Create a connect finished action that takes a userInfo object on success and possibly * an error object. * * @method connectFinished * @param {Object} $0 * @param {Object} $0.subscription A subscription object. Contains what services to subscribe to. * @param {Object} $0.userInfo An object representing the user information. * @param {Object} $0.connection A connection object. Tells Kandy where to connect and how. * @param {string} [$0.error] An error message. Only present if an error occured. * @param {string} platform The backend platform we are currently on. * @param {boolean} isSSO Boolean for whether the current connection scenario is SSO or not. * @return {Object} A flux standard action. */ function connectFinished(_ref2, platform) { var subscription = _ref2.subscription, userInfo = _ref2.userInfo, connection = _ref2.connection, error = _ref2.error; var isSSO = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var action = { type: actionTypes.CONNECT_FINISHED, meta: { platform: platform, isSSO: isSSO, isSensitive: true } }; if (error) { action.error = true; action.payload = error; } else { action.payload = { subscription: subscription, userInfo: userInfo, connection: connection }; } return action; } /** * Creates a getUserDetails action * * @method getUserDetails * @return {Object} A flux standard action. */ function getUserDetails() { return { type: actionTypes.GET_USER_DETAILS }; } /** * Create a user details received action * * @method userDetailsReceived * @param {Object} userDetailsResponse An object representing the REST response of a user details request. * @return {Object} A flux standard action. */ function userDetailsReceived(userDetailsResponse) { var action = { type: actionTypes.USER_DETAILS_RECEIVED, payload: { firstName: userDetailsResponse.firstName || userDetailsResponse.user_first_name, user_first_name: userDetailsResponse.user_first_name || userDetailsResponse.firstName, lastName: userDetailsResponse.lastName || userDetailsResponse.user_last_name, user_last_name: userDetailsResponse.user_last_name || userDetailsResponse.lastName, photoURL: userDetailsResponse.photoURL, emailAddress: userDetailsResponse.emailAddress || userDetailsResponse.user_email, user_email: userDetailsResponse.user_email || userDetailsResponse.emailAddress, username: userDetailsResponse.username } }; return action; } /** * Creates a disconnect action. * * @method disconnect * @return {Object} A flux standard action. */ function disconnect() { return { type: actionTypes.DISCONNECT }; } /** * Create a disconnectFinished action that possibly takes an error object on failure. * * @method disconnectFinished * @param {Object} $0 * @param {string} [$0.error] An error message. Only present if an error occurred. * @param {Boolean} [$0.forced] Whether the disconnect was forcefully disconnected. * @return {Object} A flux standard action. */ function disconnectFinished() { var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, error = _ref3.error, forced = _ref3.forced; var action = { type: actionTypes.DISCONNECT_FINISHED, payload: {} }; if (error) { action.error = true; action.payload = error; } action.payload.forced = forced; return action; } /** * Action creator representing the finish of a resubscription request. * Payload mirrors a connect finished action. * * @method resubscribeFinished * @param {Object} $0 * @param {string} [$0.error] An error message. Only present if an error occured. * @param {string} [$0.attemptNum] The attempt number of this resubscription. * @param {string} platform The backend platform we are currently on. * @return {Object} A flux standard action. */ function resubscribeFinished(_ref4, platform) { var error = _ref4.error, attemptNum = _ref4.attemptNum; var action = { type: actionTypes.RESUBSCRIPTION_FINISHED, meta: { platform: platform } }; if (error) { action.error = true; action.payload = error; action.payload.attemptNum = attemptNum; } else { action.payload = { attemptNum: attemptNum }; } return action; } /** * Creates a refreshTokens action with the given credentials as a payload. * * @method refreshTokens * @param {Object} credentials A crendetials object containing tokens. * @return {Object} A flux standard action. */ function refreshTokens(credentials) { var action = { type: actionTypes.REFRESH_TOKENS, payload: { credentials: credentials } }; return action; } /** * Creates a refreshTokensFinished action with connection and platform information. * Optionally includes an error. * * @method refreshTokensFinished * @param {Object} $0 * @param {Object} [$0.error] An optional error object. * @param {Object} $0.connection Connection information. * @param {string} platform The backend platform we are currently on. * @return {Object} A flux standard action. */ function refreshTokensFinished(_ref5, platform) { var error = _ref5.error, connection = _ref5.connection; var action = { type: actionTypes.REFRESH_TOKENS_FINISHED, payload: { connection: connection }, meta: { platform: platform } }; if (error) { action.error = true; action.payload = error; } return action; } /** * Represents a request to update a current subscription. * @method updateSubscription * @param {Object} subscription Information used to update subscription. * @return {Object} A flux standard action. */ function updateSubscription(subscription) { return { type: actionTypes.UPDATE_SUBSCRIPTION, payload: subscription }; } /** * Represents that the current subscription has been updated. * @method updateSubscriptionFinished * @param {Object} $0 * @param {Object} $0.subscription New subscription state to be updated. * @param {Object} [$0.error] Error object, in the case of an error. * @param {string} platform The backend platform used for the subscription. * @return {Object} A flux standard action. */ function updateSubscriptionFinished(_ref6, platform) { var subscription = _ref6.subscription, error = _ref6.error; var action = { type: actionTypes.UPDATE_SUBSCRIPTION_FINISH, meta: { platform: platform } }; if (error) { action.error = true; action.payload = error; } else { action.payload = subscription; } return action; } /** * Sets a token in state. * @method setToken * @param {Object} $0 * @param {string} $0.token A user access token. * @param {string} $0.username A full username. * @return {Object} A flux standard action. */ function setToken(_ref7) { var token = _ref7.token, username = _ref7.username; return { type: actionTypes.SET_TOKEN, payload: { token: token, username: username } }; } /***/ }), /***/ "./src/auth/interface/api.js": /*!***********************************!*\ !*** ./src/auth/interface/api.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = api; var _actions = __webpack_require__(/*! ./actions */ "./src/auth/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(/*! ./selectors */ "./src/auth/interface/selectors.js"); var _constants = __webpack_require__(/*! ../constants */ "./src/auth/constants.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Authentication API. * @method api * @param {Function} $0 * @param {Function} $0.dispatch - The redux store's dispatch function. * @param {Function} $0.getState - The redux store's getState function. * @return {Object} api - The authentication API object. */ function api(_ref) { var dispatch = _ref.dispatch, getState = _ref.getState; return { /** * Connect to Kandy with user credentials. * * @public * @memberof Authentication * @requires userCredentialsAuth * @method connect * @param {Object} credentials The credentials object. * @param {string} credentials.username The username including the application's domain. * @param {string} credentials.password The user's password. * @example * kandy.connect({ * username: 'alfred@example.kandy.io', * password: '********' * }); */ /** * Connect to Kandy with user credentials. * * @public * @memberof Authentication * @requires userCredentialsDAKAuth * @method connect * @param {Object} credentials The credentials object. * @param {string} credentials.domainApiKey The Api key for the application's domain. * @param {string} credentials.username The username without the application's domain. * @param {string} credentials.password The user's password. * @example * kandy.connect({ * domainApiKey: 'DAK1111111111111111111', * username: 'alfred', * password: '********' * }); */ /** * Connect to Kandy by providing an access token. You can optionally provide a refresh token and the SDK will automatically get new access tokens. * * @public * @memberof Authentication * @requires accessTokenAuth * @method connect * @param {Object} credentials The credentials object. * @param {string} credentials.username The username without the application's domain. * @param {string} credentials.accessToken An access token for the user with the provided user Id. * @param {string} [credentials.refreshToken] A refresh token for the same user. * @param {number} [credentials.expires] The time in seconds until the access token will expire. * @example * kandy.connect({ * username: 'alfred@example.kandy.io', * accessToken: 'AT0V1fswAiJadokx1iJMQdG04pRf', * refreshToken: 'RTG9SV3QAoJaeUSEQCZAHqrhde1yT', * expires: 3600 * }); */ /** * Connect to Kandy by providing a refresh token. * * @public * @memberof Authentication * @requires accessTokenAuth * @method connect * @param {Object} credentials The credentials object. * @param {string} credentials.username The username without the application's domain. * @param {string} credentials.refreshToken A refresh token for the same user. * @param {number} [credentials.expires] The time in seconds until the access token will expire. * @example * kandy.connect({ * username: 'alfred@example.kandy.io', * refreshToken: 'RTG9SV3QAoJaeUSEQCZAHqrhde1yT' * expires: 3600 * }); */ /** * Connect to Kandy by providing an OAuth token. * * @public * @memberof Authentication * @requires oauthToken * @method connect * @param {Object} credentials The credentials object. * @param {string} credentials.username The username without the application's domain. * @param {string} credentials.oauthToken An OAuth token provided by an outside service. * @example * kandy.connect({ * username: 'alfred@example.kandy.io', * oauthToken: 'RTG9SV3QAoJaeUSEQCZAHqrhde1yT' * }); */ connect: function connect(credentials) { dispatch(actions.connect(credentials)); }, /** * Disconnects from the backend. This will close the websocket and you will stop receiving events. * * @public * @requires userCredentialsAuth * @requires userCredentialsDAKAuth * @requires accessTokenAuth * @memberof Authentication * @method disconnect */ disconnect: function disconnect() { dispatch(actions.disconnect()); }, /** * If you're authenticating with tokens that expire and have not provided a refresh token to the `connect` function, you can update your access token with `updateToken` before it expires to stay connected. * * @public * @memberof Authentication * @requires accessTokenAuth * @param {Object} credentials The credentials object. * @param {string} credentials.accessToken The new access token. * @method updateToken * @param {Object} credentials The credentials object. * @param {string} credentials.username The username without the application's domain. * @param {string} credentials.accessToken An access token for the user with the provided user Id. */ /** * If you're authenticating with tokens that expire and have not provided a refresh token to the `connect` function, you can update your access token with `updateToken` before it expires to stay connected. * * @public * @memberof Authentication * @requires oauthToken * @method updateToken * @param {Object} credentials The credentials object. * @param {string} credentials.username The username without the application's domain. * @param {string} credentials.oauthToken An OAuth token provided by an outside service. * @example * kandy.updateToken({ * username: 'alfred@example.kandy.io', * oauthToken: 'RTG9SV3QAoJaeUSEQCZAHqrhde1yT' * }); */ updateToken: function updateToken(credentials) { dispatch(actions.refreshTokens(credentials)); }, /** * Updates the current connection. * * @public * @memberof Authentication * @requires updateConnection * @method updateConnection * @param {Object} connection * @param {Array} connection.services Services to subscribe to for notifications. * @example * kandy.updateConnection({ * services: ['IM', 'Presence', 'call'] * }) */ updateConnection: function updateConnection(connection) { dispatch(actions.updateSubscription(connection)); }, /** * Returns the current logged in user and the current auth token. * * @public * @memberof Authentication * @method getUserInfo * @returns {Object} user The user data. * @returns {string} user.username The user Id of the currently logged in user. * @returns {string} user.token The current access token. */ getUserInfo: function getUserInfo() { return (0, _selectors.getUserInfo)(getState()); }, /** * Get the connection state. * * @public * @memberof Authentication * @method getConnection * @returns {Object} connection The connection state. * @returns {boolean} connection.isConnected Whether the authenticated user is currently connected. * @returns {boolean} connection.isPending Whether the authenticated user's connection is currently pending. * @returns {Object} connection.error The error object if an error occured. * @returns {string} connection.error.message The error message. * @returns {string} connection.error.stack The stack trace of the error. */ getConnection: function getConnection() { var _getState$authenticat = getState().authentication, isConnected = _getState$authenticat.isConnected, isPending = _getState$authenticat.isPending, error = _getState$authenticat.error; return { isConnected: isConnected, isPending: isPending, error: error, subscription: (0, _selectors.getServices)(getState()) }; }, /** * Retrieves the services that the user is subscribed for. * * @public * @memberof Authentication * @requires services * @method getServices * @return {Array} A list of subscribed-to services. */ getServices: function getServices() { return (0, _selectors.getServices)(getState()); }, /** * Possible subscription states of the user. * * @public * @memberof Authentication * @property {string} FULL All requested feature subscriptions exist. * @property {string} PARTIAL Some feature subscriptions exist. * @property {string} NONE No feature subscriptions exist. */ subscriptionStates: _constants.SUBSCRIPTION_STATE, /** * Sets a token in the store to be used for authentication purposes. * A username is required as well to determine the current user. * @method setToken * @param {string} token A user access token. * @param {string} username A full username. * @requires cpaas2auth */ setToken: function setToken(token, username) { dispatch(actions.setToken({ token: token, username: username })); } }; } /** * Kandy's authentication feature handles connecting and disconnecting from any * backend services that the SDK deals with. As well, it handles and stores * authentication information on the behalf of the user. This allows the user to * interact with the server without worrying about authenticating. * * @public * @module Authentication */ /***/ }), /***/ "./src/auth/interface/eventTypes.js": /*!******************************************!*\ !*** ./src/auth/interface/eventTypes.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Authentication state has changed. You can get the new state by calling kandy.getConnection(). * * @public * @memberof Authentication * @event auth:change * @param {Object} params * @param {boolean} params.forced For a disconnection, whether the change was forced by the system. */ var AUTH_CHANGE = exports.AUTH_CHANGE = 'auth:change'; /** * There was an error with authentication. * * @public * @memberof Authentication * @event auth:error * @param {Object} params * @param {KandyError} params.error The Kandy error object. * */ var AUTH_ERROR = exports.AUTH_ERROR = 'auth:error'; /** * An attempt to extend the current user's subscription was made. * * In a failure scenario, the current user is still connected, and further * resubscription attempts will be made, but may become disconnected if the * session expires. * @public * @memberof Authentication * @event auth:resub * @param {Object} params * @param {number} params.attemptNum The attempt number of this resubscription. * @param {boolean} params.isFailure Whether the resubscription failed or not. * @param {KandyError} [params.error] The Kandy error object. */ var AUTH_RESUB = exports.AUTH_RESUB = 'auth:resub'; /***/ }), /***/ "./src/auth/interface/events.js": /*!**************************************!*\ !*** ./src/auth/interface/events.js ***! \**************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/auth/interface/eventTypes.js"); var eventTypes = _interopRequireWildcard(_eventTypes); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/auth/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function authChangedEvent(action) { return { type: action.error ? eventTypes.AUTH_ERROR : eventTypes.AUTH_CHANGE, args: action.error ? { error: action.payload } : {} }; } var eventsMap = {}; eventsMap[actionTypes.CONNECT_FINISHED] = authChangedEvent; eventsMap[actionTypes.USER_DETAILS_RECEIVED] = authChangedEvent; eventsMap[actionTypes.CONNECT] = authChangedEvent; eventsMap[actionTypes.DISCONNECT] = authChangedEvent; eventsMap[actionTypes.REFRESH_TOKENS_FINISHED] = authChangedEvent; eventsMap[actionTypes.UPDATE_SUBSCRIPTION_FINISH] = authChangedEvent; eventsMap[actionTypes.DISCONNECT_FINISHED] = function (action) { var discEvent = authChangedEvent(action); discEvent.args.forced = action.payload.forced; return discEvent; }; eventsMap[actionTypes.RESUBSCRIPTION_FINISHED] = function (action) { var resubEvent = { type: eventTypes.AUTH_RESUB, args: { attemptNum: action.payload.attemptNum, isFailure: action.error || false } }; if (action.error) { resubEvent.args.error = action.payload; } return resubEvent; }; exports.default = eventsMap; /***/ }), /***/ "./src/auth/interface/index.js": /*!*************************************!*\ !*** ./src/auth/interface/index.js ***! \*************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.api = exports.name = exports.reducer = undefined; var _reducers = __webpack_require__(/*! ./reducers */ "./src/auth/interface/reducers.js"); var _reducers2 = _interopRequireDefault(_reducers); var _name = __webpack_require__(/*! ./name */ "./src/auth/interface/name.js"); var _name2 = _interopRequireDefault(_name); var _api = __webpack_require__(/*! ./api */ "./src/auth/interface/api.js"); var _api2 = _interopRequireDefault(_api); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.reducer = _reducers2.default; exports.name = _name2.default; exports.api = _api2.default; /***/ }), /***/ "./src/auth/interface/name.js": /*!************************************!*\ !*** ./src/auth/interface/name.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * This interface is for an authentication plugin. * @type {string} */ var name = 'authentication'; exports.default = name; /***/ }), /***/ "./src/auth/interface/reducers.js": /*!****************************************!*\ !*** ./src/auth/interface/reducers.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = __webpack_require__(/*! babel-runtime/helpers/defineProperty */ "../../node_modules/babel-runtime/helpers/defineProperty.js"); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _extends8 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends9 = _interopRequireDefault(_extends8); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/auth/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var reducers = {}; reducers[actionTypes.CONNECT] = { next: function next(state) { return (0, _extends9.default)({}, state, { isPending: true, error: undefined }); } }; reducers[actionTypes.CONNECT_FINISHED] = { next: function next(state, action) { return (0, _extends9.default)({}, state, { isConnected: true, isPending: false, error: undefined, isSSO: action.meta.isSSO, platform: action.meta.platform, // Separate subscription, connection info based on the platform used. // Store platform subscription information. subscription: (0, _extends9.default)({}, state.subscription, (0, _defineProperty3.default)({}, action.meta.platform, action.payload.subscription)), // Store platform connection information to be procided to other plugins. connection: (0, _extends9.default)({}, state.connection, (0, _defineProperty3.default)({}, action.meta.platform, action.payload.connection)), // Store user information to be provided to Kandy developers. userInfo: action.payload.userInfo }); }, throw: function _throw(state, action) { return (0, _extends9.default)({}, state, { isConnected: false, isPending: false, error: action.payload }); } }; // On connection occured, store the connection information into state, but do // not update any status state. The connection has not yet finished. reducers[actionTypes.CONNECTION_OCCURRED] = { next: function next(state, action) { return (0, _extends9.default)({}, state, { // Separate subscription, connection info based on the platform used. // Store platform subscription information. subscription: (0, _extends9.default)({}, state.subscription, (0, _defineProperty3.default)({}, action.meta.platform, action.payload.subscription)), // Store platform connection information to be procided to other plugins. connection: (0, _extends9.default)({}, state.connection, (0, _defineProperty3.default)({}, action.meta.platform, action.payload.connection)) }); } }; reducers[actionTypes.DISCONNECT] = { next: function next(state) { return (0, _extends9.default)({}, state, { isPending: true, error: undefined }); } }; reducers[actionTypes.DISCONNECT_FINISHED] = { next: function next() { return { isConnected: false, isPending: false, error: undefined }; }, throw: function _throw(state, action) { return (0, _extends9.default)({}, state, { // Treat an error as if we are still disconnected. isConnected: false, isPending: false, error: action.payload }); } }; reducers[actionTypes.REFRESH_TOKENS_FINISHED] = { next: function next(state, action) { // Merge the updated requestOptions into the current state. var requestOptions = (0, _fp.merge)(state.connection[action.meta.platform].requestOptions, action.payload.connection.requestOptions); return (0, _extends9.default)({}, state, { connection: (0, _extends9.default)({}, state.connection, (0, _defineProperty3.default)({}, action.meta.platform, (0, _extends9.default)({}, state.connection[action.meta.platform], action.payload.connection, { requestOptions: requestOptions }))), userInfo: (0, _extends9.default)({}, state.userInfo, { accessToken: action.payload.connection.accessToken, refreshToken: action.payload.connection.refreshToken }) }); } }; /* * Updates the subscription information for a specified platform. */ reducers[actionTypes.UPDATE_SUBSCRIPTION_FINISH] = { next: function next(state, action) { return (0, _extends9.default)({}, state, { subscription: (0, _extends9.default)({}, state.subscription, (0, _defineProperty3.default)({}, action.meta.platform, (0, _extends9.default)({}, state.subscription[action.meta.platform], action.payload))) }); } }; reducers[actionTypes.SET_TOKEN] = { next: function next(state, action) { return (0, _extends9.default)({}, state, { userInfo: (0, _extends9.default)({}, state.userInfo, { accessToken: action.payload.token, username: action.payload.username }) }); } }; /** * Auth Interface reducer * @method reducer * @param {Object} state - The current redux state. * @param {Object} action - A flux standard action. * @return {Object} - The new redux state. * @example * Auth state structure example; connected. * authState = { * isConnected: true, * isPending: false, * error: undefined, * subscription: { ... }, * connection: { ... }, * userInfo: { ... } * } */ var reducer = (0, _reduxActions.handleActions)(reducers, { isConnected: false, isPending: false }); exports.default = reducer; /***/ }), /***/ "./src/auth/interface/selectors.js": /*!*****************************************!*\ !*** ./src/auth/interface/selectors.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getExposedState = getExposedState; exports.getAuthConfig = getAuthConfig; exports.getSubscriptionInfo = getSubscriptionInfo; exports.getConnectionInfo = getConnectionInfo; exports.getDomain = getDomain; exports.getUserInfo = getUserInfo; exports.getAuthScenario = getAuthScenario; exports.getServices = getServices; exports.getPlatform = getPlatform; exports.getRequestInfo = getRequestInfo; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _constants = __webpack_require__(/*! ../constants */ "./src/auth/constants.js"); var _constants2 = __webpack_require__(/*! ../../constants */ "./src/constants.js"); /** * Plugin selector function to expose state globally * @param {Object} pluginState The localized (plugin) state * @return {Object} The exposed state */ function getExposedState(pluginState) { // TODO: Filter out unwanted auth stuff from public state. return (0, _fp.cloneDeep)(pluginState); } /* * Redux-saga selector functions. * Used with the `select` effect in sagas to Retrieves * specific portions of the state. */ /** * Retrieves the config options provided by the auth plugin. * @method getAuthConfig * @return {Object} */ function getAuthConfig(state) { return (0, _fp.cloneDeep)(state.config.authentication); } /** * Retrieves the subscription information of a platform. * @method getSubscriptionInfo * @param {string} [platform] - The Kandy backend platform in use. * @return {Object} */ function getSubscriptionInfo(state, platform) { if (!platform) { platform = getPlatform(state); } if (state.authentication.subscription) { return (0, _fp.cloneDeep)(state.authentication.subscription[platform]); } else { return undefined; } } /** * Retrieves the connection information of a platform. * Includes the info needed to make requests to that platform. * @method getConnectionInfo * @param {string} [platform] - The Kandy backend platform in use. * @return {Object} */ function getConnectionInfo(state, platform) { if (!platform) { platform = getPlatform(state); } if (state.authentication.connection) { return (0, _fp.cloneDeep)(state.authentication.connection[platform]); } else { return undefined; } } /** * Retrieves the domain of the callee address information of a platform. * @method getDomain * @return {string} */ function getDomain(state) { var connection = getConnectionInfo(state); return (0, _fp.cloneDeep)(connection.username.substr(connection.username.indexOf('@'))); } /** * Retrieves the user information. * @method getUserInfo * @return {Object} */ function getUserInfo(state) { return (0, _fp.cloneDeep)(state.authentication.userInfo); } /** * Retrieves a flag from the store representing if the login scenario was SSO or not. * @method getAuthScenario * @return {boolean} */ function getAuthScenario(state) { return (0, _fp.cloneDeep)(state.authentication.isSSO); } /** * Retrieves information about the services that the user is subscribed for. * @method getServices * @return {Object} */ function getServices(state, platform) { var subscription = getSubscriptionInfo(state, platform); if (subscription && subscription.servicesInfo) { return subscription.servicesInfo; } else { return { // TODO: Have default as part of the reducer. requested: [], received: [], missing: [], status: _constants.SUBSCRIPTION_STATE.NONE, services: {} }; } } /** * Retrieves the name of the backend platform the user is currently subscribed to. * @method getPlatform * @return {string} */ function getPlatform(state) { return (0, _fp.cloneDeep)(state.authentication.platform); } /** * Retrieves info needed to make a REST request for the different platforms. * @method getRequestInfo * @return {Object} */ function getRequestInfo(state, platform) { if (!platform) { platform = getPlatform(state); } var _getAuthConfig = getAuthConfig(state), server = _getAuthConfig.server, subscription = _getAuthConfig.subscription, clientCorrelator = _getAuthConfig.clientCorrelator; var _cloneDeep = (0, _fp.cloneDeep)(state.authentication), userInfo = _cloneDeep.userInfo; var requestInfo = void 0; switch (platform) { case _constants2.platforms.CPAAS2: requestInfo = { baseURL: server.protocol + '://' + server.base + ':' + server.port, version: server.version, username: userInfo.username, // TODO: Token doesn't need to be here if its in requestOptions. token: userInfo.accessToken, clientCorrelator: clientCorrelator, // TODO: DO NOT hardcode this here (?). The original idea was that this // is set in state after connection. options: { headers: { Accept: 'application/json', Authorization: 'Bearer ' + userInfo.accessToken, 'Content-Type': 'application/json' } } }; break; case _constants2.platforms.CPAAS: case _constants2.platforms.LINK: requestInfo = { baseURL: subscription.protocol + '://' + subscription.server + ':' + subscription.port, version: subscription.version, username: userInfo.username }; break; default: return {}; } var connInfo = getConnectionInfo(state, platform); if (connInfo && connInfo.requestOptions) { requestInfo.requestOptions = connInfo.requestOptions; } return requestInfo; } /***/ }), /***/ "./src/auth/link/index.js": /*!********************************!*\ !*** ./src/auth/link/index.js ***! \********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = authLink; var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _events = __webpack_require__(/*! ../interface/events */ "./src/auth/interface/events.js"); var _events2 = _interopRequireDefault(_events); var _actions = __webpack_require__(/*! ../../events/interface/actions */ "./src/events/interface/actions.js"); var _interface = __webpack_require__(/*! ../interface */ "./src/auth/interface/index.js"); var _actions2 = __webpack_require__(/*! ../../config/interface/actions */ "./src/config/interface/actions.js"); var _utils = __webpack_require__(/*! ../../common/utils */ "./src/common/utils.js"); var _logs = __webpack_require__(/*! ../../logs */ "./src/logs/index.js"); var _selectors = __webpack_require__(/*! ../interface/selectors */ "./src/auth/interface/selectors.js"); var _sagas = __webpack_require__(/*! ./sagas */ "./src/auth/link/sagas.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Get the logger /** * selector for exposed authentication state */ // Utilities. // The interface to follow. // Events var log = (0, _logs.getLogManager)().getLogger('AUTH'); /** * Configuration options for the Authentication feature. * @public * @name configs.authentication * @memberof configs * @instance * @param {Object} authentication Authentication configs. * @param {Object} authentication.subscription * @param {string} [authentication.subscription.protocol=https] Protocol to be used for subscription requests. * @param {string} [authentication.subscription.server=multispidr.kandy.io] Server to be used for subscription requests. * @param {Number} [authentication.subscription.port=443] Port to be used for subscription requests. * @param {string} [authentication.subscription.server=multispidr.kandy.io] Server to be used for subscription requests. * @param {string} [authentication.subscription.version=1] Version of the REST API to be used. * @param {Number} [authentication.subscription.expires=3600] Time duration, in seconds, until a subscription should expire. * @param {Array} [authentication.subscription.service] Services to subscribe to for notifications. * @param {Object} authentication.websocket * @param {string} [authentication.websocket.protocol=wss] Protocol to be used for websocket notifications. * @param {string} [authentication.websocket.server=multiwebsocket.kandy.io] Server to be used for websocket notifications. * @param {Number} [authentication.websocket.port=443] Port to be used for websocket notifications. */ /** * On link authentication implementation factory. * @method authLink * @param {Object} options - Configuration options for authentication. See above. * @return {Object} plugin - An authentication plugin. */ // State setters. // Redux-Saga function authLink() { var _marked = /*#__PURE__*/_regenerator2.default.mark(init); var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var defaultOptions = { subscription: { protocol: 'https', port: '443', expires: 3600, service: ['IM', 'Presence', 'call'], version: '1' }, websocket: { protocol: 'wss', port: '443' } }; options = (0, _utils.mergeValues)(defaultOptions, options); if (!options.subscription.server) { log.error('No server configuration provided. Please provide proper authentication configurations.'); } function init() { return _regenerator2.default.wrap(function init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.put)((0, _actions2.update)(options, _interface.name)); case 2: _context.next = 4; return (0, _effects.put)((0, _actions.mapEvents)(_events2.default)); case 4: case 'end': return _context.stop(); } } }, _marked, this); } var capabilities = ['userCredentialsAuth', 'updateConnection', 'services']; return { sagas: [_sagas.connectFlow, _sagas.extendSubscription, _sagas.updateSubscription, _sagas.onSubscriptionGone], capabilities: capabilities, init: init, api: _interface.api, selector: _selectors.getExposedState, reducer: _interface.reducer, name: _interface.name }; } /***/ }), /***/ "./src/auth/link/sagas.js": /*!********************************!*\ !*** ./src/auth/link/sagas.js ***! \********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.connectFlow = connectFlow; exports.disconnect = disconnect; exports.extendSubscription = extendSubscription; exports.updateSubscription = updateSubscription; exports.onSubscriptionGone = onSubscriptionGone; var _reduxSaga = __webpack_require__(/*! redux-saga */ "../../node_modules/redux-saga/es/index.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _actions = __webpack_require__(/*! ../interface/actions */ "./src/auth/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _actionTypes = __webpack_require__(/*! ../interface/actionTypes */ "./src/auth/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _selectors = __webpack_require__(/*! ../interface/selectors */ "./src/auth/interface/selectors.js"); var _constants = __webpack_require__(/*! ../../constants */ "./src/constants.js"); var _requests = __webpack_require__(/*! ../subscription/requests */ "./src/auth/subscription/requests.js"); var _actionTypes2 = __webpack_require__(/*! ../../notifications/interface/actionTypes */ "./src/notifications/interface/actionTypes.js"); var _actionTypes3 = __webpack_require__(/*! ../../connectivity/interface/actionTypes */ "./src/connectivity/interface/actionTypes.js"); var wsActionTypes = _interopRequireWildcard(_actionTypes3); var _actions2 = __webpack_require__(/*! ../../connectivity/interface/actions */ "./src/connectivity/interface/actions.js"); var _base = __webpack_require__(/*! base-64 */ "../../node_modules/base-64/base64.js"); var _base2 = _interopRequireDefault(_base); var _utf = __webpack_require__(/*! utf8 */ "../../node_modules/utf8/utf8.js"); var _utf2 = _interopRequireDefault(_utf); var _logs = __webpack_require__(/*! ../../logs */ "./src/logs/index.js"); var _errors = __webpack_require__(/*! ../../errors */ "./src/errors/index.js"); var _errors2 = _interopRequireDefault(_errors); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(connectFlow), _marked2 = /*#__PURE__*/_regenerator2.default.mark(connect), _marked3 = /*#__PURE__*/_regenerator2.default.mark(disconnect), _marked4 = /*#__PURE__*/_regenerator2.default.mark(extendSubscription), _marked5 = /*#__PURE__*/_regenerator2.default.mark(updateSubscription), _marked6 = /*#__PURE__*/_regenerator2.default.mark(onSubscriptionGone); // Redux-Saga // Auth // State selectors // Constants // Requests // Other plugins. // This is an Link plugin. var platform = _constants.platforms.LINK; // Get the logger var log = (0, _logs.getLogManager)().getLogger('AUTH'); /** * Link connect saga. This Saga is in charge of the flow for connecting and disconnecting. * Handles the workflow of connecting or disconnecting to SPiDR. * @method connectFlow */ function connectFlow() { var action, config, task, finishOrError; return _regenerator2.default.wrap(function connectFlow$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (false) {} _context.next = 3; return (0, _effects.take)(actionTypes.CONNECT); case 3: action = _context.sent; _context.next = 6; return (0, _effects.select)(_selectors.getAuthConfig); case 6: config = _context.sent; _context.next = 9; return (0, _effects.fork)(connect, action, config); case 9: task = _context.sent; _context.next = 12; return (0, _effects.take)([actionTypes.CONNECT_FINISHED, actionTypes.DISCONNECT]); case 12: finishOrError = _context.sent; if (!(finishOrError.type === actionTypes.DISCONNECT)) { _context.next = 18; break; } _context.next = 16; return (0, _effects.cancel)(task); case 16: _context.next = 23; break; case 18: if (!(finishOrError.type === actionTypes.CONNECT_FINISHED && !finishOrError.error)) { _context.next = 23; break; } _context.next = 21; return (0, _effects.take)([actionTypes.DISCONNECT]); case 21: _context.next = 23; return (0, _effects.call)(disconnect); case 23: _context.next = 0; break; case 25: case 'end': return _context.stop(); } } }, _marked, this); } /** * Link connect function. * Performs the workflow of connecting to SPiDR. * @method connect */ function connect(action, config) { var requestOptions, credentials, response, userInfo, connection, subscription, websocketInfo, chan, wsOpenOrError; return _regenerator2.default.wrap(function connect$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: // Common request options, to be used for all subsequent requests after connect. requestOptions = { headers: { 'Content-Type': 'application/json', Accept: 'application/json' } // Determine what type of connect method to use. This determines what extra // information needs to be added to the request. }; credentials = action.payload.credentials; if (!credentials.password && credentials.userAccessToken) { log.info('Connecting with access token scenario.'); requestOptions.queryParams = { key: credentials.userAccessToken }; } else if (credentials.username && credentials.password) { log.info('Connecting with username/password scenario.'); requestOptions.headers['Authorization'] = 'basic ' + _base2.default.encode(_utf2.default.encode(credentials.username + ':' + credentials.password)); } else { log.info('Unexpected connect scenario.'); } _context2.prev = 3; _context2.next = 6; return (0, _effects.call)(_requests.subscribe, config.subscription, credentials, requestOptions); case 6: response = _context2.sent; if (!response.error) { _context2.next = 11; break; } _context2.next = 10; return (0, _effects.put)(actions.connectFinished({ error: response.error }, platform)); case 10: return _context2.abrupt('return'); case 11: // Gather information to provide externally. userInfo = { username: action.payload.credentials.username // Gather information to provide internally, to other plugins. }; connection = { server: { protocol: config.subscription.protocol, server: config.subscription.server, port: config.subscription.port, version: config.subscription.version }, username: action.payload.credentials.username, token: response.token, // Request options that all other (Link) plugins will use. requestOptions: requestOptions // Keep track of service subscription information. }; subscription = (0, _extends3.default)({}, response.subscriptionParams, { servicesInfo: response.servicesInfo, url: response.subscription // Need to create a new object, rather than adding `url` to // connectionInfo in order to prevent state mutation. }); websocketInfo = (0, _extends3.default)({}, config.websocket, { url: subscription.notificationChannel }); _context2.next = 17; return (0, _effects.actionChannel)(wsActionTypes.WS_CONNECT_FINISHED); case 17: chan = _context2.sent; _context2.next = 20; return (0, _effects.put)((0, _actions2.wsAttemptConnect)(websocketInfo, platform)); case 20: _context2.next = 22; return (0, _effects.take)(chan); case 22: wsOpenOrError = _context2.sent; chan.close(); if (!wsOpenOrError.error) { _context2.next = 26; break; } throw wsOpenOrError.payload; case 26: _context2.next = 28; return (0, _effects.put)(actions.connectFinished({ subscription: subscription, userInfo: userInfo, connection: connection }, platform)); case 28: _context2.next = 34; break; case 30: _context2.prev = 30; _context2.t0 = _context2['catch'](3); _context2.next = 34; return (0, _effects.put)(actions.connectFinished({ error: _context2.t0 }, platform)); case 34: _context2.prev = 34; _context2.next = 37; return (0, _effects.cancelled)(); case 37: if (!_context2.sent) { _context2.next = 40; break; } _context2.next = 40; return (0, _effects.call)(disconnect); case 40: return _context2.finish(34); case 41: case 'end': return _context2.stop(); } } }, _marked2, this, [[3, 30, 34, 41]]); } /** * Link disconnect function. * Performs the actions for actually disconnecting from SPiDR. * @method disconnect */ function disconnect() { var subscription, connection, response; return _regenerator2.default.wrap(function disconnect$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return (0, _effects.select)(_selectors.getSubscriptionInfo); case 2: subscription = _context3.sent; _context3.next = 5; return (0, _effects.select)(_selectors.getConnectionInfo); case 5: connection = _context3.sent; // If the above info is not present, we probably got a disconnect mid-connection attempt. response = {}; if (!(subscription && connection)) { _context3.next = 11; break; } _context3.next = 10; return (0, _effects.call)(_requests.unsubscribe, connection, subscription.url); case 10: response = _context3.sent; case 11: _context3.next = 13; return (0, _effects.put)((0, _actions2.wsDisconnect)()); case 13: _context3.next = 15; return (0, _effects.take)([wsActionTypes.WS_DISCONNECT_FINISHED, wsActionTypes.WS_ERROR]); case 15: if (!response.error) { _context3.next = 20; break; } _context3.next = 18; return (0, _effects.put)(actions.disconnectFinished(response)); case 18: _context3.next = 22; break; case 20: _context3.next = 22; return (0, _effects.put)(actions.disconnectFinished()); case 22: case 'end': return _context3.stop(); } } }, _marked3, this); } /** * Saga for extending a user's subscription. * When triggered, make a resub request to SPiDR for a specific subscription. * @method extendSubscription */ function extendSubscription() { var resubTriggers, action, isOnSSO, subscription, connection, linkConnection, attemptNum, resubDelay, _ref, _cancel, response; return _regenerator2.default.wrap(function extendSubscription$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return (0, _effects.actionChannel)([actionTypes.CONNECT_FINISHED, actionTypes.RESUBSCRIPTION_FINISHED]); case 2: resubTriggers = _context4.sent; case 3: if (false) {} _context4.next = 6; return (0, _effects.take)(resubTriggers); case 6: action = _context4.sent; if (!(action.type === actionTypes.CONNECT_FINISHED && action.error)) { _context4.next = 9; break; } return _context4.abrupt('continue', 3); case 9: _context4.next = 11; return (0, _effects.select)(_selectors.getAuthScenario); case 11: isOnSSO = _context4.sent; subscription = {}; connection = {}; if (!isOnSSO) { _context4.next = 24; break; } _context4.next = 17; return (0, _effects.select)(_selectors.getConnectionInfo); case 17: linkConnection = _context4.sent; connection = { server: linkConnection.server, token: action.payload.connection.token }; _context4.next = 21; return (0, _effects.select)(_selectors.getSubscriptionInfo); case 21: subscription = _context4.sent; _context4.next = 30; break; case 24: _context4.next = 26; return (0, _effects.select)(_selectors.getConnectionInfo); case 26: connection = _context4.sent; _context4.next = 29; return (0, _effects.select)(_selectors.getSubscriptionInfo); case 29: subscription = _context4.sent; case 30: attemptNum = void 0; // If the action was a failed resubscription, increment the attempt number. if (action.type === actionTypes.RESUBSCRIPTION_FINISHED && action.error) { attemptNum = action.payload.attemptNum + 1; } else { attemptNum = 1; } // Set the delay to be halfway between now and when the subscription expires. resubDelay = subscription.expires * 1000 / Math.pow(2, attemptNum); // Don't try to resub more often than every 5 minutes. resubDelay = resubDelay > 30000 ? resubDelay : 30000; // Wait for either the resub delay or a disconnect action. _context4.next = 36; return (0, _effects.race)({ expiry: (0, _effects.call)(_reduxSaga.delay, resubDelay), cancel: (0, _effects.take)(actionTypes.DISCONNECT_FINISHED) }); case 36: _ref = _context4.sent; _cancel = _ref.cancel; if (_cancel) { _context4.next = 49; break; } _context4.next = 41; return (0, _effects.call)(_requests.resubscribe, connection, subscription, isOnSSO); case 41: response = _context4.sent; if (!response.error) { _context4.next = 47; break; } _context4.next = 45; return (0, _effects.put)(actions.resubscribeFinished({ error: response.error, attemptNum: attemptNum }, platform)); case 45: _context4.next = 49; break; case 47: _context4.next = 49; return (0, _effects.put)(actions.resubscribeFinished({ attemptNum: attemptNum }, platform)); case 49: _context4.next = 3; break; case 51: case 'end': return _context4.stop(); } } }, _marked4, this); } /** * Saga for updating a subscription's services. * @method updateSubscription */ function updateSubscription() { var action, isOnSSO, connection, subscription, response; return _regenerator2.default.wrap(function updateSubscription$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: if (false) {} _context5.next = 3; return (0, _effects.take)(actionTypes.UPDATE_SUBSCRIPTION); case 3: action = _context5.sent; log.debug("Attempting to update subscription's services.", action.payload); _context5.next = 7; return (0, _effects.select)(_selectors.getAuthScenario); case 7: isOnSSO = _context5.sent; _context5.next = 10; return (0, _effects.select)(_selectors.getConnectionInfo); case 10: connection = _context5.sent; _context5.next = 13; return (0, _effects.select)(_selectors.getSubscriptionInfo); case 13: subscription = _context5.sent; subscription.service = action.payload; // Use the resubscribe request to update the subscription. The endpoint is for both. _context5.next = 17; return (0, _effects.call)(_requests.resubscribe, connection, subscription, isOnSSO); case 17: response = _context5.sent; if (!response.error) { _context5.next = 24; break; } log.debug('Failed to update subscription services.'); _context5.next = 22; return (0, _effects.put)(actions.updateSubscriptionFinished({ error: new _errors2.default({ message: response.message, code: _errors.authCodes.LINK_UPDATE_SUBSCRIPTION_FAIL }) }, platform)); case 22: _context5.next = 27; break; case 24: log.debug('Succesfully updated subscription services.', action.payload); // TODO: Use response.serviceInfo to update full/partial subscription. // Only update the service substate in subscription. _context5.next = 27; return (0, _effects.put)(actions.updateSubscriptionFinished({ subscription: { service: action.payload } }, platform)); case 27: _context5.next = 0; break; case 29: case 'end': return _context5.stop(); } } }, _marked5, this); } /** * Saga that handles a "subscription gone" notification. * Treat the notification as a forced disconnect. * @method onSubscriptionGone */ function onSubscriptionGone() { var takeGoneSubscription; return _regenerator2.default.wrap(function onSubscriptionGone$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: takeGoneSubscription = function takeGoneSubscription(action) { return action.type === _actionTypes2.NOTIFICATION_RECEIVED && action.payload.notificationMessage && action.payload.notificationMessage.eventType === 'gone'; }; // Redux-saga take() pattern. // Take notifications about the subscription being 'gone'. case 1: if (false) {} _context6.next = 4; return (0, _effects.take)(takeGoneSubscription); case 4: _context6.next = 6; return (0, _effects.put)((0, _actions2.wsDisconnect)()); case 6: _context6.next = 8; return (0, _effects.put)(actions.disconnectFinished({ forced: true })); case 8: _context6.next = 1; break; case 10: case 'end': return _context6.stop(); } } }, _marked6, this); } /***/ }), /***/ "./src/auth/subscription/requests.js": /*!*******************************************!*\ !*** ./src/auth/subscription/requests.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.subscribe = subscribe; exports.unsubscribe = unsubscribe; exports.resubscribe = resubscribe; var _selectors = __webpack_require__(/*! ../interface/selectors */ "./src/auth/interface/selectors.js"); var _services = __webpack_require__(/*! ./services */ "./src/auth/subscription/services.js"); var _effects = __webpack_require__(/*! ../../request/effects */ "./src/request/effects.js"); var _effects2 = _interopRequireDefault(_effects); var _errors = __webpack_require__(/*! ../../errors */ "./src/errors/index.js"); var _errors2 = _interopRequireDefault(_errors); var _logs = __webpack_require__(/*! ../../logs */ "./src/logs/index.js"); var _effects3 = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _utils = __webpack_require__(/*! ../../common/utils */ "./src/common/utils.js"); var _constants = __webpack_require__(/*! ../../constants */ "./src/constants.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(subscribe), _marked2 = /*#__PURE__*/_regenerator2.default.mark(unsubscribe), _marked3 = /*#__PURE__*/_regenerator2.default.mark(resubscribe); // Authentication plugin. // Other plugins. // Libraries. // Constants var log = (0, _logs.getLogManager)().getLogger('AUTH'); /** * Subscribe to SPiDR with the provided information. * @method subscribe * @param {Object} connection Server information. * @param {Object} credentials User information. * @return {Object} Subscription response. */ function subscribe(connection, credentials) { var extras = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var subscribeType, requestOptions, response, statusCode, subscribeResponse, subscribedServices, servicesInfo; return _regenerator2.default.wrap(function subscribe$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: subscribeType = connection.isAnonymous ? 'anonymous' : 'user'; requestOptions = {}; requestOptions.method = 'POST'; requestOptions.url = connection.protocol + '://' + connection.server + ':' + connection.port + ('/rest/version/' + connection.version) + ('/' + subscribeType + '/' + credentials.username + '/subscription'); requestOptions.body = (0, _stringify2.default)({ subscribeRequest: { expires: connection.expires, service: connection.service, localization: connection.localization || 'English_US', useTurn: connection.useTurn || true, notificationType: connection.notificationType || 'WebSocket' } }); // If there were any extra request options, merge them into the // options for this request. Priority is for the options defined here. requestOptions = (0, _utils.mergeValues)(extras, requestOptions); // Send the subscription request. _context.next = 8; return (0, _effects2.default)(requestOptions); case 8: response = _context.sent; if (!response.error) { _context.next = 20; break; } if (!response.payload.body) { _context.next = 16; break; } statusCode = response.payload.body.subscribeResponse.statusCode; log.debug('Failed user subscription with status code ' + statusCode + '.'); // Handle errors from the server. return _context.abrupt('return', { // TODO: Better error; more info. error: new _errors2.default({ message: 'Failed to subscribe user. Code: ' + statusCode + '.', code: _errors.authCodes.LINK_SUBSCRIBE_FAIL }) }); case 16: log.debug('Failed user subscription.', response.payload.result.message); // Handle errors from the request plugin. return _context.abrupt('return', { // TODO: Better error; more info. error: new _errors2.default({ message: 'Subscribe request failed: ' + response.payload.result.message + '.', // TODO: Shared error codes. code: _errors.authCodes.LINK_SUBSCRIBE_FAIL }) }); case 18: _context.next = 27; break; case 20: // Request was successful. subscribeResponse = response.payload.body.subscribeResponse; subscribedServices = subscribeResponse.subscriptionParams.service; _context.next = 24; return (0, _effects3.call)(_services.parseSpidrServices, connection.service, subscribedServices); case 24: servicesInfo = _context.sent; log.debug('Subscribed user. Service subscription status: ' + servicesInfo.status); return _context.abrupt('return', (0, _extends3.default)({ error: false, servicesInfo: servicesInfo }, subscribeResponse)); case 27: case 'end': return _context.stop(); } } }, _marked, this); } /** * Unsubscribe from SPiDR with the provided subscription info. * @method unsubscribe * @param {Object} connection Server information for the service in use. * @param {string} connection.server Server information for generating the URL. * @param {string} connection.requestOptions Common request options to be added. * @param {string} subscriptionURL URL of the user's subscription instance. * @return {Object} Unsubscription response. */ function unsubscribe(connection, subscriptionURL) { var requestOptions, response, statusCode, message, unsubResponse, platform; return _regenerator2.default.wrap(function unsubscribe$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: requestOptions = {}; requestOptions.method = 'DELETE'; requestOptions.url = connection.server.protocol + '://' + connection.server.server + ':' + connection.server.port + subscriptionURL; requestOptions.headers = { Accept: 'application/json', 'Content-Type': 'application/json' // Send the unsubscribe request. };_context2.next = 6; return (0, _effects2.default)(requestOptions, connection.requestOptions); case 6: response = _context2.sent; if (!response.error) { _context2.next = 19; break; } if (!response.payload.body) { _context2.next = 14; break; } // Handle errors from the server. statusCode = response.payload.body.subscribeResponse.statusCode; log.debug('Failed to unsubscribe user with status code ' + statusCode + '.'); return _context2.abrupt('return', { // TODO: Better error; more info. error: new _errors2.default({ message: 'Failed to unsubscribe user. Code: ' + statusCode + '.', code: _errors.authCodes.LINK_UNSUBSCRIBE_FAIL }) }); case 14: // Handle errors from the request helper. message = response.payload.result.message; log.debug('Failed user unsubscription.', message); return _context2.abrupt('return', { // TODO: Better error; more info. error: new _errors2.default({ message: 'Unsubscribe request failed: ' + message + '.', // TODO: Shared error codes. code: _errors.authCodes.LINK_UNSUBSCRIBE_FAIL }) }); case 17: _context2.next = 32; break; case 19: // Request was successful. unsubResponse = response.payload.body.subscribeResponse; _context2.next = 22; return (0, _effects3.select)(_selectors.getPlatform); case 22: platform = _context2.sent; if (!((platform === _constants.platforms.LINK || platform === _constants.platforms.CLOUD) && unsubResponse.statusCode === 0)) { _context2.next = 27; break; } return _context2.abrupt('return', (0, _extends3.default)({ error: false }, unsubResponse)); case 27: if (!(platform === _constants.platforms.CPAAS && unsubResponse.statusCode === 0)) { _context2.next = 31; break; } return _context2.abrupt('return', (0, _extends3.default)({ error: false }, unsubResponse)); case 31: return _context2.abrupt('return', { error: new _errors2.default({ message: 'Unknown error; statusCode: ' + unsubResponse.statusCode + '.', code: _errors.authCodes.LINK_UNSUBSCRIBE_FAIL }) }); case 32: case 'end': return _context2.stop(); } } }, _marked2, this); } /** * Resubscribe to SPiDR to extend an existing subscription. * @method resubscribe * @param {Object} connection Server information for the service in use. * @param {string} connection.server Server information for generating the URL. * @param {string} connection.requestOptions Common request options to be added. * @param {Object} subscription Information about the subscription instance. * @param {string} subscription.expires - The time (in seconds) until subscription expiry. * @param {Array} subscription.service - The SPiDR services to resubscribe to. * @param {Array} subscription.url - The URL of the user's subscription instance. * @return {Object} Resubscription response. */ function resubscribe(connection, subscription) { var requestOptions, response, statusCode, message, resubResponse, subscribedServices, servicesInfo; return _regenerator2.default.wrap(function resubscribe$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: requestOptions = {}; requestOptions.method = 'PUT'; requestOptions.url = connection.server.protocol + '://' + connection.server.server + ':' + connection.server.port + subscription.url; requestOptions.headers = { Accept: 'application/json', 'Content-Type': 'application/json' // TODO: Don't hardcode the defaults here. Should be shared with // the subscribe request as well. };requestOptions.body = (0, _stringify2.default)({ subscribeRequest: { expires: subscription.expires, service: subscription.service, localization: subscription.localization || 'English_US', useTurn: subscription.useTurn || true, notificationType: subscription.notificationType || 'WebSocket' } }); // Send the subscription update request. _context3.next = 7; return (0, _effects2.default)(requestOptions, connection.requestOptions); case 7: response = _context3.sent; if (!response.error) { _context3.next = 20; break; } if (!response.payload.body) { _context3.next = 15; break; } // Handle errors from the server. statusCode = response.payload.body.subscribeResponse.statusCode; log.debug('Failed to update user subscription with status code ' + statusCode + '.'); return _context3.abrupt('return', { // TODO: Better error; more info. error: new _errors2.default({ message: 'Failed to update user subscription. Code: ' + statusCode + '.', code: _errors.authCodes.LINK_UPDATE_SUBSCRIPTION_FAIL }) }); case 15: // Handle errors from the request helper. message = response.payload.result.message; log.debug('User subscription update request failed.', message); return _context3.abrupt('return', { // TODO: Better error; more info. error: new _errors2.default({ message: 'Update subscription request failed.: ' + message + '.', // TODO: Shared error codes. code: _errors.authCodes.LINK_UPDATE_SUBSCRIPTION_FAIL }) }); case 18: _context3.next = 31; break; case 20: // Request was successful. resubResponse = response.payload.body.subscribeResponse; if (!(resubResponse.statusCode === 0 || resubResponse.statusCode === 2)) { _context3.next = 30; break; } subscribedServices = resubResponse.subscriptionParams.service; _context3.next = 25; return (0, _effects3.call)(_services.parseSpidrServices, subscription.service, subscribedServices); case 25: servicesInfo = _context3.sent; log.debug('Resubscribed user. Service resubscription status: ' + servicesInfo.status); // Success. return _context3.abrupt('return', (0, _extends3.default)({ error: false, servicesInfo: servicesInfo }, resubResponse)); case 30: return _context3.abrupt('return', { error: new _errors2.default({ message: 'Unknown error; statusCode: ' + resubResponse.statusCode + '.', code: _errors.authCodes.LINK_UPDATE_SUBSCRIPTION_FAIL }) }); case 31: case 'end': return _context3.stop(); } } }, _marked3, this); } /***/ }), /***/ "./src/auth/subscription/services.js": /*!*******************************************!*\ !*** ./src/auth/subscription/services.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseSpidrServices = parseSpidrServices; var _constants = __webpack_require__(/*! ../constants */ "./src/auth/constants.js"); /** * Uses the requested and received SPiDR [subscription] services to determine * the SDK subscription status for each service. * @method parseSpidrServices * @param {Array} requested The list of requested SPiDR services. * @param {Array} received The list of received SPiDR services. * @return {Object} Information about the SDK's subscriptions. */ function parseSpidrServices(requested, received) { // CPaaS platform is not case-sensitive (Link is), so filter without caring about case. var upperReceived = received.map(function (service) { return service.toUpperCase(); }); // Find the missing services. var missing = requested.filter(function (reqService) { // If the requested service was received (not caring about case), // it is not missing. return upperReceived.indexOf(reqService.toUpperCase()) === -1; }); var subscriptions = { requested: requested, received: received, missing: missing, status: 'UNKNOWN', services: {} // Determine the overall subscription status. };if (received.length === 0) { subscriptions.status = _constants.SUBSCRIPTION_STATE.NONE; } else if (received.length > 0 && missing.length > 0) { subscriptions.status = _constants.SUBSCRIPTION_STATE.PARTIAL; } else if (received.length > 0 && requested.length === received.length) { subscriptions.status = _constants.SUBSCRIPTION_STATE.FULL; } else {} // Should never reach this case. // List the individual service statuses. received.forEach(function (service) { subscriptions.services[service] = true; }); missing.forEach(function (service) { subscriptions.services[service] = false; }); return subscriptions; } /***/ }), /***/ "./src/basePlugins.js": /*!****************************!*\ !*** ./src/basePlugins.js ***! \****************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _logs = __webpack_require__(/*! ./logs */ "./src/logs/index.js"); var _logs2 = _interopRequireDefault(_logs); var _config = __webpack_require__(/*! ./config */ "./src/config/index.js"); var _config2 = _interopRequireDefault(_config); var _events = __webpack_require__(/*! ./events */ "./src/events/index.js"); var _events2 = _interopRequireDefault(_events); var _notifications = __webpack_require__(/*! ./notifications */ "./src/notifications/index.js"); var _notifications2 = _interopRequireDefault(_notifications); var _request = __webpack_require__(/*! ./request */ "./src/request/index.js"); var _request2 = _interopRequireDefault(_request); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * This is a list of base plugins that most solutions will need. These plugins provide service-like capabilities * to the SDK. */ exports.default = [{ name: 'logs', fn: _logs2.default }, { name: 'config', fn: _config2.default }, { name: 'events', fn: _events2.default }, { name: 'notifications', fn: _notifications2.default }, { name: 'request', fn: _request2.default }]; /***/ }), /***/ "./src/call/callShim.js": /*!******************************!*\ !*** ./src/call/callShim.js ***! \******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _promise = __webpack_require__(/*! babel-runtime/core-js/promise */ "../../node_modules/babel-runtime/core-js/promise.js"); var _promise2 = _interopRequireDefault(_promise); exports.default = shim; var _next = __webpack_require__(/*! fcs/next */ "../fcs/next.js"); var _constants = __webpack_require__(/*! ./constants */ "./src/call/constants.js"); var _errors = __webpack_require__(/*! ../errors */ "./src/errors/index.js"); var _errors2 = _interopRequireDefault(_errors); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); var _v = __webpack_require__(/*! uuid/v4 */ "../../node_modules/uuid/v4.js"); var _v2 = _interopRequireDefault(_v); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Get the logger var log = (0, _logs.getLogManager)().getLogger('CALL'); /** * Shim for interactions between FCS calls and Redux middleware. * Because FCS uses layered callbacks, it becomes either complicated or tedious * quite quickly when trying to implement all call features. * This shim is meant to remove the callback-bloat from the middleware. * It wraps FCS' multiple step async calls into a single step. * This also handles the FCS call objects, since they cannot be stored in state. * @method shim * @param {Object} context [description] * @return {Object} api - Functions wrapped by the shim. */ // TODO: Fix this? /* eslint-disable prefer-promise-reject-errors */ // Import the "Kandy Next" version of FCS. function shim(context) { var getUsername = context.getUsername; var fcs = (0, _next.createFcs)(); /** * Map of on-going calls in FCS. * Keyed by the ID as it exists in Kandy * @type {Object} */ var ongoingCalls = {}; /** * Map of audio bridges in FCS. * Keyed by the ID as it exists in Kandy * @type {Object} */ var audioBridges = {}; /* * Information about the local, non-call video stream. */ var localStream = null; /** * Utility function to retrieve the corresponding Kandy Call IDs for * a list of FCS call object IDs * * @param {Array} fcsCalls - FCS call objects * @returns {Array} - Kandy call ID strings */ function getUnifiedSdkCalls(fcsCalls) { var map = {}; var kandyCallIds = []; if (fcsCalls.length > 0) { for (var k in ongoingCalls) { map[ongoingCalls[k].getId()] = k; } fcsCalls.forEach(function (call) { if (map[call.id]) { kandyCallIds.push(map[call.id]); delete map[call.id]; } }); } return kandyCallIds; } /** * Handler for initMedia's failure scenario. * Generates an error object based on the error code. * @method processMediaError * @param {number} errorCode [description] * @return {Object} Error object. */ function processMediaError(errorCode) { var mediaErrors = fcs.call.MediaErrors; // TODO: Don't hardcode these here. var pluginUrls = { urlWin32bit: 'https://kandy-portal.s3.amazonaws.com/public/plugin/3.1.524/Kandy_Plugin_3.1.524.exe', urlWin64bit: 'https://kandy-portal.s3.amazonaws.com/public/plugin/3.1.524/Kandy_Plugin_3.1.524_x86_64.exe', urlMacUnix: 'https://kandy-portal.s3.amazonaws.com/public/plugin/3.1.524/Kandy_Plugin_3.1.524.pkg' }; var error; switch (errorCode) { case mediaErrors.WRONG_VERSION: error = { code: mediaErrors.WRONG_VERSION, message: 'Media Plugin Version Not Supported' }; break; case mediaErrors.NEW_VERSION_WARNING: error = { code: mediaErrors.NEW_VERSION_WARNING, message: 'New Plugin Version is available,', pluginUrls: pluginUrls }; break; case mediaErrors.NOT_INITIALIZED: error = { code: mediaErrors.NOT_INITIALIZED, message: "Media couldn't be initialized." }; break; case mediaErrors.NOT_FOUND: error = { code: mediaErrors.NOT_FOUND, message: "Plugin couldn't be found!", pluginUrls: pluginUrls }; break; case mediaErrors.NO_SCREENSHARING_WARNING: error = { code: mediaErrors.NO_SCREENSHARING_WARNING, message: 'ScreenShare extension could not be found.' }; } // TODO: Provide a better error object. See PR #692 comments. return error; } /** * Attempts to initialize media. * @method initMedia * @param {Object} options FCS options for initMedia. * @return {Promise} */ function initializeMedia(options) { return new _promise2.default(function (resolve) { function initMediaSuccess() { log.info('Media initialized successfully.'); resolve({ code: 0, message: 'Media initialized.', error: false }); } function initMediaFailure(errorCode) { var result = processMediaError(errorCode); result.error = true; resolve(result); } fcs.call.initMedia(initMediaSuccess, initMediaFailure, options); }); } /** * Helper function for retrieving an ongoing call. * @method getInternalCall */ function getInternalCall(callId) { var call = ongoingCalls[callId]; if (!call) { log.info('Specified call Id does not match an on-going call.', callId); return false; } else { log.debug('Internal call retrieved.', call); return call; } } /** * Helper function for retrieving current audio bridges. * @method getInternalBridge */ function getInternalBridge(bridgeId) { var bridge = audioBridges[bridgeId]; if (!bridge) { log.info('Specified bridge Id does not match any current bridge.', bridgeId); return false; } else { log.debug('Internal bridge retrieved.', bridge); return bridge; } } /** * Handles a call state change. * Curried function so that it has the callId. * @method onStateChange * @param {string} callId - ID of the call that changed state. * @return {Function} - Function that gets attached to fcsCall.onStateChange function. */ function onStateChange(callId) { // @param {number} state - New state of the call. // @param {string} statusCode - Code representing the reason for the state change. // @param {string} reasonText - Explanation of the status code. // @param {Object} localStatusAndReason - Context from local side. Uses different codes/texts. // @param {string} localStatusAndReason.localStatusCode - Local equivalent to statusCode. // @param {string} localStatusAndReason.localReasonText - Local equivalent to reasonText. return function (state, statusCode, reasonText, localStatusAndReason) { // Treat "renegotiating" state changes as "in call" state. if (state === fcs.call.States.RENEGOTIATION) { log.debug('Renegotiating call state change. Treating as "in call".', callId); state = fcs.call.States.IN_CALL; } // Restructure FCS' state change context objects. // Only one side ever has useful information. var transition; if (statusCode && reasonText) { transition = { code: statusCode, reasonText: reasonText }; } else { transition = { code: localStatusAndReason.localStatusCode, reasonText: localStatusAndReason.localReasonText }; } // If the state change was an end, remove the call internally. // FCS has already dereference the call. if (state === fcs.call.States.ENDED) { log.debug('Call state is ended, removing internal call reference: ' + callId); delete ongoingCalls[callId]; } else { // Retrieve other call info that may have changed. var call = getInternalCall(callId); var callInfo = { remoteParticipant: call.remoteParticipant // If the FCS call has updated participant info, update the // redux call with it. Try to ensure they have domains. };var domain = getUsername() ? '@' + getUsername().split('@')[1] : ''; if (call.callerNumber) { callInfo.from = call.callerNumber; if (callInfo.from.indexOf('@') === -1) { callInfo.from += domain; } } if (call.calleeNumber) { callInfo.to = call.calleeNumber; if (callInfo.to.indexOf('@') === -1) { callInfo.to += domain; } } if (call.callerName) { callInfo.callerName = call.callerName; } if (call.calleeName) { callInfo.calleeName = call.calleeName; } // Don't try things on a joined call. They're "special". if (!call.getJoin()) { callInfo.remoteVideoState = call.getRemoteVideoState(); } } log.debug('Call state change. ID: ' + callId + ', state: ' + _constants.FCS_CALL_STATES[state] + ', context: ' + transition); // Go to the redux level. api.onCallStateChange(callId, _constants.FCS_CALL_STATES[state], transition, callInfo); }; } /** * Handles a call media state change. * Curried function so that it has the callId. * @method onStateChange * @param {string} callId - ID of the call that changed state. * @return {Function} - Function that gets attached to fcsCall.onMediaStateChange function. */ function onMediaStateChange(callId) { // @param {number} mediaState New media state of the call. return function (mediaState) { log.debug('Call media state change. ID: ' + callId + ', state: ' + _constants.FCS_ICE_MEDIA_STATES[mediaState] + '.'); // Go to the redux level. api.onMediaStateChange(callId, _constants.FCS_ICE_MEDIA_STATES[mediaState]); }; } /* * Register a listener to FCS for incoming calls. * Process the call as needed by the shim, * then go to the redux level. * @method onReceived * @param {Object} call - FCS call object. */ fcs.call.onReceived = function (call) { // Create our own call ID for storing in state. var callId = (0, _v2.default)(); ongoingCalls[callId] = call; var callInfo = { from: call.callerNumber, callerName: call.callerName, to: getUsername(), remoteVideoState: call.getRemoteVideoState(), remoteParticipant: call.remoteParticipant // TODO: Get more info from the call. // TODO: Make call info consistent between // making call and receiving call. // Register for state changes. };call.onStateChange = onStateChange(callId); call.onMediaStateChange = onMediaStateChange(callId); // Go to the redux level. api.onIncomingCall(callId, callInfo); }; var api = { /** * Endpoint for registering a listener. * Equivalent to FCS' fcs.call.onReceived. * @method onIncomingCall * @param {Object} callInfo - Information about the incoming call. */ onIncomingCall: null, /** * Endpoint for registering a listener * @method onBridgeCallsChanged * @param {Object} bridgeId - ID of the bridge whose call list has changed * * @param {Array} calls - list of call IDs */ onBridgeCallsChanged: null, /** * Endpoint for registering a listener for call state changes. * Equivalent to FCS' call.onStateChange. * @method onCallStateChange * @param {string} callId - Kandy call ID. * @param {string} state * @param {Object} transition */ onCallStateChange: null, /** * Endpoint for registering a listener for call media state changes. * Equivalent to FCS' call.onMediaStateChange. * @method onCallMediaStateChange * @param {string} callId - Kandy call ID. * @param {number} mediaState */ onCallMediaStateChange: null, // Expose some fcs methods directly. setUserAuth: fcs.setUserAuth.bind(fcs), setTokenAuth: fcs.setTokenAuth.bind(fcs), setKandyUAT: fcs.setKandyUAT.bind(fcs), setRealm: fcs.setRealm.bind(fcs), initLogging: fcs.logManager.initLogging.bind(fcs), getNotificationCallbacks: function getNotificationCallbacks() { return fcs.NotificationCallbacks; }, setup: function setup(fcsConfig) { // true = delayInitMedia, because FCS doesn't provide an initMedia // response when done on setup, but all subsequent initMedias will // be returned as a succcess. fcs.setup(fcsConfig, true); }, /** * Starts a call. * Equivalent to initializing media then starting a call. * * @method makeCall * @param {string} callId - call Id * @param {Object} options - Call options. * @return {Promise} */ makeCall: function makeCall(callId, options) { return new _promise2.default(function (resolve, reject) { /** * Callback provided to FCS' startCall. * @method startCallSuccess */ function startCallSuccess(fcsCall) { log.debug('Successful call start.', fcsCall); // Save an internal reference to the call. ongoingCalls[callId] = fcsCall; // Register for state changes. fcsCall.onStateChange = onStateChange(callId); fcsCall.onMediaStateChange = onMediaStateChange(callId); // Go back to the redux level. resolve({ callId: callId, options: options }); } /** * Callback provided to FCS' startCall. * @method startCallFailure */ function startCallFailure(errorCode) { log.debug('Failed to start call.', errorCode); var message = errorCode === 38 ? 'No media specified for call.' : 'Failed to initialize call.'; var error = { code: errorCode, message: message, type: 'call' // Go back to the redux level. };reject({ error: error, options: options }); } /** * Callback provided to FCS' initMedia. * @method mediaSuccess */ function mediaSuccess() { log.info('Call media initialized successfully.'); log.debug('Starting call with FCS options', options); // TODO: Add 'beforeunload' event listener. See kandy.call.js, line 648. fcs.call.startCall(options.from, options.contact, options.to, startCallSuccess, startCallFailure, options.isVideoEnabled, options.sendInitialVideo, options.videoResolution, { isAudioEnabled: options.isAudioEnabled, sendScreenShare: options.sendScreenShare, mediaSourceId: options.mediaSourceId, customParameters: options.customParameters }); } /** * Callback provided to FCS' initMedia. * @method initMediaFailure */ function initMediaFailure(errorCode) { var error = processMediaError(errorCode); if (error.code === fcs.call.MediaErrors.NO_SCREENSHARING_WARNING) { // This is not a failure case, just a warning. log.warn('Media initialized, but could not detect extension for screensharing.'); mediaSuccess(); } else { log.debug('Call media failed to initialize. Check media support.', error); error.type = 'media'; reject({ error: error, options: options }); } } // Options specifically for fcs.call.initMedia. var mediaOptions = { // TODO: Only init media when needed. See kandy.call.js, line 625. // TODO: Let default options be passed-in to plugin. remoteVideoContainer: options.remoteVideoContainer, localVideoContainer: options.localVideoContainer }; log.debug('Initializing call media.', mediaOptions); // Start by calling FCS' initMedia. // Then go into the shim's success / failure callback. // Then we go to the middleware's success / failure callback. // TODO: Don't call this directly here; use the api.initMedia function. // Change it when the middleware is refactored into sagas. fcs.call.initMedia(mediaSuccess, initMediaFailure, mediaOptions); }); }, /** * Answers an incoming call. * @method answerCall * @param {string} callId Id of the call to answer. * @param {Object} options Call options. * @return {Promise} */ answerCall: function answerCall(callId, options) { return new _promise2.default(function (resolve, reject) { var call = ongoingCalls[callId]; if (!call) { log.info('Specified call Id does not match an on-going call.', callId); reject({ type: 'call', callId: callId, error: 'Invalid call id.' }); } // Callback provided to FCS' call.answer. function answerSuccess() { log.debug('Successful answer call.', call); resolve({ callId: callId }); } // Callback provided to FCS' call.answer. function answerFailure(errorCode) { log.debug('Failed to answer call.', errorCode); var error = { code: errorCode, message: 'Failed to answer call.', type: 'call' // Go back to the redux level. };reject({ error: error, callId: callId }); } // Callback provided to FCS' initMedia function mediaSuccess() { log.info('Call media initialized successfully.'); log.debug('Answering call with FCS options', { isVideoEnabled: options.isVideoEnabled, isAudioEnabled: options.isAudioEnabled, videoResolution: options.videoResolution, sendInitialVideo: options.sendInitialVideo }); call.answer(answerSuccess, answerFailure, options.isVideoEnabled, options.videoResolution, { isAudioEnabled: options.isAudioEnabled, customParameters: options.customParameters }); } // Callback provided to FCS' initMedia function mediaFailure(errorCode) { var error = processMediaError(errorCode); if (error.code === fcs.call.MediaErrors.NO_SCREENSHARING_WARNING) { // This is not a failure case, just a warning. log.warn('Media initialized, but could not detect extension for screensharing.'); mediaSuccess(); } else { log.debug('Call media failed to initialize. Check media support.', error); error.type = 'media'; reject({ error: error, options: options }); } } // Options specifically for fcs.call.initMedia. var mediaOptions = { // TODO: Only init media when needed. See kandy.call.js, line 625. // TODO: Let default options be passed-in to plugin/shim. remoteVideoContainer: options.remoteVideoContainer, localVideoContainer: options.localVideoContainer }; log.debug('Initializing call media.', mediaOptions); // Start by calling FCS' initMedia. // Then go into the shim's success / failure callback. // Then we go to the middleware's success / failure callback. // TODO: Don't call this directly here; use the api.initMedia function. // Change it when the middleware is refactored into sagas. fcs.call.initMedia(mediaSuccess, mediaFailure, mediaOptions); }); }, /** * Ignore an incoming call. * @method ignoreCall * @param {string} callId FCS id of the call to ignore. * @return {Promise} */ ignoreCall: function ignoreCall(callId) { return new _promise2.default(function (resolve, reject) { function ignoreSuccess() { log.info('Successfully ignored call.'); // Go back to the redux level. resolve({ callId: callId }); } function ignoreFailure(error) { log.info('Failed to ignore call.'); // Go back to the redux level. reject({ error: error, callId: callId }); } var call = getInternalCall(callId); if (call) { call.ignore(ignoreSuccess, ignoreFailure); } else { reject({ callId: callId, error: 'Call not found. ' }); } }); }, /** * Reject an incoming call. * @method rejectCall * @param {string} callId FCS id of the call to reject. * @return {Promise} */ rejectCall: function rejectCall(callId) { return new _promise2.default(function (resolve, reject) { function rejectSuccess() { log.info('Successfully rejected call.'); // Go back to the redux level. resolve({ callId: callId }); } function rejectFailure(error) { log.info('Failed to reject call.'); // Go back to the redux level. reject({ error: error, callId: callId }); } var call = getInternalCall(callId); if (call) { call.reject(rejectSuccess, rejectFailure); } else { reject({ callId: callId, error: 'Call not found. ' }); } }); }, /** * Ends a call. * @method endCall * @param {string} callId Id of the call to end. * @return {Promise} */ endCall: function endCall(callId) { return new _promise2.default(function (resolve, reject) { function endSuccess() { log.info('Successfully ended call.'); // Go back to the redux level. resolve({ callId: callId }); } function endFailure(error) { log.info('Failed to end call.'); // Go back to the redux level. reject({ error: error, callId: callId }); } var call = getInternalCall(callId); if (call) { call.end(endSuccess, endFailure); } else { reject({ callId: callId, error: 'Call not found.' }); } }); }, /** Mutes a call. * @method muteCall * @param {string} callId The ID of the call being acted on. * @return {Promise} */ muteCall: function muteCall(callId) { return new _promise2.default(function (resolve, reject) { var call = getInternalCall(callId); if (call) { // FCS' mute function does not take callbacks. call.mute(); log.info('Call muted.'); resolve({ callId: callId }); } else { reject({ callId: callId, error: 'Call not found.' }); } }); }, /** * Unmutes a call. * @method unMuteCall * @param {string} callId The ID of the call being acted on. * @return {Promise} */ unMuteCall: function unMuteCall(callId) { return new _promise2.default(function (resolve, reject) { var call = getInternalCall(callId); if (call) { // FCS' unmute function does not take callbacks. call.unmute(); log.info('Call unmuted.'); resolve({ callId: callId }); } else { reject({ callId: callId, error: 'Call not found.' }); } }); }, /** * Gets custom parameters of call. * @method getCustomParameters * @param {string} callId The ID of the call being acted on. * @return {Array.<{name: string, value:string}>} Custom parameters of the call. */ getCustomParameters: function getCustomParameters(callId) { var call = getInternalCall(callId); if (call) { return call.getCustomParameters(); } }, /** * Sets custom parameters of call. * @method setCustomParameters * @param {string} callId The ID of the call being acted on. * @param {Array.<{name: string, value:string}>} customParameters Custom parameters for the call. */ setCustomParameters: function setCustomParameters(callId, customParameters) { var call = getInternalCall(callId); if (call) { call.setCustomParameters(customParameters); } }, /** * Starts video for a call. * @method startVideo * @param {string} callId The ID of the call being acted on. * @param {Object} params * @param {Object} params.videoResolution * @return {Promise} */ startVideo: function startVideo(callId, params) { return new _promise2.default(function (resolve, reject) { function startVideoSuccess() { log.info('Call video started successfully.'); // Go back to the redux level. resolve({ callId: callId, params: params }); } function startVideoFailure(error) { log.info('Failed to start call video.'); // Go back to the redux level. reject({ callId: callId, params: params, error: error }); } var call = getInternalCall(callId); if (call) { call.videoStart(startVideoSuccess, startVideoFailure, params.videoResolution); } else { reject({ callId: callId, error: 'Call not found.' }); } }); }, /** * Stops video for a call. * @method stopVideo * @param {string} callId The ID of the call being acted on. * @return {Promise} */ stopVideo: function stopVideo(callId) { return new _promise2.default(function (resolve, reject) { function stopVideoSuccess() { log.info('Call video stopped successfully.'); // Go back to the redux level. resolve({ callId: callId }); } function stopVideoFailure(error) { log.info('Failed to stop call video.'); // Go back to the redux level. reject({ callId: callId, error: error }); } var call = getInternalCall(callId); if (call) { call.videoStop(stopVideoSuccess, stopVideoFailure); } else { reject({ callId: callId, error: 'Call not found.' }); } }); }, /** * Holds a call. * @method holdCall * @param {string} callId The ID of the call being acted on. * @return {Promise} */ holdCall: function holdCall(callId) { return new _promise2.default(function (resolve, reject) { function holdSuccess() { log.info('Successfully held call.'); // Go back to the redux level. resolve({ callId: callId }); } function holdFailure(error) { log.info('Failed to hold call.'); // Go back to the redux level. reject({ error: error, callId: callId }); } var call = getInternalCall(callId); if (call) { call.hold(holdSuccess, holdFailure); } else { reject({ callId: callId, error: 'Call not found.' }); } }); }, /** * UnHolds a call. * @method unHoldCall * @param {string} callId The ID of the call being acted on. * @return {Promise} */ unHoldCall: function unHoldCall(callId) { return new _promise2.default(function (resolve, reject) { function unHoldSuccess() { log.info('Successfully unheld call.'); // Go back to the redux level. resolve({ callId: callId }); } function unHoldFailure(error) { log.info('Failed to unhold call.'); // Go back to the redux level. reject({ error: error, callId: callId }); } var call = getInternalCall(callId); if (call) { call.unhold(unHoldSuccess, unHoldFailure); } else { reject({ callId: callId, error: 'Call not found.' }); } }); }, /** * Starts screensharing. * @param {string} callId Id of the call being acted on. * @param {Object} params * @param {string} params.mediaSourceId Id of the media screen to share. * @param {number} [params.width=1024] The width of the screen to request. * @param {number} [params.height=768] The height of the screen to request. * @param {number} [params.frameRate=15] The number of frames per second to request. * @param {Function} screensharingStopped Callback function for when media is stopped manually. */ startScreenshare: function startScreenshare(callId, params, screensharingStopped) { return new _promise2.default(function (resolve, reject) { function startScreenshareSuccess() { log.info('Successfully shared screen.'); // Go back to the redux level. resolve({ callId: callId }); } function startScreenshareFailure(error) { log.info('Failed to share screen.'); // Go back to the redux level. reject({ callId: callId, params: params, error: error }); } // The mediaSourceId property is required. if (!params.hasOwnProperty('mediaSourceId')) { reject({ callId: callId, error: 'No media source ID provided.' }); } var call = getInternalCall(callId); if (call) { call.screenSharingStart(startScreenshareSuccess, startScreenshareFailure, screensharingStopped, params); } else { reject({ callId: callId, error: 'Call not found.' }); } }); }, /** * Stops screensharing. * @param {string} callId Id of the call being acted on. */ stopScreenshare: function stopScreenshare(callId) { return new _promise2.default(function (resolve, reject) { function stopScreenshareSuccess() { log.info('Successfully stopped screenshare.'); // Go back to the redux level. resolve({ callId: callId }); } function stopScreenshareFailure(error) { log.info('Failed to stop screenshare.'); // Go back to the redux level. reject({ callId: callId, error: error }); } var call = getInternalCall(callId); if (call) { call.screenSharingStop(stopScreenshareSuccess, stopScreenshareFailure); } else { reject({ callId: callId, error: 'Call not found.' }); } }); }, /** * Sends a DTMF tone over a call. * @method sendDTMF * @param {string} callId The ID of the call being acted on. * @param {string} tone DTMF tone to send. * @return {Promise} */ sendDTMF: function sendDTMF(callId, tone) { return new _promise2.default(function (resolve, reject) { var call = getInternalCall(callId); if (call) { // FCS' sendDTMF does not take callbacks. call.sendDTMF(tone); resolve(); } else { reject({ callId: callId, error: 'Call not found.' }); } }); }, /** * Ecplicitely sends custom parameters of a call. * @method sendCustomParameters * @param {string} callId The ID of the call being acted on. * @return {Promise} */ sendCustomParameters: function sendCustomParameters(callId) { return new _promise2.default(function (resolve, reject) { var call = getInternalCall(callId); function sendCustomParametersSuccess() { log.info('Successfully sent custom parameters.'); // Go back to the redux level. resolve({ callId: callId }); } function sendCustomParametersFailure(error) { log.info('Failed to send custom parameters.'); // Go back to the redux level. reject({ callId: callId, error: error }); } if (call) { // FCS' sendCustomParameters. call.sendCustomParameters(sendCustomParametersSuccess, sendCustomParametersFailure); } else { reject({ callId: callId, error: 'Call not found.' }); } }); }, /** * Forwards a call to another user. * @method forwardCall * @param {string} callId The ID of the call being acted on. * @param {string} destination Full user ID of another user. * @return {Promise} */ forwardCall: function forwardCall(callId, destination) { return new _promise2.default(function (resolve, reject) { function forwardSuccess() { log.info('Successfully forwarded call.'); // Go back to the redux level. resolve({ callId: callId }); } function forwardFailure(errorCode) { log.info('Failed to forward call.'); // Go back to the redux level. var error = { code: errorCode, message: 'Failed to forward call.' }; reject({ callId: callId, error: error }); } var call = getInternalCall(callId); if (call) { call.forward(destination, forwardSuccess, forwardFailure); } else { reject({ callId: callId, error: { message: 'Failed to forward call.' } }); } }); }, /** * Transfers a call to another user. * @method directTransfer * @param {string} callId The ID of the call being acted on. * @param {string} destination Full user ID of another user. * @return {Promise} */ directTransfer: function directTransfer(callId, destination) { return new _promise2.default(function (resolve, reject) { function transferSuccess() { log.info('Successfully transfered call.'); // Go back to the redux level. resolve({ callId: callId }); } function transferFailure(errorCode) { log.info('Failed to transfer call.'); // Go back to the redux level. var error = { code: errorCode, message: 'Failed to transfer call.' }; reject({ callId: callId, error: error }); } var call = getInternalCall(callId); if (call) { call.directTransfer(destination, transferSuccess, transferFailure); } else { reject({ callId: callId, error: { message: 'Failed to transfer call.' } }); } }); }, /** * Transfers a call to another call. * @method consultativeTransfer * @param {string} callId The ID of the call being acted on. * @param {string} destination The callId of another call. * @return {Promise} */ consultativeTransfer: function consultativeTransfer(callId, destination) { return new _promise2.default(function (resolve, reject) { function transferSuccess() { log.info('Successfully transfered call.'); // Go back to the redux level. resolve({ callId: callId }); } function transferFailure(errorCode) { log.info('Failed to transfer call.'); // Go back to the redux level. var error = { code: errorCode, message: 'Failed to transfer call.' }; reject({ callId: callId, error: error }); } var call = getInternalCall(callId); var dest = getInternalCall(destination); if (call && dest) { call.consultativeTransfer(dest.getId(), transferSuccess, transferFailure); } else if (!call) { reject({ callId: callId, error: { message: 'Invalid call id.' } }); } else { reject({ callId: callId, error: { message: 'Invalid destination.' } }); } }); }, /** * Joins a call with another call. * @method joinCall * @param {string} callId The ID of the call being acted on. * @param {string} destination The callId of another call. * @param {Object} options - Media options. * @return {Promise} */ joinCall: function joinCall(callId, destination, options) { return new _promise2.default(function (resolve, reject) { function joinSuccess(joinedCall) { log.info('Successfully joined call.'); // Create our own call ID for storing in state. var joinedCallId = (0, _v2.default)(); ongoingCalls[joinedCallId] = joinedCall; // Register for state changes. joinedCall.onStateChange = onStateChange(joinedCallId); joinedCall.onMediaStateChange = onMediaStateChange(joinedCallId); // Go back to the redux level. resolve({ callId: joinedCallId, joinedCalls: [callId, destination], callState: _constants.FCS_CALL_STATES[joinedCall.callState] }); } function joinFailure(errorCode) { log.info('Failed to join call.'); // Go back to the redux level. var error = { code: errorCode, message: 'Failed to join call.' }; reject({ callId: callId, joinedCalls: [callId, destination], error: error }); } initializeMedia(options).then(function (result) { if (result.code === 0 || result.code === fcs.call.MediaErrors.NO_SCREENSHARING_WARNING) { // Media initialized, perform the join operation. var call = getInternalCall(callId); var dest = getInternalCall(destination); if (call && dest) { var withVideo = call.localVideo || dest.localVideo; call.join(dest, joinSuccess, joinFailure, withVideo); } else if (!call) { reject({ callId: callId, error: { message: 'Invalid call id.' } }); } else { reject({ callId: destination, error: { message: 'Invalid destination.' } }); } } else { // Failed to initialize media; return an error. reject({ callId: callId, error: { message: 'Failed to initialize call media: ' + result.message, type: 'media', code: result.code } }); } }); }); }, /** * Sets the default devices for FCS to use for new calls. * @method setDefaultDevices * @param {Object} devices * @return {Promise} */ setDefaultDevices: function setDefaultDevices(devices) { return new _promise2.default(function (resolve, reject) { function onSpeakerSuccess() { if (devices.speaker) { log.info('Set selected speaker as default: ' + devices.speaker + '.'); } if (devices.camera) { fcs.call.setSelectedCameraId(devices.camera); log.info('Set selected camera as default: ' + devices.camera + '.'); } if (devices.microphone) { fcs.call.setSelectedMicrophoneId(devices.microphone); log.info('Set selected microphone as default: ' + devices.microphone + '.'); } resolve(devices); } function onSpeakerFailure(error) { log.info('Failed to set default speaker.', error); reject({ device: 'speaker', deviceId: devices.speaker, error: error }); } // Only setSelectedSpeakerId has callbacks, so do that one first. if (devices.speaker) { fcs.call.setSelectedSpeakerId(devices.speaker, onSpeakerSuccess, onSpeakerFailure); } else { // If we aren't setting the speaker, go straight to the success callback. onSpeakerSuccess(); } }); }, /** * Prompts for permsiion to use media. * @method promptUserMedia * @param {Object} params * @param {boolean} params.video * @param {boolean} params.audio * @return {Promise} */ promptUserMedia: function promptUserMedia(params) { return new _promise2.default(function (resolve, reject) { function promptUserMediaSuccess() { // Go back to the redux level. log.info('Media permissions granted.'); resolve({ params: params }); } function promptUserMediaFailure(error) { // Go back to the redux level. log.info('Media permissions not granted.', error); var kandyError = void 0; // Convert the callShim error object into a KandyError. kandyError = new _errors2.default({ message: 'Media permissions not granted.', code: error }); reject({ params: params, kandyError: kandyError }); } fcs.call.getUserMedia(promptUserMediaSuccess, promptUserMediaFailure, params); }); }, /** * Changes speaker for on-going calls. * @method changeSpeaker * @param {string} speakerId * @return {Promise} */ changeSpeaker: function changeSpeaker(speakerId) { return new _promise2.default(function (resolve, reject) { function changeSpeakerSuccess() { log.info('Successfully changed speaker.'); resolve(speakerId); } function changeSpeakerFailure(error) { log.info('Failed to change speaker.', error); reject({ speakerId: speakerId, error: error }); } if (speakerId) { fcs.call.changeSpeaker(speakerId, changeSpeakerSuccess, changeSpeakerFailure); } else { reject({ error: 'Invalid speaker id provided.' }); } }); }, /** * Changes the camera/microphone used for the specified call. * @method changeInputDevices * @param {string} callId * @return {Promise} */ changeInputDevices: function changeInputDevices(callId) { return new _promise2.default(function (resolve, reject) { function changeDevicesSuccess() { resolve(callId); } function changeDevicesFailure(fcsError) { reject({ callId: callId, error: fcsError }); } var call = getInternalCall(callId); if (call) { fcs.call.changeDevices({ call: call }, changeDevicesSuccess, changeDevicesFailure); } else { reject({ callId: callId, error: 'Call not found. ' }); } }); }, /** * Starts the local video stream and displays it to the user. * @method startLocalVideo * @param {HTMLElement} container The container to use for local video. * @return {Promise} */ startLocalVideo: function startLocalVideo(container) { return new _promise2.default(function (resolve, reject) { function getUserMediaSuccess(streamInfo) { // Render the local video into the container. fcs.call.createStreamRenderer(streamInfo.streamURL, container, { muted: true }); // Store the local stream's info. localStream = { stream: streamInfo, container: container }; log.info('Started local video stream.'); resolve(container); } function getUserMediaFailure() { log.info('Failed to start local video.'); var error = { message: 'Could not start local video.', type: 'video' }; reject({ error: error }); } if (localStream) { log.info('Local video is already being displayed.'); var error = { message: 'Local video is already being displayed. Stop local video before re-starting.', type: 'generic' }; reject({ error: error }); return; } else if (!container) { var _error = { message: 'No video container provided; cannot start local video.', type: 'generic' }; reject({ error: _error }); return; } // Re-use the callShim's initMedia functionality. initializeMedia().then(function (result) { if (result.code === 0 || result.code === fcs.call.MediaErrors.NO_SCREENSHARING_WARNING) { // Get the local user video media. fcs.call.getUserMedia(getUserMediaSuccess, getUserMediaFailure, { audio: false, video: true }); } else { // initMedia error. var _error2 = { message: 'Could not initialize media. Please check initMedia.', type: 'media' }; reject({ error: _error2 }); } }); }); }, /** * Stops the local video stream created in `startLocalVideo`. * @method stopLocalVideo * @return {Promise} */ stopLocalVideo: function stopLocalVideo() { return new _promise2.default(function (resolve, reject) { // Only act on the stream that was started earlier via `startLocalVideo`. if (localStream) { fcs.call.disposeStreamRenderer(localStream.container); fcs.call.removeStreamById(localStream.stream.id); // Remove the callShim's 'flag' for local video. localStream = null; log.info('Local video stream stopped.'); resolve(); } else { log.info('No local video stream to stop.'); reject({ message: 'No on-going local stream to stop.' }); } }); }, /** * Attempts to initialize media. * @method initMedia * @param {Object} options FCS options for initMedia. * @return {Promise} */ initMedia: initializeMedia, /** * Creates a local bridge for audio calls. * @method createLocalAudioBridge * @param {string} bridgeId * @param {Object} options * @return {Promise} */ createLocalAudioBridge: function createLocalAudioBridge(bridgeId) { return new _promise2.default(function (resolve, reject) { function createBridgeSuccess(bridge) { log.debug('Successfully created bridge.', bridgeId); /* * Callback method allows FCS to send updated call lists * after calls are added or removed, providing us with the opportunity * to ensure the bridge's state is up to date in Kandy * * @param {Array} calls */ bridge.onCallsChange = function (fcsCalls) { var calls = getUnifiedSdkCalls(fcsCalls); api.onBridgeCallsChanged(bridgeId, calls); }; // Save an internal reference to the bridge. audioBridges[bridgeId] = bridge; resolve(); } function createBridgeFailure() { log.debug('Failed to create bridge.', bridgeId); // Error is either that the FCS media isn't set up (ie. user // not logged in) or feature not supported in browser. var error = new _errors2.default({ message: 'Feature not supported by browser.', code: _errors.bridgeCodes.NOT_SUPPORTED }); reject(error); } fcs.call.createLocalAudioBridge(createBridgeSuccess, createBridgeFailure); }); }, /** * Closes an existing audio bridge. * @method closeAudioBridge * @param {string} bridgeId * @return {Promise} */ closeAudioBridge: function closeAudioBridge(bridgeId) { return new _promise2.default(function (resolve, reject) { var bridge = getInternalBridge(bridgeId); if (bridge) { bridge.close(); resolve(); } else { var error = new _errors2.default({ message: 'Provided ID does not match an existing bridge.', code: _errors.bridgeCodes.INVALID_INPUT }); reject(error); } }); }, addCallToBridge: function addCallToBridge(bridgeId, callId) { return new _promise2.default(function (resolve, reject) { function addCallSuccess() { log.debug('Successfully added call to bridge.', bridgeId); resolve(); } function addCallFailure(errCode) { log.debug('Failed to add call to bridge.', errCode); var error = void 0; if (errCode === 29) { // FCS' "entry already exists" code. error = new _errors2.default({ message: 'Call already added to bridge.', code: _errors.bridgeCodes.ALREADY_EXISTS }); } else if (errCode === 24) { // FCS' "media not found" code. error = new _errors2.default({ message: 'Failed to find media.', code: _errors.bridgeCodes.MEDIA_NOT_FOUND }); } else if (errCode === 3) { // FCS' "state" code. error = new _errors2.default({ message: 'Invalid state.', code: _errors.bridgeCodes.INVALID_STATE }); } else { error = new _errors2.default({ message: 'An unknown error occurred.', code: _errors.bridgeCodes.UNKNOWN_ERROR }); } reject(error); } var bridge = getInternalBridge(bridgeId); var call = getInternalCall(callId); if (bridge && call) { bridge.add(call, addCallSuccess, addCallFailure); } else { var error = new _errors2.default({ message: 'A provided ID did not match an existing bridge and/or call.', code: _errors.bridgeCodes.INVALID_INPUT }); reject(error); } }); }, /** * Removes a call from the specified audio bridge. * @method removeCallFromBridge */ removeCallFromBridge: function removeCallFromBridge(bridgeId, callId) { return new _promise2.default(function (resolve, reject) { function removeCallSuccess() { log.debug('Successfully removed call from bridge.', bridgeId); resolve(); } function removeCallFailure(err) { log.debug('Failed to remove call from bridge.', err); var error = void 0; if (err === 22) { // FCS' "invalid parameter" code. error = new _errors2.default({ message: 'Specified call not in bridge.', code: _errors.bridgeCodes.NOT_FOUND }); } else { error = new _errors2.default({ message: 'An unknown error occurred.', code: _errors.bridgeCodes.UNKNOWN_ERROR }); } reject(error); } var bridge = getInternalBridge(bridgeId); var call = getInternalCall(callId); if (bridge && call) { bridge.remove(call, removeCallSuccess, removeCallFailure); } else { var error = new _errors2.default({ message: 'A provided ID did not match an existing bridge and/or call.', code: _errors.bridgeCodes.INVALID_INPUT }); reject(error); } }); }, /** * Mutes local audio for all calls in the bridge. * @method muteAudioBridge */ muteAudioBridge: function muteAudioBridge(bridgeId) { return new _promise2.default(function (resolve, reject) { var bridge = getInternalBridge(bridgeId); if (bridge) { bridge.muteLocalAudio(); resolve(); } else { var error = new _errors2.default({ message: 'Provided ID does not match an existing bridge.', code: _errors.bridgeCodes.INVALID_INPUT }); reject(error); } }); }, /** * Unmutes local audio for all calls in the bridge. * @method unmuteAudioBridge */ unmuteAudioBridge: function unmuteAudioBridge(bridgeId) { return new _promise2.default(function (resolve, reject) { var bridge = getInternalBridge(bridgeId); if (bridge) { bridge.unmuteLocalAudio(); resolve(); } else { var error = new _errors2.default({ message: 'Provided ID does not match an existing bridge.', code: _errors.bridgeCodes.INVALID_INPUT }); reject(error); } }); } }; return api; } /***/ }), /***/ "./src/call/constants.js": /*!*******************************!*\ !*** ./src/call/constants.js ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ICE_MEDIA_STATES = exports.FCS_ICE_MEDIA_STATES = exports.WEBRTC_DEVICE_KINDS = exports.CALL_STATES = exports.FCS_CALL_STATES = undefined; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); /** * Helper function. Converts an object so that its keys are the same as its values. * @method mapValuesToKeys * @param {Object} source * @return {Object} */ function mapValuesToKeys(source) { return (0, _fp.mapKeys)(function (value) { return source[value]; })(source); } /** * Enum of FCS call states. * Key is the "code" that FCS uses, and value is the text representation. * These are taken from FCS callManager.js, but inversed. * See `fcs.call.States`. * @type {Object} */ var FCS_CALL_STATES = exports.FCS_CALL_STATES = { 0: 'IN_CALL', 1: 'ON_HOLD', 2: 'RINGING', 3: 'ENDED', 4: 'REJECTED', 5: 'OUTGOING', 6: 'INCOMING', 7: 'ANSWERING', 8: 'JOINED', 9: 'RENEGOTIATION', 10: 'TRANSFERRED', 11: 'ON_REMOTE_HOLD', 12: 'CALL_IN_PROGRESS', 13: 'EARLY_MEDIA', 14: 'TRANSFER_FAILURE', 15: 'REPLACING' /** * Call states. * Same as FCS_CALL_STATES, except both key and value are the text representation. * @name CALL_STATES */ };var CALL_STATES = exports.CALL_STATES = mapValuesToKeys(FCS_CALL_STATES); /* * A conversion from MediaDeviceInfo.kind values to their more common terms. * See: https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/kind */ var WEBRTC_DEVICE_KINDS = exports.WEBRTC_DEVICE_KINDS = { audioinput: 'microphone', videoinput: 'camera', audiooutput: 'speaker' /** * Enum of ICE media states. * These are taken from FCS call, but inversed. * See `fcs.call.MediaStates`. * @name FCS_ICE_MEDIA_STATES * @type {Object} */ };var FCS_ICE_MEDIA_STATES = exports.FCS_ICE_MEDIA_STATES = { 0: 'NEW', 1: 'CHECKING', 2: 'CONNECTED', 3: 'COMPLETED', 4: 'FAILED', 5: 'DISCONNECTED', 6: 'CLOSED' /** * ICE media states. * Same as FCS_ICE_MEDIA_STATES, except both key and value are the text representation. * @name ICE_MEDIA_STATES */ };var ICE_MEDIA_STATES = exports.ICE_MEDIA_STATES = mapValuesToKeys(FCS_ICE_MEDIA_STATES); /***/ }), /***/ "./src/call/index.js": /*!***************************!*\ !*** ./src/call/index.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = callsLink; var _callShim = __webpack_require__(/*! ./callShim */ "./src/call/callShim.js"); var _callShim2 = _interopRequireDefault(_callShim); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _actionTypes = __webpack_require__(/*! ../auth/interface/actionTypes */ "./src/auth/interface/actionTypes.js"); var authActionTypes = _interopRequireWildcard(_actionTypes); var _actionTypes2 = __webpack_require__(/*! ../notifications/interface/actionTypes */ "./src/notifications/interface/actionTypes.js"); var notiActionTypes = _interopRequireWildcard(_actionTypes2); var _selectors = __webpack_require__(/*! ../auth/interface/selectors */ "./src/auth/interface/selectors.js"); var _actions = __webpack_require__(/*! ../config/interface/actions */ "./src/config/interface/actions.js"); var _sagas = __webpack_require__(/*! ./sagas */ "./src/call/sagas.js"); var _actions2 = __webpack_require__(/*! ../events/interface/actions */ "./src/events/interface/actions.js"); var _errors = __webpack_require__(/*! ../errors */ "./src/errors/index.js"); var _errors2 = _interopRequireDefault(_errors); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); var _logManager = __webpack_require__(/*! ../logs/logManager */ "./src/logs/logManager.js"); var _interface = __webpack_require__(/*! ./interface */ "./src/call/interface/index.js"); var _interface2 = _interopRequireDefault(_interface); var _actions3 = __webpack_require__(/*! ./interface/actions */ "./src/call/interface/actions/index.js"); var _actionTypes3 = __webpack_require__(/*! ./interface/actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes3); var _selectors2 = __webpack_require__(/*! ./interface/selectors */ "./src/call/interface/selectors.js"); var _events = __webpack_require__(/*! ./interface/events */ "./src/call/interface/events.js"); var _events2 = _interopRequireDefault(_events); var _constants = __webpack_require__(/*! ../constants */ "./src/constants.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // get logger // Import the interface to implement. // Import a call shim between FCS calls and Kandy Next. // It is used to handle FCS' call object, since we cannot put it in sate. var logMgr = (0, _logs.getLogManager)(); // Constants // Utilities. var log = logMgr.getLogger('CALL'); /** * Configuration options for the call feature. * @public * @name configs.call * @memberof configs * @instance * @param {Object} call The call configuration object. * @param {Object} [call.callDefaults] Default options to be used when making/answering a call. * @param {string} [call.chromeExtensionId] ID of the Kandy Screenshare Extension being used for screenshare of Google Chrome. * @param {boolean} [call.webrtcdtls=true] Whether to enable the webRTC DTLS setting for calls. */ /** * CallsLink factory. For call-related configs, see the makeCall API documentation. * @method callsLink * @param {Object} [options={}] Plugin configs. See above. * @return {Object} Call plugin. */ function callsLink() { var _marked = /*#__PURE__*/_regenerator2.default.mark(init); var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var defaultOptions = { // Values used as defaults for making/answering a call. callDefaults: { isAudioEnabled: true, isVideoEnabled: true, sendInitialVideo: false, remoteVideoContainer: undefined, localVideoContainer: undefined }, // Values passed to FCS. webrtcdtls: true, chromeExtensionId: undefined, serverProvidedTurnCredentials: false, iceserver: [] }; var callDefaults = (0, _fp.defaults)(defaultOptions.callDefaults, options.callDefaults); options = (0, _fp.defaults)(defaultOptions, options); options.callDefaults = callDefaults; function init() { return _regenerator2.default.wrap(function init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.put)((0, _actions.update)(options, _interface2.default.name)); case 2: _context.next = 4; return (0, _effects.put)((0, _actions2.mapEvents)(_events2.default)); case 4: _context.next = 6; return (0, _effects.fork)(_sagas.checkMediaDevices); case 6: case 'end': return _context.stop(); } } }, _marked, this); } return { middleware: middleware, api: _interface2.default.api, capabilities: ['call'], name: _interface2.default.name, reducer: _interface2.default.reducer, init: init, sagas: [_sagas.watchCheckMediaDevices, _sagas.onDeviceChange] }; } function middleware(_ref) { var dispatch = _ref.dispatch, getState = _ref.getState; var config = {}; var shimContext = { // Provide the values as a function, so that we // don't call getState before the store is created. getUsername: function getUsername() { return (0, _selectors.getUserInfo)(getState()).username; } }; var callShim = (0, _callShim2.default)(shimContext); // FCS logger. function fcsLogger(loggerName, level, logObject) { var msg = logObject.timestamp + ' - ' + loggerName + ' - ' + level + ' - ' + logObject.message; // Log _all_ FCS logs if we're at least at debug level. if (logMgr.getLevel() <= _logManager.logLevels.DEBUG) { log.log(msg); } } /* * Register a listener on FCS to dispatch an action when we receive a call. * @method onReceived * @param {Object} call An FCS call object. */ callShim.onIncomingCall = function (callId, callInfo) { dispatch(_actions3.callsActions.callIncoming(callId, callInfo)); }; callShim.onCallStateChange = function (callId, state, transition) { var callInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; // Add information about the transition that we can determine using // previous state and new state. var prevCallState = (0, _selectors2.getCallById)(getState(), callId); transition.prevState = prevCallState.state; transition.newState = state; // TODO: Once this if/else chain grows, move this as a utility. if (prevCallState.state === 'RINGING' && state === 'IN_CALL') { // Call is first established. callInfo.startTime = Date.now(); transition.event = 'callEstablished'; } else if (prevCallState.state === state && prevCallState.remoteVideoState !== callInfo.remoteVideoState) { // If only the remoteVideoState property changed... transition.event = 'remoteVideoChange'; } else if (state === 'ENDED') { var now = Date.now(); callInfo.endTime = now; // If there isn't a start time, then the call was never completed. // Meaning it's duration was 0, so set the start time appropriately. if (!prevCallState.startTime) { callInfo.startTime = now; } } // Dispatch an action on state change. dispatch(_actions3.callsActions.callStateChange(callId, state, transition, callInfo)); }; callShim.onMediaStateChange = function (callId, mediaState) { // Dispatch an action on media state change. dispatch(_actions3.callsActions.callMediaStateChange(callId, mediaState)); }; callShim.onBridgeCallsChanged = function (bridgeId, calls) { // Dispatch an action on bridge state change dispatch(_actions3.audioBridgeActions.updateAudioBridgeCalls(bridgeId, calls)); }; return function (next) { return function (action) { switch (action.type) { case actionTypes.SET_DEFAULT_DEVICES: { log.debug('Setting default call devices.', action.payload); var devices = (0, _fp.pick)(['camera', 'microphone', 'speaker'], action.payload); callShim.setDefaultDevices(devices).then(function (setDevices) { dispatch(_actions3.devicesActions.setDefaultDevicesFinish({ devices: setDevices })); }).catch(function (error) { dispatch(_actions3.devicesActions.setDefaultDevicesFinish({ error: error })); }); break; } case actionTypes.PROMPT_USER_MEDIA: { log.debug('Getting user media.'); callShim.promptUserMedia(action.payload).then(function (_ref2) { var params = _ref2.params; dispatch(_actions3.mediaActions.promptUserMediaFinish(params)); }).catch(function (_ref3) { var params = _ref3.params, kandyError = _ref3.kandyError; dispatch(_actions3.mediaActions.promptUserMediaFinish(params, kandyError)); }); break; } case actionTypes.CHANGE_SPEAKER: { log.debug('Change current speaker used for call audio.', action.payload); callShim.changeSpeaker(action.payload).then(function (speakerId) { dispatch(_actions3.devicesActions.changeSpeakerFinish({ speakerId: speakerId })); }).catch(function (_ref4) { var speakerId = _ref4.speakerId, error = _ref4.error; dispatch(_actions3.devicesActions.changeSpeakerFinish({ speakerId: speakerId, error: error })); }); break; } case actionTypes.CHANGE_INPUT_DEVICES: { log.debug('Changing current camera/microphone used for call.', action.payload.callId); callShim.changeInputDevices(action.payload.callId).then(function (callId) { dispatch(_actions3.devicesActions.changeInputDevicesFinish({ callId: callId })); }).catch(function (_ref5) { var callId = _ref5.callId, error = _ref5.error; dispatch(_actions3.devicesActions.changeInputDevicesFinish({ callId: callId, error: error })); }); break; } case authActionTypes.CONNECT: { // Set up FCS logging if enabled. // Do it here since it's the earliest not-at-store-creation point // where we use FCS. // TODO: Selector for logs state? if (getState().config.logs.enableFcsLogs) { callShim.initLogging(fcsLogger, true); } var _action$payload$crede = action.payload.credentials, username = _action$payload$crede.username, password = _action$payload$crede.password; // Do this here since it's the last point we have access to the password. callShim.setUserAuth(username, password); // Retrieve configs for use within the middleware scope. // This has to be done after init*, hence after connect, but only // needed once, so not at the base of the middleware scope. config = (0, _selectors2.getCallConfig)(getState()); break; } case authActionTypes.CONNECT_FINISHED: { if (action.error) { // Don't setup FCS if the login failed. break; } var hasCallService = void 0; if (action.meta.platform === _constants.platforms.CLOUD) { hasCallService = (0, _selectors.getServices)(getState(), _constants.platforms.LINK).services.call === true; } else { hasCallService = action.payload.subscription.service.indexOf('call') > -1 || action.payload.subscription.service.indexOf('callMe') > -1; } // Log a warning if the user isn't subscribed for calls. if (!hasCallService) { // TODO: An event should be emitted from this. So the app knows to check services / // update services to try and get calls. log.error('Error: Setting up for calls without a call service subscription. Calls will likely fail.'); } if (action.meta.isSSO) { // If we are in an SSO scenario we first have to call fcs' setTokenAuth endpoint. // For normal CONNECT scenario's the equivalent is setUserAuth in the CONNECT middleware above. // For SSO we do it here since we don't get the username untill after the connect server response. callShim.setTokenAuth(action.payload.userInfo.username, action.payload.userInfo.token); // This call tells FCS to use UAT's instead of basic auth for all future rest calls. callShim.setKandyUAT(action.payload.userInfo.token); } var setupVars; // Retrieve the FCS configs from different places depending on auth's service. if (action.meta.platform === _constants.platforms.LINK) { // If we're Link, config has the variables we need. var authConfig = (0, _selectors.getAuthConfig)(getState()); setupVars = { notificationType: 'WebSocket', protocol: authConfig.subscription.protocol, restUrl: authConfig.subscription.server, restPort: authConfig.subscription.port, websocketProtocol: authConfig.websocket.protocol, websocketIP: authConfig.websocket.server, websocketPort: authConfig.websocket.port }; } else if (action.meta.platform === _constants.platforms.CLOUD) { if (action.meta.isSSO) { // We are in an SSO scenario so we need different setupVars for rest proxy. var spidrSub = action.payload.subscription.spidr_configuration; var kandyConnection = action.payload.connection; setupVars = { notificationType: 'WebSocket', protocol: kandyConnection.server.protocol, restUrl: kandyConnection.server.server, restPort: spidrSub.REST_server_port, websocketProtocol: 'wss', websocketIP: spidrSub.webSocket_server_address, websocketPort: spidrSub.webSocket_server_port }; } else { // Else, use the SPiDR subscription info from the action. var _spidrSub = action.payload.subscription.spidr_configuration; setupVars = { notificationType: 'WebSocket', protocol: _spidrSub.REST_protocol, restUrl: _spidrSub.REST_server_address, restPort: _spidrSub.REST_server_port, websocketProtocol: 'wss', websocketIP: _spidrSub.webSocket_server_address, websocketPort: _spidrSub.webSocket_server_port }; } } else if (action.meta.platform === _constants.platforms.CPAAS) { // If we're Link, config has the variables we need. var _authConfig = (0, _selectors.getAuthConfig)(getState()); log.debug('Auth config is: ' + _authConfig); setupVars = { notificationType: 'WebSocket', protocol: _authConfig.subscription.protocol, restUrl: _authConfig.subscription.server, // TODO: Auth plugin default is 80, but that doesn't work? restPort: '443', websocketProtocol: _authConfig.websocket.protocol, websocketIP: _authConfig.websocket.server, websocketPort: _authConfig.websocket.port, // Hook into FCS call requests to add the token to them. ajaxHook: function ajaxHook(xhr, unusedWindow, _ref6) { var url = _ref6.url, headers = _ref6.headers; // The token value will either be a normal Access Token or an OAuth Token if (action.payload.connection.oauthToken) { // For OAuth handling, add the Bearer token to the Request Header headers = (0, _extends3.default)({}, headers, { Authorization: 'Bearer ' + action.payload.connection.oauthToken }); } else { // For regular Access Token handling, add the token to the URL string var tokenString = 'token=' + action.payload.connection.accessToken; if (url.indexOf('?') === -1) { url += '?' + tokenString; } else { url += '&' + tokenString; } } return { url: url, headers: headers }; } }; } // Pull out the FCS' setup configs from the plugin configs. var fcsConfig = (0, _fp.omit)(['callDefaults', 'chromeExtensionId'], config); // Update the ice server info provided to FCS with the turn credentials // retrieved from subscription. if (fcsConfig.serverProvidedTurnCredentials && fcsConfig.hasOwnProperty('iceserver')) { var turnCredentials = action.payload.subscription.turnCredentials || {}; if (turnCredentials.username && turnCredentials.password) { log.debug('Using server provided turn credentials.'); fcsConfig.iceserver = fcsConfig.iceserver.map(function (iceInfo) { return (0, _extends3.default)({}, iceInfo, { username: turnCredentials.username, credential: turnCredentials.password }); }); } else { // TODO: Should this dispatch an error action? Or is a warning // enough, since an error will be encountered when calling? log.warn('Warning: Server turn credentials not found.'); } } if (config.chromeExtensionId) { fcsConfig.screenSharing = { chromeExtensionId: config.chromeExtensionId }; } // If there are plugin configs not present in setupVars, // add them in now. setupVars = (0, _fp.defaults)(fcsConfig, setupVars); if (action.payload.connection.isAnonymous) { setupVars.anonymous = true; } if (action.payload.connection.realm) { setupVars.realm = action.payload.connection.realm; callShim.setRealm(action.payload.connection.realm); } // Don't log passwords. var toLog = (0, _fp.defaults)(setupVars, { iceserver: setupVars.iceserver.map(function (server) { return (0, _extends3.default)({}, server, { credential: '********' }); }) }); log.debug('Setting up FCS with configs: ', toLog); // Setup the callstack. callShim.setup(setupVars); // Initialize media. dispatch(_actions3.mediaActions.initMedia(setupVars)); break; } case actionTypes.MAKE_CALL: { var callId = action.payload.callId; var options = (0, _fp.defaults)(config.callDefaults, action.payload.callInfo); if (!options.from) { // If no `from` is provided, use the current user. options.from = (0, _selectors.getUserInfo)(getState()).username; } log.debug('Making call with options: ', options); // Call the shim's makeCall function. callShim.makeCall(callId, options) // FCS' startCall success callback. .then(function (_ref7) { var options = _ref7.options; dispatch(_actions3.callsActions.makeCallFinish(callId, options)); }) // Failure scenario for either startCall or initMedia. .catch(function (_ref8) { var error = _ref8.error, options = _ref8.options; dispatch(_actions3.callsActions.makeCallFinish(callId, options, error)); }); break; } case actionTypes.ANSWER_CALL: { var _options = (0, _fp.defaults)(config.callDefaults, action.payload.callInfo); _options.to = (0, _selectors.getUserInfo)(getState()).username; log.debug('Answering call with options: ', _options); callShim.answerCall(action.payload.callId, _options).then(function (_ref9) { var callId = _ref9.callId; dispatch(_actions3.callsActions.answerCallFinish(callId, _options)); }).catch(function (_ref10) { var error = _ref10.error, callId = _ref10.callId; dispatch(_actions3.callsActions.answerCallFinish(callId, _options, error)); }); break; } case actionTypes.IGNORE_CALL: { log.debug('Ignoring call.', action.payload.callId); callShim.ignoreCall(action.payload.callId).then(function (_ref11) { var callId = _ref11.callId; dispatch(_actions3.callsActions.ignoreCallFinish(callId)); }).catch(function (_ref12) { var callId = _ref12.callId, error = _ref12.error; dispatch(_actions3.callsActions.ignoreCallFinish(callId, error)); }); break; } case actionTypes.REJECT_CALL: { log.debug('Rejecting call.', action.payload.callId); callShim.rejectCall(action.payload.callId).then(function (_ref13) { var callId = _ref13.callId; dispatch(_actions3.callsActions.rejectCallFinish(callId)); }).catch(function (_ref14) { var callId = _ref14.callId, error = _ref14.error; dispatch(_actions3.callsActions.rejectCallFinish(callId, error)); }); break; } case actionTypes.END_CALL: { log.debug('Ending call.', action.payload.callId); callShim.endCall(action.payload.callId).then(function (_ref15) { var callId = _ref15.callId; dispatch(_actions3.callsActions.endCallFinish(callId)); }).catch(function (_ref16) { var callId = _ref16.callId, error = _ref16.error; dispatch(_actions3.callsActions.endCallFinish(callId, error)); }); break; } case actionTypes.MUTE_CALL: { log.debug('Muting call.', action.payload.callId); callShim.muteCall(action.payload.callId).then(function (_ref17) { var callId = _ref17.callId; dispatch(_actions3.callsActions.muteCallFinish(callId)); }).catch(function (_ref18) { var callId = _ref18.callId, error = _ref18.error; dispatch(_actions3.callsActions.muteCallFinish(callId, error)); }); break; } case actionTypes.UNMUTE_CALL: { log.debug('Unmuting call.', action.payload.callId); callShim.unMuteCall(action.payload.callId).then(function (_ref19) { var callId = _ref19.callId; dispatch(_actions3.callsActions.unMuteCallFinish(callId)); }).catch(function (_ref20) { var callId = _ref20.callId, error = _ref20.error; dispatch(_actions3.callsActions.unMuteCallFinish(callId, error)); }); break; } case actionTypes.SET_CUSTOM_PARAMETERS: { log.debug('Setting custom parameters.'); callShim.setCustomParameters(action.payload.callId, action.payload.customParameters); break; } case actionTypes.START_VIDEO: { log.debug('Starting call video.', action.payload.callId); callShim.startVideo(action.payload.callId, action.payload.callInfo).then(function (_ref21) { var callId = _ref21.callId, params = _ref21.params; dispatch(_actions3.callsActions.startVideoFinish(callId, params)); }).catch(function (_ref22) { var callId = _ref22.callId, params = _ref22.params, error = _ref22.error; dispatch(_actions3.callsActions.startVideoFinish(callId, params, error)); }); break; } case actionTypes.STOP_VIDEO: { log.debug('Stopping call video.', action.payload.callId); callShim.stopVideo(action.payload.callId).then(function (_ref23) { var callId = _ref23.callId; dispatch(_actions3.callsActions.stopVideoFinish(callId)); }).catch(function (_ref24) { var callId = _ref24.callId, error = _ref24.error; dispatch(_actions3.callsActions.stopVideoFinish(callId, error)); }); break; } case actionTypes.HOLD_CALL: { log.debug('Hold call.', action.payload.callId); callShim.holdCall(action.payload.callId).then(function (_ref25) { var callId = _ref25.callId; dispatch(_actions3.callsActions.holdCallFinish(callId)); }).catch(function (_ref26) { var callId = _ref26.callId, error = _ref26.error; dispatch(_actions3.callsActions.holdCallFinish(callId, error)); }); break; } case actionTypes.UNHOLD_CALL: { log.debug('Unhold call.', action.payload.callId); callShim.unHoldCall(action.payload.callId).then(function (_ref27) { var callId = _ref27.callId; dispatch(_actions3.callsActions.unHoldCallFinish(callId)); }).catch(function (_ref28) { var callId = _ref28.callId, error = _ref28.error; dispatch(_actions3.callsActions.unHoldCallFinish(callId, error)); }); break; } case actionTypes.SEND_DTMF: { log.debug('Sending DTMF tone to call.', action.payload.callId); callShim.sendDTMF(action.payload.callId, action.payload.params.tone).then(function () { log.info('DTMF tone sent.'); // Nothing to be stored in state for DTMF tone. }).catch(function (_ref29) { var callId = _ref29.callId, error = _ref29.error; log.info('DTMF tone could not be sent.'); dispatch(_actions3.callsActions.sendDTMFFinish(callId, error)); }); break; } case actionTypes.SEND_CUSTOM_PARAMETERS: { log.debug('Sending custom parameters.', action.payload.callId); callShim.sendCustomParameters(action.payload.callId).then(function () { log.info('Custom parameters sent.'); // Nothing to be stored in state. }).catch(function (_ref30) { var callId = _ref30.callId, error = _ref30.error; log.info('Custom parameters could not be sent.'); dispatch(_actions3.callsActions.sendCustomParametersFinish(callId, error)); }); break; } case actionTypes.START_SCREENSHARE: { log.debug('Starting screenshare on call.', action.payload.callId); /** * Special case callback function. * Triggers when screensharing is stopped by the browser. * Defined in this scope so that it knows about the redux level. */ var onScreenshareStop = function onScreenshareStop() { log.debug('Screenshare stopped manually.'); dispatch(_actions3.callsActions.stopScreenshareFinish(action.payload.callId)); }; callShim.startScreenshare(action.payload.callId, action.payload.callInfo.screenshareOptions, onScreenshareStop).then(function (_ref31) { var callId = _ref31.callId, params = _ref31.params; dispatch(_actions3.callsActions.startScreenshareFinish(callId, params)); }).catch(function (_ref32) { var callId = _ref32.callId, params = _ref32.params, error = _ref32.error; dispatch(_actions3.callsActions.startScreenshareFinish(callId, params, error)); }); break; } case actionTypes.STOP_SCREENSHARE: { log.debug('Stopping screenshare on call.', action.payload.callId); callShim.stopScreenshare(action.payload.callId).then(function (_ref33) { var callId = _ref33.callId; dispatch(_actions3.callsActions.stopScreenshareFinish(callId)); }).catch(function (_ref34) { var callId = _ref34.callId, error = _ref34.error; dispatch(_actions3.callsActions.stopScreenshareFinish(callId, error)); }); break; } case actionTypes.FORWARD_CALL: { log.debug('Forwarding call to user ' + action.payload.params.destination, action.payload.callId); callShim.forwardCall(action.payload.callId, action.payload.params.destination).then(function (_ref35) { var callId = _ref35.callId; dispatch(_actions3.callsActions.forwardCallFinish(callId)); }).catch(function (_ref36) { var callId = _ref36.callId, error = _ref36.error; dispatch(_actions3.callsActions.forwardCallFinish(callId, error)); }); break; } case actionTypes.DIRECT_TRANSFER: { log.debug('Transfering call (direct) to user ' + action.payload.params.destination, action.payload.callId); callShim.directTransfer(action.payload.callId, action.payload.params.destination).then(function (_ref37) { var callId = _ref37.callId; dispatch(_actions3.callsActions.directTransferFinish(callId)); }).catch(function (_ref38) { var callId = _ref38.callId, error = _ref38.error; dispatch(_actions3.callsActions.directTransferFinish(callId, error)); }); break; } case actionTypes.CONSULTATIVE_TRANSFER: { log.debug('Transfering call (consultative) to destination ' + action.payload.params.destination, action.payload.callId); callShim.consultativeTransfer(action.payload.callId, action.payload.params.destination).then(function (_ref39) { var callId = _ref39.callId; dispatch(_actions3.callsActions.consultativeTransferFinish(callId)); }).catch(function (_ref40) { var callId = _ref40.callId, error = _ref40.error; dispatch(_actions3.callsActions.consultativeTransferFinish(callId, error)); }); break; } case actionTypes.JOIN_CALL: { log.debug('Joining call ' + action.payload.params.destination, action.payload.callId); callShim.joinCall(action.payload.callId, action.payload.params.destination).then(function (_ref41) { var joinedCallId = _ref41.callId, joinedCalls = _ref41.joinedCalls, callState = _ref41.callState; var state = getState(); var username = (0, _selectors.getUserInfo)(state).username; var joinedCallTo = joinedCalls.map(function (callId) { var call = (0, _selectors2.getCallById)(state, callId); return call.to === username ? call.from : call.to; }); // Add as much info as we can to the joined call. var callInfo = { state: callState, from: username, to: 'Joined Call', participants: joinedCallTo, // Mark this call as "special". isJoinedCall: true, joinedCalls: joinedCalls, // TODO: These values are assumed... isAudioEnabled: true, isVideoEnabled: false, muted: false }; dispatch(_actions3.callsActions.joinCallFinish(joinedCallId, joinedCalls, { callInfo: callInfo })); }).catch(function (_ref42) { var joinedCallId = _ref42.callId, joinedCalls = _ref42.joinedCalls, error = _ref42.error; dispatch(_actions3.callsActions.joinCallFinish(joinedCallId, joinedCalls, { error: error })); }); break; } case actionTypes.START_LOCAL_VIDEO: { log.debug('Starting local video.'); var videoContainer = action.payload || config.localVideoContainer; callShim.startLocalVideo(videoContainer).then(function (container) { dispatch(_actions3.localVideoActions.startLocalVideoFinish(container)); }).catch(function (_ref43) { var error = _ref43.error; var kandyError = void 0; // Convert the callShim error object into a KandyError. if (error.type === 'media') { kandyError = new _errors2.default({ message: error.message, code: _errors.callCodes.INIT_MEDIA_FAILED }); } else if (error.type === 'video') { kandyError = new _errors2.default({ message: error.message, code: _errors.callCodes.USER_MEDIA_ERROR }); } else if (error.type === 'generic') { kandyError = new _errors2.default({ message: error.message, code: _errors.callCodes.GENERIC_ERROR }); } else { kandyError = new _errors2.default({ message: 'An error occurred when starting local video.', code: _errors.callCodes.UNKNOWN_ERROR }); } dispatch(_actions3.localVideoActions.startLocalVideoFinish(null, kandyError)); }); break; } case actionTypes.STOP_LOCAL_VIDEO: { log.debug('Stopping local video.'); callShim.stopLocalVideo().then(function () { dispatch(_actions3.localVideoActions.stopLocalVideoFinish()); }).catch(function (error) { var kandyError = new _errors2.default({ message: error.message, code: _errors.callCodes.GENERIC_ERROR }); dispatch(_actions3.localVideoActions.stopLocalVideoFinish(kandyError)); }); break; } case actionTypes.INIT_MEDIA: { // Move around the extension ID to be where FCS will look for it. // Done the same way as before setup is done. if (action.payload.chromeExtensionId) { action.payload.screenSharing = { chromeExtensionId: action.payload.chromeExtensionId }; } var callState = (0, _fp.defaults)((0, _selectors2.getCallConfig)(getState()), action.payload); var isConnected = getState().authentication.isConnected; var mediaResults = (0, _selectors2.getMediaInfo)(getState()); // Only allow initMedia before connecting. Doing initMedia will // override any settings used the last time initMedia was called, // so only allow manual initMedia before connection, since // connection is where iceserver settings are retrieved from server. // TODO: Fix "this" properly (ie. fix FCS' initMedia). // Side-note: FCS' results from second+ attempt may not be accurate. if (!isConnected) { log.debug('Initializing media.'); callShim.initMedia(callState).then(function (result) { dispatch(_actions3.mediaActions.initMediaFinish(result)); }); } else { log.debug('Media already initialized; re-using results.'); dispatch(_actions3.mediaActions.initMediaFinish(mediaResults)); } break; } case actionTypes.CREATE_AUDIO_BRIDGE: { log.debug('Creating audio bridge.', action.payload.bridgeId); callShim.createLocalAudioBridge(action.payload.bridgeId).then(function () { dispatch(_actions3.audioBridgeActions.createAudioBridgeFinish(action.payload.bridgeId)); }).catch(function (error) { dispatch(_actions3.audioBridgeActions.createAudioBridgeFinish(action.payload.bridgeId, error)); }); break; } case actionTypes.CLOSE_AUDIO_BRIDGE: { log.debug('Closing audio bridge.', action.payload.bridgeId); callShim.closeAudioBridge(action.payload.bridgeId).then(function () { dispatch(_actions3.audioBridgeActions.closeAudioBridgeFinish(action.payload.bridgeId)); }).catch(function (error) { dispatch(_actions3.audioBridgeActions.closeAudioBridgeFinish(action.payload.bridgeId, error)); }); break; } /* * BRIDGE_ADD_CALL action is fired without .then(), as the bridge's active list of calls is kept up to date * in the state through the UPDATE_AUDIO_BRIDGE_CALLS action, which is emitted by the bridge itself. * UPDATE_AUDIO_BRIDGE_CALLS is mapped to the BRIDGE_CHANGE event. * * `addCallToBridge.catch()` is still used for error handling. */ case actionTypes.BRIDGE_ADD_CALL: { var _action$payload = action.payload, bridgeId = _action$payload.bridgeId, _callId = _action$payload.callId; log.debug('Adding call to bridge.', bridgeId); callShim.addCallToBridge(bridgeId, _callId).catch(function (error) { dispatch(_actions3.audioBridgeActions.addCallToBridgeFinish(bridgeId, _callId, error)); }); break; } /* * BRIDGE_REMOVE_CALL action is fired without .then(), as the bridge's active list of calls is kept up to date * in the state through the UPDATE_AUDIO_BRIDGE_CALLS action, which is emitted by the bridge itself. * UPDATE_AUDIO_BRIDGE_CALLS is mapped to the BRIDGE_CHANGE event. * * `removeCallFromBridge.catch()` is still used for error handling. */ case actionTypes.BRIDGE_REMOVE_CALL: { var _action$payload2 = action.payload, _bridgeId = _action$payload2.bridgeId, _callId2 = _action$payload2.callId; log.debug('Removing call to bridge.', _bridgeId); callShim.removeCallFromBridge(_bridgeId, _callId2).catch(function (error) { dispatch(_actions3.audioBridgeActions.removeCallFromBridgeFinish(_bridgeId, _callId2, error)); }); break; } case actionTypes.MUTE_AUDIO_BRIDGE: { log.debug('Muting audio bridge.', action.payload.bridgeId); callShim.muteAudioBridge(action.payload.bridgeId).then(function () { dispatch(_actions3.audioBridgeActions.muteAudioBridgeFinish(action.payload.bridgeId)); }).catch(function (error) { dispatch(_actions3.audioBridgeActions.muteAudioBridgeFinish(action.payload.bridgeId, error)); }); break; } case actionTypes.UNMUTE_AUDIO_BRIDGE: { log.debug('Unmuting audio bridge.', action.payload.bridgeId); callShim.unmuteAudioBridge(action.payload.bridgeId).then(function () { dispatch(_actions3.audioBridgeActions.unmuteAudioBridgeFinish(action.payload.bridgeId)); }).catch(function (error) { dispatch(_actions3.audioBridgeActions.unmuteAudioBridgeFinish(action.payload.bridgeId, error)); }); break; } case notiActionTypes.NOTIFICATION_RECEIVED: { // TODO: Limit this to only handle call related messages. // Or generalize this to another plugin/handler. var data = action.payload.notificationMessage; if (data) { var callbacks = callShim.getNotificationCallbacks(); if ((0, _fp.isFunction)(callbacks[data.eventType])) { log.debug('WS notification message received: ' + data.eventType); // Handle websocket messages by forwarding them to FCS' notification system. callbacks[data.eventType](data); } } break; } default: break; } return next(action); }; }; } /***/ }), /***/ "./src/call/interface/actionTypes.js": /*!*******************************************!*\ !*** ./src/call/interface/actionTypes.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PREFIX = '@@KANDY/'; var MAKE_CALL = exports.MAKE_CALL = PREFIX + 'MAKE_CALL'; var MAKE_CALL_FINISH = exports.MAKE_CALL_FINISH = PREFIX + 'MAKE_CALL_FINISH'; var CALL_INCOMING = exports.CALL_INCOMING = PREFIX + 'CALL_INCOMING'; var ANSWER_CALL = exports.ANSWER_CALL = PREFIX + 'ANSWER_CALL'; var ANSWER_CALL_FINISH = exports.ANSWER_CALL_FINISH = PREFIX + 'ANSWER_CALL_FINISH'; var IGNORE_CALL = exports.IGNORE_CALL = PREFIX + 'IGNORE_CALL'; var IGNORE_CALL_FINISH = exports.IGNORE_CALL_FINISH = PREFIX + 'IGNORE_CALL_FINISH'; var REJECT_CALL = exports.REJECT_CALL = PREFIX + 'REJECT_CALL'; var REJECT_CALL_FINISH = exports.REJECT_CALL_FINISH = PREFIX + 'REJECT_CALL_FINISH'; var END_CALL = exports.END_CALL = PREFIX + 'END_CALL'; var END_CALL_FINISH = exports.END_CALL_FINISH = PREFIX + 'END_CALL_FINISH'; var CALL_STATE_CHANGE = exports.CALL_STATE_CHANGE = PREFIX + 'CALL_STATE_CHANGE'; var CALL_MEDIA_STATE_CHANGE = exports.CALL_MEDIA_STATE_CHANGE = PREFIX + 'CALL_MEDIA_STATE_CHANGE'; var START_LOCAL_VIDEO = exports.START_LOCAL_VIDEO = PREFIX + 'START_LOCAL_VIDEO'; var START_LOCAL_VIDEO_FINISH = exports.START_LOCAL_VIDEO_FINISH = PREFIX + 'START_LOCAL_VIDEO_FINISH'; var STOP_LOCAL_VIDEO = exports.STOP_LOCAL_VIDEO = PREFIX + 'STOP_LOCAL_VIDEO'; var STOP_LOCAL_VIDEO_FINISH = exports.STOP_LOCAL_VIDEO_FINISH = PREFIX + 'STOP_LOCAL_VIDEO_FINISH'; /* * Mid-Call operations. */ var MUTE_CALL = exports.MUTE_CALL = PREFIX + 'MUTE_CALL'; var MUTE_CALL_FINISH = exports.MUTE_CALL_FINISH = PREFIX + 'MUTE_CALL_FINISH'; var UNMUTE_CALL = exports.UNMUTE_CALL = PREFIX + 'UNMUTE_CALL'; var UNMUTE_CALL_FINISH = exports.UNMUTE_CALL_FINISH = PREFIX + 'UNMUTE_CALL_FINISH'; var SET_CUSTOM_PARAMETERS = exports.SET_CUSTOM_PARAMETERS = PREFIX + 'SET_CUSTOM_PARAMETERS'; var START_VIDEO = exports.START_VIDEO = PREFIX + 'START_VIDEO'; var START_VIDEO_FINISH = exports.START_VIDEO_FINISH = PREFIX + 'START_VIDEO_FINISH'; var STOP_VIDEO = exports.STOP_VIDEO = PREFIX + 'STOP_VIDEO'; var STOP_VIDEO_FINISH = exports.STOP_VIDEO_FINISH = PREFIX + 'STOP_VIDEO_FINISH'; var HOLD_CALL = exports.HOLD_CALL = PREFIX + 'HOLD_CALL'; var HOLD_CALL_FINISH = exports.HOLD_CALL_FINISH = PREFIX + 'HOLD_CALL_FINISH'; var UNHOLD_CALL = exports.UNHOLD_CALL = PREFIX + 'UNHOLD_CALL'; var UNHOLD_CALL_FINISH = exports.UNHOLD_CALL_FINISH = PREFIX + 'UNHOLD_CALL_FINISH'; var START_SCREENSHARE = exports.START_SCREENSHARE = PREFIX + 'START_SCREENSHARE'; var START_SCREENSHARE_FINISH = exports.START_SCREENSHARE_FINISH = PREFIX + 'START_SCREENSHARE_FINISH'; var STOP_SCREENSHARE = exports.STOP_SCREENSHARE = PREFIX + 'STOP_SCREENSHARE'; var STOP_SCREENSHARE_FINISH = exports.STOP_SCREENSHARE_FINISH = PREFIX + 'STOP_SCREENSHARE_FINISH'; var FORWARD_CALL = exports.FORWARD_CALL = PREFIX + 'FORWARD_CALL'; var FORWARD_CALL_FINISH = exports.FORWARD_CALL_FINISH = PREFIX + 'FORWARD_CALL_FINISH'; var DIRECT_TRANSFER = exports.DIRECT_TRANSFER = PREFIX + 'DIRECT_TRANSFER'; var DIRECT_TRANSFER_FINISH = exports.DIRECT_TRANSFER_FINISH = PREFIX + 'DIRECT_TRANSFER_FINISH'; var CONSULTATIVE_TRANSFER = exports.CONSULTATIVE_TRANSFER = PREFIX + 'CONSULTATIVE_TRANSFER'; var CONSULTATIVE_TRANSFER_FINISH = exports.CONSULTATIVE_TRANSFER_FINISH = PREFIX + 'CONSULTATIVE_TRANSFER_FINISH'; var JOIN_CALL = exports.JOIN_CALL = PREFIX + 'JOIN_CALL'; var JOIN_CALL_FINISH = exports.JOIN_CALL_FINISH = PREFIX + 'JOIN_CALL_FINISH'; var SEND_CUSTOM_PARAMETERS = exports.SEND_CUSTOM_PARAMETERS = PREFIX + 'SEND_CUSTOM_PARAMETERS'; var SEND_CUSTOM_PARAMETERS_FINISH = exports.SEND_CUSTOM_PARAMETERS_FINISH = PREFIX + 'SEND_CUSTOM_PARAMETERS_FINISH'; var SEND_DTMF = exports.SEND_DTMF = PREFIX + 'SEND_DTMF'; var SEND_DTMF_FINISH = exports.SEND_DTMF_FINISH = PREFIX + 'SEND_DTMF_FINISH'; // Media devices. var CHECK_DEVICES = exports.CHECK_DEVICES = PREFIX + 'CHECK_DEVICES'; var CHECK_DEVICES_FINISH = exports.CHECK_DEVICES_FINISH = PREFIX + 'CHECK_DEVICES_FINISH'; var SET_DEFAULT_DEVICES = exports.SET_DEFAULT_DEVICES = PREFIX + 'SET_DEFAULT_DEVICES'; var SET_DEFAULT_DEVICES_FINISH = exports.SET_DEFAULT_DEVICES_FINISH = PREFIX + 'SET_DEFAULT_DEVICES_FINISH'; var PROMPT_USER_MEDIA = exports.PROMPT_USER_MEDIA = PREFIX + 'PROMPT_USER_MEDIA'; var PROMPT_USER_MEDIA_FINISH = exports.PROMPT_USER_MEDIA_FINISH = PREFIX + 'PROMPT_USER_MEDIA_FINISH'; var CHANGE_SPEAKER = exports.CHANGE_SPEAKER = PREFIX + 'CHANGE_SPEAKER'; var CHANGE_SPEAKER_FINISH = exports.CHANGE_SPEAKER_FINISH = PREFIX + 'CHANGE_SPEAKER_FINISH'; var CHANGE_INPUT_DEVICES = exports.CHANGE_INPUT_DEVICES = PREFIX + 'CHANGE_INPUT_DEVICES'; var CHANGE_INPUT_DEVICES_FINISH = exports.CHANGE_INPUT_DEVICES_FINISH = PREFIX + 'CHANGE_INPUT_DEVICES_FINISH'; // Media var INIT_MEDIA = exports.INIT_MEDIA = PREFIX + 'INIT_MEDIA'; var INIT_MEDIA_FINISH = exports.INIT_MEDIA_FINISH = PREFIX + 'INIT_MEDIA_FINISH'; // Call Me var MAKE_CALL_ANONYMOUS = exports.MAKE_CALL_ANONYMOUS = PREFIX + 'MAKE_CALL_ANONYMOUS'; // Audio Bridge var CREATE_AUDIO_BRIDGE = exports.CREATE_AUDIO_BRIDGE = PREFIX + 'CREATE_AUDIO_BRIDGE'; var CREATE_AUDIO_BRIDGE_FINISH = exports.CREATE_AUDIO_BRIDGE_FINISH = PREFIX + 'CREATE_AUDIO_BRIDGE_FINISH'; var CLOSE_AUDIO_BRIDGE = exports.CLOSE_AUDIO_BRIDGE = PREFIX + 'CLOSE_AUDIO_BRIDGE'; var CLOSE_AUDIO_BRIDGE_FINISH = exports.CLOSE_AUDIO_BRIDGE_FINISH = PREFIX + 'CLOSE_AUDIO_BRIDGE_FINISH'; var BRIDGE_ADD_CALL = exports.BRIDGE_ADD_CALL = PREFIX + 'BRIDGE_ADD_CALL'; var BRIDGE_ADD_CALL_FINISH = exports.BRIDGE_ADD_CALL_FINISH = PREFIX + 'BRIDGE_ADD_CALL_FINISH'; var BRIDGE_REMOVE_CALL = exports.BRIDGE_REMOVE_CALL = PREFIX + 'BRIDGE_REMOVE_CALL'; var BRIDGE_REMOVE_CALL_FINISH = exports.BRIDGE_REMOVE_CALL_FINISH = PREFIX + 'BRIDGE_REMOVE_CALL_FINISH'; var MUTE_AUDIO_BRIDGE = exports.MUTE_AUDIO_BRIDGE = PREFIX + 'MUTE_AUDIO_BRIDGE'; var MUTE_AUDIO_BRIDGE_FINISH = exports.MUTE_AUDIO_BRIDGE_FINISH = PREFIX + 'MUTE_AUDIO_BRIDGE_FINISH'; var UNMUTE_AUDIO_BRIDGE = exports.UNMUTE_AUDIO_BRIDGE = PREFIX + 'UNMUTE_AUDIO_BRIDGE'; var UNMUTE_AUDIO_BRIDGE_FINISH = exports.UNMUTE_AUDIO_BRIDGE_FINISH = PREFIX + 'UNMUTE_AUDIO_BRIDGE_FINISH'; var UPDATE_AUDIO_BRIDGE_CALLS = exports.UPDATE_AUDIO_BRIDGE_CALLS = PREFIX + 'UPDATE_AUDIO_BRIDGE_CALLS'; /***/ }), /***/ "./src/call/interface/actions/audioBridge.js": /*!***************************************************!*\ !*** ./src/call/interface/actions/audioBridge.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createAudioBridge = createAudioBridge; exports.createAudioBridgeFinish = createAudioBridgeFinish; exports.closeAudioBridge = closeAudioBridge; exports.closeAudioBridgeFinish = closeAudioBridgeFinish; exports.addCallToBridge = addCallToBridge; exports.updateAudioBridgeCalls = updateAudioBridgeCalls; exports.addCallToBridgeFinish = addCallToBridgeFinish; exports.removeCallFromBridge = removeCallFromBridge; exports.removeCallFromBridgeFinish = removeCallFromBridgeFinish; exports.muteAudioBridge = muteAudioBridge; exports.muteAudioBridgeFinish = muteAudioBridgeFinish; exports.unmuteAudioBridge = unmuteAudioBridge; exports.unmuteAudioBridgeFinish = unmuteAudioBridgeFinish; var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Reprents an API request to create an audio bridge. * @method createAudioBridge * @param {string} bridgeId UUID to identify the audio bridge. * @returns {Object} A flux standard action. */ function createAudioBridge(bridgeId) { return { type: actionTypes.CREATE_AUDIO_BRIDGE, payload: { bridgeId: bridgeId } }; } /** * Represents the result of creating an audio bridge. * @method createAudioBridgeFinish * @param {string} bridgeId UUID to identify the audio bridge. * @param {Boolean} [error=false] * @returns {Object} A flux standard action. */ function createAudioBridgeFinish(bridgeId) { var error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return { error: !!error, type: actionTypes.CREATE_AUDIO_BRIDGE_FINISH, payload: error || { bridgeId: bridgeId } }; } function closeAudioBridge(bridgeId) { return { type: actionTypes.CLOSE_AUDIO_BRIDGE, payload: { bridgeId: bridgeId } }; } function closeAudioBridgeFinish(bridgeId) { var error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return { error: !!error, type: actionTypes.CLOSE_AUDIO_BRIDGE_FINISH, payload: error || { bridgeId: bridgeId } }; } function addCallToBridge(bridgeId, callId) { return { type: actionTypes.BRIDGE_ADD_CALL, payload: { bridgeId: bridgeId, callId: callId } }; } function updateAudioBridgeCalls(bridgeId, calls) { return { type: actionTypes.UPDATE_AUDIO_BRIDGE_CALLS, payload: { bridgeId: bridgeId, calls: calls } }; } function addCallToBridgeFinish(bridgeId, callId) { var error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; return { error: !!error, type: actionTypes.BRIDGE_ADD_CALL_FINISH, payload: error || { bridgeId: bridgeId, callId: callId } }; } function removeCallFromBridge(bridgeId, callId) { return { type: actionTypes.BRIDGE_REMOVE_CALL, payload: { bridgeId: bridgeId, callId: callId } }; } function removeCallFromBridgeFinish(bridgeId, callId) { var error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; return { error: !!error, type: actionTypes.BRIDGE_REMOVE_CALL_FINISH, payload: error || { bridgeId: bridgeId, callId: callId } }; } function muteAudioBridge(bridgeId) { return { type: actionTypes.MUTE_AUDIO_BRIDGE, payload: { bridgeId: bridgeId } }; } function muteAudioBridgeFinish(bridgeId) { var error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return { error: !!error, type: actionTypes.MUTE_AUDIO_BRIDGE_FINISH, payload: error || { bridgeId: bridgeId } }; } function unmuteAudioBridge(bridgeId) { return { type: actionTypes.UNMUTE_AUDIO_BRIDGE, payload: { bridgeId: bridgeId } }; } function unmuteAudioBridgeFinish(bridgeId) { var error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return { error: !!error, type: actionTypes.UNMUTE_AUDIO_BRIDGE_FINISH, payload: error || { bridgeId: bridgeId } }; } /***/ }), /***/ "./src/call/interface/actions/calls.js": /*!*********************************************!*\ !*** ./src/call/interface/actions/calls.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); exports.callActionHelper = callActionHelper; exports.makeCall = makeCall; exports.makeCallFinish = makeCallFinish; exports.callIncoming = callIncoming; exports.answerCall = answerCall; exports.answerCallFinish = answerCallFinish; exports.ignoreCall = ignoreCall; exports.ignoreCallFinish = ignoreCallFinish; exports.rejectCall = rejectCall; exports.rejectCallFinish = rejectCallFinish; exports.endCall = endCall; exports.endCallFinish = endCallFinish; exports.callStateChange = callStateChange; exports.callMediaStateChange = callMediaStateChange; exports.muteCall = muteCall; exports.muteCallFinish = muteCallFinish; exports.unMuteCall = unMuteCall; exports.unMuteCallFinish = unMuteCallFinish; exports.setCustomParameters = setCustomParameters; exports.startVideo = startVideo; exports.startVideoFinish = startVideoFinish; exports.stopVideo = stopVideo; exports.stopVideoFinish = stopVideoFinish; exports.holdCall = holdCall; exports.holdCallFinish = holdCallFinish; exports.unHoldCall = unHoldCall; exports.unHoldCallFinish = unHoldCallFinish; exports.startScreenshare = startScreenshare; exports.startScreenshareFinish = startScreenshareFinish; exports.stopScreenshare = stopScreenshare; exports.stopScreenshareFinish = stopScreenshareFinish; exports.sendDTMF = sendDTMF; exports.sendDTMFFinish = sendDTMFFinish; exports.sendCustomParameters = sendCustomParameters; exports.sendCustomParametersFinish = sendCustomParametersFinish; exports.forwardCall = forwardCall; exports.forwardCallFinish = forwardCallFinish; exports.directTransfer = directTransfer; exports.directTransferFinish = directTransferFinish; exports.consultativeTransfer = consultativeTransfer; exports.consultativeTransferFinish = consultativeTransferFinish; exports.joinCall = joinCall; exports.joinCallFinish = joinCallFinish; exports.makeAnonymousCall = makeAnonymousCall; var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Helper function for formatting call actions. * @method callActionHelper * @param {string} type - Action type. * @param {string} callId - Id of the call being acted on. * @param {Object} $2 * @param {Object} $2.callInfo - Call state properties. * @param {Object} $2.error * @return {Object} A flux standard action. */ function callActionHelper(type, callId) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, callInfo = _ref.callInfo, error = _ref.error, params = _ref.params; var action = { type: type, payload: {} }; if (error) { action.error = true; var message = typeof error === 'string' ? error : error.message; action.payload = new Error(message); // TODO: Ensure the middleware uses consistent error objects. // Ensure the action has the entire error object. action.payload.error = error; } if (callInfo) { action.payload.callInfo = callInfo; } if (params) { action.payload.params = params; } action.payload.callId = callId; return action; } /** * Creates a make call action to start an outgoing call. * @method makeCall * @param {string} callee Full user ID of the call recipient. * @param {string} callId A unique identifier for the call. * @param {Object} [options={}] Call options. * @returns {Object} A flux standard action representing the make call action. */ function makeCall(callee, callId) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callInfo = (0, _extends3.default)({}, options, { to: callee }); return callActionHelper(actionTypes.MAKE_CALL, callId, { callInfo: callInfo }); } /** * Creates a make call finish action. * @method makeCallFinish * @param {string} callId The outgoing call ID. * @param {Object} callInfo Information about the call. * @param {Object} error The error object, in the case of an error. * @returns {Object} A flux standard action representing the make call finish action. */ function makeCallFinish(callId, callInfo, error) { return callActionHelper(actionTypes.MAKE_CALL_FINISH, callId, { callInfo: callInfo, error: error }); } /** * Create a call incoming action. * @method callIncoming * @param {string} callId The outgoing call ID. * @param {Object} callInfo Information about the call. * @returns {Object} A flux standard action representing the call incoming action. */ function callIncoming(callId, callInfo) { return callActionHelper(actionTypes.CALL_INCOMING, callId, { callInfo: callInfo }); } /** * Creating an answer call action. * @method answerCall * @param {string} callId The ID of the call to answer. * @param {Object} [options={}] Call options. * @returns {Object} A flux standard action representing the answer call action. */ function answerCall(callId) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return callActionHelper(actionTypes.ANSWER_CALL, callId, { callInfo: options }); } /** * Creating an answer call finish action. * @method answerCall * @param {string} callId The ID of the call that was answered. * @param {Object} [error] The error object, in the case of an error. * @returns {Object} A flux standard action representing the answer call finish action. */ function answerCallFinish(callId, callInfo, error) { return callActionHelper(actionTypes.ANSWER_CALL_FINISH, callId, { callInfo: callInfo, error: error }); } /** * Creates an ignore call action. * @method ignoreCall * @param {string} callId The ID of the call to ignore. * @returns {Object} A flux standard action representing the ignore call action. */ function ignoreCall(callId) { return callActionHelper(actionTypes.IGNORE_CALL, callId); } /** * Creates an ignore call finish action. * @method ignoreCallFinish * @param {string} callId The ID of the ignored call. * @param {Object} [error] The error object, in the case of an error. * @return {Object} A flux standard action. */ function ignoreCallFinish(callId, error) { return callActionHelper(actionTypes.IGNORE_CALL_FINISH, callId, { error: error }); } /** * Creates an reject call action. * @method rejectCall * @param {string} callId The ID of the call to reject. * @returns {Object} A flux standard action representing the reject call action. */ function rejectCall(callId) { return callActionHelper(actionTypes.REJECT_CALL, callId); } /** * Creates an reject call finish action. * @method rejectCallFinish * @param {string} callId The ID of the rejected call. * @param {Object} [error] The error object, in the case of an error. * @return {Object} A flux standard action. */ function rejectCallFinish(callId, error) { return callActionHelper(actionTypes.REJECT_CALL_FINISH, callId, { error: error }); } /** * Create an end call action. * @method endCall * @param {string} callId The outgoing call ID. * @returns {Object} A flux standard action representing the end call action. */ function endCall(callId) { return callActionHelper(actionTypes.END_CALL, callId); } /** * Creates an end call finish action. * @method endCallFinish * @param {string} callId Id of the call that was ended. * @param {Object} error The error object, in the case of an error. * @returns {Object} A flux standard action representing the end call finish action. */ function endCallFinish(callId, error) { return callActionHelper(actionTypes.END_CALL_FINISH, callId, { error: error }); } /** * Represents an action about a call state changing. * @method callStateChange * @param {string} callId Id of the call that changed. * @param {string} state The new call state. * @param {Object} transition Information about the state change. * @param {Object} callInfo Meta information about the call. * @returns {Object} A flux standard action. */ function callStateChange(callId, state, transition, callInfo) { // TODO: Error action if error state change? return { type: actionTypes.CALL_STATE_CHANGE, payload: { callId: callId, state: state, transition: transition, callInfo: callInfo } }; } /** * Represents that a call's media state has changed. * @method callMediaStateChange * @param {string} callId Id of the call that changed. * @param {number} mediaState The new call media state. * @returns {Object} A flux standard action. */ function callMediaStateChange(callId, mediaState) { return { type: actionTypes.CALL_MEDIA_STATE_CHANGE, payload: { callId: callId, mediaState: mediaState } }; } /** * Represents an action to mute a call. * @method muteCall * @param {string} callId The ID of the call being acted on. * @returns {Object} A flux standard action. */ function muteCall(callId) { return callActionHelper(actionTypes.MUTE_CALL, callId); } /** * Represents the finish of an action to mute a call. * @method muteCallFinish * @param {string} callId The ID of the call being acted on. * @param {Object} error The error object, in the case of an error. * @returns {Object} A flux standard action. */ function muteCallFinish(callId, error) { return callActionHelper(actionTypes.MUTE_CALL_FINISH, callId, { error: error }); } /** * Represents an action to unmute a call. * @method unMuteCall * @param {string} callId The ID of the call being acted on. * @returns {Object} A flux standard action. */ function unMuteCall(callId) { return callActionHelper(actionTypes.UNMUTE_CALL, callId); } /** * Represents the finish of an action to unmute a call. * @method unMuteCallFinish * @param {string} callId The ID of the call being acted on. * @param {Object} error The error object, in the case of an error. * @returns {Object} A flux standard action. */ function unMuteCallFinish(callId, error) { return callActionHelper(actionTypes.UNMUTE_CALL_FINISH, callId, { error: error }); } /** * Represents an action to set parameters. * @method setCustomParameters * @param {string} callId The ID of the call being acted on. * @param {Array.<{name: string, value:string}>} customParameters Custom parameters. * @returns {Object} A flux standard action. */ function setCustomParameters(callId) { var customParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; return { type: actionTypes.SET_CUSTOM_PARAMETERS, payload: { callId: callId, customParameters: customParameters } }; } /** * Represents an action to start video for a call. * @method startVideo * @param {string} callId The ID of the call being acted on. * @param {Object} [params] * @param {Object} [params.videoResolution] * @returns {Object} A flux standard action. */ function startVideo(callId) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return callActionHelper(actionTypes.START_VIDEO, callId, { callInfo: params }); } /** * Represents the finish of an action to start video for a call. * @method startVideoFinish * @param {string} callId The ID of the call being acted on. * @param {Object} [error] The error object, in the case of an error. * @param {Object} [params] * @param {Object} [params.videoResolution] * @returns {Object} A flux standard action. */ function startVideoFinish(callId, params, error) { return callActionHelper(actionTypes.START_VIDEO_FINISH, callId, { callInfo: params, error: error }); } /** * Represents an action to stop video for a call. * @method stopVideo * @param {string} callId The ID of the call being acted on. * @returns {Object} A flux standard action. */ function stopVideo(callId) { return callActionHelper(actionTypes.STOP_VIDEO, callId); } /** * Represents the finish of an action to stop video for a call. * @method stopVideoFinish * @param {string} callId The ID of the call being acted on. * @param {Object} [error] The error object, in the case of an error. * @returns {Object} A flux standard action. */ function stopVideoFinish(callId, error) { return callActionHelper(actionTypes.STOP_VIDEO_FINISH, callId, { error: error }); } /** * Represents an action to hold a call. * @method holdCall * @param {string} callId The ID of the call being acted on. * @returns {Object} A flux standard action. */ function holdCall(callId) { return callActionHelper(actionTypes.HOLD_CALL, callId); } /** * Represents the finish of an action to hold a call. * @method holdCallFinish * @param {string} callId The ID of the call being acted on. * @param {Object} error The error object, in the case of an error. * @returns {Object} A flux standard action. */ function holdCallFinish(callId, error) { return callActionHelper(actionTypes.HOLD_CALL_FINISH, callId, { error: error }); } /** * Represents an action to unhold a call. * @method unHoldCall * @param {string} callId The ID of the call being acted on. * @returns {Object} A flux standard action. */ function unHoldCall(callId) { return callActionHelper(actionTypes.UNHOLD_CALL, callId); } /** * Represents the finish of an action to unhold a call. * @method unHoldCallFinish * @param {string} callId The ID of the call being acted on. * @param {Object} error The error object, in the case of an error. * @returns {Object} A flux standard action. */ function unHoldCallFinish(callId, error) { return callActionHelper(actionTypes.UNHOLD_CALL_FINISH, callId, { error: error }); } /** * Represents an action to start screensharing over a call. * @method startScreenshare * @param {string} callId The ID of the call being acted on. * @param {Object} params * @param {Number} [params.width=1024] The width of the screen to request. * @param {Number} [params.height=768] The height of the screen to request. * @param {Number} [params.frameRate=15] The number of frames per second to request. * @returns {Object} A flux standard action. */ function startScreenshare(callId) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return callActionHelper(actionTypes.START_SCREENSHARE, callId, { callInfo: { screenshareOptions: params } }); } /** * Represents the finish of an action to start screensharing over a call. * @method startScreenshareFinish * @param {string} callId The ID of the call being acted on. * @param {Object} error The error object, in the case of an error. * @param {Object} params * @param {Number} [params.width=1024] The width of the screen to request. * @param {Number} [params.height=768] The height of the screen to request. * @param {Number} [params.frameRate=15] The number of frames per second to request. * @returns {Object} A flux standard action. */ function startScreenshareFinish(callId, params, error) { return callActionHelper(actionTypes.START_SCREENSHARE_FINISH, callId, { callInfo: { screenshareOptions: params }, error: error }); } /** * Represents an action to stop screensharing over a call. * @method stopScreenshare * @param {string} callId The ID of the call being acted on. * @returns {Object} A flux standard action. */ function stopScreenshare(callId) { return callActionHelper(actionTypes.STOP_SCREENSHARE, callId); } /** * Represents the finish of an action to stop screensharing over a call. * @method stopScreenshareFinish * @param {string} callId The ID of the call being acted on. * @param {Object} error The error object, in the case of an error. * @returns {Object} A flux standard action. */ function stopScreenshareFinish(callId, error) { return callActionHelper(actionTypes.STOP_SCREENSHARE_FINISH, callId, { error: error }); } /** * Represents an action to send a DTMF tone over a call. * @method sendDTMF * @param {string} callId The ID of the call being acted on. * @param {string} tone DTMF tone to send. * @returns {Object} A flux standard action. */ function sendDTMF(callId, tone) { return callActionHelper(actionTypes.SEND_DTMF, callId, { params: { tone: tone } }); } /** * Represents the finish of an action to send a DTMF tone. * Error action only. * @method sendDTMFFinish * @param {string} callId The ID of the call being acted on. * @param {Object} error * @returns {Object} A flux standard action. */ function sendDTMFFinish(callId, error) { var payload = new Error(error); payload.callId = callId; return { type: actionTypes.SEND_DTMF_FINISH, error: true, payload: payload }; } /** * Represents the request to send custom parameters. * @method sendCustomParameters * @param {string} callId The ID of the call being acted on. * @returns {Object} A flux standard action. */ function sendCustomParameters(callId) { return callActionHelper(actionTypes.SEND_CUSTOM_PARAMETERS, callId); } /** * Represents the finish of an action to send custom parameters. * Error action only. * @method sendCustomPrametersFinish * @param {string} callId The ID of the call being acted on. * @param {Object} error The error object, in the case of an error. * @returns {Object} A flux standard action. */ function sendCustomParametersFinish(callId, error) { var payload = new Error(error); payload.callId = callId; return { type: actionTypes.SEND_CUSTOM_PARAMETERS_FINISH, error: true, payload: payload }; } /** * Represents the request to forward an incoming call. * @method forwardCall * @param {string} callId The ID of the call being acted on. * @param {string} destination The user the call is to be forwarded to. * @returns {Object} A flux standard action. */ function forwardCall(callId, destination) { return callActionHelper(actionTypes.FORWARD_CALL, callId, { params: { destination: destination } }); } /** * Represents the finish of an action to forward a call. * @method forwardCallFinish * @param {string} callId The ID of the call being acted on. * @param {Object} error The error object, in the case of an error. * * @returns {Object} A flux standard action. */ function forwardCallFinish(callId, error) { return callActionHelper(actionTypes.FORWARD_CALL_FINISH, callId, { error: error }); } /** * Represents the request to transfer a call (direct transfer). * @method directTransfer * @param {string} callId The ID of the call being acted on. * @param {string} destination The user the call is to be transfered to. * @returns {Object} A flux standard action. */ function directTransfer(callId, destination) { return callActionHelper(actionTypes.DIRECT_TRANSFER, callId, { params: { destination: destination } }); } /** * Represents the finish of an action to transfer a call. * @method directTransferFinish * @param {string} callId The ID of the call being acted on. * @param {Object} error The error object, in the case of an error. * * @returns {Object} A flux standard action. */ function directTransferFinish(callId, error) { return callActionHelper(actionTypes.DIRECT_TRANSFER_FINISH, callId, { error: error }); } /** * Represents the request to transfer a call (consultative transfer). * @method consultativeTransfer * @param {string} callId The ID of the call being acted on. * @param {string} destination The callId to be transfered to. * @returns {Object} A flux standard action. */ function consultativeTransfer(callId, destination) { return callActionHelper(actionTypes.CONSULTATIVE_TRANSFER, callId, { params: { destination: destination } }); } /** * Represents the finish of an action to transfer a call. * @method consultativeTransferFinish * @param {string} callId The ID of the call being acted on. * @param {Object} error The error object, in the case of an error. * @returns {Object} A flux standard action. */ function consultativeTransferFinish(callId, error) { return callActionHelper(actionTypes.CONSULTATIVE_TRANSFER_FINISH, callId, { error: error }); } /** * Represents the request to join two calls. * @method joinCall * @param {string} callId The ID of the call being acted on. * @param {string} destination The callId to be joined with. * @returns {Object} A flux standard action. */ function joinCall(callId, destination, callInfo) { return callActionHelper(actionTypes.JOIN_CALL, callId, { callInfo: callInfo, params: { destination: destination } }); } /** * Represents the finish of an action to join two calls. * @method joinCallFinish * @param {string} callId The ID of the call being acted on. * @param {Array} joinedCalls List of call IDs that were joined. * @param {Object} $2 * @param {Object} $2.callInfo Call state properties. * @param {Object} $2.error The error object, in the case of an error. * @returns {Object} A flux standard action. */ function joinCallFinish(callId, joinedCalls, _ref2) { var callInfo = _ref2.callInfo, error = _ref2.error; return callActionHelper(actionTypes.JOIN_CALL_FINISH, callId, { error: error, callInfo: callInfo, params: { joinedCalls: joinedCalls } }); } /** * Represents a request to start the anonymous call process. * @method makeAnonymousCall * @param {string} callee Full user ID of the call recipient. * @param {string} callId A unique identifier for the call. * @param {Object} credentials Information needed to validate a token anonymous call. * @param {Object} [options={}] Call options. * @returns {Object} A flux standard action. */ function makeAnonymousCall(callee, callId) { var credentials = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; return { type: actionTypes.MAKE_CALL_ANONYMOUS, payload: { callee: callee, callId: callId, credentials: credentials, callInfo: (0, _extends3.default)({}, options) } }; } /***/ }), /***/ "./src/call/interface/actions/devices.js": /*!***********************************************!*\ !*** ./src/call/interface/actions/devices.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); exports.checkDevices = checkDevices; exports.checkDevicesFinish = checkDevicesFinish; exports.setDefaultDevices = setDefaultDevices; exports.setDefaultDevicesFinish = setDefaultDevicesFinish; exports.changeSpeaker = changeSpeaker; exports.changeSpeakerFinish = changeSpeakerFinish; exports.changeInputDevices = changeInputDevices; exports.changeInputDevicesFinish = changeInputDevicesFinish; var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _calls = __webpack_require__(/*! ./calls */ "./src/call/interface/actions/calls.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Represents a request to check media devices. * @method checkDevices * @returns {Object} A flux standard action. */ function checkDevices() { return { type: actionTypes.CHECK_DEVICES }; } /** * Represents that media devices have been checked. * @method checkDevicesFinish * @param {Object} $0 * @param {Object} $0.devices * @param {Error} $0.error * @returns {Object} A flux standard action. */ function checkDevicesFinish(_ref) { var devices = _ref.devices, error = _ref.error; var action = { type: actionTypes.CHECK_DEVICES_FINISH }; if (error) { action.error = true; action.payload = error; } else { action.payload = devices; } return action; } /** * Represents a request to set default devices for calls. * @method setDefaultDevices * @param {Object} devices * @param {string} [devices.camera] The ID of the camera to set as default. * @param {string} [devices.microphone] The ID of the microphone to set as default. * @param {string} [devices.speaker] The ID of the speaker to set as default. * @return {Object} A flux standard action. */ function setDefaultDevices(devices) { return { type: actionTypes.SET_DEFAULT_DEVICES, payload: (0, _extends3.default)({}, devices) }; } /** * Represents that the default devices was attempted to be set. * @method setDefaultDevicesFinish * @param {Object} $0 * @param {Object} $0.devices The devices that were set as defaults. * @param {Object} $0.error Error object, in the case of an issue. * @return {Object} A flux standard action. */ function setDefaultDevicesFinish(_ref2) { var devices = _ref2.devices, error = _ref2.error; return { type: actionTypes.SET_DEFAULT_DEVICES_FINISH, payload: error || devices, error: !!error }; } /** * Represents a request to change the current speaker in use for a call. * @method changeSpeaker * @param {string} speakerId Id of the speaker. * @return {Object} A flux standard action. */ function changeSpeaker(speakerId) { return { type: actionTypes.CHANGE_SPEAKER, payload: speakerId }; } /** * Represents that the current speaker was attempted to be changed. * @method changeSpeakerFinish * @param {Object} error Error object, in the case of an issue. * @return {Object} A flux standard action. */ function changeSpeakerFinish(_ref3) { var speakerId = _ref3.speakerId, error = _ref3.error; return { type: actionTypes.CHANGE_SPEAKER_FINISH, payload: error || speakerId, error: !!error }; } /** * Represents a request to change the camera/microphone for a call. * @method changeInputDevices * @param {string} callId The ID of the call to act upon. * @return {Object} A flux standard action. */ function changeInputDevices(callId) { return (0, _calls.callActionHelper)(actionTypes.CHANGE_INPUT_DEVICES, callId); } /** * Represents that input devices was (attempted) changed for a call. * @method changeInputDevicesFinish * @param {Object} $0 * @param {string} $0.callId Id of the call that changed. * @param {Object} $0.error Error object, in the case of an issue. * @return {Object} A flux standard action. */ function changeInputDevicesFinish(_ref4) { var callId = _ref4.callId, error = _ref4.error; return (0, _calls.callActionHelper)(actionTypes.CHANGE_INPUT_DEVICES_FINISH, callId, { error: error }); } /***/ }), /***/ "./src/call/interface/actions/index.js": /*!*********************************************!*\ !*** ./src/call/interface/actions/index.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.audioBridgeActions = exports.callsActions = exports.devicesActions = exports.mediaActions = exports.localVideoActions = undefined; var _localVideo = __webpack_require__(/*! ./localVideo */ "./src/call/interface/actions/localVideo.js"); var localVideoActionsImport = _interopRequireWildcard(_localVideo); var _media = __webpack_require__(/*! ./media */ "./src/call/interface/actions/media.js"); var mediaActionsImport = _interopRequireWildcard(_media); var _devices = __webpack_require__(/*! ./devices */ "./src/call/interface/actions/devices.js"); var devicesActionsImport = _interopRequireWildcard(_devices); var _calls = __webpack_require__(/*! ./calls */ "./src/call/interface/actions/calls.js"); var callsActionsImport = _interopRequireWildcard(_calls); var _audioBridge = __webpack_require__(/*! ./audioBridge */ "./src/call/interface/actions/audioBridge.js"); var audioBridgeActionsImport = _interopRequireWildcard(_audioBridge); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } // Apparently the following doesn't work: // export * as newName from './place'; // So import everything from each file, then re-export. var localVideoActions = exports.localVideoActions = localVideoActionsImport; var mediaActions = exports.mediaActions = mediaActionsImport; var devicesActions = exports.devicesActions = devicesActionsImport; var callsActions = exports.callsActions = callsActionsImport; var audioBridgeActions = exports.audioBridgeActions = audioBridgeActionsImport; /***/ }), /***/ "./src/call/interface/actions/localVideo.js": /*!**************************************************!*\ !*** ./src/call/interface/actions/localVideo.js ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.startLocalVideo = startLocalVideo; exports.startLocalVideoFinish = startLocalVideoFinish; exports.stopLocalVideo = stopLocalVideo; exports.stopLocalVideoFinish = stopLocalVideoFinish; var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Represents that local video should be displayed in the container. * @method startLocalVideo * @param {HTMLElement} videoContainer The container to use for local video. * @returns {Object} A flux standard action. */ function startLocalVideo(videoContainer) { return { type: actionTypes.START_LOCAL_VIDEO, payload: videoContainer }; } /** * Represents that a request for local video has finished. * @method startLocalVideoFinish * @param {HTMLElement} videoContainer The container that local video is being displayed in. * @param {KandyError} error A Kandy Error object, if an error occurred. * @returns {Object} A flux standard action. */ function startLocalVideoFinish(videoContainer, error) { return { type: actionTypes.START_LOCAL_VIDEO_FINISH, payload: error || videoContainer, error: !!error }; } /** * Represents that local video should stop being displayed. * @method stopLocalVideo * @returns {Object} A flux standard action. */ function stopLocalVideo() { return { type: actionTypes.STOP_LOCAL_VIDEO }; } /** * Represnts that an action to stop local video has finished. * @method stopLocalVideoFinish * @param {KandyError} error A Kandy Error object, if an error occurred. * @returns {Object} A flux standard action. */ function stopLocalVideoFinish(error) { return { type: actionTypes.STOP_LOCAL_VIDEO_FINISH, payload: error || undefined, error: !!error }; } /***/ }), /***/ "./src/call/interface/actions/media.js": /*!*********************************************!*\ !*** ./src/call/interface/actions/media.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.initMedia = initMedia; exports.initMediaFinish = initMediaFinish; exports.promptUserMedia = promptUserMedia; exports.promptUserMediaFinish = promptUserMediaFinish; var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Represents that media should be initialized. * @method initMedia * @param {Object} [options] * @param {string} [options.chromeExtensionId] ID of the Chrome Screenshare extension to be used. * @returns {Object} A flux standard action. */ function initMedia() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return { type: actionTypes.INIT_MEDIA, payload: options }; } /** * Represents that media has been / tried to be initialized. * @method initMediaFinish * @param {Object} result Information about media support. * @param {boolean} result.error Whether the initiazation was successful or not. * @param {number} result.code A unqiue code describing the result scenario. * @param {string} result.message Human readable message of the result. * @returns {Object} A flux standard action. */ function initMediaFinish(result) { return { type: actionTypes.INIT_MEDIA_FINISH, payload: result }; } /** * Represents an action to prompt user for permission to use speakers or camera. * @method promptUserMedia * @param {Object} [params] * @param {boolean} [params.video] * @param {boolean} [params.audio] * @returns {Object} A flux standard action. */ function promptUserMedia(options) { return { type: actionTypes.PROMPT_USER_MEDIA, payload: options }; } /** * Represents the finish of an action to prompt user for permission to use speakers or camera. * @method promptUserMediaFinish * @param {Object} [error] The error object, in the case of an error. * @param {Object} [params] * @param {boolean} [params.video] * @param {boolean} [params.audio] * @returns {Object} A flux standard action. */ function promptUserMediaFinish(options, error) { if (typeof error !== 'undefined') { return { type: actionTypes.PROMPT_USER_MEDIA_FINISH, payload: { options: options, error: error }, error: !!error }; } else { return { type: actionTypes.PROMPT_USER_MEDIA_FINISH, payload: options }; } } /***/ }), /***/ "./src/call/interface/api.js": /*!***********************************!*\ !*** ./src/call/interface/api.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = api; var _selectors = __webpack_require__(/*! ./selectors */ "./src/call/interface/selectors.js"); var _selectors2 = __webpack_require__(/*! ../../auth/interface/selectors */ "./src/auth/interface/selectors.js"); var _actions = __webpack_require__(/*! ./actions */ "./src/call/interface/actions/index.js"); var _normalization = __webpack_require__(/*! ../utils/normalization */ "./src/call/utils/normalization.js"); var _constants = __webpack_require__(/*! ../constants */ "./src/call/constants.js"); var _v = __webpack_require__(/*! uuid/v4 */ "../../node_modules/uuid/v4.js"); var _v2 = _interopRequireDefault(_v); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _logs = __webpack_require__(/*! ../../logs */ "./src/logs/index.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Get the logger /** * Kandy's call feature is used to make audio and video calls between Kandy * users, or to PSTN phones and SIP endpoints. Kandy will store meta-information * about each call made during the current session in internal state, which can * be accessed via the call getter functions. * * Call functions are namespaced beneath 'call' on the returned Kandy object. * * @public * @module Calls */ /** * Kandy's media features are used to control WebRTC Media Devices. * * Media functions are namespaced beneath 'media' on the returned Kandy object. * * @public * @module Media */ /** * Kandy's audio bridge feature allows multiple audio calls to be bridged together * for a local three-way call. * * Audio bridge functions are namespaced beneath 'audioBridge' on the returned Kandy object. * @public * @module AudioBridge * @requires call */ var log = (0, _logs.getLogManager)().getLogger('CALL'); /** * Call API. * @method api * @param {Function} $0 * @param {Function} $0.dispatch - The redux store's dispatch function. * @param {Function} $0.getState - The redux store's getState function. * @return {Object} api - The call API object. */ // Libraries. function api(_ref) { var dispatch = _ref.dispatch, getState = _ref.getState; var mediaApi = { /** * Sets the selected devices as the default devices. * They will be used for audio output for future calls. * Changing speaker is supported on browser's that support HTMLMediaElement.setSinkId(). * @memberof Media * @public * @requires call * @requires callMe * @method setDefaultDevices * @param {Object} devices * @param {string} [devices.camera] The ID of the camera to set as default. * @param {string} [devices.microphone] The ID of the microphone to set as default. * @param {string} [devices.speaker] The ID of the speaker to set as default. * @example * // Set only the default microphone and camera. * kandy.media.setDefaultDevices({ * camera: 'abc123...', * microphone: 'def456...' * }); */ setDefaultDevices: function setDefaultDevices(devices) { dispatch(_actions.devicesActions.setDefaultDevices(devices)); }, /** Retrieves the available media devices for use. * @memberof Media * @public * @requires call * @requires callMe * @method getDevices */ getDevices: function getDevices() { dispatch(_actions.devicesActions.checkDevices()); }, /** * Starts the local video stream and displays it to the user. * @memberof Media * @public * @requires call * @method startPreviewVideo * @param {HTMLElement} [videoContainer] The container to use for local video. * @example * ``` javascript * var container = document.getElementById('local-video'); * kandy.media.startPreviewVideo(container); * ``` */ startPreviewVideo: function startPreviewVideo(videoContainer) { dispatch(_actions.localVideoActions.startLocalVideo(videoContainer)); }, /** * Stops the local video stream created in `startPreviewVideo`. * @memberof Media * @public * @requires call * @method stopPreviewVideo */ stopPreviewVideo: function stopPreviewVideo() { dispatch(_actions.localVideoActions.stopLocalVideo()); }, /** * Initialize media to ensure webRTC support * If you are calling this manually, you NEED to pass the call configs * to this API. Otherwise it will not properly check for screensharing * support. * @memberof Media * @requires call * @requires callMe * @method init * @param {Object} [options] * @param {string} [options.chromeExtensionId] The ID of the Chrome Screenshare extension, if your application will be using screenshare on Chrome. */ init: function init(options) { dispatch(_actions.mediaActions.initMedia(options)); }, /** * Prompt the user for permission to use their audio and/or video devices. * * @memberof Media * @public * @requires call * @method promptUserMedia * @param {Object} [options] * @param {boolean} [options.video] Whether to get permission for video. * @param {boolean} [options.audio] Whether to get permission for audio. */ promptUserMedia: function promptUserMedia() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; dispatch(_actions.mediaActions.promptUserMedia(options)); } }; var callApi = { /** * Retrieves the state of calls made during the current session. * * @public * @memberof Calls * @requires call * @requires callMe * @method getAll * @return {Array} Call objects. * @example * let calls = kandy.call.getAll(); * let currentCalls = calls.filter(call => { * return call.state === kandy.call.states.IN_CALL; * }); */ getAll: function getAll() { return (0, _selectors.getCalls)(getState()); }, /** * Retrieves a call from state with a specific call ID. * * @public * @memberof Calls * @requires call * @requires callMe * @method getById * @param {string} callId The ID of the call to retrieve. * @return {Object} A call object. */ getById: function getById(callId) { return (0, _selectors.getCallById)(getState(), callId); }, /* * Retrieves media support information. Requires `initMedia` to have * been called beforehand. * @requires call * @requires callMe * @method getMediaInfo * @param {Object} state Redux state. * @return {Object} */ getMediaInfo: function getMediaInfo() { return (0, _selectors.getMediaInfo)(getState()); }, /** * Changes camera and microphone for the specified call. * The call will use the current selected default devices. * @memberof Calls * @requires call * @requires callMe * @method changeInputDevices * @param {string} callId The ID of the call to act upon. */ changeInputDevices: function changeInputDevices(callId) { dispatch(_actions.devicesActions.changeInputDevices(callId)); }, /** * Changes speaker used for call audio output. * Supported on browser's that support HTMLMediaElement.setSinkId(). * @memberof Calls * @requires call * @requires callMe * @method changeSpeaker * @param {string} speakerId ID of the speaker to use for call audio. */ changeSpeaker: function changeSpeaker(speakerId) { dispatch(_actions.devicesActions.changeSpeaker(speakerId)); }, /** * States of a call. * @public * @memberof Calls * @requires call * @requires callMe * @property {string} IN_CALL The call is on-going. * @property {string} RINGING The call has been established and is waiting for a user response. * @property {string} ENDED The call has been terminated. * @property {string} ON_HOLD The call has been put on hold locally. * @property {string} ON_REMOTE_HOLD The call has been put on hold remotely. * @example * kandy.on('call:stateChange', function(callInfo) { * if(callInfo.state === kandy.call.states.ENDED) { * // Call has ended. * } * }); */ states: _constants.CALL_STATES, /** * State of the media connection within a call. * @public * @memberof Calls * @requires call * @requires callMe * @property {string} NEW A new media connection process has started. * @property {string} CHECKING Media is searching for a connection. * @property {string} CONNECTED Media has found a connection, but may still be searching for a better connection to use. * @property {string} COMLETED Media has finished searching and been established. Audio/video should now be flowing on the call. * @property {string} FAILED Media was not able to find a connection. Audio/video will not flow. * @property {string} DISCONNECTED The media connection has lost its connection and is trying to recover. * @property {string} CLOSED The media connection has shut down. * */ mediaStates: _constants.ICE_MEDIA_STATES, /** * Start an outgoing call. * * @public * @memberof Calls * @requires call * @method make * @param {string} callee Full user ID of the call recipient. * @param {Object} [options] Call options. * @param {string} [options.from] Sets the display name of the caller to be sent alongside the username of the user. * @param {boolean} [options.isVideoEnabled=true] Whether to enable video during the call. If false, you cannot start video mid-call. * @param {Object} [options.contact] Object containing firstName and lastName of caller. * @param {boolean} [options.sendInitialVideo=false] Whether to start the call sending the local video stream. * @param {boolean} [options.isAudioEnabled=true] Whether to enable audio during the call. Setting this to false will disable audio for the call. * @param {boolean} [options.webrtcdtls=true] Whether to enable DTLS for WebRTC calls. * @param {Object} [options.videoResolution] The object to configure the local video resolution. * @param {number} [options.videoResolution.height] The height in pixels of the local video. * @param {number} [options.videoResolution.width] The width in pixels of the local video. * @param {Array.<{name: string, value:string}>} [options.customParameters] Custom SIP header parameters for the SIP backend. * @param {HTMLElement} [options.remoteVideoContainer] The HTML element to use as a container for the remote video. * @param {HTMLElement} [options.localVideoContainer] The HTML element to use as a container for the local video. * @param {boolean} [options.normalizeAddress=false] Whether to enable normalization of callee address. * @return {string} Id of the outgoing call. * @example * let remoteContainer = document.getElementById('remote-container'); * // Start a video call that only shows the remote media (not local). * let callId = kandy.call.make('sampleUser@kandy.io', { * isVideoEnabled: true, * sendInitialVideo: true, * remoteVideoContainer: remoteContainer, * customParameters: [ * { * "name": "X-GPS", * "value": "42.686032,23.344565" * } * ] * }); */ make: function make(callee) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var callOptions = ['from', 'contact', 'isAudioEnabled', 'isVideoEnabled', 'sendInitialVideo', 'webrtcdtls', 'remoteVideoContainer', 'localVideoContainer', 'normalizeAddress', 'videoResolution', 'customParameters', // Internal options. 'sendScreenShare', 'mediaSourceId']; // Pick out the valid call options. options = (0, _fp.pick)(callOptions, options); options.contact = (0, _fp.defaults)({ firstName: '', lastName: '' }, options.contact); if (options.normalizeAddress) { // Normalize callee addresses callee = (0, _normalization.normalizeSipUri)(callee, (0, _selectors2.getDomain)(getState())); log.info('Address normalized to: ', callee); } // Create our own call ID for storing in state. var callId = (0, _v2.default)(); dispatch(_actions.callsActions.makeCall(callee, callId, options)); return callId; }, /** * Answer an incoming call. * * @public * @memberof Calls * @requires call * @method answer * @param {string} callId The ID of the call to answer. * @param {Object} [options] Call options. * @param {boolean} [options.isVideoEnabled] Whether to enable video during the call. If false, you cannot start video mid-call. * @param {boolean} [options.sendInitialVideo] Whether to start the call sending the local video stream. * @param {boolean} [options.isAudioEnabled=true] Whether to enable audio during the call. Setting this to false will disable audio for the call. * @param {Object} [options.videoResolution] The object to configure the local video resolution. * @param {number} [options.videoResolution.height] The height in pixels of the local video. * @param {number} [options.videoResolution.width] The width in pixels of the local video. * @param {HTMLElement} [options.localVideoContainer] The HTML element to use as a container for the remote video. * @param {HTMLElement} [options.remoteVideoContainer] The HTML element to use as a container for the local video. */ answer: function answer(callId, options) { dispatch(_actions.callsActions.answerCall(callId, options)); }, /** * Ignore an incoming call. * * @public * @memberof Calls * @requires call * @method ignore * @param {string} callId The ID of the call to ignore. */ ignore: function ignore(callId) { dispatch(_actions.callsActions.ignoreCall(callId)); }, /** * Reject an incoming call. * * @public * @memberof Calls * @requires call * @method reject * @param {string} callId The ID of the call to reject. */ reject: function reject(callId) { dispatch(_actions.callsActions.rejectCall(callId)); }, /** * End an on-going call. * * @public * @memberof Calls * @requires call * @requires callMe * @method end * @param {string} callId Id of the call to end. */ end: function end(callId) { dispatch(_actions.callsActions.endCall(callId)); }, /* * Mid-Call operations. */ /** * Mute the local audio stream on an ongoing call. * * @public * @memberof Calls * @requires call * @requires callMe * @method mute * @param {string} callId The ID of the call being acted on. */ mute: function mute(callId) { dispatch(_actions.callsActions.muteCall(callId)); }, /** * Unmute the local audio stream on an ongoing call. * * @public * @memberof Calls * @requires call * @requires callMe * @method unmute * @param {string} callId The ID of the call being acted on. */ unmute: function unmute(callId) { dispatch(_actions.callsActions.unMuteCall(callId)); }, /** * Retrieves a call's customParameters. * * @public * @memberof Calls * @requires call * @requires callMe * @method getCustomParameters * @param {string} callId The ID of the call to retrieve custom parameters. * @return {Array.<{name: string, value:string}>} Custom parameters of the call. */ getCustomParameters: function getCustomParameters(callId) { return (0, _selectors.getCustomParametersById)(getState(), callId); }, /** * Set custom parameters on an ongoing call. * * @public * @memberof Calls * @requires call * @requires callMe * @method setCustomParameters * @param {string} callId The ID of the call being acted on. * @param {Array.<{name: string, value:string}>} customParameters Custom parameters for the call. * @example * // Set custom parameters for call. * kandy.call.setCustomParameters( * callId, * [ * { "name": "X-GPS", * "value": "42.686032,23.344565" * } * ] * }); */ setCustomParameters: function setCustomParameters(callId) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; dispatch(_actions.callsActions.setCustomParameters(callId, params)); }, /** * Start local video stream for an ongoing call. * * @public * @memberof Calls * @requires call * @requires callMe * @method startVideo * @param {string} callId Id of the call being acted on. * @param {Object} [options] options Options for the video stream. * @param {Object} [options.videoResolution] videoResolution The video resolution configuation object. * @param {number} [options.videoResolution.height] height The height of the outoing video in pixels. * @param {number} [options.videoResolution.width] width The width of the outoing video in pixels. */ startVideo: function startVideo(callId) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; dispatch(_actions.callsActions.startVideo(callId, options)); }, /** * Stop local video for an ongoing call. * * @public * @memberof Calls * @requires call * @requires callMe * @method stopVideo * @param {string} callId Id of the call being acted on. */ stopVideo: function stopVideo(callId) { dispatch(_actions.callsActions.stopVideo(callId)); }, /** * Put an ongoing call on hold. * * @public * @memberof Calls * @requires call * @requires callMe * @method hold * @param {string} callId Id of the call being acted on. */ hold: function hold(callId) { dispatch(_actions.callsActions.holdCall(callId)); }, /** * Return a held call to ongoing. * * @public * @memberof Calls * @requires call * @requires callMe * @method unhold * @param {string} callId Id of the call being acted on. */ unhold: function unhold(callId) { dispatch(_actions.callsActions.unHoldCall(callId)); }, /** * Starts sharing a screen over a call. * * @public * @memberof Calls * @requires call * @requires callMe * @method startScreenshare * @param {string} callId Id of the call being acted on. * @param {Object} options * @param {string} options.mediaSourceId Id of the media screen to share. * @param {Number} [options.height=768] The height of the video stream to send. * @param {Number} [options.width=1024] The width of the video stream to send. * @param {Number} [options.frameRate=15] The number of frames per second to request. */ startScreenshare: function startScreenshare(callId) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; dispatch(_actions.callsActions.startScreenshare(callId, options)); }, /** * Stops sharing a screen over a call. * * @public * @memberof Calls * @requires call * @requires callMe * @method stopScreenshare * @param {string} callId Id of the call being acted on. */ stopScreenshare: function stopScreenshare(callId) { dispatch(_actions.callsActions.stopScreenshare(callId)); }, /** * Send a DTMF tone over a call. * * @public * @memberof Calls * @requires call * @requires callMe * @method sendDTMF * @param {string} callId Id of the call being acted on. * @param {number} tone DTMF tone to send. Valid values are [0,1,2,3,4,5,6,7,8,9,#]. * */ sendDTMF: function sendDTMF(callId, tone) { dispatch(_actions.callsActions.sendDTMF(callId, tone)); }, /** * Explicitly send the current custom parameters for a call. * * @public * @memberof Calls * @requires call * @requires callMe * @method sendCustomParameters * @param {string} callId Id of the call being acted on. */ sendCustomParameters: function sendCustomParameters(callId) { dispatch(_actions.callsActions.sendCustomParameters(callId)); }, /** * Forward an incoming call to another user. * * @public * @memberof Calls * @requires call * @method forwardCall * @param {string} callId Id of the call being acted on. * @param {string} destination The user to forward the call to. */ forwardCall: function forwardCall(callId, destination) { dispatch(_actions.callsActions.forwardCall(callId, destination)); }, /** * Transfer a call to another user. * * @public * @memberof Calls * @requires call * @method directTransfer * @param {string} callId Id of the call being acted on. * @param {string} destination The user to transfer the call to. */ directTransfer: function directTransfer(callId, destination) { dispatch(_actions.callsActions.directTransfer(callId, destination)); }, /** * Transfer a call to another user. * * @public * @memberof Calls * @requires call * @method consultativeTransfer * @param {string} callId Id of the call being acted on. * @param {string} destination The callId to transfer the call to. */ consultativeTransfer: function consultativeTransfer(callId, destination) { dispatch(_actions.callsActions.consultativeTransfer(callId, destination)); }, /** * Join two calls (both must be on hold and audio only). The joined call can be referenced via callId. * * @public * @memberof Calls * @requires call * @method join * @param {string} callId Id of the call being acted on. * @param {string} destination The callId to join the call with. */ join: function join(callId, destination) { dispatch(_actions.callsActions.joinCall(callId, destination)); }, /** * Retrieves the resolution of the remote video of a call. * @memberof Calls * @requires call * @requires callMe * @method getRemoteVideoResolutions * @param {string} callId Id of the call being acted on. * @return {Object} Height and width properties of the remote video. */ getRemoteVideoResolutions: function getRemoteVideoResolutions(callId) { /* Implement this in the API temporarily, since this should be done * automatically on a state change, but we can't due to FCS timing * issues. See KAA-424. */ var call = (0, _selectors.getCallById)(getState(), callId); // If the remote side is sending video and we're rendering it.. if (call && call.remoteVideoState.indexOf('send') > -1 && call.remoteVideoContainer) { var videoTag = void 0; // Find the video tag. // Turn the nodeList into a real array so IE11 can us forEach var childNodes = Array.prototype.slice.call(call.remoteVideoContainer.childNodes); childNodes.forEach(function (node) { if (node.tagName === 'VIDEO') { videoTag = node; } }); if (videoTag) { return { height: videoTag.videoHeight, width: videoTag.videoWidth }; } } } }; var audioBridgeApi = { /** * Creates a local bridge that can be used to join audio calls. * @public * @memberof AudioBridge * @method create * @return {string} ID used to identify the bridge. */ create: function create() { // Create our own ID for storing in state. var bridgeId = (0, _v2.default)(); dispatch(_actions.audioBridgeActions.createAudioBridge(bridgeId)); return bridgeId; }, /** * Closes an existing audio bridge. * @public * @memberof AudioBridge * @method close * @param {string} bridgeId Identifier for the bridge to act on. */ close: function close(bridgeId) { dispatch(_actions.audioBridgeActions.closeAudioBridge(bridgeId)); }, /** * Adds a call to the specified local audio bridge. * @public * @memberof AudioBridge * @method addCall * @param {string} bridgeId Identifier for the bridge to act on. * @param {string} callId Identifier for the call to add. */ addCall: function addCall(bridgeId, callId) { dispatch(_actions.audioBridgeActions.addCallToBridge(bridgeId, callId)); }, /** * Remove a specified call from the local audio bridge. * @public * @memberof AudioBridge * @method removeCall * @param {string} bridgeId Identifier for the bridge to act on. * @param {string} callId Identifier for the call to remove. */ removeCall: function removeCall(bridgeId, callId) { dispatch(_actions.audioBridgeActions.removeCallFromBridge(bridgeId, callId)); }, /** * Mute the local audio for all of the calls on the bridge. * @public * @memberof AudioBridge * @method mute * @param {string} bridgeId Identifier for the bridge to act on. */ mute: function mute(bridgeId) { dispatch(_actions.audioBridgeActions.muteAudioBridge(bridgeId)); }, /** * Unmute the local audio for all of the calls on the bridge. * @public * @memberof AudioBridge * @method unmute * @param {string} bridgeId Identifier for the bridge to act on. */ unmute: function unmute(bridgeId) { dispatch(_actions.audioBridgeActions.unmuteAudioBridge(bridgeId)); }, /** * Retrieve information about audio bridges. * @public * @memberof AudioBridge * @method getAll * @return {Array} List of active audio bridges. */ getAll: function getAll() { return (0, _selectors.getAudioBridges)(getState()); }, /** * Retrieve all calls currently part of an audio bridge. * @public * @memberof AudioBridge * @method getBridgeCalls * @param {string} bridgeId The ID of the bridge whose calls we wish to retrieve * @return {Array} List of calls currently part of the specified audio bridge. */ getBridgeCalls: function getBridgeCalls(bridgeId) { return (0, _selectors.getBridgeCalls)(getState(), bridgeId); } }; // TODO: Split up this file. It's getting too large. return { call: callApi, media: mediaApi, audioBridge: audioBridgeApi }; } /***/ }), /***/ "./src/call/interface/eventTypes.js": /*!******************************************!*\ !*** ./src/call/interface/eventTypes.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * An outgoing call has successfully started. * * @public * @memberof Calls * @requires call * @requires callMe * @event call:start * @param {Object} params * @param {string} params.callId The Id of the call. */ var CALL_STARTED = exports.CALL_STARTED = 'call:start'; /** * A new incoming call has been received. * * @public * @memberof Calls * @requires call * @event call:receive * @param {Object} params * @param {string} params.callId The Id of the call. * @example * kandy.on('call:receive', function(callId) { * // We have received a call, prompt the user to respond. * promptUser(kandy.call.getById(callId)); * }); */ var CALL_INCOMING = exports.CALL_INCOMING = 'call:receive'; /** * Calls have been successfully joined. * @public * @requires call * @memberof Calls * @event call:join * @param {Object} params * @param {string} params.callId The ID of the new, joined call. * @param {Array} params.joinedCalls The two calls that were joined together. */ var CALL_JOIN = exports.CALL_JOIN = 'call:join'; /** * A call has successfully been forwarded. * * @public * @memberof Calls * @requires call * @event call:forward * @param {Object} params * @param {string} params.callId The Id of the call. */ var CALL_FORWARDED = exports.CALL_FORWARDED = 'call:forward'; /** * A call's state has changed. * * @public * @memberof Calls * @requires call * @requires callMe * @event call:stateChange * @param {Object} params * @param {string} params.callId The Id of the call. * @param {string} params.state New state of the call. * @param {Object} params.transition Information about the state change. * @param {number} params.transition.code Code representing the reason for the state change. * @param {string} params.transition.reasonText Explanation of the status code. * @param {string} params.transition.oldState The previous state of the call. * @example * kandy.on('call:stateChange', function(params) { * // We are now in call with another user, so update our app to show it. * if(params.state === kandy.call.states.IN_CALL) { * renderCall(kandy.call.getById(params.callId)); * } * }); */ var CALL_STATE_CHANGE = exports.CALL_STATE_CHANGE = 'call:stateChange'; /** * A call's media state has changed. * @public * @memberof Calls * @requires call * @requires callMe * @event call:mediaStateChange * @param {Object} params * @param {string} params.callId The Id of the call. * @param {string} params.mediaState New media state of the call. */ var CALL_MEDIA_STATE_CHANGE = exports.CALL_MEDIA_STATE_CHANGE = 'call:mediaStateChange'; /** * Screensharing has been started turned on or off. * * @public * @memberof Calls * @requires call * @requires callMe * @event call:screenshareChange * @param {Object} params * @param {string} params.callId The Id of the call. */ var CALL_SCREENSHARE_CHANGE = exports.CALL_SCREENSHARE_CHANGE = 'call:screenshareChange'; /** * An error has occurred with a call. * * @public * @memberof Calls * @requires call * @requires callMe * @event call:error * @param {Object} params * @param {string} params.callId The id of the call. * @param {KandyError} params.error The Kandy error object. */ var CALL_ERROR = exports.CALL_ERROR = 'call:error'; /** * The status of previewing local video has changed. * @public * @memberof Media * @requires call * @event videoPreview:change * @param {Object} params * @param {boolean} params.displaying Whether the local video preview is being displayed or not. */ var LOCAL_VIDEO_CHANGE = exports.LOCAL_VIDEO_CHANGE = 'videoPreview:change'; /** * An error has occurred when changing local video preview status. * @public * @memberof Media * @requires call * @event videoPreview:error * @param {Object} params * @param {KandyError} params.error Information about the error. */ var LOCAL_VIDEO_ERROR = exports.LOCAL_VIDEO_ERROR = 'videoPreview:error'; // Media devices. /** * A change has been made to default devices used for calls. * @public * @memberof Media * @requires call * @requires callMe * @event devices:defaultsChange * @param {Object} params * @param {Object} params.devices The devices now set as default. */ var DEVICE_DEFAULT_CHANGE = exports.DEVICE_DEFAULT_CHANGE = 'devices:defaultsChange'; /** * Available media devices have been changed. * @memberof Media * @requires call * @requires callMe * @event devices:change * @param {Object} params * @param {Object} params.devices The devices, seperated by device type. */ var DEVICE_CHANGE = exports.DEVICE_CHANGE = 'devices:change'; /** * Media device permissions have been granted by the user. * @memberof Media * @requires call * @event media:permissions * @param {Object} params * @param {Object} params.devices The devices to request permission for. * @param {KandyError} params.error The Kandy error object. * @param {boolean} params.granted Whether premission was granted? */ var MEDIA_PERMISSIONS = exports.MEDIA_PERMISSIONS = 'media:permissions'; /** * An error occurred while performing a device operation. * @memberof Media * @requires call * @requires callMe * @param {Object} params * @param {KandyError} params.error The Kandy error object. */ var DEVICE_ERROR = exports.DEVICE_ERROR = 'devices:error'; /** * Media support has been checked. * @public * @memberof Media * @requires call * @requires callMe * @event media:initialize * @param {Object} params * @param {Object} params.result Results of initializing media. * @param {boolean} params.result.error Whether the initiazation was successful or not. * @param {number} params.result.code A unqiue code describing the result scenario. * @param {string} params.result.message Human readable message of the result. */ var MEDIA_INITIALIZED = exports.MEDIA_INITIALIZED = 'media:initialize'; /** * A change has occurred in an audio bridge. * @public * @memberof AudioBridge * @event audioBridge:change * @param {Object} params * @param {string} bridgeId The bridge that the change occurred on. */ var BRIDGE_CHANGE = exports.BRIDGE_CHANGE = 'audioBridge:change'; /** * An error occurred while performing an audio bridge operation. * @public * @memberof AudioBridge * @event audioBridge:error * @param {Object} params * @param {KandyError} params.error The Kandy error object. */ var BRIDGE_ERROR = exports.BRIDGE_ERROR = 'audioBridge:error'; /***/ }), /***/ "./src/call/interface/events.js": /*!**************************************!*\ !*** ./src/call/interface/events.js ***! \**************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/call/interface/eventTypes.js"); var eventTypes = _interopRequireWildcard(_eventTypes); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Helper function for call error events. * @method callErrorEvent * @param {Object} action * @return {Object} */ function callErrorEvent(action) { if (action.error) { return { type: eventTypes.CALL_ERROR, args: { callId: action.payload.callId, error: action.payload } }; } } var events = {}; // Actions that only emit an event on an error action. // For most, callStateChange emits the success event. events[actionTypes.IGNORE_CALL_FINISH] = callErrorEvent; events[actionTypes.REJECT_CALL_FINISH] = callErrorEvent; events[actionTypes.END_CALL_FINISH] = callErrorEvent; events[actionTypes.START_VIDEO_FINISH] = callErrorEvent; events[actionTypes.STOP_VIDEO_FINISH] = callErrorEvent; events[actionTypes.HOLD_CALL_FINISH] = callErrorEvent; events[actionTypes.UNHOLD_CALL_FINISH] = callErrorEvent; events[actionTypes.SEND_DTMF_FINISH] = callErrorEvent; events[actionTypes.SEND_CUSTOM_PARAMETERS_FINISH] = callErrorEvent; events[actionTypes.MAKE_CALL_FINISH] = function (action) { if (action.error) { // Call start error event. return callErrorEvent(action); } else { // Call start event. return { type: eventTypes.CALL_STARTED, args: { callId: action.payload.callId } }; } }; events[actionTypes.CALL_INCOMING] = function (action) { return { type: eventTypes.CALL_INCOMING, args: { callId: action.payload.callId } }; }; events[actionTypes.FORWARD_CALL_FINISH] = function (action) { if (action.error) { return callErrorEvent(action); } else { return { type: eventTypes.CALL_FORWARDED, args: { callId: action.payload.callId } }; } }; events[actionTypes.CALL_STATE_CHANGE] = function (action) { return { type: eventTypes.CALL_STATE_CHANGE, args: { callId: action.payload.callId, state: action.payload.state, transition: action.payload.transition } }; }; events[actionTypes.CALL_MEDIA_STATE_CHANGE] = function (action) { return { type: eventTypes.CALL_MEDIA_STATE_CHANGE, args: { callId: action.payload.callId, mediaState: action.payload.mediaState } }; }; events[actionTypes.ANSWER_CALL_FINISH] = function (action) { // For a successful answer call, an event is emitted // as a stateChanged event. if (action.error) { // Call start error event. return callErrorEvent(action); } }; events[actionTypes.JOIN_CALL_FINISH] = function (action) { if (!action.error) { return { type: eventTypes.CALL_JOIN, args: { callId: action.payload.callId, joinedCalls: action.payload.params.joinedCalls } }; } }; events[actionTypes.MUTE_CALL_FINISH] = function (action) { if (action.error) { return callErrorEvent(action); } else { return { type: eventTypes.CALL_STATE_CHANGE, args: { callId: action.payload.callId } }; } }; events[actionTypes.UNMUTE_CALL_FINISH] = function (action) { if (action.error) { return callErrorEvent(action); } else { return { type: eventTypes.CALL_STATE_CHANGE, args: { callId: action.payload.callId } }; } }; events[actionTypes.START_SCREENSHARE_FINISH] = function (action) { if (action.error) { return callErrorEvent(action); } else { return { type: eventTypes.CALL_SCREENSHARE_CHANGE, args: { callId: action.payload.callId } }; } }; events[actionTypes.STOP_SCREENSHARE_FINISH] = function (action) { if (action.error) { return callErrorEvent(action); } else { return { type: eventTypes.CALL_SCREENSHARE_CHANGE, args: { callId: action.payload.callId } }; } }; // TODO: Store devices in state on device change // Notify an application when media devices change. events[actionTypes.CHECK_DEVICES_FINISH] = function (action) { if (!action.error) { return { type: eventTypes.DEVICE_CHANGE, args: { devices: action.payload } }; } else { return { type: eventTypes.DEVICE_ERROR, args: { devices: {}, error: action.payload } }; } }; events[actionTypes.SET_DEFAULT_DEVICES_FINISH] = function (action) { if (action.error) { return { type: eventTypes.DEVICE_ERROR, args: { error: action.payload } }; } else { return { type: eventTypes.DEVICE_DEFAULT_CHANGE, args: { devices: action.payload } }; } }; events[actionTypes.PROMPT_USER_MEDIA_FINISH] = function (action) { if (action.error) { return { type: eventTypes.MEDIA_PERMISSIONS, args: { granted: false, devices: action.payload.options, error: action.payload.error } }; } else { return { type: eventTypes.MEDIA_PERMISSIONS, args: { granted: true, devices: action.payload } }; } }; // TODO: Store devices in state on device change events[actionTypes.CHANGE_SPEAKER_FINISH] = function (action) { if (action.error) { return { type: eventTypes.DEVICE_ERROR, args: { error: action.payload } }; } else { return { type: eventTypes.DEVICE_CHANGE, args: { type: 'speaker', deviceId: action.payload } }; } }; events[actionTypes.INIT_MEDIA_FINISH] = function (action) { return { type: eventTypes.MEDIA_INITIALIZED, args: { result: action.payload } }; }; events[actionTypes.START_LOCAL_VIDEO_FINISH] = function (action) { if (action.error) { return { type: eventTypes.LOCAL_VIDEO_ERROR, args: { error: action.payload } }; } else { return { type: eventTypes.LOCAL_VIDEO_CHANGE, args: { displaying: true } }; } }; events[actionTypes.STOP_LOCAL_VIDEO_FINISH] = function (action) { if (action.error) { return { type: eventTypes.LOCAL_VIDEO_ERROR, args: { error: action.payload } }; } else { return { type: eventTypes.LOCAL_VIDEO_CHANGE, args: { displaying: false } }; } }; function audioBridgeEvents(action) { if (action.error) { return { type: eventTypes.BRIDGE_ERROR, args: { error: action.payload } }; } else { return { type: eventTypes.BRIDGE_CHANGE, args: { bridgeId: action.payload.bridgeId } }; } } events[actionTypes.CREATE_AUDIO_BRIDGE_FINISH] = audioBridgeEvents; events[actionTypes.CLOSE_AUDIO_BRIDGE_FINISH] = audioBridgeEvents; events[actionTypes.UPDATE_AUDIO_BRIDGE_CALLS] = audioBridgeEvents; events[actionTypes.MUTE_AUDIO_BRIDGE_FINISH] = audioBridgeEvents; events[actionTypes.UNMUTE_AUDIO_BRIDGE_FINISH] = audioBridgeEvents; exports.default = events; /***/ }), /***/ "./src/call/interface/index.js": /*!*************************************!*\ !*** ./src/call/interface/index.js ***! \*************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _api = __webpack_require__(/*! ./api */ "./src/call/interface/api.js"); var _api2 = _interopRequireDefault(_api); var _reducers = __webpack_require__(/*! ./reducers */ "./src/call/interface/reducers/index.js"); var _reducers2 = _interopRequireDefault(_reducers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * This interface is for a call plugin. * @type {string} */ // Import the components of the interface. var name = 'call'; // Export the interface as a single object. exports.default = { name: name, api: _api2.default, reducer: _reducers2.default }; /***/ }), /***/ "./src/call/interface/reducers/audioBridges.js": /*!*****************************************************!*\ !*** ./src/call/interface/reducers/audioBridges.js ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Top-tier reducers: Handles the whole audioBridge state. var reducers = {}; // Bridge-tier reducers: Handles only a specific bridge's state. var bridgeReducers = {}; reducers[actionTypes.CREATE_AUDIO_BRIDGE_FINISH] = { next: function next(state, action) { var newBridge = { id: action.payload.bridgeId, options: action.payload.options, muted: false, calls: [], status: 'OPEN' }; return (0, _fp.concat)(state, newBridge); } }; /* * Bridge-tier reducers. * Receive a single bridge's state as state. */ bridgeReducers[actionTypes.CLOSE_AUDIO_BRIDGE_FINISH] = { next: function next(state) { return (0, _extends3.default)({}, state, { status: 'CLOSED' }); } }; bridgeReducers[actionTypes.MUTE_AUDIO_BRIDGE_FINISH] = { next: function next(state) { return (0, _extends3.default)({}, state, { muted: true }); } }; bridgeReducers[actionTypes.UNMUTE_AUDIO_BRIDGE_FINISH] = { next: function next(state) { return (0, _extends3.default)({}, state, { muted: false }); } }; bridgeReducers[actionTypes.UPDATE_AUDIO_BRIDGE_CALLS] = { next: function next(state, action) { return (0, _extends3.default)({}, state, { calls: action.payload.calls }); } }; /* * Combine all of the bridge-tier reducers into a single reducer, * each with a default state of empty object. */ var bridgeReducer = (0, _reduxActions.handleActions)(bridgeReducers, {}); // Actions routed to bridge-tier reducers. var specificBridgeActions = (0, _reduxActions.combineActions)(actionTypes.CLOSE_AUDIO_BRIDGE_FINISH, actionTypes.MUTE_AUDIO_BRIDGE_FINISH, actionTypes.UNMUTE_AUDIO_BRIDGE_FINISH, actionTypes.UPDATE_AUDIO_BRIDGE_CALLS); /* * Reducer to handle specific bridge actions. * Routes the actions to the bridge-tier reducers. */ reducers[specificBridgeActions] = function (state, action) { return state.map(function (bridge) { if (bridge.id === action.payload.bridgeId) { return bridgeReducer(bridge, action); } else { return bridge; } }); }; /* * Combine all of the top-tier reducers into a single reducer, * each with a default state of an empty object. */ var reducer = (0, _reduxActions.handleActions)(reducers, []); exports.default = reducer; /***/ }), /***/ "./src/call/interface/reducers/calls.js": /*!**********************************************!*\ !*** ./src/call/interface/reducers/calls.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Top-tier reducers: Handles the whole call state. var reducers = {}; // Call-tier reducers: Handles only a specific call's state. var callReducers = {}; /* * Top-tier reducers. * Receives the entire call substate as state. */ /* * Reducer to handle MAKE_CAL action. * Create a new call object and add it to state. */ reducers[actionTypes.MAKE_CALL] = { next: function next(state, action) { var newCall = (0, _extends3.default)({}, action.payload.callInfo, { state: 'INITIATING', muted: false, direction: 'outgoing', isScreensharing: action.payload.callInfo.sendScreenShare || false, originalRemoteParticipant: { displayNumber: action.payload.callInfo.to }, id: action.payload.callId }); return (0, _fp.concat)(state, newCall); } }; /* * Reducer to handle CALL_INCOMING actions. * Cannot have an error 'incoming call'. Add the * incoming call to state. */ reducers[actionTypes.CALL_INCOMING] = { next: function next(state, action) { var newCall = (0, _extends3.default)({ state: 'RINGING', muted: false, direction: 'incoming', isScreensharing: false, id: action.payload.callId }, action.payload.callInfo); return (0, _fp.concat)(state, newCall); } }; reducers[actionTypes.JOIN_CALL_FINISH] = { next: function next(state, action) { var newCall = (0, _extends3.default)({}, action.payload.callInfo, { direction: 'outgoing', id: action.payload.callId }); return (0, _fp.concat)(state, newCall); } }; /* * Call-tier reducers. * Receive a single call's state as state. */ /* * Reducer to handle SET_CUSTOM_PARAMETERS actions. */ callReducers[actionTypes.SET_CUSTOM_PARAMETERS] = { next: function next(state, action) { return (0, _extends3.default)({}, state, { customParameters: action.payload.customParameters }); } }; /* * Reducer to handle MAKE_CALL_FINISH actions. * In both cases, update the existing call in state with * the new call state. */ callReducers[actionTypes.MAKE_CALL_FINISH] = { next: function next(state, action) { var callInfo = action.payload.callInfo; return (0, _extends3.default)({}, state, callInfo, { state: 'INITIATED', sendingVideo: callInfo.sendInitialVideo || false }); }, throw: function _throw(state, action) { return (0, _extends3.default)({}, state, action.payload.callInfo, { state: 'ENDED', error: action.payload }); } }; /* * Reducer to handle ANSWER_CALL_FINISH actions. * Only intended to set call info, not current state. */ callReducers[actionTypes.ANSWER_CALL_FINISH] = { next: function next(state, action) { var callInfo = action.payload.callInfo; return (0, _extends3.default)({}, state, callInfo, { sendingVideo: callInfo.sendInitialVideo || false // State change action sets the call's current state. }); }, throw: function _throw(state, action) { return (0, _extends3.default)({}, state, action.payload.callInfo, { error: action.payload // State change action sets the call's current state. }); } }; /* * Reducer to handle CALL_STATE_CHANGE actions. * Change the specified call's state. */ callReducers[actionTypes.CALL_STATE_CHANGE] = { next: function next(state, action) { return (0, _extends3.default)({}, state, action.payload.callInfo, { state: action.payload.state, transition: action.payload.transition }); } }; /* * Reducer to handle media state change actions. * Change the specified call's media state. */ callReducers[actionTypes.CALL_MEDIA_STATE_CHANGE] = { next: function next(state, action) { return (0, _extends3.default)({}, state, { mediaState: action.payload.mediaState }); } }; /* * Reducer to handle MUTE_CALL_FINISH actions. * Change the specified call's state to muted. */ callReducers[actionTypes.MUTE_CALL_FINISH] = { next: function next(state) { return (0, _extends3.default)({}, state, { muted: true }); } }; /* * Reducer to handle UNMUTE_CALL_FINISH actions. * Change the specified call's state to not muted. */ callReducers[actionTypes.UNMUTE_CALL_FINISH] = { next: function next(state) { return (0, _extends3.default)({}, state, { muted: false }); } }; /* * Handles changing the call's screensharing state. */ callReducers[actionTypes.START_SCREENSHARE_FINISH] = { next: function next(state) { return (0, _extends3.default)({}, state, { isScreensharing: true }); } }; /* * Handles changing the call's screensharing state. */ callReducers[actionTypes.STOP_SCREENSHARE_FINISH] = { next: function next(state) { return (0, _extends3.default)({}, state, { isScreensharing: false }); } }; /* * Handles changing the call's video state. */ callReducers[actionTypes.START_VIDEO_FINISH] = { next: function next(state) { return (0, _extends3.default)({}, state, { sendingVideo: true }); } }; /* * Handles changing the call's video state. */ callReducers[actionTypes.STOP_VIDEO_FINISH] = { next: function next(state) { return (0, _extends3.default)({}, state, { sendingVideo: false }); } }; /* * Combine all of the call-tier reducers into a single reducer, * each with a default state of empty object. */ var callReducer = (0, _reduxActions.handleActions)(callReducers, {}); // Actions routed to call-tier reducers. var specificCallActions = (0, _reduxActions.combineActions)(actionTypes.MAKE_CALL_FINISH, actionTypes.ANSWER_CALL_FINISH, actionTypes.CALL_STATE_CHANGE, actionTypes.CALL_MEDIA_STATE_CHANGE, actionTypes.MUTE_CALL_FINISH, actionTypes.UNMUTE_CALL_FINISH, actionTypes.START_SCREENSHARE_FINISH, actionTypes.STOP_SCREENSHARE_FINISH, actionTypes.START_VIDEO_FINISH, actionTypes.STOP_VIDEO_FINISH, actionTypes.SET_CUSTOM_PARAMETERS); /* * Reducer to handle specific call actions. * Routes the actions to the call-tier reducers. */ reducers[specificCallActions] = function (state, action) { return state.map(function (call) { // Only update the call related to the action. if (call.id === action.payload.callId) { return callReducer(call, action); } else { return call; } }); }; /* * Combine all of top-tier reducers into a single reducer, * each with a default state of an empty array. */ var reducer = (0, _reduxActions.handleActions)(reducers, []); exports.default = reducer; /***/ }), /***/ "./src/call/interface/reducers/devices.js": /*!************************************************!*\ !*** ./src/call/interface/reducers/devices.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var reducers = {}; // Replace old devices with newly checked devices. reducers[actionTypes.CHECK_DEVICES_FINISH] = { next: function next(state, action) { return (0, _extends3.default)({}, state, action.payload); } }; reducers[actionTypes.SET_DEFAULT_DEVICES_FINISH] = { next: function next(state, action) { // Replace the default devices with the newly set defaults. return (0, _extends3.default)({}, state, { defaults: (0, _extends3.default)({}, state.defaults, action.payload) }); } }; var reducer = (0, _reduxActions.handleActions)(reducers, {}); exports.default = reducer; /***/ }), /***/ "./src/call/interface/reducers/index.js": /*!**********************************************!*\ !*** ./src/call/interface/reducers/index.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments[1]; return { calls: (0, _calls2.default)(state.calls, action), devices: (0, _devices2.default)(state.devices, action), media: (0, _media2.default)(state.media, action), localVideo: (0, _localVideo2.default)(state.localVideo, action), audioBridges: (0, _audioBridges2.default)(state.audioBridges, action) }; }; var _calls = __webpack_require__(/*! ./calls */ "./src/call/interface/reducers/calls.js"); var _calls2 = _interopRequireDefault(_calls); var _devices = __webpack_require__(/*! ./devices */ "./src/call/interface/reducers/devices.js"); var _devices2 = _interopRequireDefault(_devices); var _localVideo = __webpack_require__(/*! ./localVideo */ "./src/call/interface/reducers/localVideo.js"); var _localVideo2 = _interopRequireDefault(_localVideo); var _media = __webpack_require__(/*! ./media */ "./src/call/interface/reducers/media.js"); var _media2 = _interopRequireDefault(_media); var _audioBridges = __webpack_require__(/*! ./audioBridges */ "./src/call/interface/reducers/audioBridges.js"); var _audioBridges2 = _interopRequireDefault(_audioBridges); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), /***/ "./src/call/interface/reducers/localVideo.js": /*!***************************************************!*\ !*** ./src/call/interface/reducers/localVideo.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var defaultState = { displaying: false }; var reducers = {}; // Store information about the local video being displayed. reducers[actionTypes.START_LOCAL_VIDEO_FINISH] = { next: function next(state, action) { return { displaying: true, container: action.payload }; } }; // Remove info / Return to default state. reducers[actionTypes.STOP_LOCAL_VIDEO_FINISH] = { next: function next() { return defaultState; } }; var reducer = (0, _reduxActions.handleActions)(reducers, defaultState); exports.default = reducer; /***/ }), /***/ "./src/call/interface/reducers/media.js": /*!**********************************************!*\ !*** ./src/call/interface/reducers/media.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var reducers = {}; // Replace old media info with new info. reducers[actionTypes.INIT_MEDIA_FINISH] = { next: function next(state, action) { // If media state has been set, don't reset it. results from second+ // initMedia attempt may not be accurate. if (!state) { return action.payload; } else { return state; } } }; var reducer = (0, _reduxActions.handleActions)(reducers, ''); exports.default = reducer; /***/ }), /***/ "./src/call/interface/selectors.js": /*!*****************************************!*\ !*** ./src/call/interface/selectors.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCallConfig = getCallConfig; exports.getCalls = getCalls; exports.getCallById = getCallById; exports.getCustomParametersById = getCustomParametersById; exports.getDevices = getDevices; exports.getMediaInfo = getMediaInfo; exports.getAudioBridges = getAudioBridges; exports.getBridgeCalls = getBridgeCalls; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); /** * Retrieves the config options provided by the call plugin. * @method getCallConfig * @return {Object} */ function getCallConfig(state) { return (0, _fp.cloneDeep)(state.config.call); } /** * Retrieves all calls in state. * @method getCalls * @param {Object} state Redux state. * @return {Array} Call objects. */ function getCalls(state) { return (0, _fp.cloneDeep)(state.call.calls); } /** * Retrieves a call from state with a specific call ID. * @method getCallById * @param {Object} state Redux state. * @param {string} callId The ID of the call to retrieve. * @return {Object} A call object. */ function getCallById(state, callId) { return (0, _fp.find)(function (call) { return call.id === callId; }, getCalls(state)); } /** * Retrieves custom parameters from a call with a specific call ID. * @method getCustomParametersById * @param {Object} state Redux state. * @param {string} callId The ID of the call to retrieve. * @return {Object} A call object. */ function getCustomParametersById(state, callId) { var call = (0, _fp.find)(function (call) { return call.id === callId; }, getCalls(state)); if (call && call.customParameters) { return call.customParameters; } return []; } /** * Retrieves media devices available on the system. * @method getDevices * @param {Object} state Redux state. * @return {Object} */ function getDevices(state) { return (0, _fp.cloneDeep)(state.call.devices); } /** * Retrieves media support information. * @method getMediaInfo * @param {Object} state Redux state. * @return {Object} */ function getMediaInfo(state) { return (0, _fp.cloneDeep)(state.call.media); } /** * Retrieves audio bridge information. * @method getAudioBridges * @param {Object} state Redux state. * @return {Object} */ function getAudioBridges(state) { return (0, _fp.cloneDeep)(state.call.audioBridges); } /** * Retrieve all calls currently part of an audio bridge. * @method getBridgeCalls * @param state * @param bridgeId * @return {Array} List of calls currently part of the specified audio bridge. */ function getBridgeCalls(state, bridgeId) { return (0, _fp.cloneDeep)((0, _fp.find)(function (bridge) { return bridge.id === bridgeId; }, getAudioBridges(state)).calls); } /***/ }), /***/ "./src/call/sagas.js": /*!***************************!*\ !*** ./src/call/sagas.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.watchCheckMediaDevices = watchCheckMediaDevices; exports.checkMediaDevices = checkMediaDevices; exports.onDeviceChange = onDeviceChange; var _reduxSaga = __webpack_require__(/*! redux-saga */ "../../node_modules/redux-saga/es/index.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); var _errors = __webpack_require__(/*! ../errors */ "./src/errors/index.js"); var _errors2 = _interopRequireDefault(_errors); var _actions = __webpack_require__(/*! ./interface/actions */ "./src/call/interface/actions/index.js"); var _actionTypes = __webpack_require__(/*! ./interface/actionTypes */ "./src/call/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _mediaDevices = __webpack_require__(/*! ./utils/mediaDevices */ "./src/call/utils/mediaDevices.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(watchCheckMediaDevices), _marked2 = /*#__PURE__*/_regenerator2.default.mark(checkMediaDevices), _marked3 = /*#__PURE__*/_regenerator2.default.mark(onDeviceChange); // Get the logger var log = (0, _logs.getLogManager)().getLogger('CALL'); /** * Naively checks whether navigator.mediaDevices is supported in this environment. * @method isSupported * @return {boolean} */ function isSupported() { return typeof navigator !== 'undefined' && typeof navigator.mediaDevices !== 'undefined'; } // TODO: Somewhere else should "initialize" this. if (!isSupported()) { log.warn('MediaDevices not supported; will not watch for media device changes.'); } /** * Saga watcher. * Forwards actions to checkMediaDevices saga. * @method watchCheckMediaDevices */ function watchCheckMediaDevices() { return _regenerator2.default.wrap(function watchCheckMediaDevices$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.takeEvery)(actionTypes.CHECK_DEVICES, checkMediaDevices); case 2: case 'end': return _context.stop(); } } }, _marked, this); } /** * Retrieves media devices when requested. * @method checkMediaDevices */ function checkMediaDevices() { var getDevices, devices; return _regenerator2.default.wrap(function checkMediaDevices$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: getDevices = function getDevices() { return navigator.mediaDevices.enumerateDevices(); }; if (isSupported()) { _context2.next = 5; break; } _context2.next = 4; return (0, _effects.put)(_actions.devicesActions.checkDevicesFinish({ error: new _errors2.default({ code: _errors.callCodes.NOT_SUPPORTED, message: 'MediaDevices APIs are not supported in this environment.' }) })); case 4: return _context2.abrupt('return'); case 5: devices = void 0; _context2.prev = 6; _context2.next = 9; return (0, _effects.call)(getDevices); case 9: devices = _context2.sent; _context2.next = 18; break; case 12: _context2.prev = 12; _context2.t0 = _context2['catch'](6); log.debug('Failed to retrieve media devices.', _context2.t0); _context2.next = 17; return (0, _effects.put)(_actions.devicesActions.checkDevicesFinish({ error: _context2.t0 })); case 17: return _context2.abrupt('return'); case 18: log.debug('Retrieved latest media devices.', devices); // Format the device list into a user-friendly object. devices = (0, _mediaDevices.convertDevices)(devices); _context2.next = 22; return (0, _effects.put)(_actions.devicesActions.checkDevicesFinish({ devices: devices })); case 22: case 'end': return _context2.stop(); } } }, _marked2, this, [[6, 12]]); } /** * Listens for device changes. * Groups changes within a short time period into a single emitted event. * @method onDeviceChange */ function onDeviceChange() { var deviceChangeChannel, action; return _regenerator2.default.wrap(function onDeviceChange$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (isSupported()) { _context3.next = 2; break; } return _context3.abrupt('return'); case 2: deviceChangeChannel = (0, _reduxSaga.eventChannel)(function (emit) { var recentDeviceChange = false; navigator.mediaDevices.ondevicechange = function () { log.info('Media device change detected.'); // A physical device change results in one event per // device "kind". Group the events together. if (!recentDeviceChange) { recentDeviceChange = true; setTimeout(function () { recentDeviceChange = false; emit(_actions.devicesActions.checkDevices()); }, 50); } }; // Return unsubscribe function. return function () { navigator.mediaDevices.ondevicechange = null; }; }); case 3: if (false) {} _context3.next = 6; return (0, _effects.take)(deviceChangeChannel); case 6: action = _context3.sent; _context3.next = 9; return (0, _effects.put)(action); case 9: _context3.next = 3; break; case 11: case 'end': return _context3.stop(); } } }, _marked3, this); } /***/ }), /***/ "./src/call/utils/mediaDevices.js": /*!****************************************!*\ !*** ./src/call/utils/mediaDevices.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.convertDevices = convertDevices; var _constants = __webpack_require__(/*! ../constants */ "./src/call/constants.js"); /** * Converts an array of MediaDevices into an object keyed on device type. * @method parseDevices * @param {Array} [devices=[]] Media devices, in the form of MediaDeviceInfo objects. * @return {Object} Media device object. */ function convertDevices() { var devices = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var convertedDevices = { microphone: [], camera: [], speaker: [] }; devices.forEach(function (device) { convertedDevices[_constants.WEBRTC_DEVICE_KINDS[device.kind]].push(device); }); return convertedDevices; } /***/ }), /***/ "./src/call/utils/normalization.js": /*!*****************************************!*\ !*** ./src/call/utils/normalization.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.normalizeSipUri = normalizeSipUri; /** *The function takes in the input dial string and domain address of the user, performs a normalization process based on the phone number handling normalization rules * @function normalizeSipUri * @param {string} address It contains the input dial string the user dials in or the callee address * @param {string} domain It contains the user's domain address * @returns {string} output The output which is the normalized callee address/phone number */ function normalizeSipUri(address, domain) { var output; // Remove all leading space and tailing space address = address.trim(); // Remove all in-between spaces address = address.replace(/[ ]/g, ''); // Check for: '@' if at the beginning or at the end if (address.indexOf('@') === 0 || address.indexOf('@') === address.length - 1) { output = 'sip:' + address + '@' + domain; } else { var dialAddress; var domainAddress; // Check for: '@' symbol in address if (address.indexOf('@') !== -1) { // Split address at the occurence of '@' into two e.g 12345 and @domain.com, so we can normalize better dialAddress = address.substr(0, address.indexOf('@')); domainAddress = address.substr(address.indexOf('@')); } else { dialAddress = address; domainAddress = domain; } var leadingChar = dialAddress.substring(0, 1); // Check for: no leading char if (!(['*', '+', '#'].indexOf(leadingChar) !== -1)) { // Check for: digits and visual seperators if (dialAddress.match(/^[0-9-+().]*$/)) { address = dialAddress.replace(/[-+().]/g, ''); } else if (dialAddress.match(/^[a-zA-Z0-9-]*$/)) { // Check for: lower case and uppercase alpha chars, digits and visual seperators address = dialAddress; } } else { // Check for: leading char if (dialAddress.indexOf(leadingChar) === 0) { // Check for: leading char(*), digits and visual seperators if (dialAddress.match(/^\*+[0-9-+.()]*$/)) { address = dialAddress.replace(/[-+.()]/g, ''); } else if (dialAddress.match(/^\+[0-9-+.()]*$/)) { // Check for: leading char(+), digits and visual seperators address = leadingChar + dialAddress.replace(/[-+.()]/g, ''); } else if (dialAddress.match(/^\+[a-zA-Z0-9-]*$/)) { // Check for: leading char(+), alpha chars, digits and visual seperators address = dialAddress.replace(/[.()]/g, ''); } else if (dialAddress.match(/^\+[#0-9-+.()]*$/)) { // Check for: leading char(+), digits and visual seperators address = leadingChar + dialAddress.replace(/[-+.()]/g, ''); } else if (dialAddress.match(/^[#0-9.()]*$/)) { // Check for: leading char(#), digits and visual seperators address = dialAddress.replace(/[.()]/g, ''); } } else { address = dialAddress; } } if (domainAddress.indexOf('@') === 0) { output = 'sip:' + address + domainAddress; } else { output = 'sip:' + address + '@' + domainAddress; } } return output; } /***/ }), /***/ "./src/callHistory/index.js": /*!**********************************!*\ !*** ./src/callHistory/index.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = callHistory; var _interface = __webpack_require__(/*! ./interface */ "./src/callHistory/interface/index.js"); var _sagas = __webpack_require__(/*! ./sagas */ "./src/callHistory/sagas.js"); var sagas = _interopRequireWildcard(_sagas); var _events = __webpack_require__(/*! ./interface/events */ "./src/callHistory/interface/events.js"); var _events2 = _interopRequireDefault(_events); var _actions = __webpack_require__(/*! ../events/interface/actions */ "./src/events/interface/actions.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Call History plugin factory. * @method callHistory * @return {Object} plugin - A Kandy plugin. */ // Libraries. // Call History plugin. function callHistory() { var _marked = /*#__PURE__*/_regenerator2.default.mark(init); function init() { return _regenerator2.default.wrap(function init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.put)((0, _actions.mapEvents)(_events2.default)); case 2: case 'end': return _context.stop(); } } }, _marked, this); } return { name: _interface.name, capabilities: ['callHistory'], init: init, api: _interface.api, reducer: _interface.reducer, sagas: (0, _fp.values)(sagas) }; } // Other plugins. /***/ }), /***/ "./src/callHistory/interface/actionTypes.js": /*!**************************************************!*\ !*** ./src/callHistory/interface/actionTypes.js ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var prefix = '@@KANDY/'; var FETCH_CALL_HISTORY = exports.FETCH_CALL_HISTORY = prefix + 'FETCH_CALL_HISTORY'; var FETCH_CALL_HISTORY_FINISH = exports.FETCH_CALL_HISTORY_FINISH = prefix + 'FETCH_CALL_HISTORY_FINISH'; var DELETE_CALL_HISTORY = exports.DELETE_CALL_HISTORY = prefix + 'DELETE_CALL_HISTORY'; var DELETE_CALL_HISTORY_FINISH = exports.DELETE_CALL_HISTORY_FINISH = prefix + 'DELETE_CALL_HISTORY_FINISH'; var ADD_CALL_HISTORY_ENTRY = exports.ADD_CALL_HISTORY_ENTRY = prefix + 'ADD_CALL_HISTORY_ENTRY'; /***/ }), /***/ "./src/callHistory/interface/actions.js": /*!**********************************************!*\ !*** ./src/callHistory/interface/actions.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.retrieveCallLogs = retrieveCallLogs; exports.retrieveCallLogsFinish = retrieveCallLogsFinish; exports.removeCallLogs = removeCallLogs; exports.removeCallLogsFinish = removeCallLogsFinish; exports.addCallLogEntry = addCallLogEntry; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/callHistory/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Represents a request to fetch call logs. * @method retrieveCallLogs * @param {number} amount The number of records to retrieve. * @param {number} offset Starting offset for records to retrieve. * @return {Object} A flux standard action. */ function retrieveCallLogs(amount, offset) { return { type: actionTypes.FETCH_CALL_HISTORY, payload: { amount: amount, offset: offset } }; } /** * Represents a received response from fetching call logs. * @method retrieveCallLogsFinish * @param {Object} $0 * @param {Object} $0.logs Retrieved call logs. * @param {KandyError} $0.error Error object, in the case of an error. * @return {Object} A flux standard action. */ function retrieveCallLogsFinish(_ref) { var logs = _ref.logs, error = _ref.error; return { type: actionTypes.FETCH_CALL_HISTORY_FINISH, error: !!error, payload: error || logs }; } /** * Represents a request to delete call logs. * @method removeCallLogs * @param {number} recordId Which logs to delete. * @return {Object} A flux standard action. */ function removeCallLogs(recordId) { return { type: actionTypes.DELETE_CALL_HISTORY, payload: recordId }; } /** * Represents a received response from deleting call logs. * @method removeCallLogsFinish * @param {Object} $0 * @param {number|string} $0.recordId The ID of the removed record. Can also be 'all'. * @param {KandyError} $0.error Error object, in the case of an error. * @return {Object} A flux standard action. */ function removeCallLogsFinish(_ref2) { var recordId = _ref2.recordId, error = _ref2.error; return { type: actionTypes.DELETE_CALL_HISTORY_FINISH, error: !!error, payload: error || recordId }; } /** * Represents a request to add a new entry to the call logs. * @method addCallLogEntry * @param {Object} $0 The call log entry to add * @return {Object} A flux standard action. */ function addCallLogEntry(logEntry) { return { type: actionTypes.ADD_CALL_HISTORY_ENTRY, payload: logEntry }; } /***/ }), /***/ "./src/callHistory/interface/api.js": /*!******************************************!*\ !*** ./src/callHistory/interface/api.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = api; var _actions = __webpack_require__(/*! ./actions */ "./src/callHistory/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(/*! ./selectors */ "./src/callHistory/interface/selectors.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Call History API. * @method api * @param {Function} $0 * @param {Function} $0.dispatch The redux store's dispatch function. * @param {Function} $0.getState - The redux store's getState function. * @return {Object} API. */ /** * Kandy's call history feature is used to retrieve and inspect the authenticated * users call logs. * * CallHistory functions are namespaced beneath 'call.history' on the returned Kandy object. * * @public * @module CallHistory */ // Call History interface. function api(_ref) { var dispatch = _ref.dispatch, getState = _ref.getState; var callHistoryApi = { /** * Fetches the list of call logs and stores them locally. The API * `getCallLogs` can then be used to get the logs from local state after * it has been updated. * @public * @memberof CallHistory * @requires callHistory * @method fetch * @param {number} [amount=50] The number of records to retrieve. * @param {number} [offset=0] Starting offset for records to retrieve. */ fetch: function fetch() { var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; dispatch(actions.retrieveCallLogs(amount, offset)); }, /** * Deletes the specified call log. * @public * @memberof CallHistory * @requires callHistory * @method remove * @param {number} recordId The ID of the call log to be removed. */ remove: function remove(recordId) { dispatch(actions.removeCallLogs(recordId)); }, /** * Deletes all call logs. * @public * @memberof CallHistory * @requires callHistory * @method clear */ clear: function clear() { dispatch(actions.removeCallLogs('all')); }, /** * Gets the list of call logs cached locally. The event * `callHistory:changed` is used to indicate the local state of logs * has been updated. * @public * @memberof CallHistory * @requires callHistory * @method get * @example * kandy.on('callHistory:change', function() { * // Get all call logs when they've been updated. * let callLogs = kandy.call.history.get(); * }); * @returns {Array} A list of call log records, ordered by latest first. */ get: function get() { return (0, _selectors.getCallHistory)(getState()); } }; return { call: { history: callHistoryApi } }; } /***/ }), /***/ "./src/callHistory/interface/eventTypes.js": /*!*************************************************!*\ !*** ./src/callHistory/interface/eventTypes.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Call history state has been updated. See `getCallLogs()` to retrieve new state. * @public * @memberof CallHistory * @event callHistory:change */ var CALL_HISTORY_CHANGE = exports.CALL_HISTORY_CHANGE = 'callHistory:change'; /** * An error occured while performing a call history operation. * @public * @memberof CallHistory * @event callHistory:error * @param {Object} params * @param {KandyError} params.error The Kandy error object. */ var CALL_HISTORY_ERROR = exports.CALL_HISTORY_ERROR = 'callHistory:error'; /***/ }), /***/ "./src/callHistory/interface/events.js": /*!*********************************************!*\ !*** ./src/callHistory/interface/events.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/callHistory/interface/eventTypes.js"); var eventTypes = _interopRequireWildcard(_eventTypes); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/callHistory/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function callHistoryEvent(action) { if (!action.error) { return { type: eventTypes.CALL_HISTORY_CHANGE, args: {} }; } else { return { type: eventTypes.CALL_HISTORY_ERROR, args: { error: action.payload } }; } } var events = {}; events[actionTypes.FETCH_CALL_HISTORY_FINISH] = callHistoryEvent; events[actionTypes.DELETE_CALL_HISTORY_FINISH] = callHistoryEvent; events[actionTypes.ADD_CALL_HISTORY_ENTRY] = callHistoryEvent; exports.default = events; /***/ }), /***/ "./src/callHistory/interface/index.js": /*!********************************************!*\ !*** ./src/callHistory/interface/index.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reducer = exports.api = exports.name = undefined; var _api = __webpack_require__(/*! ./api */ "./src/callHistory/interface/api.js"); var _api2 = _interopRequireDefault(_api); var _reducers = __webpack_require__(/*! ./reducers */ "./src/callHistory/interface/reducers.js"); var _reducers2 = _interopRequireDefault(_reducers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var name = 'callHistory'; exports.name = name; exports.api = _api2.default; exports.reducer = _reducers2.default; /***/ }), /***/ "./src/callHistory/interface/reducers.js": /*!***********************************************!*\ !*** ./src/callHistory/interface/reducers.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/callHistory/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var reducers = {}; reducers[actionTypes.FETCH_CALL_HISTORY_FINISH] = { next: function next(state, action) { // Note: If a conflict occurs in the below unionBy, the newer log is // preferred over the older log. This is because SPiDR only keeps // 50 records at a time, and it re-uses old recordIds when it // creates new record logs. It's stupid. // Get local Logs. Local logs are identified by having a recordID of 16 characters var localLogs = state.filter(function (log) { return log.recordId.length === 36 && log.duration !== '0'; }); // Remove the local logs var localLogsRemoved = state.filter(function (log) { return log.resourceLocation !== ''; }); // Generate a list of unique logs (ie; not found in server logs) var uniqueLogs = localLogs.filter(function (log) { var result = action.payload.some(isSimilar, log); return !result; }); // Combine server logs and new logs. var newLogs = (0, _fp.concat)((0, _fp.unionBy)('recordId', action.payload, localLogsRemoved), uniqueLogs); // Sort start time, in descending order. return (0, _fp.reverse)((0, _fp.sortBy)('startTime', newLogs)); } }; reducers[actionTypes.DELETE_CALL_HISTORY_FINISH] = { next: function next(state, action) { if (action.payload === 'all') { return []; } else { return state.map(function (log) { return log.recordId !== action.payload; }); } } }; reducers[actionTypes.ADD_CALL_HISTORY_ENTRY] = { next: function next(state, action) { return (0, _fp.concat)(action.payload, state); } }; // Call History default state is an empty array. var reducer = (0, _reduxActions.handleActions)(reducers, []); exports.default = reducer; /* * A helper function to determine if 2 log entries are similar. * A log is considered similar under the following conditions: * - the startTime is within 10 seconds * - the duration is within 5 seconds * - the direction is the same */ var isSimilar = function isSimilar(serverLogEntry) { var startTimePadding = 10000; var durationPadding = 5000; if (Math.abs(serverLogEntry.startTime - this.startTime) > startTimePadding) { return false; } if (Math.abs(serverLogEntry.duration - this.duration) > durationPadding) { return false; } if (serverLogEntry.direction !== this.direction) { return false; } return true; }; /***/ }), /***/ "./src/callHistory/interface/selectors.js": /*!************************************************!*\ !*** ./src/callHistory/interface/selectors.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCallHistory = getCallHistory; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); /** * Retrieves call history stored in state. * @method getCallHistory * @param {Object} state Redux state. * @return {Array} */ function getCallHistory(state) { return (0, _fp.cloneDeep)(state.callHistory); } /***/ }), /***/ "./src/callHistory/sagas.js": /*!**********************************!*\ !*** ./src/callHistory/sagas.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.retrieveCallLogs = retrieveCallLogs; exports.removeCallLogs = removeCallLogs; exports.storeCallLogs = storeCallLogs; var _actionTypes = __webpack_require__(/*! ./interface/actionTypes */ "./src/callHistory/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _actions = __webpack_require__(/*! ./interface/actions */ "./src/callHistory/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _effects = __webpack_require__(/*! ../request/effects */ "./src/request/effects.js"); var _effects2 = _interopRequireDefault(_effects); var _selectors = __webpack_require__(/*! ../auth/interface/selectors */ "./src/auth/interface/selectors.js"); var _selectors2 = __webpack_require__(/*! ../call/interface/selectors */ "./src/call/interface/selectors.js"); var _errors = __webpack_require__(/*! ../errors */ "./src/errors/index.js"); var _errors2 = _interopRequireDefault(_errors); var _actionTypes2 = __webpack_require__(/*! ../call/interface/actionTypes */ "./src/call/interface/actionTypes.js"); var callActionTypes = _interopRequireWildcard(_actionTypes2); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _effects3 = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _constants = __webpack_require__(/*! ../constants */ "./src/constants.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(retrieveCallLogs), _marked2 = /*#__PURE__*/_regenerator2.default.mark(removeCallLogs), _marked3 = /*#__PURE__*/_regenerator2.default.mark(storeCallLogs); // Call History plugin. // Other plugins. // Libraries. // Constants // Get the logger var log = (0, _logs.getLogManager)().getLogger('CALLHISTORY'); /** * Saga for fetching call log records. * @method retrieveCallLogs */ function retrieveCallLogs() { var retrieveChannel, action, requestInfo, platform, version, url, queryParams, response, error, statusCode, message, logs; return _regenerator2.default.wrap(function retrieveCallLogs$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects3.actionChannel)(actionTypes.FETCH_CALL_HISTORY); case 2: retrieveChannel = _context.sent; case 3: if (false) {} _context.next = 6; return (0, _effects3.take)(retrieveChannel); case 6: action = _context.sent; log.debug('Attempting to retrieve ' + action.payload.amount + ' call log(s),' + (' offset of ' + action.payload.offset + '.')); // Catch invalid input (which breaks SPiDR) before making the request. if (!(!(0, _fp.isNumber)(action.payload.amount) || action.payload.amount < 0 || !(0, _fp.isNumber)(action.payload.offset))) { _context.next = 13; break; } log.info('Could not retrieve log(s): Invalid input.'); _context.next = 12; return (0, _effects3.put)(actions.retrieveCallLogsFinish({ error: new _errors2.default({ code: _errors.callHistoryCodes.BAD_REQUEST, message: 'Could not retrieve call logs: Invalid input.' }) })); case 12: return _context.abrupt('continue', 3); case 13: _context.next = 15; return (0, _effects3.select)(_selectors.getRequestInfo); case 15: requestInfo = _context.sent; _context.next = 18; return (0, _effects3.select)(_selectors.getPlatform); case 18: platform = _context.sent; version = platform === _constants.platforms.CPAAS ? 1 : requestInfo.version; url = requestInfo.baseURL + '/rest/version/' + version + '/user/' + requestInfo.username + '/logHistory'; queryParams = { startIndex: action.payload.offset, count: action.payload.amount }; _context.next = 24; return (0, _effects2.default)({ url: url, queryParams: queryParams, method: 'GET' }, requestInfo.requestOptions); case 24: response = _context.sent; if (!response.error) { _context.next = 32; break; } error = void 0; if (response.payload.body) { // Handle errors from the server. statusCode = response.payload.body.logHistory.statusCode; log.debug('Failed to retrieve call logs with status code ' + statusCode + '.'); error = new _errors2.default({ code: statusCode === 37 ? _errors.callHistoryCodes.BAD_REQUEST : _errors.callHistoryCodes.UNKNOWN_ERROR, message: 'Failed to retrieve call logs. Code: ' + statusCode + '.' }); } else { // Handle errrs from the request helper. message = response.payload.result.message; log.debug('Failed call log retrieval', message); error = new _errors2.default({ code: _errors.callHistoryCodes.UNKNOWN_ERROR, message: 'Call log fetch failed: ' + message + '.' }); } _context.next = 30; return (0, _effects3.put)(actions.retrieveCallLogsFinish({ error: error })); case 30: _context.next = 37; break; case 32: log.info('Successfully retrieved log(s) from call history.'); // Massage the call logs into a more concise format. logs = response.payload.body.logHistory.logItems.map(function (log) { if (log.type === 'CallLog') { return log.params; } }); // Massage the call logs to include the remoteParticipant property. logs = logs.map(function (log) { /** * There is a bug in SPiDR where it always uses the keys `callerName` and * `callerDisplayNumber` for ALL logs, instead of only incoming logs. * Because of this, callerDisplayNumber is always the remote participant, * even when the local user is the caller. * This if statement is a workaround for this problem. * // TODO: Remove this if when the SPiDR issue is resolved. */ if (log.direction === 'outgoing' && !log.calleeDisplayNumber && !log.calleeName) { log.calleeDisplayNumber = log.callerDisplayNumber; log.calleeName = log.callerName; // Keep callerDisplayNumber and callerName properties unchanged for // backwards compatibility. } if (log.direction === 'outgoing') { log.remoteParticipant = { displayName: log.calleeName, displayNumber: log.calleeDisplayNumber }; } else { log.remoteParticipant = { displayName: log.callerName, displayNumber: log.callerDisplayNumber }; } return log; }); _context.next = 37; return (0, _effects3.put)(actions.retrieveCallLogsFinish({ logs: logs })); case 37: _context.next = 3; break; case 39: case 'end': return _context.stop(); } } }, _marked, this); } /** * Saga for deleting call logs. * @method removeCallLogs */ function removeCallLogs() { var removeChannel, action, requestInfo, platform, version, url, response, error, statusCode, message; return _regenerator2.default.wrap(function removeCallLogs$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return (0, _effects3.actionChannel)(actionTypes.DELETE_CALL_HISTORY); case 2: removeChannel = _context2.sent; case 3: if (false) {} _context2.next = 6; return (0, _effects3.take)(removeChannel); case 6: action = _context2.sent; log.debug('Attempting to remove call log(s): ' + action.payload + '.'); if (action.payload) { _context2.next = 13; break; } log.info('Could not remove call logs from history: Invalid input.'); _context2.next = 12; return (0, _effects3.put)(actions.removeCallLogsFinish({ error: new _errors2.default({ code: _errors.callHistoryCodes.BAD_REQUEST, message: 'Could not remove call logs: Invalid input.' }) })); case 12: return _context2.abrupt('continue', 3); case 13: _context2.next = 15; return (0, _effects3.select)(_selectors.getRequestInfo); case 15: requestInfo = _context2.sent; _context2.next = 18; return (0, _effects3.select)(_selectors.getPlatform); case 18: platform = _context2.sent; version = platform === _constants.platforms.CPAAS ? 1 : requestInfo.version; url = requestInfo.baseURL + '/rest/version/' + version + '/user/' + requestInfo.username + '/'; if (action.payload === 'all') { url += 'logHistory'; } else { url += 'logRecord/' + action.payload; } _context2.next = 24; return (0, _effects2.default)({ url: url, method: 'DELETE' }, requestInfo.requestOptions); case 24: response = _context2.sent; if (!response.error) { _context2.next = 32; break; } error = void 0; if (response.payload.body) { // Handle errors from the server. statusCode = response.payload.body.logRecord.statusCode; log.info('Failed to remove log(s) from call history (status ' + statusCode + ').'); error = new _errors2.default({ code: statusCode === 42 ? _errors.callHistoryCodes.NOT_FOUND : _errors.callHistoryCodes.UNKNOWN_ERROR, message: 'Failed to remove call log. Code: ' + statusCode + '.' }); } else { // Handle errrs from the request helper. message = response.payload.result.message; log.debug('Failed call log removal.', message); error = new _errors2.default({ code: _errors.callHistoryCodes.UNKNOWN_ERROR, message: 'Call log removal failed: ' + message + '.' }); } _context2.next = 30; return (0, _effects3.put)(actions.removeCallLogsFinish({ error: error })); case 30: _context2.next = 35; break; case 32: log.info('Successfully removed log(s) from call history.'); _context2.next = 35; return (0, _effects3.put)(actions.removeCallLogsFinish({ recordId: action.payload.body })); case 35: _context2.next = 3; break; case 37: case 'end': return _context2.stop(); } } }, _marked2, this); } /** * Saga for storing call event in the local call history. * @method storeCallLogs */ function storeCallLogs() { var callEventChannel, action, call, logEntry, contactName; return _regenerator2.default.wrap(function storeCallLogs$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return (0, _effects3.actionChannel)(callActionTypes.CALL_STATE_CHANGE); case 2: callEventChannel = _context3.sent; case 3: if (false) {} _context3.next = 6; return (0, _effects3.take)(callEventChannel); case 6: action = _context3.sent; if (!(action.payload.state === 'ENDED')) { _context3.next = 16; break; } _context3.next = 10; return (0, _effects3.select)(_selectors2.getCallById, action.payload.callId); case 10: call = _context3.sent; logEntry = { recordId: action.payload.callId, startTime: '' + call.startTime, duration: '' + (call.endTime - call.startTime), callerDisplayNumber: call.from, calleeDisplayNumber: call.to, calleeName: call.calleeName, remoteParticipant: call.remoteParticipant, originalRemoteParticipant: call.originalRemoteParticipant, resourceLocation: '' }; if (call.direction === 'incoming') { // If the previous state was ringing, and the change was not because the call was // answered by another device (ie. code 9904), then it is a missed call. if (action.payload.transition.prevState === 'RINGING' && action.payload.transition.code !== '9904') { logEntry.direction = 'missed'; } else { logEntry.direction = 'incoming'; } logEntry.callerName = call.callerName; } else { logEntry.direction = 'outgoing'; // Use the contact name provided to the call as the current user's name. contactName = (call.contact.firstName + ' ' + call.contact.lastName).trim(); logEntry.callerName = contactName || call.from.split('@')[0]; } log.debug('Adding call event to the local call history:', logEntry); _context3.next = 16; return (0, _effects3.put)(actions.addCallLogEntry(logEntry)); case 16: _context3.next = 3; break; case 18: case 'end': return _context3.stop(); } } }, _marked3, this); } /***/ }), /***/ "./src/clickToCall/index.js": /*!**********************************!*\ !*** ./src/clickToCall/index.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = clickToCallImplementation; var _interface = __webpack_require__(/*! ./interface */ "./src/clickToCall/interface/index.js"); var _interface2 = _interopRequireDefault(_interface); var _sagas = __webpack_require__(/*! ./sagas */ "./src/clickToCall/sagas.js"); var _events = __webpack_require__(/*! ./interface/events */ "./src/clickToCall/interface/events.js"); var _events2 = _interopRequireDefault(_events); var _actions = __webpack_require__(/*! ../events/interface/actions */ "./src/events/interface/actions.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * clickToCall Plugin (that is implemented using a saga). * * @method clickToCallImplementation * @return {Object} An instance of the "clickToCall" plugin. */ // Other plugins. // Sagas function clickToCallImplementation() { var _marked = /*#__PURE__*/_regenerator2.default.mark(init); function init() { return _regenerator2.default.wrap(function init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.put)((0, _actions.mapEvents)(_events2.default)); case 2: case 'end': return _context.stop(); } } }, _marked, this); } return { // Interface Components: name: _interface2.default.name, capabilities: ['clickToCall'], api: _interface2.default.api, reducer: _interface2.default.reducer, // Implementation Components sagas: [_sagas.clickToCallSaga], init: init }; } // Libraries. // Events /** * This file is a plugin for the "clickToCall" feature. It is meant to connect two specified devices * Reference info: https://confluence.genband.com/display/KSDK/Plugins */ /***/ }), /***/ "./src/clickToCall/interface/actionTypes.js": /*!**************************************************!*\ !*** ./src/clickToCall/interface/actionTypes.js ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PREFIX = '@@KANDY/'; var CLICK_TO_CALL = exports.CLICK_TO_CALL = PREFIX + 'CLICK_TO_CALL'; var CLICK_TO_CALL_FINISH = exports.CLICK_TO_CALL_FINISH = PREFIX + 'CLICK_TO_CALL_FINISH'; /***/ }), /***/ "./src/clickToCall/interface/actions.js": /*!**********************************************!*\ !*** ./src/clickToCall/interface/actions.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.clickToCall = clickToCall; exports.clickToCallFinish = clickToCallFinish; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/clickToCall/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Represents a request to POST clickToCall data. * @method clickToCall * @param {string} callId * @param {string} caller * @param {string} callee * @return {Action} A redux action. */ function clickToCall(callId, caller, callee) { return { type: actionTypes.CLICK_TO_CALL, payload: { callId: callId, caller: caller, callee: callee } }; } /** * Represents that a response was received for a clickToCall request. * @method clickToCallFinish * @param {string} callId * @param {string} caller * @param {string} callee * @param {number} requestTime time that the request was made at * @param {Boolean} [error] A parameter to indicate if there was an issue. * @return {Action} A redux action. */ function clickToCallFinish(_ref) { var callId = _ref.callId, caller = _ref.caller, callee = _ref.callee, requestTime = _ref.requestTime, error = _ref.error; if (error) { return { type: actionTypes.CLICK_TO_CALL_FINISH, error: true, payload: { error: error } }; } else { return { type: actionTypes.CLICK_TO_CALL_FINISH, error: false, payload: { callId: callId, caller: caller, callee: callee, requestTime: requestTime } }; } } /***/ }), /***/ "./src/clickToCall/interface/api.js": /*!******************************************!*\ !*** ./src/clickToCall/interface/api.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = api; var _actions = __webpack_require__(/*! ./actions */ "./src/clickToCall/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(/*! ./selectors */ "./src/clickToCall/interface/selectors.js"); var _v = __webpack_require__(/*! uuid/v4 */ "../../node_modules/uuid/v4.js"); var _v2 = _interopRequireDefault(_v); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function api(context) { var clickToCallApi = { /** * Attempts to establish a call between two specified devices * * @public * @memberof ClickToCall * @method clickToCall * @param {string} caller A string representing the person making the call * @param {string} callee A string representing the person receiving the call * @returns {string} callId A unique id representing the call */ make: function make(caller, callee) { var callId = (0, _v2.default)(); context.dispatch(actions.clickToCall(callId, caller, callee)); return callId; }, /** * Gets all local clickToCall calls * * @public * @memberof ClickToCall * @requires clickToCall * @method get * @returns {Array} A list of clickToCall records, ordered by earliest requestTime */ get: function get() { return (0, _selectors.getAll)(context.getState()); } }; return { clickToCall: clickToCallApi }; } /** * Kandy's clickToCall feature is used to bridge a call between two specified devices * * @public * @module ClickToCall * @requires clickToCall */ /***/ }), /***/ "./src/clickToCall/interface/eventTypes.js": /*!*************************************************!*\ !*** ./src/clickToCall/interface/eventTypes.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * ClickToCall has successfully started. * * @public * @memberof ClickToCall * @requires clickToCall * @event clickToCall:start * @param {Object} params * @param {string} params.callId A unique id representing the call made */ var CLICK_TO_CALL_STARTED = exports.CLICK_TO_CALL_STARTED = 'clickToCall:start'; /** * ClickToCall had an error. * * @public * @memberof ClickToCall * @requires clickToCall * @event clickToCall:error * @param {Object} params * @param {string} params.callId A unique id representing the call made * @param {KandyError} params.error The Kandy error object. * */ var CLICK_TO_CALL_ERROR = exports.CLICK_TO_CALL_ERROR = 'clickToCall:error'; /***/ }), /***/ "./src/clickToCall/interface/events.js": /*!*********************************************!*\ !*** ./src/clickToCall/interface/events.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/clickToCall/interface/eventTypes.js"); var eventTypes = _interopRequireWildcard(_eventTypes); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/clickToCall/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Helper function for clickToCall error events. * * @method clickToCallEvent * @param {Object} action * @return {Object} */ function clickToCallEvent(action) { if (!action.error) { return { type: eventTypes.CLICK_TO_CALL_STARTED, args: { callId: action.payload.callId } }; } else { return { type: eventTypes.CLICK_TO_CALL_ERROR, args: { callId: action.payload.callId, error: action.payload } }; } } var events = {}; events[actionTypes.CLICK_TO_CALL_FINISH] = clickToCallEvent; exports.default = events; /***/ }), /***/ "./src/clickToCall/interface/index.js": /*!********************************************!*\ !*** ./src/clickToCall/interface/index.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _api = __webpack_require__(/*! ./api */ "./src/clickToCall/interface/api.js"); var _api2 = _interopRequireDefault(_api); var _reducers = __webpack_require__(/*! ./reducers */ "./src/clickToCall/interface/reducers.js"); var _reducers2 = _interopRequireDefault(_reducers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * This interface is for a clickToCall plugin. * @type {string} */ var name = 'clickToCall'; exports.default = { reducer: _reducers2.default, name: name, api: _api2.default }; /***/ }), /***/ "./src/clickToCall/interface/reducers.js": /*!***********************************************!*\ !*** ./src/clickToCall/interface/reducers.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/clickToCall/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * clicktoCall Plugin. * * Handles the clicktoCall plugin substate. Defines how to communicate back to * the Interface (ie. which actions to use). * @param {Object} [state={}] Default state for the reducer is an empty object. * @param {Action} action A dispatched action. * @return {Object} state The new example sub-state. */ var reducers = {}; reducers[actionTypes.CLICK_TO_CALL_FINISH] = { next: function next(state, action) { if (action.error) { return state; } else { return state.concat({ callId: action.payload.callId, caller: action.payload.caller, callee: action.payload.callee, requestTime: action.payload.requestTime }); } } }; // clickToCall default state is empty array var reducer = (0, _reduxActions.handleActions)(reducers, []); exports.default = reducer; /***/ }), /***/ "./src/clickToCall/interface/selectors.js": /*!************************************************!*\ !*** ./src/clickToCall/interface/selectors.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getAll = getAll; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); /** * Retrieves clickToCall calls stored in state * * @method getAll * @param {Object} state Redux state. * @return {Array} */ function getAll(state) { return (0, _fp.cloneDeep)(state.clickToCall); } // Other Libraries /***/ }), /***/ "./src/clickToCall/sagas.js": /*!**********************************!*\ !*** ./src/clickToCall/sagas.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.clickToCallSaga = clickToCallSaga; var _actionTypes = __webpack_require__(/*! ./interface/actionTypes */ "./src/clickToCall/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _actions = __webpack_require__(/*! ./interface/actions */ "./src/clickToCall/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(/*! ../auth/interface/selectors */ "./src/auth/interface/selectors.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); var _effects2 = __webpack_require__(/*! ../request/effects */ "./src/request/effects.js"); var _effects3 = _interopRequireDefault(_effects2); var _errors = __webpack_require__(/*! ../errors */ "./src/errors/index.js"); var _errors2 = _interopRequireDefault(_errors); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(clickToCallSaga); // clickToCall plugin. // Libraries. // Other plugins. // Error handling // Get the logger var log = (0, _logs.getLogManager)().getLogger('CLICKTOCALL'); function clickToCallSaga() { var action, conn, server, username, requestOptions, url, data, options, requestTime, response; return _regenerator2.default.wrap(function clickToCallSaga$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (false) {} _context.next = 3; return (0, _effects.take)(actionTypes.CLICK_TO_CALL); case 3: action = _context.sent; if (!(!action.payload.caller || !action.payload.callee)) { _context.next = 9; break; } log.info('Missing call particiant information'); _context.next = 8; return (0, _effects.put)(actions.clickToCallFinish({ payload: { error: new _errors2.default({ message: 'callee or caller were not provided in CLICK_TO_CALL action payload', code: _errors.clickToCallCodes.MISSING_ARGS }), callId: action.payload.callId } })); case 8: return _context.abrupt('continue', 0); case 9: _context.next = 11; return (0, _effects.select)(_selectors.getConnectionInfo); case 11: conn = _context.sent; server = conn.server, username = conn.username, requestOptions = conn.requestOptions; url = server.protocol + '://' + server.server + ':' + server.port + '/rest/version/' + server.version + '/user/' + username + '/clicktocall'; data = { clickToCallRequest: { callingParty: action.payload.caller, calledParty: action.payload.callee } }; options = { url: url, method: 'POST', body: (0, _stringify2.default)(data) }; requestTime = new Date().getTime(); // wait until we get a response from /clicktocall service _context.next = 19; return (0, _effects3.default)(options, requestOptions); case 19: response = _context.sent; if (!response.error) { _context.next = 25; break; } _context.next = 23; return (0, _effects.put)(actions.clickToCallFinish({ payload: { error: new _errors2.default({ message: response.payload.result.message, code: _errors.clickToCallCodes.RESPONSE_ERROR }), callId: action.payload.callId } })); case 23: _context.next = 27; break; case 25: _context.next = 27; return (0, _effects.put)(actions.clickToCallFinish({ callId: action.payload.callId, caller: action.payload.caller, callee: action.payload.callee, requestTime: requestTime })); case 27: _context.next = 0; break; case 29: case 'end': return _context.stop(); } } }, _marked, this); } /***/ }), /***/ "./src/common/utils.js": /*!*****************************!*\ !*** ./src/common/utils.js ***! \*****************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _keys = __webpack_require__(/*! babel-runtime/core-js/object/keys */ "../../node_modules/babel-runtime/core-js/object/keys.js"); var _keys2 = _interopRequireDefault(_keys); exports.mergeValues = mergeValues; exports.toQueryString = toQueryString; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Deeply merges the values of multiple objects. Objects on the left receive the values from objects on their right. * Unlike lodash's default merge behavior this doesn't merge arrays. * * @name mergeValues * @param {...Object} objects - Objects to merge * @return {Object} A new object containing the merged values. */ function mergeValues() { for (var _len = arguments.length, objects = Array(_len), _key = 0; _key < _len; _key++) { objects[_key] = arguments[_key]; } return (0, _fp.mergeAllWith)(function (leftValue, rightValue) { // Overwrite the default behavior of lodash's merge for arrays and simply // clobber what's on the left so we don't end up with merged arrays. if ((0, _fp.isArray)(leftValue)) { return rightValue; } }, objects); } /* * Utility function to convert an object to a query string. */ function toQueryString() { var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var keys = (0, _keys2.default)(params).filter(function (key) { return params[key] !== undefined; }); var queryString = ''; if (keys.length > 0) { queryString = '?' + keys.map(function (key) { return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); }).join('&'); } return queryString; } /***/ }), /***/ "./src/config/index.js": /*!*****************************!*\ !*** ./src/config/index.js ***! \*****************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = configImplementation; var _interface = __webpack_require__(/*! ./interface */ "./src/config/interface/index.js"); var _interface2 = _interopRequireDefault(_interface); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Config Plugin * * @method configImplementation * @return {Object} An instance of the "Config" plugin. */ // yarn lint:docs complains if this isn't defined in a plugin. /** * @module configs */ function configImplementation() { return { // Interface Components: name: _interface2.default.name, capabilities: ['config'], api: _interface2.default.api, reducer: _interface2.default.reducer }; } /** * This file is a plugin for the "Config" plugin * Reference info: https://confluence.genband.com/display/KSDK/Plugins */ /***/ }), /***/ "./src/config/interface/actionTypes.js": /*!*********************************************!*\ !*** ./src/config/interface/actionTypes.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PREFIX = '@@KANDY/'; var CONFIG_UPDATE = exports.CONFIG_UPDATE = PREFIX + 'CONFIG_UPDATE'; /***/ }), /***/ "./src/config/interface/actions.js": /*!*****************************************!*\ !*** ./src/config/interface/actions.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = __webpack_require__(/*! babel-runtime/helpers/defineProperty */ "../../node_modules/babel-runtime/helpers/defineProperty.js"); var _defineProperty3 = _interopRequireDefault(_defineProperty2); exports.update = update; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/config/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Add or update a specific key within the store.config. * * @param {Object} values The values that will be placed in the store. * @param {string} [pluginName] The plugin name of the config being set. * @return {Action} action A redux action. */ function update(values) { var pluginName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var payload; // Use the plugin name as a substate key, if present. if (pluginName) { payload = (0, _defineProperty3.default)({}, pluginName, values); } else { payload = values; } return { type: actionTypes.CONFIG_UPDATE, payload: payload }; } /***/ }), /***/ "./src/config/interface/api.js": /*!*************************************!*\ !*** ./src/config/interface/api.js ***! \*************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = api; var _actions = __webpack_require__(/*! ./actions */ "./src/config/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(/*! ./selectors */ "./src/config/interface/selectors.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * An interface for getting and updating the configuration Object. * * @public * @module Config * @requires config */ function api(context) { var configApi = { /** * Gets the current configuration Object * * @public * @memberof Config * @requires config * @method getConfig * @returns {Object} A configuration Object */ getConfig: function getConfig() { return (0, _selectors.getConfiguration)(context.getState()); }, /** * Update values in the global Config section of the store. * * @public * @memberof Config * @requires config * @method updateConfig * @param {Object} newConfigValues Key Value pairs that will be placed into the store. */ updateConfig: function updateConfig(newConfigValues) { context.dispatch(actions.update(newConfigValues)); } }; return configApi; } /***/ }), /***/ "./src/config/interface/index.js": /*!***************************************!*\ !*** ./src/config/interface/index.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _api = __webpack_require__(/*! ./api */ "./src/config/interface/api.js"); var _api2 = _interopRequireDefault(_api); var _reducers = __webpack_require__(/*! ./reducers */ "./src/config/interface/reducers.js"); var _reducers2 = _interopRequireDefault(_reducers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * This interface is for a Config plugin. * @type {string} */ var name = 'config'; exports.default = { reducer: _reducers2.default, name: name, api: _api2.default }; /***/ }), /***/ "./src/config/interface/reducers.js": /*!******************************************!*\ !*** ./src/config/interface/reducers.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/config/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var reducers = {}; reducers[actionTypes.CONFIG_UPDATE] = { next: function next(state, action) { return (0, _fp.merge)(state, action.payload); } }; // Config default state is an empty Object var reducer = (0, _reduxActions.handleActions)(reducers, {}); exports.default = reducer; /***/ }), /***/ "./src/config/interface/selectors.js": /*!*******************************************!*\ !*** ./src/config/interface/selectors.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getConfiguration = getConfiguration; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); /** * Retrieves configuration Object stored in state * * @method getConfiguration * @param {Object} state Redux state. * @return {Object} */ function getConfiguration(state) { return (0, _fp.cloneDeep)(state.config); } /***/ }), /***/ "./src/connectivity/defaults.js": /*!**************************************!*\ !*** ./src/connectivity/defaults.js ***! \**************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Connectivity plugin defaults. * @param {String} [method='keepAlive'] The method of connectivity checking to use. Either 'keepAlive' or 'pingPong'. * @param {Number} [pingInterval=5000] Time in between websocket ping attempts (milliseconds). * @param {Number} [reconnectLimit=5] Number of failed reconnect attempts before reporting an error. * @param {Number} [reconnectDelay=5000] Base time between websocket reconnect attempts (milliseconds). * @param {Number} [reconnectTimeMultiplier=1] Reconnect delay multiplier for subsequent attempts. * @param {Number} [reconnectTimeLimit=640000] Maximum time delay between reconnect attempts (milliseconds). * @param {Number} [reconnectCount=0] Initial reconnect count. * @param {Boolean} [autoReconnect=true] Flag to determine whether Kandy will attempt to automatically reconnect after connectivity disruptions. * @param {Number} [maxMissedPings=3] Maximum pings sent (without receiving a response) before reporting an error. * @param {Boolean} [checkConnectivity=false] Flag to determine whether Kandy should check connectivity. */ exports.default = { method: 'keepAlive', pingInterval: 5000, reconnectLimit: 5, reconnectDelay: 5000, reconnectTimeMultiplier: 1, reconnectTimeLimit: 640000, reconnectCount: 0, autoReconnect: true, maxMissedPings: 3, checkConnectivity: true }; /***/ }), /***/ "./src/connectivity/index.js": /*!***********************************!*\ !*** ./src/connectivity/index.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = connectivity; var _interface = __webpack_require__(/*! ./interface */ "./src/connectivity/interface/index.js"); var _defaults = __webpack_require__(/*! ./defaults */ "./src/connectivity/defaults.js"); var _defaults2 = _interopRequireDefault(_defaults); var _events = __webpack_require__(/*! ./interface/events */ "./src/connectivity/interface/events.js"); var _events2 = _interopRequireDefault(_events); var _sagas = __webpack_require__(/*! ./sagas */ "./src/connectivity/sagas.js"); var _actions = __webpack_require__(/*! ../config/interface/actions */ "./src/config/interface/actions.js"); var _actions2 = __webpack_require__(/*! ../events/interface/actions */ "./src/events/interface/actions.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Configuration options for the Connectivity feature. * @public * @name configs.connectivity * @memberof configs * @instance * @param {Object} connectivity Connectivity configs. * @param {String} [connectivity.method='keepAlive'] The method of connectivity checking to use. Either 'keepAlive' or 'pingPong'. * @param {Number} [connectivity.pingInterval=5000] Time in between websocket ping attempts (milliseconds). * @param {Number} [connectivity.reconnectLimit=5] Number of failed reconnect attempts before reporting an error. * @param {Number} [connectivity.reconnectDelay=5000] Base time between websocket reconnect attempts (milliseconds). * @param {Number} [connectivity.reconnectTimeMultiplier=1] Reconnect delay multiplier for subsequent attempts. * @param {Number} [connectivity.reconnectTimeLimit=640000] Maximum time delay between reconnect attempts (milliseconds). * @param {Number} [connectivity.reconnectCount=0] Initial reconnect count. * @param {Boolean} [connectivity.autoReconnect=true] Flag to determine whether Kandy will attempt to automatically reconnect after connectivity disruptions. * @param {Number} [connectivity.maxMissedPings=3] Maximum pings sent (without receiving a response) before reporting an error. * @param {Boolean} [connectivity.checkConnectivity=false] Flag to determine whether Kandy should check connectivity. */ /** * Connectivity plugin factory. * Responsible for handling websockets. * @method connectivity * @param {Object} [options={}] Connectivity configs. See above. * @return {Object} Plugin - A connectivity plugin. */ // Libraries. // Other plugins. // Connectivity plugin. function connectivity() { var _marked = /*#__PURE__*/_regenerator2.default.mark(init); var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; options = (0, _fp.defaults)(_defaults2.default, options); function init() { return _regenerator2.default.wrap(function init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.put)((0, _actions.update)(options, _interface.name)); case 2: _context.next = 4; return (0, _effects.put)((0, _actions2.mapEvents)(_events2.default)); case 4: case 'end': return _context.stop(); } } }, _marked, this); } return { sagas: [_sagas.wsConnectFlow], init: init, name: _interface.name, reducer: _interface.reducer, api: _interface.api }; } /***/ }), /***/ "./src/connectivity/interface/actionTypes.js": /*!***************************************************!*\ !*** ./src/connectivity/interface/actionTypes.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var prefix = '@@KANDY/CONN/'; // Actions to tell connectivity plugin what to do var WS_ATTEMPT_CONNECT = exports.WS_ATTEMPT_CONNECT = prefix + 'WS_ATTEMPT_CONNECT'; var WS_CONNECT_FINISHED = exports.WS_CONNECT_FINISHED = prefix + 'WS_CONNECT_FINISHED'; var WS_DISCONNECT = exports.WS_DISCONNECT = prefix + 'WS_DISCONNECT'; var WS_DISCONNECT_FINISHED = exports.WS_DISCONNECT_FINISHED = prefix + 'WS_DISCONNECT_FINISHED'; // actions for hooking into connectivity plugin behaviour var WS_CLOSED = exports.WS_CLOSED = prefix + 'WS_CLOSED'; var WS_ERROR = exports.WS_ERROR = prefix + 'WS_ERROR'; var LOST_CONNECTION = exports.LOST_CONNECTION = prefix + 'LOST_CONNECTION'; var CHANGE_CONNECTIVITY_CHECKING = exports.CHANGE_CONNECTIVITY_CHECKING = prefix + 'CHANGE_CONNECTIVITY_CHECKING'; /***/ }), /***/ "./src/connectivity/interface/actions.js": /*!***********************************************!*\ !*** ./src/connectivity/interface/actions.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.lostConnection = exports.wsError = exports.wsClosed = exports.wsDisconnectFinished = exports.wsConnectFinished = exports.wsDisconnect = exports.wsAttemptConnect = undefined; exports.changeConnectivityChecking = changeConnectivityChecking; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/connectivity/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _constants = __webpack_require__(/*! ../../constants */ "./src/constants.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * @param {string} type */ function createWsAction(type) { /** * @param {any=} payload * @param {string=} platform */ function action(payload) { var platform = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _constants.platforms.LINK; return { type: type, // TODO: This must check for kandy error eventually instead. error: payload instanceof Error, payload: payload, meta: { platform: platform } }; } return action; } // Constants var wsAttemptConnect = exports.wsAttemptConnect = createWsAction(actionTypes.WS_ATTEMPT_CONNECT); var wsDisconnect = exports.wsDisconnect = createWsAction(actionTypes.WS_DISCONNECT); var wsConnectFinished = exports.wsConnectFinished = createWsAction(actionTypes.WS_CONNECT_FINISHED); var wsDisconnectFinished = exports.wsDisconnectFinished = createWsAction(actionTypes.WS_DISCONNECT_FINISHED); var wsClosed = exports.wsClosed = createWsAction(actionTypes.WS_CLOSED); var wsError = exports.wsError = createWsAction(actionTypes.WS_ERROR); var lostConnection = exports.lostConnection = createWsAction(actionTypes.LOST_CONNECTION); /** * Represents a request to change the connectivity checking (ie. pinging). * @method changeConnectivityChecking * @param {boolean} enable Whether to enable or disable connectivity checking. * @return {Object} A flux-standard action. */ function changeConnectivityChecking(enable) { return { type: actionTypes.CHANGE_CONNECTIVITY_CHECKING, payload: enable }; } /***/ }), /***/ "./src/connectivity/interface/api.js": /*!*******************************************!*\ !*** ./src/connectivity/interface/api.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = api; var _constants = __webpack_require__(/*! ../../constants */ "./src/constants.js"); var _actions = __webpack_require__(/*! ./actions */ "./src/connectivity/interface/actions.js"); var _selectors = __webpack_require__(/*! ./selectors */ "./src/connectivity/interface/selectors.js"); /** * Kandy's connection feature is used to connect and maintain connections between * the SDK and one or more backend servers. * * Connectivity functions are namespaced beneath 'connection' on the returned Kandy object. * * @public * @module Connectivity * */ function api(_ref) { var dispatch = _ref.dispatch, getState = _ref.getState; var connectivityApi = { /** * Get the state of the websocket. * @public * @memberof Connectivity * @method getSocketState * @param {string} [platform='link'] Backend platform for which websocket's state to request. */ getSocketState: function getSocketState() { var platform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _constants.platforms.LINK; return (0, _selectors.getConnectionState)(getState(), platform); }, /** * Enables or disables connectivity checking. * @public * @memberof Connectivity * @method enableConnectivityChecking * @param {boolean} enable Whether to enable or disable connectivity checking. */ enableConnectivityChecking: function enableConnectivityChecking(enable) { dispatch((0, _actions.changeConnectivityChecking)(enable)); } }; return { connection: connectivityApi }; } // Constants /***/ }), /***/ "./src/connectivity/interface/eventTypes.js": /*!**************************************************!*\ !*** ./src/connectivity/interface/eventTypes.js ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * The websocket to the server has changed state. * * @public * @memberof Connectivity * @event ws:change * @param {Object} params * @param {string} params.platform The platform */ var WS_CHANGE = exports.WS_CHANGE = 'ws:change'; /***/ }), /***/ "./src/connectivity/interface/events.js": /*!**********************************************!*\ !*** ./src/connectivity/interface/events.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/connectivity/interface/eventTypes.js"); var eventTypes = _interopRequireWildcard(_eventTypes); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/connectivity/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var events = {}; events[actionTypes.WS_CONNECT_FINISHED] = function (action) { if (action.error) { // TODO: Handle the error case? } else { return { type: eventTypes.WS_CHANGE, args: { platform: action.meta.platform } }; } }; events[actionTypes.LOST_CONNECTION] = function (action) { return { type: eventTypes.WS_CHANGE, args: { platform: action.meta.platform } }; }; // TODO: Differentiate between types of disconnects? events[actionTypes.WS_DISCONNECT_FINISHED] = events[actionTypes.LOST_CONNECTION]; // TODO: Does an app care that we're trying to connect/reconnect? events[actionTypes.WS_ATTEMPT_CONNECT] = function (action) { return { type: eventTypes.WS_CHANGE, args: { platform: action.meta.platform } }; }; exports.default = events; /***/ }), /***/ "./src/connectivity/interface/index.js": /*!*********************************************!*\ !*** ./src/connectivity/interface/index.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reducer = exports.api = exports.name = undefined; var _name = __webpack_require__(/*! ./name */ "./src/connectivity/interface/name.js"); var _name2 = _interopRequireDefault(_name); var _api = __webpack_require__(/*! ./api */ "./src/connectivity/interface/api.js"); var _api2 = _interopRequireDefault(_api); var _reducers = __webpack_require__(/*! ./reducers */ "./src/connectivity/interface/reducers.js"); var _reducers2 = _interopRequireDefault(_reducers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.name = _name2.default; exports.api = _api2.default; exports.reducer = _reducers2.default; /***/ }), /***/ "./src/connectivity/interface/name.js": /*!********************************************!*\ !*** ./src/connectivity/interface/name.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var name = 'connectivity'; exports.default = name; /***/ }), /***/ "./src/connectivity/interface/reducers.js": /*!************************************************!*\ !*** ./src/connectivity/interface/reducers.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = __webpack_require__(/*! babel-runtime/helpers/defineProperty */ "../../node_modules/babel-runtime/helpers/defineProperty.js"); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _extends5 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends6 = _interopRequireDefault(_extends5); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/connectivity/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var reducers = {}; reducers[actionTypes.WS_ATTEMPT_CONNECT] = { next: function next(state, action) { return (0, _extends6.default)({}, state, (0, _defineProperty3.default)({}, action.meta.platform, (0, _extends6.default)({}, state[action.meta.platform], { connected: false, pinging: false }))); } }; reducers[actionTypes.WS_CONNECT_FINISHED] = { next: function next(state, action) { return (0, _extends6.default)({}, state, (0, _defineProperty3.default)({}, action.meta.platform, (0, _extends6.default)({}, state[action.meta.platform], { connected: true, method: action.payload.kandy.method, platform: action.meta.platform }, (0, _fp.omit)('checkConnectivity', action.payload.kandy)))); }, throw: function _throw(state, action) { return (0, _defineProperty3.default)({}, action.meta.platform, { connected: false, pinging: false }); } }; reducers[actionTypes.LOST_CONNECTION] = { next: function next(state, action) { return (0, _extends6.default)({}, state, (0, _defineProperty3.default)({}, action.meta.platform, (0, _extends6.default)({}, state[action.meta.platform], { connected: false, pinging: false }))); } }; reducers[actionTypes.WS_DISCONNECT_FINISHED] = { next: function next(state, action) { return (0, _defineProperty3.default)({}, action.meta.platform, { connected: false, pinging: false }); }, throw: function _throw(state, action) { return (0, _defineProperty3.default)({}, action.meta.platform, { connected: false, pinging: false }); } }; reducers[actionTypes.WS_ERROR] = { next: function next(state, action) { return (0, _defineProperty3.default)({}, action.meta.platform, { connected: false, pinging: false }); }, throw: function _throw(state, action) { return (0, _defineProperty3.default)({}, action.meta.platform, { connected: false, pinging: false }); } }; reducers[actionTypes.CHANGE_CONNECTIVITY_CHECKING] = { next: function next(state, action) { return (0, _extends6.default)({}, state, { checkConnectivity: action.payload }); } }; /** * Connectivity Interface reducer * @method reducer * @param {Object} state - The current redux state. * @param {Object} action - A flux standard action. * @return {Object} - The new redux state. */ var reducer = (0, _reduxActions.handleActions)(reducers, {}); exports.default = reducer; /***/ }), /***/ "./src/connectivity/interface/selectors.js": /*!*************************************************!*\ !*** ./src/connectivity/interface/selectors.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getConnectionState = getConnectionState; exports.getConnectivityConfig = getConnectivityConfig; exports.getCheckConnectivity = getCheckConnectivity; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _name = __webpack_require__(/*! ./name */ "./src/connectivity/interface/name.js"); var _name2 = _interopRequireDefault(_name); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getConnectionState(state, platform) { if (state[_name2.default][platform]) { return (0, _fp.cloneDeep)(state[_name2.default][platform]); } else { return new Error('No sockets are up. Have you attempted to connect?'); } } /** * Retrieves the config options provided by the connectivity plugin. * @method getConnectivityConfig * @return {Object} */ function getConnectivityConfig(state) { return (0, _fp.cloneDeep)(state.config[_name2.default]); } /** * Retrieves the flag for whether websocket connectivity checks should occur. * @method getCheckConnectivity * @param {Object} state Redux state. * @return {boolean} checkConnectivity */ function getCheckConnectivity(state) { return (0, _fp.cloneDeep)(state[_name2.default].checkConnectivity); } /***/ }), /***/ "./src/connectivity/sagas.js": /*!***********************************!*\ !*** ./src/connectivity/sagas.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.wsConnectFlow = wsConnectFlow; exports.websocketLifecycle = websocketLifecycle; exports.pingFlow = pingFlow; exports.connectWebsocket = connectWebsocket; var _websocket = __webpack_require__(/*! ./websocket */ "./src/connectivity/websocket.js"); var _selectors = __webpack_require__(/*! ./interface/selectors */ "./src/connectivity/interface/selectors.js"); var _actionTypes = __webpack_require__(/*! ./interface/actionTypes */ "./src/connectivity/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _actions = __webpack_require__(/*! ./interface/actions */ "./src/connectivity/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _selectors2 = __webpack_require__(/*! ../auth/interface/selectors */ "./src/auth/interface/selectors.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _reduxSaga = __webpack_require__(/*! redux-saga */ "../../node_modules/redux-saga/es/index.js"); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); var _constants = __webpack_require__(/*! ../constants */ "./src/constants.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(wsConnectFlow), _marked2 = /*#__PURE__*/_regenerator2.default.mark(websocketLifecycle), _marked3 = /*#__PURE__*/_regenerator2.default.mark(pingFlow), _marked4 = /*#__PURE__*/_regenerator2.default.mark(connectWebsocket); // Connectivity plugin. // Other plugins. // Libraries. // Constants // Get the logger var log = (0, _logs.getLogManager)().getLogger('CONNECTIVITY'); function wsConnectFlow() { var chan; return _regenerator2.default.wrap(function wsConnectFlow$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.actionChannel)(actionTypes.WS_ATTEMPT_CONNECT); case 2: chan = _context.sent; _context.next = 5; return (0, _reduxSaga.takeEvery)(chan, websocketLifecycle); case 5: case 'end': return _context.stop(); } } }, _marked, this); } /** * Saga that handles a websocket over its lifecycle. * @method websocketLifecycle * @param {Object} wsConnectAction */ function websocketLifecycle(wsConnectAction) { var wsInfo, platform, websocket, emitTask, pingTask, closeWebsocketPattern, action, _ref, notificationChannel, _ref2, accessToken, oauthToken; return _regenerator2.default.wrap(function websocketLifecycle$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: closeWebsocketPattern = function closeWebsocketPattern(action) { return (action.type === actionTypes.WS_DISCONNECT || action.type === actionTypes.LOST_CONNECTION) && action.meta.platform === platform; }; wsInfo = wsConnectAction.payload; platform = wsConnectAction.meta.platform; // Try to open the websocket. _context2.next = 5; return (0, _effects.call)(connectWebsocket, wsInfo, platform); case 5: websocket = _context2.sent; _context2.next = 8; return (0, _effects.select)(_selectors.getConnectivityConfig); case 8: websocket.kandy = _context2.sent; websocket.kandy.wsInfo = wsInfo; websocket.kandy.platform = platform; // If the websocket didn't open, dispatch the error and stop here. if (!websocket.error) { _context2.next = 15; break; } _context2.next = 14; return (0, _effects.put)(actions.wsConnectFinished(new Error(websocket.message), platform)); case 14: return _context2.abrupt('return'); case 15: // set last contact in both cases to be now websocket.kandy.lastContact = Date.now(); _context2.next = 18; return (0, _effects.fork)(_websocket.wsEmitter, websocket, platform); case 18: emitTask = _context2.sent; _context2.next = 21; return (0, _effects.fork)(pingFlow, websocket, platform); case 21: pingTask = _context2.sent; _context2.next = 24; return (0, _effects.put)(actions.wsConnectFinished(websocket, platform)); case 24: _context2.next = 26; return (0, _effects.take)(closeWebsocketPattern); case 26: action = _context2.sent; // Whether we're disconnecting or have lost connection, // we want to cancel these tasks either way. (0, _effects.cancel)(emitTask); (0, _effects.cancel)(pingTask); if (!(action.type === actionTypes.WS_DISCONNECT)) { _context2.next = 36; break; } _context2.next = 32; return (0, _effects.call)(_websocket.closeWebsocket, websocket); case 32: _context2.next = 34; return (0, _effects.put)(actions.wsDisconnectFinished(undefined, platform)); case 34: _context2.next = 50; break; case 36: if (!(wsConnectAction.meta.platform === _constants.platforms.CPAAS)) { _context2.next = 48; break; } _context2.next = 39; return (0, _effects.select)(_selectors2.getSubscriptionInfo); case 39: _ref = _context2.sent; notificationChannel = _ref.notificationChannel; _context2.next = 43; return (0, _effects.select)(_selectors2.getConnectionInfo); case 43: _ref2 = _context2.sent; accessToken = _ref2.accessToken; oauthToken = _ref2.oauthToken; wsInfo.url = notificationChannel; if (oauthToken && !accessToken) { wsInfo.params = { access_token: oauthToken }; } else { wsInfo.params = { token: accessToken }; } case 48: _context2.next = 50; return (0, _effects.put)(actions.wsAttemptConnect(wsInfo, wsConnectAction.meta.platform)); case 50: case 'end': return _context2.stop(); } } }, _marked2, this); } /** * A function that takes a websocket and pings the websocket periodically. * Will not ping the websocket if configured not to. */ function pingFlow(ws) { var reconnectAfter, _ref3, checkConnectivity, method, shouldCheck, lastContact, wasDisabled, sendCheck, error, _error, action, _ref4, close; return _regenerator2.default.wrap(function pingFlow$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: reconnectAfter = ws.kandy.pingInterval * ws.kandy.maxMissedPings; _context3.next = 3; return (0, _effects.select)(_selectors.getConnectivityConfig); case 3: _ref3 = _context3.sent; checkConnectivity = _ref3.checkConnectivity; method = _ref3.method; shouldCheck = void 0; lastContact = void 0; wasDisabled = false; // Sends a ping or keepalive. Returns true if an error occurs, else false. sendCheck = function sendCheck(ws, message) { wasDisabled = false; try { if (ws && ws.readyState === 1) { ws.send(message); return false; } else { // TODO: add reconnect logic here? check autoReconnect and then put a lostConnection action? log.error('The websocket has been closed. Connectivity may be gone or subscription may have expired.'); return true; } } catch (e) { log.error('Exception in pingFlow: ' + e.message); return true; } }; case 10: if (false) {} _context3.next = 13; return (0, _effects.select)(_selectors.getCheckConnectivity); case 13: shouldCheck = _context3.sent; shouldCheck = typeof shouldCheck !== 'undefined' ? shouldCheck : checkConnectivity; if (!shouldCheck) { _context3.next = 49; break; } if (!(method === 'keepAlive')) { _context3.next = 26; break; } // If method is keepalive, we don't care about pongs, just send messages over the ws. log.debug(ws.kandy.platform + ' sending a keepalive.'); error = sendCheck(ws, 'keepalive'); if (!error) { _context3.next = 24; break; } if (!ws.kandy.autoReconnect) { _context3.next = 23; break; } _context3.next = 23; return (0, _effects.put)(actions.lostConnection(undefined, ws.kandy.platform)); case 23: return _context3.abrupt('break', 64); case 24: _context3.next = 47; break; case 26: if (!(method === 'pingPong')) { _context3.next = 46; break; } // If method is pingpong, we want to see pongs at some point. lastContact = Date.now() - ws.kandy.lastContact; log.debug(ws.kandy.platform + ' websocket last contact: ' + lastContact + '. Reconnect after ' + reconnectAfter + '.'); // If we've gone too long without contact, and pinging wasn't disabled, report a connection issue. if (!(lastContact >= ws.kandy.pingInterval * ws.kandy.maxMissedPings && !wasDisabled)) { _context3.next = 37; break; } log.warn('Websocket closed due to inactivity.', ws.kandy.platform); if (!ws.kandy.autoReconnect) { _context3.next = 34; break; } _context3.next = 34; return (0, _effects.put)(actions.lostConnection(undefined, ws.kandy.platform)); case 34: return _context3.abrupt('break', 64); case 37: if (lastContact < ws.kandy.pingInterval) { _context3.next = 44; break; } // Check if we have recently contacted the server. If so, don't bother pinging. // TODO: Determine ping message format. _error = sendCheck(ws, (0, _stringify2.default)({ message_type: 'ping' })); if (!_error) { _context3.next = 44; break; } if (!ws.kandy.autoReconnect) { _context3.next = 43; break; } _context3.next = 43; return (0, _effects.put)(actions.lostConnection(undefined, ws.kandy.platform)); case 43: return _context3.abrupt('break', 64); case 44: _context3.next = 47; break; case 46: log.warn('An invalid connectivity method (' + method + ') has been passed in. Valid options are \'pingPong\' and \'keepAlive\'.'); case 47: _context3.next = 56; break; case 49: log.debug('Set to not check websocket connectivity.'); // If we shouldn't ping, wait until we receive a trigger to (maybe) ping. _context3.next = 52; return (0, _effects.take)(actionTypes.CHANGE_CONNECTIVITY_CHECKING); case 52: action = _context3.sent; shouldCheck = action.payload; wasDisabled = true; log.debug('Connectivity check setting changed. Check connectivity?: ' + shouldCheck); case 56: _context3.next = 58; return (0, _effects.race)({ expiry: (0, _effects.call)(_reduxSaga.delay, ws.kandy.pingInterval), close: (0, _effects.take)(actionTypes.WS_DISCONNECT_FINISHED) }); case 58: _ref4 = _context3.sent; close = _ref4.close; if (!close) { _context3.next = 62; break; } return _context3.abrupt('break', 64); case 62: _context3.next = 10; break; case 64: case 'end': return _context3.stop(); } } }, _marked3, this); } /** * Helper function for connecting to a websocket. * Attempts to connect a specified number of times before returning an error. * Includes a delay in between attempts, determined by configs. * @method connectWebsocket * @param {Object} wsInfo * @return {Websocket|Object} Either a connected websocket or an error object. */ function connectWebsocket(wsInfo, platform) { var configs, connectionAttempt, delayTime, websocket, disconnectWebsocketPattern, _ref5, _cancel; return _regenerator2.default.wrap(function connectWebsocket$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: disconnectWebsocketPattern = function disconnectWebsocketPattern(action) { return action.type === actionTypes.WS_DISCONNECT && action.meta.platform === platform; }; _context4.next = 3; return (0, _effects.select)(_selectors.getConnectivityConfig); case 3: configs = _context4.sent; connectionAttempt = 0; delayTime = 0; websocket = void 0; // Redux-saga take() pattern. // Take disconnect websocket action for this platform. // If no limit is set, we will continually attempt to reconnect. if (!configs.reconnectLimit) { log.debug('No connectivity reconnect limit set.'); } case 8: if (!(connectionAttempt < configs.reconnectLimit || !configs.reconnectLimit)) { _context4.next = 36; break; } _context4.prev = 9; _context4.next = 12; return (0, _effects.call)(_websocket.openWebsocket, wsInfo); case 12: websocket = _context4.sent; log.debug('Successfully connected to websocket.', platform); return _context4.abrupt('break', 36); case 17: _context4.prev = 17; _context4.t0 = _context4['catch'](9); connectionAttempt++; websocket = _context4.t0; log.debug('Failed websocket connection (#' + connectionAttempt + '): ' + websocket.message + '.', platform); // If we want to try to reconnect, delay a certain about of time before trying. if (!(connectionAttempt < configs.reconnectLimit || !configs.reconnectLimit)) { _context4.next = 33; break; } // Increase the delay time if we're not at the limit. if (delayTime !== configs.reconnectTimeLimit) { delayTime = configs.reconnectDelay * Math.pow(configs.reconnectTimeMultiplier, connectionAttempt - 1); delayTime = delayTime < configs.reconnectTimeLimit ? delayTime : configs.reconnectTimeLimit; } log.debug('Websocket reconnect attempt after ' + delayTime + 'ms.', platform); // Wait for either the delay period or a trigger to stop connection attempts. _context4.next = 27; return (0, _effects.race)({ delay: (0, _effects.call)(_reduxSaga.delay, delayTime), cancel: (0, _effects.take)(disconnectWebsocketPattern) }); case 27: _ref5 = _context4.sent; _cancel = _ref5.cancel; if (!_cancel) { _context4.next = 31; break; } return _context4.abrupt('break', 36); case 31: _context4.next = 34; break; case 33: log.debug('Stopping websocket connection attempts.', platform); case 34: _context4.next = 8; break; case 36: return _context4.abrupt('return', websocket); case 37: case 'end': return _context4.stop(); } } }, _marked4, this, [[9, 17]]); } /***/ }), /***/ "./src/connectivity/websocket.js": /*!***************************************!*\ !*** ./src/connectivity/websocket.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); var _promise = __webpack_require__(/*! babel-runtime/core-js/promise */ "../../node_modules/babel-runtime/core-js/promise.js"); var _promise2 = _interopRequireDefault(_promise); exports.openWebsocket = openWebsocket; exports.closeWebsocket = closeWebsocket; exports.wsEmitter = wsEmitter; var _actions = __webpack_require__(/*! ./interface/actions */ "./src/connectivity/interface/actions.js"); var _reduxSaga = __webpack_require__(/*! redux-saga */ "../../node_modules/redux-saga/es/index.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _utils = __webpack_require__(/*! ../common/utils */ "./src/common/utils.js"); var _actions2 = __webpack_require__(/*! ../notifications/interface/actions */ "./src/notifications/interface/actions.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(wsEmitter); var INITIAL_BUFFER_SIZE = 50; /** * Create a new websocket. * @method openWebsocket * @param {Object} [options] Websocket configuration options. * @param {string} [options.protocol=wss] Websocket protocol to use. * @param {string} [options.server=multiwebsocket.kandy.io] Websocket IP. * @param {string} [options.port=443] Websocket port to use. * @param {string} [options.url] Websocket notification channel. * @param {Object} [options.params] A list of URL params to attach to the websocket. * @return {WebSocket} ws Newly connected websocket. */ function openWebsocket(options) { // Create the websocket. var ws = new WebSocket(options.protocol + '://' + options.server + ':' + options.port + options.url + (0, _utils.toQueryString)(options.params)); // Use a promise to wait for the first message from the websocket. // This indicates whether the WS opened successfully or not. var validateWS = new _promise2.default(function (resolve, reject) { var onOpen = function onOpen() { ws.onopen = null; ws.onerror = null; resolve(ws); }; var onError = function onError() { ws.onopen = null; ws.onerror = null; // TODO: Fix this? /* eslint-disable-next-line prefer-promise-reject-errors */ reject({ error: true, message: 'Could not connect to websocket. Received error on open.' }); }; ws.onopen = onOpen; ws.onerror = onError; }); return validateWS; } /** * Clean-up a provided websocket. * @method closeWebsocket * @param {Websocket} ws Websocket to be cleaned-up. * @return {Websocket} ws The websocket after being cleaned. */ function closeWebsocket(ws) { if (ws.close) { ws.close(); } else { ws.onclose = null; } ws.onmessage = null; ws.onopen = null; ws.onerror = null; } /** * Create an event channel for a given websocket * @param {WebSocket} ws The websocket to make an event channel for. * @param {string} [platform=link] The backend platform associated with the websocket. * @return {EventChannel} The event channel corresponding to the WebSocket */ function createWsChannel(ws, platform) { return (0, _reduxSaga.eventChannel)(function (emit) { // Define handlers ws.onmessage = function (message) { // Mark this websocket are being connected as of now. ws.kandy.lastContact = Date.now(); var data = JSON.parse(message.data); if (data.message_type && data.message_type === 'pong') { // Ignore Cloud pong messages. } else { emit((0, _actions2.websocketNotification)(data, platform)); } }; ws.onclose = function (data) { emit((0, _actions.wsClosed)(data, platform)); emit(_reduxSaga.END); }; ws.onerror = function (err) { emit((0, _actions.wsError)(new Error(err), platform)); emit(_reduxSaga.END); }; return function () { return closeWebsocket(ws); }; }, _reduxSaga.buffers.expanding(INITIAL_BUFFER_SIZE)); } /** * Saga worker for creating a websocket and emitting its events * @param {Object} ws configuration options. * @param {string} [platform=link] The backend platform associated with the websocket. * @return {Generator} */ function wsEmitter(ws, platform) { var wsChannel, action; return _regenerator2.default.wrap(function wsEmitter$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.call)(createWsChannel, ws, platform); case 2: wsChannel = _context.sent; case 3: if (false) {} _context.next = 6; return (0, _effects.take)(wsChannel); case 6: action = _context.sent; _context.next = 9; return (0, _effects.put)(action); case 9: _context.next = 3; break; case 11: case 'end': return _context.stop(); } } }, _marked, this); } /***/ }), /***/ "./src/constants.js": /*!**************************!*\ !*** ./src/constants.js ***! \**************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var platforms = exports.platforms = { LINK: 'link', CPAAS: 'cpaas', CPAAS2: 'cpaas2', CLOUD: 'cloud' }; var notificationTypes = exports.notificationTypes = { WEBSOCKET: 'websocket', PUSH: 'push' }; /***/ }), /***/ "./src/errors/codes.js": /*!*****************************!*\ !*** ./src/errors/codes.js ***! \*****************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Error codes for the Auth plugin. * @name authCodes */ var authCodes = exports.authCodes = { INVALID_CREDENTIALS: 'authentication:1', CLOUD_SUBSCRIBE_FAIL: 'authentication:2', CONNECT_FAIL_WS_ERROR: 'authentication:3', LINK_UNSUBSCRIBE_FAIL: 'authentication:4', LINK_SUBSCRIBE_FAIL: 'authentication:5', LINK_EXTEND_SUBSCRIPTION_FAIL: 'authentication:6', LINK_UPDATE_SUBSCRIPTION_FAIL: 'authentication:7', CPAAS_SUBSCRIBE_FAIL: 'authentication:8', CPAAS_REFRESH_TOKEN_FAIL: 'authentication:9', CPAAS_CREATE_TOKEN_FAIL: 'authentication:10', CPAAS_EXTEND_SUBSCRIPTION_FAIL: 'authentication:11', CPAAS_DISCONNECT_FAIL: 'authentication:12', MISSING_SERVICE: 'authentication:13' /** * Error codes for the Call plugin. * @name callCodes */ };var callCodes = exports.callCodes = { UNKNOWN_ERROR: 'call:1', GENERIC_ERROR: 'call:2', INIT_MEDIA_FAILED: 'call:3', USER_MEDIA_ERROR: 'call:4', NOT_SUPPORTED: 'call:5' /** * Error codes for the Call History plugin. * @name callHistoryCodes */ };var callHistoryCodes = exports.callHistoryCodes = { UNKNOWN_ERROR: 'callHistory:1', BAD_REQUEST: 'callHistory:2', NOT_FOUND: 'callHistory:3' /** * @name clickToCallCodes */ };var clickToCallCodes = exports.clickToCallCodes = { MISSING_ARGS: 'clickToCall:1', RESPONSE_ERROR: 'clickToCall:2' /** * Error codes for the Message plugin. * @name messagingCodes */ };var messagingCodes = exports.messagingCodes = { CREATE_GROUP_FAIL: 'messaging:1', MARK_READ_FAIL: 'messaging:2', REMOVE_MEMBERS_FAIL: 'messaging:3', ADD_MEMBERS_FAIL: 'messaging:4', SEND_MESSAGE_FAIL: 'messaging:5' /** * Error codes for the Message Waiting Indicator plugin. * @name mwiCodes */ };var mwiCodes = exports.mwiCodes = { FETCH_MWI_FAIL: 'mwi:1' /** * Error codes from the Sip Events plugin. * @name sipEventCodes */ };var sipEventCodes = exports.sipEventCodes = { UNKNOWN_ERROR: 'sipEvents:1', // The user did not subscribe/connect for the specified sip event service. NOT_PROVISIONED: 'sipEvents:2', // The user is not subscribed for the specified sip event. NOT_SUBSCRIBED: 'sipEvents:3' /** * Error codes for the audio bridge portion of the call plugin. * @name bridgeCodes */ };var bridgeCodes = exports.bridgeCodes = { UNKNOWN_ERROR: 'audioBridge:1', // TODO: Make "invalid input" (and others) a generic code. INVALID_INPUT: 'audioBridge:2', ALREADY_EXISTS: 'audioBridge:3', NOT_FOUND: 'audioBridge:4', NOT_SUPPORTED: 'audioBridge:5', MEDIA_NOT_FOUND: 'audioBridge:6', INVALID_STATE: 'audioBridge:7' /** * Error codes for the subscription plugin. * @name subscriptionCodes */ };var subscriptionCodes = exports.subscriptionCodes = { WS_CONNECTION_ERROR: 'subscription:1', CPAAS2_WSREQUEST_FAIL: 'subscription:2', CPAAS2_WSREVOKE_FAIL: 'subscription:3', CPAAS2_WSREFRESH_FAIL: 'subscription:4', CPAAS2_SERVICE_SUB_FAIL: 'subscription:5' }; /***/ }), /***/ "./src/errors/index.js": /*!*****************************!*\ !*** ./src/errors/index.js ***! \*****************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.subscriptionCodes = exports.bridgeCodes = exports.clickToCallCodes = exports.sipEventCodes = exports.mwiCodes = exports.messagingCodes = exports.callHistoryCodes = exports.callCodes = exports.authCodes = undefined; var _classCallCheck2 = __webpack_require__(/*! babel-runtime/helpers/classCallCheck */ "../../node_modules/babel-runtime/helpers/classCallCheck.js"); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _codes = __webpack_require__(/*! ./codes */ "./src/errors/codes.js"); Object.defineProperty(exports, 'authCodes', { enumerable: true, get: function get() { return _codes.authCodes; } }); Object.defineProperty(exports, 'callCodes', { enumerable: true, get: function get() { return _codes.callCodes; } }); Object.defineProperty(exports, 'callHistoryCodes', { enumerable: true, get: function get() { return _codes.callHistoryCodes; } }); Object.defineProperty(exports, 'messagingCodes', { enumerable: true, get: function get() { return _codes.messagingCodes; } }); Object.defineProperty(exports, 'mwiCodes', { enumerable: true, get: function get() { return _codes.mwiCodes; } }); Object.defineProperty(exports, 'sipEventCodes', { enumerable: true, get: function get() { return _codes.sipEventCodes; } }); Object.defineProperty(exports, 'clickToCallCodes', { enumerable: true, get: function get() { return _codes.clickToCallCodes; } }); Object.defineProperty(exports, 'bridgeCodes', { enumerable: true, get: function get() { return _codes.bridgeCodes; } }); Object.defineProperty(exports, 'subscriptionCodes', { enumerable: true, get: function get() { return _codes.subscriptionCodes; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var KandyError = function KandyError(_ref) { var message = _ref.message, code = _ref.code; (0, _classCallCheck3.default)(this, KandyError); this.name = 'KandyError'; this.code = code || 'NO_CODE'; this.message = message ? '' + message : 'An error occurred.'; }; exports.default = KandyError; /***/ }), /***/ "./src/events/eventEmitter.js": /*!************************************!*\ !*** ./src/events/eventEmitter.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _assign = __webpack_require__(/*! babel-runtime/core-js/object/assign */ "../../node_modules/babel-runtime/core-js/object/assign.js"); var _assign2 = _interopRequireDefault(_assign); exports.default = eventEmitter; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* * Event emitter module. Can be used as a standalone factory or as a mixin. * * @private * @class emitter * @example * ``` javascript * var eventEmitter = emitter(); // Create a new emitter. * emitter(myEmittingObject.prototype); // Mixin to an existing object. * ``` */ function eventEmitter() { var prototype = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var eventMap = []; var subscribeMap = []; var strictMode = false; /* * Check if the event is a valid event type. */ function checkEvent(type) { if (strictMode && !eventMap[type]) { throw new Error('Invalid event type: ' + type); } } return (0, _assign2.default)(prototype, { /* * Define an event type with the event emitter. * * @method define * @param {String} type The name for the event type. */ define: function define(type) { eventMap[type] = eventMap[type] || []; }, /* * Define an alias for an event type. * * @method alias * @param {String} type The event type for which to add an alias. * @param {String} alias The alias name for the event type. * @throws {Error} Invalid event type */ alias: function alias(type, _alias) { checkEvent(type); eventMap[_alias] = eventMap[type] = eventMap[type] || []; }, /* * Add an event listener for the specified event type. * * @method on * @param {String} type The event type for which to add the listener. * @param {Function} listener The listener for the event type. The parameters * of the listener depend on the event type. * @throws {Error} Invalid event type */ on: function on(type, listener) { checkEvent(type);(eventMap[type] = eventMap[type] || []).push(listener); }, /* * Removes an event listener for the specified event type. * * @method off * @param {String} type The event type for which to remote the listener. * @param {Function} listener The listener to remove. * @throws {Error} Invalid event type */ off: function off(type, listener) { checkEvent(type); var list = eventMap[type] || []; var i = list.length; while (i--) { if (listener === list[i]) { list.splice(i, 1); } } }, /* * Emits an event of the specified type. * * @method emit * @param {String} type The event type to emit. * @param {any} [...args] The arguments to pass to the listeners of the event. * @throws {Error} Invalid event type */ emit: function emit(type) { checkEvent(type); var args = Array.prototype.slice.call(arguments, 1); var list = eventMap[type] || []; var i = 0; for (; i < list.length; i++) { list[i].apply(undefined, args); } for (var j = 0; j < subscribeMap.length; j++) { subscribeMap[j].call(undefined, type, args); } }, /* * Add a subscription for all event types. * * @method subscribe * @param {Function} listener The listener for all event types. * @throws {Error} Listener not a function */ subscribe: function subscribe(listener) { if (typeof listener === 'function') { subscribeMap.push(listener); } else { throw new Error('Listener not a function'); } }, /* * Remove a subscription for all event types. * * @method unsubscribe * @param {Function} listener The listener for all event types. * @throws {Error} Listener not a function */ unsubscribe: function unsubscribe(listener) { if (typeof listener === 'function') { var i = subscribeMap.length; while (i--) { if (listener === subscribeMap[i]) { subscribeMap.splice(i, 1); } } } else { throw new Error('Listener not a function'); } }, /* * Sets the emitter in strict mode where it only allows events that have been defined or aliases. * * @method setStrictMode * @param {Boolean} strict Whether to set strict mode for the emitter. */ setStrictMode: function setStrictMode(strict) { strictMode = strict; } }); } /***/ }), /***/ "./src/events/index.js": /*!*****************************!*\ !*** ./src/events/index.js ***! \*****************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _getIterator2 = __webpack_require__(/*! babel-runtime/core-js/get-iterator */ "../../node_modules/babel-runtime/core-js/get-iterator.js"); var _getIterator3 = _interopRequireDefault(_getIterator2); var _promise = __webpack_require__(/*! babel-runtime/core-js/promise */ "../../node_modules/babel-runtime/core-js/promise.js"); var _promise2 = _interopRequireDefault(_promise); var _toConsumableArray2 = __webpack_require__(/*! babel-runtime/helpers/toConsumableArray */ "../../node_modules/babel-runtime/helpers/toConsumableArray.js"); var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2); exports.default = eventsCloudImplementation; var _interface = __webpack_require__(/*! ./interface */ "./src/events/interface/index.js"); var _interface2 = _interopRequireDefault(_interface); var _actions = __webpack_require__(/*! ./interface/actions */ "./src/events/interface/actions.js"); var _actionTypes = __webpack_require__(/*! ./interface/actionTypes */ "./src/events/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _eventEmitter = __webpack_require__(/*! ./eventEmitter */ "./src/events/eventEmitter.js"); var _eventEmitter2 = _interopRequireDefault(_eventEmitter); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Event Emitter Implementation. * Factory function to create the Event Emitter Implementation. * Defines the functionality exposed by an Event Emitter Interface. */ // Events plugin. function eventsCloudImplementation() { return { name: _interface2.default.name, middleware: middleware, api: _interface2.default.api, reducer: _interface2.default.reducer }; } /** * Implementation of Event Emitter Interface. * @return {Middleware} middleware Middleware to be applied to the redux store. */ function middleware(context) { var emitter = (0, _eventEmitter2.default)(); var eventMap = {}; /** * Middleware to handle Event Emitter Interface actions. * Redirects Interface actions to the Plugin functionality, and dispatches * actions to update the store if needed. * @type {Function} */ return function (next) { return function (action) { switch (action.type) { case actionTypes.EVENTS_ON: emitter.on(action.payload.eventType, action.payload.listener); break; case actionTypes.EVENTS_OFF: emitter.off(action.payload.eventType, action.payload.listener); break; case actionTypes.EVENTS_SUBSCRIBE: emitter.subscribe(action.payload); break; case actionTypes.EVENTS_UNSUBSCRIBE: emitter.unsubscribe(action.payload); break; case actionTypes.EVENTS_ALIAS: emitter.alias(action.payload.eventType, action.payload.alias); break; case actionTypes.EVENTS_EMIT: emitter.emit.apply(emitter, [action.payload.eventType].concat((0, _toConsumableArray3.default)(action.payload.args))); break; case actionTypes.MAP_EVENTS: for (var actionType in action.payload) { if (action.payload.hasOwnProperty(actionType)) { var mapper = action.payload[actionType]; if (eventMap.hasOwnProperty(actionType)) { eventMap[actionType].push(mapper); } else { eventMap[actionType] = [mapper]; } } } break; default: if (eventMap.hasOwnProperty(action.type)) { var result = next(action); // make this compatible with promise middleware by ensuring we // wait for the promise to resolve. It's easier to just always // use a promise, as opposed to handling cases. if (!result || !result.then) { result = _promise2.default.resolve(result); } result.then(function () { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = (0, _getIterator3.default)(eventMap[action.type]), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _mapper = _step.value; var events = _mapper(action, context); if (!events) { events = []; } else if (!Array.isArray(events)) { events = [events]; } var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = (0, _getIterator3.default)(events), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var event = _step2.value; if (!event.args) { event.args = {}; } context.dispatch((0, _actions.emitEvent)(event.type, event.args)); } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } }); return result; } break; } return next(action); }; }; } /***/ }), /***/ "./src/events/interface/actionTypes.js": /*!*********************************************!*\ !*** ./src/events/interface/actionTypes.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PREFIX = '@@KANDY/'; var EVENTS_ON = exports.EVENTS_ON = PREFIX + 'EVENTS_ON'; var EVENTS_OFF = exports.EVENTS_OFF = PREFIX + 'EVENTS_OFF'; var EVENTS_SUBSCRIBE = exports.EVENTS_SUBSCRIBE = PREFIX + 'EVENTS_SUBSCRIBE'; var EVENTS_UNSUBSCRIBE = exports.EVENTS_UNSUBSCRIBE = PREFIX + 'EVENTS_UNSUBSCRIBE'; var EVENTS_ALIAS = exports.EVENTS_ALIAS = PREFIX + 'EVENTS_ALIAS'; var EVENTS_EMIT = exports.EVENTS_EMIT = PREFIX + 'EVENTS_EMIT'; var MAP_EVENTS = exports.MAP_EVENTS = PREFIX + 'MAP_EVENTS'; /***/ }), /***/ "./src/events/interface/actions.js": /*!*****************************************!*\ !*** ./src/events/interface/actions.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mapEvents = mapEvents; exports.on = on; exports.off = off; exports.subscribe = subscribe; exports.unsubscribe = unsubscribe; exports.emitEvent = emitEvent; exports.aliasEvent = aliasEvent; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/events/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Add an action-to-event mapping * @param {Object} mapping A mapping object * @return {action} A redux action. */ function mapEvents(mapping) { return { type: actionTypes.MAP_EVENTS, payload: mapping }; } /* Interface actions */ /** * Add a listener for a specified event type. * * @param {string} type The event type to add the listener on. * @param {Function} listener The event listener to be added. * @return {Action} action A redux action. */ function on(type, listener) { return { type: actionTypes.EVENTS_ON, payload: { eventType: type, listener: listener } }; } /** * Remove a listener from a specified event type. * * @param {string} type The event type to remove the listener from. * @param {Function} listener The event listener to be removed. * @return {Action} action A redux action. */ function off(type, listener) { return { type: actionTypes.EVENTS_OFF, payload: { eventType: type, listener: listener } }; } /** * Add a global event listener. * * @param {Function} listener The event listener to be added. * @return {Action} action A redux action. */ function subscribe(listener) { return { type: actionTypes.EVENTS_SUBSCRIBE, payload: listener }; } /** * Remove a global event listener. * * @param {Function} listener The event listener to be removed. * @return {Action} action A redux action. */ function unsubscribe(listener) { return { type: actionTypes.EVENTS_UNSUBSCRIBE, payload: listener }; } /* Internal actions */ /* * Emits an event of the specified type. * * @method emitEvent * @param {Object} payload Information of the event to emit. * @throws {Error} Invalid event type * @return action An EVENTS_EMIT action. */ function emitEvent(type) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (type === undefined) { throw Error('Attempted to emit an event without a type.'); } return { type: actionTypes.EVENTS_EMIT, payload: { eventType: type, args: args } }; } /* * Define an alias for an event type. * * @method alias * @param {String} type The event type for which to add an alias. * @param {String} alias The alias name for the event type. */ function aliasEvent(type, alias) { if (type === undefined || alias === undefined) { throw Error('Invalid attempt to alias an event.'); } return { type: actionTypes.EVENTS_ALIAS, payload: { eventType: type, alias: alias } }; } /***/ }), /***/ "./src/events/interface/api.js": /*!*************************************!*\ !*** ./src/events/interface/api.js ***! \*************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = api; var _actions = __webpack_require__(/*! ./actions */ "./src/events/interface/actions.js"); /** * API for Event Emitter plugin. * Defines the public end-points exposed by event plugins. * @param {Object} context The Kandy instance context. * @returns {Object} api The interface object. */ function api(_ref) { var dispatch = _ref.dispatch; var api = {}; /** * Add an event listener for the specified event type. * * @public * @memberof Events * @method on * @param {string} type The event type for which to add the listener. * @param {Function} listener The listener for the event type. The parameters of the listener depend on the event type. * @throws {Error} Invalid event type */ api.on = function (type, listener) { dispatch((0, _actions.on)(type, listener)); }; /** * Removes an event listener for the specified event type. * * @public * @memberof Events * @method off * @param {string} type The event type for which to remote the listener. * @param {Function} listener The listener to remove. * @throws {Error} Invalid event type */ api.off = function (type, listener) { dispatch((0, _actions.off)(type, listener)); }; /** * Adds a global event listener * * @public * @memberof Events * @method subscribe * @param {Function} listener The event listener to add. The parameters are (type, ...args), where args depend on the event type. * @throws {Error} Listener not a function */ api.subscribe = function (listener) { dispatch((0, _actions.subscribe)(listener)); }; /** * Removes a global event listener * * @public * @memberof Events * @method unsubscribe * @param {Function} listener The event listener to remove. * @throws {Error} Listener not a function */ api.unsubscribe = function (listener) { dispatch((0, _actions.unsubscribe)(listener)); }; return api; } /** * @public * @module Events */ // Actions the interface uses. /***/ }), /***/ "./src/events/interface/index.js": /*!***************************************!*\ !*** ./src/events/interface/index.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _api = __webpack_require__(/*! ./api */ "./src/events/interface/api.js"); var _api2 = _interopRequireDefault(_api); var _reducers = __webpack_require__(/*! ./reducers */ "./src/events/interface/reducers.js"); var _reducers2 = _interopRequireDefault(_reducers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * This interface is for an events plugin. * @type {string} */ // Import the components of the interface. var name = 'events'; exports.default = { name: name, api: _api2.default, reducer: _reducers2.default }; /***/ }), /***/ "./src/events/interface/reducers.js": /*!******************************************!*\ !*** ./src/events/interface/reducers.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = __webpack_require__(/*! babel-runtime/helpers/defineProperty */ "../../node_modules/babel-runtime/helpers/defineProperty.js"); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _extends3 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends4 = _interopRequireDefault(_extends3); exports.default = reducer; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/events/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Events plugin. function eventReducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { aliases: [], count: 0 }; var action = arguments[1]; switch (action.type) { case actionTypes.EVENTS_ON: return (0, _fp.update)('count', (0, _fp.add)(1), state); case actionTypes.EVENTS_OFF: return (0, _fp.update)('count', (0, _fp.add)(-1), state); case actionTypes.EVENTS_ALIAS: return (0, _fp.update)('aliases', (0, _fp.concat)(action.payload.alias), state); default: return state; } } /** * Reducer for Event Emitter plugin. * Defines the events an Event plugin should dispatch to modify state. * @param {Object} [state={}] The events substate. * @param {Object} action A Flux Standard action. * @returns {Object} state The new event substate. */ // Libraries. function reducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments[1]; // Only handle event types. if (!(0, _fp.contains)(action.type, actionTypes)) { return state; } return (0, _extends4.default)({}, state, (0, _defineProperty3.default)({}, action.payload.eventType, eventReducer(state[action.payload.eventType], action))); } /***/ }), /***/ "./src/factory.js": /*!************************!*\ !*** ./src/factory.js ***! \************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _getIterator2 = __webpack_require__(/*! babel-runtime/core-js/get-iterator */ "../../node_modules/babel-runtime/core-js/get-iterator.js"); var _getIterator3 = _interopRequireDefault(_getIterator2); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); var _defineProperty = __webpack_require__(/*! babel-runtime/core-js/object/define-property */ "../../node_modules/babel-runtime/core-js/object/define-property.js"); var _defineProperty2 = _interopRequireDefault(_defineProperty); var _getOwnPropertyDescriptor = __webpack_require__(/*! babel-runtime/core-js/object/get-own-property-descriptor */ "../../node_modules/babel-runtime/core-js/object/get-own-property-descriptor.js"); var _getOwnPropertyDescriptor2 = _interopRequireDefault(_getOwnPropertyDescriptor); exports.factory = factory; var _redux = __webpack_require__(/*! redux */ "../../node_modules/redux/es/index.js"); var _reduxDevtoolsExtension = __webpack_require__(/*! redux-devtools-extension */ "../../node_modules/redux-devtools-extension/index.js"); var _reduxSaga = __webpack_require__(/*! redux-saga */ "../../node_modules/redux-saga/es/index.js"); var _reduxSaga2 = _interopRequireDefault(_reduxSaga); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _compose = __webpack_require__(/*! stampit/compose */ "../../node_modules/stampit/compose.js"); var _compose2 = _interopRequireDefault(_compose); var _logs = __webpack_require__(/*! ./logs */ "./src/logs/index.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var log = (0, _logs.getLogManager)().getLogger('FACTORY'); /** * Returns whether the passed in property descriptor represents a normal ES3 property defined like so: * * ``` * var bar = { * name: 'value' * }; * * isNormalProperty(bar.getOwnPropertyDescriptor('name')); * // => true * ``` * * @param {PropertyDescriptor} propertyDescriptor The property descriptor to check for normalcy. * @return {boolean} True if the property is a normal property, false otherwise. */ // Logs function isNormalProperty(_ref) { var enumerable = _ref.enumerable, configurable = _ref.configurable, writable = _ref.writable, get = _ref.get, set = _ref.set; return configurable && enumerable && writable && !get && !set; } /** * Creates an instance of kandy with the specified plugins and configuration. * * @param {Plugin[]} plugins - The list of plugins to load into this instance of Kandy. */ function factory(plugins) { var _marked = /*#__PURE__*/_regenerator2.default.mark(rootSaga); // Log Kandy's version (templated by webpack) on initialization. var version = '3.0.0-beta.17786'; log.info('Kandy.js version: ' + version); var sagas = []; var store; var selectors = {}; var middlewares = []; var reducers = {}; var initSagas = []; var context = { capabilities: [], api: {}, primitives: {}, getState: function getState() { if (!store) { throw Error('Store is not available during factory creation'); } return store.getState(); }, dispatch: function dispatch() { var _store; if (!store) { throw Error('Store is not available during factory creation'); } return (_store = store).dispatch.apply(_store, arguments); }, subscribe: function subscribe(fn) { if (!store) { throw Error('Store is not available during factory creation'); } return store.subscribe(fn); } }; // Special case middleware for logging. var loggerMiddleware; // Run all the plugins to build the context. // Set up each plugin component individually. plugins.forEach(function (plugin) { if (plugin.capabilities) { context.capabilities = context.capabilities.concat(plugin.capabilities); } if (plugin.reducer) { reducers[plugin.name] = plugin.reducer; } if (plugin.selector) { selectors[plugin.name] = (0, _fp.memoize)(plugin.selector); } if (plugin.middleware) { if (plugin.name === 'logs') { loggerMiddleware = plugin.middleware; } else { middlewares.push(function () { return plugin.middleware(context); }); // pass context to middleware instead of store } } if (plugin.api) { // The following mergeWith uses a customizer that functions like Object.assign // except it copies property descriptors so that accessor type properties // are copied fully instead of just copying their current values. // The first two parameters are not being used. context.api = (0, _fp.mergeWith)(function (objValue, srcValue, property, destination, source) { var descriptor = (0, _getOwnPropertyDescriptor2.default)(source, property); if (descriptor && !isNormalProperty(descriptor)) { (0, _defineProperty2.default)(destination, property, descriptor); } else { if (destination === undefined) { destination = {}; } destination[property] = source[property]; } }, context.api, plugin.api(context)); } if (plugin.init) { initSagas.push(plugin.init); } if (plugin.sagas) { sagas = sagas.concat(plugin.sagas); } // TODO: Revisit this. Looks a little extreme for a couple stamps... if (plugin.mixins) { // Define a base stamp that all stamps will be composed with. // This gives stamps access to the factory's context. var baseStamp = { propertyDescriptors: { context: { get: function get() { return context; } } } }; for (var objName in plugin.mixins) { if (plugin.mixins.hasOwnProperty(objName)) { // Ensure that every stamp starts with the base stamp. if (!context.primitives.hasOwnProperty(objName)) { context.primitives[objName] = baseStamp; } context.primitives[objName] = (0, _compose2.default)(context.primitives[objName], plugin.mixins[objName]); } } } }); if (loggerMiddleware) { // The redux logger middleware should be the last middleware. middlewares.push(function () { return loggerMiddleware(context); }); } /** * Higher-order function to auto-restart sagas when they crash. * Based on: https://github.com/redux-saga/redux-saga/pull/644#issuecomment-266454875 * @method autoRestart * @param {Generator} saga The saga to wrap. * @return {Generator} Wrapped saga. */ function autoRestart(saga) { return (/*#__PURE__*/_regenerator2.default.mark(function autoRestarting() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var shouldRestart; return _regenerator2.default.wrap(function autoRestarting$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: // Only restart the saga if it crashed; avoid restarting it if // it returned normally. shouldRestart = false; case 1: _context.prev = 1; _context.next = 4; return _effects.call.apply(undefined, [saga].concat(args)); case 4: shouldRestart = false; _context.next = 11; break; case 7: _context.prev = 7; _context.t0 = _context['catch'](1); log.error('Unhandled error in saga ' + saga.name + '.', _context.t0); shouldRestart = true; case 11: if (shouldRestart) { _context.next = 1; break; } case 12: case 'end': return _context.stop(); } } }, autoRestarting, this, [[1, 7]]); }) ); } // Compose the root saga function rootSaga() { var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, init, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, saga; return _regenerator2.default.wrap(function rootSaga$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: // Give all plugins an opportunity to initialize themselves. // Note: Sagas have not been forked yet, so init cannot use them // by dispatching actions. See PR #698. // Note: If anything asynchronous is done in an init, it MUST be // non-blocking (ie. use fork, not call). See PR #699. _iteratorNormalCompletion = true; _didIteratorError = false; _iteratorError = undefined; _context2.prev = 3; _iterator = (0, _getIterator3.default)(initSagas); case 5: if (_iteratorNormalCompletion = (_step = _iterator.next()).done) { _context2.next = 11; break; } init = _step.value; return _context2.delegateYield(init(), 't0', 8); case 8: _iteratorNormalCompletion = true; _context2.next = 5; break; case 11: _context2.next = 17; break; case 13: _context2.prev = 13; _context2.t1 = _context2['catch'](3); _didIteratorError = true; _iteratorError = _context2.t1; case 17: _context2.prev = 17; _context2.prev = 18; if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } case 20: _context2.prev = 20; if (!_didIteratorError) { _context2.next = 23; break; } throw _iteratorError; case 23: return _context2.finish(20); case 24: return _context2.finish(17); case 25: // Run all of the sagas provided by implementation plugins. _iteratorNormalCompletion2 = true; _didIteratorError2 = false; _iteratorError2 = undefined; _context2.prev = 28; _iterator2 = (0, _getIterator3.default)(sagas); case 30: if (_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done) { _context2.next = 37; break; } saga = _step2.value; _context2.next = 34; return (0, _effects.fork)(autoRestart(saga)); case 34: _iteratorNormalCompletion2 = true; _context2.next = 30; break; case 37: _context2.next = 43; break; case 39: _context2.prev = 39; _context2.t2 = _context2['catch'](28); _didIteratorError2 = true; _iteratorError2 = _context2.t2; case 43: _context2.prev = 43; _context2.prev = 44; if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } case 46: _context2.prev = 46; if (!_didIteratorError2) { _context2.next = 49; break; } throw _iteratorError2; case 49: return _context2.finish(46); case 50: return _context2.finish(43); case 51: case 'end': return _context2.stop(); } } }, _marked, this, [[3, 13, 17, 25], [18,, 20, 24], [28, 39, 43, 51], [44,, 46, 50]]); } // don't include saga stuff if there are no sagas. if (initSagas.length + sagas.length > 0) { var sagaMiddleware = (0, _reduxSaga2.default)(); // Create the store with the plugins (incl. sagas) and with the configuration as the initial state. store = (0, _redux.createStore)((0, _redux.combineReducers)(reducers), (0, _reduxDevtoolsExtension.composeWithDevTools)(_redux.applyMiddleware.apply(undefined, [sagaMiddleware].concat(middlewares)))); sagaMiddleware.run(rootSaga); } else { // Create the store with the plugins (excl. sagas) and with the configuration as the initial state. store = (0, _redux.createStore)((0, _redux.combineReducers)(reducers), (0, _reduxDevtoolsExtension.composeWithDevTools)(_redux.applyMiddleware.apply(undefined, middlewares))); } // setup the API var selectState = function selectState(kandyState) { var exposedState = {}; // Determine what state should be exposed to an application. plugins.forEach(function (plugin) { var name = plugin.name; // If the plugin designates a selector to filter publuc state, use it. if (selectors[name]) { exposedState[name] = selectors[name](kandyState[name]); } else if (kandyState[name]) { // Otherwise, just expose the state directly, but // only expose state if there actually is state. exposedState[name] = kandyState[name]; } }); return exposedState; }; selectState = (0, _fp.memoize)(selectState); var publicAPI = (0, _extends3.default)({}, context.api, { state: { get: function get() { return selectState(store.getState()); }, subscribe: function subscribe() { var _store2; return (_store2 = store).subscribe.apply(_store2, arguments); } }, getCapabilities: function getCapabilities() { return context.capabilities; }, getVersion: function getVersion() { return version; } }); // Return the public API. return publicAPI; } /***/ }), /***/ "./src/index.common.js": /*!*****************************!*\ !*** ./src/index.common.js ***! \*****************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = commonIndex; var _factory = __webpack_require__(/*! ./factory */ "./src/factory.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); /** * The Kandy.js SDK Factory. Create an instance of the SDK by calling this factory with the the desired configurations. * @public * @method createKandy * @param {Object} configs The configuration object. * @example * // Instantiate the SDK. * let kandy = createKandy({ * authentication: { ... }, * logs: { ... }, * ... * }); * // Use the Kandy API. * kandy.on( ... ); */ /** * The configuration object. This object defines what different configuration * values you can use when instantiating the SDK. * @public * @module configs */ /** * A List of handlers for manipulating the SDP Object * @public * @module sdpHandlers */ /** * In some scenarios it's necessary to remove certain codecs being offered by the SDK to the remote party. While creating an SDP handler would allow a user to perform this type of manipulation, it is a non-trivial task that requires in-depth knowledge of WebRTC SDP. * * To facilitate this common task, the SDK provides a codec removal handler that can be used for this purpose. * * The SDP handlers are exposed on the entry point of the SDK. They need to be added to the list of SDP handlers via configuration on creation of a Kandy instance. * * @public * @memberof sdpHandlers * @method createCodecRemover * @example * import createKandy from 'kandy'; * const codecRemover = createKandy.sdpHandlers.createCodecRemover(['VP8', 'VP9']) * const kandy = createKandy({ * call: { * sdpHandlers: [codecRemover] * } * }) * */ /* * Index template file that is used to create pre-defined version of Kandy. */ function commonIndex() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var plugins = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var pluginInstances = (0, _fp.map)(function (plugin) { return plugin.fn(options[plugin.name]); }, plugins); return (0, _factory.factory)(pluginInstances); } /***/ }), /***/ "./src/index.link.js": /*!***************************!*\ !*** ./src/index.link.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _toConsumableArray2 = __webpack_require__(/*! babel-runtime/helpers/toConsumableArray */ "../../node_modules/babel-runtime/helpers/toConsumableArray.js"); var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2); var _index = __webpack_require__(/*! ./index.common */ "./src/index.common.js"); var _index2 = _interopRequireDefault(_index); var _basePlugins = __webpack_require__(/*! ./basePlugins */ "./src/basePlugins.js"); var _basePlugins2 = _interopRequireDefault(_basePlugins); var _link = __webpack_require__(/*! ./auth/link */ "./src/auth/link/index.js"); var _link2 = _interopRequireDefault(_link); var _call = __webpack_require__(/*! ./call */ "./src/call/index.js"); var _call2 = _interopRequireDefault(_call); var _callHistory = __webpack_require__(/*! ./callHistory */ "./src/callHistory/index.js"); var _callHistory2 = _interopRequireDefault(_callHistory); var _connectivity = __webpack_require__(/*! ./connectivity */ "./src/connectivity/index.js"); var _connectivity2 = _interopRequireDefault(_connectivity); var _sipEvents = __webpack_require__(/*! ./sipEvents */ "./src/sipEvents/index.js"); var _sipEvents2 = _interopRequireDefault(_sipEvents); var _link3 = __webpack_require__(/*! ./messaging/link */ "./src/messaging/link/index.js"); var _link4 = _interopRequireDefault(_link3); var _link5 = __webpack_require__(/*! ./mwi/link */ "./src/mwi/link/index.js"); var _link6 = _interopRequireDefault(_link5); var _presence = __webpack_require__(/*! ./presence */ "./src/presence/index.js"); var _presence2 = _interopRequireDefault(_presence); var _link7 = __webpack_require__(/*! ./users/link */ "./src/users/link.js"); var _link8 = _interopRequireDefault(_link7); var _clickToCall = __webpack_require__(/*! ./clickToCall */ "./src/clickToCall/index.js"); var _clickToCall2 = _interopRequireDefault(_clickToCall); var _codecRemover = __webpack_require__(/*! ../../fcs/src/js/sdp/codecRemover */ "../fcs/src/js/sdp/codecRemover.js"); var _codecRemover2 = _interopRequireDefault(_codecRemover); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var kandyPlugins = [].concat((0, _toConsumableArray3.default)(_basePlugins2.default), [{ name: 'authentication', fn: _link2.default }, { name: 'call', fn: _call2.default }, { name: 'callHistory', fn: _callHistory2.default }, { name: 'connectivity', fn: _connectivity2.default }, { name: 'sipEvents', fn: _sipEvents2.default }, { name: 'messaging', fn: _link4.default }, { name: 'mwi', fn: _link6.default }, { name: 'presence', fn: _presence2.default }, { name: 'users', fn: _link8.default }, { name: 'clickToCall', fn: _clickToCall2.default }]); function kandy() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var plugins = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; return (0, _index2.default)(options, [].concat((0, _toConsumableArray3.default)(kandyPlugins), (0, _toConsumableArray3.default)(plugins))); } kandy.sdpHandlers = { createCodecRemover: _codecRemover2.default // Export this way as a work-around, so it can be used as `<export>();`. // See: https://github.com/webpack/webpack/issues/706 };module.exports = kandy; /***/ }), /***/ "./src/logs/index.js": /*!***************************!*\ !*** ./src/logs/index.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = logger; exports.getLogManager = getLogManager; var _transformers = __webpack_require__(/*! ./transformers */ "./src/logs/transformers.js"); var _transformers2 = _interopRequireDefault(_transformers); var _api = __webpack_require__(/*! ./interface/api */ "./src/logs/interface/api.js"); var _api2 = _interopRequireDefault(_api); var _actions = __webpack_require__(/*! ../config/interface/actions */ "./src/config/interface/actions.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _utils = __webpack_require__(/*! ../common/utils */ "./src/common/utils.js"); var _logManager = __webpack_require__(/*! ./logManager */ "./src/logs/logManager.js"); var _logManager2 = _interopRequireDefault(_logManager); var _utils2 = __webpack_require__(/*! ./utils */ "./src/logs/utils.js"); var _reduxLogger = __webpack_require__(/*! redux-logger */ "../../node_modules/redux-logger/dist/redux-logger.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Default logging options // Other plugins. // Logs plugin. var defaultOptions = { // Possible levels: trace, debug, info, warn, error, silent. logLevel: 'debug', // Flatten the log entries into a string, rather than logging more complex data types. flatten: false, // Whether a stack trace should be included with the log. stackTraces: false, logActions: { // Only show action out of prevState, action, newState. actionOnly: true, // Collapse prevState, action, nextState objects by default. collapsed: false, // Log the diff for each action. diff: false, // set redux-logger's level to debug level: 'debug' }, enableFcsLogs: true // Instantiate the log manager }; // Redux Logger middleware // Log manager, log levels and redux-logger options // Libraries. var logMgr = getLogManager(defaultOptions); /** * Configuration options for the Logs feature. * @public * @name configs.logs * @memberof configs * @instance * @param {Object} logs Logs configs. * @param {String} [logs.logLevel=debug] Log level to be set. See `kandy.logger.levels`. * @param {Boolean} [logs.stackTraces=false] Set whether the log manager should always provide a stack trace. * @param {Boolean} [logs.flatten=false] Display the logged information as a string. * @param {Object} [logs.logActions] Extra configs when logLevel is at DEBUG+ levels. Set this to false to not log actions. * @param {Boolean} [logs.logActions.actionLogger=false] Override the logger provided to redux-logger. * @param {Boolean} [logs.logActions.actionOnly=true] Only show the action payload. * @param {Boolean} [logs.logActions.collapsed=false] Have logged objects be collapsed. * @param {Boolean} [logs.logActions.diff=false] Display the diff for each action log. * @param {Boolean} [logs.logActions.colors=false] Set whether colors are to be used in redux-logger * @param {Boolean} [logs.enableFcsLogs=true] Enable the detailed call logger. */ /** * Logger Plugin. * @method logger * @param {Object} [options] Plugin configurations. See above. * @return {Object} plugin A plugin object. */ function logger() { var _marked = /*#__PURE__*/_regenerator2.default.mark(init); var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var name = 'logs'; // Backwards compatibility: flatten replaced logActions.flattenActions // TODO: Remove this after awhile. if (options.logActions && options.logActions.flattenActions && options.flatten === undefined) { logMgr.getLogger('LOGS').warn('The Logs plugin config "logActions.flattenActions" has been ' + 'deprecated in favour of "flatten", and will be removed in a future build.'); options.flatten = options.logActions.flattenActions; } options = (0, _utils.mergeValues)(defaultOptions, options); // Now that plugins are being called, we can update the log manager with our desired configuration options logMgr.updateManager(options); function init() { return _regenerator2.default.wrap(function init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.put)((0, _actions.update)(options, name)); case 2: case 'end': return _context.stop(); } } }, _marked, this); } var components = { name: name, init: init, api: _api2.default // Consider actions to be at the INFO log level. // Only export a middleware (for actions) at the appropriate levels. };if (logMgr.getLevel() <= _logManager.logLevels.INFO && options.logActions !== false) { var actionOptions = {}; // Use different options for redux-logger depending on log level. if (logMgr.getLevel() === _logManager.logLevels.INFO) { // At the INFO level, hide everything except the action name. actionOptions.level = false; actionOptions.diff = false; } else { // At the DEBUG+ levels, use the configs. actionOptions = (0, _extends3.default)({}, options.logActions); } if (options.logActions.actionOnly) { // Hide prevState and nextState. // Log action and error at info level, so the browser won't hide it by default. actionOptions.level = { prevState: false, action: 'info', error: 'info', nextState: false }; } // ALWAYS use our own logger actionOptions.logger = logMgr.getLogger('ACTION'); // ALWAYS remove theming/styling from the action log messages actionOptions.titleFormatter = _utils2.titleFormatter; actionOptions.colors = false; // Setup the transformers based on the options. var transformers = (0, _transformers2.default)(options.logActions); // Create the kandy logger middleware. components.middleware = (0, _reduxLogger.createLogger)((0, _extends3.default)({}, actionOptions, transformers)); } return components; } /** * Getter checks to see if an instance of logManager exists, instantiates it if it does not, and returns * the instance of LogManager * @param {Object} [options] * @param {string} [options.logLevel] - the logging level, as per options found in logManager.levels * @param {Boolean} [options.flatten] * @param {Boolean} [options.stackTraces] * @returns {LogManager} an instance of our LogManager */ function getLogManager(options) { return logMgr || new _logManager2.default(options); } /***/ }), /***/ "./src/logs/interface/api.js": /*!***********************************!*\ !*** ./src/logs/interface/api.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = api; /** * The internal logger used to provide information about the SDK's behaviour. * Provide a log level as part of the SDK configuration (see `configs.logs`) to use the logger. * @public * @module Logger */ function api() { var api = { /** * Possible levels for the SDK logger. * @public * @memberof Logger * @property {string} SILENT Logs nothing. * @property {string} ERROR Only log unhandled errors. * @property {string} WARN Log issues that may cause problems or unexpected behaviour. * @property {string} INFO Log useful information and messages to indicate the SDK's internal operations. * @property {string} DEBUG Log information to help diagnose problematic behaviour. */ levels: { SILENT: 'silent', ERROR: 'error', WARN: 'warn', INFO: 'info', DEBUG: 'debug' } }; return { logger: api }; } /***/ }), /***/ "./src/logs/logManager.js": /*!********************************!*\ !*** ./src/logs/logManager.js ***! \********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.logLevels = undefined; var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); var _toConsumableArray2 = __webpack_require__(/*! babel-runtime/helpers/toConsumableArray */ "../../node_modules/babel-runtime/helpers/toConsumableArray.js"); var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2); exports.default = LogManager; var _loglevel = __webpack_require__(/*! loglevel */ "../../node_modules/loglevel/lib/loglevel.js"); var _loglevel2 = _interopRequireDefault(_loglevel); var _utils = __webpack_require__(/*! ./utils */ "./src/logs/utils.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Exposed logLevels object describes the level hierarchy * * @type {{TRACE: number, DEBUG: number, INFO: number, WARN: number, ERROR: number, SILENT: number}} */ var logLevels = exports.logLevels = { TRACE: 0, DEBUG: 1, INFO: 2, WARN: 3, ERROR: 4, SILENT: 5 /** * Creates a log manager to provision loggers and coordinate processing of log entries * @method LogManager * @param {Object} [options] * @param {string} [options.logLevel='INFO'] * @param {boolean} [options.flatten=false] * @param {boolean} [options.stackTraces=false] */ };function LogManager(_ref) { var _this2 = this; var _ref$logLevel = _ref.logLevel, logLevel = _ref$logLevel === undefined ? 'INFO' : _ref$logLevel, _ref$flatten = _ref.flatten, flatten = _ref$flatten === undefined ? false : _ref$flatten, _ref$stackTraces = _ref.stackTraces, stackTraces = _ref$stackTraces === undefined ? false : _ref$stackTraces; // Create a property to reference the master logger this._log = _loglevel2.default; // Always convert the logLevel string to upper case for consistency this.level = logLevels[logLevel.toUpperCase()]; this._log.setLevel(this.level, false); // Setting flatten to true will result in stringified output this.flatten = flatten; this.stackTracesEnabled = stackTraces; var loggers = {}; var _logMgr = this; _logMgr._log.info('Creating Log Manager'); /** * Logger getter function to be used to retrieve all loggers in the Kandy SDK * @method getLogger * @param {string} name, The name of the logger to be created/retrieved * @returns {Logger} */ this.getLogger = function getLogger(name) { var logger; if (loggers[name]) { logger = loggers[name]; } else { logger = new Logger(name); loggers[logger.getName()] = logger; } return logger; }; /** * Log handler to compose a log message and determine the appropriate console logging function to * print log entry * @method logHandler * @param {string} name Name of the logger. * @param {LogItem} logItem */ this.logHandler = function logHandler(name, logItem) { var _logMgr$_log, _logMgr$_log2, _logMgr$_log3, _logMgr$_log4, _logMgr$_log5, _logMgr$_log6; var msg = parseLogMessage(name, logItem); if (logLevels[logItem.level] >= _logMgr.level) { switch (logLevels[logItem.level]) { case logLevels.TRACE: (_logMgr$_log = _logMgr._log).trace.apply(_logMgr$_log, [msg].concat((0, _toConsumableArray3.default)(logItem.args))); break; case logLevels.DEBUG: (_logMgr$_log2 = _logMgr._log).debug.apply(_logMgr$_log2, [msg].concat((0, _toConsumableArray3.default)(logItem.args))); break; case logLevels.INFO: (_logMgr$_log3 = _logMgr._log).info.apply(_logMgr$_log3, [msg].concat((0, _toConsumableArray3.default)(logItem.args))); break; case logLevels.WARN: (_logMgr$_log4 = _logMgr._log).warn.apply(_logMgr$_log4, [msg].concat((0, _toConsumableArray3.default)(logItem.args))); break; case logLevels.ERROR: (_logMgr$_log5 = _logMgr._log).error.apply(_logMgr$_log5, [msg].concat((0, _toConsumableArray3.default)(logItem.args))); break; case logLevels.SILENT: /* TODO we should implement a secondary logging mechanism, which would save the logs on a private server this secondary mechanism would also include messages that were created while logging level was set to SILENT */ break; default: (_logMgr$_log6 = _logMgr._log).info.apply(_logMgr$_log6, [msg].concat((0, _toConsumableArray3.default)(logItem.args))); break; } } else { /* Log level is not sufficiently Low to allow message to be visible */ } }; /** * Creates a new logger which can be identified by name for subsequent retrieval * * @param name * @constructor */ function Logger(name) { var _this = this; this.name = name; /** * Logger name getter function * * @returns {string} name - The name of the logger */ this.getName = function () { return _this.name; }; /** * Log function to instantiate a log item and send to handler * for processing * * @param {string} level - The log function level which was used to create the log message * @param {string} message - The unparsed log message * @param {*} args - The arguments provided along the message */ function log(level, message, args) { var logItem = new LogItem(level, message, args, isTraceEnabled()); if (_logMgr) { _logMgr.logHandler(name, logItem); } } this.error = function (msg) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return log('ERROR', msg, args); }; this.warn = function (msg) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } return log('WARN', msg, args); }; this.info = function (msg) { for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } return log('INFO', msg, args); }; this.debug = function (msg) { for (var _len4 = arguments.length, args = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { args[_key4 - 1] = arguments[_key4]; } return log('DEBUG', msg, args); }; this.trace = function (msg) { for (var _len5 = arguments.length, args = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { args[_key5 - 1] = arguments[_key5]; } return log('TRACE', msg, args); }; // Treat `logger.log` as a special case for now. Pass it straight through // to the logger (without parsing/formatting). Prevents logs that aren't // setup to work with the logger from being double-formatted (eg. FCS). // TODO: Remove `logger.log` when FCS logs work well with this log manager. this.log = function (msg) { var _logMgr$_log7; for (var _len6 = arguments.length, args = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { args[_key6 - 1] = arguments[_key6]; } (_logMgr$_log7 = _logMgr._log).log.apply(_logMgr$_log7, [msg].concat(args)); }; /** * Handle group-related console functions * * @param data */ this.group = function (data) { window.console.group(data); }; this.groupCollapsed = function (data) { window.console.groupCollapsed(data); }; this.groupEnd = function () { window.console.groupEnd(); }; } /** * Update the configuration of the log manager after it has been instantiated * * This is necessary as the log manager needs to be created prior to initializing each * of the plugins in Kandy. * @method updateManager * @param {Object} [options] * @param {string} [options.logLevel] - the logging level, as per options found in logManager.levels * @param {Boolean} [options.flatten] * @param {Boolean} [options.stackTraces] */ this.updateManager = function (_ref2) { var logLevel = _ref2.logLevel, flatten = _ref2.flatten, stackTraces = _ref2.stackTraces; // Update the manager's options _if_ they were provided. _logMgr.level = logLevel ? logLevels[logLevel.toUpperCase()] : _logMgr.level; _logMgr._log.setLevel(_this2.level, false); _logMgr.flatten = flatten || _logMgr.flatten; _logMgr.stackTracesEnabled = stackTraces || _logMgr.stackTracesEnabled; }; /** * Getter to return the current level set in the log manager * @method getLevel * @returns {string} */ this.getLevel = function () { return _logMgr.level; }; /** * Helper function to check if stack traces are enabled * * @returns {boolean} */ function isTraceEnabled() { return _logMgr.stackTracesEnabled; } /** * Helper function to check if verbose mode is enabled * * @returns {boolean} */ function isVerboseEnabled() { return _logMgr.flatten; } /** * Determines type of log entry being recorded and composes an appropriate message * * @param {string} name - The name of the logger for which this message is being parsed * @param {Object} logItem - The log entry * @returns {string} logMessage - The fully composed log message */ function parseLogMessage(name, logItem) { var logMessage = void 0; switch (name) { case 'ACTION': logMessage = parseActionMessage(name, logItem); break; case 'GENERAL': logMessage = parseMessage(name, logItem); break; default: logMessage = parseMessage(name, logItem); break; } return logMessage; } /** * Determines the specific type of action if the log entry is of messageTypes.ACTION * * @param actionArgs * @param message * @returns {*} */ function getActionType(actionArgs, message) { if (actionArgs.length > 0 && 'type' in actionArgs[0]) { return actionArgs[0].type; } return message.indexOf('prev') !== -1 ? 'PREV STATE' : 'NEXT STATE'; } /** * Parses a general purpose log message * * @param {string} name * @param {Object} logItem * @returns {string} */ function parseMessage(name, logItem) { if (typeof logItem !== 'undefined' && logItem.hasOwnProperty('message')) { if (isVerboseEnabled()) { // TODO Improve the stringification process to mitigate circular JSON errors return logItem.timestamp + ' - ' + name + ' - ' + logItem.level + ' - MESSAGE - ' + (0, _stringify2.default)(logItem.message) + ' - ARGS - ' + (0, _stringify2.default)(logItem.args); } return logItem.timestamp + ' - ' + name + ' - ' + logItem.level + ' - ' + logItem.message; } } /** * Parses log items containing actions and composes an informative log message * * @param name * @param logItem * @returns {string} */ function parseActionMessage(name, logItem) { var actionType = getActionType(logItem.args, logItem.message); if (isVerboseEnabled()) { return logItem.timestamp + ' - ' + name + ' - ' + logItem.level + ' - MESSAGE - ' + (0, _stringify2.default)(logItem.message) + ' - ARGS - ' + (0, _stringify2.default)(logItem.args); } return logItem.timestamp + ' - ' + name + ' - ' + logItem.level + ' - ' + actionType; } } /** * Base structure for a log entry * * @constructor * * @property {string} message - The visible message being displayed by the log entry, undefined at instantiation * @property {string} level - The logging level * @property {*} args - The arguments supplied with the log entry, if supplied * @property {string} timestamp - The time of the log entry * * @param level * @param msg * @param [args] * @param [stackTraces] * @returns {LogItem} */ function LogItem(level, msg, args) { var stackTraces = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; this.level = level; this.timestamp = Date.now(); this.message = msg; if (typeof args !== 'undefined' || stackTraces) { this.args = typeof args !== 'undefined' ? args : []; if (stackTraces) { // TODO Figure out the best location to make this call, as it needs to faithfully represent the origin of the // logging call this.args.push((0, _utils.stackTrace)()); } } else { delete this.args; } return this; } /***/ }), /***/ "./src/logs/transformers.js": /*!**********************************!*\ !*** ./src/logs/transformers.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = setupTransformers; /** * Determines which redux-logger transformers we need based on options. * @method setupTransformers * @param {Object} options * @return {Object} An object of transformers to be provided to redux-logger. */ function setupTransformers() { // A "pipeline" of all redux-logger action transformers. function actionPipeline(transformers) { return function (action) { transformers.forEach(function (transformer) { action = transformer(action); }); return action; }; } var transformers = {}; // Always include the passwordHider. var actionTransformers = [passwordHider]; // Create the actionTransformer pipeline with the included transformers. transformers.actionTransformer = actionPipeline(actionTransformers); return transformers; } // Redux-logger actionTransformer to prevent passwords from being logged. function passwordHider(action) { if (action.meta && action.meta.isSensitive) { // Only log the action name for actions that have sensitive data in them. return { type: action.type }; } return action; } /***/ }), /***/ "./src/logs/utils.js": /*!***************************!*\ !*** ./src/logs/utils.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stackTrace = stackTrace; exports.titleFormatter = titleFormatter; var _errorStackParser = __webpack_require__(/*! error-stack-parser */ "../../node_modules/error-stack-parser/error-stack-parser.js"); var ErrorStackParser = _interopRequireWildcard(_errorStackParser); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Utility function to perform a stack trace at any given point in the application * Removing the first 4 elements to make the first element of array represent * the point of origin where log function was called * * @returns {*} */ function stackTrace() { return ErrorStackParser.parse(new Error()); } /** * Standard title formatter function is almost identical to the defaultTitleFormatter found in redux-logger * but removes placeholder characters previously used for styling, which is not being used in Kandy's logging * configuration * * @param action * @param time * @param took * @returns {string} */ function titleFormatter(action, time, took) { var parts = ['action']; parts.push(action.type); parts.push('@ ' + time); parts.push('(in ' + took.toFixed(2) + ' ms)'); return parts.join(' '); } /***/ }), /***/ "./src/messaging/interface/actionTypes.js": /*!************************************************!*\ !*** ./src/messaging/interface/actionTypes.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PREFIX = '@@KANDY/'; var CREATE_CONVERSATION = exports.CREATE_CONVERSATION = PREFIX + 'CREATE_CONVERSATION'; var SEND_MESSAGE = exports.SEND_MESSAGE = PREFIX + 'SEND_MESSAGE'; var SEND_MESSAGE_FINISH = exports.SEND_MESSAGE_FINISH = PREFIX + 'SEND_MESSAGE_FINISH'; var SEND_MESSAGE_ERROR = exports.SEND_MESSAGE_ERROR = PREFIX + 'SEND_MESSAGE_ERROR'; var MESSAGE_RECEIVED = exports.MESSAGE_RECEIVED = PREFIX + 'MESSAGE_RECEIVED'; var INCOMING_MESSAGE_READ = exports.INCOMING_MESSAGE_READ = PREFIX + 'INCOMING_MESSAGE_READ'; var SEND_MESSAGE_READ = exports.SEND_MESSAGE_READ = PREFIX + 'SEND_MESSAGE_READ'; var SEND_MESSAGE_READ_FINISH = exports.SEND_MESSAGE_READ_FINISH = PREFIX + 'SEND_MESSAGE_READ_FINISH'; var CLEAR_MESSAGES = exports.CLEAR_MESSAGES = PREFIX + 'CLEAR_MESSAGES'; var CLEAR_MESSAGES_FINISH = exports.CLEAR_MESSAGES_FINISH = PREFIX + 'CLEAR_MESSAGES_FINISH'; var CREATE_GROUP_CONVERSATION = exports.CREATE_GROUP_CONVERSATION = PREFIX + 'CREATE_GROUP_CONVERSATION'; var CREATE_GROUP_CONVERSATION_FINISH = exports.CREATE_GROUP_CONVERSATION_FINISH = PREFIX + 'CREATE_GROUP_CONVERSATION_FINISH'; var SEND_GROUP_MESSAGE = exports.SEND_GROUP_MESSAGE = PREFIX + 'SEND_GROUP_MESSAGE'; var SEND_GROUP_MESSAGE_FINISH = exports.SEND_GROUP_MESSAGE_FINISH = PREFIX + 'SEND_GROUP_MESSAGE_FINISH'; var GROUP_MESSAGE_RECEIVED = exports.GROUP_MESSAGE_RECEIVED = PREFIX + 'GROUP_MESSAGE_RECEIVED'; var REMOVE_GROUP_MEMBERS = exports.REMOVE_GROUP_MEMBERS = PREFIX + 'REMOVE_GROUP_MEMBERS'; var REMOVE_GROUP_MEMBERS_FINISH = exports.REMOVE_GROUP_MEMBERS_FINISH = PREFIX + 'REMOVE_GROUP_MEMBERS_FINISH'; var ADD_GROUP_MEMBERS = exports.ADD_GROUP_MEMBERS = PREFIX + 'ADD_GROUP_MEMBERS'; var ADD_GROUP_MEMBERS_FINISH = exports.ADD_GROUP_MEMBERS_FINISH = PREFIX + 'ADD_GROUP_MEMBERS_FINISH'; var FETCH_CONVERSATIONS = exports.FETCH_CONVERSATIONS = PREFIX + 'FETCH_CONVERSATIONS'; var FETCH_CONVERSATIONS_FINISHED = exports.FETCH_CONVERSATIONS_FINISHED = PREFIX + 'FETCH_CONVERSATIONS_FINISHED'; var FETCH_MESSAGES = exports.FETCH_MESSAGES = PREFIX + 'FETCH_MESSAGES'; var FETCH_MESSAGES_FINISHED = exports.FETCH_MESSAGES_FINISHED = PREFIX + 'FETCH_MESSAGES_FINISHED'; /***/ }), /***/ "./src/messaging/interface/actions/conversations.js": /*!**********************************************************!*\ !*** ./src/messaging/interface/actions/conversations.js ***! \**********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = __webpack_require__(/*! babel-runtime/helpers/defineProperty */ "../../node_modules/babel-runtime/helpers/defineProperty.js"); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); exports.createConversation = createConversation; exports.createGroupConversation = createGroupConversation; exports.createGroupConversationFinish = createGroupConversationFinish; exports.fetchConversations = fetchConversations; exports.fetchConversationsFinished = fetchConversationsFinished; var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/messaging/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Conversation actions. * Actions relating to the creation/management of conversation objects. */ /** * Creates a create conversation action. Triggered when the user creates a new conversation object. * * @method createConversation * @param {string} user The User that this conversation is with. * @param {Object} options The options object can contain any keys an app may want passed along into the conversation object in the store. * @returns {Object} A flux standard action representing the create conversation action. */ function createConversation(user, options) { return { type: actionTypes.CREATE_CONVERSATION, payload: (0, _defineProperty3.default)({}, user, (0, _extends3.default)({ messages: [] }, options)) }; } /** * Creates a create group conversation action. Triggered when the user creates a new group conversation object. * * @method createGroupConversation * @param {string} name The name of the group * @param {Object} options - Optional object * @param {Object} options.image - An image to represent the group. * @param {Array} options.members - An array containing a list of full user names as strings. * @param {Function} resolve A promise resolve function to be used by the middleware. * @returns {Object} A flux standard action representing the create group conversation action. */ function createGroupConversation(name, options, resolve) { return { type: actionTypes.CREATE_GROUP_CONVERSATION, payload: { name: name, options: options, resolve: resolve } }; } /** * Creates a create group conversation finish action. Triggered when the group create call to the server has been resolved. * * @method createGroupConversationFinish * @param {Object} $0 * @param {string} $0.groupInfo The groups info, coming from the server. * @param {Object} $0.error A Kandy Error object. * @returns {Object} A flux standard action representing the create group conversation finish action. */ function createGroupConversationFinish(_ref) { var groupInfo = _ref.groupInfo, error = _ref.error; return { type: actionTypes.CREATE_GROUP_CONVERSATION_FINISH, payload: error || { groupInfo: groupInfo }, error: !!error }; } /** * Creates a fetch conversations action. This is dispatched by the API directly. * @method fetchConversations * @returns {Object} A flux standard action representing the fetch conversations action. */ function fetchConversations() { return { type: actionTypes.FETCH_CONVERSATIONS }; } /** * Creates a fetch conversations finished action. * @method fetchConversationsFinished * @param {Object} $0 * @param {Object} $0.error An error object, only included if fetchConversations implementation had an error. * @param {Array} $0.conversations An array of messaging conversations. * @returns {Object} A flux standard action representing the fetch conversations finished action. */ function fetchConversationsFinished(_ref2) { var error = _ref2.error, conversations = _ref2.conversations; return { type: actionTypes.FETCH_CONVERSATIONS_FINISHED, payload: error || { conversations: conversations }, error: !!error }; } /***/ }), /***/ "./src/messaging/interface/actions/groups.js": /*!***************************************************!*\ !*** ./src/messaging/interface/actions/groups.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.removeGroupMembersFinish = exports.removeGroupMembers = exports.addGroupMembersFinish = exports.addGroupMembers = undefined; var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/messaging/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Action helper functions. */ function groupMembersHelper(actionType, groupId, members) { return { type: actionType, payload: { groupId: groupId, members: members } }; } function groupMembersFinishHelper(actionType, groupId, members, error) { return { type: actionType, payload: error || { groupId: groupId, members: members }, error: !!error }; } /** * Group actions. * Actions about managing groups / group conversations. */ /** * Creates an add group members action. Used to send an add group members request to the server. * * @method addGroupMembers * @param {string} groupId The unique id of the group. * @param {Array} members An array containing strings representing full user id's of the users to be added. * @returns {Object} A flux standard action representing an add group members action. */ var addGroupMembers = exports.addGroupMembers = function addGroupMembers(groupId, members) { return groupMembersHelper(actionTypes.ADD_GROUP_MEMBERS, groupId, members); }; /** * Creates an add group members finish action. Triggered on a server response when attempting to add group members. * * @method addGroupMembersFinish * @param {Object} $0 * @param {string} $0.groupId The unique id of the group. * @param {Array} $0.members An array containing strings representing full user id's of the users to be added. * @param {Object} $0.error A Kandy Error object. * @returns {Object} A flux standard action representing a add group members finish action. */ var addGroupMembersFinish = exports.addGroupMembersFinish = function addGroupMembersFinish(_ref) { var groupId = _ref.groupId, members = _ref.members, error = _ref.error; return groupMembersFinishHelper(actionTypes.ADD_GROUP_MEMBERS_FINISH, groupId, members, error); }; /** * Creates a remove group members action. Used to send a remove group members request to the server. * * @method removeGroupMembers * @param {string} groupId The unique id of the group. * @param {Array} members An array containing strings representing full user id's of the users to be removed. * @returns {Object} A flux standard action representing a remove group members action. */ var removeGroupMembers = exports.removeGroupMembers = function removeGroupMembers(groupId, members) { return groupMembersHelper(actionTypes.REMOVE_GROUP_MEMBERS, groupId, members); }; /** * Creates a remove group members finish action. Triggered on a server response when attempting to remove group members. * * @method removeGroupMembersFinish * @param {Object} $0 * @param {string} $0.groupId The unique id of the group. * @param {Array} $0.members An array containing strings representing full user id's of the users to be removed. * @param {Object} $0.error A Kandy Error object. * @returns {Object} A flux standard action representing a remove group members finish action. */ var removeGroupMembersFinish = exports.removeGroupMembersFinish = function removeGroupMembersFinish(_ref2) { var groupId = _ref2.groupId, members = _ref2.members, error = _ref2.error; return groupMembersFinishHelper(actionTypes.REMOVE_GROUP_MEMBERS_FINISH, groupId, members, error); }; /***/ }), /***/ "./src/messaging/interface/actions/index.js": /*!**************************************************!*\ !*** ./src/messaging/interface/actions/index.js ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.groupActions = exports.convoActions = exports.messageActions = undefined; var _messages = __webpack_require__(/*! ./messages */ "./src/messaging/interface/actions/messages.js"); var messageActionsImport = _interopRequireWildcard(_messages); var _conversations = __webpack_require__(/*! ./conversations */ "./src/messaging/interface/actions/conversations.js"); var convoActionsImport = _interopRequireWildcard(_conversations); var _groups = __webpack_require__(/*! ./groups */ "./src/messaging/interface/actions/groups.js"); var groupActionsImport = _interopRequireWildcard(_groups); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } // Apparently the following doesn't work: // export * as newName from './place'; // So import everything from each file, then re-export. /** * The messaging plugin's actions are organized into three types: * - message actions: those which act on message object, * - convo actions: those which act on conversation objects, * - group actions: those which manage groups. */ var messageActions = exports.messageActions = messageActionsImport; var convoActions = exports.convoActions = convoActionsImport; var groupActions = exports.groupActions = groupActionsImport; /***/ }), /***/ "./src/messaging/interface/actions/messages.js": /*!*****************************************************!*\ !*** ./src/messaging/interface/actions/messages.js ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sendMessageRead = exports.incomingMessageRead = exports.sendGroupMessageFinish = exports.sendGroupMessage = exports.sendMessageFinish = exports.sendMessage = undefined; exports.messageReceived = messageReceived; exports.groupMessageReceived = groupMessageReceived; exports.sendMessageReadFinish = sendMessageReadFinish; exports.fetchMessages = fetchMessages; exports.fetchMessagesFinished = fetchMessagesFinished; exports.clearMessages = clearMessages; var _actionTypes = __webpack_require__(/*! ../actionTypes */ "./src/messaging/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Action helper functions. */ function sendMessageHelper(actionType, participant, parts, timestamp, type) { return { type: actionType, payload: { participant: participant, message: { timestamp: timestamp, isPending: true, read: false, parts: parts, type: type } } }; } function sendMessageFinishHelper(actionType, sender, participant, parts, timestamp, messageId, error) { return { type: actionType, payload: { sender: sender, participant: participant, parts: parts, timestamp: timestamp, messageId: messageId, error: error }, error: !!error }; } function messageReadHelper(actionType, messageId, participant) { return { type: actionType, payload: { messageId: messageId, participant: participant } }; } /** * Message actions. * Actions about the CRUD of message objects. */ /** * Creates a send message action. Triggered when the user initiates the send message process. * * @method sendMessage * @param {string} participant The user who the conversation is with. * @param {Array} parts The message parts, as a formatted object. * @param {number} timestamp A timestamp for the sent message. * @param {string} type Type of message. 'im' or 'sms'. * @returns {Object} A flux standard action representing the send message action. */ var sendMessage = exports.sendMessage = function sendMessage(participant, parts, timestamp, type) { return sendMessageHelper(actionTypes.SEND_MESSAGE, participant, parts, timestamp, type); }; /** * Creates a send message finished action. Trigged when a message send function has received a success response. * * @method sendMessageFinish * @param {Object} $0 * @param {string} $0.sender The sender of the outgoing message. * @param {string} $0.participant Who the message went to. * @param {Array} $0.parts The message parts. * @param {number} $0.timestamp A timestamp for the sent message. * @param {string} $0.messageId The returned messageId of the message that has been sent. * @param {Object} $0.error A kandy error object * @returns {Object} A flux standard action representing the send message finished action. */ var sendMessageFinish = exports.sendMessageFinish = function sendMessageFinish(_ref) { var sender = _ref.sender, participant = _ref.participant, parts = _ref.parts, timestamp = _ref.timestamp, messageId = _ref.messageId, error = _ref.error; return sendMessageFinishHelper(actionTypes.SEND_MESSAGE_FINISH, sender, participant, parts, timestamp, messageId, error); }; /** * Creates a send group message action. Triggered when the user initiates the send message process. * * @method sendGroupMessage * @param {string} participant The group who the conversation is with. * @param {Array} parts The message parts, as a formatted object. * @param {number} timestamp A timestamp for the sent message. * @returns {Object} A flux standard action representing the send message action. */ var sendGroupMessage = exports.sendGroupMessage = function sendGroupMessage(participant, parts, timestamp, type) { return sendMessageHelper(actionTypes.SEND_GROUP_MESSAGE, participant, parts, timestamp, type); }; /** * Creates a send group message finished action. Trigged when a message send function has received a success response. * * @method sendGroupMessageFinish * @param {Object} params * @param {string} params.sender The sender of the outgoing message. * @param {string} params.participant The group the message went to. * @param {Array} params.parts The message parts. * @param {number} params.timestamp A timestamp for the sent message. * @param {string} params.messageId The returned messageId of the message that has been sent. * @param {Object} params.error A kandy error object * @returns {Object} A flux standard action representing the send message finished action. */ var sendGroupMessageFinish = exports.sendGroupMessageFinish = function sendGroupMessageFinish(_ref2) { var sender = _ref2.sender, participant = _ref2.participant, parts = _ref2.parts, timestamp = _ref2.timestamp, messageId = _ref2.messageId, error = _ref2.error; return sendMessageFinishHelper(actionTypes.SEND_GROUP_MESSAGE_FINISH, sender, participant, parts, timestamp, messageId, error); }; /** * Creates a message received action. Triggered when the kandy websocket receives a chat message. * * @method messageReceived * @param {Array} parts The message parts. * @param {string} messageId The messageId of the message that has been received. * @param {string} sender The user who sent the message. This is the user who the conversation is with. * @param {number} timestamp A timestamp for the sent message. * @param {Object} meta - A meta object. * @param {boolean} meta.newConversation - A boolean value indicating whether the message corresponds to a conversation not yet in the store. * @returns {Object} A flux standard action representing the message received action. */ function messageReceived(parts, messageId, sender, timestamp, meta) { return { type: actionTypes.MESSAGE_RECEIVED, meta: { newConversation: meta ? meta.newConversation : false }, payload: { participant: sender, message: { timestamp: timestamp, isPending: false, read: false, parts: parts, sender: sender, messageId: messageId } } }; } /** * Creates a group messaged received action. Triggered when the app gets a group message notification over the websocket. * * @method groupMessageReceived * @param {string} groupId The group's unique id. * @param {Array} parts The parts of the incoming message. * @param {string} messageId The message's unique id. * @param {string} sender The sender of the group message (full username). * @param {number} timestamp A timestamp for the message. * @returns {Object} A flux standard action representing a group message received action. */ function groupMessageReceived(groupId, parts, messageId, sender, timestamp) { return { type: actionTypes.GROUP_MESSAGE_RECEIVED, payload: { groupId: groupId, message: { parts: parts, messageId: messageId, sender: sender, timestamp: timestamp } } }; } /** * Creates an incoming message read action. This triggers when we receive a "Message Read" notification over the websocket. * * @method incomingMessageRead * @param {string} messageId The unique id of the message being marked as read. * @param {string} participant The other pariticipant of the conversation. * @returns {Object} A flux standard action representing the incoming message read action. */ var incomingMessageRead = exports.incomingMessageRead = function incomingMessageRead(messageId, participant) { return messageReadHelper(actionTypes.INCOMING_MESSAGE_READ, messageId, participant); }; /** * Creates a send message read action. This should send a "mark message as read" request to the server. * * @method sendMessageRead * @param {string} messageId The unique id of the message being marked as read. * @param {string} participant The other pariticipant of the conversation. * @returns {Object} A flux standard action representing the send message read action. */ var sendMessageRead = exports.sendMessageRead = function sendMessageRead(messageId, participant) { return messageReadHelper(actionTypes.SEND_MESSAGE_READ, messageId, participant); }; /** * Creates a send message read finish action. This triggers on server response when attempting to mark a message read. * * @method sendMessageReadFinish * @param {Object} $0 * @param {string} $0.messageId The unique id of the message being marked as read. * @param {string} $0.participant The other pariticipant of the conversation. * @param {Object} $0.error A Kandy Error object. * @returns {Object} A flux standard action representing the send message read finish action. */ function sendMessageReadFinish(_ref3) { var messageId = _ref3.messageId, participant = _ref3.participant, error = _ref3.error; return { type: actionTypes.SEND_MESSAGE_READ_FINISH, payload: error || { messageId: messageId, participant: participant }, error: !!error }; } /** * Creates a fetch messages action. This is dispatched by the API directly. * @method fetchMessages * @param {string} id The id of the conversation / user that we want to fetch messages for. * @param {number} amount A number representing the amount of messages to fetch. * @returns {Object} A flux standard action representing the fetch messages action. */ function fetchMessages(id, amount) { return { type: actionTypes.FETCH_MESSAGES, payload: { id: id, amount: amount } }; } /** * Creates a fetch messages finished action. * @method fetchMessagesFinished * @param {Object} $0 * @param {string} $0.id The id of the conversation / user that we are fetching messages for. * @param {Array} $0.messages An array of formatted messages to put into the store. * @param {Object} $0.error An error object, only present if an error occured. * @returns {Object} A flux standard action representing the fetch messages finished action. */ function fetchMessagesFinished(_ref4) { var id = _ref4.id, messages = _ref4.messages, error = _ref4.error; return { type: actionTypes.FETCH_MESSAGES_FINISHED, payload: error || { id: id, messages: messages }, error: !!error }; } /** * Request to clear messages from a conversation's state. * @method clearMessages * @param {string} id The id of the conversation / user being acted upon. * @returns {Object} A flux standard action. */ function clearMessages(id) { return { type: actionTypes.CLEAR_MESSAGES, payload: id }; } /***/ }), /***/ "./src/messaging/interface/api.js": /*!****************************************!*\ !*** ./src/messaging/interface/api.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _promise = __webpack_require__(/*! babel-runtime/core-js/promise */ "../../node_modules/babel-runtime/core-js/promise.js"); var _promise2 = _interopRequireDefault(_promise); exports.default = api; var _actions = __webpack_require__(/*! ./actions */ "./src/messaging/interface/actions/index.js"); var _selectors = __webpack_require__(/*! ./selectors */ "./src/messaging/interface/selectors.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * * Kandy's Messaging features revolve around a "conversation" structure. Kandy stores the conversations * and its messages, and returns conversation objects when requested. * * See the "Conversation" and "Message" sections of the documentation for more details. * * Messaging functions are namespaced beneath 'conversation' on the returned Kandy object. Ex: kandy.conversation.get('id'). * * @public * @module Messaging */ function api(context) { var messagingApi = { /** * Attempts to retrieve a list of conversations that the current user is a part of. * These conversations can then be retrieved from the store using get(). * * @public * @memberof Messaging * @requires fetchConversations * @method fetch */ fetch: function fetch() { context.dispatch(_actions.convoActions.fetchConversations()); }, /** * Create and return a conversation object. If successfull, the event 'conversations:change' will be emitted. * If a conversation with the given user already exists in the store, then no new one will be created. * If no conversation exists, then a new conversation will be created in the store. * * @public * @memberof Messaging * @requires onlyInternalMessaging * @method get * @param {string} userId The Id of user for whom to create the conversation. * @returns {Conversation} A Conversation object. */ /** * Create and return a conversation object. If successfull, the event 'conversations:change' will be emitted. * If a conversation with the given user already exists in the store, then no new one will be created. * If no conversation exists, then a new conversation will be created in the store. * * @public * @memberof Messaging * @requires internalAndSmsMessaging * @method get * @param {string} userId The Id of user for whom to create the conversation. * @param {Object} [options] An options object for the conversation. * @param {string} [options.type = im] The type of conversation. Can be 'im' or 'sms'. * @returns {Conversation} A Conversation object. */ get: function get(userId) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { type: 'im' }; // TODO: Verify user input. `type` should only be 'im', 'sms', or 'group'. // TODO: Fire off a a `conversations:new` event here, so all instances of creating a convo in store fires the event. if (!(0, _selectors.getConversations)(context.getState())[userId]) { context.dispatch(_actions.convoActions.createConversation(userId, options)); } return context.primitives.Conversation({ destination: userId, type: options.type }); }, /** * Returns a promise that resolves when the serverside group conversation * has been successfully created. * @public * @memberof Messaging * @requires groupMessaging * @method createGroup * @param {string} name - A name for the group conversation. * @param {Object} [options] - Optional object * @param {Object} [options.image] - An image to represent the group. * @param {Array} [options.members] - An array containing a list of full user names as strings. * @returns {Promise} A promise object. */ createGroup: function createGroup(name, options) { return new _promise2.default(function (resolve) { // Dispatch an action for the saga to attempt to create a groupConversation server side. context.dispatch(_actions.convoActions.createGroupConversation(name, options, resolve)); }).then(function (_ref) { var groupInfo = _ref.groupInfo, error = _ref.error; if (error) { return error; } else { return context.primitives.GroupConversation({ destination: groupInfo.groupId }); } }); } }; return { conversation: messagingApi }; } /***/ }), /***/ "./src/messaging/interface/eventTypes.js": /*!***********************************************!*\ !*** ./src/messaging/interface/eventTypes.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A change has occured in the conversation list. * * @public * @memberof Messaging * @event conversations:change * @param {Object} params * @param {Array} params.conversationIds The IDs/participants of the conversations affected. */ var CONVERSATIONS_CHANGE = exports.CONVERSATIONS_CHANGE = 'conversations:change'; /** * A change has occured in a specific conversations message list. * If a single message was affected/created, `messageId` will be present * as part of the event argument. * * @public * @memberof Messaging * @event messages:change * @param {Object} params * @param {string} params.conversationId The ID/participant of the conversation that has changes in its message list. * @param {string} params.messageId The ID of the message affected. */ var MESSAGES_CHANGE = exports.MESSAGES_CHANGE = 'messages:change'; /** * An error occured with messaging. * * @public * @memberof Messaging * @event messages:error * @param {Object} params * @param {KandyError} params.error The Kandy error object. */ var MESSAGING_ERROR = exports.MESSAGING_ERROR = 'messaging:error'; /***/ }), /***/ "./src/messaging/interface/events.js": /*!*******************************************!*\ !*** ./src/messaging/interface/events.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _keys = __webpack_require__(/*! babel-runtime/core-js/object/keys */ "../../node_modules/babel-runtime/core-js/object/keys.js"); var _keys2 = _interopRequireDefault(_keys); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/messaging/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/messaging/interface/eventTypes.js"); var eventTypes = _interopRequireWildcard(_eventTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var eventsMap = {}; eventsMap[actionTypes.SEND_MESSAGE_FINISH] = function (action) { return [{ type: eventTypes.MESSAGES_CHANGE, args: { conversationId: action.payload.participant, messageId: action.payload.messageId } }]; }; eventsMap[actionTypes.MESSAGE_RECEIVED] = function (action) { var meta = action.meta, payload = action.payload; if (meta.newConversation) { return { type: eventTypes.CONVERSATIONS_CHANGE, args: { // TODO: Remove `conversationId` at some point. // It is deprecated; replaced by `conversationIds`. conversationId: payload.participant, conversationIds: [payload.participant] } }; } return [{ type: eventTypes.MESSAGES_CHANGE, args: { conversationId: payload.participant, messageId: payload.message.messageId } }]; }; eventsMap[actionTypes.SEND_GROUP_MESSAGE_FINISH] = function (_ref) { var messageId = _ref.messageId, groupId = _ref.payload.groupId; return messageId && [{ type: eventTypes.MESSAGES_CHANGE, args: { conversationId: groupId, messageId: messageId } }]; }; eventsMap[actionTypes.FETCH_CONVERSATIONS_FINISHED] = function (action) { if (action.error) { return { type: eventTypes.MESSAGING_ERROR, args: { error: action.payload } }; } else { return { type: eventTypes.CONVERSATIONS_CHANGE, args: { conversationIds: (0, _keys2.default)(action.payload.conversations) } }; } }; eventsMap[actionTypes.FETCH_MESSAGES_FINISHED] = function (action) { if (action.error) { return { type: eventTypes.MESSAGING_ERROR, args: { error: action.payload } }; } else { return { type: eventTypes.MESSAGES_CHANGE, args: { conversationId: action.payload.id, messageId: undefined } }; } }; function groupEventMapper(action) { if (action.error) { return { type: eventTypes.MESSAGING_ERROR, args: { error: action.payload } }; } } eventsMap[actionTypes.CREATE_GROUP_CONVERSATION_FINISH] = groupEventMapper; eventsMap[actionTypes.ADD_GROUP_MEMBERS_FINISH] = groupEventMapper; eventsMap[actionTypes.REMOVE_GROUP_MEMBERS_FINISH] = groupEventMapper; eventsMap[actionTypes.SEND_MESSAGE_READ_FINISH] = groupEventMapper; eventsMap[actionTypes.CLEAR_MESSAGES] = function (action) { return { type: eventTypes.MESSAGES_CHANGE, args: { conversationId: action.payload, messageId: undefined } }; }; exports.default = eventsMap; /***/ }), /***/ "./src/messaging/interface/index.js": /*!******************************************!*\ !*** ./src/messaging/interface/index.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _api = __webpack_require__(/*! ./api */ "./src/messaging/interface/api.js"); var _api2 = _interopRequireDefault(_api); var _reducers = __webpack_require__(/*! ./reducers */ "./src/messaging/interface/reducers.js"); var _reducers2 = _interopRequireDefault(_reducers); var _mixins = __webpack_require__(/*! ./mixins */ "./src/messaging/interface/mixins.js"); var _mixins2 = _interopRequireDefault(_mixins); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * This interface is for a messaging plugin. * @type {string} */ var name = 'messaging'; // Import the components of the interface. exports.default = { name: name, api: _api2.default, reducer: _reducers2.default, mixins: _mixins2.default }; /***/ }), /***/ "./src/messaging/interface/mixins.js": /*!*******************************************!*\ !*** ./src/messaging/interface/mixins.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _getPrototypeOf = __webpack_require__(/*! babel-runtime/core-js/object/get-prototype-of */ "../../node_modules/babel-runtime/core-js/object/get-prototype-of.js"); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _actions = __webpack_require__(/*! ./actions */ "./src/messaging/interface/actions/index.js"); var _selectors = __webpack_require__(/*! ./selectors */ "./src/messaging/interface/selectors.js"); var _compose = __webpack_require__(/*! stampit/compose */ "../../node_modules/stampit/compose.js"); var _compose2 = _interopRequireDefault(_compose); var _actions2 = __webpack_require__(/*! ../../events/interface/actions */ "./src/events/interface/actions.js"); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/messaging/interface/eventTypes.js"); var _logs = __webpack_require__(/*! ../../logs */ "./src/logs/index.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var log = (0, _logs.getLogManager)().getLogger('MESSAGING'); /** * Base conversation stamp * @param {string} destination - The identifier of the conversation. Either a username or groupId. */ // Events /** * A Conversation object represents a conversation between either two users, or a * user and a group. A Conversation can spawn messages via the conversations * createMessage() function. * @public * @module Conversation * @type {Object} */ /** * A Message object represents an inidividual message. Messages in Kandy have parts * which represent pieces of a message, such as a text part or a file part. Once * all the desired parts have been added, a message can be sent with the send() * function. * @public * @module Message * @type {Object} */ var conversationBase = { initializers: [function (_ref) { var destination = _ref.destination, _ref$type = _ref.type, type = _ref$type === undefined ? 'im' : _ref$type; this.destination = destination; this.type = type; if (!this.isGroup) { var features = (0, _selectors.getMessagingConfig)(this.context.getState()).features; var groupIndex = features.indexOf('group'); if (groupIndex > -1) { features.splice(groupIndex, 1); } this.features = features; } }], methods: { /** * Create and return a message object. You must specify the part. If this is a simple text message, provide a `text` part as demonstrated in the example. * * @public * @memberof Conversation * @requires richMessaging * @constructs Message * @param {Object} part The part to add to the message. * @param {string} part.type The type of part. Can be "text", "json", "file", or "location". * @param {string} [part.text] The text of the part. Must be a part of type "text". * @param {Object} [part.json] The json of the part. Must be a part of type "json". * @param {File} [part.file] The file of the part. Must be a part of type "file". * @param {Object} [part.location] The location of the part. Must be a part of type "location". * @param {number} [part.location.longitude] The longitude of the location. * @param {number} [part.location.latitude] The latitude of the location. * @returns {Message} The newly created Message object. * * @example * conversation.createMessage({type: 'text', text: 'This is the message'}); */ /** * Create and return a message object. You must specify the part. If this is a simple text message, provide a `text` part as demonstrated in the example. * * @public * @memberof Conversation * @requires richMessagingWithoutLocation * @constructs Message * @param {Object} part The part to add to the message. * @param {string} part.type The type of part. Can be "text", "json", "file". * @param {string} [part.text] The text of the part. Must be a part of type "text". * @param {Object} [part.json] The json of the part. Must be a part of type "json". * @param {File} [part.file] The file of the part. Must be a part of type "file". * @returns {Message} The newly created Message object. * * @example * conversation.createMessage({type: 'text', text: 'This is the message'}); */ /** * Create and return a message object. You must provide a `text` part as demonstrated in the example. * * @public * @memberof Conversation * @requires simpleMessagingOnly * @param {Object} part The part to add to the message. * @param {string} part.type The type of part. Must be "text". * @param {string} part.text The text of the part. Must be a part of type "text". * @returns {Message} The newly created Message object. * * @example * conversation.createMessage({type: 'text', text: 'This is the message'}); */ createMessage: function createMessage(part) { var messageContext = { features: this.features, isGroup: this.isGroup }; return this.context.primitives.Message({ destination: this.destination, part: part, context: messageContext, type: this.type }); }, /** * Clears all messages in this conversation from local state. * @public * @memberof Conversation * @method clearMessages */ clearMessages: function clearMessages() { this.context.dispatch(_actions.messageActions.clearMessages(this.destination)); }, /** * Get the messages associated with this conversation. * * @public * @memberof Conversation * @returns {Object[]} messages An array containing the conversation's messages. * @returns {Function} messages.markRead Marks the message as read. * @returns {Function} messages.forward Forward the message to another user. * @returns {string} messages.messageId The Id of the message. * @returns {string} messages.sender The user Id of the user who sent the message. * @returns {number} messages.timestamp The time at which the message was sent. * @returns {boolean} messages.read Whether the message has been marked as read. * @returns {boolean} messages.isPending Whether the message has finished being sent to the server. * @returns {Object[]} messages.parts The parts of the message. */ getMessages: function getMessages() { var _this = this; var convo = (0, _selectors.getConversations)(this.context.getState())[this.destination]; return convo.messages.map(function (message) { message.forward = function (participant) { _this.context.dispatch(_actions.messageActions.sendMessage(participant, message.parts, Date.now())); }; // Only allow the end user to markRead on message that were incoming. if (message.sender === _this.destination) { message.markRead = function () { _this.context.dispatch(_actions.messageActions.sendMessageRead(message.messageId, _this.destination)); }; } return message; }); }, /** * Get a specific message from this conversation. * @public * @method getMessage * @memberof Conversation * @param {string} messageId ID of the message to retrieve. * @return {Message} A message object. */ getMessage: function getMessage(messageId) { var _this2 = this; var convo = (0, _selectors.getConversations)(this.context.getState())[this.destination]; var message = (0, _fp.find)(function (message) { return message.messageId === messageId; })(convo.messages); if (!message) { log.debug('Message (' + messageId + ') not found in conversation (' + this.destination + ').'); return; } // TODO: Have a helper that "augments" messages. // "Augment" the message like we do in `getMessages`. message.forward = function (participant) { _this2.context.dispatch(_actions.messageActions.sendMessage(participant, message.parts, Date.now())); }; // Only allow the end user to markRead on message that were incoming. if (message.sender === this.destination) { message.markRead = function () { _this2.context.dispatch(_actions.messageActions.sendMessageRead(message.messageId, _this2.destination)); }; } return message; }, /** * Subscribe to this conversations messages array. * * @public * @memberof Conversation * @param {Function} subscriber A subscriber function to be triggered when the messages array of this conversation is updated. * @param {string} subscriber.conversationId The conversation participant. * @param {string} subscriber.messageId The ID of the message that caused the event. * @return {Function} The unsubscribe function. */ subscribe: function subscribe(subscriber) { var _this3 = this; if (subscriber) { // Create a subscriber wrapper to properly determine if this messages:change event is relevant to this convo var subscriberWrapper = function subscriberWrapper(_ref2) { var conversationId = _ref2.conversationId, messageId = _ref2.messageId; if (conversationId === _this3.destination) { subscriber({ conversationId: conversationId, messageId: messageId }); } }; // Subscribe to the messages:change event with the wrapped subscriber this.context.api.on('messages:change', subscriberWrapper); // Return the unsubscribe function return function () { _this3.context.api.off('messages:change', subscriberWrapper); }; } } } /* * Conversation history stamp. Handles any functions that retrieve history from the server concerning conversations. */ };var conversationHistory = { initializers: [function () { var features = (0, _selectors.getMessagingConfig)(this.context.getState()).features; if (!(0, _fp.includes)('history', features)) { var prototype = (0, _getPrototypeOf2.default)(this); delete prototype.fetchMessages; } return this; }], methods: { /** * Allows the user to fetch messages associated with a specific conversation from the server. * When the operation is complete, a NEW_MESSAGE event will be emitted. * Messages can then be retrieved using getMessages. * * @public * @memberof Conversation * @method fetchMessages * @param {number} [amount=50] An amount of messages to fetch. */ fetchMessages: function fetchMessages() { var amount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; this.context.dispatch(_actions.messageActions.fetchMessages(this.destination, amount)); } } /* * Group conversation stamp * @param {string} destination The identifier of the conversation. Either a username or groupId. * @param {Uri} image An image for the group. */ };var groupConversation = { initializers: [function () { // TODO: Determine how this initializer interacts with the base messaging initializer. Order matters. Why does features contain group at this point? this.isGroup = true; this.features = (0, _selectors.getMessagingConfig)(this.context.getState()).features; if (this.features.indexOf('group') === -1) { this.context.dispatch((0, _actions2.emitEvent)(_eventTypes.MESSAGING_ERROR, { error: 'This build of Kandy does not support group messaging.' })); } }], methods: { /** * Remove an array of members from a group. * @memberof Conversation * @requires groupMessaging * @method removeMembers * @param {Array} members An array containing full user IDs of users to remove from a group. */ removeMembers: function removeMembers(members) { this.context.dispatch(_actions.groupActions.removeGroupMembers(this.destination, members)); }, /** * Remove an array of members from a group. * @memberof Conversation * @requires groupMessaging * @method addMembers * @param {Array} members An array containing full user IDs of users to add to a group. */ addMembers: function addMembers(members) { this.context.dispatch(_actions.groupActions.addGroupMembers(this.destination, members)); } } /* * base Message stamp * @param {string} destination - The full user Id of the message participant or the groupId. * @param {Object} part - Initial part to the message. * @param {Object} context - Information and capabilities for how the message will act with regard to the conversation. * @param {Array} context.features - List of features the conversation supports. * @param {Function} context.send - Function for sending the message. * @param {string} type=im - The type of the message */ };var messageBase = { initializers: [function (_ref3) { var destination = _ref3.destination, part = _ref3.part, context = _ref3.context, _ref3$type = _ref3.type, type = _ref3$type === undefined ? 'im' : _ref3$type; this.destination = destination; this.convoContext = context; this.type = type; if (typeof part === 'string') { part = { type: 'text', text: part }; } this.parts = [part]; }], methods: { /** * Sends the message. * * @public * @method send * @memberof Message */ send: function send() { if (this.convoContext.isGroup) { this.context.dispatch(_actions.messageActions.sendGroupMessage(this.destination, this.parts, Date.now(), this.type)); } else { this.context.dispatch(_actions.messageActions.sendMessage(this.destination, this.parts, Date.now(), this.type)); } } } /** * stamp to add message parts capabilities to a Message primitive * @name withParts * @param {Object} context - Information and capabilities for how the message will act with regard to the conversation. * @param {Array} context.features - List of features the conversation supports. */ };var withParts = { initializers: [function (_ref4) { var _ref4$context$feature = _ref4.context.features, features = _ref4$context$feature === undefined ? [] : _ref4$context$feature; if (!(0, _fp.includes)('parts', features)) { var prototype = (0, _getPrototypeOf2.default)(this); delete prototype.addPart; } return this; }], methods: { /** * Add an additional part to a message. * * @public * @memberof Message * @requires richMessaging * @memberof withParts * @param {Object} part The part to add to the message. * @param {string} part.type The type of part. Can be "text", "json", "file", or "location". * @param {string} [part.text] The text of the part. Must be a part of type "text". * @param {Object} [part.json] The json of the part. Must be a part of type "json". * @param {File} [part.file] The file of the part. Must be a part of type "file". * @param {Object} [part.location] The location of the part. Must be a part of type "location". * @param {number} [part.location.longitude] The longitude of the location. * @param {number} [part.location.latitude] The latitude of the location. */ /** * Add an additional part to a message. * * @public * @memberof Message * @requires richMessagingWithoutLocation * @param {Object} part The part to add to the message. * @param {string} part.type The type of part. Can be "text", "json", "file", or "location". * @param {string} [part.text] The text of the part. Must be a part of type "text". * @param {Object} [part.json] The json of the part. Must be a part of type "json". * @param {File} [part.file] The file of the part. Must be a part of type "file". */ addPart: function addPart(part) { // Validate the part. If not valid, returns an error. var validationResponse = validatePart(part, this.convoContext.features); if (validationResponse instanceof Error) { this.context.dispatch((0, _actions2.emitEvent)(_eventTypes.MESSAGING_ERROR, { error: validationResponse.message })); } this.parts.push(part); } } /* * A helper function to validate inputs. Will be progressively updated as we * allow for more and more input types. */ };var validatePart = function validatePart(part, features) { if (part.hasOwnProperty('type')) { if (part.hasOwnProperty(part.type)) { var validTypeFlag = false; switch (part.type) { case 'text': validTypeFlag = true; break; case 'file': validTypeFlag = features.indexOf('rich') !== -1; break; case 'location': validTypeFlag = features.indexOf('rich') !== -1; break; case 'json': validTypeFlag = features.indexOf('rich') !== -1; } return validTypeFlag || new Error('This build of kandy does not support parts of type ' + part.type); } else { return new Error('A message part must have a payload corresponding with its declared type'); } } else { return new Error('A message part must have a type. Options are: [text, file, location, json]'); } }; exports.default = { Conversation: (0, _compose2.default)(conversationBase, conversationHistory), GroupConversation: (0, _compose2.default)(groupConversation, conversationBase, conversationHistory), Message: (0, _compose2.default)(messageBase, withParts) }; /***/ }), /***/ "./src/messaging/interface/reducers.js": /*!*********************************************!*\ !*** ./src/messaging/interface/reducers.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = __webpack_require__(/*! babel-runtime/helpers/defineProperty */ "../../node_modules/babel-runtime/helpers/defineProperty.js"); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _toConsumableArray2 = __webpack_require__(/*! babel-runtime/helpers/toConsumableArray */ "../../node_modules/babel-runtime/helpers/toConsumableArray.js"); var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2); var _extends11 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends12 = _interopRequireDefault(_extends11); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/messaging/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var reducers = {}; reducers[actionTypes.CREATE_CONVERSATION] = { next: function next(state, action) { return (0, _extends12.default)({}, state, { conversations: (0, _extends12.default)({}, state.conversations, action.payload) }); } }; reducers[actionTypes.FETCH_CONVERSATIONS_FINISHED] = { next: function next(state, action) { var newState = (0, _fp.cloneDeep)(state); for (var newConvo in action.payload.conversations) { if (action.payload.conversations.hasOwnProperty(newConvo)) { if (!newState.conversations[newConvo]) { // The store doesn't have a convo for this user. Put it in. newState.conversations[newConvo] = action.payload.conversations[newConvo]; } } } return newState; } }; reducers[actionTypes.FETCH_MESSAGES_FINISHED] = { next: function next(state, action) { var newState = (0, _fp.cloneDeep)(state); var stateMessages = newState.conversations[action.payload.id].messages; var actionMessages = action.payload.messages; // Combine the messages from state with the new fetched messages, unique by messageId. // Note: If a duplicate messageId is found, the newly fetched message is kept. var combinedMessages = (0, _fp.unionBy)('messageId', actionMessages, stateMessages); // Sort by timestamp, ascending. newState.conversations[action.payload.id].messages = (0, _fp.sortBy)('timestamp', combinedMessages); return newState; } }; reducers[actionTypes.SEND_MESSAGE] = reducers[actionTypes.SEND_GROUP_MESSAGE] = { next: function next(state, action) { return (0, _extends12.default)({}, state, { conversations: (0, _extends12.default)({}, state.conversations, (0, _defineProperty3.default)({}, action.payload.participant, (0, _extends12.default)({}, state.conversations[action.payload.participant], { messages: [].concat((0, _toConsumableArray3.default)(state.conversations[action.payload.participant].messages), [(0, _extends12.default)({}, action.payload.message)]) }))) }); } }; reducers[actionTypes.INCOMING_MESSAGE_READ] = { next: function next(state, action) { return (0, _extends12.default)({}, state, { conversations: (0, _extends12.default)({}, state.conversations, (0, _defineProperty3.default)({}, action.payload.participant, (0, _extends12.default)({}, state.conversations[action.payload.participant], { messages: state.conversations[action.payload.participant].messages.map(function (message) { if (message.messageId === action.payload.messageId) { message.read = true; } return message; }) }))) }); } }; reducers[actionTypes.SEND_MESSAGE_READ_FINISH] = { next: function next(state, action) { return (0, _extends12.default)({}, state, { conversations: (0, _extends12.default)({}, state.conversations, (0, _defineProperty3.default)({}, action.payload.participant, (0, _extends12.default)({}, state.conversations[action.payload.participant], { messages: state.conversations[action.payload.participant].messages.map(function (message) { if (message.messageId === action.payload.messageId) { message.read = true; } return message; }) }))) }); } }; reducers[actionTypes.MESSAGE_RECEIVED] = { next: function next(state, action) { var prevMessages = state.conversations[action.payload.participant] ? state.conversations[action.payload.participant].messages : []; // Ignore duplicate messages (ex. when sending to self) if ((0, _fp.find)(function (message) { return message.messageId === action.payload.message.messageId; }, prevMessages)) { return state; } return (0, _extends12.default)({}, state, { conversations: (0, _extends12.default)({}, state.conversations, (0, _defineProperty3.default)({}, action.payload.participant, (0, _extends12.default)({}, state.conversations[action.payload.participant], { messages: [].concat((0, _toConsumableArray3.default)(prevMessages), [(0, _extends12.default)({}, action.payload.message)]) }))) }); } }; reducers[actionTypes.SEND_MESSAGE_FINISH] = reducers[actionTypes.SEND_GROUP_MESSAGE_FINISH] = function (state, action) { return (0, _extends12.default)({}, state, { conversations: (0, _extends12.default)({}, state.conversations, (0, _defineProperty3.default)({}, action.payload.participant, (0, _extends12.default)({}, state.conversations[action.payload.participant], { messages: state.conversations[action.payload.participant].messages.map(function (message) { return sendMessageFinishHelper(message, action); }) }))) }); }; reducers[actionTypes.CREATE_GROUP_CONVERSATION_FINISH] = { next: function next(state, action) { return (0, _extends12.default)({}, state, { conversations: (0, _extends12.default)({}, state.conversations, (0, _defineProperty3.default)({}, action.payload.groupInfo.groupId, (0, _extends12.default)({}, action.payload.groupInfo, { messages: [] }))) }); } }; reducers[actionTypes.GROUP_MESSAGE_RECEIVED] = { next: function next(state, action) { return (0, _extends12.default)({}, state, { conversations: (0, _extends12.default)({}, state.conversations, (0, _defineProperty3.default)({}, action.payload.groupId, (0, _extends12.default)({}, state.conversations[action.payload.groupId], { messages: [].concat((0, _toConsumableArray3.default)(state.conversations[action.payload.groupId].messages), [(0, _extends12.default)({}, action.payload.message)]) }))) }); } }; reducers[actionTypes.REMOVE_GROUP_MEMBERS_FINISH] = reducers[actionTypes.ADD_GROUP_MEMBERS_FINISH] = { next: function next(state, action) { return (0, _extends12.default)({}, state, { conversations: (0, _extends12.default)({}, state.conversations, (0, _defineProperty3.default)({}, action.payload.groupId, (0, _extends12.default)({}, state.conversations[action.payload.groupId], { members: action.payload.members }))) }); } }; // Remove all messages from the specified conversation. reducers[actionTypes.CLEAR_MESSAGES] = { next: function next(state, action) { return (0, _extends12.default)({}, state, { conversations: (0, _extends12.default)({}, state.conversations, (0, _defineProperty3.default)({}, action.payload, (0, _extends12.default)({}, state.conversations[action.payload], { messages: [] }))) }); } }; /* * Combine all of reducers into a single reducer, with * a default state of an empty array. */ var reducer = (0, _reduxActions.handleActions)(reducers, { conversations: {} }); exports.default = reducer; /* * A helper function to make dealing with the messages array in SEND_MESSAGE_FINISH * a little bit easier. */ var sendMessageFinishHelper = function sendMessageFinishHelper(message, action) { if (message.timestamp === action.payload.timestamp) { if (action.payload.error) { message = (0, _extends12.default)({}, message, { sender: action.payload.sender, isPending: false, messageId: null, error: action.payload.error }); } else { message = (0, _extends12.default)({}, message, { sender: action.payload.sender, isPending: false, messageId: action.payload.messageId, parts: action.payload.parts }); } } else { message = (0, _extends12.default)({}, message); } return message; }; /***/ }), /***/ "./src/messaging/interface/selectors.js": /*!**********************************************!*\ !*** ./src/messaging/interface/selectors.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getMessagingConfig = getMessagingConfig; exports.getConversations = getConversations; exports.getMessages = getMessages; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); /* * Redux-saga selector functions. * Used with the `select` effect in sagas to retrieve * specific portions of the state. */ /** * Retrieves the config options provided by the messaging plugin. * @method getMessagingConfig * @return {Object} */ function getMessagingConfig(state) { return (0, _fp.cloneDeep)(state.config.messaging); } /** * Retrieves conversations from the store pertaining to messaging. * @method getConversations * @return {Object} */ function getConversations(state) { return (0, _fp.cloneDeep)(state.messaging.conversations); } /** * Retrieves the messages from the store pertaining to a specific messaging * conversation. * @method getMessages * @return {Object} */ function getMessages(state, conversationId) { return (0, _fp.cloneDeep)(state.messaging.conversations[conversationId].messages); } /***/ }), /***/ "./src/messaging/link/index.js": /*!*************************************!*\ !*** ./src/messaging/link/index.js ***! \*************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = linkMessaging; var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _events = __webpack_require__(/*! ../interface/events */ "./src/messaging/interface/events.js"); var _events2 = _interopRequireDefault(_events); var _actions = __webpack_require__(/*! ../../events/interface/actions */ "./src/events/interface/actions.js"); var _actions2 = __webpack_require__(/*! ../../config/interface/actions */ "./src/config/interface/actions.js"); var _logs = __webpack_require__(/*! ../../logs */ "./src/logs/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _sagas = __webpack_require__(/*! ./sagas */ "./src/messaging/link/sagas.js"); var _interface = __webpack_require__(/*! ../interface */ "./src/messaging/interface/index.js"); var _interface2 = _interopRequireDefault(_interface); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Get the logger // Redux-Saga var log = (0, _logs.getLogManager)().getLogger('MESSAGING'); // The interface to implement. // Events function linkMessaging() { var _marked = /*#__PURE__*/_regenerator2.default.mark(init); var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var defaultOptions = { features: ['base'] }; options = (0, _fp.defaults)(defaultOptions, options); if (options.features.length > 1 || options.features[0] !== defaultOptions.features[0]) { log.warn('Link messaging is not compatible with add-on ' + 'features. Reverting to base messaging.'); options.features = defaultOptions.features; } log.info('Messaging features in use: ' + options.features); function init() { return _regenerator2.default.wrap(function init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.put)((0, _actions2.update)(options, _interface2.default.name)); case 2: _context.next = 4; return (0, _effects.put)((0, _actions.mapEvents)(_events2.default)); case 4: case 'end': return _context.stop(); } } }, _marked, this); } var capabilities = ['simpleMessagingOnly', 'onlyInternalMessaging']; return { sagas: [_sagas.sendMessage, _sagas.receiveMessage], capabilities: capabilities, init: init, api: _interface2.default.api, name: _interface2.default.name, reducer: _interface2.default.reducer, mixins: _interface2.default.mixins }; } /***/ }), /***/ "./src/messaging/link/sagas.js": /*!*************************************!*\ !*** ./src/messaging/link/sagas.js ***! \*************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.sendMessage = sendMessage; exports.receiveMessage = receiveMessage; var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _actionTypes = __webpack_require__(/*! ../interface/actionTypes */ "./src/messaging/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _actions = __webpack_require__(/*! ../interface/actions */ "./src/messaging/interface/actions/index.js"); var _selectors = __webpack_require__(/*! ../interface/selectors */ "./src/messaging/interface/selectors.js"); var _selectors2 = __webpack_require__(/*! ../../auth/interface/selectors */ "./src/auth/interface/selectors.js"); var _actionTypes2 = __webpack_require__(/*! ../../notifications/interface/actionTypes */ "./src/notifications/interface/actionTypes.js"); var _predicates = __webpack_require__(/*! ../../predicates */ "./src/predicates.js"); var P = _interopRequireWildcard(_predicates); var _effects2 = __webpack_require__(/*! ../../request/effects */ "./src/request/effects.js"); var _effects3 = _interopRequireDefault(_effects2); var _errors = __webpack_require__(/*! ../../errors */ "./src/errors/index.js"); var _errors2 = _interopRequireDefault(_errors); var _logs = __webpack_require__(/*! ../../logs */ "./src/logs/index.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(sendMessage), _marked2 = /*#__PURE__*/_regenerator2.default.mark(receiveMessage); // Messaging // Auth // Request // Error // Logs var log = (0, _logs.getLogManager)().getLogger('MESSAGING'); /** * Link send message saga. * Performs the workflow of sending a message using SPiDR/Link. * @method sendMessage */ function sendMessage() { var sendMessageChannel, action, participant, parts, timestamp, _ref, server, username, requestOptions, response, error, statusCode, message; return _regenerator2.default.wrap(function sendMessage$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.actionChannel)([actionTypes.SEND_MESSAGE]); case 2: sendMessageChannel = _context.sent; case 3: if (false) {} _context.next = 6; return (0, _effects.take)(sendMessageChannel); case 6: action = _context.sent; participant = action.payload.participant; parts = action.payload.message.parts; timestamp = action.payload.message.timestamp; _context.next = 12; return (0, _effects.select)(_selectors2.getConnectionInfo); case 12: _ref = _context.sent; server = _ref.server; username = _ref.username; requestOptions = _ref.requestOptions; _context.next = 18; return (0, _effects3.default)({ url: server.protocol + '://' + server.server + ':' + server.port + '/rest/version/' + server.version + '/user/' + username + '/instantmessage', method: 'POST', body: (0, _stringify2.default)({ imRequest: { charset: 'UTF-8', toUrl: participant, message: parts[0].text, type: 'A2' } }) }, requestOptions); case 18: response = _context.sent; if (!response.error) { _context.next = 26; break; } error = void 0; if (response.payload.body) { // Handle errors from the server. statusCode = response.payload.body.imResponse.statusCode; log.debug('Failed to send message with status code ' + statusCode + '.'); error = new _errors2.default({ code: _errors.messagingCodes.SEND_MESSAGE_FAIL, message: 'Failed to send message. Code: ' + statusCode + '.' }); } else { // Handler errors from the request helper. message = response.payload.result.message; log.debug('Send message request failed', message); error = new _errors2.default({ code: _errors.messagingCodes.SEND_MESSAGE_FAIL, message: 'Send message request failed: ' + message + '.' }); } _context.next = 24; return (0, _effects.put)(_actions.messageActions.sendMessageFinish({ sender: username, participant: participant, parts: parts, timestamp: timestamp, error: error })); case 24: _context.next = 31; break; case 26: if (!(response.payload.body.imResponse && response.payload.body.imResponse.messageId)) { _context.next = 31; break; } _context.next = 29; return (0, _effects.put)(_actions.messageActions.sendMessageFinish({ sender: username, participant: participant, parts: parts, timestamp: timestamp, messageId: response.payload.body.imResponse.messageId })); case 29: _context.next = 31; break; case 31: _context.next = 3; break; case 33: case 'end': return _context.stop(); } } }, _marked, this); } /** * Link receive message saga. * Performs the workflow of receiving messages over the SPiDR websocket. * @method receiveMessage */ function receiveMessage() { var receiveMessagePattern, action, message, sender, messageId, conversations; return _regenerator2.default.wrap(function receiveMessage$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: receiveMessagePattern = function receiveMessagePattern(action) { return P.and(P.type(_actionTypes2.NOTIFICATION_RECEIVED)(action) && P.link)(action); }; // Redux-saga take() pattern. // Using predicates directly doesn't work... so wrap it. // TODO: Fix this properly. case 1: if (false) {} _context2.next = 4; return (0, _effects.take)(receiveMessagePattern); case 4: action = _context2.sent; if (!action.payload.notificationMessage) { _context2.next = 20; break; } if (!(action.payload.notificationMessage.eventType === 'IM')) { _context2.next = 20; break; } message = action.payload.notificationMessage.imnotificationParams.msgText; sender = action.payload.notificationMessage.imnotificationParams.primaryContact.split('sip:')[1]; messageId = action.payload.notificationMessage.eventId; _context2.next = 12; return (0, _effects.select)(_selectors.getConversations); case 12: conversations = _context2.sent; if (!conversations.hasOwnProperty(sender)) { _context2.next = 18; break; } _context2.next = 16; return (0, _effects.put)(_actions.messageActions.messageReceived([{ mimeType: 'text/plain', text: message }], messageId, sender, Date.now(), { newConversation: false })); case 16: _context2.next = 20; break; case 18: _context2.next = 20; return (0, _effects.put)(_actions.messageActions.messageReceived([{ mimeType: 'text/plain', text: message }], messageId, sender, Date.now(), { newConversation: true })); case 20: _context2.next = 1; break; case 22: case 'end': return _context2.stop(); } } }, _marked2, this); } /***/ }), /***/ "./src/mwi/interface/actionTypes.js": /*!******************************************!*\ !*** ./src/mwi/interface/actionTypes.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PREFIX = '@@KANDY/'; var MWI_UPDATE = exports.MWI_UPDATE = PREFIX + 'MWI_UPDATE'; var FETCH_MWI = exports.FETCH_MWI = PREFIX + 'FETCH_MWI'; /***/ }), /***/ "./src/mwi/interface/actions.js": /*!**************************************!*\ !*** ./src/mwi/interface/actions.js ***! \**************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); exports.mwiUpdate = mwiUpdate; exports.fetchMwi = fetchMwi; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/mwi/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Creates a message waiting indicator update action. * * @method mwiUpdate * @param {Object} $0 * @param {string} $0.mwiEvent An mwiEvent object from spidr. * @param {Object} $0.error A Kandy Error object. * @returns {Object} A flux standard action. */ function mwiUpdate(_ref) { var mwiData = _ref.mwiData, error = _ref.error; if (error) { return { type: actionTypes.MWI_UPDATE, payload: error, error: true }; } else { return { type: actionTypes.MWI_UPDATE, payload: (0, _extends3.default)({}, mwiData) }; } } /** * Creates a fetch message waiting indicator action. * * @method fetchMwi * @returns {Object} A flux standard action. */ function fetchMwi() { return { type: actionTypes.FETCH_MWI }; } /***/ }), /***/ "./src/mwi/interface/api.js": /*!**********************************!*\ !*** ./src/mwi/interface/api.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = api; var _actions = __webpack_require__(/*! ./actions */ "./src/mwi/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(/*! ./selectors */ "./src/mwi/interface/selectors.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Kandy's mwi (Message Waiting Indicator) features are used to retrieve and view * voicemail indicators. * * Voicemail functions are namespaced beneath 'voicemail' on the returned Kandy object. * * @public * @requires voicemail * @module Voicemail */ function api(_ref) { var dispatch = _ref.dispatch, getState = _ref.getState; var mwiApi = { /** * Attempts to retrieve voicemail information from the server. * A `voicemail:new` event is emitted upon completion. * * @public * @requires voicemail * @memberof Voicemail * @method fetch */ fetch: function fetch() { dispatch(actions.fetchMwi()); }, /** * Returns voicemail data from the store. * * @public * @requires voicemail * @memberof Voicemail * @method get */ get: function get() { return (0, _selectors.getMwi)(getState()); } }; return { voicemail: mwiApi }; } /***/ }), /***/ "./src/mwi/interface/eventTypes.js": /*!*****************************************!*\ !*** ./src/mwi/interface/eventTypes.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // TODO: Fix params in this file, move to voicemail over MWI on all public wording. /** * A voicemail event has been received. * * @requires voicemail * @public * @memberof Voicemail * @event voicemail:change * @param {Object} params An object containing voicemail info. * @param {number} params.lastUpdated Timestamp of the last time voicemail data was checked. * @param {boolean} params.newMessagesWaiting Whether there are new messages. * @param {number} params.totalVoice The total number of voicemail messages. * @param {number} params.unheardVoice Number of unheard voicemail messages. * @param {Object} params.voice Object containing individual counts of new, old, urgent voicemails. * @param {Object} params.fax Object containing individual counts of new, old, urgent faxes. * @param {Object} params.multimedia Object containing individual counts of new, old, urgent multimedia messages. */ var MWI_CHANGE = exports.MWI_CHANGE = 'voicemail:change'; /** * An error has occured while attempting to retrieve voicemail data. * * @requires voicemail * @public * @memberof Voicemail * @event voicemail:error * @param {Object} params * @param {KandyError} params.error The Kandy error object. */ var MWI_ERROR = exports.MWI_ERROR = 'voicemail:error'; /***/ }), /***/ "./src/mwi/interface/events.js": /*!*************************************!*\ !*** ./src/mwi/interface/events.js ***! \*************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/mwi/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/mwi/interface/eventTypes.js"); var eventTypes = _interopRequireWildcard(_eventTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var eventsMap = {}; eventsMap[actionTypes.MWI_UPDATE] = function (action) { if (action.error) { return { type: eventTypes.MWI_ERROR, args: { error: action.payload } }; } else { return { type: eventTypes.MWI_CHANGE, args: { lastUpdated: action.payload.lastUpdated, newMessagesWaiting: action.payload.newMessagesWaiting, totalVoice: action.payload.totalVoice, unheardVoice: action.payload.unheardVoice, voice: action.payload.voice, fax: action.payload.fax, multimedia: action.payload.multimedia } }; } }; exports.default = eventsMap; /***/ }), /***/ "./src/mwi/interface/index.js": /*!************************************!*\ !*** ./src/mwi/interface/index.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _api = __webpack_require__(/*! ./api */ "./src/mwi/interface/api.js"); var _api2 = _interopRequireDefault(_api); var _reducers = __webpack_require__(/*! ./reducers */ "./src/mwi/interface/reducers.js"); var _reducers2 = _interopRequireDefault(_reducers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * This interface is for a mwi plugin. * @type {string} */ // Import the components of the interface. var name = 'mwi'; exports.default = { name: name, api: _api2.default, reducer: _reducers2.default }; /***/ }), /***/ "./src/mwi/interface/reducers.js": /*!***************************************!*\ !*** ./src/mwi/interface/reducers.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/mwi/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var reducers = {}; reducers[actionTypes.MWI_UPDATE] = { next: function next(state, action) { return (0, _extends3.default)({}, action.payload); } }; var reducer = (0, _reduxActions.handleActions)(reducers, {}); exports.default = reducer; /***/ }), /***/ "./src/mwi/interface/selectors.js": /*!****************************************!*\ !*** ./src/mwi/interface/selectors.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getMwi = getMwi; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); /* * Redux-saga selector functions. * Used with the `select` effect in sagas to retrieve * specific portions of the state. */ /** * Retrieves the message waiting indicator data from the state. * @method getMwi * @return {Object} */ function getMwi(state) { return (0, _fp.cloneDeep)(state.mwi); } /***/ }), /***/ "./src/mwi/link/index.js": /*!*******************************!*\ !*** ./src/mwi/link/index.js ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = mwiLink; var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _events = __webpack_require__(/*! ../interface/events */ "./src/mwi/interface/events.js"); var _events2 = _interopRequireDefault(_events); var _actions = __webpack_require__(/*! ../../events/interface/actions */ "./src/events/interface/actions.js"); var _interface = __webpack_require__(/*! ../interface */ "./src/mwi/interface/index.js"); var _interface2 = _interopRequireDefault(_interface); var _sagas = __webpack_require__(/*! ./sagas */ "./src/mwi/link/sagas.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Plugin for Kandy Link's Messages Waiting Indicator (MWI) service. * Provides the SDK with the Voicemail feature. */ // Import the interface to implement. // Events function mwiLink() { var _marked = /*#__PURE__*/_regenerator2.default.mark(init); function init() { return _regenerator2.default.wrap(function init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.put)((0, _actions.mapEvents)(_events2.default)); case 2: case 'end': return _context.stop(); } } }, _marked, this); } var capabilities = ['voicemail']; return { capabilities: capabilities, api: _interface2.default.api, name: _interface2.default.name, reducer: _interface2.default.reducer, init: init, sagas: [_sagas.mwiReceived, _sagas.fetchMwi] }; } /***/ }), /***/ "./src/mwi/link/sagas.js": /*!*******************************!*\ !*** ./src/mwi/link/sagas.js ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); exports.mwiReceived = mwiReceived; exports.fetchMwi = fetchMwi; var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _selectors = __webpack_require__(/*! ../../auth/interface/selectors */ "./src/auth/interface/selectors.js"); var _actionTypes = __webpack_require__(/*! ../../notifications/interface/actionTypes */ "./src/notifications/interface/actionTypes.js"); var _actions = __webpack_require__(/*! ../interface/actions */ "./src/mwi/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _actionTypes2 = __webpack_require__(/*! ../interface/actionTypes */ "./src/mwi/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes2); var _effects2 = __webpack_require__(/*! ../../request/effects */ "./src/request/effects.js"); var _effects3 = _interopRequireDefault(_effects2); var _errors = __webpack_require__(/*! ../../errors */ "./src/errors/index.js"); var _errors2 = _interopRequireDefault(_errors); var _constants = __webpack_require__(/*! ../../constants */ "./src/constants.js"); var _logs = __webpack_require__(/*! ../../logs */ "./src/logs/index.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(mwiReceived), _marked2 = /*#__PURE__*/_regenerator2.default.mark(fetchMwi); // Auth // Notifications // MWI Actions // Request // Errors // Constants // Logs var log = (0, _logs.getLogManager)().getLogger('MWI'); function mwiReceived() { var mwiEventChannel, mwiReceived, action, mwiData; return _regenerator2.default.wrap(function mwiReceived$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: mwiEventChannel = (0, _effects.actionChannel)(function (action) { return action.type === _actionTypes.NOTIFICATION_RECEIVED && action.payload.notificationMessage && action.payload.notificationMessage.eventType === 'mwi'; }); _context.next = 3; return mwiEventChannel; case 3: mwiReceived = _context.sent; case 4: if (false) {} _context.next = 7; return (0, _effects.take)(mwiReceived); case 7: action = _context.sent; // Parse the mwi data mwiData = (0, _extends3.default)({}, action.payload.notificationMessage.mwiNotificationParams); mwiData.newMessagesWaiting = mwiData.mwi === 'yes'; delete mwiData.mwi; mwiData.lastUpdated = action.payload.notificationMessage.time; _context.next = 14; return (0, _effects.put)(actions.mwiUpdate({ mwiData: mwiData })); case 14: _context.next = 4; break; case 16: case 'end': return _context.stop(); } } }, _marked, this); } function fetchMwi() { var action, connInfo, options, platform, version, response, error, statusCode, message, mwiData; return _regenerator2.default.wrap(function fetchMwi$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (false) {} _context2.next = 3; return (0, _effects.take)(actionTypes.FETCH_MWI); case 3: action = _context2.sent; _context2.next = 6; return (0, _effects.select)(_selectors.getConnectionInfo); case 6: connInfo = _context2.sent; options = (0, _extends3.default)({}, action.payload, connInfo); _context2.next = 10; return (0, _effects.select)(_selectors.getPlatform); case 10: platform = _context2.sent; version = platform === _constants.platforms.CPAAS ? 1 : options.server.version; _context2.next = 14; return (0, _effects3.default)({ url: options.server.protocol + '://' + options.server.server + ':' + options.server.port + '/rest/version/' + version + '/user/' + options.username + '/voicemail', method: 'GET' }, connInfo.requestOptions); case 14: response = _context2.sent; if (!response.error) { _context2.next = 22; break; } error = void 0; if (response.payload.body) { // Handle errors from the server. statusCode = response.payload.body.mwiresponse.statusCode; log.debug('Failed to fetch voicemails with status code ' + statusCode + '.'); error = new _errors2.default({ code: _errors.mwiCodes.FETCH_MWI_FAIL, message: 'Failed to fetch voicemail. Code: ' + statusCode + '.' }); } else { // Handle errors from the request helper. message = response.payload.result.message; log.debug('Fetch voicemail request failed.', message); error = new _errors2.default({ code: _errors.mwiCodes.FETCH_MWI_FAIL, message: 'Fetch voicemail request failed: ' + message + '.' }); } _context2.next = 20; return (0, _effects.put)(actions.mwiUpdate({ error: error })); case 20: _context2.next = 26; break; case 22: mwiData = {}; if (response.payload.body.mwiresponse.statusCode === 52) { // This statusCode means this user has absolutely no messages, new or old. // It is therefore accompanied with absolutely no data, so we make some for the store. mwiData = { lastUpdated: Date.now(), newMessagesWaiting: false, totalVoice: '0', unheardVoice: '0' }; } else { mwiData = (0, _extends3.default)({}, response.payload.body.mwiresponse); delete mwiData.statusCode; // Parse the mwi data mwiData.newMessagesWaiting = mwiData.mwi === 'yes'; delete mwiData.mwi; mwiData.lastUpdated = Date.now(); } _context2.next = 26; return (0, _effects.put)(actions.mwiUpdate({ mwiData: mwiData })); case 26: _context2.next = 0; break; case 28: case 'end': return _context2.stop(); } } }, _marked2, this); } /***/ }), /***/ "./src/notifications/index.js": /*!************************************!*\ !*** ./src/notifications/index.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = notifications; var _interface = __webpack_require__(/*! ./interface */ "./src/notifications/interface/index.js"); var _events = __webpack_require__(/*! ./interface/events */ "./src/notifications/interface/events.js"); var _events2 = _interopRequireDefault(_events); var _sagas = __webpack_require__(/*! ./sagas */ "./src/notifications/sagas.js"); var sagas = _interopRequireWildcard(_sagas); var _actions = __webpack_require__(/*! ../events/interface/actions */ "./src/events/interface/actions.js"); var _actions2 = __webpack_require__(/*! ../config/interface/actions */ "./src/config/interface/actions.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Configuration options for the notification feature. * @public * @name configs.notifications * @memberof configs * @instance * @param {Object} notifications - The notifications configuration object. * @param {number} [notifications.idCacheLength=100] - Default amount of event ids to remember for de-duplication purposes. * @param {Object} [notifications.pushRegistration] - Object describing the server to use for push services. * @param {string} [notifications.pushRegistration.server] - Hostname for the push registration server. * @param {string} [notifications.pushRegistration.port] - Port for the push registration server. * @param {string} [notifications.pushRegistration.protocol] - Protocol for the push registration server. * @param {string} [notifications.pushRegistration.version] - Version for the push registration server. * @param {string} [notifications.realm] - The realm used for push notifications * @param {string} [notifications.bundleId] - The bundle id used for push notifications */ /** * Notifications plugin factory. * @method notifications * @param {configs.notifications} options - Configuration options for authentication. * @return {Object} plugin - A notifications plugin. */ // Libraries. // Other plugins. function notifications() { var _marked = /*#__PURE__*/_regenerator2.default.mark(init); var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var defaultOptions = { idCacheLength: 100, pushRegistration: undefined, realm: undefined, bundleId: undefined }; var pluginOptions = (0, _fp.defaultsDeep)(defaultOptions, options); function init() { return _regenerator2.default.wrap(function init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.put)((0, _actions2.update)(pluginOptions, _interface.name)); case 2: _context.next = 4; return (0, _effects.put)((0, _actions.mapEvents)(_events2.default)); case 4: case 'end': return _context.stop(); } } }, _marked, this); } var capabilities = ['push', 'registerPushNotifications']; return { name: _interface.name, capabilities: capabilities, init: init, api: _interface.api, reducer: _interface.reducer, sagas: (0, _fp.values)(sagas) }; } // Notification plugin. /***/ }), /***/ "./src/notifications/interface/actionTypes.js": /*!****************************************************!*\ !*** ./src/notifications/interface/actionTypes.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var prefix = '@@KANDY/'; var PROCESS_NOTIFICATION = exports.PROCESS_NOTIFICATION = prefix + 'PROCESS_NOTIFICATION'; var PROCESS_NOTIFICATION_FINISH = exports.PROCESS_NOTIFICATION_FINISH = prefix + 'PROCESS_NOTIFICATION_FINISH'; var NOTIFICATION_RECEIVED = exports.NOTIFICATION_RECEIVED = prefix + 'NOTIFICATION_RECEIVED'; var ENABLE_NOTIFICATION_CHANNEL = exports.ENABLE_NOTIFICATION_CHANNEL = prefix + 'ENABLE_NOTIFICATION_CHANNEL'; var ENABLE_NOTIFICATION_CHANNEL_FINISH = exports.ENABLE_NOTIFICATION_CHANNEL_FINISH = prefix + 'ENABLE_NOTIFICATION_CHANNEL_FINISH'; /***/ }), /***/ "./src/notifications/interface/actions.js": /*!************************************************!*\ !*** ./src/notifications/interface/actions.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); exports.websocketNotification = websocketNotification; exports.externalNotification = externalNotification; exports.notificationReceived = notificationReceived; exports.processNotificationFinish = processNotificationFinish; exports.enableNotificationChannel = enableNotificationChannel; exports.enableNotificationChannelFinish = enableNotificationChannelFinish; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/notifications/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _constants = __webpack_require__(/*! ../../constants */ "./src/constants.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Helper function for funneling all notification types into a single action. * @method notificationHelper * @param {string} channel - The channel that the notification came from. * @param {Object} notification * @param {string} platform * @return {Object} A flux standard action. */ function notificationHelper(channel, notification, platform) { return { type: actionTypes.PROCESS_NOTIFICATION, payload: notification, meta: { platform: platform, channel: channel } }; } /** * Represents an application request to process a websocket notification. * @method websocketNotification * @param {Object} notification * @param {string} platform * @return {Object} A flux standard action. */ // Constants function websocketNotification(notification) { var platform = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _constants.platforms.LINK; return notificationHelper('WEBSOCKET', notification, platform); } /** * Represents an application request to process an external notification. * @method externalNotification * @param {Object} notification * @param {string} [channel='EXTERNAL'] - The channel that the notification came from. * @return {Object} A flux standard action. */ function externalNotification(notification) { var channel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EXTERNAL'; // TODO: Are external notifications _only_ for Link? return notificationHelper(channel.toUpperCase(), notification, _constants.platforms.LINK); } /** * Represents a received notification. * @method notificationReceived * @param {Object} notification * @param {string} platform * @return {Object} A flux standard action. */ function notificationReceived(notification, platform) { return { type: actionTypes.NOTIFICATION_RECEIVED, payload: notification, error: notification instanceof Error, meta: { platform: platform } }; } /** * Represents a received notification. * @method processNotificationFinish * @param {Object} notification * @param {string} platform * @return {Object} A flux standard action. */ function processNotificationFinish(notification, platform) { return { type: actionTypes.PROCESS_NOTIFICATION_FINISH, payload: notification, error: notification instanceof Error, meta: { platform: platform } }; } /** * Represents a request to change a notification channel status. * @method enableNotificationChannel * @param {string} channel - The notification channel being affected. * @param {Object} params * @param {boolean} params.channelEnabled - Whether to enable the channel or not. * @return {Object} A flux standard action. */ function enableNotificationChannel(channel) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return { type: actionTypes.ENABLE_NOTIFICATION_CHANNEL, payload: (0, _extends3.default)({}, params), meta: { channel: channel } }; } /** * Represents the response of a change in a notification channel status. * @method enableNotificationChannelFinish * @param {string} channel - The notification channel being affected. * @param {Object} $1 * @param {Object} $1.params - Information about the channel change. * @param {Object} $1.params.channelEnabled - Whether the channel was enabled or not. * @param {Object} $1.error - Error object, in the case of an error. * @return {Object} A flux standard action. */ function enableNotificationChannelFinish(channel) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, params = _ref.params, error = _ref.error; var action = { type: actionTypes.ENABLE_NOTIFICATION_CHANNEL_FINISH, meta: { channel: channel } }; if (error) { action.error = true; action.payload = new Error(error); action.payload.channelEnabled = params.channelEnabled; } else { action.payload = (0, _extends3.default)({}, params); } return action; } /***/ }), /***/ "./src/notifications/interface/api.js": /*!********************************************!*\ !*** ./src/notifications/interface/api.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); exports.default = api; var _actions = __webpack_require__(/*! ./actions */ "./src/notifications/interface/actions.js"); var actions = _interopRequireWildcard(_actions); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Notifications API. * @method api * @param {Function} dispatch The redux store's dispatch function. * @return {Object} api The notifications API object. */ function api(_ref) { var dispatch = _ref.dispatch; var notificationApi = { /** * Provides an external notification to Kandy for processing. * * @public * @requires externalNotifications * @memberof Notification * @method process * @param {Object} notification * @param {string} [channel] - The channel that the notification came from. */ process: function process(notification, channel) { dispatch(actions.externalNotification(notification, channel)); }, /** * Registers a device token for push notifications. * * @public * @requires push * @memberof Notification * @method registerPush * @param {Object} params * @param {string} params.deviceToken - The device token to be registered. * @param {string[]} params.services - Array of services to register for. * @param {string} params.pushProvider - The push provider, can be either 'apple' or 'google'. * @param {string} params.clientCorrelator - Unique identifier for a client device. */ registerPush: function registerPush(params) { dispatch(actions.enableNotificationChannel('PUSH', (0, _extends3.default)({}, params, { channelEnabled: true }))); }, /** * Deregisters for push notifications. * * @public * @requires push * @memberof Notification * @method deregisterPush */ deregisterPush: function deregisterPush() { dispatch(actions.enableNotificationChannel('PUSH', { channelEnabled: false })); }, /** * Enables, or disables, the processing of websocket notifications. * * @public * @requires push * @memberof Notification * @method enableWebsocket * @param {boolean} enable - Whether the websocket channel should be enabled. */ enableWebsocket: function enableWebsocket(enable) { dispatch(actions.enableNotificationChannel('WEBSOCKET', { channelEnabled: enable })); } }; return { notification: notificationApi }; } /** * @public * @requires push * @module Notification */ /***/ }), /***/ "./src/notifications/interface/eventTypes.js": /*!***************************************************!*\ !*** ./src/notifications/interface/eventTypes.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Push notifications registration state has changed. * * @public * @requires push * @memberof Notification * @event notifications:change * @param {Object} params * @param {string} params.channel The channel for the notification. */ var NOTI_CHANGE = exports.NOTI_CHANGE = 'notifications:change'; /** * An error occured with push notifications. * * @public * @requires push * @memberof Notification * @event notifications:error * @param {Object} params * @param {KandyError} params.error The Kandy error object. * @param {string} params.channel The channel for the notification. */ var NOTI_ERROR = exports.NOTI_ERROR = 'notifications:error'; /***/ }), /***/ "./src/notifications/interface/events.js": /*!***********************************************!*\ !*** ./src/notifications/interface/events.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/notifications/interface/eventTypes.js"); var eventTypes = _interopRequireWildcard(_eventTypes); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/notifications/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var events = {}; events[actionTypes.ENABLE_NOTIFICATION_CHANNEL_FINISH] = function (action) { if (action.error) { return { type: eventTypes.NOTI_ERROR, args: { channel: action.meta.channel, error: action.payload.error } }; } else { return { type: eventTypes.NOTI_CHANGE, args: { channel: action.meta.channel } }; } }; exports.default = events; /***/ }), /***/ "./src/notifications/interface/index.js": /*!**********************************************!*\ !*** ./src/notifications/interface/index.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reducer = exports.api = exports.name = undefined; var _reducers = __webpack_require__(/*! ./reducers */ "./src/notifications/interface/reducers.js"); var _reducers2 = _interopRequireDefault(_reducers); var _api = __webpack_require__(/*! ./api */ "./src/notifications/interface/api.js"); var _api2 = _interopRequireDefault(_api); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var name = 'notifications'; exports.name = name; exports.api = _api2.default; exports.reducer = _reducers2.default; /***/ }), /***/ "./src/notifications/interface/reducers.js": /*!*************************************************!*\ !*** ./src/notifications/interface/reducers.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = __webpack_require__(/*! babel-runtime/helpers/defineProperty */ "../../node_modules/babel-runtime/helpers/defineProperty.js"); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _extends3 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends4 = _interopRequireDefault(_extends3); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/notifications/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _actionTypes2 = __webpack_require__(/*! ../../connectivity/interface/actionTypes */ "./src/connectivity/interface/actionTypes.js"); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var reducers = {}; reducers[actionTypes.ENABLE_NOTIFICATION_CHANNEL_FINISH] = { next: function next(state, action) { var channel = action.meta.channel; var enabled = action.payload.channelEnabled; var newChannelState = void 0; if (enabled) { newChannelState = (0, _extends4.default)({}, state[channel], action.payload); } else { // If the channel is being disabled, clear old state. newChannelState = (0, _extends4.default)({}, action.payload); } return (0, _extends4.default)({}, state, (0, _defineProperty3.default)({}, channel, newChannelState)); } }; /* * The websocket channel is assumed to be enabled when the * websocket is opened. */ reducers[_actionTypes2.WS_CONNECT_FINISHED] = { next: function next(state) { // TODO: Link WS only? return (0, _extends4.default)({}, state, { WEBSOCKET: (0, _extends4.default)({}, state.WEBSOCKET, { channelEnabled: true }) }); } }; // Default notifications sub-state. var defaultState = { WEBSOCKET: { channelEnabled: false }, PUSH: { channelEnabled: false }, EXTERNAL: { channelEnabled: true } /** * Notifications reducer. * @method reducer * @param {Object} state - The current redux state. * @param {Object} action - A flux standard action. * @return {Object} - The new redux state. */ };var reducer = (0, _reduxActions.handleActions)(reducers, defaultState); exports.default = reducer; /***/ }), /***/ "./src/notifications/interface/selectors.js": /*!**************************************************!*\ !*** ./src/notifications/interface/selectors.js ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getNotificationsInfo = getNotificationsInfo; exports.getNotificationConfig = getNotificationConfig; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); /** * Retrieves the notifications state. * @method getNotificationsInfo * @param {String} [channel] - Specific notification channel information to retrieve. * @return {Object} */ function getNotificationsInfo(state) { var channel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; if (channel) { return state.notifications[channel]; } else { return state.notifications; } } /** * Retrieves notification config. * @method getNotificationConfig * @return {Object} */ function getNotificationConfig(state) { return (0, _fp.cloneDeep)(state.config.notifications); } /***/ }), /***/ "./src/notifications/requests.js": /*!***************************************!*\ !*** ./src/notifications/requests.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.pushNotificationsRegistration = pushNotificationsRegistration; exports.pushNotificationsDeRegistration = pushNotificationsDeRegistration; exports.fetchSDP = fetchSDP; var _effects = __webpack_require__(/*! ../request/effects */ "./src/request/effects.js"); var _effects2 = _interopRequireDefault(_effects); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(pushNotificationsRegistration), _marked2 = /*#__PURE__*/_regenerator2.default.mark(pushNotificationsDeRegistration), _marked3 = /*#__PURE__*/_regenerator2.default.mark(fetchSDP); // Request // Logs var log = (0, _logs.getLogManager)().getLogger('NOTIFICATIONS'); /** * Registers a device token with On-Prem services. * @method pushNotificationsRegistration * @param {Object} connection - Information for formatting the request. * @param {Object} options * @param {string} options.deviceToken * @param {string[]} options.services - Push service to register to; either 'google' or 'apple'. * @param {string} options.pushProvider - The push provider, can be either 'apple' or 'google'. * @param {string} options.bundleId - The bundle id to use for registration. * @param {string} options.clientCorrelator - Unique identifier for a client device. * @return {Object} response */ function pushNotificationsRegistration(connection, options) { var server, requestOptions, url, method, body, response, registrationResponse, responseName, statusCode, message; return _regenerator2.default.wrap(function pushNotificationsRegistration$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: server = connection.server, requestOptions = connection.requestOptions; url = server.protocol + '://' + server.server + ':' + server.port + '/' + ('rest/version/' + server.version + '/') + ('user/' + connection.username + '/') + 'push/' + options.pushProvider.toLowerCase() + '/devices/'; method = 'POST'; body = (0, _stringify2.default)({ deviceToken: options.deviceToken, bundleID: options.bundleId, service: options.services, clientCorrelator: options.clientCorrelator, realm: connection.realm }); _context.next = 6; return (0, _effects2.default)({ url: url, method: method, body: body }, requestOptions); case 6: response = _context.sent; registrationResponse = void 0; responseName = options.pushProvider.toLowerCase() + 'DeviceRegistrationResponse'; if (response.payload.body && response.payload.body[responseName]) { registrationResponse = response.payload.body[responseName]; } if (!response.error) { _context.next = 22; break; } if (!response.payload.body) { _context.next = 17; break; } // Handle errors from the server. statusCode = registrationResponse.statusCode; log.debug('Failed to register device token for push notifications. Status: ' + statusCode); return _context.abrupt('return', { error: true, status: statusCode, text: 'Failed to register device token. Error: ' + response.payload.statusCode }); case 17: // Handle errors from the request helper. message = response.payload.result.message; log.debug('Device registration request failed: ' + message + '.'); return _context.abrupt('return', { error: true, status: response.payload.result.code, text: 'Failed to register device token. Error: ' + response.payload.result.message }); case 20: _context.next = 28; break; case 22: if (!(registrationResponse && registrationResponse.statusCode !== 0)) { _context.next = 26; break; } return _context.abrupt('return', { error: true, status: registrationResponse.statuscode, text: 'Failed to register device token. Error: ' + registrationResponse.statusCode }); case 26: log.debug('Successfully registered device token for push notifications.', registrationResponse.statusCode); return _context.abrupt('return', (0, _extends3.default)({ error: false }, registrationResponse)); case 28: case 'end': return _context.stop(); } } }, _marked, this); } /** * De-Registers a device token with On-Prem services. * @method pushNotificationsDeRegistration * @param {Object} connection - Information for formatting the request. * @param {Object} options * @param {string} options.registration * @return {Object} response */ function pushNotificationsDeRegistration(connection, options) { var server, requestOptions, url, method, response, statusCode, message; return _regenerator2.default.wrap(function pushNotificationsDeRegistration$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: server = connection.server, requestOptions = connection.requestOptions; url = server.protocol + '://' + server.server + ':' + server.port + options.registration; method = 'DELETE'; _context2.next = 5; return (0, _effects2.default)({ url: url, method: method }, requestOptions); case 5: response = _context2.sent; if (!response.error) { _context2.next = 18; break; } if (!response.payload.body) { _context2.next = 13; break; } // Handle errors from the server. statusCode = response.payload.body.statusCode; log.debug('Failed to deregister device token for push. Status: ' + statusCode + '.'); // TODO: Proper errors. return _context2.abrupt('return', { error: true, status: statusCode, text: 'Failed to deregister device token. Code: ' + statusCode + '.' }); case 13: // Handle errors from the request helper. message = response.payload.result.message; log.debug('Device token deregistration request failed: ' + message); // TODO: Proper error. return _context2.abrupt('return', { error: true, status: response.payload.result.code, text: 'Device token deregistration request failed: ' + message }); case 16: _context2.next = 20; break; case 18: log.debug('Successfully de-registered device token for push notifications.'); // Successful de-register has no response. return _context2.abrupt('return', { error: false }); case 20: case 'end': return _context2.stop(); } } }, _marked2, this); } /** * Fetches SDP data from a given partial URL. * @method fetchSDP * @param {Object} partialUrl - A partial URL. Contains everything after the protocol://server:port * @return {Object} response A response payload */ function fetchSDP(connection, partialUrl) { var server, requestOptions, response; return _regenerator2.default.wrap(function fetchSDP$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: server = connection.server, requestOptions = connection.requestOptions; _context3.next = 3; return (0, _effects2.default)({ url: server.protocol + '://' + server.server + ':' + server.port + partialUrl, method: 'GET' }, requestOptions); case 3: response = _context3.sent; if (response.error) { _context3.next = 6; break; } return _context3.abrupt('return', response.payload.body); case 6: case 'end': return _context3.stop(); } } }, _marked3, this); } /***/ }), /***/ "./src/notifications/sagas.js": /*!************************************!*\ !*** ./src/notifications/sagas.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.processNotification = processNotification; exports.registerPushDeviceToken = registerPushDeviceToken; exports.deregisterPushDeviceToken = deregisterPushDeviceToken; exports.enableWebsocketChannel = enableWebsocketChannel; var _actions = __webpack_require__(/*! ./interface/actions */ "./src/notifications/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _actionTypes = __webpack_require__(/*! ./interface/actionTypes */ "./src/notifications/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _selectors = __webpack_require__(/*! ./interface/selectors */ "./src/notifications/interface/selectors.js"); var _requests = __webpack_require__(/*! ./requests */ "./src/notifications/requests.js"); var requests = _interopRequireWildcard(_requests); var _selectors2 = __webpack_require__(/*! ../auth/interface/selectors */ "./src/auth/interface/selectors.js"); var _pako = __webpack_require__(/*! pako */ "../../node_modules/pako/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); var _reduxSaga = __webpack_require__(/*! redux-saga */ "../../node_modules/redux-saga/es/index.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _constants = __webpack_require__(/*! ../constants */ "./src/constants.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(processNotification), _marked2 = /*#__PURE__*/_regenerator2.default.mark(normalizeSDP), _marked3 = /*#__PURE__*/_regenerator2.default.mark(registerPushDeviceToken), _marked4 = /*#__PURE__*/_regenerator2.default.mark(deregisterPushDeviceToken), _marked5 = /*#__PURE__*/_regenerator2.default.mark(enableWebsocketChannel); // Notification plugin. // Other plugins. // Libraries. // Logs // Constants var INITIAL_BUFFER_SIZE = 10; // Get the logger var log = (0, _logs.getLogManager)().getLogger('NOTIFICATION'); function processNotification() { var config, idCache, isDuplicate, externalNotifications, action, channel, notificationId, formattedPayload, error; return _regenerator2.default.wrap(function processNotification$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: isDuplicate = function isDuplicate(id) { if (idCache.indexOf(id) !== -1) { return true; // duplicate. } else { // Not a duplicate. idCache.push(id); if (idCache.length > config.idCacheLength) { idCache.shift(); } return false; } }; _context.next = 3; return (0, _effects.select)(_selectors.getNotificationConfig); case 3: config = _context.sent; idCache = []; /** * Checks whether a notification has already been received, * judging by its event ID. * @method isDuplicate * @param {string} id * @return {boolean} */ _context.next = 7; return (0, _effects.actionChannel)(actionTypes.PROCESS_NOTIFICATION, _reduxSaga.buffers.expanding(INITIAL_BUFFER_SIZE)); case 7: externalNotifications = _context.sent; case 8: if (false) {} _context.next = 11; return (0, _effects.take)(externalNotifications); case 11: action = _context.sent; _context.next = 14; return (0, _effects.select)(_selectors.getNotificationsInfo, action.meta.channel); case 14: channel = _context.sent; if (channel.channelEnabled) { _context.next = 18; break; } log.debug('Notification received on disabled channel. Ignoring it.', action.meta.channel); return _context.abrupt('continue', 8); case 18: // Find the unique ID of the received notification. notificationId = void 0; _context.t0 = action.meta.platform; _context.next = _context.t0 === _constants.platforms.LINK ? 22 : _context.t0 === _constants.platforms.CLOUD ? 24 : _context.t0 === _constants.platforms.CPAAS ? 26 : 28; break; case 22: notificationId = action.payload.notificationMessage.eventId; return _context.abrupt('break', 29); case 24: notificationId = action.payload.message.UUID; return _context.abrupt('break', 29); case 26: // A Link notification can be in either the Link format or the SPiDR format (for calls). notificationId = action.payload.notificationMessage.id || action.payload.notificationMessage.eventId; return _context.abrupt('break', 29); case 28: log.debug('Received notification from unknown platform.'); case 29: formattedPayload = action.payload; if (!(0, _fp.has)('payload.notificationMessage.sessionParams.sdpFormat', action)) { _context.next = 37; break; } log.debug('Notification contains SDP. Normalizing.'); _context.next = 34; return (0, _effects.call)(normalizeSDP, action.payload); case 34: formattedPayload = _context.sent; _context.next = 38; break; case 37: log.debug('Notification did not contain any SDP'); case 38: if (isDuplicate(notificationId)) { _context.next = 43; break; } _context.next = 41; return (0, _effects.put)(actions.notificationReceived(formattedPayload, action.meta.platform)); case 41: _context.next = 46; break; case 43: error = new Error('Notification id ' + notificationId + ' is duplicate.'); // TODO: Tech-debt; this action should be a notificationReceived error action. // But that requires all sagas listening for notifications to filter out // error actions ..which requires their take() patterns changed, which // is another tech-debt item. _context.next = 46; return (0, _effects.put)(actions.processNotificationFinish(error)); case 46: _context.next = 8; break; case 48: case 'end': return _context.stop(); } } }, _marked, this); } /** * This function accepts a notification payload. If the payload is a spidr payload * and contains an sdpFormat that needs manipulating, it is done here. * @method normalizeSDP * @param payload A processNotification action payload * @returns payload A processNotification action payload */ function normalizeSDP(payload) { var sdpCompressedBytes, sdpUnCompressedBytes, sdpString, connection, _ref, pushRegistration, response; return _regenerator2.default.wrap(function normalizeSDP$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: // Copy the payload to not disturb the action. payload = (0, _extends3.default)({}, payload); if (!(payload.notificationMessage.sessionParams.sdpFormat === 'compressed')) { _context2.next = 12; break; } log.debug('sdpFormat: compressed. Deflating compressed SDP...'); // convert based64 encoded string into bytes sdpCompressedBytes = atob(payload.notificationMessage.sessionParams.sdp); // uncompress the bytes _context2.next = 6; return (0, _effects.call)(_pako.inflate, sdpCompressedBytes); case 6: sdpUnCompressedBytes = _context2.sent; // convert uncompress bytes back into string sdpString = String.fromCharCode.apply(null, new Uint16Array(sdpUnCompressedBytes)); payload.notificationMessage.sessionParams.sdp = sdpString; return _context2.abrupt('return', payload); case 12: if (!(payload.notificationMessage.sessionParams.sdpFormat === 'url')) { _context2.next = 29; break; } log.debug('sdpFormat: url. Fetching SDP...'); _context2.next = 16; return (0, _effects.select)(_selectors2.getConnectionInfo); case 16: connection = _context2.sent; _context2.next = 19; return (0, _effects.select)(_selectors.getNotificationConfig); case 19: _ref = _context2.sent; pushRegistration = _ref.pushRegistration; // If a push registration endpoint was configured, use that instead of default. if (pushRegistration) { connection.server = (0, _fp.defaults)(connection.server, pushRegistration); connection.protocol = (0, _fp.defaults)(connection.protocol, pushRegistration); connection.port = (0, _fp.defaults)(connection.port, pushRegistration); connection.version = (0, _fp.defaults)(connection.version, pushRegistration); } _context2.next = 24; return (0, _effects.call)(requests.fetchSDP, connection, payload.notificationMessage.sessionParams.sdp); case 24: response = _context2.sent; payload.notificationMessage.sessionParams.sdp = response.eventDataResponse.sdp; return _context2.abrupt('return', payload); case 29: log.debug('Unknown sdpFormat received: ' + payload.notificationMessage.sessionParams.sdpFormat + '.'); return _context2.abrupt('return', payload); case 31: case 'end': return _context2.stop(); } } }, _marked2, this); } /** * Saga for registering a device token for push notifications. * @method registerPushDeviceToken */ function registerPushDeviceToken() { var takePushRegistrations, action, connection, _ref2, pushRegistration, realm, bundleId, response; return _regenerator2.default.wrap(function registerPushDeviceToken$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: takePushRegistrations = function takePushRegistrations(action) { return action.type === actionTypes.ENABLE_NOTIFICATION_CHANNEL && action.meta.channel === 'PUSH' && action.payload.channelEnabled; }; // Redux-saga take() pattern. // Take 'enable PUSH channel' actions. case 1: if (false) {} _context3.next = 4; return (0, _effects.take)(takePushRegistrations); case 4: action = _context3.sent; _context3.next = 7; return (0, _effects.select)(_selectors2.getConnectionInfo); case 7: connection = _context3.sent; _context3.next = 10; return (0, _effects.select)(_selectors.getNotificationConfig); case 10: _ref2 = _context3.sent; pushRegistration = _ref2.pushRegistration; realm = _ref2.realm; bundleId = _ref2.bundleId; // If a push registration endpoint was configured, use that instead of default. if (pushRegistration) { connection.server = (0, _fp.defaults)(connection.server, pushRegistration); connection.protocol = (0, _fp.defaults)(connection.protocol, pushRegistration); connection.port = (0, _fp.defaults)(connection.port, pushRegistration); connection.version = (0, _fp.defaults)(connection.version, pushRegistration); } connection.realm = realm; log.debug('Registering device token for push notifications.'); _context3.next = 19; return (0, _effects.call)(requests.pushNotificationsRegistration, connection, (0, _extends3.default)({}, action.payload, { bundleId: bundleId })); case 19: response = _context3.sent; if (!response.error) { _context3.next = 25; break; } _context3.next = 23; return (0, _effects.put)(actions.enableNotificationChannelFinish(action.meta.channel, { params: action.payload, error: response.text })); case 23: _context3.next = 27; break; case 25: _context3.next = 27; return (0, _effects.put)(actions.enableNotificationChannelFinish(action.meta.channel, { params: { channelEnabled: action.payload.channelEnabled, registration: response.registration, services: response.subscriptionParams.service } })); case 27: _context3.next = 1; break; case 29: case 'end': return _context3.stop(); } } }, _marked3, this); } /** * Saga for deregistering a device token for push notifications. * @method deregisterPushDeviceToken */ function deregisterPushDeviceToken() { var takePushDeregistrations, action, connection, _ref3, pushRegistration, realm, pushInfo, response; return _regenerator2.default.wrap(function deregisterPushDeviceToken$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: takePushDeregistrations = function takePushDeregistrations(action) { return action.type === actionTypes.ENABLE_NOTIFICATION_CHANNEL && action.meta.channel === 'PUSH' && !action.payload.channelEnabled; }; // Redux-saga take() pattern. // Take 'disable PUSH channel' actions. case 1: if (false) {} _context4.next = 4; return (0, _effects.take)(takePushDeregistrations); case 4: action = _context4.sent; _context4.next = 7; return (0, _effects.select)(_selectors2.getConnectionInfo); case 7: connection = _context4.sent; _context4.next = 10; return (0, _effects.select)(_selectors.getNotificationConfig); case 10: _ref3 = _context4.sent; pushRegistration = _ref3.pushRegistration; realm = _ref3.realm; // If a push registration endpoint was configured, use that instead of default. if (pushRegistration) { connection.server = (0, _fp.defaults)(connection.server, pushRegistration); connection.protocol = (0, _fp.defaults)(connection.protocol, pushRegistration); connection.port = (0, _fp.defaults)(connection.port, pushRegistration); connection.version = (0, _fp.defaults)(connection.version, pushRegistration); } connection.realm = realm; _context4.next = 17; return (0, _effects.select)(_selectors.getNotificationsInfo, action.meta.channel); case 17: pushInfo = _context4.sent; log.debug('De-registering device token for push notifications.'); _context4.next = 21; return (0, _effects.call)(requests.pushNotificationsDeRegistration, connection, pushInfo); case 21: response = _context4.sent; if (!response.error) { _context4.next = 27; break; } _context4.next = 25; return (0, _effects.put)(actions.enableNotificationChannelFinish(action.meta.channel, { params: action.payload, error: response.text })); case 25: _context4.next = 29; break; case 27: _context4.next = 29; return (0, _effects.put)(actions.enableNotificationChannelFinish(action.meta.channel, { params: action.payload })); case 29: _context4.next = 1; break; case 31: case 'end': return _context4.stop(); } } }, _marked4, this); } function enableWebsocketChannel() { var takeWebsocketChannel, action; return _regenerator2.default.wrap(function enableWebsocketChannel$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: takeWebsocketChannel = function takeWebsocketChannel(action) { return action.type === actionTypes.ENABLE_NOTIFICATION_CHANNEL && action.meta.channel === 'WEBSOCKET'; }; // Redux-saga take() pattern. // Take 'WEBSOCKET channel' actions. case 1: if (false) {} _context5.next = 4; return (0, _effects.take)(takeWebsocketChannel); case 4: action = _context5.sent; if (action.payload.enable) {} // TODO: If websockets are not connected, connect them here. // TODO: Handle possible error case when connecting websockets. // Otherwise, plain dispatch to update state. _context5.next = 8; return (0, _effects.put)(actions.enableNotificationChannelFinish(action.meta.channel, { params: action.payload })); case 8: _context5.next = 1; break; case 10: case 'end': return _context5.stop(); } } }, _marked5, this); } /***/ }), /***/ "./src/predicates.js": /*!***************************!*\ !*** ./src/predicates.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.cloud = exports.link = exports.types = exports.platform = exports.type = exports.or = exports.and = exports.matches = undefined; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _constants = __webpack_require__(/*! ./constants */ "./src/constants.js"); exports.matches = _fp.matches; // Constants var and = exports.and = function and() { for (var _len = arguments.length, operands = Array(_len), _key = 0; _key < _len; _key++) { operands[_key] = arguments[_key]; } return (0, _fp.overEvery)(operands); }; var or = exports.or = function or() { for (var _len2 = arguments.length, operands = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { operands[_key2] = arguments[_key2]; } return (0, _fp.overSome)(operands); }; var type = exports.type = function type(_type) { return (0, _fp.matches)({ type: _type }); }; var platform = exports.platform = function platform(_platform) { return (0, _fp.matches)({ meta: { platform: _platform } }); }; var types = exports.types = function types() { for (var _len3 = arguments.length, _types = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { _types[_key3] = arguments[_key3]; } return (0, _fp.overSome)((0, _fp.map)(type, _types)); }; var link = exports.link = platform(_constants.platforms.LINK); var cloud = exports.cloud = platform(_constants.platforms.CLOUD); /***/ }), /***/ "./src/presence/index.js": /*!*******************************!*\ !*** ./src/presence/index.js ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _interface = __webpack_require__(/*! ./interface */ "./src/presence/interface/index.js"); var _sagas = __webpack_require__(/*! ./sagas */ "./src/presence/sagas.js"); var sagas = _interopRequireWildcard(_sagas); var _events = __webpack_require__(/*! ./interface/events */ "./src/presence/interface/events.js"); var _events2 = _interopRequireDefault(_events); var _actions = __webpack_require__(/*! ../events/interface/actions */ "./src/events/interface/actions.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } // Libraries // Presence plugin. var name = 'presence'; // Other plugins. var capabilities = ['presence']; exports.default = function () { return { name: name, capabilities: capabilities, api: _interface.api, reducer: _interface.reducer, init: function init() { return [(0, _effects.put)((0, _actions.mapEvents)(_events2.default))]; }, sagas: (0, _fp.values)(sagas) }; }; /***/ }), /***/ "./src/presence/interface/actionTypes.js": /*!***********************************************!*\ !*** ./src/presence/interface/actionTypes.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var prefix = '@@KANDY/PRESENCE/'; var UPDATE = exports.UPDATE = prefix + 'UPDATE'; var UPDATE_FINISH = exports.UPDATE_FINISH = prefix + 'UPDATE_FINISH'; var GET = exports.GET = prefix + 'GET'; var GET_FINISH = exports.GET_FINISH = prefix + 'GET_FINISH'; var SUBSCRIBE = exports.SUBSCRIBE = prefix + 'SUBSCRIBE'; var SUBSCRIBE_FINISH = exports.SUBSCRIBE_FINISH = prefix + 'SUBSCRIBE_FINISH'; var UNSUBSCRIBE = exports.UNSUBSCRIBE = prefix + 'UNSUBSCRIBE'; var UNSUBSCRIBE_FINISH = exports.UNSUBSCRIBE_FINISH = prefix + 'UNSUBSCRIBE_FINISH'; var RECEIVED = exports.RECEIVED = prefix + 'RECEIVED'; /***/ }), /***/ "./src/presence/interface/actions.js": /*!*******************************************!*\ !*** ./src/presence/interface/actions.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.updatePresence = updatePresence; exports.updatePresenceFinish = updatePresenceFinish; exports.getPresence = getPresence; exports.getPresenceFinish = getPresenceFinish; exports.subscribePresence = subscribePresence; exports.subscribePresenceFinish = subscribePresenceFinish; exports.unsubscribePresence = unsubscribePresence; exports.unsubscribePresenceFinish = unsubscribePresenceFinish; exports.presenceReceived = presenceReceived; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/presence/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Update the presence for the current user * @param {string} status The status of the presence state * @param {string} activity The activity to be shown as presence state * @param {string} note The note to be shown as alternative presence state * which is determined by the user. The note entry is * effective on the remote sip client when the * activity is “other”. * @return {Object} A Flux Standard Action for UPDATE_PRESENCE */ function updatePresence(status, activity, note) { return { type: actionTypes.UPDATE, payload: { status: status, activity: activity, note: note } }; } function updatePresenceFinish(payload) { return { type: actionTypes.UPDATE_FINISH, error: payload instanceof Error, payload: payload }; } /** * Get the presence for the given user(s) * @param {string} users A user id or an array of user ids. * @return {Object} A Flux Standard Action for GET_PRESENCE */ function getPresence(users) { return { type: actionTypes.GET, payload: users }; } function getPresenceFinish(payload) { return { type: actionTypes.GET_FINISH, error: payload instanceof Error, payload: payload }; } /** * Subscribe to the presence for the given user(s) * @param {string} users A user id or an array of user ids. * @return {Object} A Flux Standard Action for SUBSCRIBE_PRESENCE */ function subscribePresence(users) { return { type: actionTypes.SUBSCRIBE, payload: users }; } function subscribePresenceFinish(payload) { return { type: actionTypes.SUBSCRIBE_FINISH, error: payload instanceof Error, payload: payload }; } /** * Unsubscribe from the presence for the given user(s) * @param {string} users A user id or an array of user ids. * @return {Object} A Flux Standard Action for UNSUBSCRIBE_PRESENCE */ function unsubscribePresence(users) { return { type: actionTypes.UNSUBSCRIBE, payload: users }; } function unsubscribePresenceFinish(payload) { return { type: actionTypes.UNSUBSCRIBE_FINISH, error: payload instanceof Error, payload: payload }; } function presenceReceived(_ref) { var name = _ref.name, status = _ref.status, activity = _ref.activity, note = _ref.note; return { type: actionTypes.RECEIVED, payload: { userId: name, status: status, activity: activity, note: note } }; } /***/ }), /***/ "./src/presence/interface/api.js": /*!***************************************!*\ !*** ./src/presence/interface/api.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ACTIVITY = exports.STATUS = undefined; var _values = __webpack_require__(/*! babel-runtime/core-js/object/values */ "../../node_modules/babel-runtime/core-js/object/values.js"); var _values2 = _interopRequireDefault(_values); exports.default = function (context) { var presenceApi = { /** * Update the presence for the current user * * @public * @memberof Presence * @requires presence * @method update * @param {string} status The status of the presence state * @param {string} activity The activity to be shown as presence state * @param {string} note The note to be shown as alternative presence state which is determined by the user. The note entry is effective on the remote sip client when the activity is “other”. */ update: function update(status, activity, note) { if ((0, _values2.default)(STATUS).indexOf(status) === -1) { throw new Error('Invalid status.'); } if ((0, _values2.default)(ACTIVITY).indexOf(activity) === -1) { throw new Error('Invalid activity.'); } context.dispatch(actions.updatePresence(status, activity, note)); }, /** * Get (from state) the presence for the given user(s) * * @public * @memberof Presence * @requires presence * @method get * @param {string} [users] A user id or an array of user ids. * @return An array of presence objects containing: * userId, * loading, * status, * activity, * and note. * Or, if a userId was provided instead of an array, returns * the corresponding presence object or `undefined`. */ get: function get(users) { var storedUsers = selectors.getPresence(context.getState(), users); // return something sensible based on the input if (!Array.isArray(users)) { if (storedUsers.length) { return storedUsers[0]; } return undefined; } return storedUsers; }, /** * Fetch (from the server) the presence for the given users. * This will update the store with the retrieved values, which can then * be accessed using `getPresence`. * * @public * @memberof Presence * @requires presence * @method fetch * @param {string} users A user id or an array of user ids. */ fetch: function fetch(users) { context.dispatch(actions.getPresence(users)); }, /** * Subscribe to the presence of the given user(s). * * @public * @memberof Presence * @requires presence * @method subscribe * @param {string} users A user id or an array of user ids. */ subscribe: function subscribe(users) { context.dispatch(actions.subscribePresence(users)); }, /** * Unsubscribe from the presence of the given user(s). * * @public * @memberof Presence * @requires presence * @method unsubscribe * @param {string} users A user id or an array of user ids. */ unsubscribe: function unsubscribe(users) { context.dispatch(actions.unsubscribePresence(users)); } }; return { presence: presenceApi }; }; var _actions = __webpack_require__(/*! ./actions */ "./src/presence/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(/*! ./selectors */ "./src/presence/interface/selectors.js"); var selectors = _interopRequireWildcard(_selectors); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The status of the presence state * @name STATUS */ /** * Kandy's presence functions are used to update the authenticated users presence * on the server, as well as retrieve other users presence information. * * Presence functions are namespaced beneath 'presence' on the returned Kandy object. * * @public * @requires presence * @module Presence */ var STATUS = exports.STATUS = { OPEN: 'open', CLOSED: 'closed' /** * The activity to be shown as presence state * @name ACTIVITY */ };var ACTIVITY = exports.ACTIVITY = { ACTIVE: 'active', IDLE: 'idle', AWAY: 'away', LUNCH: 'lunch', OTHER: 'other', BUSY: 'busy', VACATION: 'vacation', ON_THE_PHONE: 'on-the-phone', UNKNOWN: 'unknown' }; /***/ }), /***/ "./src/presence/interface/eventTypes.js": /*!**********************************************!*\ !*** ./src/presence/interface/eventTypes.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Received a presence event. * * @public * @memberof Presence * @requires presence * @event presence:change * @param {Object} params A presence object containing data. * @param {string} params.userId The ID of the user. * @param {string} params.status The presence status of the user. * @param {string} params.activity The activity of the user. * @param {string} params.note A custom note provided by the user. */ var RECEIVED = exports.RECEIVED = 'presence:change'; /** * An error occured with presence. * * @public * @memberof Presence * @requires presence * @event presence:error * @param {Object} params * @param {KandyError} params.error The Kandy error object. */ var ERROR = exports.ERROR = 'presence:error'; /***/ }), /***/ "./src/presence/interface/events.js": /*!******************************************!*\ !*** ./src/presence/interface/events.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/presence/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/presence/interface/eventTypes.js"); var eventTypes = _interopRequireWildcard(_eventTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } // Helper function for error events. function presenceError(action) { if (action.error) { return { type: eventTypes.ERROR, args: { error: action.payload } }; } } var eventsMap = {}; eventsMap[actionTypes.RECEIVED] = function (action) { return { type: eventTypes.RECEIVED, args: { userId: action.payload.userId, status: action.payload.status, activity: action.payload.activity, note: action.payload.note } }; }; // TODO: Should have events to notifiy of successful operations for these actions. eventsMap[actionTypes.UPDATE_FINISH] = presenceError; eventsMap[actionTypes.GET_FINISH] = presenceError; eventsMap[actionTypes.SUBSCRIBE_FINISH] = presenceError; eventsMap[actionTypes.UNSUBSCRIBE_FINISH] = presenceError; exports.default = eventsMap; /***/ }), /***/ "./src/presence/interface/index.js": /*!*****************************************!*\ !*** ./src/presence/interface/index.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _api = __webpack_require__(/*! ./api */ "./src/presence/interface/api.js"); Object.defineProperty(exports, 'api', { enumerable: true, get: function get() { return _interopRequireDefault(_api).default; } }); var _reducers = __webpack_require__(/*! ./reducers */ "./src/presence/interface/reducers.js"); Object.defineProperty(exports, 'reducer', { enumerable: true, get: function get() { return _interopRequireDefault(_reducers).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), /***/ "./src/presence/interface/reducers.js": /*!********************************************!*\ !*** ./src/presence/interface/reducers.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = __webpack_require__(/*! babel-runtime/helpers/defineProperty */ "../../node_modules/babel-runtime/helpers/defineProperty.js"); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _getIterator2 = __webpack_require__(/*! babel-runtime/core-js/get-iterator */ "../../node_modules/babel-runtime/core-js/get-iterator.js"); var _getIterator3 = _interopRequireDefault(_getIterator2); var _extends3 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends4 = _interopRequireDefault(_extends3); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/presence/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var reducers = {}; reducers[actionTypes.UPDATE] = { next: function next(state) { return (0, _extends4.default)({}, state, { self: (0, _extends4.default)({}, state.self, { loading: true, error: false }) }); } }; reducers[actionTypes.UPDATE_FINISH] = { next: function next(state, action) { return (0, _extends4.default)({}, state, { self: { loading: false, error: false, status: action.payload.status, activity: action.payload.activity, note: action.payload.note } }); }, throw: function _throw(state, action) { return (0, _extends4.default)({}, state, { self: (0, _extends4.default)({}, state.self, { loading: false, error: action.payload }) }); } }; reducers[actionTypes.GET] = { next: function next(state, _ref) { var userIds = _ref.payload; var users = (0, _extends4.default)({}, state.users); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = (0, _getIterator3.default)(userIds), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var userId = _step.value; users[userId] = { userId: userId, loading: true }; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return (0, _extends4.default)({}, state, { users: users }); } }; reducers[actionTypes.RECEIVED] = { next: function next(state, _ref2) { var payload = _ref2.payload; return (0, _extends4.default)({}, state, { users: (0, _extends4.default)({}, state.users, (0, _defineProperty3.default)({}, payload.userId, { userId: payload.userId, // optimize for filtering by userId status: payload.status, activity: payload.activity, note: payload.note })) }); } }; var reducer = (0, _reduxActions.handleActions)(reducers, { self: {}, users: {} }); exports.default = reducer; /***/ }), /***/ "./src/presence/interface/selectors.js": /*!*********************************************!*\ !*** ./src/presence/interface/selectors.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _values = __webpack_require__(/*! babel-runtime/core-js/object/values */ "../../node_modules/babel-runtime/core-js/object/values.js"); var _values2 = _interopRequireDefault(_values); exports.getPresence = getPresence; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getPresence(state, users) { // If no users specified, return them all if (!users) { return state.presence.users; } // If only a single user is specified, put that user into an array if (!Array.isArray(users)) { users = [users]; } // Grab all users that match the passed in IDs, return them return (0, _values2.default)(state.presence.users).filter(function (user) { return users.indexOf(user.userId) !== -1; }); } /***/ }), /***/ "./src/presence/requests.js": /*!**********************************!*\ !*** ./src/presence/requests.js ***! \**********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.updatePresenceRequest = updatePresenceRequest; exports.watchPresenceRequest = watchPresenceRequest; var _effects = __webpack_require__(/*! ../request/effects */ "./src/request/effects.js"); var _effects2 = _interopRequireDefault(_effects); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(updatePresenceRequest), _marked2 = /*#__PURE__*/_regenerator2.default.mark(watchPresenceRequest); // Request // Logs var log = (0, _logs.getLogManager)().getLogger('PRESENCE'); function updatePresenceRequest(_ref, requestInfo) { var status = _ref.status, activity = _ref.activity, note = _ref.note; var url, data, body, method, response, statusCode, message; return _regenerator2.default.wrap(function updatePresenceRequest$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: url = requestInfo.baseURL + '/rest/version/' + requestInfo.version + '/user/' + requestInfo.username + '/presence'; data = { status: status, activity: activity }; if (note) { data.note = note; } body = (0, _stringify2.default)({ presenceRequest: data }); method = 'POST'; _context.next = 7; return (0, _effects2.default)({ url: url, body: body, method: method }, requestInfo.requestOptions); case 7: response = _context.sent; if (!response.error) { _context.next = 20; break; } if (!response.payload.body) { _context.next = 15; break; } // Handle errors from the server. statusCode = response.payload.body.presenceResponse.statusCode; log.debug('Failed to update presence with status code ' + statusCode + '.'); // TODO: Proper error. return _context.abrupt('return', new Error('Failed to update presence with status code ' + statusCode + '.')); case 15: // Handle errors from the request helper. message = response.payload.result.message; log.debug('Update presence request failed: ' + message + '.'); // TODO: Proper error. return _context.abrupt('return', new Error('Update presence request failed: ' + message + '.')); case 18: _context.next = 23; break; case 20: if (!(response.payload.body.presenceResponse.statusCode === 0)) { _context.next = 22; break; } return _context.abrupt('return', true); case 22: return _context.abrupt('return', new Error('Failed to update presence. Code: ' + response.payload.body.presenceResponse.statusCode + '.')); case 23: case 'end': return _context.stop(); } } }, _marked, this); } /** * Make a request to the presenceWatcher resource * @param {array<User>} users a lits of users for the watch request * @param {string} action watch Starts watching the presence updates * for the users in the users array. * stopwatch Stops watching the presence updates * for the users in the users array. * get Gets the presence updates one time * only for the users in the users array. */ function watchPresenceRequest(users, action, requestInfo) { var url, body, method, response, statusCode, message; return _regenerator2.default.wrap(function watchPresenceRequest$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: url = requestInfo.baseURL + '/rest/version/' + requestInfo.version + '/user/' + requestInfo.username + '/presenceWatcher'; body = (0, _stringify2.default)({ presenceWatcherRequest: { userList: users, action: action } }); method = 'POST'; _context2.next = 5; return (0, _effects2.default)({ url: url, method: method, body: body }, requestInfo.requestOptions); case 5: response = _context2.sent; if (!response.error) { _context2.next = 18; break; } if (!response.payload.body) { _context2.next = 13; break; } // Handle errors from the server. statusCode = response.payload.body.presenceWatcherResponse.statusCode; log.debug('Failed to watch presence with status code ' + statusCode + '.'); // TODO: Proper error. return _context2.abrupt('return', new Error('Failed to watch presence with status code ' + statusCode + '.')); case 13: // Handle errors from the request helper. message = response.payload.result.message; log.debug('Watch presence request failed: ' + message + '.'); // TODO: Proper error. return _context2.abrupt('return', new Error('Watch presence request failed: ' + message + '.')); case 16: _context2.next = 21; break; case 18: if (!(response.payload.body.presenceWatcherResponse.statusCode === 0)) { _context2.next = 20; break; } return _context2.abrupt('return', response.payload.body); case 20: return _context2.abrupt('return', new Error('Failed to execute presence operation (' + action + '). Code: ' + response.payload.body.presenceResponse.statusCode + '.')); case 21: case 'end': return _context2.stop(); } } }, _marked2, this); } /***/ }), /***/ "./src/presence/sagas.js": /*!*******************************!*\ !*** ./src/presence/sagas.js ***! \*******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.presenceUpdateSaga = presenceUpdateSaga; exports.presenceGetSaga = presenceGetSaga; exports.presenceSubscribeSaga = presenceSubscribeSaga; exports.presenceUnsubscribeSaga = presenceUnsubscribeSaga; exports.presenceReceivedSaga = presenceReceivedSaga; var _actionTypes = __webpack_require__(/*! ./interface/actionTypes */ "./src/presence/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _actions = __webpack_require__(/*! ./interface/actions */ "./src/presence/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _requests = __webpack_require__(/*! ./requests */ "./src/presence/requests.js"); var _selectors = __webpack_require__(/*! ../auth/interface/selectors */ "./src/auth/interface/selectors.js"); var _actionTypes2 = __webpack_require__(/*! ../notifications/interface/actionTypes */ "./src/notifications/interface/actionTypes.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _constants = __webpack_require__(/*! ../constants */ "./src/constants.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(presenceUpdateSaga), _marked2 = /*#__PURE__*/_regenerator2.default.mark(presenceGetSaga), _marked3 = /*#__PURE__*/_regenerator2.default.mark(presenceSubscribeSaga), _marked4 = /*#__PURE__*/_regenerator2.default.mark(presenceUnsubscribeSaga), _marked5 = /*#__PURE__*/_regenerator2.default.mark(presenceReceivedSaga), _marked6 = /*#__PURE__*/_regenerator2.default.mark(updatePresence), _marked7 = /*#__PURE__*/_regenerator2.default.mark(getPresence), _marked8 = /*#__PURE__*/_regenerator2.default.mark(subscribePresence), _marked9 = /*#__PURE__*/_regenerator2.default.mark(unsubscribePresence), _marked10 = /*#__PURE__*/_regenerator2.default.mark(receivePresence); // Presence plugin. // Other plugins. // Libraries. // Constants function presenceUpdateSaga() { return _regenerator2.default.wrap(function presenceUpdateSaga$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.takeEvery)(actionTypes.UPDATE, updatePresence); case 2: case 'end': return _context.stop(); } } }, _marked, this); } function presenceGetSaga() { return _regenerator2.default.wrap(function presenceGetSaga$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return (0, _effects.takeEvery)(actionTypes.GET, getPresence); case 2: case 'end': return _context2.stop(); } } }, _marked2, this); } function presenceSubscribeSaga() { return _regenerator2.default.wrap(function presenceSubscribeSaga$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return (0, _effects.takeEvery)(actionTypes.SUBSCRIBE, subscribePresence); case 2: case 'end': return _context3.stop(); } } }, _marked3, this); } function presenceUnsubscribeSaga() { return _regenerator2.default.wrap(function presenceUnsubscribeSaga$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return (0, _effects.takeEvery)(actionTypes.UNSUBSCRIBE, unsubscribePresence); case 2: case 'end': return _context4.stop(); } } }, _marked4, this); } function presenceReceivedSaga() { return _regenerator2.default.wrap(function presenceReceivedSaga$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return (0, _effects.takeEvery)(function (action) { return action.type === _actionTypes2.NOTIFICATION_RECEIVED && action.payload.notificationMessage && action.payload.notificationMessage.eventType === 'presenceWatcher'; }, receivePresence); case 2: case 'end': return _context5.stop(); } } }, _marked5, this); } function updatePresence(_ref) { var payload = _ref.payload; var requestInfo, platform, res; return _regenerator2.default.wrap(function updatePresence$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return (0, _effects.select)(_selectors.getRequestInfo); case 2: requestInfo = _context6.sent; _context6.next = 5; return (0, _effects.select)(_selectors.getPlatform); case 5: platform = _context6.sent; requestInfo.version = platform === _constants.platforms.CPAAS ? 1 : requestInfo.version; _context6.next = 9; return (0, _effects.call)(_requests.updatePresenceRequest, payload, requestInfo); case 9: res = _context6.sent; if (!(res instanceof Error)) { _context6.next = 15; break; } _context6.next = 13; return (0, _effects.put)(actions.updatePresenceFinish(res)); case 13: _context6.next = 17; break; case 15: _context6.next = 17; return (0, _effects.put)(actions.updatePresenceFinish(payload)); case 17: case 'end': return _context6.stop(); } } }, _marked6, this); } function getPresence(_ref2) { var payload = _ref2.payload; var users, requestInfo, platform, res; return _regenerator2.default.wrap(function getPresence$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: users = Array.isArray(payload) ? payload : [payload]; _context7.next = 3; return (0, _effects.select)(_selectors.getRequestInfo); case 3: requestInfo = _context7.sent; _context7.next = 6; return (0, _effects.select)(_selectors.getPlatform); case 6: platform = _context7.sent; requestInfo.version = platform === _constants.platforms.CPAAS ? 1 : requestInfo.version; _context7.next = 10; return (0, _effects.call)(_requests.watchPresenceRequest, users, 'get', requestInfo); case 10: res = _context7.sent; _context7.next = 13; return (0, _effects.put)(actions.getPresenceFinish(res)); case 13: case 'end': return _context7.stop(); } } }, _marked7, this); } function subscribePresence(_ref3) { var payload = _ref3.payload; var users, requestInfo, platform, res; return _regenerator2.default.wrap(function subscribePresence$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: users = Array.isArray(payload) ? payload : [payload]; _context8.next = 3; return (0, _effects.select)(_selectors.getRequestInfo); case 3: requestInfo = _context8.sent; _context8.next = 6; return (0, _effects.select)(_selectors.getPlatform); case 6: platform = _context8.sent; requestInfo.version = platform === _constants.platforms.CPAAS ? 1 : requestInfo.version; _context8.next = 10; return (0, _effects.call)(_requests.watchPresenceRequest, users, 'watch', requestInfo); case 10: res = _context8.sent; _context8.next = 13; return (0, _effects.put)(actions.subscribePresenceFinish(res)); case 13: case 'end': return _context8.stop(); } } }, _marked8, this); } function unsubscribePresence(_ref4) { var payload = _ref4.payload; var users, requestInfo, platform, res; return _regenerator2.default.wrap(function unsubscribePresence$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: users = Array.isArray(payload) ? payload : [payload]; _context9.next = 3; return (0, _effects.select)(_selectors.getRequestInfo); case 3: requestInfo = _context9.sent; _context9.next = 6; return (0, _effects.select)(_selectors.getPlatform); case 6: platform = _context9.sent; requestInfo.version = platform === _constants.platforms.CPAAS ? 1 : requestInfo.version; _context9.next = 10; return (0, _effects.call)(_requests.watchPresenceRequest, users, 'stopwatch', requestInfo); case 10: res = _context9.sent; _context9.next = 13; return (0, _effects.put)(actions.unsubscribePresenceFinish(res)); case 13: case 'end': return _context9.stop(); } } }, _marked9, this); } function receivePresence(wsAction) { var params; return _regenerator2.default.wrap(function receivePresence$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: params = wsAction.payload.notificationMessage.presenceWatcherNotificationParams; _context10.next = 3; return (0, _effects.put)(actions.presenceReceived(params)); case 3: case 'end': return _context10.stop(); } } }, _marked10, this); } /***/ }), /***/ "./src/request/effects.js": /*!********************************!*\ !*** ./src/request/effects.js ***! \********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = request; var _actionTypes = __webpack_require__(/*! ./interface/actionTypes */ "./src/request/interface/actionTypes.js"); var _actions = __webpack_require__(/*! ./interface/actions */ "./src/request/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _utils = __webpack_require__(/*! ../common/utils */ "./src/common/utils.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(requestSaga); // Requests plugin. // Libraries. /** * Creates an effect description that instructs the middleware to perform a request with the provided options. * This effect is blocking and will yield a RESPONSE action on completion. * * @param {Object} options See https://developer.mozilla.org/en-US/docs/Web/API/Request/Request * @param {string} options.url The url to perform the request on. * @param {string} options.method The HTTP method to use for the request. * @param {Object} options.headers Object literal of headers you want to add to the request. * @param {Blob|BufferSource|FormData|UrlSearchParams|string} options.body Any body that you want to add to your request. * @return [type] [description] */ function request(options, commonOptions) { return (0, _effects.call)(requestSaga, options, commonOptions); } /* * The saga backing the request effect. */ function requestSaga(options, commonOptions) { var requestAction, responseAction; return _regenerator2.default.wrap(function requestSaga$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: // Merge any extra request options into the provided options // for this request. Priority is for the passed-in options. options = (0, _utils.mergeValues)(commonOptions, options); _context.next = 3; return (0, _effects.put)(actions.request(options)); case 3: requestAction = _context.sent; _context.next = 6; return (0, _effects.take)(function (action) { return action.type === _actionTypes.RESPONSE && (0, _fp.get)('meta.requestId', action) === requestAction.meta.requestId; }); case 6: responseAction = _context.sent; return _context.abrupt('return', responseAction); case 8: case 'end': return _context.stop(); } } }, _marked, this); } /***/ }), /***/ "./src/request/index.js": /*!******************************!*\ !*** ./src/request/index.js ***! \******************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = request; var _actionTypes = __webpack_require__(/*! ./interface/actionTypes */ "./src/request/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _actions = __webpack_require__(/*! ./interface/actions */ "./src/request/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _fetchPonyfill2 = __webpack_require__(/*! fetch-ponyfill */ "../../node_modules/fetch-ponyfill/build/fetch-browser.js"); var _fetchPonyfill3 = _interopRequireDefault(_fetchPonyfill2); var _promise = __webpack_require__(/*! babel-runtime/core-js/promise */ "../../node_modules/babel-runtime/core-js/promise.js"); var _promise2 = _interopRequireDefault(_promise); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); var _utils = __webpack_require__(/*! ../common/utils */ "./src/common/utils.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(watchRequests), _marked2 = /*#__PURE__*/_regenerator2.default.mark(handleRequest); var _fetchPonyfill = (0, _fetchPonyfill3.default)({ Promise: _promise2.default }), fetch = _fetchPonyfill.fetch; var log = (0, _logs.getLogManager)().getLogger('REQUEST'); /* * HTTP request plugin. */ function request() { return { sagas: [watchRequests], name: 'requests' }; } /* * Saga to watch for every request action. */ function watchRequests() { return _regenerator2.default.wrap(function watchRequests$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.takeEvery)(actionTypes.REQUEST, handleRequest); case 2: case 'end': return _context.stop(); } } }, _marked, this); } /* * Generator that handles a request action with standard HTTP handling features and reports * a requestFinished action when the request is done. * * @param {FluxStandardAction} action The action to handle. */ function handleRequest(action) { var result; return _regenerator2.default.wrap(function handleRequest$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return (0, _effects.call)(makeRequest, action.payload, action.meta.requestId); case 2: result = _context2.sent; _context2.next = 5; return (0, _effects.put)(actions.response(action.meta.requestId, result, !!result.error)); case 5: case 'end': return _context2.stop(); } } }, _marked2, this); } /* * Make a request with the specified options. The options is very similar to the options passed to the GlobalFetch * method except that is also accepts the url as part of the options. * * Currently this processes the request and assumes nothing about the response. * - If the response has a body, it will always be parsed and forwarded on. * - If no body, then an empty object in its place. * - If the fetch succeded, the response "results" will always be forwarded on, * even if the response is outside of the 200-299 range. * - Because some backends provide more detailed error info (that a saga * may need) as part of the body, rather than just the response status. * * @param {Object} options Options to make the request with. * @param {string} options.url The URL to make the request to. * @return {Promise} A promise that resolves with a custom response object. */ function makeRequest(options, requestId) { // Extract and remove the url property. var optionsCopy = (0, _extends3.default)({}, options); var url = optionsCopy.url, queryParams = optionsCopy.queryParams; delete optionsCopy.url; delete optionsCopy.queryParams; return fetch(url + (0, _utils.toQueryString)(queryParams), optionsCopy).then(function (response) { // Information about the result of the actual fetch request. var result = { ok: response.ok, code: response.status, message: response.statusText }; var error = response.ok ? false : 'REQUEST'; // TODO: Check response.headers.get('Content-Type') to see if its json? // Check whether there is a JSON body or not. If not, provide a dummy response. return response.json().then(function (responseBody) { return { body: responseBody, error: error, result: result }; }).catch(function (err) { log.debug('Error parsing JSON \'' + err + '\' response for request ' + requestId + '.'); return { body: false, error: error, result: result }; }); }).catch(function (error) { // Scenario: fetch failed, and so went straight to catch. // Only the fetch error is provided here; there is no response. // Ref: https://github.com/github/fetch/issues/201#issuecomment-308213104 log.debug('Fetch request ' + requestId + ' failed: ' + error.message + '.'); // TODO: Improve this error checking / Provide info on what the // error was? return { body: false, error: 'FETCH', result: { ok: false, code: error.name, message: error.message } }; }); } /***/ }), /***/ "./src/request/interface/actionTypes.js": /*!**********************************************!*\ !*** ./src/request/interface/actionTypes.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PREFIX = '@@KANDY/'; var REQUEST = exports.REQUEST = PREFIX + 'REQUEST'; var RESPONSE = exports.RESPONSE = PREFIX + 'RESPONSE'; /***/ }), /***/ "./src/request/interface/actions.js": /*!******************************************!*\ !*** ./src/request/interface/actions.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.request = request; exports.response = response; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/request/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var nextRequestId = 0; function generateRequestId() { return nextRequestId++; } /** * Creates a request action. */ function request(options) { return { type: actionTypes.REQUEST, payload: options, meta: { requestId: generateRequestId() } }; } /** * Creates a response action. */ function response(requestId, result) { var error = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; return { type: actionTypes.RESPONSE, payload: result, error: error, meta: { requestId: requestId } }; } /***/ }), /***/ "./src/sipEvents/index.js": /*!********************************!*\ !*** ./src/sipEvents/index.js ***! \********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = sipEvents; var _interface = __webpack_require__(/*! ./interface */ "./src/sipEvents/interface/index.js"); var _interface2 = _interopRequireDefault(_interface); var _sagas = __webpack_require__(/*! ./sagas */ "./src/sipEvents/sagas.js"); var sagas = _interopRequireWildcard(_sagas); var _events = __webpack_require__(/*! ./interface/events */ "./src/sipEvents/interface/events.js"); var _events2 = _interopRequireDefault(_events); var _actions = __webpack_require__(/*! ../events/interface/actions */ "./src/events/interface/actions.js"); var _effects = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Sip Events Plugin Factory. * @method sipEvents * @return {Object} Sip Events plugin. */ // Libraries. // Sip Events plugin. function sipEvents() { var _marked = /*#__PURE__*/_regenerator2.default.mark(init); var name = _interface2.default.name, api = _interface2.default.api, reducer = _interface2.default.reducer; var capabilities = ['sipEvents']; function init() { return _regenerator2.default.wrap(function init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects.put)((0, _actions.mapEvents)(_events2.default)); case 2: case 'end': return _context.stop(); } } }, _marked, this); } return { name: name, init: init, api: api, reducer: reducer, capabilities: capabilities, sagas: (0, _fp.values)(sagas) }; } // Other plugins. /***/ }), /***/ "./src/sipEvents/interface/actionTypes.js": /*!************************************************!*\ !*** ./src/sipEvents/interface/actionTypes.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var PREFIX = '@@KANDY/'; var SIP_EVENT_SUBSCRIBE = exports.SIP_EVENT_SUBSCRIBE = PREFIX + 'SIP_EVENT_SUBSCRIBE'; var SIP_EVENT_SUBSCRIBE_FINISH = exports.SIP_EVENT_SUBSCRIBE_FINISH = PREFIX + 'SIP_EVENT_SUBSCRIBE_FINISH'; var SIP_EVENT_UPDATE = exports.SIP_EVENT_UPDATE = PREFIX + 'SIP_EVENT_UPDATE'; var SIP_EVENT_UPDATE_FINISH = exports.SIP_EVENT_UPDATE_FINISH = PREFIX + 'SIP_EVENT_UPDATE_FINISH'; var SIP_EVENT_UNSUBSCRIBE = exports.SIP_EVENT_UNSUBSCRIBE = PREFIX + 'SIP_EVENT_UNSUBSCRIBE'; var SIP_EVENT_UNSUBSCRIBE_FINISH = exports.SIP_EVENT_UNSUBSCRIBE_FINISH = PREFIX + 'SIP_EVENT_UNSUBSCRIBE_FINISH'; var SIP_EVENT_RECEIVED = exports.SIP_EVENT_RECEIVED = PREFIX + 'SIP_EVENT_RECEIVED'; /***/ }), /***/ "./src/sipEvents/interface/actions.js": /*!********************************************!*\ !*** ./src/sipEvents/interface/actions.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _keys = __webpack_require__(/*! babel-runtime/core-js/object/keys */ "../../node_modules/babel-runtime/core-js/object/keys.js"); var _keys2 = _interopRequireDefault(_keys); exports.sipEventSubscribe = sipEventSubscribe; exports.sipEventSubscribeFinish = sipEventSubscribeFinish; exports.sipEventUpdate = sipEventUpdate; exports.sipEventUpdateFinish = sipEventUpdateFinish; exports.sipEventUnsubscribe = sipEventUnsubscribe; exports.sipEventUnsubscribeFinish = sipEventUnsubscribeFinish; exports.sipEventReceived = sipEventReceived; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/sipEvents/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Helper function for formatting _FINISH actions. function finishActionHelper(actionType, _ref) { var response = _ref.response, error = _ref.error; return { type: actionType, error: !!error, payload: error || response }; } /** * Represents a request to subscribe to a specific sip event. * @method sipEventSubscribe * @param {string} eventType * @param {Array} subscribeUserList * @param {string} clientCorrelator * @param {Object} customParameters * @returns {Object} A flux standard action. */ function sipEventSubscribe(eventType, subscribeUserList, clientCorrelator, customParameters) { return { type: actionTypes.SIP_EVENT_SUBSCRIBE, payload: { eventType: eventType, subscribeUserList: subscribeUserList, clientCorrelator: clientCorrelator, customParameters: customParameters } }; } /** * Represents the response/error of a sip event subscription request. * @method sipEventSubscribeFinish * @param {Object} $0 * @param {Object} $0.response Information about the subscription response. * @param {KandyError} $0.error An error object, in the case of an issue. * @returns {Object} A flux standard action. */ function sipEventSubscribeFinish(_ref2) { var response = _ref2.response, error = _ref2.error; return finishActionHelper(actionTypes.SIP_EVENT_SUBSCRIBE_FINISH, { response: response, error: error }); } /** * Represents a request to update a sip event subscription or resubscribe for it. * @method sipEventUpdate * @param {string} eventType * @param {Object} userLists * @param {Object} customParameters * @returns {Object} A flux standard action. */ function sipEventUpdate(eventType) { var userLists = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var customParameters = arguments[2]; // If no userList changes, this should just be a resubscription. var isResub = (0, _keys2.default)(userLists).length === 0; return { type: actionTypes.SIP_EVENT_UPDATE, payload: { eventType: eventType, subscribeUserList: userLists.subscribeUserList || [], unsubscribeUserList: userLists.unsubscribeUserList || [], customParameters: customParameters }, meta: isResub ? { isResub: true } : {} }; } /** * Represents the response/error of a sip event update/resub request. * @method sipEventUpdateFinish * @param {Object} $0 * @param {Object} $0.response Information about the update/resub response. * @param {KandyError} $0.error An error object, in the case of an issue. * @returns {Object} A flux standard action. */ function sipEventUpdateFinish(_ref3) { var response = _ref3.response, error = _ref3.error; return finishActionHelper(actionTypes.SIP_EVENT_UPDATE_FINISH, { response: response, error: error }); } /** * Represents a request to unsubscribe from sip event subscriptions. * @method sipEventUnsubscribe * @param {string} eventType The sip event subscription to unsubscribe from. * @returns {Object} A flux standard action. */ function sipEventUnsubscribe(eventType) { return { type: actionTypes.SIP_EVENT_UNSUBSCRIBE, payload: eventType }; } /** * Represents the response/error of a sip event unsubscribe request. * @method sipEventUnsubscribeFinish * @param {Object} $0 * @param {Object} $0.response Information about the unsubscribe response. * @param {KandyError} $0.error An error object, in the case of an issue. * @returns {Object} A flux standard action. */ function sipEventUnsubscribeFinish(_ref4) { var response = _ref4.response, error = _ref4.error; return finishActionHelper(actionTypes.SIP_EVENT_UNSUBSCRIBE_FINISH, { response: response, error: error }); } /** * Represents that a sip event notification has been received. * @method sipEventReceived * @param {Object} sipEvent * @returns {Object} A flux standard action. */ function sipEventReceived(sipEvent) { return { type: actionTypes.SIP_EVENT_RECEIVED, payload: sipEvent }; } /***/ }), /***/ "./src/sipEvents/interface/api.js": /*!****************************************!*\ !*** ./src/sipEvents/interface/api.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = api; var _selectors = __webpack_require__(/*! ./selectors */ "./src/sipEvents/interface/selectors.js"); var _actions = __webpack_require__(/*! ./actions */ "./src/sipEvents/interface/actions.js"); var actions = _interopRequireWildcard(_actions); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * Sip Events API. * @method api * @param {Object} $0 * @param {Function} $0.dispatch Redux dispatch. * @param {Function} $0.getState Redux getState. * @return {Object} Sip Events' plugin API. */ /** * Allows a user to subscribe to, and receive notifications for, sip events. * * SipEvents functions are namespaced beneath 'sip' on the returned Kandy object. * * @public * @requires sipEvents * @module SipEvents */ function api(_ref) { var dispatch = _ref.dispatch, getState = _ref.getState; var api = { /** * Subscribe for a sip event. * @public * @method subscribe * @requires sipEvents * @memberof SipEvents * @param {string} eventType The sip event type to subscribe for. * @param {Array} subscribeUserList The list of users to subcribe to. * @param {string} clientCorrelator * @param {Array} [customParameters] List of custom options provided as part of the subscription. */ subscribe: function subscribe(eventType, subscribeUserList, clientCorrelator) { var customParameters = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; dispatch(actions.sipEventSubscribe(eventType, subscribeUserList, clientCorrelator, customParameters)); }, /** * Update a subscription for a sip event. * @public * @method update * @requires sipEvents * @memberof SipEvents * @param {string} eventType The sip event subscription to update. * @param {Object} userLists * @param {Array} userLists.subscribeUserList The list of users to subcribe to. * @param {Array} userLists.unsubscribeUserList The list of users to unsubscribe from. If all users are unsubscribed from, the event subscription is removed completly. * @param {Array} [customParameters] List of custom options provided as part of the subscription. */ update: function update(eventType, userLists) { var customParameters = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; dispatch(actions.sipEventUpdate(eventType, userLists, customParameters)); }, /** * Unsubscribe from a sip event. * @public * @method unsubscribe * @requires sipEvents * @memberof SipEvents * @param {string} eventType The sip event to unsubscribe from. */ unsubscribe: function unsubscribe(eventType) { dispatch(actions.sipEventUnsubscribe(eventType)); }, /** * Retrieve information about a specified sip event. * @public * @method getDetails * @requires sipEvents * @memberof SipEvents * @param {string} [eventType] Type of sip event to retrieve. * @return {Object} Returns all information related to the chosen eventType that is contained in the store. If no eventType is specified, it will return information for all eventTypes. */ getDetails: function getDetails(eventType) { return (0, _selectors.getSipEventInfo)(getState(), eventType); } }; // Namespace the API. return { sip: api }; } /***/ }), /***/ "./src/sipEvents/interface/eventTypes.js": /*!***********************************************!*\ !*** ./src/sipEvents/interface/eventTypes.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * A change in SIP event subscriptions has occurred. * @public * @requires sipEvents * @memberof SipEvents * @event sip:subscriptionChange * @param {Object} params * @param {string} params.eventType The type of sip event. * @param {Object} params.change The change operation that occurred. * @param {Array} params.subscribedUsers Users that were subscribed to. * @param {Array} params.unsubscribedUsers Users that were unsubscribed from. */ var EVENT_SUBSCRIPTION_CHANGED = exports.EVENT_SUBSCRIPTION_CHANGED = 'sip:subscriptionChange'; /** * An error occurred while performing a SIP event action. * @public * @requires sipEvents * @memberof SipEvents * @event sip:error * @param {Object} params * @param {KandyError} params.error The Kandy error object. */ var EVENT_ERROR = exports.EVENT_ERROR = 'sip:error'; /** * A SIP event notification has been received. * @public * @requires sipEvents * @memberof SipEvents * @event sip:eventsChange * @param {Object} params Information about the notification. * @param {string} params.eventType The type of sip event. * @param {string} params.eventId The ID of the event. * @param {Object} params.event The full event object. */ var EVENT_RECEIVED = exports.EVENT_RECEIVED = 'sip:eventsChange'; /***/ }), /***/ "./src/sipEvents/interface/events.js": /*!*******************************************!*\ !*** ./src/sipEvents/interface/events.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/sipEvents/interface/eventTypes.js"); var eventTypes = _interopRequireWildcard(_eventTypes); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/sipEvents/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } // Helper function for formatting "changed" events. function subscriptionChange(_ref) { var change = _ref.change, action = _ref.action; if (action.error) { return { type: eventTypes.EVENT_ERROR, args: { error: action.payload } }; } else { return { type: eventTypes.EVENT_SUBSCRIPTION_CHANGED, args: { eventType: action.payload.eventType, change: change, subscribedUsers: action.payload.subscribedUsers, unsubscribedUsers: action.payload.unsubscribedUsers } }; } } var events = {}; events[actionTypes.SIP_EVENT_SUBSCRIBE_FINISH] = function (action) { return subscriptionChange({ change: 'newSubscription', action: action }); }; events[actionTypes.SIP_EVENT_UPDATE_FINISH] = function (action) { return subscriptionChange({ change: 'updateSubscription', action: action }); }; events[actionTypes.SIP_EVENT_UNSUBSCRIBE_FINISH] = function (action) { return subscriptionChange({ change: 'unsubscribe', action: action }); }; events[actionTypes.SIP_EVENT_RECEIVED] = function (action) { // Pass the notification straight through. return { type: eventTypes.EVENT_RECEIVED, args: { eventType: action.payload.eventType, eventId: action.payload.eventId, event: action.payload } }; }; exports.default = events; /***/ }), /***/ "./src/sipEvents/interface/index.js": /*!******************************************!*\ !*** ./src/sipEvents/interface/index.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _api = __webpack_require__(/*! ./api */ "./src/sipEvents/interface/api.js"); var _api2 = _interopRequireDefault(_api); var _reducer = __webpack_require__(/*! ./reducer */ "./src/sipEvents/interface/reducer.js"); var _reducer2 = _interopRequireDefault(_reducer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Import the components of the interface. var name = 'sipEvents'; exports.default = { name: name, api: _api2.default, reducer: _reducer2.default }; /***/ }), /***/ "./src/sipEvents/interface/reducer.js": /*!********************************************!*\ !*** ./src/sipEvents/interface/reducer.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = __webpack_require__(/*! babel-runtime/helpers/defineProperty */ "../../node_modules/babel-runtime/helpers/defineProperty.js"); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _extends5 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends6 = _interopRequireDefault(_extends5); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/sipEvents/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var reducers = {}; // Libraries. reducers[actionTypes.SIP_EVENT_SUBSCRIBE_FINISH] = { next: function next(state, action) { return (0, _extends6.default)({}, state, (0, _defineProperty3.default)({}, action.payload.eventType, { sessionData: action.payload.sessionData, subscribedUsers: action.payload.subscribedUsers })); } }; reducers[actionTypes.SIP_EVENT_UPDATE_FINISH] = { next: function next(state, action) { var subscribedUsers = state[action.payload.eventType].subscribedUsers; // Add the new subscribed users. subscribedUsers = (0, _fp.union)(action.payload.subscribeUserList, subscribedUsers); // Remove the unsubscribed users. subscribedUsers = (0, _fp.without)(action.payload.unsubscribeUserList, subscribedUsers); // Update the subscribed users for the sip event section. if (subscribedUsers.length === 0) { // If there are no subscribed users for this session, the session is deleted. var newState = (0, _extends6.default)({}, state); delete newState[action.payload.eventType]; return newState; } else { return (0, _extends6.default)({}, state, (0, _defineProperty3.default)({}, action.payload.eventType, (0, _extends6.default)({}, state[action.payload.eventType], { subscribedUsers: subscribedUsers }))); } } }; reducers[actionTypes.SIP_EVENT_UNSUBSCRIBE_FINISH] = { next: function next(state, action) { // Remove the specified sip event section. return (0, _fp.omit)(action.payload.eventType, state); } }; reducers[actionTypes.SIP_EVENT_RECEIVED] = function (state, action) { // Ensure everything is defined. var eventInfo = state[action.payload.eventType] || {}; var notifications = eventInfo.notifications || []; // Concat the notification to the specified sip event section. return (0, _extends6.default)({}, state, (0, _defineProperty3.default)({}, action.payload.eventType, (0, _extends6.default)({}, state[action.payload.eventType], { notifications: (0, _fp.concat)(notifications, action.payload) }))); }; var reducer = (0, _reduxActions.handleActions)(reducers, {}); exports.default = reducer; /***/ }), /***/ "./src/sipEvents/interface/selectors.js": /*!**********************************************!*\ !*** ./src/sipEvents/interface/selectors.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getSipEventInfo = getSipEventInfo; var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); /** * Retrieves information about a sip event. * @method getSipEventInfo * @param {string} eventType * @return {Object} */ function getSipEventInfo(state, eventType) { if (eventType) { return (0, _fp.cloneDeep)(state.sipEvents[eventType]); } else { return (0, _fp.cloneDeep)(state.sipEvents); } } /***/ }), /***/ "./src/sipEvents/sagas.js": /*!********************************!*\ !*** ./src/sipEvents/sagas.js ***! \********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); exports.sipEventSubscribe = sipEventSubscribe; exports.sipEventUpdate = sipEventUpdate; exports.sipEventUnsubscribe = sipEventUnsubscribe; exports.receiveEventNotify = receiveEventNotify; var _actionTypes = __webpack_require__(/*! ./interface/actionTypes */ "./src/sipEvents/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _actions = __webpack_require__(/*! ./interface/actions */ "./src/sipEvents/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(/*! ./interface/selectors */ "./src/sipEvents/interface/selectors.js"); var _selectors2 = __webpack_require__(/*! ../auth/interface/selectors */ "./src/auth/interface/selectors.js"); var _actionTypes2 = __webpack_require__(/*! ../notifications/interface/actionTypes */ "./src/notifications/interface/actionTypes.js"); var _effects = __webpack_require__(/*! ../request/effects */ "./src/request/effects.js"); var _effects2 = _interopRequireDefault(_effects); var _errors = __webpack_require__(/*! ../errors */ "./src/errors/index.js"); var _errors2 = _interopRequireDefault(_errors); var _reduxSaga = __webpack_require__(/*! redux-saga */ "../../node_modules/redux-saga/es/index.js"); var _effects3 = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); var _fp = __webpack_require__(/*! lodash/fp */ "../../node_modules/lodash/fp.js"); var _constants = __webpack_require__(/*! ../constants */ "./src/constants.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked = /*#__PURE__*/_regenerator2.default.mark(sipEventSubscribe), _marked2 = /*#__PURE__*/_regenerator2.default.mark(sipEventResub), _marked3 = /*#__PURE__*/_regenerator2.default.mark(sipEventUpdate), _marked4 = /*#__PURE__*/_regenerator2.default.mark(sipEventUnsubscribe), _marked5 = /*#__PURE__*/_regenerator2.default.mark(receiveEventNotify); // Sip Events plugin. // Other plugins. // Libraries. // Logs // Constants // Get the logger var log = (0, _logs.getLogManager)().getLogger('SIPEVENTS'); /** * Saga for subscribing to specified Sip Events. * @method sipEventSubscribe */ function sipEventSubscribe() { var action, _ref, subscribedServices, sipEvents, _ref2, expires, platform, _ref3, server, username, token, accessToken, commonOptions, requestOptions, response, error, statusCode, message, finishAction; return _regenerator2.default.wrap(function sipEventSubscribe$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (false) {} _context.next = 3; return (0, _effects3.take)(actionTypes.SIP_EVENT_SUBSCRIBE); case 3: action = _context.sent; // TODO: Have the client correlator be provided as a config, not through the API. log.debug('Subscribing for sip ' + action.payload.eventType + '.', action.payload.clientCorrelator); // Determine if the user is subscribed to the specified sip event. _context.next = 7; return (0, _effects3.select)(_selectors2.getServices); case 7: _ref = _context.sent; subscribedServices = _ref.received; sipEvents = subscribedServices.filter(function (service) { return service.startsWith('event:'); }); if ((0, _fp.includes)(action.payload.eventType, sipEvents)) { _context.next = 15; break; } log.info('Cannot subcribe to sip ' + action.payload.eventType + '; service not provisioned.'); _context.next = 14; return (0, _effects3.put)(actions.sipEventSubscribeFinish({ error: new _errors2.default({ code: _errors.sipEventCodes.NOT_PROVISIONED, message: 'Cannot subscribe to sip event; service was not provisioned during connection.' }) })); case 14: return _context.abrupt('continue', 0); case 15: _context.next = 17; return (0, _effects3.select)(_selectors2.getSubscriptionInfo); case 17: _ref2 = _context.sent; expires = _ref2.expires; _context.next = 21; return (0, _effects3.select)(_selectors2.getPlatform); case 21: platform = _context.sent; _context.next = 24; return (0, _effects3.select)(_selectors2.getConnectionInfo); case 24: _ref3 = _context.sent; server = _ref3.server; username = _ref3.username; token = _ref3.token; accessToken = _ref3.accessToken; commonOptions = _ref3.requestOptions; // TODO: CPaaS should store it's token the same way as Link. if (platform === _constants.platforms.CPAAS && !token) { token = accessToken; } requestOptions = {}; requestOptions.method = 'POST'; requestOptions.url = server.protocol + '://' + server.server + ':' + server.port + '/' + ('rest/version/' + server.version + '/') + ('user/' + username + '/') + 'eventSubscription'; requestOptions.body = { eventSubscriptionRequest: { subscribeUserList: action.payload.subscribeUserList, clientCorrelator: action.payload.clientCorrelator, eventType: action.payload.eventType, expires: expires } }; if (action.payload.customParameters.length) { requestOptions.body.eventSubscriptionRequest.customParameters = action.payload.customParameters; } requestOptions.body = (0, _stringify2.default)(requestOptions.body); _context.next = 39; return (0, _effects2.default)(requestOptions, commonOptions); case 39: response = _context.sent; if (!response.error) { _context.next = 47; break; } error = void 0; if (response.payload.body) { // Handle errors from the server. statusCode = response.payload.body.eventSubscriptionResponse.statusCode; log.info('Failed to subscribe to sip event ' + action.payload.eventType + ', ' + ('status code ' + statusCode)); error = new _errors2.default({ code: _errors.sipEventCodes.UNKNOWN_ERROR, message: 'Failed to subscribe to sip event ' + action.payload.eventType + ', ' + ('status code ' + statusCode) }); } else { // Handler errors from the request helper. message = response.payload.result.message; log.info('SIP event subscription request failed: ' + message + '.'); error = new _errors2.default({ code: _errors.sipEventCodes.UNKNOWN_ERROR, message: 'SIP event subscription request failed: ' + message + '.' }); } _context.next = 45; return (0, _effects3.put)(actions.sipEventSubscribeFinish({ error: error })); case 45: _context.next = 53; break; case 47: log.info('Successfully subscribed to sip event ' + action.payload.eventType + '.'); finishAction = actions.sipEventSubscribeFinish({ response: (0, _extends3.default)({}, response.payload.body.eventSubscriptionResponse, { eventType: action.payload.eventType, subscribedUsers: action.payload.subscribeUserList }) }); // Spawn a non-blocking saga to handle resubscriptions. _context.next = 51; return (0, _effects3.spawn)(sipEventResub, finishAction); case 51: _context.next = 53; return (0, _effects3.put)(finishAction); case 53: _context.next = 0; break; case 55: case 'end': return _context.stop(); } } }, _marked, this); } /** * Saga to handle automatic resubscription to subscribed sip event. * @method sipEventResub * @param {Object} action A SIP_EVENT_SUBSCRIBE_FINISH action. */ function sipEventResub(action) { var shouldResub, resubDelay, _ref4, cancel, eventInfo; return _regenerator2.default.wrap(function sipEventResub$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: shouldResub = true; case 1: if (!shouldResub) { _context2.next = 23; break; } resubDelay = action.payload.expires * 1000 / 2; // Wait for either the resub delay or an unsubscribe action. _context2.next = 5; return (0, _effects3.race)({ expiry: (0, _effects3.call)(_reduxSaga.delay, resubDelay), cancel: (0, _effects3.take)(function (unsubAction) { return unsubAction.type === actionTypes.SIP_EVENT_UNSUBSCRIBE_FINISH && unsubAction.payload.eventType === action.payload.eventType; }) }); case 5: _ref4 = _context2.sent; cancel = _ref4.cancel; if (cancel) { _context2.next = 20; break; } _context2.next = 10; return (0, _effects3.select)(_selectors.getSipEventInfo, action.payload.eventType); case 10: eventInfo = _context2.sent; if (!eventInfo) { _context2.next = 17; break; } log.info('Re-subscribing for sip ' + action.payload.eventType + '.'); _context2.next = 15; return (0, _effects3.put)(actions.sipEventUpdate(action.payload.eventType, {})); case 15: _context2.next = 18; break; case 17: shouldResub = false; case 18: _context2.next = 21; break; case 20: shouldResub = false; case 21: _context2.next = 1; break; case 23: case 'end': return _context2.stop(); } } }, _marked2, this); } /** * Saga to update/resubscribe to a subscribed sip event. * @method sipEventUpdate */ function sipEventUpdate() { var action, eventInfo, error, _error, platform, _ref5, server, username, token, accessToken, commonOptions, requestOptions, userLists, response, _error2, statusCode, message; return _regenerator2.default.wrap(function sipEventUpdate$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: if (false) {} _context3.next = 3; return (0, _effects3.take)(actionTypes.SIP_EVENT_UPDATE); case 3: action = _context3.sent; log.debug('Updating sip event subscription: ' + action.payload.eventType + '.'); _context3.next = 7; return (0, _effects3.select)(_selectors.getSipEventInfo, action.payload.eventType); case 7: eventInfo = _context3.sent; if (eventInfo) { _context3.next = 19; break; } if (!action.meta.isResub) { _context3.next = 15; break; } // Don't need to resub, since we're not subscribed anymore. // TODO Tech-Debt: KandyError isn't very useful for these scenarios. The emitted event provides // the KandyError, except there's no (easy to use) info indicating _which_ event was being // acted on. KandyError needs the ability to provide extra information. error = new _errors2.default({ code: _errors.sipEventCodes.NOT_SUBSCRIBED, message: 'Cannot resubscribe for ' + action.payload.eventType + ' subscription; user not subscribed.' }); _context3.next = 13; return (0, _effects3.put)(actions.sipEventUpdateFinish({ error: error })); case 13: _context3.next = 18; break; case 15: // Error: Not subscribed to this sip event. Cannot update. _error = new _errors2.default({ code: _errors.sipEventCodes.NOT_SUBSCRIBED, message: 'Cannot update subscription for ' + action.payload.eventType + '; user not subscribed.' }); _context3.next = 18; return (0, _effects3.put)(actions.sipEventUpdateFinish({ error: _error })); case 18: return _context3.abrupt('continue', 0); case 19: _context3.next = 21; return (0, _effects3.select)(_selectors2.getPlatform); case 21: platform = _context3.sent; _context3.next = 24; return (0, _effects3.select)(_selectors2.getConnectionInfo); case 24: _ref5 = _context3.sent; server = _ref5.server; username = _ref5.username; token = _ref5.token; accessToken = _ref5.accessToken; commonOptions = _ref5.requestOptions; // TODO: CPaaS should store it's token the same way as Link. if (platform === _constants.platforms.CPAAS && !token) { token = accessToken; } requestOptions = {}; requestOptions.method = 'PUT'; requestOptions.url = server.protocol + '://' + server.server + ':' + server.port + '/' + ('rest/version/' + server.version + '/') + ('user/' + username + '/') + ('eventSubscription/' + eventInfo.sessionData); // Only include user lists in the request body if there are entries. userLists = {}; if (action.payload.subscribeUserList.length > 0) { userLists.subscribeUserList = action.payload.subscribeUserList; } if (action.payload.unsubscribeUserList.length > 0) { userLists.unsubscribeUserList = action.payload.unsubscribeUserList; } requestOptions.body = (0, _stringify2.default)({ eventSubscriptionRequest: (0, _extends3.default)({}, userLists, { eventType: action.payload.eventType, customParameters: action.payload.customParameters, expires: eventInfo.expires }) }); _context3.next = 40; return (0, _effects2.default)(requestOptions, commonOptions); case 40: response = _context3.sent; if (!response.error) { _context3.next = 48; break; } _error2 = void 0; if (response.payload.body) { // Handle errors from the server. statusCode = response.payload.body.eventSubscriptionResponse.statusCode; log.info('Failed to update sip event subscription; ' + action.payload.eventType + ', ' + ('status code ' + statusCode)); _error2 = new _errors2.default({ code: _errors.sipEventCodes.UNKNOWN_ERROR, message: 'Failed to update to sip event subscription; ' + action.payload.eventType + ', ' + ('status code ' + statusCode) }); } else { // Handler errors from the request helper. message = response.payload.result.message; log.info('SIP event update subscription request failed: ' + message + '.'); _error2 = new _errors2.default({ code: _errors.sipEventCodes.UNKNOWN_ERROR, message: 'SIP event update subscription request failed: ' + message + '.' }); } _context3.next = 46; return (0, _effects3.put)(actions.sipEventUpdateFinish({ error: _error2 })); case 46: _context3.next = 51; break; case 48: log.info('Updated sip event subscription: ' + action.payload.eventType + '.'); _context3.next = 51; return (0, _effects3.put)(actions.sipEventUpdateFinish({ response: (0, _extends3.default)({}, response.payload.body.eventSubscriptionResponse, { eventType: action.payload.eventType, subscribeUserList: action.payload.subscribeUserList || [], unsubscribeUserList: action.payload.unsubscribeUserList || [] }) })); case 51: _context3.next = 0; break; case 53: case 'end': return _context3.stop(); } } }, _marked3, this); } /** * Saga to unsubscribe from [all currently subscribed] sip events. * @method sipEventUnsubscribe */ function sipEventUnsubscribe() { var action, eventInfo, error, platform, _ref6, server, username, token, accessToken, commonOptions, requestOptions, response, _error3, statusCode, message; return _regenerator2.default.wrap(function sipEventUnsubscribe$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: if (false) {} _context4.next = 3; return (0, _effects3.take)(actionTypes.SIP_EVENT_UNSUBSCRIBE); case 3: action = _context4.sent; log.debug('Unsubscribing from sip event subscriptions: ' + action.payload + '.'); _context4.next = 7; return (0, _effects3.select)(_selectors.getSipEventInfo, action.payload); case 7: eventInfo = _context4.sent; if (eventInfo) { _context4.next = 14; break; } log.info('Cannot unsubscribe from sip event ' + action.payload + '; no subscription exists.'); error = new _errors2.default({ code: _errors.sipEventCodes.NOT_SUBSCRIBED, message: 'Cannot unsubscribe from ' + action.payload + '; no subscription found.' }); _context4.next = 13; return (0, _effects3.put)(actions.sipEventUnsubscribeFinish({ error: error })); case 13: return _context4.abrupt('continue', 0); case 14: _context4.next = 16; return (0, _effects3.select)(_selectors2.getPlatform); case 16: platform = _context4.sent; _context4.next = 19; return (0, _effects3.select)(_selectors2.getConnectionInfo); case 19: _ref6 = _context4.sent; server = _ref6.server; username = _ref6.username; token = _ref6.token; accessToken = _ref6.accessToken; commonOptions = _ref6.requestOptions; // TODO: CPaaS should store it's token the same way as Link. if (platform === _constants.platforms.CPAAS && !token) { token = accessToken; } requestOptions = {}; requestOptions.method = 'DELETE'; requestOptions.url = server.protocol + '://' + server.server + ':' + server.port + '/' + ('rest/version/' + server.version + '/') + ('user/' + username + '/') + ('eventSubscription/' + eventInfo.sessionData); _context4.next = 31; return (0, _effects2.default)(requestOptions, commonOptions); case 31: response = _context4.sent; if (!response.error) { _context4.next = 39; break; } _error3 = void 0; if (response.payload.body) { // Handle errors from the server. statusCode = response.payload.body.eventSubscriptionResponse.statusCode; log.info('Failed to unsubscribe from sip event ' + action.payload.eventType + ', ' + ('status code ' + statusCode)); _error3 = new _errors2.default({ code: _errors.sipEventCodes.UNKNOWN_ERROR, message: 'Failed to unsubscribe from sip event ' + action.payload.eventType + ', ' + ('status code ' + statusCode) }); } else { // Handler errors from the request helper. message = response.payload.result.message; log.info('SIP event unsubscription request failed: ' + message + '.'); _error3 = new _errors2.default({ code: _errors.sipEventCodes.UNKNOWN_ERROR, message: 'SIP event unsubscription request failed: ' + message + '.' }); } _context4.next = 37; return (0, _effects3.put)(actions.sipEventUnsubscribeFinish({ error: _error3 })); case 37: _context4.next = 42; break; case 39: log.info('Successfully unsubscribed from sip ' + action.payload + '.'); _context4.next = 42; return (0, _effects3.put)(actions.sipEventUnsubscribeFinish({ response: { eventType: action.payload } })); case 42: _context4.next = 0; break; case 44: case 'end': return _context4.stop(); } } }, _marked4, this); } /** * Saga to handle received sip event notifications. * @method receiveEventNotify */ function receiveEventNotify() { var receiveEventNotifyPattern, action, _ref7, subscribedServices, sipEvents, notification, eventInfo; return _regenerator2.default.wrap(function receiveEventNotify$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: receiveEventNotifyPattern = function receiveEventNotifyPattern(action) { return action.type === _actionTypes2.NOTIFICATION_RECEIVED && action.payload.notificationMessage.hasOwnProperty('genericNotificationParams'); }; // Redux-saga take() pattern. // Take notification actions that MAY be for sip events. case 1: if (false) {} _context5.next = 4; return (0, _effects3.take)(receiveEventNotifyPattern); case 4: action = _context5.sent; _context5.next = 7; return (0, _effects3.select)(_selectors2.getServices); case 7: _ref7 = _context5.sent; subscribedServices = _ref7.received; sipEvents = subscribedServices.filter(function (service) { return service.startsWith('event:'); }); notification = action.payload.notificationMessage; // Determine if this notification is for a sip event the user subscribed/connected for. if (!(0, _fp.includes)(notification.eventType, sipEvents)) { _context5.next = 24; break; } _context5.next = 14; return (0, _effects3.select)(_selectors.getSipEventInfo, notification.eventType); case 14: eventInfo = _context5.sent; if (!eventInfo) { _context5.next = 21; break; } log.info('Received sip event notification of type ' + notification.eventType + '.'); _context5.next = 19; return (0, _effects3.put)(actions.sipEventReceived(notification)); case 19: _context5.next = 22; break; case 21: // Subscribed to sip event, but received a notification for it? log.debug('Received sip event notification for untracked event.', notification); case 22: _context5.next = 25; break; case 24: // Not subscribed to sip event, but received a notification for it? log.debug('Received sip event notification without subscription.', action.payload.eventType); case 25: _context5.next = 1; break; case 27: case 'end': return _context5.stop(); } } }, _marked5, this); } /***/ }), /***/ "./src/users/interface/actionTypes.js": /*!********************************************!*\ !*** ./src/users/interface/actionTypes.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var prefix = '@@KANDY/'; var CACHE_USER = exports.CACHE_USER = prefix + 'CACHE_USER'; var CACHE_USER_FINISHED = exports.CACHE_USER_FINISHED = prefix + 'CACHE_USER_FINISHED'; var REFRESH_CONTACTS = exports.REFRESH_CONTACTS = prefix + 'REFRESH_CONTACTS'; var ADD_CONTACT = exports.ADD_CONTACT = prefix + 'ADD_CONTACT'; var REMOVE_CONTACT = exports.REMOVE_CONTACT = prefix + 'REMOVE_CONTACT'; var UPDATE_CONTACT = exports.UPDATE_CONTACT = prefix + 'UPDATE_CONTACT'; var CONTACTS_CHANGED = exports.CONTACTS_CHANGED = prefix + 'CONTACTS_CHANGED'; var SEARCH_DIRECTORY = exports.SEARCH_DIRECTORY = prefix + 'SEARCH_DIRECTORY'; var DIRECTORY_CHANGED = exports.DIRECTORY_CHANGED = prefix + 'DIRECTORY_CHANGED'; var FETCH_USER_DETAILS = exports.FETCH_USER_DETAILS = prefix + 'FETCH_USER_DETAILS'; /***/ }), /***/ "./src/users/interface/actions.js": /*!****************************************!*\ !*** ./src/users/interface/actions.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fetchUserDetails = exports.directoryChanged = exports.contactsChanged = exports.cacheUserFinished = undefined; exports.cacheUser = cacheUser; exports.refreshContacts = refreshContacts; exports.addContact = addContact; exports.removeContact = removeContact; exports.updateContact = updateContact; exports.searchDirectory = searchDirectory; var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/users/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function cacheUser(id) { return { type: actionTypes.CACHE_USER, payload: id }; } var cacheUserFinished = exports.cacheUserFinished = (0, _reduxActions.createAction)(actionTypes.CACHE_USER_FINISHED); /** * Refresh the contact list. * * @returns {Object} A flux standard action representing the REFRESH_CONTACTS action. */ function refreshContacts() { return { type: actionTypes.REFRESH_CONTACTS, payload: null }; } /** * Adds a contact in contact list. * * @returns {Object} A flux standard action representing the ADD_CONTACT action. */ function addContact(user) { return { type: actionTypes.ADD_CONTACT, payload: user }; } /** * Removes a contact in contact list. * * @returns {Object} A flux standard action representing the REMOVE_CONTACT action. */ function removeContact(id) { return { type: actionTypes.REMOVE_CONTACT, payload: id }; } /** * Updates a contact in contact list. * * @returns {Object} A flux standard action representing the UPDATE_CONTACT action. */ function updateContact(id, user) { return { type: actionTypes.UPDATE_CONTACT, payload: { id: id, user: user } }; } /** * Create an action that sets the contacts. * * @param {Array} Contacts The contacts * @param {Object} Error An error object. * @returns {Object} A flux standard action representing the CONTACTS_CHANGED action. */ var contactsChanged = exports.contactsChanged = (0, _reduxActions.createAction)(actionTypes.CONTACTS_CHANGED); /** * Create an action that searches the directory. * * @param {string} criteria The criteria to search the directory by. * @param {string} type The type of search, one of these 4: ['phone_number', 'name', 'user_id', undefined] * @returns {Object} A flux standard action representing the SEARCH_DIRECTORY action. */ function searchDirectory(criteria, type) { return { type: actionTypes.SEARCH_DIRECTORY, payload: { searchCriteria: criteria, searchType: type } }; } /** * Create an action that sets the directory. * * @param {Array} Contacts The contacts * @param {Object} Error An error object. * @returns {Object} A flux standard action representing the DIRECTORY_CHANGED action. */ var directoryChanged = exports.directoryChanged = (0, _reduxActions.createAction)(actionTypes.DIRECTORY_CHANGED); /** * Action for fetching the current user's profile data. * @returns {Object} A flux standard action */ var fetchUserDetails = exports.fetchUserDetails = (0, _reduxActions.createAction)(actionTypes.FETCH_USER_DETAILS); /***/ }), /***/ "./src/users/interface/api.js": /*!************************************!*\ !*** ./src/users/interface/api.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = api; var _actions = __webpack_require__(/*! ./actions */ "./src/users/interface/actions.js"); var actions = _interopRequireWildcard(_actions); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function api(context) { var contactsApi = { /** * Refreshes the contacts in the state. This will get new contacts from the server. * * @public * @memberof Contacts * @method refresh */ refresh: function refresh() { context.dispatch(actions.refreshContacts()); }, /** * Add a contact to a user's personal address book. * * @public * @memberof Contacts * @method add * @param {Object} contact The contact object. * @param {string} contact.userId The userId for the contact * @param {string} contact.primaryContact The primary userId for the contact * @param {number} contact.id The id number by which this user is indexed in your address book * @param {boolean} [contact.friendStatus] Indicates whether or not the contact is a friend of the user * @param {string} [contact.username] The contact's username, shortened from their userId * @param {string} [contact.firstName] The contact's first name * @param {string} [contact.lastName] The contact's last name * @param {string} [contact.nickname] The contact's nickname * @param {string} [contact.email] The contact's email address * @param {string} [contact.homePhone] The contact's home phone number * @param {string} [contact.workPhone] The contact's work phone number * @param {string} [contact.mobilePhone] The contact's mobile phone number * @param {string} [contact.fax] The contact's fax number * @param {string} [contact.pager] The contact's pager number * @param {Array} [contact.groupList] A list of groups associated with the contact */ add: function add(contact) { context.dispatch(actions.addContact(contact)); }, /** * Remove a contact from a personal address book. * * @public * @memberof Contacts * @method remove * @param {string} id The Id of the contact that will be removed. */ remove: function remove(id) { context.dispatch(actions.removeContact(id)); }, /** * Update a contact from the user's personal address book. * * @public * @memberof Contacts * @method update * @param {string} id The id of the contact that will be updated. * @param {Object} contact The contact object. */ update: function update(id, contact) { context.dispatch(actions.updateContact(id, contact)); }, /** * Search the users in the directory. * * @public * @memberof Contacts * @method search * @param {string} criteria Search criteria. * @param {string} type The type of criteria. Can be `FIRSTNAME`, `LASTNAME`, `NAME`, `PHONENUMBER` or `USERNAME`. */ search: function search(criteria, type) { context.dispatch(actions.searchDirectory(criteria, type)); } }; var usersApi = { /** * Get user details from the server. * * @public * @memberof Users * @method fetch * @param {string} userId The Id of the user to fetch. */ fetch: function fetch(userId) { context.dispatch(actions.cacheUser(userId)); }, /** * Fetch the current user's profile data. * * @public * @memberof Users * @method fetchDetails */ fetchDetails: function fetchDetails() { context.dispatch(actions.fetchUserDetails()); }, /** * Get user from local state. * * @public * @memberof Users * @method get * @param {string} userId The Id of the user to get. * @return {User} A User object for the requested user. */ get: function get(userId) { return context.primitives.User({ userId: userId }); }, /** * Get currently logged in user data from the local state. * * @public * @memberof Users * @method getSelf * @return {User} A User object for the currently logged in user. */ getSelf: function getSelf() { return context.primitives.User({ userId: context.getState().authentication.userInfo.username }); } }; return { user: usersApi, contacts: contactsApi }; } /** * * Users functions are namespaced beneath 'users' on the returned Kandy object. * @public * @module Users */ /** * * Contacts functions are namespaced beneath 'contacts' on the returned Kandy object. * @public * @module Contacts */ /***/ }), /***/ "./src/users/interface/eventTypes.js": /*!*******************************************!*\ !*** ./src/users/interface/eventTypes.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * The contacts list has changed. * @memberof Users * @param {Object} params * @param {Array} params.contacts The updated list of contacts. */ var CONTACTS_CHANGE = exports.CONTACTS_CHANGE = 'contacts:change'; /** * An error occurred while performing a contact operation. * @memberof Users * @param {Object} params * @param {Object} params.error The Kandy error object. */ var CONTACTS_ERROR = exports.CONTACTS_ERROR = 'contacts:error'; /** * The directory has changed. * @memberof Users * @param {Object} params * @param {Array} params.results The results of the directory search. */ var DIRECTORY_CHANGE = exports.DIRECTORY_CHANGE = 'directory:change'; /** * An error occurred while performing a directory operation. * @memberof Users * @param {Object} params * @param {Object} params.error The Kandy error object. */ var DIRECTORY_ERROR = exports.DIRECTORY_ERROR = 'directory:error'; /** * The cached user list has changed. * @memberof Users * @param {Object} params * @param {Object} params.user The fetched user. */ var FETCH_USER = exports.FETCH_USER = 'user:fetch'; /** * An error occurred while performing a fetch operation. * @memberof Users * @param {Object} params * @param {Object} params.error The Kandy error object. */ var FETCH_ERROR = exports.FETCH_ERROR = 'user:fetchError'; /***/ }), /***/ "./src/users/interface/events.js": /*!***************************************!*\ !*** ./src/users/interface/events.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/users/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _eventTypes = __webpack_require__(/*! ./eventTypes */ "./src/users/interface/eventTypes.js"); var eventTypes = _interopRequireWildcard(_eventTypes); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } var eventsMap = {}; eventsMap[actionTypes.CONTACTS_CHANGED] = function (action) { if (action.error) { return { type: eventTypes.CONTACTS_ERROR, args: { error: action.payload } }; } else { return { type: eventTypes.CONTACTS_CHANGE, args: { contacts: action.payload } }; } }; eventsMap[actionTypes.DIRECTORY_CHANGED] = function (action) { if (action.error) { return { type: eventTypes.DIRECTORY_ERROR, args: { error: action.payload } }; } else { return { type: eventTypes.DIRECTORY_CHANGE, args: { results: action.payload } }; } }; eventsMap[actionTypes.CACHE_USER_FINISHED] = function (action, context) { if (action.error) { return { type: eventTypes.FETCH_ERROR, args: { error: action.payload } }; } else { var user = {}; // If a user was fetched, return a user object. Otherwise empty. if (action.payload.userId) { user = context.primitives.User({ userId: action.payload.userId }); } return { type: eventTypes.FETCH_USER, args: { user: user } }; } }; exports.default = eventsMap; /***/ }), /***/ "./src/users/interface/index.js": /*!**************************************!*\ !*** ./src/users/interface/index.js ***! \**************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mixins = exports.eventsMap = exports.reducer = exports.api = exports.name = undefined; var _api = __webpack_require__(/*! ./api */ "./src/users/interface/api.js"); var _api2 = _interopRequireDefault(_api); var _reducers = __webpack_require__(/*! ./reducers */ "./src/users/interface/reducers.js"); var _reducers2 = _interopRequireDefault(_reducers); var _mixins = __webpack_require__(/*! ./mixins */ "./src/users/interface/mixins.js"); var _mixins2 = _interopRequireDefault(_mixins); var _events = __webpack_require__(/*! ./events */ "./src/users/interface/events.js"); var _events2 = _interopRequireDefault(_events); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var name = 'users'; exports.name = name; exports.api = _api2.default; exports.reducer = _reducers2.default; exports.eventsMap = _events2.default; exports.mixins = _mixins2.default; /***/ }), /***/ "./src/users/interface/mixins.js": /*!***************************************!*\ !*** ./src/users/interface/mixins.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var userBase = { initializers: [function (_ref) { var userId = _ref.userId; this.userId = userId; }], methods: { getInfo: function getInfo() { return this.state; } }, propertyDescriptors: { state: { get: function get() { return this.context.getState().users.cache[this.userId]; } } } }; exports.default = { User: userBase }; /***/ }), /***/ "./src/users/interface/reducers.js": /*!*****************************************!*\ !*** ./src/users/interface/reducers.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = __webpack_require__(/*! babel-runtime/helpers/defineProperty */ "../../node_modules/babel-runtime/helpers/defineProperty.js"); var _defineProperty3 = _interopRequireDefault(_defineProperty2); var _getIterator2 = __webpack_require__(/*! babel-runtime/core-js/get-iterator */ "../../node_modules/babel-runtime/core-js/get-iterator.js"); var _getIterator3 = _interopRequireDefault(_getIterator2); var _extends4 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends5 = _interopRequireDefault(_extends4); var _actionTypes = __webpack_require__(/*! ./actionTypes */ "./src/users/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _reduxActions = __webpack_require__(/*! redux-actions */ "../../node_modules/redux-actions/es/index.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var reducers = {}; var contactsPendingReducer = { next: function next(state) { return (0, _extends5.default)({}, state, { isPending: true }); } }; reducers[actionTypes.ADD_CONTACT] = contactsPendingReducer; reducers[actionTypes.REMOVE_CONTACT] = contactsPendingReducer; reducers[actionTypes.UPDATE_CONTACT] = contactsPendingReducer; reducers[actionTypes.REFRESH_CONTACTS] = contactsPendingReducer; reducers[actionTypes.SEARCH_DIRECTORY] = contactsPendingReducer; reducers[actionTypes.CONTACTS_CHANGED] = { next: function next(state, action) { return (0, _extends5.default)({}, state, { contacts: action.payload || [], isPending: false }); }, throw: function _throw(state, action) { return (0, _extends5.default)({}, state, { isPending: false, errors: state.errors.concat(action.payload) }); } }; reducers[actionTypes.DIRECTORY_CHANGED] = { next: function next(state, action) { var directory = action.payload || []; var cache = (0, _extends5.default)({}, state.cache); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = (0, _getIterator3.default)(directory), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var user = _step.value; cache[user.userId] = user; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return (0, _extends5.default)({}, state, { directory: directory, cache: cache, isPending: false }); }, throw: function _throw(state, action) { return (0, _extends5.default)({}, state, { isPending: false, errors: state.errors.concat(action.payload) }); } }; reducers[actionTypes.CACHE_USER] = { next: function next(state, action) { return (0, _extends5.default)({}, state, { cache: (0, _extends5.default)({}, state.cache, (0, _defineProperty3.default)({}, action.payload, {})) }); } }; reducers[actionTypes.CACHE_USER_FINISHED] = { next: function next(state, action) { return (0, _extends5.default)({}, state, { cache: (0, _extends5.default)({}, state.cache, (0, _defineProperty3.default)({}, action.payload.userId, (0, _extends5.default)({}, action.payload.data))) }); } }; /* * Combine all of reducers into a single reducer, with * a default state of empty arrays. */ var reducer = (0, _reduxActions.handleActions)(reducers, { contacts: [], directory: [], errors: [], cache: {}, isPending: false }); exports.default = reducer; /***/ }), /***/ "./src/users/interface/selectors.js": /*!******************************************!*\ !*** ./src/users/interface/selectors.js ***! \******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getContacts = getContacts; /* * Redux-saga selector functions. * Used with the `select` effect in sagas to Retrieves * specific portions of the state. */ /** * Gets the contacts from state. * @method getContacts * @return {Object} */ function getContacts(state) { return state.users.contacts; } /***/ }), /***/ "./src/users/link.js": /*!***************************!*\ !*** ./src/users/link.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = __webpack_require__(/*! babel-runtime/helpers/extends */ "../../node_modules/babel-runtime/helpers/extends.js"); var _extends3 = _interopRequireDefault(_extends2); var _stringify = __webpack_require__(/*! babel-runtime/core-js/json/stringify */ "../../node_modules/babel-runtime/core-js/json/stringify.js"); var _stringify2 = _interopRequireDefault(_stringify); var _regenerator = __webpack_require__(/*! babel-runtime/regenerator */ "../../node_modules/babel-runtime/regenerator/index.js"); var _regenerator2 = _interopRequireDefault(_regenerator); exports.default = usersLink; exports.fetchUserDetails = fetchUserDetails; var _actionTypes = __webpack_require__(/*! ./interface/actionTypes */ "./src/users/interface/actionTypes.js"); var actionTypes = _interopRequireWildcard(_actionTypes); var _actions = __webpack_require__(/*! ./interface/actions */ "./src/users/interface/actions.js"); var actions = _interopRequireWildcard(_actions); var _selectors = __webpack_require__(/*! ../auth/interface/selectors */ "./src/auth/interface/selectors.js"); var _selectors2 = __webpack_require__(/*! ./interface/selectors */ "./src/users/interface/selectors.js"); var _interface = __webpack_require__(/*! ./interface */ "./src/users/interface/index.js"); var _actions2 = __webpack_require__(/*! ../events/interface/actions */ "./src/events/interface/actions.js"); var _normalizeUser = __webpack_require__(/*! ./normalizeUser */ "./src/users/normalizeUser.js"); var _effects = __webpack_require__(/*! ../request/effects */ "./src/request/effects.js"); var _effects2 = _interopRequireDefault(_effects); var _logs = __webpack_require__(/*! ../logs */ "./src/logs/index.js"); var _effects3 = __webpack_require__(/*! redux-saga/effects */ "../../node_modules/redux-saga/es/effects.js"); var _constants = __webpack_require__(/*! ../constants */ "./src/constants.js"); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _marked9 = /*#__PURE__*/_regenerator2.default.mark(userRequest), _marked10 = /*#__PURE__*/_regenerator2.default.mark(getDirectory), _marked11 = /*#__PURE__*/_regenerator2.default.mark(fetchUserDetails); // Request // Libraries. // Logs // Constants // Get the logger var log = (0, _logs.getLogManager)().getLogger('USERS'); function usersLink() { var _marked = /*#__PURE__*/_regenerator2.default.mark(init), _marked2 = /*#__PURE__*/_regenerator2.default.mark(refreshContacts), _marked3 = /*#__PURE__*/_regenerator2.default.mark(addContact), _marked4 = /*#__PURE__*/_regenerator2.default.mark(removeContact), _marked5 = /*#__PURE__*/_regenerator2.default.mark(updateContact), _marked6 = /*#__PURE__*/_regenerator2.default.mark(searchDirectory), _marked7 = /*#__PURE__*/_regenerator2.default.mark(cacheUser), _marked8 = /*#__PURE__*/_regenerator2.default.mark(cacheSelf); function init() { return _regenerator2.default.wrap(function init$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _effects3.put)((0, _actions2.mapEvents)(_interface.eventsMap)); case 2: case 'end': return _context.stop(); } } }, _marked, this); } function refreshContacts() { var action, connection, res, contacts; return _regenerator2.default.wrap(function refreshContacts$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: if (false) {} _context2.next = 3; return (0, _effects3.take)([actionTypes.REFRESH_CONTACTS]); case 3: action = _context2.sent; if (!action.error) { _context2.next = 6; break; } return _context2.abrupt('continue', 0); case 6: _context2.next = 8; return (0, _effects3.select)(_selectors.getConnectionInfo); case 8: connection = _context2.sent; _context2.next = 11; return (0, _effects3.call)(userRequest, 'GET', connection); case 11: res = _context2.sent; if (!res.error) { _context2.next = 17; break; } _context2.next = 15; return (0, _effects3.put)(actions.contactsChanged(new Error(res.error))); case 15: _context2.next = 20; break; case 17: contacts = res.result.addressBookEntries || []; _context2.next = 20; return (0, _effects3.put)(actions.contactsChanged(contacts)); case 20: _context2.next = 0; break; case 22: case 'end': return _context2.stop(); } } }, _marked2, this); } function addContact() { var _this = this; var contacts, contactData; return _regenerator2.default.wrap(function addContact$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: if (false) {} _context4.prev = 1; return _context4.delegateYield( /*#__PURE__*/_regenerator2.default.mark(function _callee() { var action, contact, connection, res; return _regenerator2.default.wrap(function _callee$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return (0, _effects3.take)(actionTypes.ADD_CONTACT); case 2: action = _context3.sent; contact = (0, _normalizeUser.userToContact)(action.payload, 'entryId'); _context3.next = 6; return (0, _effects3.select)(_selectors2.getContacts); case 6: contacts = _context3.sent; if (!find(function (c) { return c.id === action.payload.id; }, contacts)) { _context3.next = 9; break; } throw new Error('There is already a contact with id ' + action.payload.id + ' in contact list'); case 9: contactData = { addressBookRequest: { addressBookEntries: [contact] } }; _context3.next = 12; return (0, _effects3.select)(_selectors.getConnectionInfo); case 12: connection = _context3.sent; _context3.next = 15; return (0, _effects3.call)(userRequest, 'POST', connection, 'contacts/', (0, _stringify2.default)(contactData)); case 15: res = _context3.sent; if (!res.error) { _context3.next = 18; break; } throw new Error(res.error); case 18: _context3.next = 20; return (0, _effects3.put)(actions.contactsChanged(contacts.concat(action.payload))); case 20: case 'end': return _context3.stop(); } } }, _callee, _this); })(), 't0', 3); case 3: _context4.next = 9; break; case 5: _context4.prev = 5; _context4.t1 = _context4['catch'](1); _context4.next = 9; return (0, _effects3.put)(actions.contactsChanged(_context4.t1)); case 9: _context4.next = 0; break; case 11: case 'end': return _context4.stop(); } } }, _marked3, this, [[1, 5]]); } function removeContact() { var _this2 = this; var contacts; return _regenerator2.default.wrap(function removeContact$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: if (false) {} _context6.prev = 1; return _context6.delegateYield( /*#__PURE__*/_regenerator2.default.mark(function _callee2() { var action, connection, res; return _regenerator2.default.wrap(function _callee2$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return (0, _effects3.take)(actionTypes.REMOVE_CONTACT); case 2: action = _context5.sent; _context5.next = 5; return (0, _effects3.select)(_selectors.getConnectionInfo); case 5: connection = _context5.sent; _context5.next = 8; return (0, _effects3.call)(userRequest, 'DELETE', connection, 'contacts/' + encodeURIComponent(atob(action.payload))); case 8: res = _context5.sent; _context5.next = 11; return (0, _effects3.select)(_selectors2.getContacts); case 11: contacts = _context5.sent; if (find(function (c) { return c.id === action.payload; }, contacts)) { _context5.next = 14; break; } throw new Error('There is no contact with id ' + action.payload + ' in contact list'); case 14: if (!res.error) { _context5.next = 16; break; } throw new Error(res.error); case 16: _context5.next = 18; return (0, _effects3.put)(actions.contactsChanged(contacts.filter(function (c) { return c.id !== action.payload; }))); case 18: case 'end': return _context5.stop(); } } }, _callee2, _this2); })(), 't0', 3); case 3: _context6.next = 9; break; case 5: _context6.prev = 5; _context6.t1 = _context6['catch'](1); _context6.next = 9; return (0, _effects3.put)(actions.contactsChanged(_context6.t1)); case 9: _context6.next = 0; break; case 11: case 'end': return _context6.stop(); } } }, _marked4, this, [[1, 5]]); } function updateContact() { var _this3 = this; var contacts, contactData; return _regenerator2.default.wrap(function updateContact$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: if (false) {} _context8.prev = 1; return _context8.delegateYield( /*#__PURE__*/_regenerator2.default.mark(function _callee3() { var action, contact, connection, res; return _regenerator2.default.wrap(function _callee3$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; return (0, _effects3.take)(actionTypes.UPDATE_CONTACT); case 2: action = _context7.sent; contact = (0, _normalizeUser.userToContact)(action.payload.user, 'entryId'); _context7.next = 6; return (0, _effects3.select)(_selectors2.getContacts); case 6: contacts = _context7.sent; if (find(function (c) { return c.id === action.payload.id; }, contacts)) { _context7.next = 9; break; } throw new Error('There is no contact with id ' + action.payload.id + ' in contact list'); case 9: contactData = { addressBookRequest: { addressBookEntries: [contact] } }; _context7.next = 12; return (0, _effects3.select)(_selectors.getConnectionInfo); case 12: connection = _context7.sent; _context7.next = 15; return (0, _effects3.call)(userRequest, 'PUT', connection, 'contacts/' + encodeURIComponent(atob(action.payload.id)), (0, _stringify2.default)(contactData)); case 15: res = _context7.sent; if (!res.error) { _context7.next = 18; break; } throw new Error(res.error); case 18: _context7.next = 20; return (0, _effects3.put)(actions.contactsChanged(contacts.map(function (c) { return c.id === action.payload.id ? action.payload.user : c; }))); case 20: case 'end': return _context7.stop(); } } }, _callee3, _this3); })(), 't0', 3); case 3: _context8.next = 9; break; case 5: _context8.prev = 5; _context8.t1 = _context8['catch'](1); _context8.next = 9; return (0, _effects3.put)(actions.contactsChanged(_context8.t1)); case 9: _context8.next = 0; break; case 11: case 'end': return _context8.stop(); } } }, _marked5, this, [[1, 5]]); } function searchDirectory() { var action, body, connection, res, items; return _regenerator2.default.wrap(function searchDirectory$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: if (false) {} _context9.next = 3; return (0, _effects3.take)(actionTypes.SEARCH_DIRECTORY); case 3: action = _context9.sent; body = { searchCriteria: action.payload.searchCriteria, searchType: searchTypeInteger(action.payload.searchType) }; _context9.next = 7; return (0, _effects3.select)(_selectors.getConnectionInfo); case 7: connection = _context9.sent; _context9.next = 10; return (0, _effects3.call)(getDirectory, connection, body); case 10: res = _context9.sent; if (!res.error) { _context9.next = 16; break; } _context9.next = 14; return (0, _effects3.put)(actions.directoryChanged(new Error(res.error))); case 14: _context9.next = 19; break; case 16: items = res.result.directoryItems || []; _context9.next = 19; return (0, _effects3.put)(actions.directoryChanged(items.map(_normalizeUser.normalizeUser))); case 19: _context9.next = 0; break; case 21: case 'end': return _context9.stop(); } } }, _marked6, this); } /** * On-Premises cacheUser saga * Performs to uworkflow of caching a user. * @return {Generator} [description] */ function cacheUser() { var _ref, userId, body, connection, res, data; return _regenerator2.default.wrap(function cacheUser$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: if (false) {} _context10.next = 3; return (0, _effects3.take)(actionTypes.CACHE_USER); case 3: _ref = _context10.sent; userId = _ref.payload; body = { searchCriteria: userId, searchType: searchTypeInteger('user_id') }; _context10.next = 8; return (0, _effects3.select)(_selectors.getConnectionInfo); case 8: connection = _context10.sent; _context10.next = 11; return (0, _effects3.call)(getDirectory, connection, body); case 11: res = _context10.sent; if (!res.error) { _context10.next = 17; break; } _context10.next = 15; return (0, _effects3.put)(actions.cacheUserFinished(new Error(res.error))); case 15: _context10.next = 25; break; case 17: if (!res.result.directoryItems) { _context10.next = 23; break; } data = (0, _normalizeUser.normalizeUser)(res.result.directoryItems[0]); _context10.next = 21; return (0, _effects3.put)(actions.cacheUserFinished({ userId: userId, data: data })); case 21: _context10.next = 25; break; case 23: _context10.next = 25; return (0, _effects3.put)(actions.cacheUserFinished({})); case 25: _context10.next = 0; break; case 27: case 'end': return _context10.stop(); } } }, _marked7, this); } /** * On-Premises getUserDetails saga. * Performs the workflow of caching the currently logged in user. * @method getUserDetails */ function cacheSelf() { var action, connection, response, userId, data; return _regenerator2.default.wrap(function cacheSelf$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: if (false) {} _context11.next = 3; return (0, _effects3.take)(actionTypes.FETCH_USER_DETAILS); case 3: action = _context11.sent; if (!action.error) { _context11.next = 6; break; } return _context11.abrupt('continue', 0); case 6: _context11.next = 8; return (0, _effects3.select)(_selectors.getConnectionInfo); case 8: connection = _context11.sent; _context11.next = 11; return (0, _effects3.call)(fetchUserDetails, connection); case 11: response = _context11.sent; if (response.error) { _context11.next = 18; break; } userId = connection.username; data = (0, _normalizeUser.normalizeUser)(response); data.userId = userId; // response doesn't include user id information _context11.next = 18; return (0, _effects3.put)(actions.cacheUserFinished({ userId: userId, data: data })); case 18: _context11.next = 0; break; case 20: case 'end': return _context11.stop(); } } }, _marked8, this); } return { sagas: [refreshContacts, addContact, removeContact, updateContact, searchDirectory, cacheUser, cacheSelf], api: _interface.api, mixins: _interface.mixins, reducer: _interface.reducer, name: _interface.name, init: init }; } function userRequest(method, conn, extraURL, body) { var platform, version, url, options, response, statusCode, message, err; return _regenerator2.default.wrap(function userRequest$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: _context12.next = 2; return (0, _effects3.select)(_selectors.getPlatform); case 2: platform = _context12.sent; version = platform === _constants.platforms.CPAAS ? 1 : conn.server.version; if (extraURL) { url = conn.server.protocol + '://' + conn.server.server + ':' + conn.server.port + '/rest/version/' + version + '/user/' + conn.username + '/addressbook/' + extraURL; } else { url = conn.server.protocol + '://' + conn.server.server + ':' + conn.server.port + '/rest/version/' + version + '/user/' + conn.username + '/addressbook'; } options = { method: method }; if (body) { options.body = body; } _context12.next = 9; return (0, _effects2.default)((0, _extends3.default)({ url: url }, options), conn.requestOptions); case 9: response = _context12.sent; if (!response.error) { _context12.next = 22; break; } if (!response.payload.body) { _context12.next = 17; break; } // Handle errors from the server. statusCode = response.payload.body.addressBookResponse.statusCode; log.debug('Failed to search addressbook with status code ' + statusCode + '.'); // TODO: Proper errors. return _context12.abrupt('return', { error: new Error('Failed to search addressbook; status ' + statusCode + '.') }); case 17: // Handle errors from the request helper. message = response.payload.result.message; log.debug('Addressbook search request failed: ' + message); // TODO: Proper errors. return _context12.abrupt('return', { error: new Error('Addressbook search request failed: ' + message) }); case 20: _context12.next = 29; break; case 22: if (!(response.payload.body && response.payload.body.addressBookResponse.statusCode === 0)) { _context12.next = 26; break; } return _context12.abrupt('return', { result: response.payload.body.addressBookResponse || {} }); case 26: // Unknown case. log.debug('Unknown error case for addressbook search.'); err = new Error('Unknown error.'); return _context12.abrupt('return', { error: err }); case 29: case 'end': return _context12.stop(); } } }, _marked9, this); } // see SPiDR 4.3 REST API Documentation - 12.11.3 function searchTypeInteger(searchType) { switch (searchType) { case 'first_name': case 'firstName': case 'FIRSTNAME': return 1; case 'last_name': case 'lastName': case 'LASTNAME': return 2; case 'name': case 'NAME': return 3; case 'phone_number': case 'phoneNumber': case 'PHONENUMBER': return 4; case 'user_id': case 'userId': case 'USERID': case 'user_name': case 'userName': case 'USERNAME': return 5; } } function getDirectory(conn) { var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var platform, version, url, queryParams, method, response, statusCode, message, err; return _regenerator2.default.wrap(function getDirectory$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: _context13.next = 2; return (0, _effects3.select)(_selectors.getPlatform); case 2: platform = _context13.sent; version = platform === _constants.platforms.CPAAS ? 1 : conn.server.version; url = conn.server.protocol + '://' + conn.server.server + ':' + conn.server.port + '/rest/version/' + version + '/user/' + conn.username + '/directory'; queryParams = {}; if (params.searchType) { queryParams['criteria'] = params.searchCriteria; queryParams['criteriaType'] = params.searchType; } else if (params.searchCriteria) { queryParams['criteria'] = params.searchCriteria; } method = 'GET'; _context13.next = 10; return (0, _effects2.default)({ url: url, queryParams: queryParams, method: method }, conn.requestOptions); case 10: response = _context13.sent; if (!response.error) { _context13.next = 23; break; } if (!response.payload.body) { _context13.next = 18; break; } // Handle errors from the server. statusCode = response.payload.body.directory.statusCode; log.debug('Failed to search directory with status code ' + statusCode + '.'); // TODO: Proper errors. return _context13.abrupt('return', { error: new Error('Failed to search directory; status ' + statusCode + '.') }); case 18: // Handle errors from the request helper. message = response.payload.result.message; log.debug('Directory search request failed: ' + message); // TODO: Proper errors. return _context13.abrupt('return', { error: new Error('Directory search request failed: ' + message) }); case 21: _context13.next = 30; break; case 23: if (!(response.payload.body && response.payload.body.directory.statusCode === 0)) { _context13.next = 27; break; } return _context13.abrupt('return', { result: response.payload.body.directory || {} }); case 27: // Unknown case. log.debug('Unknown error case for directory search.'); err = new Error('Unknown error.'); return _context13.abrupt('return', { error: err }); case 30: case 'end': return _context13.stop(); } } }, _marked10, this); } /** * Fetch userProfileData from SPiDR with the provided connection info. * @param {Object} connection Connection information for the platform in use. * @return {Object} Fetch request's response, parsed. */ function fetchUserDetails(connection) { var platform, version, url, params, response, statusCode, message; return _regenerator2.default.wrap(function fetchUserDetails$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.next = 2; return (0, _effects3.select)(_selectors.getPlatform); case 2: platform = _context14.sent; version = platform === _constants.platforms.CPAAS ? 1 : connection.server.version; url = connection.server.protocol + '://' + connection.server.server + ':' + connection.server.port + '/rest/version/' + version + '/user/' + connection.username + '/userProfileData'; params = { method: 'GET' }; _context14.next = 8; return (0, _effects2.default)((0, _extends3.default)({ url: url }, params), connection.requestOptions); case 8: response = _context14.sent; if (!response.error) { _context14.next = 21; break; } if (!response.payload.body) { _context14.next = 16; break; } // Handle errors from the server. statusCode = response.payload.body.userProfileData.statusCode; log.debug('Failed to fetch user details with status code ' + statusCode + '.'); // TODO: Proper errors. return _context14.abrupt('return', { error: true, status: statusCode, text: 'Failed to fetch user details with status code ' + statusCode + '.' }); case 16: // Handle errors from the request helper. message = response.payload.result.message; log.debug('User details fetch request failed: ' + message); // TODO: Proper errors. return _context14.abrupt('return', { error: true, text: 'User details fetch request failed: ' + message }); case 19: _context14.next = 27; break; case 21: if (!(response.payload.body && response.payload.body.userProfileData && response.payload.body.userProfileData.statusCode === 0)) { _context14.next = 25; break; } return _context14.abrupt('return', response.payload.body.userProfileData); case 25: // Unknown case. log.debug('Unknown error case for user details fetch.'); return _context14.abrupt('return', { error: true, text: 'Unknown error case.' }); case 27: case 'end': return _context14.stop(); } } }, _marked11, this); } /***/ }), /***/ "./src/users/normalizeUser.js": /*!************************************!*\ !*** ./src/users/normalizeUser.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _defineProperty2 = __webpack_require__(/*! babel-runtime/helpers/defineProperty */ "../../node_modules/babel-runtime/helpers/defineProperty.js"); var _defineProperty3 = _interopRequireDefault(_defineProperty2); exports.normalizeUser = normalizeUser; exports.userToContact = userToContact; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function normalizeUser(user) { return { id: btoa(user.contact_id || user.nickname || user.full_user_id || user.primaryContact), userId: user.full_user_id || user.primaryContact || user.contact_user_name, firstName: user.user_first_name || user.firstName || user.contact_first_name, lastName: user.user_last_name || user.lastName || user.contact_last_name, email: user.email || user.emailAddress, defaultPhone: user.phone_number, nickname: user.nickname, photoUrl: user.photoUrl, homePhone: user.homePhone, workPhone: user.workPhone, mobilePhone: user.mobilePhone, conferenceURL: user.conferenceURL, fax: user.fax, friendStatus: user.friendStatus, pager: user.pager, groupList: user.groupList }; } function userToContact(user) { var _ref; var idField = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'contact_id'; return _ref = {}, (0, _defineProperty3.default)(_ref, idField, atob(user.id)), (0, _defineProperty3.default)(_ref, 'primaryContact', user.userId), (0, _defineProperty3.default)(_ref, 'firstName', user.firstName), (0, _defineProperty3.default)(_ref, 'lastName', user.lastName), (0, _defineProperty3.default)(_ref, 'emailAddress', user.emailAddress), (0, _defineProperty3.default)(_ref, 'nickname', user.nickname), (0, _defineProperty3.default)(_ref, 'photoUrl', user.photoUrl), (0, _defineProperty3.default)(_ref, 'homePhone', user.homePhone), (0, _defineProperty3.default)(_ref, 'workPhone', user.workPhone), (0, _defineProperty3.default)(_ref, 'mobilePhone', user.mobilePhone), (0, _defineProperty3.default)(_ref, 'conferenceURL', user.conferenceURL), (0, _defineProperty3.default)(_ref, 'fax', user.fax), (0, _defineProperty3.default)(_ref, 'friendStatus', user.friendStatus), (0, _defineProperty3.default)(_ref, 'pager', user.pager), (0, _defineProperty3.default)(_ref, 'groupList', user.groupList), _ref; } /***/ }) /******/ }); }); //# sourceMappingURL=kandy.link.js.map
JavaScript
CL
106e0dedd38093fa82c6679b07e3f70eb1d02acd7d1be78bb81c0d3769201ff2