code
stringlengths
2
1.05M
(function( factory ) { if ( typeof define === "function" && define.amd ) { define( ["../../../jquery/jquery", "../jquery.validate"], factory ); } else { factory( jQuery ); } }(function( $ ) { /* * Translated default messages for the jQuery validation plugin. * Locale: ET (Estonian; eesti, eesti keel) */ $.extend($.validator.messages, { required: "See väli peab olema täidetud.", maxlength: $.validator.format("Palun sisestage vähem kui {0} tähemärki."), minlength: $.validator.format("Palun sisestage vähemalt {0} tähemärki."), rangelength: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1} tähemärki."), email: "Palun sisestage korrektne e-maili aadress.", url: "Palun sisestage korrektne URL.", date: "Palun sisestage korrektne kuupäev.", dateISO: "Palun sisestage korrektne kuupäev (YYYY-MM-DD).", number: "Palun sisestage korrektne number.", digits: "Palun sisestage ainult numbreid.", equalTo: "Palun sisestage sama väärtus uuesti.", range: $.validator.format("Palun sisestage väärtus vahemikus {0} kuni {1}."), max: $.validator.format("Palun sisestage väärtus, mis on väiksem või võrdne arvuga {0}."), min: $.validator.format("Palun sisestage väärtus, mis on suurem või võrdne arvuga {0}."), creditcard: "Palun sisestage korrektne krediitkaardi number." }); }));
(function() { var app = angular.module('app', [ 'ngRoute', 'ngResource', 'ngMaterial', 'ngStorage', 'ui.router', 'module.controller', 'module.service', 'module.constant', 'module.component' ]); app.config(function ($stateProvider, $urlRouterProvider,$httpProvider,$mdThemingProvider,$mdIconProvider) { $stateProvider.state('init', { abstract: true, views: { 'content@': { template: '<ui-view />', // NEW line, with a target for a child } } }).state('root', { abstract: true, views: { '@': { template: '<ui-view />', // NEW line, with a target for a child }, 'header@': { templateUrl: 'views/header.view.html', controller: 'controllerHeader' }, 'content@': { templateUrl: 'views/leftSide.view.html', controller: 'controller.leftSide', } } }).state('login', { parent:'init', url: "/login", templateUrl: "views/login.view.html", controller: "controller.login" }); $urlRouterProvider.otherwise("/uiTable"); $httpProvider.interceptors.push(['$q', '$location','serviceStorage', function($q, $location, serviceStorage) { return { 'request': function (config) { config.headers = config.headers || {}; if (serviceStorage.getData('token')) { config.headers.Authorization = serviceStorage.getData('token'); } return config; }, 'responseError': function(response) { if(response.status === 401 || response.status === 403 || response.status === 500 || response.status===0) { //$location.path('/login'); } return $q.reject(response); } }; }]); $mdIconProvider .defaultIconSet("svg/avatars.svg", 128) .icon("menu", "svg/menu.svg", 24) .icon("share", "svg/share.svg", 24) .icon("arrow_back", "svg/arrow_back.svg", 24) .icon("arrow_forward", "svg/arrow_forward.svg", 24) .icon("caret_up", "svg/caret_up.svg", 24) .icon("caret_down", "svg/caret_down.svg", 24) .icon("search", "svg/search.svg", 24) .icon("close", "svg/close.svg", 24); $mdThemingProvider.theme('default') .primaryPalette('blue') .accentPalette('red'); }); app.run( function( $rootScope ,$resourceService, $state) { var checkingSession = function(){ var verify = $resourceService.request('verify'); verify.get(function(verify){ $state.go('dashboard'); },function(error){ $state.go('login'); }); }; $rootScope.$on('$locationChangeStart',function(obj,data){ //checkingSession(); }); }); })();
/* @license dhtmlxGantt v.3.1.1 Stardard This software is covered by GPL license. You also can obtain Commercial or Enterprise license to use it in non-GPL project - please contact sales@dhtmlx.com. Usage without proper license is prohibited. (c) Dinamenta, UAB. */ gantt.locale = { date: { month_full: ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"], month_short: ["Sty", "Lut", "Mar", "Kwi", "Maj", "Cze", "Lip", "Sie", "Wrz", "Paź", "Lis", "Gru"], day_full: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota"], day_short: ["Nie", "Pon", "Wto", "Śro", "Czw", "Pią", "Sob"] }, labels: { dhx_cal_today_button: "Dziś", day_tab: "Dzień", week_tab: "Tydzień", month_tab: "Miesiąc", new_event: "Nowe zdarzenie", icon_save: "Zapisz", icon_cancel: "Anuluj", icon_details: "Szczegóły", icon_edit: "Edytuj", icon_delete: "Usuń", confirm_closing: "", //Zmiany zostaną usunięte, jesteś pewien? confirm_deleting: "Zdarzenie zostanie usunięte na zawsze, kontynuować?", section_description: "Opis", section_time: "Okres czasu", section_type: "Typ", /* grid columns */ column_text : "Nazwa zadania", column_start_date : "Początek", column_duration : "Czas trwania", column_add : "", /* link confirmation */ link: "Link", confirm_link_deleting:"zostanie usunięty", link_start: " (początek)", link_end: " (koniec)", type_task: "Zadanie", type_project: "Projekt", type_milestone: "Milestone", minutes: "Minuty", hours: "Godziny", days: "Dni", weeks: "Tydzień", months: "Miesiące", years: "Lata" } };
'use strict' var cssShorthandProperties = require('css-shorthand-properties').shorthandProperties module.exports = function isCssShorthand (property) { if (typeof property !== 'string') { throw new TypeError('is-css-shorthand expected a string') } return Object.keys(cssShorthandProperties).indexOf(property.toLowerCase()) !== -1 }
/* * Export named constants only * e.g. * export const MY_ACTION_CONST = 'MY_ACTION_CONST'; * export const MY_ACTION_2_CONST = 'MY_ACTION_2_CONST'; * * This allows for proper ES6 module importing into files * e.g. * import { MY_ACTION_CONST } from './constants' */
$(document).ready(function() { $('form').submit(function(e) { $(".alert").remove(); var user = $("#userBox").val(); var pass = $("#passBox").val(); if (user.length>15 || user.length<2) { $("#userBox").val(""); $("<p class='alert' style='color:#E83C3C'>*Please select a username between 2-15 characters long</p>").insertAfter("#userBox"); e.preventDefault(); } else if (pass.length<8) { $("#passBox").val(""); $("<p class='alert' style='color:#E83C3C'>*Please select a password greater than 8 characters long.</p>").insertAfter("#passBox"); e.preventDefault(); } else { } }) ; });
/** * RTMFP - The Protocol * * Copyright 2011 OpenRTMFP * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License received along this program for more * details (or else see http://www.gnu.org/licenses/). * * This file is a part of ArcusNode. */ var net = require('net'); var Packet = require('./packet.js'); var AMF = require('./amf.js'); var AMF0 = require('./amf0.js'); var rtmfp = require('../build/default/rtmfp.node'); //Packet Markers var RTMFP_MARKER_HANDSHAKE = 0x0b, RTMFP_MARKER_MESSAGE_1 = 0x0d, RTMFP_MARKER_MESSAGE_2 = 0x8d, RTMFP_MARKER_MESSAGE_3 = 0x89, RTMFP_MARKER_MESSAGE_4 = 0x09, RTMFP_MARKER_RESPONSE_1 = 0x4e, RTMFP_MARKER_RESPONSE_2 = 0x4a, RTMFP_VALID_MARKERS = [0x8d, 0x8e, 0x8a, 0x0d, 0x0b, 0x89, 0x09, 0x49, 0x4e, 0x4a, 0x0e]; RTMFP_VALID_MESSAGES = [0x10, 0x11, 0x30, 0x38, 0x51, 0x01, 0x41, 0x0c, 0x4c, 0x18, 0x71, 0x70, 0x78, 0x5e]; /** * RTMFP * TODO: handle connect and address message as command * TODO: the deltaNack in a command is an index for a command flow */ var RTMFP = module.exports = function(){ var _rtmfp = new rtmfp.RTMFP(); var _epoch = (function(){ var d = new Date(); return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()); })(); /** * Read RTMFP Messages from a packet and return message objects in an array */ this.readPacket = function(pkt){ messages = []; pkt.pos(6); var marker = pkt.readInt8(); if (RTMFP_VALID_MARKERS.indexOf(marker) == -1){ throw new Error('Ivalid packet marker ' + marker); } var time1 = pkt.readInt16(); var time2 = 0; var message = null; //with echo time if ((marker | 0xF0) == 0xFD || marker == 0x4e || marker == 0x0e) { time2 = pkt.readInt16(); } while(pkt.available() > 0 && RTMFP_VALID_MESSAGES.indexOf(pkt.peek()) != -1) { message = this.readMessage(pkt, message); if(message) { var now = _timeNow(); message.receivedTime = now; message.sentTime = time1; message.echoTime = time2; if(time2 > 0) message.latency = now - time2; messages.push(message); } } return messages; }; /** * Read a single message from a packet */ this.readMessage = function(pkt, lastMessage){ var type = pkt.readInt8(); //Ensure packet bytes if(pkt.available() < 2) return null; var messageSize = pkt.readInt16(); //Ensure packet bytes if(pkt.available() < messageSize){ return null; } //Clip packet to size var clippedPkt = new Packet(pkt.readBytes(messageSize), messageSize); var message = null; switch(type) { // // FORWARD_REQUEST // case 0x71: message = { type: RTMFP.FORWARD_REQUEST }; message.tag = clippedPkt.readBytes(clippedPkt.readInt8(), true); message.addresses = []; //TODO: read IPv6 also while(clippedPkt.available() > 0 && clippedPkt.readInt8() ) { message.addresses.push(this.readRawIpv4(clippedPkt)); } break; // // Message: HANDSHAKE_REQUEST / RENDEZVOUZ_REQUEST // case 0x30: var msgLength; //Two times the message length clippedPkt.readU29(); msgLength = clippedPkt.readU29(); var handshakeType = clippedPkt.readInt8(); //Rendevouz if(handshakeType == 0x0f) { if(clippedPkt.available() > 32){ message = { type: RTMFP.RENDEZVOUZ_REQUEST }; message.peerIds = [clippedPkt.readBytes(32, true)]; //Read more than one peer id while(clippedPkt.available() > 36 && clippedPkt.peek() == 0x11){ clippedPkt.skip(1); if(clippedPkt.readInt16() == 34 && clippedPkt.readInt16() == 11){ message.peerIds.push(clippedPkt.readBytes(32, true)); } else { throw new Error('Tried to read more than one peer id for rendezvouz but failed. ' + pkt.toString()); } } } } else if(handshakeType == 0x0a) { if(clippedPkt.available() >= msgLength - 1){ message = { type: RTMFP.HANDSHAKE_REQUEST }; //URL connected to message.url = clippedPkt.readBytes(msgLength - 1).toString('ascii'); } } if(message != null && clippedPkt.available() >= 16){ message.tag = clippedPkt.readBytes(16, true); } else { message = null; } if(message == null){ throw new Error('Tried to read malicious handshake packet: ' + pkt.toString()); } break; // // HANDSHAKE_RESPONSE // case 0x70: message = { type: RTMFP.HANDSHAKE_RESPONSE }; message.tag = clippedPkt.readBytes(clippedPkt.readInt8(), true); message.cookie = clippedPkt.readBytes(clippedPkt.readInt8()); message.certificate = clippedPkt.readBytes(clippedPkt.size() - clippedPkt.pos()); break; // // KEY_RESPONSE // case 0x78: message = { type: RTMFP.KEY_RESPONSE }; message.connectionId = clippedPkt.readInt32(); clippedPkt.skip(1); message.signature = clippedPkt.readBytes(clippedPkt.readInt8()); message.publicKey = clippedPkt.readBytes(clippedPkt.size() - clippedPkt.pos() - 1); break; // // Message: KEY_REQUEST // case 0x38: message = { type: RTMFP.KEY_REQUEST }; message.connectionId = clippedPkt.readInt32(); var cookie_size = clippedPkt.readInt8(); if(cookie_size != 64) { throw new Error('COOKIE SIZE != 64'); } message.cookie = clippedPkt.readBytes(cookie_size); var keySize = clippedPkt.readU29(); var pos = clippedPkt.pos(); message.clientSignature = clippedPkt.readBytes(4); message.publicKey = clippedPkt.readBytes(keySize - 4); clippedPkt.pos(pos); var keyPlusSig = clippedPkt.readBytes(keySize); var certificate_size = clippedPkt.readInt8(); if(certificate_size != 76) { throw new Error('handshake client certificate size exceeded!'); } message.clientCertificate = clippedPkt.readBytes(certificate_size); //Compute the client peer id if(!keyPlusSig || keySize == 0){ throw new Error('Cannot compute peer id without correct arguments'); } message.peerId = _rtmfp.computePeerId(keyPlusSig, keySize); break; // // Message: KEEPALIVE_REQUEST // case 0x01: message = { type: RTMFP.KEEPALIVE_REQUEST }; break; // // Message: KEEPALIVE_RESPONSE // case 0x41 : message = { type: RTMFP.KEEPALIVE_RESPONSE }; break; // // Message: NET_CONNECTION_CLOSE // case 0x0c: case 0x4c: message = { type: RTMFP.NET_CONNECTION_CLOSE }; break; // // Message: ACK and NACK // case 0x51: var sequence = clippedPkt.readInt8(); var ackMarker = clippedPkt.readInt8(); if(ackMarker == 0xFF) //happens after response is resend many times... { ackMarker = clippedPkt.readInt8(); } message = { type: (ackMarker == 0x7f) ? RTMFP.ACK : RTMFP.NOT_ACK }; message.sequence = sequence; message.stage = clippedPkt.readInt8(); break; // // Message: NC_FAILED_REQUEST // raises "NetConnection.Connect.Failed" on client // case 0x5e: message = { type: RTMFP.NC_FAILED_REQUEST }; message.sequence = clippedPkt.readInt8(); break; // // Message: UNKNOWN // case 0x18: throw new Error('UNHANDLED MESSAGE TYPE 0x18'); break; // // Message: SEQUENCE (RPC || GROUP) // TODO: handle 91 2E F8 CE 3B 05 09 E2 B6 10 00 04 03 03 02 01 -> Asking for ack // case 0x10 : case 0x11 : message = {}; message.flag = clippedPkt.readInt8(); // 0x80 extended header, 0x00 non extended header //Sometimes 11 00 01 03 is appended to Group Join, don't know why... if(messageSize == 1 || clippedPkt.available() < 3) { return null; } if(type == 0x11 && lastMessage != null) { message.sequence = lastMessage.sequence; message.stage = lastMessage.stage; message.delta = lastMessage.delta; if(lastMessage.signature) { message.signature = lastMessage.signature; } } else { message.sequence = clippedPkt.readInt8(); message.stage = clippedPkt.readInt8(); message.delta = clippedPkt.readInt8(); } if(message.flag == 0x80 || message.flag == 0x83) { message.signature = clippedPkt.readBytes(clippedPkt.readInt8(), true); } //Flag 0x03 is connect failed answer/retry without header (when connection request was acknowledged) //Flag 0x83 is connect failed answer/retry WITH header/signature (if connection request was NOT acknowledged if(message.flag == 0x83 || message.flag == 0x03){ return message; } if(message.sequence == 0x02) { //TODO: investigate message.unknown2 = clippedPkt.readBytes(6); //TODO: Add by Liang: To fix reading NET_CONNECTION_RESPONSE var a = message.unknown2[0], b = message.unknown2[1], c = message.unknown2[2]; // console.log(a,b,c); if(a == 0x02){ message.unknown2 = [0x00, 0x14, 0x00, 0x00, 0x00, 0x01]; clippedPkt.readBytes(3); } if(a == 4 && b == 0 && c == 0){ NET_CONNECTION_ADDRESSES_RESPONSE = 100; message.type = NET_CONNECTION_ADDRESSES_RESPONSE; return message; } var __pos = clippedPkt.pos(); if(a == 0x14 && b == 0x00){ //COMMAND response clippedPkt.pos(__pos - 1); // console.log(clippedPkt.peek()); } // END, Liang message.commandName = AMF0.readString(clippedPkt); message.commandHandle = AMF0.readNumber(clippedPkt); switch(message.commandName) { //Handle NetConnection case 'connect': message.type = RTMFP.NET_CONNECTION_REQUEST; //Read AMF Data //TODO: only read AMF data if null marker message.commandData = AMF.readAMF0(clippedPkt); break; //Handle Addresses for NetConnection //TODO: handle as command outside case 'setPeerInfo': message.type = RTMFP.NET_CONNECTION_ADDRESSES; clippedPkt.skip(1); message.addresses = []; while(clippedPkt.available() > 3 && clippedPkt.readInt8() == 0x02) { message.addresses.push(this.readAddress(clippedPkt)); } break; //read command object and return it with message default: //Read AMF Data message.type = RTMFP.COMMAND; //TODO: only read AMF data if null marker message.commandData = AMF.readAMF0(clippedPkt); break; } } //NetGroup stage 1 else if(message.sequence > 0x02 && message.stage == 0x01) { message.type = RTMFP.NET_GROUP_JOIN; message.unknown1 = clippedPkt.readBytes(2); //Unknown data clippedPkt.skip(3); message.groupId = clippedPkt.readBytes(clippedPkt.readU29(), true); } //NetGroup stage 2 else if(message.sequence > 0x02 && message.stage == 0x02) { message.type = RTMFP.NET_GROUP_LEAVE; } break; default: throw new Error('Unhandled Message: ', pkt.toString()); break; } return message; }; /** * Writes a message to a packet * TODO: rename to writeMessage() ??? */ this.writePacket = function(pkt, message){ pkt.pos(6); switch(message.type) { // // HANDSHAKE_RESPONSE // case RTMFP.HANDSHAKE_RESPONSE: pkt.writeInt8(RTMFP_MARKER_HANDSHAKE); pkt.writeInt16(_timeNow()); pkt.writeInt8(0x70); pkt.writeInt16(16 + message.cookie.length + 77 + 2); pkt.writeInt8(16); pkt.writeBuffer(message.tag); pkt.writeInt8(message.cookie.length); pkt.writeBuffer(message.cookie); pkt.writeBytes([0x01,0x0A,0x41,0x0E]) if(message.certificate.length != 64){ throw new Error('Incorrect certificate for handshake response'); } pkt.writeBuffer(message.certificate); pkt.writeBytes([0x02,0x15,0x02,0x02,0x15,0x05,0x02,0x15,0x0E]) break; // // HANDSHAKE_REQUEST // case RTMFP.HANDSHAKE_REQUEST: pkt.writeInt8(RTMFP_MARKER_HANDSHAKE); pkt.writeInt16(_timeNow()); pkt.writeInt8(0x30); pkt.writeInt16(message.tag.length + message.url.length + 3); //write url size pkt.writeU29(message.url.length + 2); pkt.writeU29(message.url.length + 1); pkt.writeInt8(0x0a); pkt.writeString(message.url); pkt.writeBuffer(message.tag); break; // // FORWARD_REQUEST // case RTMFP.FORWARD_REQUEST: pkt.writeInt8(RTMFP_MARKER_HANDSHAKE); pkt.writeInt16(_timeNow()); pkt.writeInt8(0x71); var sizePos = pkt.pos(); pkt.skip(2); //size placeholder pkt.writeInt8(16); pkt.writeBuffer(message.tag); for(var i = 0; i < message.endpoints.length; i++) { this.writeAddress(pkt, message.endpoints[i], false); } //write size finally writeSize(pkt, sizePos, pkt.size() - sizePos - 2); break; // // KEY_RESPONSE // case RTMFP.KEY_RESPONSE: pkt.writeInt8(RTMFP_MARKER_HANDSHAKE); pkt.writeInt16(_timeNow()); pkt.writeInt8(0x78); var nonce = this.createServerNonce(message.publicKey); pkt.writeInt16(nonce.length + 7); pkt.writeInt32(message.connectionId); //Todo: writeU29 method for packet //pkt.writeU29(server_signature.size() + sizeof(message.server_key)); pkt.writeU29(nonce.length); pkt.writeBuffer(nonce); pkt.writeInt8(0x58); break; // // KEY_REQUEST // case RTMFP.KEY_REQUEST: pkt.writeInt8(RTMFP_MARKER_HANDSHAKE); pkt.writeInt16(_timeNow()); pkt.writeInt8(0x38); var sizePos = pkt.pos(); pkt.skip(2); //size placeholder pkt.writeInt32(message.connectionId); pkt.writeInt8(message.cookie.length); pkt.writeBuffer(message.cookie); //TODO: write real keysize and signature pkt.writeBytes([0x81, 0x04, 0x81, 0x02, 0x1d, 0x02]); pkt.writeBuffer(message.publicKey); var nonce = this.createClientNonce(message.certificate); pkt.writeU29(nonce.length); pkt.writeBuffer(nonce); pkt.writeInt8(0x58); //write size finally writeSize(pkt, sizePos, pkt.size() - sizePos - 2); break; // // NET_CONNECTION_REQUEST // case RTMFP.NET_CONNECTION_REQUEST: if(!message.echoTime){ pkt.writeInt8(RTMFP_MARKER_MESSAGE_3); pkt.writeInt16(_timeNow()); } else { pkt.writeInt8(RTMFP_MARKER_MESSAGE_2); pkt.writeInt16(_timeNow()); pkt.writeInt16(message.echoTime); } pkt.writeInt8(0x10); var sizePos = pkt.pos(); pkt.skip(2); //size placeholder pkt.writeInt8(0x80); //header flag pkt.writeBytes([0x02, 0x01, 0x01]); //hardcoded for testing sequence, stage, command index pkt.writeBytes([0x05, 0x00, 0x54, 0x43, 0x04, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01]); //hardcoded header AMF0.writeString(pkt, 'connect'); //commandName AMF0.writeNumber(pkt, 1); //commandHandle AMF0.writeObject(pkt, { app: message.app, //rtmfp://127.0.0.1/test <- app/devkey objectEncoding: 3, swfUrl: undefined, pageUrl: undefined, tcUrl: message.url, flashVer: 'WIN 10,2,159,1', fpad: false, capabilities: 235, audioCodecs: 3191, videoCodecs: 252, videoFunction: 1 }); //write size finally writeSize(pkt, sizePos, pkt.size() - sizePos - 2); break; // // NET_CONNECTION_RESPONSE // TODO: add and handle NET_CONNECTION_FAILED & NET_CONNECTION_SUCCESS // case RTMFP.NET_CONNECTION_RESPONSE: //Todo: check if response was sent multiple times and after //30 sec send response without echo time (message.sentTime and message.echoTime) //TODO: No echo time if latency > 30 sec pkt.writeInt8(RTMFP_MARKER_RESPONSE_1); //response with echo time pkt.writeInt16(_timeNow()); pkt.writeInt16(message.sentTime); // Prepare response pkt.writeInt8(0x10); var sizePos = pkt.pos(); pkt.skip(2); //size placeholder pkt.writeInt8(message.flag); pkt.writeInt8(message.sequence); pkt.writeInt8(message.stage); pkt.writeInt8(0x01); // 0x01 flag to ack previus command //Echo message signature //TODO: only echo if flag says so? pkt.writeInt8(message.signature.length); pkt.writeBuffer(message.signature); pkt.writeBytes([0x02, 0x0a, 0x02]); //TODO: replace last byte with sequence id? //Echo yet unknown part from message pkt.writeBuffer(message.unknown2); AMF0.writeString(pkt, '_result'); AMF0.writeNumber(pkt, message.commandHandle); AMF0.writeNull(pkt); //Write success status object AMF0.writeObject(pkt, { objectEncoding: 3, //We only can take 3 for rtmfp, otherwise flash fails connection description: 'Connection succeeded', level: 'status', code: 'NetConnection.Connect.Success' }); //write size finally writeSize(pkt, sizePos, pkt.size() - sizePos - 2); break; // // Response: COMMAND_RESULT // Response: COMMAND_ERROR // case RTMFP.COMMAND_RESULT: case RTMFP.COMMAND_ERROR: //TODO: No echo time if latency > 30 sec pkt.writeInt8(RTMFP_MARKER_RESPONSE_1); //response with echo time pkt.writeInt16(_timeNow()); pkt.writeInt16(message.sentTime); // Prepare response pkt.writeInt8(0x10); var sizePos = pkt.pos(); pkt.skip(2); //size placeholder pkt.writeInt8(message.flag); pkt.writeInt8(message.sequence); pkt.writeInt8(message.stage); pkt.writeInt8(0x01); // 0x01 flag to ack previous command pkt.writeInt8(0x14); pkt.writeInt32(0x00); AMF0.writeString(pkt, (message.type === RTMFP.COMMAND_RESULT) ? '_result' : '_error'); AMF0.writeNumber(pkt, message.commandHandle); //AMF0 NULL MARKER to close header AMF0.writeNull(pkt); if(message.type === RTMFP.COMMAND_RESULT) { //write response AMF if(typeof message.commandData !== 'undefined'){ AMF0.writeValue(pkt, message.commandData); } } else if(message.type === RTMFP.COMMAND_ERROR) { var statusObject = { level: 'error', code: 'NetConnection.Call.Failed' }; if(typeof message.statusDescription === 'string') { statusObject.description = message.statusDescription; } //write response AMF AMF0.writeObject(pkt, statusObject); } //write size finally writeSize(pkt, sizePos, pkt.size() - sizePos - 2); break; // // Response: NET_CONNECTION_ADDRESSES // case RTMFP.NET_CONNECTION_ADDRESSES: //TODO: No echo time if latency > 30 sec pkt.writeInt8(RTMFP_MARKER_RESPONSE_1); //response with echo time pkt.writeInt16(_timeNow()); pkt.writeInt16(message.sentTime); if(message.stage == 0x02) { pkt.writeInt8(0x10); pkt.writeInt16(0x13); pkt.writeBytes([0x00, 0x02, 0x02, 0x01, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29]); pkt.writeInt32(message.serverKeepalive); pkt.writeInt32(message.clientKeepalive); } break; // // Response: NET_CONNECTION_CLOSE // case RTMFP.NET_CONNECTION_CLOSE: //form close message pkt.writeInt8(RTMFP_MARKER_RESPONSE_2); //response without echo time pkt.writeInt16(_timeNow()); pkt.writeInt8(0x0c); pkt.writeInt16(0); break; // // Response: NET_GROUP_JOIN // case RTMFP.NET_GROUP_JOIN: //TODO: No echo time if latency > 30 sec pkt.writeInt8(RTMFP_MARKER_RESPONSE_1); //response with echo time pkt.writeInt16(_timeNow()); pkt.writeInt16(message.sentTime); this.writeAck(pkt, message.sequence, message.stage, true); //If group exists we have peer ids to add if(message.peers && message.peers.length > 0) { pkt.writeInt8(0x10); var sizePos = pkt.pos(); pkt.skip(2); //size placeholder pkt.writeInt8(message.flag); pkt.writeInt8(message.sequence); pkt.writeInt8(message.stage); pkt.writeInt8(message.delta); pkt.writeInt8(0x03); pkt.writeBuffer(message.signature); pkt.writeBuffer(message.unknown1); pkt.writeInt8(0x03); pkt.writeInt16(0x0b); pkt.writeBuffer(message.peers[0].peerId); //write size finally writeSize(pkt, sizePos, pkt.size() - sizePos - 2); //Append additional peer ids for(var i = 1; i < message.peers.length; i++) { pkt.writeInt8(0x11); pkt.writeInt16(0x22); pkt.writeInt16(0x0b); pkt.writeBuffer(message.peers[i].peerId); } } break; // // Response: NET_GROUP_LEAVE // case RTMFP.NET_GROUP_LEAVE: //TODO: No echo time if latency > 30 sec pkt.writeInt8(RTMFP_MARKER_RESPONSE_1); //response with echo time pkt.writeInt16(_timeNow()); pkt.writeInt16(message.sentTime); this.writeAck(pkt, message.sequence, message.stage, true); break; // // Response: RENDEZVOUZ // case RTMFP.RENDEZVOUZ_RESPONSE: pkt.writeInt8(RTMFP_MARKER_HANDSHAKE); pkt.writeInt16(_timeNow()); pkt.writeInt8(0x71); var sizePos = pkt.pos(); pkt.skip(2); //size placeholder pkt.writeInt8(message.tag.length); pkt.writeBuffer(message.tag); var publicFlag = true; for(var i = 0; i < message.addresses.length; i++) { //TODO: get public/private flag from address itself this.writeAddress(pkt, message.addresses[i], publicFlag); publicFlag = false; } //write size finally writeSize(pkt, sizePos, pkt.size() - sizePos - 2); break; // // Response: RENDEZVOUZ_NEWCOMER // case RTMFP.RENDEZVOUZ_NEWCOMER: //TODO: use a general function to write the correct time depending on echoTime pkt.writeInt8(RTMFP_MARKER_RESPONSE_1); //echo time pkt.writeInt16(_timeNow()); pkt.writeInt16(message.echoTime); pkt.writeInt8(0x0f); var sizePos = pkt.pos(); pkt.skip(2); //size placeholder //TODO: write real size 2x U29 pkt.writeBytes([0x22, 0x21, 0x0f]); //Write Peer Id (of the peer we send the newcomer message to) if(!message.peerId || message.peerId.length != 32){ throw new Error('Peer id for newcomer request mandatory and has to be 32 bytes.'); } pkt.writeBuffer(message.peerId); //TODO: get public/private marker from address itself this.writeAddress(pkt, message.address, message.pp); pkt.writeBuffer(message.tag); //write size finally writeSize(pkt, sizePos, pkt.size() - sizePos - 2); break; // // Response: KEEPALIVE_REQUEST // case RTMFP.KEEPALIVE_REQUEST: break; // // Response: KEEPALIVE // case RTMFP.KEEPALIVE_RESPONSE: //TODO: No echo time if latency > 30 sec pkt.writeInt8(RTMFP_MARKER_RESPONSE_1); //response with echo time pkt.writeInt16(_timeNow()); pkt.writeInt16(message.sentTime); pkt.writeInt8(0x41); pkt.writeInt16(0x0); break; // // Response: ACK // case RTMFP.ACK: pkt.writeInt8(RTMFP_MARKER_RESPONSE_1); //response with echo time pkt.writeInt16(_timeNow()); pkt.writeInt16(message.sentTime); this.writeAck(pkt, message.sequence, message.stage, true); break; // // Response: NACK // case RTMFP.NOT_ACK: pkt.writeInt8(RTMFP_MARKER_RESPONSE_1); //response with echo time pkt.writeInt16(_timeNow()); pkt.writeInt16(message.sentTime); this.writeAck(pkt, message.sequence, message.stage, false); break; // // NC_FAILED_RESPONSE // case RTMFP.NC_FAILED_RESPONSE: pkt.writeInt8(0x8d); //response with echo time pkt.writeInt16(_timeNow()); pkt.writeInt16(message.echoTime); pkt.writeInt8(0x10); pkt.writeInt16(4); pkt.writeInt8(3); pkt.writeInt8(message.sequence); pkt.writeInt8(message.stage); pkt.writeInt8(0); break; // // NC_FAILED_REQUEST // case RTMFP.NC_FAILED_REQUEST: pkt.writeInt8(0x4a); //response without echo time pkt.writeInt16(_timeNow()); pkt.writeInt8(0x5e); pkt.writeInt16(2); pkt.writeInt8(message.sequence); pkt.writeInt8(0); break; // // Response: UNKNOWN // case RTMFP.UNKNOWN: //Do nothing break; } return pkt; }; /** * Writes packet size to given position and returns to current write position */ var writeSize = function(pkt, pos, size) { var lastPos = pkt.pos(); pkt.pos(pos); pkt.writeInt16( pkt.size() - pos - 2); pkt.pos(lastPos); }; /** * Writes ack/nack to the packet */ this.writeAck = function(pkt, sequence, stage, ack) { // Write Acknowledgment pkt.writeInt8(0x51); pkt.writeInt16(3); pkt.writeInt8(sequence); pkt.writeInt8((ack) ? 0x7f : 0x00); pkt.writeInt8(stage); return true; } /** * Read a byte encoded address/port endpoint * * @param {Packet} pkt * @return {endpoint} */ this.readRawIpv4 = function(pkt){ var endpoint = {}; endpoint.address = pkt.readInt8() + '.' + pkt.readInt8() + '.' + pkt.readInt8() + '.' + pkt.readInt8(); endpoint.port = pkt.readInt16(); return endpoint; }; function ipv6ToBytes(ip){ var parts = ip.split(':'); for(k in parts){ if(parts[k] === '0'){ parts[k] = '0000'; } for(var z = 0; z < 4 - parts[k].length; z++){ parts[k] = '0' + parts[k]; } } return new Buffer(parts.join(''), 'hex'); }; /** * Reads an IP address and port combination from a packet */ this.readAddress = function(pkt) { var rawAddress = pkt.readBytes(pkt.readInt16()).toString(); var colonPos = rawAddress.lastIndexOf(':'); var endpoint = { address: rawAddress.substr(0, colonPos)}; if(endpoint.address.substr(0, 1) == '['){ endpoint.address = ipv6ToBytes(endpoint.address.substr(1, endpoint.address.length - 2)); endpoint.is_IPv6 = true; } endpoint.port = rawAddress.substr(colonPos + 1) return endpoint; }; /** * Writes an IP address and port combination to a packet */ this.writeAddress = function(pkt, endpoint, isPublic) { //validate addresses (has address and port) if(!endpoint.address || !endpoint.port) { throw new Error('An endpoint needs an address and a port'); } //TODO: implement endpoint distinction if(endpoint.is_IPv6) { //IPv6 pkt.writeInt8(isPublic ? 0x82 : 0x81); pkt.writeBuffer(endpoint.address); } else { //IPv4 pkt.writeInt8(isPublic ? 0x02 : 0x01); var ipParts = endpoint.address.split('.'); for(k in ipParts){ pkt.writeInt8(ipParts[k]); } } pkt.writeInt16(endpoint.port); }; /** * Reads the connection id from the packet and sets the buffer position to 4 */ this.decodePacket = function(pkt){ pkt.pos(0); var connection_id = 0; for(i = 0; i < 3; ++i) connection_id ^= pkt.readInt32(); pkt.pos(4); return connection_id; }; /** * Adds the connection id to the packet */ this.encodePacket = function(pkt, connectionId){ pkt.pos(4); var encodedId = pkt.readInt32() ^ pkt.readInt32() ^ connectionId; pkt.pos(0); pkt.writeInt32(encodedId); }; /** * Get the checksum for the packet */ this.packetChecksum = function(pkt) { var sum = 0, pos = pkt.pos(); pkt.pos(6); while(pkt.available() > 0) sum += (pkt.available() == 1) ? pkt.readInt8() : pkt.readInt16(); pkt.pos(pos); return _rtmfp.finishChecksum(sum); }; /** * Decrypts the packet with the given key, * returns true if the decrypted packet matches the checksum. */ this.decryptPacket = function(pkt, key) { if(!pkt || !key){ throw new Error('Cannot decrypt with either missing packet or key'); } _rtmfp.decryptBuffer(pkt.buffer(), key, 4); pkt.pos(4); var check = pkt.readInt16(); var comp = this.packetChecksum(pkt); return (check == comp); }; /** * Encrypts the packet with the given key and adds the checksum. */ this.encryptPacket = function(pkt, key){ //Ensure pkt and key are given, otherwise we risk crashing the C Module if(!pkt || !key){ throw new Error('Cannot encrypt with either missing packet or key'); } //Add padding bytes to the end var paddingBytesLength = _rtmfp.paddingLength(pkt.size()); pkt.pos(pkt.size()); for(i = 0; i < paddingBytesLength; i++){ pkt.writeInt8(0xFF); } //Write Checksum pkt.pos(4); var comp = this.packetChecksum(pkt); pkt.writeInt16(comp); pkt.pos(4); var check = pkt.readInt16(); _rtmfp.encryptBuffer(pkt.buffer(), pkt.size(), key, 4); }; /** * Create server nonce part */ this.createServerNonce = function(publicKey){ var serverNonce = new Packet(new Buffer(11 + publicKey.length)); serverNonce.writeBytes([0x03,0x1a,0x00,0x00,0x02,0x1e,0x00,0x81,0x02,0x0d,0x02]); serverNonce.writeBuffer(publicKey); return serverNonce.buffer(); }; /** * Create client nonce part */ this.createClientNonce = function(certificate){ var clientNonce = new Packet(new Buffer(76)); clientNonce.writeBytes([0x02, 0x1d, 0x02, 0x41, 0x0e]); clientNonce.writeBuffer(certificate); clientNonce.writeBytes([0x03, 0x1a, 0x02, 0x0a, 0x02, 0x1e, 0x02]); return clientNonce.buffer(); }; var _timeNow = function() { var d = new Date(); return Math.round((Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()) - _epoch) / 4); }; // TODO: Added by Liang: to access _timeNow for other commands; this._timeNow = _timeNow; this.writeSize = writeSize; this.nativeRTMFP = _rtmfp; }; //statics RTMFP.UNKNOWN = 0x00; RTMFP.RENDEZVOUZ_REQUEST = 0x01; RTMFP.RENDEZVOUZ_RESPONSE = 0x02; RTMFP.RENDEZVOUZ_NEWCOMER = 0x03; RTMFP.HANDSHAKE_REQUEST = 0x04; RTMFP.HANDSHAKE_RESPONSE = 0x05; RTMFP.KEY_REQUEST = 0x06; RTMFP.KEY_RESPONSE = 0x07; RTMFP.KEEPALIVE_REQUEST = 0x08; RTMFP.KEEPALIVE_RESPONSE = 0x09; RTMFP.NET_CONNECTION_CLOSE = 0x0A; RTMFP.NET_CONNECTION_REQUEST = 0x0B; RTMFP.NET_CONNECTION_RESPONSE = 0x0C; RTMFP.NET_GROUP_JOIN = 0x0D; RTMFP.NET_GROUP_LEAVE = 0x0E; RTMFP.NET_CONNECTION_ADDRESSES = 0x0F; RTMFP.ACK = 0x10; RTMFP.NOT_ACK = 0x11; RTMFP.NC_FAILED_REQUEST = 0x12; RTMFP.NC_FAILED_RESPONSE = 0x13; RTMFP.COMMAND = 0x14; RTMFP.COMMAND_RESULT = 0x15; RTMFP.COMMAND_ERROR = 0x16; RTMFP.FORWARD_REQUEST = 0x17; RTMFP.FORWARD_RESPONSE = 0x18; RTMFP.SYMETRIC_KEY = new Buffer('Adobe Systems 02');
import MediaList from 'react-bootstrap/lib/MediaList'; export default MediaList;
var express = require('express') var app = express() app.use(express.logger('dev')) app.use(express.static(__dirname)) app.use(express.static(__dirname + '/..')) app.get('/', function(req, res){ res.sendfile('test/index.html') }) app.listen(4000) console.log('listening on port 4000')
/** * This file was generated by a tool. Modifying it will produce unexpected behavior. */ var key = '_1JArBGDet5Uj9pJOV/9sFw'; var allStrings = (typeof DEPRECATED_UNIT_TEST === 'undefined' || DEPRECATED_UNIT_TEST) ? require("../../resx-strings/en-us.json") : require("resx-strings"); var strings = allStrings[key]; export default strings; //# sourceMappingURL=MobilePreview.resx.js.map
var searchData= [ ['unlinkstringvalue',['unlinkStringValue',['../class_my_string.html#ab6e04b4279403f3b1dcfcae2d8027cda',1,'MyString']]] ];
$(function() { var fileText; var maxFileSizeInBytes = 100000; // 100kB $('#inputFile').change(function () { fileText = null; $('#inputFileResult').hide(); var file = this.files[0]; if (file.type != 'text/plain' && file.type != '') { $.bootstrapGrowl('Only plain text files are allowed', { type: 'danger' }); $('#inputFile').val(null); return; } if (file.size > maxFileSizeInBytes) { $.bootstrapGrowl('File is too big', { type: 'danger' }); $('#inputFile').val(null); return; } var fileReader = new FileReader(); fileReader.readAsText(file); fileReader.onload = function(event) { fileText = event.target.result; $('#inputFileResult').html(fileText.replace(/\n/g, '<br>')); $('#inputFileResult').show(); } fileReader.onerror = function(event) { $.bootstrapGrowl('Something went wrong', { type: 'danger' }); $('#inputFile').val(null); $('#inputFileResult').hide(); } }); $('#fileUploadSubmit').click(function() { if (fileText == null) { $.bootstrapGrowl('Choose a file', { type: 'danger' }); } else { $('#fileUploadSubmit').prop('disabled', 'disabled'); $.post('upload', {text: fileText}, function () { window.location.href = '/'; }); } }); });
'use strict'; // Setting up route angular.module('core').config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { // Redirect to home view when route not found $urlRouterProvider.otherwise('/'); // Home state routing $stateProvider. state('home', { url: '/', templateUrl: 'modules/core/views/home.client.view.html' }). state('learnmore', { url: '/learnmore', templateUrl: 'modules/core/views/learnmore.client.view.html' }); } ]);
'use strict'; var utils = require('lazy-cache')(require); var fn = require; require = utils; /** * Lazily required module dependencies */ require('define-property', 'define'); require('isobject', 'isObject'); require = fn; /** * Expose `utils` modules */ module.exports = utils;
//>>built define(["dojo/_base/lang","./matrix","dojo/_base/Color"],function(q,h,f){function n(a,d,l,e,f,c){a=h.multiplyPoint(l,a,d);e=h.multiplyPoint(e,a);return{r:a,p:e,o:h.multiplyPoint(f,e).x/c}}function r(a,d){return a.o-d.o}var p=q.getObject("dojox.gfx.gradient",!0);p.rescale=function(a,d,l){var e=a.length,h=l<d,c;h&&(c=d,d=l,l=c);if(!e)return[];if(l<=a[0].offset)c=[{offset:0,color:a[0].color},{offset:1,color:a[0].color}];else if(d>=a[e-1].offset)c=[{offset:0,color:a[e-1].color},{offset:1,color:a[e-1].color}]; else{var g=l-d,b,m,k;c=[];0>d&&c.push({offset:0,color:new f(a[0].color)});for(k=0;k<e&&!(b=a[k],b.offset>=d);++k);k?(m=a[k-1],c.push({offset:0,color:f.blendColors(new f(m.color),new f(b.color),(d-m.offset)/(b.offset-m.offset))})):c.push({offset:0,color:new f(b.color)});for(;k<e;++k){b=a[k];if(b.offset>=l)break;c.push({offset:(b.offset-d)/g,color:new f(b.color)})}k<e?(m=a[k-1],c.push({offset:1,color:f.blendColors(new f(m.color),new f(b.color),(l-m.offset)/(b.offset-m.offset))})):c.push({offset:1,color:new f(a[e- 1].color)})}if(h)for(c.reverse(),k=0,e=c.length;k<e;++k)b=c[k],b.offset=1-b.offset;return c};p.project=function(a,d,l,e,f,c){a=a||h.identity;var g=h.multiplyPoint(a,d.x1,d.y1),b=h.multiplyPoint(a,d.x2,d.y2);f=Math.atan2(b.y-g.y,b.x-g.x);c=h.project(b.x-g.x,b.y-g.y);g=h.multiplyPoint(c,g);b=h.multiplyPoint(c,b);g=new h.Matrix2D([h.rotate(-f),{dx:-g.x,dy:-g.y}]);b=h.multiplyPoint(g,b).x;a=[n(l.x,l.y,a,c,g,b),n(e.x,e.y,a,c,g,b),n(l.x,e.y,a,c,g,b),n(e.x,l.y,a,c,g,b)].sort(r);d=p.rescale(d.colors,a[0].o, a[3].o);return{type:"linear",x1:a[0].p.x,y1:a[0].p.y,x2:a[3].p.x,y2:a[3].p.y,colors:d,angle:f}};return p});
<<<<<<< HEAD // Last time updated: 2017-04-29 7:05:22 AM UTC ======= // Last time updated at Sep 25, 2015, 08:32:23 >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 // Latest file can be found here: https://cdn.webrtc-experiment.com/DetectRTC.js // Muaz Khan - www.MuazKhan.com // MIT License - www.WebRTC-Experiment.com/licence // Documentation - github.com/muaz-khan/DetectRTC // ____________ // DetectRTC.js // DetectRTC.hasWebcam (has webcam device!) // DetectRTC.hasMicrophone (has microphone device!) // DetectRTC.hasSpeakers (has speakers!) (function() { 'use strict'; <<<<<<< HEAD var browserFakeUserAgent = 'Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45'; var isNodejs = typeof process === 'object' && typeof process.versions === 'object' && process.versions.node; if (isNodejs) { var version = process.versions.node.toString().replace('v', ''); browserFakeUserAgent = 'Nodejs/' + version + ' (NodeOS) AppleWebKit/' + version + ' (KHTML, like Gecko) Nodejs/' + version + ' Nodejs/' + version } (function(that) { if (typeof window !== 'undefined') { return; } if (typeof window === 'undefined' && typeof global !== 'undefined') { global.navigator = { userAgent: browserFakeUserAgent, getUserMedia: function() {} }; /*global window:true */ that.window = global; } else if (typeof window === 'undefined') { // window = this; } if (typeof document === 'undefined') { /*global document:true */ that.document = {}; document.createElement = document.captureStream = document.mozCaptureStream = function() { return {}; }; } if (typeof location === 'undefined') { /*global location:true */ that.location = { protocol: 'file:', href: '', hash: '' }; } if (typeof screen === 'undefined') { /*global screen:true */ that.screen = { width: 0, height: 0 }; } })(typeof global !== 'undefined' ? global : window); /*global navigator:true */ var navigator = window.navigator; ======= var navigator = window.navigator; if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) { // Firefox 38+ seems having support of enumerateDevices // Thanks @xdumaine/enumerateDevices navigator.enumerateDevices = function(callback) { navigator.mediaDevices.enumerateDevices().then(callback); }; } >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 if (typeof navigator !== 'undefined') { if (typeof navigator.webkitGetUserMedia !== 'undefined') { navigator.getUserMedia = navigator.webkitGetUserMedia; } if (typeof navigator.mozGetUserMedia !== 'undefined') { navigator.getUserMedia = navigator.mozGetUserMedia; } } else { navigator = { <<<<<<< HEAD getUserMedia: function() {}, userAgent: browserFakeUserAgent }; } var isMobileDevice = !!(/Android|webOS|iPhone|iPad|iPod|BB10|BlackBerry|IEMobile|Opera Mini|Mobile|mobile/i.test(navigator.userAgent || '')); var isEdge = navigator.userAgent.indexOf('Edge') !== -1 && (!!navigator.msSaveOrOpenBlob || !!navigator.msSaveBlob); var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; var isFirefox = typeof window.InstallTrigger !== 'undefined'; var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0; var isChrome = !!window.chrome && !isOpera; var isIE = !!document.documentMode && !isEdge; ======= getUserMedia: function() {} }; } var isMobileDevice = !!navigator.userAgent.match(/Android|iPhone|iPad|iPod|BlackBerry|IEMobile/i); var isEdge = navigator.userAgent.indexOf('Edge') !== -1 && (!!navigator.msSaveOrOpenBlob || !!navigator.msSaveBlob); >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 // this one can also be used: // https://www.websocket.org/js/stuff.js (DetectBrowser.js) function getBrowserInfo() { var nVer = navigator.appVersion; var nAgt = navigator.userAgent; var browserName = navigator.appName; var fullVersion = '' + parseFloat(navigator.appVersion); var majorVersion = parseInt(navigator.appVersion, 10); var nameOffset, verOffset, ix; // In Opera, the true version is after 'Opera' or after 'Version' <<<<<<< HEAD if (isOpera) { browserName = 'Opera'; try { fullVersion = navigator.userAgent.split('OPR/')[1].split(' ')[0]; majorVersion = fullVersion.split('.')[0]; } catch (e) { fullVersion = '0.0.0.0'; majorVersion = 0; } } // In MSIE, the true version is after 'MSIE' in userAgent else if (isIE) { verOffset = nAgt.indexOf('MSIE'); browserName = 'IE'; fullVersion = nAgt.substring(verOffset + 5); } // In Chrome, the true version is after 'Chrome' else if (isChrome) { verOffset = nAgt.indexOf('Chrome'); browserName = 'Chrome'; fullVersion = nAgt.substring(verOffset + 7); } // In Safari, the true version is after 'Safari' or after 'Version' else if (isSafari) { verOffset = nAgt.indexOf('Safari'); ======= if ((verOffset = nAgt.indexOf('Opera')) !== -1) { browserName = 'Opera'; fullVersion = nAgt.substring(verOffset + 6); if ((verOffset = nAgt.indexOf('Version')) !== -1) { fullVersion = nAgt.substring(verOffset + 8); } } // In MSIE, the true version is after 'MSIE' in userAgent else if ((verOffset = nAgt.indexOf('MSIE')) !== -1) { browserName = 'IE'; fullVersion = nAgt.substring(verOffset + 5); } // In Chrome, the true version is after 'Chrome' else if ((verOffset = nAgt.indexOf('Chrome')) !== -1) { browserName = 'Chrome'; fullVersion = nAgt.substring(verOffset + 7); } // In Safari, the true version is after 'Safari' or after 'Version' else if ((verOffset = nAgt.indexOf('Safari')) !== -1) { >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 browserName = 'Safari'; fullVersion = nAgt.substring(verOffset + 7); if ((verOffset = nAgt.indexOf('Version')) !== -1) { fullVersion = nAgt.substring(verOffset + 8); } } <<<<<<< HEAD // In Firefox, the true version is after 'Firefox' else if (isFirefox) { verOffset = nAgt.indexOf('Firefox'); ======= // In Firefox, the true version is after 'Firefox' else if ((verOffset = nAgt.indexOf('Firefox')) !== -1) { >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 browserName = 'Firefox'; fullVersion = nAgt.substring(verOffset + 8); } <<<<<<< HEAD // In most other browsers, 'name/version' is at the end of userAgent ======= // In most other browsers, 'name/version' is at the end of userAgent >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) { browserName = nAgt.substring(nameOffset, verOffset); fullVersion = nAgt.substring(verOffset + 1); if (browserName.toLowerCase() === browserName.toUpperCase()) { browserName = navigator.appName; } } if (isEdge) { browserName = 'Edge'; // fullVersion = navigator.userAgent.split('Edge/')[1]; <<<<<<< HEAD fullVersion = parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10).toString(); ======= fullVersion = parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10); >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 } // trim the fullVersion string at semicolon/space if present if ((ix = fullVersion.indexOf(';')) !== -1) { fullVersion = fullVersion.substring(0, ix); } if ((ix = fullVersion.indexOf(' ')) !== -1) { fullVersion = fullVersion.substring(0, ix); } majorVersion = parseInt('' + fullVersion, 10); if (isNaN(majorVersion)) { fullVersion = '' + parseFloat(navigator.appVersion); majorVersion = parseInt(navigator.appVersion, 10); } return { fullVersion: fullVersion, version: majorVersion, <<<<<<< HEAD name: browserName, isPrivateBrowsing: false }; } // via: https://gist.github.com/cou929/7973956 function retry(isDone, next) { var currentTrial = 0, maxRetry = 50, interval = 10, isTimeout = false; var id = window.setInterval( function() { if (isDone()) { window.clearInterval(id); next(isTimeout); } if (currentTrial++ > maxRetry) { window.clearInterval(id); isTimeout = true; next(isTimeout); } }, 10 ); } function isIE10OrLater(userAgent) { var ua = userAgent.toLowerCase(); if (ua.indexOf('msie') === 0 && ua.indexOf('trident') === 0) { return false; } var match = /(?:msie|rv:)\s?([\d\.]+)/.exec(ua); if (match && parseInt(match[1], 10) >= 10) { return true; } return false; } function detectPrivateMode(callback) { var isPrivate; try { if (window.webkitRequestFileSystem) { window.webkitRequestFileSystem( window.TEMPORARY, 1, function() { isPrivate = false; }, function(e) { isPrivate = true; } ); } else if (window.indexedDB && /Firefox/.test(window.navigator.userAgent)) { var db; try { db = window.indexedDB.open('test'); db.onerror = function() { return true; }; } catch (e) { isPrivate = true; } if (typeof isPrivate === 'undefined') { retry( function isDone() { return db.readyState === 'done' ? true : false; }, function next(isTimeout) { if (!isTimeout) { isPrivate = db.result ? false : true; } } ); } } else if (isIE10OrLater(window.navigator.userAgent)) { isPrivate = false; try { if (!window.indexedDB) { isPrivate = true; } } catch (e) { isPrivate = true; } } else if (window.localStorage && /Safari/.test(window.navigator.userAgent)) { try { window.localStorage.setItem('test', 1); } catch (e) { isPrivate = true; } if (typeof isPrivate === 'undefined') { isPrivate = false; window.localStorage.removeItem('test'); } } } catch (e) { isPrivate = false; } retry( function isDone() { return typeof isPrivate !== 'undefined' ? true : false; }, function next(isTimeout) { callback(isPrivate); } ); } ======= name: browserName }; } >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 var isMobile = { Android: function() { return navigator.userAgent.match(/Android/i); }, BlackBerry: function() { <<<<<<< HEAD return navigator.userAgent.match(/BlackBerry|BB10/i); ======= return navigator.userAgent.match(/BlackBerry/i); >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 }, iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Opera: function() { return navigator.userAgent.match(/Opera Mini/i); }, Windows: function() { return navigator.userAgent.match(/IEMobile/i); }, any: function() { return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); }, getOsName: function() { var osName = 'Unknown OS'; if (isMobile.Android()) { osName = 'Android'; } if (isMobile.BlackBerry()) { osName = 'BlackBerry'; } if (isMobile.iOS()) { osName = 'iOS'; } if (isMobile.Opera()) { osName = 'Opera Mini'; } if (isMobile.Windows()) { osName = 'Windows'; } return osName; } }; <<<<<<< HEAD // via: http://jsfiddle.net/ChristianL/AVyND/ function detectDesktopOS() { var unknown = '-'; var nVer = navigator.appVersion; var nAgt = navigator.userAgent; var os = unknown; var clientStrings = [{ s: 'Windows 10', r: /(Windows 10.0|Windows NT 10.0)/ }, { s: 'Windows 8.1', r: /(Windows 8.1|Windows NT 6.3)/ }, { s: 'Windows 8', r: /(Windows 8|Windows NT 6.2)/ }, { s: 'Windows 7', r: /(Windows 7|Windows NT 6.1)/ }, { s: 'Windows Vista', r: /Windows NT 6.0/ }, { s: 'Windows Server 2003', r: /Windows NT 5.2/ }, { s: 'Windows XP', r: /(Windows NT 5.1|Windows XP)/ }, { s: 'Windows 2000', r: /(Windows NT 5.0|Windows 2000)/ }, { s: 'Windows ME', r: /(Win 9x 4.90|Windows ME)/ }, { s: 'Windows 98', r: /(Windows 98|Win98)/ }, { s: 'Windows 95', r: /(Windows 95|Win95|Windows_95)/ }, { s: 'Windows NT 4.0', r: /(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/ }, { s: 'Windows CE', r: /Windows CE/ }, { s: 'Windows 3.11', r: /Win16/ }, { s: 'Android', r: /Android/ }, { s: 'Open BSD', r: /OpenBSD/ }, { s: 'Sun OS', r: /SunOS/ }, { s: 'Linux', r: /(Linux|X11)/ }, { s: 'iOS', r: /(iPhone|iPad|iPod)/ }, { s: 'Mac OS X', r: /Mac OS X/ }, { s: 'Mac OS', r: /(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/ }, { s: 'QNX', r: /QNX/ }, { s: 'UNIX', r: /UNIX/ }, { s: 'BeOS', r: /BeOS/ }, { s: 'OS/2', r: /OS\/2/ }, { s: 'Search Bot', r: /(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/ }]; for (var i = 0, cs; cs = clientStrings[i]; i++) { if (cs.r.test(nAgt)) { os = cs.s; break; } } var osVersion = unknown; if (/Windows/.test(os)) { if (/Windows (.*)/.test(os)) { osVersion = /Windows (.*)/.exec(os)[1]; } os = 'Windows'; } switch (os) { case 'Mac OS X': if (/Mac OS X (10[\.\_\d]+)/.test(nAgt)) { osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1]; } break; case 'Android': if (/Android ([\.\_\d]+)/.test(nAgt)) { osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1]; } break; case 'iOS': if (/OS (\d+)_(\d+)_?(\d+)?/.test(nAgt)) { osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer); osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0); } break; } return { osName: os, osVersion: osVersion }; } var osName = 'Unknown OS'; var osVersion = 'Unknown OS Version'; function getAndroidVersion(ua) { ua = (ua || navigator.userAgent).toLowerCase(); var match = ua.match(/android\s([0-9\.]*)/); return match ? match[1] : false; } var osInfo = detectDesktopOS(); if (osInfo && osInfo.osName && osInfo.osName != '-') { osName = osInfo.osName; osVersion = osInfo.osVersion; } else if (isMobile.any()) { osName = isMobile.getOsName(); if (osName == 'Android') { osVersion = getAndroidVersion(); } } var isNodejs = typeof process === 'object' && typeof process.versions === 'object' && process.versions.node; if (osName === 'Unknown OS' && isNodejs) { osName = 'Nodejs'; osVersion = process.versions.node.toString().replace('v', ''); } ======= var osName = 'Unknown OS'; if (isMobile.any()) { osName = isMobile.getOsName(); } else { if (navigator.appVersion.indexOf('Win') !== -1) { osName = 'Windows'; } if (navigator.appVersion.indexOf('Mac') !== -1) { osName = 'MacOS'; } if (navigator.appVersion.indexOf('X11') !== -1) { osName = 'UNIX'; } if (navigator.appVersion.indexOf('Linux') !== -1) { osName = 'Linux'; } } >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 var isCanvasSupportsStreamCapturing = false; var isVideoSupportsStreamCapturing = false; ['captureStream', 'mozCaptureStream', 'webkitCaptureStream'].forEach(function(item) { <<<<<<< HEAD if (!isCanvasSupportsStreamCapturing && item in document.createElement('canvas')) { isCanvasSupportsStreamCapturing = true; } if (!isVideoSupportsStreamCapturing && item in document.createElement('video')) { ======= // asdf if (item in document.createElement('canvas')) { isCanvasSupportsStreamCapturing = true; } if (item in document.createElement('video')) { >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 isVideoSupportsStreamCapturing = true; } }); // via: https://github.com/diafygi/webrtc-ips function DetectLocalIPAddress(callback) { <<<<<<< HEAD if (!DetectRTC.isWebRTCSupported) { return; } if (DetectRTC.isORTCSupported) { return; } ======= >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 getIPs(function(ip) { //local IPs if (ip.match(/^(192\.168\.|169\.254\.|10\.|172\.(1[6-9]|2\d|3[01]))/)) { callback('Local: ' + ip); } //assume the rest are public IPs else { callback('Public: ' + ip); } }); } //get the IP addresses associated with an account function getIPs(callback) { var ipDuplicates = {}; //compatibility for firefox and chrome var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; var useWebKit = !!window.webkitRTCPeerConnection; // bypass naive webrtc blocking using an iframe if (!RTCPeerConnection) { var iframe = document.getElementById('iframe'); if (!iframe) { //<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe> throw 'NOTE: you need to have an iframe in the page right above the script tag.'; } var win = iframe.contentWindow; RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection; useWebKit = !!win.webkitRTCPeerConnection; } <<<<<<< HEAD // if still no RTCPeerConnection then it is not supported by the browser so just return if (!RTCPeerConnection) { return; } ======= >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 //minimal requirements for data connection var mediaConstraints = { optional: [{ RtpDataChannels: true }] }; //firefox already has a default stun server in about:config // media.peerconnection.default_iceservers = // [{"url": "stun:stun.services.mozilla.com"}] var servers; //add same stun server for chrome if (useWebKit) { servers = { iceServers: [{ urls: 'stun:stun.services.mozilla.com' }] }; if (typeof DetectRTC !== 'undefined' && DetectRTC.browser.isFirefox && DetectRTC.browser.version <= 38) { servers[0] = { url: servers[0].urls }; } } //construct a new RTCPeerConnection var pc = new RTCPeerConnection(servers, mediaConstraints); function handleCandidate(candidate) { //match just the IP address var ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/; <<<<<<< HEAD var match = ipRegex.exec(candidate); if (!match) { console.warn('Could not match IP address in', candidate); return; } var ipAddress = match[1]; ======= var ipAddress = ipRegex.exec(candidate)[1]; >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 //remove duplicates if (ipDuplicates[ipAddress] === undefined) { callback(ipAddress); } ipDuplicates[ipAddress] = true; } //listen for candidate events pc.onicecandidate = function(ice) { //skip non-candidate events if (ice.candidate) { handleCandidate(ice.candidate.candidate); } }; //create a bogus data channel pc.createDataChannel(''); //create an offer sdp pc.createOffer(function(result) { //trigger the stun server request pc.setLocalDescription(result, function() {}, function() {}); }, function() {}); //wait for a while to let everything done setTimeout(function() { //read candidate info from local description var lines = pc.localDescription.sdp.split('\n'); lines.forEach(function(line) { if (line.indexOf('a=candidate:') === 0) { handleCandidate(line); } }); }, 1000); } var MediaDevices = []; <<<<<<< HEAD var audioInputDevices = []; var audioOutputDevices = []; var videoInputDevices = []; if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) { // Firefox 38+ seems having support of enumerateDevices // Thanks @xdumaine/enumerateDevices navigator.enumerateDevices = function(callback) { navigator.mediaDevices.enumerateDevices().then(callback).catch(function() { callback([]); }); }; } // Media Devices detection ======= // ---------- Media Devices detection >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 var canEnumerate = false; /*global MediaStreamTrack:true */ if (typeof MediaStreamTrack !== 'undefined' && 'getSources' in MediaStreamTrack) { canEnumerate = true; } else if (navigator.mediaDevices && !!navigator.mediaDevices.enumerateDevices) { canEnumerate = true; } <<<<<<< HEAD var hasMicrophone = false; var hasSpeakers = false; var hasWebcam = false; var isWebsiteHasMicrophonePermissions = false; var isWebsiteHasWebcamPermissions = false; // http://dev.w3.org/2011/webrtc/editor/getusermedia.html#mediadevices function checkDeviceSupport(callback) { if (!canEnumerate) { if (callback) { callback(); } return; } ======= var hasMicrophone = canEnumerate; var hasSpeakers = canEnumerate; var hasWebcam = canEnumerate; // http://dev.w3.org/2011/webrtc/editor/getusermedia.html#mediadevices // todo: switch to enumerateDevices when landed in canary. function checkDeviceSupport(callback) { // This method is useful only for Chrome! >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 if (!navigator.enumerateDevices && window.MediaStreamTrack && window.MediaStreamTrack.getSources) { navigator.enumerateDevices = window.MediaStreamTrack.getSources.bind(window.MediaStreamTrack); } if (!navigator.enumerateDevices && navigator.enumerateDevices) { navigator.enumerateDevices = navigator.enumerateDevices.bind(navigator); } if (!navigator.enumerateDevices) { if (callback) { callback(); } return; } MediaDevices = []; <<<<<<< HEAD audioInputDevices = []; audioOutputDevices = []; videoInputDevices = []; isWebsiteHasMicrophonePermissions = false; isWebsiteHasWebcamPermissions = false; // to prevent duplication var alreadyUsedDevices = {}; ======= >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 navigator.enumerateDevices(function(devices) { devices.forEach(function(_device) { var device = {}; for (var d in _device) { <<<<<<< HEAD try { if (typeof _device[d] !== 'function') { device[d] = _device[d]; } } catch (e) {} } if (alreadyUsedDevices[device.deviceId + device.label]) { ======= device[d] = _device[d]; } var skip; MediaDevices.forEach(function(d) { if (d.id === device.id) { skip = true; } }); if (skip) { >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 return; } // if it is MediaStreamTrack.getSources if (device.kind === 'audio') { device.kind = 'audioinput'; } if (device.kind === 'video') { device.kind = 'videoinput'; } if (!device.deviceId) { device.deviceId = device.id; } if (!device.id) { device.id = device.deviceId; } if (!device.label) { device.label = 'Please invoke getUserMedia once.'; <<<<<<< HEAD if (DetectRTC.browser.isChrome && DetectRTC.browser.version >= 46 && !/^(https:|chrome-extension:)$/g.test(location.protocol || '')) { if (document.domain.search && document.domain.search(/localhost|127.0./g) === -1) { device.label = 'HTTPs is required to get label of this ' + device.kind + ' device.'; } } } else { if (device.kind === 'videoinput' && !isWebsiteHasWebcamPermissions) { isWebsiteHasWebcamPermissions = true; } if (device.kind === 'audioinput' && !isWebsiteHasMicrophonePermissions) { isWebsiteHasMicrophonePermissions = true; } } if (device.kind === 'audioinput') { hasMicrophone = true; if (audioInputDevices.indexOf(device) === -1) { audioInputDevices.push(device); } ======= if (!isHTTPs) { device.label = 'HTTPs is required to get label of this ' + device.kind + ' device.'; } } if (device.kind === 'audioinput' || device.kind === 'audio') { hasMicrophone = true; >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 } if (device.kind === 'audiooutput') { hasSpeakers = true; <<<<<<< HEAD if (audioOutputDevices.indexOf(device) === -1) { audioOutputDevices.push(device); } } if (device.kind === 'videoinput') { hasWebcam = true; if (videoInputDevices.indexOf(device) === -1) { videoInputDevices.push(device); } } // there is no 'videoouput' in the spec. MediaDevices.push(device); alreadyUsedDevices[device.deviceId + device.label] = device; }); if (typeof DetectRTC !== 'undefined') { // to sync latest outputs ======= } if (device.kind === 'videoinput' || device.kind === 'video') { hasWebcam = true; } // there is no 'videoouput' in the spec. MediaDevices.push(device); }); if (typeof DetectRTC !== 'undefined') { >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 DetectRTC.MediaDevices = MediaDevices; DetectRTC.hasMicrophone = hasMicrophone; DetectRTC.hasSpeakers = hasSpeakers; DetectRTC.hasWebcam = hasWebcam; <<<<<<< HEAD DetectRTC.isWebsiteHasWebcamPermissions = isWebsiteHasWebcamPermissions; DetectRTC.isWebsiteHasMicrophonePermissions = isWebsiteHasMicrophonePermissions; DetectRTC.audioInputDevices = audioInputDevices; DetectRTC.audioOutputDevices = audioOutputDevices; DetectRTC.videoInputDevices = videoInputDevices; ======= >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 } if (callback) { callback(); } }); } // check for microphone/camera support! checkDeviceSupport(); <<<<<<< HEAD var DetectRTC = window.DetectRTC || {}; ======= var DetectRTC = {}; >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 // ---------- // DetectRTC.browser.name || DetectRTC.browser.version || DetectRTC.browser.fullVersion DetectRTC.browser = getBrowserInfo(); <<<<<<< HEAD detectPrivateMode(function(isPrivateBrowsing) { DetectRTC.browser.isPrivateBrowsing = !!isPrivateBrowsing; }); // DetectRTC.isChrome || DetectRTC.isFirefox || DetectRTC.isEdge DetectRTC.browser['is' + DetectRTC.browser.name] = true; // ----------- DetectRTC.osName = osName; DetectRTC.osVersion = osVersion; var isNodeWebkit = typeof process === 'object' && typeof process.versions === 'object' && process.versions['node-webkit']; // --------- Detect if system supports WebRTC 1.0 or WebRTC 1.1. var isWebRTCSupported = false; ['RTCPeerConnection', 'webkitRTCPeerConnection', 'mozRTCPeerConnection', 'RTCIceGatherer'].forEach(function(item) { if (isWebRTCSupported) { return; } ======= // DetectRTC.isChrome || DetectRTC.isFirefox || DetectRTC.isEdge DetectRTC.browser['is' + DetectRTC.browser.name] = true; var isHTTPs = location.protocol === 'https:'; var isNodeWebkit = !!(window.process && (typeof window.process === 'object') && window.process.versions && window.process.versions['node-webkit']); // --------- Detect if system supports WebRTC 1.0 or WebRTC 1.1. var isWebRTCSupported = false; ['webkitRTCPeerConnection', 'mozRTCPeerConnection', 'RTCIceGatherer'].forEach(function(item) { >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 if (item in window) { isWebRTCSupported = true; } }); DetectRTC.isWebRTCSupported = isWebRTCSupported; //------- DetectRTC.isORTCSupported = typeof RTCIceGatherer !== 'undefined'; // --------- Detect if system supports screen capturing API var isScreenCapturingSupported = false; if (DetectRTC.browser.isChrome && DetectRTC.browser.version >= 35) { isScreenCapturingSupported = true; } else if (DetectRTC.browser.isFirefox && DetectRTC.browser.version >= 34) { isScreenCapturingSupported = true; } <<<<<<< HEAD if (!/^(https:|chrome-extension:)$/g.test(location.protocol || '')) { if (document.domain.search && document.domain.search(/localhost|127.0./g) === -1) { // DetectRTC.browser.isChrome isScreenCapturingSupported = false; } if (DetectRTC.browser.isFirefox) { isScreenCapturingSupported = false; } ======= if (!isHTTPs) { isScreenCapturingSupported = false; >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 } DetectRTC.isScreenCapturingSupported = isScreenCapturingSupported; // --------- Detect if WebAudio API are supported <<<<<<< HEAD var webAudio = { isSupported: false, isCreateMediaStreamSourceSupported: false }; ['AudioContext', 'webkitAudioContext', 'mozAudioContext', 'msAudioContext'].forEach(function(item) { if (webAudio.isSupported) { return; } if (item in window) { webAudio.isSupported = true; if (window[item] && 'createMediaStreamSource' in window[item].prototype) { ======= var webAudio = {}; ['AudioContext', 'webkitAudioContext', 'mozAudioContext', 'msAudioContext'].forEach(function(item) { if (webAudio.isSupported && webAudio.isCreateMediaStreamSourceSupported) { return; } if (item in window) { webAudio.isSupported = true; if ('createMediaStreamSource' in window[item].prototype) { >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 webAudio.isCreateMediaStreamSourceSupported = true; } } }); DetectRTC.isAudioContextSupported = webAudio.isSupported; DetectRTC.isCreateMediaStreamSourceSupported = webAudio.isCreateMediaStreamSourceSupported; // ---------- Detect if SCTP/RTP channels are supported. var isRtpDataChannelsSupported = false; if (DetectRTC.browser.isChrome && DetectRTC.browser.version > 31) { isRtpDataChannelsSupported = true; } DetectRTC.isRtpDataChannelsSupported = isRtpDataChannelsSupported; var isSCTPSupportd = false; if (DetectRTC.browser.isFirefox && DetectRTC.browser.version > 28) { isSCTPSupportd = true; } else if (DetectRTC.browser.isChrome && DetectRTC.browser.version > 25) { isSCTPSupportd = true; } else if (DetectRTC.browser.isOpera && DetectRTC.browser.version >= 11) { isSCTPSupportd = true; } DetectRTC.isSctpDataChannelsSupported = isSCTPSupportd; // --------- DetectRTC.isMobileDevice = isMobileDevice; // "isMobileDevice" boolean is defined in "getBrowserInfo.js" // ------ <<<<<<< HEAD ======= DetectRTC.isWebSocketsSupported = 'WebSocket' in window && 2 === window.WebSocket.CLOSING; DetectRTC.isWebSocketsBlocked = 'Checking'; if (DetectRTC.isWebSocketsSupported) { var websocket = new WebSocket('wss://echo.websocket.org:443/'); websocket.onopen = function() { DetectRTC.isWebSocketsBlocked = false; if (DetectRTC.loadCallback) { DetectRTC.loadCallback(); } }; websocket.onerror = function() { DetectRTC.isWebSocketsBlocked = true; if (DetectRTC.loadCallback) { DetectRTC.loadCallback(); } }; } // ------ >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 var isGetUserMediaSupported = false; if (navigator.getUserMedia) { isGetUserMediaSupported = true; } else if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { isGetUserMediaSupported = true; } <<<<<<< HEAD if (DetectRTC.browser.isChrome && DetectRTC.browser.version >= 46 && !/^(https:|chrome-extension:)$/g.test(location.protocol || '')) { if (document.domain.search && document.domain.search(/localhost|127.0./g) === -1) { isGetUserMediaSupported = 'Requires HTTPs'; } } if (DetectRTC.osName === 'Nodejs') { isGetUserMediaSupported = false; } DetectRTC.isGetUserMediaSupported = isGetUserMediaSupported; var displayResolution = ''; if (screen.width) { var width = (screen.width) ? screen.width : ''; var height = (screen.height) ? screen.height : ''; displayResolution += '' + width + ' x ' + height; } DetectRTC.displayResolution = displayResolution; ======= if (DetectRTC.browser.isChrome && DetectRTC.browser.version >= 47 && !isHTTPs) { DetectRTC.isGetUserMediaSupported = 'Requires HTTPs'; } DetectRTC.isGetUserMediaSupported = isGetUserMediaSupported; // ----------- DetectRTC.osName = osName; // "osName" is defined in "detectOSName.js" >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 // ---------- DetectRTC.isCanvasSupportsStreamCapturing = isCanvasSupportsStreamCapturing; DetectRTC.isVideoSupportsStreamCapturing = isVideoSupportsStreamCapturing; <<<<<<< HEAD if (DetectRTC.browser.name == 'Chrome' && DetectRTC.browser.version >= 53) { if (!DetectRTC.isCanvasSupportsStreamCapturing) { DetectRTC.isCanvasSupportsStreamCapturing = 'Requires chrome flag: enable-experimental-web-platform-features'; } if (!DetectRTC.isVideoSupportsStreamCapturing) { DetectRTC.isVideoSupportsStreamCapturing = 'Requires chrome flag: enable-experimental-web-platform-features'; } } // ------ DetectRTC.DetectLocalIPAddress = DetectLocalIPAddress; DetectRTC.isWebSocketsSupported = 'WebSocket' in window && 2 === window.WebSocket.CLOSING; DetectRTC.isWebSocketsBlocked = !DetectRTC.isWebSocketsSupported; if (DetectRTC.osName === 'Nodejs') { DetectRTC.isWebSocketsSupported = true; DetectRTC.isWebSocketsBlocked = false; } DetectRTC.checkWebSocketsSupport = function(callback) { callback = callback || function() {}; try { var websocket = new WebSocket('wss://echo.websocket.org:443/'); websocket.onopen = function() { DetectRTC.isWebSocketsBlocked = false; callback(); websocket.close(); websocket = null; }; websocket.onerror = function() { DetectRTC.isWebSocketsBlocked = true; callback(); }; } catch (e) { DetectRTC.isWebSocketsBlocked = true; callback(); } }; // ------- DetectRTC.load = function(callback) { callback = callback || function() {}; ======= // ------ DetectRTC.DetectLocalIPAddress = DetectLocalIPAddress; // ------- DetectRTC.load = function(callback) { this.loadCallback = callback; >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 checkDeviceSupport(callback); }; DetectRTC.MediaDevices = MediaDevices; DetectRTC.hasMicrophone = hasMicrophone; DetectRTC.hasSpeakers = hasSpeakers; DetectRTC.hasWebcam = hasWebcam; <<<<<<< HEAD DetectRTC.isWebsiteHasWebcamPermissions = isWebsiteHasWebcamPermissions; DetectRTC.isWebsiteHasMicrophonePermissions = isWebsiteHasMicrophonePermissions; DetectRTC.audioInputDevices = audioInputDevices; DetectRTC.audioOutputDevices = audioOutputDevices; DetectRTC.videoInputDevices = videoInputDevices; ======= >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 // ------ var isSetSinkIdSupported = false; if ('setSinkId' in document.createElement('video')) { isSetSinkIdSupported = true; } DetectRTC.isSetSinkIdSupported = isSetSinkIdSupported; // ----- var isRTPSenderReplaceTracksSupported = false; <<<<<<< HEAD if (DetectRTC.browser.isFirefox && typeof mozRTCPeerConnection !== 'undefined' /*&& DetectRTC.browser.version > 39*/ ) { ======= if (DetectRTC.browser.isFirefox /*&& DetectRTC.browser.version > 39*/ ) { >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 /*global mozRTCPeerConnection:true */ if ('getSenders' in mozRTCPeerConnection.prototype) { isRTPSenderReplaceTracksSupported = true; } <<<<<<< HEAD } else if (DetectRTC.browser.isChrome && typeof webkitRTCPeerConnection !== 'undefined') { ======= } else if (DetectRTC.browser.isChrome) { >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 /*global webkitRTCPeerConnection:true */ if ('getSenders' in webkitRTCPeerConnection.prototype) { isRTPSenderReplaceTracksSupported = true; } } DetectRTC.isRTPSenderReplaceTracksSupported = isRTPSenderReplaceTracksSupported; //------ var isRemoteStreamProcessingSupported = false; if (DetectRTC.browser.isFirefox && DetectRTC.browser.version > 38) { isRemoteStreamProcessingSupported = true; } DetectRTC.isRemoteStreamProcessingSupported = isRemoteStreamProcessingSupported; //------- var isApplyConstraintsSupported = false; /*global MediaStreamTrack:true */ if (typeof MediaStreamTrack !== 'undefined' && 'applyConstraints' in MediaStreamTrack.prototype) { isApplyConstraintsSupported = true; } DetectRTC.isApplyConstraintsSupported = isApplyConstraintsSupported; //------- var isMultiMonitorScreenCapturingSupported = false; if (DetectRTC.browser.isFirefox && DetectRTC.browser.version >= 43) { // version 43 merely supports platforms for multi-monitors // version 44 will support exact multi-monitor selection i.e. you can select any monitor for screen capturing. isMultiMonitorScreenCapturingSupported = true; } DetectRTC.isMultiMonitorScreenCapturingSupported = isMultiMonitorScreenCapturingSupported; <<<<<<< HEAD DetectRTC.isPromisesSupported = !!('Promise' in window); if (typeof DetectRTC === 'undefined') { window.DetectRTC = {}; } var MediaStream = window.MediaStream; if (typeof MediaStream === 'undefined' && typeof webkitMediaStream !== 'undefined') { MediaStream = webkitMediaStream; } if (typeof MediaStream !== 'undefined') { DetectRTC.MediaStream = Object.keys(MediaStream.prototype); } else DetectRTC.MediaStream = false; if (typeof MediaStreamTrack !== 'undefined') { DetectRTC.MediaStreamTrack = Object.keys(MediaStreamTrack.prototype); } else DetectRTC.MediaStreamTrack = false; var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; if (typeof RTCPeerConnection !== 'undefined') { DetectRTC.RTCPeerConnection = Object.keys(RTCPeerConnection.prototype); } else DetectRTC.RTCPeerConnection = false; window.DetectRTC = DetectRTC; if (typeof module !== 'undefined' /* && !!module.exports*/ ) { module.exports = DetectRTC; } if (typeof define === 'function' && define.amd) { define('DetectRTC', [], function() { return DetectRTC; }); } ======= window.DetectRTC = DetectRTC; >>>>>>> 3c996bd0bf2e56dd992323760e6bb5dc4e47df98 })();
/* * * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import controllableMixin from './controllableMixin.js'; import H from './../../parts/Globals.js'; import MockPoint from './../MockPoint.js'; import Tooltip from '../../parts/Tooltip.js'; import U from './../../parts/Utilities.js'; var extend = U.extend, format = U.format, isNumber = U.isNumber, merge = U.merge, pick = U.pick; import '../../parts/SVGRenderer.js'; /* eslint-disable no-invalid-this, valid-jsdoc */ /** * A controllable label class. * * @requires modules/annotations * * @private * @class * @name Highcharts.AnnotationControllableLabel * * @param {Highcharts.Annotation} annotation * An annotation instance. * @param {Highcharts.AnnotationsLabelOptions} options * A label's options. * @param {number} index * Index of the label. */ var ControllableLabel = function (annotation, options, index) { this.init(annotation, options, index); this.collection = 'labels'; }; /** * Shapes which do not have background - the object is used for proper * setting of the contrast color. * * @type {Array<string>} */ ControllableLabel.shapesWithoutBackground = ['connector']; /** * Returns new aligned position based alignment options and box to align to. * It is almost a one-to-one copy from SVGElement.prototype.align * except it does not use and mutate an element * * @param {Highcharts.AnnotationAlignObject} alignOptions * * @param {Highcharts.BBoxObject} box * * @return {Highcharts.PositionObject} * Aligned position. */ ControllableLabel.alignedPosition = function (alignOptions, box) { var align = alignOptions.align, vAlign = alignOptions.verticalAlign, x = (box.x || 0) + (alignOptions.x || 0), y = (box.y || 0) + (alignOptions.y || 0), alignFactor, vAlignFactor; if (align === 'right') { alignFactor = 1; } else if (align === 'center') { alignFactor = 2; } if (alignFactor) { x += (box.width - (alignOptions.width || 0)) / alignFactor; } if (vAlign === 'bottom') { vAlignFactor = 1; } else if (vAlign === 'middle') { vAlignFactor = 2; } if (vAlignFactor) { y += (box.height - (alignOptions.height || 0)) / vAlignFactor; } return { x: Math.round(x), y: Math.round(y) }; }; /** * Returns new alignment options for a label if the label is outside the * plot area. It is almost a one-to-one copy from * Series.prototype.justifyDataLabel except it does not mutate the label and * it works with absolute instead of relative position. */ ControllableLabel.justifiedOptions = function (chart, label, alignOptions, alignAttr) { var align = alignOptions.align, verticalAlign = alignOptions.verticalAlign, padding = label.box ? 0 : (label.padding || 0), bBox = label.getBBox(), off, // options = { align: align, verticalAlign: verticalAlign, x: alignOptions.x, y: alignOptions.y, width: label.width, height: label.height }, // x = alignAttr.x - chart.plotLeft, y = alignAttr.y - chart.plotTop; // Off left off = x + padding; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } } // Off right off = x + bBox.width - padding; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } } // Off top off = y + padding; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } } // Off bottom off = y + bBox.height - padding; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } } return options; }; /** * A map object which allows to map options attributes to element attributes * * @type {Highcharts.Dictionary<string>} */ ControllableLabel.attrsMap = { backgroundColor: 'fill', borderColor: 'stroke', borderWidth: 'stroke-width', zIndex: 'zIndex', borderRadius: 'r', padding: 'padding' }; merge(true, ControllableLabel.prototype, controllableMixin, /** @lends Annotation.ControllableLabel# */ { /** * Translate the point of the label by deltaX and deltaY translations. * The point is the label's anchor. * * @param {number} dx translation for x coordinate * @param {number} dy translation for y coordinate **/ translatePoint: function (dx, dy) { controllableMixin.translatePoint.call(this, dx, dy, 0); }, /** * Translate x and y position relative to the label's anchor. * * @param {number} dx translation for x coordinate * @param {number} dy translation for y coordinate **/ translate: function (dx, dy) { var chart = this.annotation.chart, // Annotation.options labelOptions = this.annotation.userOptions, // Chart.options.annotations annotationIndex = chart.annotations.indexOf(this.annotation), chartAnnotations = chart.options.annotations, chartOptions = chartAnnotations[annotationIndex], temp; if (chart.inverted) { temp = dx; dx = dy; dy = temp; } // Local options: this.options.x += dx; this.options.y += dy; // Options stored in chart: chartOptions[this.collection][this.index].x = this.options.x; chartOptions[this.collection][this.index].y = this.options.y; labelOptions[this.collection][this.index].x = this.options.x; labelOptions[this.collection][this.index].y = this.options.y; }, render: function (parent) { var options = this.options, attrs = this.attrsFromOptions(options), style = options.style; this.graphic = this.annotation.chart.renderer .label('', 0, -9999, // #10055 options.shape, null, null, options.useHTML, null, 'annotation-label') .attr(attrs) .add(parent); if (!this.annotation.chart.styledMode) { if (style.color === 'contrast') { style.color = this.annotation.chart.renderer.getContrast(ControllableLabel.shapesWithoutBackground.indexOf(options.shape) > -1 ? '#FFFFFF' : options.backgroundColor); } this.graphic .css(options.style) .shadow(options.shadow); } if (options.className) { this.graphic.addClass(options.className); } this.graphic.labelrank = options.labelrank; controllableMixin.render.call(this); }, redraw: function (animation) { var options = this.options, text = this.text || options.format || options.text, label = this.graphic, point = this.points[0], show = false, anchor, attrs; label.attr({ text: text ? format(text, point.getLabelConfig(), this.annotation.chart) : options.formatter.call(point, this) }); anchor = this.anchor(point); attrs = this.position(anchor); show = attrs; if (show) { label.alignAttr = attrs; attrs.anchorX = anchor.absolutePosition.x; attrs.anchorY = anchor.absolutePosition.y; label[animation ? 'animate' : 'attr'](attrs); } else { label.attr({ x: 0, y: -9999 // #10055 }); } label.placed = Boolean(show); controllableMixin.redraw.call(this, animation); }, /** * All basic shapes don't support alignTo() method except label. * For a controllable label, we need to subtract translation from * options. */ anchor: function () { var anchor = controllableMixin.anchor.apply(this, arguments), x = this.options.x || 0, y = this.options.y || 0; anchor.absolutePosition.x -= x; anchor.absolutePosition.y -= y; anchor.relativePosition.x -= x; anchor.relativePosition.y -= y; return anchor; }, /** * Returns the label position relative to its anchor. * * @param {Highcharts.AnnotationAnchorObject} anchor * * @return {Highcharts.PositionObject|null} */ position: function (anchor) { var item = this.graphic, chart = this.annotation.chart, point = this.points[0], itemOptions = this.options, anchorAbsolutePosition = anchor.absolutePosition, anchorRelativePosition = anchor.relativePosition, itemPosition, alignTo, itemPosRelativeX, itemPosRelativeY, showItem = point.series.visible && MockPoint.prototype.isInsidePlot.call(point); if (showItem) { if (itemOptions.distance) { itemPosition = Tooltip.prototype.getPosition.call({ chart: chart, distance: pick(itemOptions.distance, 16) }, item.width, item.height, { plotX: anchorRelativePosition.x, plotY: anchorRelativePosition.y, negative: point.negative, ttBelow: point.ttBelow, h: (anchorRelativePosition.height || anchorRelativePosition.width) }); } else if (itemOptions.positioner) { itemPosition = itemOptions.positioner.call(this); } else { alignTo = { x: anchorAbsolutePosition.x, y: anchorAbsolutePosition.y, width: 0, height: 0 }; itemPosition = ControllableLabel.alignedPosition(extend(itemOptions, { width: item.width, height: item.height }), alignTo); if (this.options.overflow === 'justify') { itemPosition = ControllableLabel.alignedPosition(ControllableLabel.justifiedOptions(chart, item, itemOptions, itemPosition), alignTo); } } if (itemOptions.crop) { itemPosRelativeX = itemPosition.x - chart.plotLeft; itemPosRelativeY = itemPosition.y - chart.plotTop; showItem = chart.isInsidePlot(itemPosRelativeX, itemPosRelativeY) && chart.isInsidePlot(itemPosRelativeX + item.width, itemPosRelativeY + item.height); } } return showItem ? itemPosition : null; } }); /* ********************************************************************** */ /** * General symbol definition for labels with connector * @private */ H.SVGRenderer.prototype.symbols.connector = function (x, y, w, h, options) { var anchorX = options && options.anchorX, anchorY = options && options.anchorY, path, yOffset, lateral = w / 2; if (isNumber(anchorX) && isNumber(anchorY)) { path = [['M', anchorX, anchorY]]; // Prefer 45 deg connectors yOffset = y - anchorY; if (yOffset < 0) { yOffset = -h - yOffset; } if (yOffset < w) { lateral = anchorX < x + (w / 2) ? yOffset : w - yOffset; } // Anchor below label if (anchorY > y + h) { path.push(['L', x + lateral, y + h]); // Anchor above label } else if (anchorY < y) { path.push(['L', x + lateral, y]); // Anchor left of label } else if (anchorX < x) { path.push(['L', x, y + h / 2]); // Anchor right of label } else if (anchorX > x + w) { path.push(['L', x + w, y + h / 2]); } } return path || []; }; export default ControllableLabel;
export const SHOW_ALL = 0; export const SHOW_MARKED = 1; export const SHOW_UNMARKED = 2;
/* global helpDescribe, ngDescribe, it, la, sinon */ helpDescribe('ng-alertify', function () { var check = window.check; ngDescribe({ name: 'alertify service', only: false, modules: 'Alertify', inject: ['Alertify', '$rootScope'], tests: function (deps) { it('has Alertify injected', function () { la(deps.Alertify); }); it('has main methods', function () { la(check.fn(deps.Alertify.success), 'has success'); la(check.fn(deps.Alertify.error), 'has error'); la(check.fn(deps.Alertify.log), 'has log method'); }); it('it can be spied on', function () { sinon.spy(deps.Alertify, 'success'); deps.Alertify.success('everything is ok'); la(deps.Alertify.success.called); deps.Alertify.success.restore(); }); it('replaces new lines with break tags in log method', function () { sinon.spy(window.alertify, 'log'); deps.Alertify.log('line 1\nline 2'); var logString = window.alertify.log.lastCall.args[0]; la(logString.indexOf('<br>') !== -1); la(logString.indexOf('\n') === -1); window.alertify.log.restore(); }); it('replaces new lines with break tags in error method', function () { sinon.spy(window.alertify, 'error'); // make sure to remove all new lines deps.Alertify.error('line 1\nline 2\nline 3'); var logString = window.alertify.error.lastCall.args[0]; la(logString.indexOf('<br>') !== -1); la(logString.indexOf('\n') === -1); window.alertify.error.restore(); }); it('accepts multiple string arguments', function () { sinon.spy(window.alertify, 'error'); deps.Alertify.error('foo', 'bar', 'baz'); var logString = window.alertify.error.lastCall.args[0]; la(logString === 'foo bar baz'); window.alertify.error.restore(); }); it('supports Error instances', function () { sinon.spy(window.alertify, 'error'); deps.Alertify.error('foo', new Error('bar')); var logString = window.alertify.error.lastCall.args[0]; la(logString === 'foo bar'); window.alertify.error.restore(); }); it('has promise-returning confirm', function (done) { function confirm(message, cb, cssClass) { la(message === 'foo'); la(cssClass === 'bar-class'); cb('ok'); } var stub = sinon.stub(window.alertify, 'confirm', confirm); deps.Alertify.confirm('foo', 'bar-class') .then(function (result) { la(result === 'ok'); }, function rejected() { la(false, 'unexpected rejection'); }) .finally(function () { stub.restore(); done(); }); deps.$rootScope.$apply(); }); } }); ngDescribe({ name: 'alertify meta', only: false, modules: 'Alertify', inject: 'meta', tests: function (deps) { // TODO: move to check-more-types check.semver = function semver(value) { if (!check.unemptyString(value)) { return false; } var parts = value.split('.'); if (parts.length !== 3) { return false; } return check.number(parseInt(parts[0])) && check.number(parseInt(parts[1])) && check.number(parseInt(parts[2])); }; it('has meaningful meta', function () { la(check.object(deps.meta)); la(check.unemptyString(deps.meta.name)); la(check.unemptyString(deps.meta.version)); la(check.semver(deps.meta.version)); }); } }); });
import { BufferGeometry } from '../core/BufferGeometry.js'; import { Float32BufferAttribute } from '../core/BufferAttribute.js'; import { Vector3 } from '../math/Vector3.js'; import { Vector2 } from '../math/Vector2.js'; class CircleGeometry extends BufferGeometry { constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) { super(); this.type = 'CircleGeometry'; this.parameters = { radius: radius, segments: segments, thetaStart: thetaStart, thetaLength: thetaLength }; segments = Math.max( 3, segments ); // buffers const indices = []; const vertices = []; const normals = []; const uvs = []; // helper variables const vertex = new Vector3(); const uv = new Vector2(); // center point vertices.push( 0, 0, 0 ); normals.push( 0, 0, 1 ); uvs.push( 0.5, 0.5 ); for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) { const segment = thetaStart + s / segments * thetaLength; // vertex vertex.x = radius * Math.cos( segment ); vertex.y = radius * Math.sin( segment ); vertices.push( vertex.x, vertex.y, vertex.z ); // normal normals.push( 0, 0, 1 ); // uvs uv.x = ( vertices[ i ] / radius + 1 ) / 2; uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; uvs.push( uv.x, uv.y ); } // indices for ( let i = 1; i <= segments; i ++ ) { indices.push( i, i + 1, 0 ); } // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); } } export { CircleGeometry, CircleGeometry as CircleBufferGeometry };
let commentFormIsOpen = new ReactiveVar(false); BlazeComponent.extendComponent({ template() { return 'commentForm'; }, onDestroyed() { commentFormIsOpen.set(false); }, commentFormIsOpen() { return commentFormIsOpen.get(); }, getInput() { return this.$('.js-new-comment-input'); }, events() { return [{ 'click .js-new-comment:not(.focus)': function() { commentFormIsOpen.set(true); }, 'submit .js-new-comment-form': function(evt) { let input = this.getInput(); if ($.trim(input.val())) { CardComments.insert({ boardId: this.currentData().boardId, cardId: this.currentData()._id, text: input.val() }); resetCommentInput(input); Tracker.flush(); autosize.update(input); } evt.preventDefault(); }, // Pressing Ctrl+Enter should submit the form 'keydown form textarea': function(evt) { if (evt.keyCode === 13 && (evt.metaKey || evt.ctrlKey)) { this.find('button[type=submit]').click(); } } }]; } }).register('commentForm'); // XXX This should be a static method of the `commentForm` component function resetCommentInput(input) { input.val(''); input.blur(); commentFormIsOpen.set(false); } // XXX This should handled a `onUpdated` callback of the `commentForm` component // but since this callback doesn't exists, and `onRendered` is not called if the // data is not destroyed and recreated, we simulate the desired callback using // Tracker.autorun to register the component dependencies, and re-run when these // dependencies are invalidated. A better component API would remove this hack. Tracker.autorun(() => { Session.get('currentCard'); Tracker.afterFlush(() => { autosize.update($('.js-new-comment-input')); }); }) EscapeActions.register('inlinedForm', function() { const draftKey = { fieldName: 'cardComment', docId: Session.get('currentCard') }; let commentInput = $('.js-new-comment-input'); if ($.trim(commentInput.val())) { UnsavedEdits.set(draftKey, commentInput.val()); } else { UnsavedEdits.reset(draftKey); } resetCommentInput(commentInput); }, function() { return commentFormIsOpen.get(); }, { noClickEscapeOn: '.js-new-comment' } );
'use strict'; const EVENT = require('./constants.js').EVENT; const debug = require('./common.js').debug; const matches = require('./common.js').matches; const denormaliseOptions = require('./config.js'); const shouldAddResourceHints = require('./resource-hints.js').shouldAddResourceHints; const addInitialChunkResourceHints = require('./initial-chunk-resource-hints.js'); const addAsyncChunkResourceHints = require('./async-chunk-resource-hints.js'); const elements = require('./elements.js'); const debugEvent = msg => { debug(`${EVENT}: ${msg}`); }; const falsySafeConcat = arrays => { return arrays.reduce( (combined, array) => array ? combined.concat(array) : combined, [] ); }; class ScriptExtHtmlWebpackPlugin { constructor (options) { this.options = denormaliseOptions(options); } apply (compiler) { const options = this.options; compiler.plugin('compilation', (compilation) => { compilation.plugin(EVENT, (pluginArgs, callback) => { try { debugEvent('starting'); if (elements.shouldUpdate(options)) { debugEvent('replacing <head> <script> elements'); pluginArgs.head = elements.update(compilation, options, pluginArgs.head); debugEvent('replacing <body> <script> elements'); pluginArgs.body = elements.update(compilation, options, pluginArgs.body); } if (shouldAddResourceHints(options)) { debugEvent('adding resource hints'); pluginArgs.head = falsySafeConcat([ pluginArgs.head, addInitialChunkResourceHints(options, pluginArgs.head), addInitialChunkResourceHints(options, pluginArgs.body), addAsyncChunkResourceHints(options, compilation) ]); } debugEvent('completed'); callback(null, pluginArgs); } catch (err) { callback(err); } }); }); compiler.plugin('emit', (compilation, callback) => { if (options.inline.test.length > 0 && options.removeInlinedAssets) { debug('emit: deleting assets'); Object.keys(compilation.assets).forEach((assetName) => { if (matches(assetName, options.inline.test)) { debug(`emit: deleting asset '${assetName}'`); delete compilation.assets[assetName]; } }); } callback(); }); } } module.exports = ScriptExtHtmlWebpackPlugin;
/* This file is part of Ext JS 4 Copyright (c) 2011 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. */ Ext.require('Ext.chart.*'); Ext.require(['Ext.Window', 'Ext.fx.target.Sprite', 'Ext.layout.container.Fit']); Ext.onReady(function () { store1.loadData(generateData()); var win = Ext.create('Ext.Window', { width: 800, height: 600, hidden: false, shadow: false, maximizable: true, style: 'overflow: hidden;', title: 'Filled Radar Chart', renderTo: Ext.getBody(), layout: 'fit', tbar: [{ text: 'Reload Data', handler: function() { store1.loadData(generateData()); } }, { enableToggle: true, pressed: true, text: 'Animate', toggleHandler: function(btn, pressed) { var chart = Ext.getCmp('chartCmp'); chart.animate = pressed ? { easing: 'ease', duration: 500 } : false; } }], items: { id: 'chartCmp', xtype: 'chart', style: 'background:#fff', theme: 'Category2', insetPadding: 20, animate: true, store: store1, legend: { position: 'right' }, axes: [{ type: 'Radial', position: 'radial', label: { display: true } }], series: [{ showInLegend: true, type: 'radar', xField: 'name', yField: 'data1', style: { opacity: 0.4 } },{ showInLegend: true, type: 'radar', xField: 'name', yField: 'data2', style: { opacity: 0.4 } },{ showInLegend: true, type: 'radar', xField: 'name', yField: 'data3', style: { opacity: 0.4 } }] } }); });
'use strict'; /*global rtc: true */ angular.module('mean.rooms').factory('UIHandler',['$window','$timeout',function($window, $timeout){ var _this = this; _this._data = {}; //necessary to avoid asyncronious errors _this._data.safeApply = function(scope, fn) { var phase = scope.$root.$$phase; if(phase === '$apply' || phase === '$digest') { scope.$eval(fn); } else { scope.$apply(fn); } }; _this._data.debug = false; _this._data.version = 'v'+window.loowidVersion; _this._data.node = window.loowidNode; _this.keyboard = { buffer: [], detectCombination: function() { var codes = {}; _this.keyboard.buffer.forEach(function(code) { codes['key' + code] = 1; }); if (codes.key17 && codes.key16 && codes.key68) { rtc.debug = !rtc.debug; var status = (rtc.debug) ? 'enabled' : 'disabled'; console.log ('RTC Debug ' + status); return true; } return false; }, keydown: function(event) { _this.keyboard.buffer.push(event.keyCode); if (_this.keyboard.detectCombination()){ event.preventDefault(); } }, keyup: function(event) { _this.keyboard.buffer = []; event.preventDefault(); } }; document.addEventListener ('keydown',_this.keyboard.keydown); document.addEventListener ('keyup',_this.keyboard.keyup); return _this._data; }]);
// # Quintus moving ball example // // [Run the example](../examples/ball/index.html) // // This is one of the simplest possible examples of using // Quintus that doesn't use the scene/stage functionality, // but rather just creates a single sprite and steps and // draws that sprite // // The goal of the example is to demonstrate the modularity // of the engine and the ability to only include the components // you actually need. // Wait for the load event to start the game. window.addEventListener("load",function() { // Create an instance of the engine, including only // the `Sprites` module, and then call setup to create a // canvas element on the page. If you already have a // canvas element in your page, you can pass the element // or it's id as the first parameter to set up as well. var Q = window.Q = Quintus().include("Sprites").setup({ width: 400, height: 400 }); // The `MovingSprite` class is a descendant of the base `Sprite` class, // all it does is add in a step method to Sprite that runs the standard // 2D motion equations using properties vx, vy for the velocity and ax, ay // to calculate the new x and y positions. Q.MovingSprite.extend("Ball",{ // Sprites by default expect either a `sheet` or an `asset` property // to draw themselves, but by overriding the draw method you can draw a // shape directly on the canvas instead. draw: function(ctx) { ctx.fillStyle = "black"; ctx.beginPath(); ctx.arc(-this.p.cx, -this.p.cy, this.p.w/2,0,Math.PI*2); ctx.fill(); } }); // Create a new instance of the `Ball` Sprite, // passing in the size, position, velocity, and // acceleration var ball = window.ball = new Q.Ball({ w: 20, h: 20, x: 30, y: 300, vx: 30, vy: -100, ax: 0, ay: 30 }); // You can start the game loop directly by // calling `gameLoop` with a callback and Quintus // will set up a requestAnimationFrame powered game loop // for you. Most examples don't call `gameLoop` directly as // calling `stageScene` will start a game loop that takes care // of clearing the canvas and updating and drawing all the stages // for you. Q.gameLoop(function(dt) { // Clear the canvas Q.clear(); // Move the ball `dt` forward in time ball.update(dt); // Render the ball onto the canvas context. ball.render(Q.ctx); }); // ## Possible Experimentations: // // 1. Try adding multiple balls of different positions and sizes // and looping over them manually in game loop // 2. Change the clear color of the canvas // 3. Add in the `Scenes` module and create and stage a scene. });
/** * Copyright (C) 2014-2015 Triumph LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; /** * Object transformation API * @name transform * @namespace * @exports exports as transform */ b4w.module["__transform"] = function(exports, require) { var m_bounds = require("__boundings"); var m_cam = require("__camera"); var m_cons = require("__constraints"); var m_lights = require("__lights"); var m_mat3 = require("__mat3"); var m_mat4 = require("__mat4"); var m_particles = require("__particles"); var m_quat = require("__quat"); var m_scs = require("__scenes"); var m_sfx = require("__sfx"); var m_tsr = require("__tsr"); var m_obj = require("__objects"); var m_obj_util = require("__obj_util"); var m_util = require("__util"); var m_vec3 = require("__vec3"); var m_vec4 = require("__vec4"); var _vec3_tmp = new Float32Array(3); var _quat4_tmp = new Float32Array(4); var _mat3_tmp = new Float32Array(9); var _tsr_tmp = m_tsr.create(); var _tsr_tmp2 = m_tsr.create(); var _elapsed = 0; // transform in world space exports.SPACE_WORLD = 0; // transform in local space exports.SPACE_LOCAL = 1; // transform in parent space exports.SPACE_PARENT = 2; exports.update = function(elapsed) { _elapsed = elapsed; } exports.set_translation = function(obj, trans) { var render = obj.render; if (m_cons.has_child_of(obj)) { m_tsr.set_trans(trans, render.tsr); var tsr_par = m_cons.get_child_of_parent_tsr(obj); var tsr_inv = m_tsr.invert(tsr_par, _tsr_tmp); var offset = m_cons.get_child_of_offset(obj); m_tsr.multiply(tsr_inv, render.tsr, offset); } else m_vec3.copy(trans, render.trans); } exports.set_translation_rel = set_translation_rel; function set_translation_rel(obj, trans) { if (m_cons.has_child_of(obj)) { var offset = m_cons.get_child_of_offset(obj); m_tsr.set_trans(trans, offset); } else { var render = obj.render; m_vec3.copy(trans, render.trans); } } exports.get_translation = function(obj, dest) { m_vec3.copy(obj.render.trans, dest); return dest; } exports.get_translation_rel = function(obj, dest) { if (m_cons.has_child_of(obj)) { var offset = m_cons.get_child_of_offset(obj); m_vec3.copy(m_tsr.get_trans_view(offset), dest); } else { m_vec3.copy(obj.render.trans, dest); } return dest; } exports.set_rotation = set_rotation; function set_rotation(obj, quat) { var render = obj.render; if (m_cons.has_child_of(obj)) { m_tsr.set_quat(quat, render.tsr); var tsr_par = m_cons.get_child_of_parent_tsr(obj); var tsr_inv = m_tsr.invert(tsr_par, _tsr_tmp); var offset = m_cons.get_child_of_offset(obj); m_tsr.multiply(tsr_inv, render.tsr, offset); } else m_quat.copy(quat, render.quat); } exports.set_rotation_rel = set_rotation_rel; function set_rotation_rel(obj, quat) { if (m_cons.has_child_of(obj)) { var offset = m_cons.get_child_of_offset(obj); m_tsr.set_quat(quat, offset); } else { var render = obj.render; m_quat.copy(quat, render.quat); } } exports.get_rotation = function(obj, dest) { m_quat.copy(obj.render.quat, dest); return dest; } exports.get_rotation_rel = function(obj, dest) { if (m_cons.has_child_of(obj)) { var offset = m_cons.get_child_of_offset(obj); m_quat.copy(m_tsr.get_quat_view(offset), dest); } else { m_quat.copy(obj.render.quat, dest); } return dest; } exports.set_rotation_euler = function(obj, euler) { var quat = m_util.euler_to_quat(euler, _quat4_tmp); set_rotation(obj, quat); } exports.set_rotation_euler_rel = function(obj, euler) { var quat = m_util.euler_to_quat(euler, _quat4_tmp); set_rotation_rel(obj, quat); } exports.set_scale = function(obj, scale) { var render = obj.render; if (m_cons.has_child_of(obj)) { var offset = m_cons.get_child_of_offset(obj); var scale_par = m_tsr.get_scale(m_cons.get_child_of_parent_tsr(obj)); m_tsr.set_scale(scale/scale_par, offset); } else render.scale = scale; } exports.set_scale_rel = function(obj, scale) { if (m_cons.has_child_of(obj)) { var offset = m_cons.get_child_of_offset(obj); m_tsr.set_scale(scale, offset); } else obj.render.scale = scale; } exports.get_scale = function(obj) { return obj.render.scale; } exports.get_scale_rel = function(obj) { if (m_cons.has_child_of(obj)) { var offset = m_cons.get_child_of_offset(obj); return m_tsr.get_scale(offset); } else return obj.render.scale; } exports.set_tsr = function(obj, tsr) { var render = obj.render; if (m_cons.has_child_of(obj)) { m_tsr.set_trans(trans, render.tsr); var tsr_par = m_cons.get_child_of_parent_tsr(obj); var tsr_inv = m_tsr.invert(tsr_par, _tsr_tmp); var offset = m_cons.get_child_of_offset(obj); m_tsr.multiply(tsr_inv, render.tsr, offset); } else set_tsr_raw(obj, tsr); } exports.set_tsr_rel = set_tsr_rel; function set_tsr_rel(obj, tsr) { if (m_cons.has_child_of(obj)) { var offset = m_cons.get_child_of_offset(obj); m_tsr.copy(tsr, offset); } else set_tsr_raw(obj, tsr); } function set_tsr_raw(obj, tsr) { var render = obj.render; render.trans[0] = tsr[0]; render.trans[1] = tsr[1]; render.trans[2] = tsr[2]; render.scale = tsr[3]; render.quat[0] = tsr[4]; render.quat[1] = tsr[5]; render.quat[2] = tsr[6]; render.quat[3] = tsr[7]; } exports.get_tsr = function(obj, dest) { var render = obj.render; m_tsr.set_sep(render.trans, render.scale, render.quat, dest); return dest; } exports.get_tsr_rel = get_tsr_rel; function get_tsr_rel(obj, dest) { if (m_cons.has_child_of(obj)) { var offset = m_cons.get_child_of_offset(obj); m_tsr.copy(offset, dest); } else { var render = obj.render; m_tsr.set_sep(render.trans, render.scale, render.quat, dest); } return dest; } exports.get_object_size = function(obj) { var render = obj.render; var bb = render.bb_original; var x_size = render.scale * (bb.max_x - bb.min_x); var y_size = render.scale * (bb.max_y - bb.min_y); var z_size = render.scale * (bb.max_z - bb.min_z); var size = 0.5 * Math.sqrt(x_size * x_size + y_size * y_size + z_size * z_size); return size; } exports.get_object_center = function(obj, calc_bs_center, dest) { if (!dest) var dest = new Float32Array(3); if (calc_bs_center) { var render = obj.render; m_vec3.copy(render.bs_world.center, dest); } else { var render = obj.render; var bb = render.bb_original; dest[0] = (bb.max_x + bb.min_x)/2; dest[1] = (bb.max_y + bb.min_y)/2; dest[2] = (bb.max_z + bb.min_z)/2; m_vec3.transformMat4(dest, render.world_matrix, dest); } return dest; } /** * Calculate new translation based on distances in local space */ exports.move_local = function(obj, dx, dy, dz) { var p_tsr = get_tsr_rel(obj, _tsr_tmp); var trans = _vec3_tmp; trans[0] = dx; trans[1] = dy; trans[2] = dz; m_tsr.transform_vec3(trans, p_tsr, trans); set_translation_rel(obj, trans); } exports.rotate_local = function(obj, quat) { var p_tsr = get_tsr_rel(obj, _tsr_tmp); var tsr = m_tsr.set_quat(quat, m_tsr.identity(_tsr_tmp2)); m_tsr.multiply(p_tsr, tsr, tsr); set_tsr_rel(obj, tsr); } exports.update_transform = update_transform; /** * Set object render world_matrix. * NOTE: do not try to update batched objects (buggy _dg_parent influence) * @methodOf transform * @param {Object3D} obj Object 3D */ function update_transform(obj) { var render = obj.render; var scenes_data = obj.scenes_data; var obj_type = obj.type; // NOTE: need to update before constraints, because they rely on to this flag if (obj_type == "CAMERA") m_cam.update_camera_upside_down(obj); m_cons.update_constraint(obj, _elapsed); if (obj_type == "CAMERA") m_cam.update_camera(obj); // should not change after constraint update var trans = render.trans; var scale = render.scale; var quat = render.quat; m_tsr.set_sep(trans, scale, quat, render.tsr); var wm = render.world_matrix; m_mat4.fromQuat(quat, wm); // TODO: remove world matrix and move to tsr system if (obj_type != "CAMERA") m_util.scale_mat4(wm, scale, wm); wm[12] = trans[0]; wm[13] = trans[1]; wm[14] = trans[2]; m_mat4.invert(wm, render.inv_world_matrix); // NOTE: available only after batch creation (really needed now?) if (render.bb_local && render.bb_world) { m_bounds.bounding_box_transform(render.bb_local, wm, render.bb_world); m_bounds.bounding_sphere_transform(render.bs_local, wm, render.bs_world); m_bounds.bounding_ellipsoid_transform(render.be_local, render.tsr, render.be_world) } switch (obj_type) { case "SPEAKER": m_sfx.speaker_update_transform(obj, _elapsed); break; case "MESH": var armobj = obj.armobj; if (armobj) { var armobj_tsr = armobj.render.tsr; m_tsr.invert(armobj_tsr, _tsr_tmp); m_tsr.multiply(_tsr_tmp, render.tsr, _tsr_tmp); m_vec4.set(_tsr_tmp[0], _tsr_tmp[1], _tsr_tmp[2], _tsr_tmp[3], render.arm_rel_trans); m_quat.set(_tsr_tmp[4], _tsr_tmp[5], _tsr_tmp[6], _tsr_tmp[7], render.arm_rel_quat); } break; case "CAMERA": m_cam.update_camera_transform(obj); // listener only for active scene camera if (m_scs.check_active()) { var active_scene = m_scs.get_active(); if (m_scs.get_camera(active_scene) == obj) m_sfx.listener_update_transform(active_scene, trans, quat, _elapsed); } break; case "LAMP": m_lights.update_light_transform(obj); break; } for (var i = 0; i < scenes_data.length; i++) { var sc_data = scenes_data[i]; if (sc_data.is_active) { var scene = sc_data.scene; var sc_render = scene._render; var batches = sc_data.batches; switch (obj_type) { case "LAMP": m_scs.update_lamp_scene(obj, scene); break; case "CAMERA": m_scs.schedule_grass_map_update(scene); // camera movement only influence csm shadows if (sc_render.shadow_params && sc_render.shadow_params.enable_csm) m_scs.schedule_shadow_update(scene); break; case "MESH": if (render.bb_local && render.bb_world) { if (render.shadow_cast) m_scs.schedule_shadow_update(scene); var cube_refl_subs = sc_data.cube_refl_subs; if (render.cube_reflection_id != null && cube_refl_subs) m_scs.update_cube_reflect_subs(cube_refl_subs, trans); } if (obj.anim_slots.length && m_particles.obj_has_anim_particles(obj)) m_particles.update_emitter_transform(obj, batches); break; case "EMPTY": m_obj.update_force(obj); break; } var plane_refl_subs = sc_data.plane_refl_subs; var refl_objs = obj.reflective_objs; if (refl_objs.length && plane_refl_subs) { var cam = plane_refl_subs.camera; m_scs.update_plane_reflect_subs(plane_refl_subs, trans, quat); m_obj_util.update_refl_objects(refl_objs, cam.reflection_plane); m_cam.set_view(cam, m_scs.get_camera(scene)); m_util.extract_frustum_planes(cam.view_proj_matrix, cam.frustum_planes); } } } var cons_descends = obj.cons_descends; for (var i = 0; i < cons_descends.length; i++) update_transform(cons_descends[i]); var cons_armat_bone_descends = obj.cons_armat_bone_descends; for (var i = 0; i < cons_armat_bone_descends.length; i++) { var cons_armat_desc = cons_armat_bone_descends[i]; var armobj = cons_armat_desc[0]; var bone_name = cons_armat_desc[1]; m_cons.update_bone_constraint(armobj, bone_name); } render.force_zsort = true; } exports.distance = function(obj1, obj2) { return m_vec3.dist(obj1.render.trans, obj2.render.trans); } exports.obj_point_distance = function(obj, point) { return m_vec3.dist(obj.render.trans, point); } exports.get_object_bounding_box = function(obj) { return { max_x: obj.render.bb_world.max_x, min_x: obj.render.bb_world.min_x, max_y: obj.render.bb_world.max_y, min_y: obj.render.bb_world.min_y, max_z: obj.render.bb_world.max_z, min_z: obj.render.bb_world.min_z }; } }
'use strict' var Seneca = require('../..') var seneca = Seneca() seneca .add('a:1', function (m, d) { d(new Error('E/a:1')) }) .add('b:1', function (m, d) { this.act('a:1', d) }) if ('listen' === process.argv[2]) { seneca.listen() } else { seneca.act('b:1', console.log) }
/** * Simulator process * Pokemon Showdown - http://pokemonshowdown.com/ * * This file is where the battle simulation itself happens. * * The most important part of the simulation happens in runEvent - * see that function's definition for details. * * @license MIT license */ require('sugar'); global.Config = require('./config/config.js'); if (Config.crashguard) { // graceful crash - allow current battles to finish before restarting process.on('uncaughtException', function (err) { require('./crashlogger.js')(err, 'A simulator process'); /* var stack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("<br />"); if (Rooms.lobby) { Rooms.lobby.addRaw('<div><b>THE SERVER HAS CRASHED:</b> ' + stack + '<br />Please restart the server.</div>'); Rooms.lobby.addRaw('<div>You will not be able to talk in the lobby or start new battles until the server restarts.</div>'); } Config.modchat = 'crash'; Rooms.global.lockdown = true; */ }); } /** * Converts anything to an ID. An ID must have only lowercase alphanumeric * characters. * If a string is passed, it will be converted to lowercase and * non-alphanumeric characters will be stripped. * If an object with an ID is passed, its ID will be returned. * Otherwise, an empty string will be returned. */ global.toId = function (text) { if (text && text.id) text = text.id; else if (text && text.userid) text = text.userid; return string(text).toLowerCase().replace(/[^a-z0-9]+/g, ''); }; /** * Validates a username or Pokemon nickname */ global.toName = function (name) { name = string(name); name = name.replace(/[\|\s\[\]\,]+/g, ' ').trim(); if (name.length > 18) name = name.substr(0, 18).trim(); return name; }; /** * Safely ensures the passed variable is a string * Simply doing '' + str can crash if str.toString crashes or isn't a function * If we're expecting a string and being given anything that isn't a string * or a number, it's safe to assume it's an error, and return '' */ global.string = function (str) { if (typeof str === 'string' || typeof str === 'number') return '' + str; return ''; }; global.Tools = require('./tools.js'); var Battle, BattleSide, BattlePokemon; var Battles = Object.create(null); require('./repl.js').start('battle-engine-', process.pid, function (cmd) { return eval(cmd); }); // Receive and process a message sent using Simulator.prototype.send in // another process. process.on('message', function (message) { //console.log('CHILD MESSAGE RECV: "' + message + '"'); var nlIndex = message.indexOf("\n"); var more = ''; if (nlIndex > 0) { more = message.substr(nlIndex + 1); message = message.substr(0, nlIndex); } var data = message.split('|'); if (data[1] === 'init') { if (!Battles[data[0]]) { try { Battles[data[0]] = Battle.construct(data[0], data[2], data[3]); } catch (err) { var stack = err.stack + '\n\n' + 'Additional information:\n' + 'message = ' + message; var fakeErr = {stack: stack}; if (!require('./crashlogger.js')(fakeErr, 'A battle')) { var ministack = ("" + err.stack).escapeHTML().split("\n").slice(0, 2).join("<br />"); process.send(data[0] + '\nupdate\n|html|<div class="broadcast-red"><b>A BATTLE PROCESS HAS CRASHED:</b> ' + ministack + '</div>'); } else { process.send(data[0] + '\nupdate\n|html|<div class="broadcast-red"><b>The battle crashed!</b><br />Don\'t worry, we\'re working on fixing it.</div>'); } } } } else if (data[1] === 'dealloc') { if (Battles[data[0]] && Battles[data[0]].destroy) { Battles[data[0]].destroy(); } else { var stack = '\n\n' + 'Additional information:\n' + 'message = ' + message; var fakeErr = {stack: stack}; require('./crashlogger.js')(fakeErr, 'A battle'); } delete Battles[data[0]]; } else { var battle = Battles[data[0]]; if (battle) { var prevRequest = battle.currentRequest; var prevRequestDetails = battle.currentRequestDetails || ''; try { battle.receive(data, more); } catch (err) { var stack = err.stack + '\n\n' + 'Additional information:\n' + 'message = ' + message + '\n' + 'currentRequest = ' + prevRequest + '\n\n' + 'Log:\n' + battle.log.join('\n').replace(/\n\|split\n[^\n]*\n[^\n]*\n[^\n]*\n/g, '\n'); var fakeErr = {stack: stack}; require('./crashlogger.js')(fakeErr, 'A battle'); var logPos = battle.log.length; battle.add('html', '<div class="broadcast-red"><b>The battle crashed</b><br />You can keep playing but it might crash again.</div>'); var nestedError; try { battle.makeRequest(prevRequest, prevRequestDetails); } catch (e) { nestedError = e; } battle.sendUpdates(logPos); if (nestedError) { throw nestedError; } } } else if (data[1] === 'eval') { try { eval(data[2]); } catch (e) {} } } }); process.on('disconnect', function () { process.exit(); }); BattlePokemon = (function () { function BattlePokemon(set, side) { this.side = side; this.battle = side.battle; var pokemonScripts = this.battle.data.Scripts.pokemon; if (pokemonScripts) Object.merge(this, pokemonScripts); if (typeof set === 'string') set = {name: set}; // "pre-bound" functions for nicer syntax (avoids repeated use of `bind`) this.getHealth = (this.getHealth || BattlePokemon.getHealth).bind(this); this.getDetails = (this.getDetails || BattlePokemon.getDetails).bind(this); this.set = set; this.baseTemplate = this.battle.getTemplate(set.species || set.name); if (!this.baseTemplate.exists) { this.battle.debug('Unidentified species: ' + this.species); this.baseTemplate = this.battle.getTemplate('Unown'); } this.species = this.baseTemplate.species; if (set.name === set.species || !set.name || !set.species) { set.name = this.species; } this.name = (set.name || set.species || 'Bulbasaur').substr(0, 20); this.speciesid = toId(this.species); this.template = this.baseTemplate; this.moves = []; this.baseMoves = this.moves; this.movepp = {}; this.moveset = []; this.baseMoveset = []; this.level = this.battle.clampIntRange(set.forcedLevel || set.level || 100, 1, 9999); var genders = {M:'M', F:'F'}; this.gender = this.template.gender || genders[set.gender] || (Math.random() * 2 < 1 ? 'M' : 'F'); if (this.gender === 'N') this.gender = ''; this.happiness = typeof set.happiness === 'number' ? this.battle.clampIntRange(set.happiness, 0, 255) : 255; this.pokeball = this.set.pokeball || 'pokeball'; this.fullname = this.side.id + ': ' + this.name; this.details = this.species + (this.level === 100 ? '' : ', L' + this.level) + (this.gender === '' ? '' : ', ' + this.gender) + (this.set.shiny ? ', shiny' : ''); this.id = this.fullname; // shouldn't really be used anywhere this.statusData = {}; this.volatiles = {}; this.negateImmunity = {}; this.height = this.template.height; this.heightm = this.template.heightm; this.weight = this.template.weight; this.weightkg = this.template.weightkg; this.ignore = {}; this.baseAbility = toId(set.ability); this.ability = this.baseAbility; this.item = toId(set.item); this.abilityData = {id: this.ability}; this.itemData = {id: this.item}; this.speciesData = {id: this.speciesid}; this.types = this.baseTemplate.types; this.typesData = []; for (var i = 0, l = this.types.length; i < l; i++) { this.typesData.push({ type: this.types[i], suppressed: false, isAdded: false }); } if (this.set.moves) { for (var i = 0; i < this.set.moves.length; i++) { var move = this.battle.getMove(this.set.moves[i]); if (!move.id) continue; if (move.id === 'hiddenpower') { if (!this.set.ivs || Object.values(this.set.ivs).every(31)) { this.set.ivs = this.battle.getType(move.type).HPivs; } move = this.battle.getMove('hiddenpower'); } this.baseMoveset.push({ move: move.name, id: move.id, pp: (move.noPPBoosts ? move.pp : move.pp * 8 / 5), maxpp: (move.noPPBoosts ? move.pp : move.pp * 8 / 5), target: (move.nonGhostTarget && !this.hasType('Ghost') ? move.nonGhostTarget : move.target), disabled: false, used: false }); this.moves.push(move.id); } } this.disabledMoves = {}; this.canMegaEvo = this.battle.canMegaEvo(this); if (!this.set.evs) { this.set.evs = {hp: 84, atk: 84, def: 84, spa: 84, spd: 84, spe: 84}; } if (!this.set.ivs) { this.set.ivs = {hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31}; } var stats = {hp: 31, atk: 31, def: 31, spe: 31, spa: 31, spd: 31}; for (var i in stats) { if (!this.set.evs[i]) this.set.evs[i] = 0; if (!this.set.ivs[i] && this.set.ivs[i] !== 0) this.set.ivs[i] = 31; } for (var i in this.set.evs) { this.set.evs[i] = this.battle.clampIntRange(this.set.evs[i], 0, 255); } for (var i in this.set.ivs) { this.set.ivs[i] = this.battle.clampIntRange(this.set.ivs[i], 0, 31); } var hpTypes = ['Fighting', 'Flying', 'Poison', 'Ground', 'Rock', 'Bug', 'Ghost', 'Steel', 'Fire', 'Water', 'Grass', 'Electric', 'Psychic', 'Ice', 'Dragon', 'Dark']; if (this.battle.gen && this.battle.gen === 2) { // Gen 2 specific Hidden Power check. IVs are still treated 0-31 so we get them 0-15 var atkDV = Math.floor(this.set.ivs.atk / 2); var defDV = Math.floor(this.set.ivs.def / 2); var speDV = Math.floor(this.set.ivs.spe / 2); var spcDV = Math.floor(this.set.ivs.spa / 2); this.hpType = hpTypes[4 * (atkDV % 4) + (defDV % 4)]; this.hpPower = Math.floor((5 * ((spcDV >> 3) + (2 * (speDV >> 3)) + (4 * (defDV >> 3)) + (8 * (atkDV >> 3))) + (spcDV > 2 ? 3 : spcDV)) / 2 + 31); } else { // Hidden Power check for gen 3 onwards var hpTypeX = 0, hpPowerX = 0; var i = 1; for (var s in stats) { hpTypeX += i * (this.set.ivs[s] % 2); hpPowerX += i * (Math.floor(this.set.ivs[s] / 2) % 2); i *= 2; } this.hpType = hpTypes[Math.floor(hpTypeX * 15 / 63)]; // In Gen 6, Hidden Power is always 60 base power this.hpPower = (this.battle.gen && this.battle.gen < 6) ? Math.floor(hpPowerX * 40 / 63) + 30 : 60; } this.boosts = {atk: 0, def: 0, spa: 0, spd: 0, spe: 0, accuracy: 0, evasion: 0}; this.stats = {atk:0, def:0, spa:0, spd:0, spe:0}; this.baseStats = {atk:10, def:10, spa:10, spd:10, spe:10}; // This is used in gen 1 only, here to avoid code repetition. // Only declared if gen 1 to avoid declaring an object we aren't going to need. if (this.battle.gen === 1) this.modifiedStats = {atk:0, def:0, spa:0, spd:0, spe:0}; for (var statName in this.baseStats) { var stat = this.template.baseStats[statName]; stat = Math.floor(Math.floor(2 * stat + this.set.ivs[statName] + Math.floor(this.set.evs[statName] / 4)) * this.level / 100 + 5); var nature = this.battle.getNature(this.set.nature); if (statName === nature.plus) stat *= 1.1; if (statName === nature.minus) stat *= 0.9; this.baseStats[statName] = Math.floor(stat); } this.maxhp = Math.floor(Math.floor(2 * this.template.baseStats['hp'] + this.set.ivs['hp'] + Math.floor(this.set.evs['hp'] / 4) + 100) * this.level / 100 + 10); if (this.template.baseStats['hp'] === 1) this.maxhp = 1; // shedinja this.hp = this.hp || this.maxhp; this.baseIvs = this.set.ivs; this.baseHpType = this.hpType; this.baseHpPower = this.hpPower; this.clearVolatile(true); } BattlePokemon.prototype.trapped = false; BattlePokemon.prototype.maybeTrapped = false; BattlePokemon.prototype.maybeDisabled = false; BattlePokemon.prototype.hp = 0; BattlePokemon.prototype.maxhp = 100; BattlePokemon.prototype.illusion = null; BattlePokemon.prototype.fainted = false; BattlePokemon.prototype.faintQueued = false; BattlePokemon.prototype.lastItem = ''; BattlePokemon.prototype.ateBerry = false; BattlePokemon.prototype.status = ''; BattlePokemon.prototype.position = 0; BattlePokemon.prototype.lastMove = ''; BattlePokemon.prototype.moveThisTurn = ''; BattlePokemon.prototype.lastDamage = 0; BattlePokemon.prototype.lastAttackedBy = null; BattlePokemon.prototype.usedItemThisTurn = false; BattlePokemon.prototype.newlySwitched = false; BattlePokemon.prototype.beingCalledBack = false; BattlePokemon.prototype.isActive = false; BattlePokemon.prototype.isStarted = false; // has this pokemon's Start events run yet? BattlePokemon.prototype.transformed = false; BattlePokemon.prototype.duringMove = false; BattlePokemon.prototype.hpType = 'Dark'; BattlePokemon.prototype.hpPower = 60; BattlePokemon.prototype.speed = 0; BattlePokemon.prototype.toString = function () { var fullname = this.fullname; if (this.illusion) fullname = this.illusion.fullname; var positionList = 'abcdef'; if (this.isActive) return fullname.substr(0, 2) + positionList[this.position] + fullname.substr(2); return fullname; }; // "static" function BattlePokemon.getDetails = function (side) { if (this.illusion) return this.illusion.details + '|' + this.getHealth(side); return this.details + '|' + this.getHealth(side); }; BattlePokemon.prototype.update = function (init) { this.negateImmunity = {}; this.trapped = this.maybeTrapped = false; this.maybeDisabled = false; // reset for ignore settings this.ignore = {}; for (var i in this.moveset) { if (this.moveset[i]) this.moveset[i].disabled = false; } if (init) return; // Change formes based on held items (for Transform) // Only ever relevant in Generation 4 since Generation 3 didn't have item-based forme changes if (this.battle.gen === 4) { if (this.template.num === 487) { // Giratina formes if (this.template.species === 'Giratina' && this.item === 'griseousorb') { this.formeChange('Giratina-Origin'); this.battle.add('-formechange', this, 'Giratina-Origin'); } else if (this.template.species === 'Giratina-Origin' && this.item !== 'griseousorb') { this.formeChange('Giratina'); this.battle.add('-formechange', this, 'Giratina'); } } if (this.template.num === 493) { // Arceus formes var item = Tools.getItem(this.item); var targetForme = (item && item.onPlate ? 'Arceus-' + item.onPlate : 'Arceus'); if (this.template.species !== targetForme) { this.formeChange(targetForme); this.battle.add('-formechange', this, targetForme); } } } if (this.runImmunity('trapped')) this.battle.runEvent('MaybeTrapPokemon', this); // Disable the faculty to cancel switches if a foe may have a trapping ability for (var i = 0; i < this.battle.sides.length; ++i) { var side = this.battle.sides[i]; if (side === this.side) continue; for (var j = 0; j < side.active.length; ++j) { var pokemon = side.active[j]; if (!pokemon || pokemon.fainted) continue; var template = (pokemon.illusion || pokemon).template; if (!template.abilities) continue; for (var k in template.abilities) { var ability = template.abilities[k]; if (ability === pokemon.ability) { // This event was already run above so we don't need // to run it again. continue; } if ((k === 'H') && template.unreleasedHidden) { // unreleased hidden ability continue; } if (this.runImmunity('trapped')) { this.battle.singleEvent('FoeMaybeTrapPokemon', this.battle.getAbility(ability), {}, this, pokemon); } } } } this.battle.runEvent('ModifyPokemon', this); this.speed = this.getStat('spe'); }; BattlePokemon.prototype.calculateStat = function (statName, boost, modifier) { statName = toId(statName); if (statName === 'hp') return this.maxhp; // please just read .maxhp directly // base stat var stat = this.stats[statName]; // stat boosts // boost = this.boosts[statName]; var boosts = {}; boosts[statName] = boost; boosts = this.battle.runEvent('ModifyBoost', this, null, null, boosts); boost = boosts[statName]; var boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4]; if (boost > 6) boost = 6; if (boost < -6) boost = -6; if (boost >= 0) { stat = Math.floor(stat * boostTable[boost]); } else { stat = Math.floor(stat / boostTable[-boost]); } // stat modifier stat = this.battle.modify(stat, (modifier || 1)); if (this.battle.getStatCallback) { stat = this.battle.getStatCallback(stat, statName, this); } return stat; }; BattlePokemon.prototype.getStat = function (statName, unboosted, unmodified) { statName = toId(statName); if (statName === 'hp') return this.maxhp; // please just read .maxhp directly // base stat var stat = this.stats[statName]; // stat boosts if (!unboosted) { var boosts = this.battle.runEvent('ModifyBoost', this, null, null, Object.clone(this.boosts)); var boost = boosts[statName]; var boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4]; if (boost > 6) boost = 6; if (boost < -6) boost = -6; if (boost >= 0) { stat = Math.floor(stat * boostTable[boost]); } else { stat = Math.floor(stat / boostTable[-boost]); } } // stat modifier effects if (!unmodified) { var statTable = {atk:'Atk', def:'Def', spa:'SpA', spd:'SpD', spe:'Spe'}; var statMod = 1; statMod = this.battle.runEvent('Modify' + statTable[statName], this, null, null, statMod); stat = this.battle.modify(stat, statMod); } if (this.battle.getStatCallback) { stat = this.battle.getStatCallback(stat, statName, this, unboosted); } return stat; }; BattlePokemon.prototype.getWeight = function () { var weight = this.template.weightkg; weight = this.battle.runEvent('ModifyWeight', this, null, null, weight); if (weight < 0.1) weight = 0.1; return weight; }; BattlePokemon.prototype.getMoveData = function (move) { move = this.battle.getMove(move); for (var i = 0; i < this.moveset.length; i++) { var moveData = this.moveset[i]; if (moveData.id === move.id) { return moveData; } } return null; }; BattlePokemon.prototype.deductPP = function (move, amount, source) { move = this.battle.getMove(move); var ppData = this.getMoveData(move); var success = false; if (ppData) { ppData.used = true; } if (ppData && ppData.pp) { ppData.pp -= this.battle.runEvent('DeductPP', this, source || this, move, amount || 1); if (ppData.pp <= 0) { ppData.pp = 0; } success = true; } return success; }; BattlePokemon.prototype.moveUsed = function (move) { this.lastMove = this.battle.getMove(move).id; this.moveThisTurn = this.lastMove; }; BattlePokemon.prototype.gotAttacked = function (move, damage, source) { if (!damage) damage = 0; move = this.battle.getMove(move); this.lastAttackedBy = { pokemon: source, damage: damage, move: move.id, thisTurn: true }; }; BattlePokemon.prototype.getLockedMove = function () { var lockedMove = this.battle.runEvent('LockMove', this); if (lockedMove === true) lockedMove = false; return lockedMove; }; BattlePokemon.prototype.getMoves = function (lockedMove, restrictData) { if (lockedMove) { lockedMove = toId(lockedMove); this.trapped = true; } if (lockedMove === 'recharge') { return [{ move: 'Recharge', id: 'recharge' }]; } var moves = []; var hasValidMove = false; for (var i = 0; i < this.moveset.length; i++) { var move = this.moveset[i]; if (lockedMove) { if (lockedMove === move.id) { return [{ move: move.move, id: move.id }]; } continue; } if (this.disabledMoves[move.id] && (!restrictData || !this.disabledMoves[move.id].isHidden) || !move.pp && (this.battle.gen !== 1 || !this.volatiles['partialtrappinglock'])) { move.disabled = !restrictData && this.disabledMoves[move.id] && this.disabledMoves[move.id].isHidden ? 'hidden' : true; } else if (!move.disabled || move.disabled === 'hidden' && restrictData) { hasValidMove = true; } var moveName = move.move; if (move.id === 'hiddenpower') { moveName = 'Hidden Power ' + this.hpType; if (this.battle.gen < 6) moveName += ' ' + this.hpPower; } moves.push({ move: moveName, id: move.id, pp: move.pp, maxpp: move.maxpp, target: move.target, disabled: move.disabled }); } if (lockedMove) { return [{ move: this.battle.getMove(lockedMove).name, id: lockedMove }]; } if (hasValidMove) return moves; return []; }; BattlePokemon.prototype.getRequestData = function () { var lockedMove = this.getLockedMove(); // Information should be restricted for the last active Pokémon var isLastActive = this.isLastActive(); var moves = this.getMoves(lockedMove, isLastActive); var data = {moves: moves.length ? moves : [{move: 'Struggle', id: 'struggle'}]}; if (isLastActive) { if (this.maybeDisabled) { data.maybeDisabled = true; } if (this.trapped === true) { data.trapped = true; } else if (this.maybeTrapped) { data.maybeTrapped = true; } } else { if (this.trapped) data.trapped = true; } return data; }; BattlePokemon.prototype.isLastActive = function () { if (!this.isActive) return false; var allyActive = this.side.active; for (var i = this.position + 1; i < allyActive.length; i++) { if (allyActive[i] && !allyActive.fainted) return false; } return true; }; BattlePokemon.prototype.positiveBoosts = function () { var boosts = 0; for (var i in this.boosts) { if (this.boosts[i] > 0) boosts += this.boosts[i]; } return boosts; }; BattlePokemon.prototype.boostBy = function (boost) { var changed = false; for (var i in boost) { var delta = boost[i]; this.boosts[i] += delta; if (this.boosts[i] > 6) { delta -= this.boosts[i] - 6; this.boosts[i] = 6; } if (this.boosts[i] < -6) { delta -= this.boosts[i] - (-6); this.boosts[i] = -6; } if (delta) changed = true; } this.update(); return changed; }; BattlePokemon.prototype.clearBoosts = function () { for (var i in this.boosts) { this.boosts[i] = 0; } this.update(); }; BattlePokemon.prototype.setBoost = function (boost) { for (var i in boost) { this.boosts[i] = boost[i]; } this.update(); }; BattlePokemon.prototype.copyVolatileFrom = function (pokemon) { this.clearVolatile(); this.boosts = pokemon.boosts; for (var i in pokemon.volatiles) { if (this.battle.getEffect(i).noCopy) continue; // shallow clones this.volatiles[i] = Object.clone(pokemon.volatiles[i]); if (this.volatiles[i].linkedPokemon) { delete pokemon.volatiles[i].linkedPokemon; delete pokemon.volatiles[i].linkedStatus; this.volatiles[i].linkedPokemon.volatiles[this.volatiles[i].linkedStatus].linkedPokemon = this; } } pokemon.clearVolatile(); this.update(); for (var i in this.volatiles) { this.battle.singleEvent('Copy', this.getVolatile(i), this.volatiles[i], this); } }; BattlePokemon.prototype.transformInto = function (pokemon, user) { var template = pokemon.template; if (pokemon.fainted || pokemon.illusion || (pokemon.volatiles['substitute'] && this.battle.gen >= 5)) { return false; } if (!template.abilities || (pokemon && pokemon.transformed && this.battle.gen >= 2) || (user && user.transformed && this.battle.gen >= 5)) { return false; } if (!this.formeChange(template, true)) { return false; } this.transformed = true; this.typesData = []; for (var i = 0, l = pokemon.typesData.length; i < l; i++) { this.typesData.push({ type: pokemon.typesData[i].type, suppressed: false, isAdded: pokemon.typesData[i].isAdded }); } for (var statName in this.stats) { this.stats[statName] = pokemon.stats[statName]; } this.moveset = []; this.moves = []; this.set.ivs = (this.battle.gen >= 5 ? this.set.ivs : pokemon.set.ivs); this.hpType = (this.battle.gen >= 5 ? this.hpType : pokemon.hpType); this.hpPower = (this.battle.gen >= 5 ? this.hpPower : pokemon.hpPower); for (var i = 0; i < pokemon.moveset.length; i++) { var moveData = pokemon.moveset[i]; var moveName = moveData.move; if (moveData.id === 'hiddenpower') { moveName = 'Hidden Power ' + this.hpType; } this.moveset.push({ move: moveName, id: moveData.id, pp: moveData.maxpp === 1 ? 1 : 5, maxpp: this.battle.gen >= 5 ? (moveData.maxpp === 1 ? 1 : 5) : moveData.maxpp, target: moveData.target, disabled: false }); this.moves.push(toId(moveName)); } for (var j in pokemon.boosts) { this.boosts[j] = pokemon.boosts[j]; } this.battle.add('-transform', this, pokemon); this.setAbility(pokemon.ability); this.update(); return true; }; BattlePokemon.prototype.formeChange = function (template, dontRecalculateStats) { template = this.battle.getTemplate(template); if (!template.abilities) return false; this.illusion = null; this.template = template; this.types = template.types; this.typesData = []; this.types = template.types; for (var i = 0, l = this.types.length; i < l; i++) { this.typesData.push({ type: this.types[i], suppressed: false, isAdded: false }); } if (!dontRecalculateStats) { for (var statName in this.stats) { var stat = this.template.baseStats[statName]; stat = Math.floor(Math.floor(2 * stat + this.set.ivs[statName] + Math.floor(this.set.evs[statName] / 4)) * this.level / 100 + 5); // nature var nature = this.battle.getNature(this.set.nature); if (statName === nature.plus) stat *= 1.1; if (statName === nature.minus) stat *= 0.9; this.baseStats[statName] = this.stats[statName] = Math.floor(stat); // If gen 1, we reset modified stats. if (this.battle.gen === 1) { this.modifiedStats[statName] = Math.floor(stat); // ...and here is where the gen 1 games re-apply burn and para drops. if (this.status === 'par') this.modifyStat('spe', 0.25); if (this.status === 'brn') this.modifyStat('atk', 0.5); } } this.speed = this.stats.spe; } return true; }; BattlePokemon.prototype.clearVolatile = function (init) { this.boosts = { atk: 0, def: 0, spa: 0, spd: 0, spe: 0, accuracy: 0, evasion: 0 }; this.moveset = this.baseMoveset.slice(); this.moves = this.moveset.map(function (move) { return toId(move.move); }); this.transformed = false; this.ability = this.baseAbility; this.set.ivs = this.baseIvs; this.hpType = this.baseHpType; this.hpPower = this.baseHpPower; for (var i in this.volatiles) { if (this.volatiles[i].linkedStatus) { this.volatiles[i].linkedPokemon.removeVolatile(this.volatiles[i].linkedStatus); } } this.volatiles = {}; this.switchFlag = false; this.lastMove = ''; this.moveThisTurn = ''; this.lastDamage = 0; this.lastAttackedBy = null; this.newlySwitched = true; this.beingCalledBack = false; this.formeChange(this.baseTemplate); this.update(init); }; BattlePokemon.prototype.hasType = function (type) { if (!type) return false; if (Array.isArray(type)) { for (var i = 0; i < type.length; i++) { if (this.hasType(type[i])) return true; } } else { if (this.getTypes().indexOf(type) > -1) return true; } return false; }; // returns the amount of damage actually dealt BattlePokemon.prototype.faint = function (source, effect) { // This function only puts the pokemon in the faint queue; // actually setting of this.fainted comes later when the // faint queue is resolved. if (this.fainted || this.faintQueued) return 0; var d = this.hp; this.hp = 0; this.switchFlag = false; this.faintQueued = true; this.battle.faintQueue.push({ target: this, source: source, effect: effect }); return d; }; BattlePokemon.prototype.damage = function (d, source, effect) { if (!this.hp) return 0; if (d < 1 && d > 0) d = 1; d = Math.floor(d); if (isNaN(d)) return 0; if (d <= 0) return 0; this.hp -= d; if (this.hp <= 0) { d += this.hp; this.faint(source, effect); } return d; }; BattlePokemon.prototype.tryTrap = function (isHidden) { if (this.runImmunity('trapped')) { if (this.trapped && isHidden) return true; this.trapped = isHidden ? 'hidden' : true; return true; } return false; }; BattlePokemon.prototype.hasMove = function (moveid) { moveid = toId(moveid); if (moveid.substr(0, 11) === 'hiddenpower') moveid = 'hiddenpower'; for (var i = 0; i < this.moveset.length; i++) { if (moveid === this.battle.getMove(this.moveset[i].move).id) { return moveid; } } return false; }; BattlePokemon.prototype.disableMove = function (moveid, isHidden, sourceEffect) { if (!sourceEffect && this.battle.event) { sourceEffect = this.battle.effect; } moveid = toId(moveid); if (moveid.substr(0, 11) === 'hiddenpower') moveid = 'hiddenpower'; if (this.disabledMoves[moveid] && !this.disabledMoves[moveid].isHidden) return; this.disabledMoves[moveid] = { isHidden: !!isHidden, sourceEffect: sourceEffect }; }; // returns the amount of damage actually healed BattlePokemon.prototype.heal = function (d) { if (!this.hp) return false; d = Math.floor(d); if (isNaN(d)) return false; if (d <= 0) return false; if (this.hp >= this.maxhp) return false; this.hp += d; if (this.hp > this.maxhp) { d -= this.hp - this.maxhp; this.hp = this.maxhp; } return d; }; // sets HP, returns delta BattlePokemon.prototype.sethp = function (d) { if (!this.hp) return 0; d = Math.floor(d); if (isNaN(d)) return; if (d < 1) d = 1; d = d - this.hp; this.hp += d; if (this.hp > this.maxhp) { d -= this.hp - this.maxhp; this.hp = this.maxhp; } return d; }; BattlePokemon.prototype.trySetStatus = function (status, source, sourceEffect) { if (!this.hp) return false; if (this.status) return false; return this.setStatus(status, source, sourceEffect); }; BattlePokemon.prototype.cureStatus = function () { if (!this.hp) return false; // unlike clearStatus, gives cure message if (this.status) { this.battle.add('-curestatus', this, this.status); this.setStatus(''); } }; BattlePokemon.prototype.setStatus = function (status, source, sourceEffect, ignoreImmunities) { if (!this.hp) return false; status = this.battle.getEffect(status); if (this.battle.event) { if (!source) source = this.battle.event.source; if (!sourceEffect) sourceEffect = this.battle.effect; } if (!ignoreImmunities && status.id) { // the game currently never ignores immunities if (!this.runImmunity(status.id === 'tox' ? 'psn' : status.id)) { this.battle.debug('immune to status'); return false; } } if (this.status === status.id) return false; var prevStatus = this.status; var prevStatusData = this.statusData; if (status.id && !this.battle.runEvent('SetStatus', this, source, sourceEffect, status)) { this.battle.debug('set status [' + status.id + '] interrupted'); return false; } this.status = status.id; this.statusData = {id: status.id, target: this}; if (source) this.statusData.source = source; if (status.duration) { this.statusData.duration = status.duration; } if (status.durationCallback) { this.statusData.duration = status.durationCallback.call(this.battle, this, source, sourceEffect); } if (status.id && !this.battle.singleEvent('Start', status, this.statusData, this, source, sourceEffect)) { this.battle.debug('status start [' + status.id + '] interrupted'); // cancel the setstatus this.status = prevStatus; this.statusData = prevStatusData; return false; } this.update(); if (status.id && !this.battle.runEvent('AfterSetStatus', this, source, sourceEffect, status)) { return false; } return true; }; BattlePokemon.prototype.clearStatus = function () { // unlike cureStatus, does not give cure message return this.setStatus(''); }; BattlePokemon.prototype.getStatus = function () { return this.battle.getEffect(this.status); }; BattlePokemon.prototype.eatItem = function (item, source, sourceEffect) { if (!this.hp || !this.isActive) return false; if (!this.item) return false; var id = toId(item); if (id && this.item !== id) return false; if (!sourceEffect && this.battle.effect) sourceEffect = this.battle.effect; if (!source && this.battle.event && this.battle.event.target) source = this.battle.event.target; item = this.getItem(); if (this.battle.runEvent('UseItem', this, null, null, item) && this.battle.runEvent('EatItem', this, null, null, item)) { this.battle.add('-enditem', this, item, '[eat]'); this.battle.singleEvent('Eat', item, this.itemData, this, source, sourceEffect); this.lastItem = this.item; this.item = ''; this.itemData = {id: '', target: this}; this.usedItemThisTurn = true; this.ateBerry = true; this.battle.runEvent('AfterUseItem', this, null, null, item); return true; } return false; }; BattlePokemon.prototype.useItem = function (item, source, sourceEffect) { if (!this.isActive) return false; if (!this.item) return false; var id = toId(item); if (id && this.item !== id) return false; if (!sourceEffect && this.battle.effect) sourceEffect = this.battle.effect; if (!source && this.battle.event && this.battle.event.target) source = this.battle.event.target; item = this.getItem(); if (this.battle.runEvent('UseItem', this, null, null, item)) { switch (item.id) { case 'redcard': this.battle.add('-enditem', this, item, '[of] ' + source); break; default: if (!item.isGem) { this.battle.add('-enditem', this, item); } break; } this.battle.singleEvent('Use', item, this.itemData, this, source, sourceEffect); this.lastItem = this.item; this.item = ''; this.itemData = {id: '', target: this}; this.usedItemThisTurn = true; this.battle.runEvent('AfterUseItem', this, null, null, item); return true; } return false; }; BattlePokemon.prototype.takeItem = function (source) { if (!this.isActive) return false; if (!this.item) return false; if (!source) source = this; if (this.battle.gen === 4) { if (toId(this.ability) === 'multitype') return false; if (source && toId(source.ability) === 'multitype') return false; } var item = this.getItem(); if (this.battle.runEvent('TakeItem', this, source, null, item)) { this.item = ''; this.itemData = {id: '', target: this}; return item; } return false; }; BattlePokemon.prototype.setItem = function (item, source, effect) { if (!this.hp || !this.isActive) return false; item = this.battle.getItem(item); this.lastItem = this.item; this.item = item.id; this.itemData = {id: item.id, target: this}; if (item.id) { this.battle.singleEvent('Start', item, this.itemData, this, source, effect); } if (this.lastItem) this.usedItemThisTurn = true; return true; }; BattlePokemon.prototype.getItem = function () { return this.battle.getItem(this.item); }; BattlePokemon.prototype.hasItem = function (item) { if (this.ignore['Item']) return false; var ownItem = this.item; if (!Array.isArray(item)) { return ownItem === toId(item); } return (item.map(toId).indexOf(ownItem) >= 0); }; BattlePokemon.prototype.clearItem = function () { return this.setItem(''); }; BattlePokemon.prototype.setAbility = function (ability, source, effect, noForce) { if (!this.hp) return false; ability = this.battle.getAbility(ability); var oldAbility = this.ability; if (noForce && oldAbility === ability.id) { return false; } if (ability.id in {illusion:1, multitype:1, stancechange:1}) return false; if (oldAbility in {multitype:1, stancechange:1}) return false; this.battle.singleEvent('End', this.battle.getAbility(oldAbility), this.abilityData, this, source, effect); this.ability = ability.id; this.abilityData = {id: ability.id, target: this}; if (ability.id && this.battle.gen > 3) { this.battle.singleEvent('Start', ability, this.abilityData, this, source, effect); } return oldAbility; }; BattlePokemon.prototype.getAbility = function () { return this.battle.getAbility(this.ability); }; BattlePokemon.prototype.hasAbility = function (ability) { if (this.ignore['Ability']) return false; var ownAbility = this.ability; if (!Array.isArray(ability)) { return ownAbility === toId(ability); } return (ability.map(toId).indexOf(ownAbility) >= 0); }; BattlePokemon.prototype.clearAbility = function () { return this.setAbility(''); }; BattlePokemon.prototype.getNature = function () { return this.battle.getNature(this.set.nature); }; BattlePokemon.prototype.addVolatile = function (status, source, sourceEffect, linkedStatus) { var result; status = this.battle.getEffect(status); if (!this.hp && !status.affectsFainted) return false; if (this.battle.event) { if (!source) source = this.battle.event.source; if (!sourceEffect) sourceEffect = this.battle.effect; } if (this.volatiles[status.id]) { if (!status.onRestart) return false; return this.battle.singleEvent('Restart', status, this.volatiles[status.id], this, source, sourceEffect); } if (!this.runImmunity(status.id)) return false; result = this.battle.runEvent('TryAddVolatile', this, source, sourceEffect, status); if (!result) { this.battle.debug('add volatile [' + status.id + '] interrupted'); return result; } this.volatiles[status.id] = {id: status.id}; this.volatiles[status.id].target = this; if (source) { this.volatiles[status.id].source = source; this.volatiles[status.id].sourcePosition = source.position; } if (sourceEffect) { this.volatiles[status.id].sourceEffect = sourceEffect; } if (status.duration) { this.volatiles[status.id].duration = status.duration; } if (status.durationCallback) { this.volatiles[status.id].duration = status.durationCallback.call(this.battle, this, source, sourceEffect); } result = this.battle.singleEvent('Start', status, this.volatiles[status.id], this, source, sourceEffect); if (!result) { // cancel delete this.volatiles[status.id]; return result; } if (linkedStatus && source && !source.volatiles[linkedStatus]) { source.addVolatile(linkedStatus, this, sourceEffect, status); source.volatiles[linkedStatus].linkedPokemon = this; source.volatiles[linkedStatus].linkedStatus = status; this.volatiles[status].linkedPokemon = source; this.volatiles[status].linkedStatus = linkedStatus; } this.update(); return true; }; BattlePokemon.prototype.getVolatile = function (status) { status = this.battle.getEffect(status); if (!this.volatiles[status.id]) return null; return status; }; BattlePokemon.prototype.removeVolatile = function (status) { if (!this.hp) return false; status = this.battle.getEffect(status); if (!this.volatiles[status.id]) return false; this.battle.singleEvent('End', status, this.volatiles[status.id], this); var linkedPokemon = this.volatiles[status.id].linkedPokemon; var linkedStatus = this.volatiles[status.id].linkedStatus; delete this.volatiles[status.id]; if (linkedPokemon && linkedPokemon.volatiles[linkedStatus]) { linkedPokemon.removeVolatile(linkedStatus); } this.update(); return true; }; // "static" function BattlePokemon.getHealth = function (side) { if (!this.hp) return '0 fnt'; var hpstring; if ((side === true) || (this.side === side) || this.battle.getFormat().debug || this.battle.reportExactHP) { hpstring = '' + this.hp + '/' + this.maxhp; } else { var ratio = this.hp / this.maxhp; if (this.battle.reportPercentages) { // HP Percentage Mod mechanics var percentage = Math.ceil(ratio * 100); if ((percentage === 100) && (ratio < 1.0)) { percentage = 99; } hpstring = '' + percentage + '/100'; } else { // In-game accurate pixel health mechanics var pixels = Math.floor(ratio * 48) || 1; hpstring = '' + pixels + '/48'; if ((pixels === 9) && (ratio > 0.2)) { hpstring += 'y'; // force yellow HP bar } else if ((pixels === 24) && (ratio > 0.5)) { hpstring += 'g'; // force green HP bar } } } if (this.status) hpstring += ' ' + this.status; return hpstring; }; BattlePokemon.prototype.setType = function (newType, enforce) { // Arceus first type cannot be normally changed if (!enforce && this.template.num === 493) return false; this.typesData = [{ type: newType, suppressed: false, isAdded: false }]; return true; }; BattlePokemon.prototype.addType = function (newType) { // removes any types added previously and adds another one this.typesData = this.typesData.filter(function (typeData) { return !typeData.isAdded; }).concat([{ type: newType, suppressed: false, isAdded: true }]); return true; }; BattlePokemon.prototype.getTypes = function (getAll) { var types = []; for (var i = 0, l = this.typesData.length; i < l; i++) { if (getAll || !this.typesData[i].suppressed) { types.push(this.typesData[i].type); } } if (types.length) return types; if (this.battle.gen >= 5) return ['Normal']; return ['???']; }; BattlePokemon.prototype.runEffectiveness = function (move) { var totalTypeMod = 0; var types = this.getTypes(); for (var i = 0; i < types.length; i++) { var typeMod = this.battle.getEffectiveness(move, types[i]); typeMod = this.battle.singleEvent('Effectiveness', move, null, types[i], move, null, typeMod); totalTypeMod += this.battle.runEvent('Effectiveness', this, types[i], move, typeMod); } return totalTypeMod; }; BattlePokemon.prototype.runImmunity = function (type, message) { if (this.fainted) { return false; } if (!type || type === '???') { return true; } if (this.negateImmunity[type]) return true; if (!(this.negateImmunity['Type'] && type in this.battle.data.TypeChart)) { // Ring Target not active if (!this.battle.getImmunity(type, this)) { this.battle.debug('natural immunity'); if (message) { this.battle.add('-immune', this, '[msg]'); } return false; } } var immunity = this.battle.runEvent('Immunity', this, null, null, type); if (!immunity) { this.battle.debug('artificial immunity'); if (message && immunity !== null) { this.battle.add('-immune', this, '[msg]'); } return false; } return true; }; BattlePokemon.prototype.destroy = function () { // deallocate ourself // get rid of some possibly-circular references this.battle = null; this.side = null; }; return BattlePokemon; })(); BattleSide = (function () { function BattleSide(name, battle, n, team) { var sideScripts = battle.data.Scripts.side; if (sideScripts) Object.merge(this, sideScripts); this.battle = battle; this.n = n; this.name = name; this.pokemon = []; this.active = [null]; this.sideConditions = {}; this.id = n ? 'p2' : 'p1'; switch (this.battle.gameType) { case 'doubles': this.active = [null, null]; break; case 'triples': case 'rotation': this.active = [null, null, null]; break; } this.team = this.battle.getTeam(this, team); for (var i = 0; i < this.team.length && i < 6; i++) { //console.log("NEW POKEMON: " + (this.team[i] ? this.team[i].name : '[unidentified]')); this.pokemon.push(new BattlePokemon(this.team[i], this)); } this.pokemonLeft = this.pokemon.length; for (var i = 0; i < this.pokemon.length; i++) { this.pokemon[i].position = i; } } BattleSide.prototype.isActive = false; BattleSide.prototype.pokemonLeft = 0; BattleSide.prototype.faintedLastTurn = false; BattleSide.prototype.faintedThisTurn = false; BattleSide.prototype.decision = null; BattleSide.prototype.foe = null; BattleSide.prototype.toString = function () { return this.id + ': ' + this.name; }; BattleSide.prototype.getData = function () { var data = { name: this.name, id: this.id, pokemon: [] }; for (var i = 0; i < this.pokemon.length; i++) { var pokemon = this.pokemon[i]; data.pokemon.push({ ident: pokemon.fullname, details: pokemon.details, condition: pokemon.getHealth(pokemon.side), active: (pokemon.position < pokemon.side.active.length), stats: { atk: pokemon.baseStats['atk'], def: pokemon.baseStats['def'], spa: pokemon.baseStats['spa'], spd: pokemon.baseStats['spd'], spe: pokemon.baseStats['spe'] }, moves: pokemon.moves.map(function (move) { if (move === 'hiddenpower') { return move + toId(pokemon.hpType) + (pokemon.hpPower === 70 ? '' : pokemon.hpPower); } return move; }), baseAbility: pokemon.baseAbility, item: pokemon.item, pokeball: pokemon.pokeball, canMegaEvo: !!pokemon.canMegaEvo }); } return data; }; BattleSide.prototype.randomActive = function () { var actives = this.active.filter(function (active) { return active && !active.fainted; }); if (!actives.length) return null; var i = Math.floor(Math.random() * actives.length); return actives[i]; }; BattleSide.prototype.addSideCondition = function (status, source, sourceEffect) { status = this.battle.getEffect(status); if (this.sideConditions[status.id]) { if (!status.onRestart) return false; return this.battle.singleEvent('Restart', status, this.sideConditions[status.id], this, source, sourceEffect); } this.sideConditions[status.id] = {id: status.id}; this.sideConditions[status.id].target = this; if (source) { this.sideConditions[status.id].source = source; this.sideConditions[status.id].sourcePosition = source.position; } if (status.duration) { this.sideConditions[status.id].duration = status.duration; } if (status.durationCallback) { this.sideConditions[status.id].duration = status.durationCallback.call(this.battle, this, source, sourceEffect); } if (!this.battle.singleEvent('Start', status, this.sideConditions[status.id], this, source, sourceEffect)) { delete this.sideConditions[status.id]; return false; } this.battle.update(); return true; }; BattleSide.prototype.getSideCondition = function (status) { status = this.battle.getEffect(status); if (!this.sideConditions[status.id]) return null; return status; }; BattleSide.prototype.removeSideCondition = function (status) { status = this.battle.getEffect(status); if (!this.sideConditions[status.id]) return false; this.battle.singleEvent('End', status, this.sideConditions[status.id], this); delete this.sideConditions[status.id]; this.battle.update(); return true; }; BattleSide.prototype.send = function () { var parts = Array.prototype.slice.call(arguments); var functions = parts.map(function (part) { return typeof part === 'function'; }); var sideUpdate = []; if (functions.indexOf(true) < 0) { sideUpdate.push('|' + parts.join('|')); } else { var line = ''; for (var j = 0; j < parts.length; ++j) { line += '|'; if (functions[j]) { line += parts[j](this); } else { line += parts[j]; } } sideUpdate.push(line); } this.battle.send('sideupdate', this.id + "\n" + sideUpdate); }; BattleSide.prototype.emitCallback = function () { this.battle.send('callback', this.id + "\n" + Array.prototype.slice.call(arguments).join('|')); }; BattleSide.prototype.emitRequest = function (update) { this.battle.send('request', this.id + "\n" + this.battle.rqid + "\n" + JSON.stringify(update)); }; BattleSide.prototype.resolveDecision = function () { if (this.decision) return this.decision; var decisions = []; switch (this.currentRequest) { case 'move': for (var i = 0; i < this.active.length; i++) { var pokemon = this.active[i]; if (!pokemon || pokemon.fainted) continue; var lockedMove = pokemon.getLockedMove(); if (lockedMove) { decisions.push({ choice: 'move', pokemon: pokemon, targetLoc: this.battle.runEvent('LockMoveTarget', pokemon) || 0, move: lockedMove }); continue; } var moveid = 'struggle'; var moves = pokemon.getMoves(); for (var j = 0; j < moves.length; j++) { if (moves[j].disabled) continue; moveid = moves[j].id; break; } decisions.push({ choice: 'move', pokemon: pokemon, targetLoc: 0, move: moveid }); } break; case 'switch': var canSwitchOut = []; for (var i = 0; i < this.active.length; i++) { if (this.active[i] && this.active[i].switchFlag) canSwitchOut.push(i); } var canSwitchIn = []; for (var i = this.active.length; i < this.pokemon.length; i++) { if (this.pokemon[i] && !this.pokemon[i].fainted) canSwitchIn.push(i); } var willPass = canSwitchOut.splice(Math.min(canSwitchOut.length, canSwitchIn.length)); for (var i = 0; i < canSwitchOut.length; i++) { decisions.push({ choice: 'switch', pokemon: this.active[canSwitchOut[i]], target: this.pokemon[canSwitchIn[i]], priority: 101 }); } for (var i = 0; i < willPass.length; i++) { decisions.push({ choice: 'pass', pokemon: this.active[willPass[i]], priority: 102 }); } break; case 'teampreview': decisions.push({ choice: 'team', side: this, team: [0, 1, 2, 3, 4, 5].slice(0, this.pokemon.length) }); } return decisions; }; BattleSide.prototype.destroy = function () { // deallocate ourself // deallocate children and get rid of references to them for (var i = 0; i < this.pokemon.length; i++) { if (this.pokemon[i]) this.pokemon[i].destroy(); this.pokemon[i] = null; } this.pokemon = null; for (var i = 0; i < this.active.length; i++) { this.active[i] = null; } this.active = null; if (this.decision) { delete this.decision.side; delete this.decision.pokemon; } this.decision = null; // get rid of some possibly-circular references this.battle = null; this.foe = null; }; return BattleSide; })(); Battle = (function () { var Battle = {}; Battle.construct = (function () { var battleProtoCache = {}; return function (roomid, formatarg, rated) { var battle = Object.create((function () { if (battleProtoCache[formatarg] !== undefined) { return battleProtoCache[formatarg]; } // Scripts overrides Battle overrides Scripts overrides Tools var tools = Tools.mod(formatarg); var proto = Object.create(tools); for (var i in Battle.prototype) { proto[i] = Battle.prototype[i]; } var battle = Object.create(proto); var ret = Object.create(battle); tools.install(ret); return (battleProtoCache[formatarg] = ret); })()); Battle.prototype.init.call(battle, roomid, formatarg, rated); return battle; }; })(); Battle.prototype = {}; Battle.prototype.init = function (roomid, formatarg, rated) { var format = Tools.getFormat(formatarg); this.log = []; this.sides = [null, null]; this.roomid = roomid; this.id = roomid; this.rated = rated; this.weatherData = {id:''}; this.terrainData = {id:''}; this.pseudoWeather = {}; this.format = toId(format); this.formatData = {id:this.format}; this.effect = {id:''}; this.effectData = {id:''}; this.event = {id:''}; this.gameType = (format.gameType || 'singles'); this.queue = []; this.faintQueue = []; this.messageLog = []; // use a random initial seed (64-bit, [high -> low]) this.startingSeed = this.seed = [ Math.floor(Math.random() * 0x10000), Math.floor(Math.random() * 0x10000), Math.floor(Math.random() * 0x10000), Math.floor(Math.random() * 0x10000) ]; }; Battle.prototype.turn = 0; Battle.prototype.p1 = null; Battle.prototype.p2 = null; Battle.prototype.lastUpdate = 0; Battle.prototype.weather = ''; Battle.prototype.terrain = ''; Battle.prototype.ended = false; Battle.prototype.started = false; Battle.prototype.active = false; Battle.prototype.eventDepth = 0; Battle.prototype.lastMove = ''; Battle.prototype.activeMove = null; Battle.prototype.activePokemon = null; Battle.prototype.activeTarget = null; Battle.prototype.midTurn = false; Battle.prototype.currentRequest = ''; Battle.prototype.currentRequestDetails = ''; Battle.prototype.rqid = 0; Battle.prototype.lastMoveLine = 0; Battle.prototype.reportPercentages = false; Battle.prototype.supportCancel = false; Battle.prototype.toString = function () { return 'Battle: ' + this.format; }; // This function is designed to emulate the on-cartridge PRNG for Gens 3 and 4, as described in // http://www.smogon.com/ingame/rng/pid_iv_creation#pokemon_random_number_generator // This RNG uses a 32-bit initial seed // This function has three different results, depending on arguments: // - random() returns a real number in [0, 1), just like Math.random() // - random(n) returns an integer in [0, n) // - random(m, n) returns an integer in [m, n) // m and n are converted to integers via Math.floor. If the result is NaN, they are ignored. /* Battle.prototype.random = function (m, n) { this.seed = (this.seed * 0x41C64E6D + 0x6073) >>> 0; // truncate the result to the last 32 bits var result = this.seed >>> 16; // the first 16 bits of the seed are the random value m = Math.floor(m); n = Math.floor(n); return (m ? (n ? (result % (n - m)) + m : result % m) : result / 0x10000); }; */ // This function is designed to emulate the on-cartridge PRNG for Gen 5 and uses a 64-bit initial seed // This function has three different results, depending on arguments: // - random() returns a real number in [0, 1), just like Math.random() // - random(n) returns an integer in [0, n) // - random(m, n) returns an integer in [m, n) // m and n are converted to integers via Math.floor. If the result is NaN, they are ignored. Battle.prototype.random = function (m, n) { this.seed = this.nextFrame(); // Advance the RNG var result = (this.seed[0] << 16 >>> 0) + this.seed[1]; // Use the upper 32 bits m = Math.floor(m); n = Math.floor(n); result = (m ? (n ? Math.floor(result * (n - m) / 0x100000000) + m : Math.floor(result * m / 0x100000000)) : result / 0x100000000); this.debug('randBW(' + (m ? (n ? m + ', ' + n : m) : '') + ') = ' + result); return result; }; Battle.prototype.nextFrame = function (n) { var seed = this.seed; n = n || 1; for (var frame = 0; frame < n; ++frame) { // The RNG is a Linear Congruential Generator (LCG) in the form: x_{n + 1} = (a x_n + c) % m // Where: x_0 is the seed, x_n is the random number after n iterations, // a = 0x5D588B656C078965, c = 0x00269EC3 and m = 2^64 // Javascript doesnt handle such large numbers properly, so this function does it in 16-bit parts. // x_{n + 1} = (x_n * a) + c // Let any 64 bit number n = (n[0] << 48) + (n[1] << 32) + (n[2] << 16) + n[3] // Then x_{n + 1} = // ((a[3] x_n[0] + a[2] x_n[1] + a[1] x_n[2] + a[0] x_n[3] + c[0]) << 48) + // ((a[3] x_n[1] + a[2] x_n[2] + a[1] x_n[3] + c[1]) << 32) + // ((a[3] x_n[2] + a[2] x_n[3] + c[2]) << 16) + // a[3] x_n[3] + c[3] // Which can be generalised where b is the number of 16 bit words in the number: // (Notice how the a[] word starts at b-1, and decrements every time it appears again on the line; // x_n[] starts at b-<line#>-1 and increments to b-1 at the end of the line per line, limiting the length of the line; // c[] is at b-<line#>-1 for each line and the left shift is 16 * <line#>) // ((a[b-1] + x_n[b-1] + c[b-1]) << (16 * 0)) + // ((a[b-1] x_n[b-2] + a[b-2] x_n[b-1] + c[b-2]) << (16 * 1)) + // ((a[b-1] x_n[b-3] + a[b-2] x_n[b-2] + a[b-3] x_n[b-1] + c[b-3]) << (16 * 2)) + // ... // ((a[b-1] x_n[1] + a[b-2] x_n[2] + ... + a[2] x_n[b-2] + a[1] + x_n[b-1] + c[1]) << (16 * (b-2))) + // ((a[b-1] x_n[0] + a[b-2] x_n[1] + ... + a[1] x_n[b-2] + a[0] + x_n[b-1] + c[0]) << (16 * (b-1))) // Which produces this equation: \sum_{l=0}^{b-1}\left(\sum_{m=b-l-1}^{b-1}\left\{a[2b-m-l-2] x_n[m]\right\}+c[b-l-1]\ll16l\right) // This is all ignoring overflow/carry because that cannot be shown in a pseudo-mathematical equation. // The below code implements a optimised version of that equation while also checking for overflow/carry. var a = [0x5D58, 0x8B65, 0x6C07, 0x8965]; var c = [0, 0, 0x26, 0x9EC3]; var nextSeed = [0, 0, 0, 0]; var carry = 0; for (var cN = seed.length - 1; cN >= 0; --cN) { nextSeed[cN] = carry; carry = 0; var aN = seed.length - 1; var seedN = cN; for (; seedN < seed.length; --aN, ++seedN) { var nextWord = a[aN] * seed[seedN]; carry += nextWord >>> 16; nextSeed[cN] += nextWord & 0xFFFF; } nextSeed[cN] += c[cN]; carry += nextSeed[cN] >>> 16; nextSeed[cN] &= 0xFFFF; } seed = nextSeed; } return seed; }; Battle.prototype.setWeather = function (status, source, sourceEffect) { status = this.getEffect(status); if (sourceEffect === undefined && this.effect) sourceEffect = this.effect; if (source === undefined && this.event && this.event.target) source = this.event.target; if (this.weather === status.id && (this.gen > 2 || status.id === 'sandstorm')) { return false; } if (status.id) { var result = this.runEvent('SetWeather', source, source, status); if (!result) { if (result === false) { if (sourceEffect && sourceEffect.weather) { this.add('-fail', source, sourceEffect, '[from]: ' + this.weather); } else if (sourceEffect && sourceEffect.effectType === 'Ability') { this.add('-ability', source, sourceEffect, '[from] ' + this.weather, '[fail]'); } } return null; } } if (this.weather && !status.id) { var oldstatus = this.getWeather(); this.singleEvent('End', oldstatus, this.weatherData, this); } var prevWeather = this.weather; var prevWeatherData = this.weatherData; this.weather = status.id; this.weatherData = {id: status.id}; if (source) { this.weatherData.source = source; this.weatherData.sourcePosition = source.position; } if (status.duration) { this.weatherData.duration = status.duration; } if (status.durationCallback) { this.weatherData.duration = status.durationCallback.call(this, source, sourceEffect); } if (!this.singleEvent('Start', status, this.weatherData, this, source, sourceEffect)) { this.weather = prevWeather; this.weatherData = prevWeatherData; return false; } this.update(); return true; }; Battle.prototype.clearWeather = function () { return this.setWeather(''); }; Battle.prototype.effectiveWeather = function (target) { if (this.event) { if (!target) target = this.event.target; } if (!this.runEvent('TryWeather', target)) return ''; return this.weather; }; Battle.prototype.isWeather = function (weather, target) { var ourWeather = this.effectiveWeather(target); if (!Array.isArray(weather)) { return ourWeather === toId(weather); } return (weather.map(toId).indexOf(ourWeather) >= 0); }; Battle.prototype.getWeather = function () { return this.getEffect(this.weather); }; Battle.prototype.setTerrain = function (status, source, sourceEffect) { status = this.getEffect(status); if (sourceEffect === undefined && this.effect) sourceEffect = this.effect; if (source === undefined && this.event && this.event.target) source = this.event.target; if (this.terrain === status.id) return false; if (this.terrain && !status.id) { var oldstatus = this.getTerrain(); this.singleEvent('End', oldstatus, this.terrainData, this); } var prevTerrain = this.terrain; var prevTerrainData = this.terrainData; this.terrain = status.id; this.terrainData = {id: status.id}; if (source) { this.terrainData.source = source; this.terrainData.sourcePosition = source.position; } if (status.duration) { this.terrainData.duration = status.duration; } if (status.durationCallback) { this.terrainData.duration = status.durationCallback.call(this, source, sourceEffect); } if (!this.singleEvent('Start', status, this.terrainData, this, source, sourceEffect)) { this.terrain = prevTerrain; this.terrainData = prevTerrainData; return false; } this.update(); return true; }; Battle.prototype.clearTerrain = function () { return this.setTerrain(''); }; Battle.prototype.effectiveTerrain = function (target) { if (this.event) { if (!target) target = this.event.target; } if (!this.runEvent('TryTerrain', target)) return ''; return this.terrain; }; Battle.prototype.isTerrain = function (terrain, target) { var ourTerrain = this.effectiveTerrain(target); if (!Array.isArray(terrain)) { return ourTerrain === toId(terrain); } return (terrain.map(toId).indexOf(ourTerrain) >= 0); }; Battle.prototype.getTerrain = function () { return this.getEffect(this.terrain); }; Battle.prototype.getFormat = function () { return this.getEffect(this.format); }; Battle.prototype.addPseudoWeather = function (status, source, sourceEffect) { status = this.getEffect(status); if (this.pseudoWeather[status.id]) { if (!status.onRestart) return false; return this.singleEvent('Restart', status, this.pseudoWeather[status.id], this, source, sourceEffect); } this.pseudoWeather[status.id] = {id: status.id}; if (source) { this.pseudoWeather[status.id].source = source; this.pseudoWeather[status.id].sourcePosition = source.position; } if (status.duration) { this.pseudoWeather[status.id].duration = status.duration; } if (status.durationCallback) { this.pseudoWeather[status.id].duration = status.durationCallback.call(this, source, sourceEffect); } if (!this.singleEvent('Start', status, this.pseudoWeather[status.id], this, source, sourceEffect)) { delete this.pseudoWeather[status.id]; return false; } this.update(); return true; }; Battle.prototype.getPseudoWeather = function (status) { status = this.getEffect(status); if (!this.pseudoWeather[status.id]) return null; return status; }; Battle.prototype.removePseudoWeather = function (status) { status = this.getEffect(status); if (!this.pseudoWeather[status.id]) return false; this.singleEvent('End', status, this.pseudoWeather[status.id], this); delete this.pseudoWeather[status.id]; this.update(); return true; }; Battle.prototype.setActiveMove = function (move, pokemon, target) { if (!move) move = null; if (!pokemon) pokemon = null; if (!target) target = pokemon; this.activeMove = move; this.activePokemon = pokemon; this.activeTarget = target; // Mold Breaker and the like this.update(); }; Battle.prototype.clearActiveMove = function (failed) { if (this.activeMove) { if (!failed) { this.lastMove = this.activeMove.id; } this.activeMove = null; this.activePokemon = null; this.activeTarget = null; // Mold Breaker and the like, again this.update(); } }; Battle.prototype.update = function () { var actives = this.p1.active; for (var i = 0; i < actives.length; i++) { if (actives[i]) actives[i].update(); } actives = this.p2.active; for (var i = 0; i < actives.length; i++) { if (actives[i]) actives[i].update(); } }; // bubbles up Battle.comparePriority = function (a, b) { // intentionally not in Battle.prototype a.priority = a.priority || 0; a.subPriority = a.subPriority || 0; a.speed = a.speed || 0; b.priority = b.priority || 0; b.subPriority = b.subPriority || 0; b.speed = b.speed || 0; if ((typeof a.order === 'number' || typeof b.order === 'number') && a.order !== b.order) { if (typeof a.order !== 'number') { return -1; } if (typeof b.order !== 'number') { return 1; } if (b.order - a.order) { return -(b.order - a.order); } } if (b.priority - a.priority) { return b.priority - a.priority; } if (b.speed - a.speed) { return b.speed - a.speed; } if (b.subOrder - a.subOrder) { return -(b.subOrder - a.subOrder); } return Math.random() - 0.5; }; Battle.prototype.getResidualStatuses = function (thing, callbackType) { var statuses = this.getRelevantEffectsInner(thing || this, callbackType || 'residualCallback', null, null, false, true, 'duration'); statuses.sort(Battle.comparePriority); //if (statuses[0]) this.debug('match ' + (callbackType || 'residualCallback') + ': ' + statuses[0].status.id); return statuses; }; Battle.prototype.eachEvent = function (eventid, effect, relayVar) { var actives = []; if (!effect && this.effect) effect = this.effect; for (var i = 0; i < this.sides.length; i++) { var side = this.sides[i]; for (var j = 0; j < side.active.length; j++) { if (side.active[j]) actives.push(side.active[j]); } } actives.sort(function (a, b) { if (b.speed - a.speed) { return b.speed - a.speed; } return Math.random() - 0.5; }); for (var i = 0; i < actives.length; i++) { if (actives[i].isStarted) { this.runEvent(eventid, actives[i], null, effect, relayVar); } } }; Battle.prototype.residualEvent = function (eventid, relayVar) { var statuses = this.getRelevantEffectsInner(this, 'on' + eventid, null, null, false, true, 'duration'); statuses.sort(Battle.comparePriority); while (statuses.length) { var statusObj = statuses.shift(); var status = statusObj.status; if (statusObj.thing.fainted) continue; if (statusObj.statusData && statusObj.statusData.duration) { statusObj.statusData.duration--; if (!statusObj.statusData.duration) { statusObj.end.call(statusObj.thing, status.id); continue; } } this.singleEvent(eventid, status, statusObj.statusData, statusObj.thing, relayVar); } }; // The entire event system revolves around this function // (and its helper functions, getRelevant * ) Battle.prototype.singleEvent = function (eventid, effect, effectData, target, source, sourceEffect, relayVar) { if (this.eventDepth >= 8) { // oh fuck this.add('message', 'STACK LIMIT EXCEEDED'); this.add('message', 'PLEASE REPORT IN BUG THREAD'); this.add('message', 'Event: ' + eventid); this.add('message', 'Parent event: ' + this.event.id); throw new Error("Stack overflow"); } //this.add('Event: ' + eventid + ' (depth ' + this.eventDepth + ')'); effect = this.getEffect(effect); var hasRelayVar = true; if (relayVar === undefined) { relayVar = true; hasRelayVar = false; } if (effect.effectType === 'Status' && target.status !== effect.id) { // it's changed; call it off return relayVar; } if (target.ignore && target.ignore[effect.effectType] && target.ignore[effect.effectType] !== 'A') { this.debug(eventid + ' handler suppressed by Gastro Acid, Klutz or Magic Room'); return relayVar; } if (effect.effectType === 'Weather' && eventid !== 'TryWeather' && !this.runEvent('TryWeather', target)) { this.debug(eventid + ' handler suppressed by Air Lock'); return relayVar; } if (effect['on' + eventid] === undefined) return relayVar; var parentEffect = this.effect; var parentEffectData = this.effectData; var parentEvent = this.event; this.effect = effect; this.effectData = effectData; this.event = {id: eventid, target: target, source: source, effect: sourceEffect}; this.eventDepth++; var args = [target, source, sourceEffect]; if (hasRelayVar) args.unshift(relayVar); var returnVal; if (typeof effect['on' + eventid] === 'function') { returnVal = effect['on' + eventid].apply(this, args); } else { returnVal = effect['on' + eventid]; } this.eventDepth--; this.effect = parentEffect; this.effectData = parentEffectData; this.event = parentEvent; if (returnVal === undefined) return relayVar; return returnVal; }; /** * runEvent is the core of Pokemon Showdown's event system. * * Basic usage * =========== * * this.runEvent('Blah') * will trigger any onBlah global event handlers. * * this.runEvent('Blah', target) * will additionally trigger any onBlah handlers on the target, onAllyBlah * handlers on any active pokemon on the target's team, and onFoeBlah * handlers on any active pokemon on the target's foe's team * * this.runEvent('Blah', target, source) * will additionally trigger any onSourceBlah handlers on the source * * this.runEvent('Blah', target, source, effect) * will additionally pass the effect onto all event handlers triggered * * this.runEvent('Blah', target, source, effect, relayVar) * will additionally pass the relayVar as the first argument along all event * handlers * * You may leave any of these null. For instance, if you have a relayVar but * no source or effect: * this.runEvent('Damage', target, null, null, 50) * * Event handlers * ============== * * Items, abilities, statuses, and other effects like SR, confusion, weather, * or Trick Room can have event handlers. Event handlers are functions that * can modify what happens during an event. * * event handlers are passed: * function (target, source, effect) * although some of these can be blank. * * certain events have a relay variable, in which case they're passed: * function (relayVar, target, source, effect) * * Relay variables are variables that give additional information about the * event. For instance, the damage event has a relayVar which is the amount * of damage dealt. * * If a relay variable isn't passed to runEvent, there will still be a secret * relayVar defaulting to `true`, but it won't get passed to any event * handlers. * * After an event handler is run, its return value helps determine what * happens next: * 1. If the return value isn't `undefined`, relayVar is set to the return * value * 2. If relayVar is falsy, no more event handlers are run * 3. Otherwise, if there are more event handlers, the next one is run and * we go back to step 1. * 4. Once all event handlers are run (or one of them results in a falsy * relayVar), relayVar is returned by runEvent * * As a shortcut, an event handler that isn't a function will be interpreted * as a function that returns that value. * * You can have return values mean whatever you like, but in general, we * follow the convention that returning `false` or `null` means * stopping or interrupting the event. * * For instance, returning `false` from a TrySetStatus handler means that * the pokemon doesn't get statused. * * If a failed event usually results in a message like "But it failed!" * or "It had no effect!", returning `null` will suppress that message and * returning `false` will display it. Returning `null` is useful if your * event handler already gave its own custom failure message. * * Returning `undefined` means "don't change anything" or "keep going". * A function that does nothing but return `undefined` is the equivalent * of not having an event handler at all. * * Returning a value means that that value is the new `relayVar`. For * instance, if a Damage event handler returns 50, the damage event * will deal 50 damage instead of whatever it was going to deal before. * * Useful values * ============= * * In addition to all the methods and attributes of Tools, Battle, and * Scripts, event handlers have some additional values they can access: * * this.effect: * the Effect having the event handler * this.effectData: * the data store associated with the above Effect. This is a plain Object * and you can use it to store data for later event handlers. * this.effectData.target: * the Pokemon, Side, or Battle that the event handler's effect was * attached to. * this.event.id: * the event ID * this.event.target, this.event.source, this.event.effect: * the target, source, and effect of the event. These are the same * variables that are passed as arguments to the event handler, but * they're useful for functions called by the event handler. */ Battle.prototype.runEvent = function (eventid, target, source, effect, relayVar, onEffect) { if (this.eventDepth >= 8) { // oh fuck this.add('message', 'STACK LIMIT EXCEEDED'); this.add('message', 'PLEASE REPORT IN BUG THREAD'); this.add('message', 'Event: ' + eventid); this.add('message', 'Parent event: ' + this.event.id); throw new Error("Stack overflow"); } if (!target) target = this; var statuses = this.getRelevantEffects(target, 'on' + eventid, 'onSource' + eventid, source); var hasRelayVar = true; effect = this.getEffect(effect); var args = [target, source, effect]; //console.log('Event: ' + eventid + ' (depth ' + this.eventDepth + ') t:' + target.id + ' s:' + (!source || source.id) + ' e:' + effect.id); if (relayVar === undefined || relayVar === null) { relayVar = true; hasRelayVar = false; } else { args.unshift(relayVar); } var parentEvent = this.event; this.event = {id: eventid, target: target, source: source, effect: effect, modifier: 1}; this.eventDepth++; if (onEffect && 'on' + eventid in effect) { statuses.unshift({status: effect, callback: effect['on' + eventid], statusData: {}, end: null, thing: target}); } for (var i = 0; i < statuses.length; i++) { var status = statuses[i].status; var thing = statuses[i].thing; //this.debug('match ' + eventid + ': ' + status.id + ' ' + status.effectType); if (status.effectType === 'Status' && thing.status !== status.id) { // it's changed; call it off continue; } if (thing.ignore && thing.ignore[status.effectType] === 'A') { // ignore attacking events var AttackingEvents = { BeforeMove: 1, BasePower: 1, Immunity: 1, Accuracy: 1, RedirectTarget: 1, Damage: 1, SubDamage: 1, Heal: 1, TakeItem: 1, SetStatus: 1, CriticalHit: 1, ModifyPokemon: 1, ModifyAtk: 1, ModifyDef: 1, ModifySpA: 1, ModifySpD: 1, ModifySpe: 1, ModifyBoost: 1, ModifyDamage: 1, ModifyWeight: 1, TryHit: 1, TryHitSide: 1, TrySecondaryHit: 1, Hit: 1, Boost: 1, DragOut: 1 }; if (eventid in AttackingEvents) { if (eventid !== 'ModifyPokemon') { this.debug(eventid + ' handler suppressed by Mold Breaker'); } continue; } } else if (thing.ignore && thing.ignore[status.effectType]) { if (eventid !== 'ModifyPokemon' && eventid !== 'Update') { this.debug(eventid + ' handler suppressed by Gastro Acid, Klutz or Magic Room'); } continue; } if ((status.effectType === 'Weather' || eventid === 'Weather') && eventid !== 'TryWeather' && !this.runEvent('TryWeather', target)) { this.debug(eventid + ' handler suppressed by Air Lock'); continue; } var returnVal; if (typeof statuses[i].callback === 'function') { var parentEffect = this.effect; var parentEffectData = this.effectData; this.effect = statuses[i].status; this.effectData = statuses[i].statusData; this.effectData.target = thing; returnVal = statuses[i].callback.apply(this, args); this.effect = parentEffect; this.effectData = parentEffectData; } else { returnVal = statuses[i].callback; } if (returnVal !== undefined) { relayVar = returnVal; if (!relayVar) break; if (hasRelayVar) { args[0] = relayVar; } } } this.eventDepth--; if (this.event.modifier !== 1 && typeof relayVar === 'number') { // this.debug(eventid + ' modifier: 0x' + ('0000' + (this.event.modifier * 4096).toString(16)).slice(-4).toUpperCase()); relayVar = this.modify(relayVar, this.event.modifier); } this.event = parentEvent; return relayVar; }; Battle.prototype.resolveLastPriority = function (statuses, callbackType) { var order = false; var priority = 0; var subOrder = 0; var status = statuses[statuses.length - 1]; if (status.status[callbackType + 'Order']) { order = status.status[callbackType + 'Order']; } if (status.status[callbackType + 'Priority']) { priority = status.status[callbackType + 'Priority']; } else if (status.status[callbackType + 'SubOrder']) { subOrder = status.status[callbackType + 'SubOrder']; } status.order = order; status.priority = priority; status.subOrder = subOrder; if (status.thing && status.thing.getStat) status.speed = status.thing.speed; }; // bubbles up to parents Battle.prototype.getRelevantEffects = function (thing, callbackType, foeCallbackType, foeThing) { var statuses = this.getRelevantEffectsInner(thing, callbackType, foeCallbackType, foeThing, true, false); statuses.sort(Battle.comparePriority); //if (statuses[0]) this.debug('match ' + callbackType + ': ' + statuses[0].status.id); return statuses; }; Battle.prototype.getRelevantEffectsInner = function (thing, callbackType, foeCallbackType, foeThing, bubbleUp, bubbleDown, getAll) { if (!callbackType || !thing) return []; var statuses = []; var status; if (thing.sides) { for (var i in this.pseudoWeather) { status = this.getPseudoWeather(i); if (status[callbackType] !== undefined || (getAll && thing.pseudoWeather[i][getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.pseudoWeather[i], end: this.removePseudoWeather, thing: thing}); this.resolveLastPriority(statuses, callbackType); } } status = this.getWeather(); if (status[callbackType] !== undefined || (getAll && thing.weatherData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.weatherData, end: this.clearWeather, thing: thing, priority: status[callbackType + 'Priority'] || 0}); this.resolveLastPriority(statuses, callbackType); } status = this.getTerrain(); if (status[callbackType] !== undefined || (getAll && thing.terrainData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.terrainData, end: this.clearTerrain, thing: thing, priority: status[callbackType + 'Priority'] || 0}); this.resolveLastPriority(statuses, callbackType); } status = this.getFormat(); if (status[callbackType] !== undefined || (getAll && thing.formatData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: this.formatData, end: function () {}, thing: thing, priority: status[callbackType + 'Priority'] || 0}); this.resolveLastPriority(statuses, callbackType); } if (bubbleDown) { statuses = statuses.concat(this.getRelevantEffectsInner(this.p1, callbackType, null, null, false, true, getAll)); statuses = statuses.concat(this.getRelevantEffectsInner(this.p2, callbackType, null, null, false, true, getAll)); } return statuses; } if (thing.pokemon) { for (var i in thing.sideConditions) { status = thing.getSideCondition(i); if (status[callbackType] !== undefined || (getAll && thing.sideConditions[i][getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.sideConditions[i], end: thing.removeSideCondition, thing: thing}); this.resolveLastPriority(statuses, callbackType); } } if (foeCallbackType) { statuses = statuses.concat(this.getRelevantEffectsInner(thing.foe, foeCallbackType, null, null, false, false, getAll)); if (foeCallbackType.substr(0, 5) === 'onFoe') { var eventName = foeCallbackType.substr(5); statuses = statuses.concat(this.getRelevantEffectsInner(thing.foe, 'onAny' + eventName, null, null, false, false, getAll)); statuses = statuses.concat(this.getRelevantEffectsInner(thing, 'onAny' + eventName, null, null, false, false, getAll)); } } if (bubbleUp) { statuses = statuses.concat(this.getRelevantEffectsInner(this, callbackType, null, null, true, false, getAll)); } if (bubbleDown) { for (var i = 0; i < thing.active.length; i++) { statuses = statuses.concat(this.getRelevantEffectsInner(thing.active[i], callbackType, null, null, false, true, getAll)); } } return statuses; } if (!thing.getStatus) { this.debug(JSON.stringify(thing)); return statuses; } var status = thing.getStatus(); if (status[callbackType] !== undefined || (getAll && thing.statusData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.statusData, end: thing.clearStatus, thing: thing}); this.resolveLastPriority(statuses, callbackType); } for (var i in thing.volatiles) { status = thing.getVolatile(i); if (status[callbackType] !== undefined || (getAll && thing.volatiles[i][getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.volatiles[i], end: thing.removeVolatile, thing: thing}); this.resolveLastPriority(statuses, callbackType); } } status = thing.getAbility(); if (status[callbackType] !== undefined || (getAll && thing.abilityData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.abilityData, end: thing.clearAbility, thing: thing}); this.resolveLastPriority(statuses, callbackType); } status = thing.getItem(); if (status[callbackType] !== undefined || (getAll && thing.itemData[getAll])) { statuses.push({status: status, callback: status[callbackType], statusData: thing.itemData, end: thing.clearItem, thing: thing}); this.resolveLastPriority(statuses, callbackType); } status = this.getEffect(thing.template.baseSpecies); if (status[callbackType] !== undefined) { statuses.push({status: status, callback: status[callbackType], statusData: thing.speciesData, end: function () {}, thing: thing}); this.resolveLastPriority(statuses, callbackType); } if (foeThing && foeCallbackType && foeCallbackType.substr(0, 8) !== 'onSource') { statuses = statuses.concat(this.getRelevantEffectsInner(foeThing, foeCallbackType, null, null, false, false, getAll)); } else if (foeCallbackType) { var foeActive = thing.side.foe.active; var allyActive = thing.side.active; var eventName = ''; if (foeCallbackType.substr(0, 8) === 'onSource') { eventName = foeCallbackType.substr(8); if (foeThing) { statuses = statuses.concat(this.getRelevantEffectsInner(foeThing, foeCallbackType, null, null, false, false, getAll)); } foeCallbackType = 'onFoe' + eventName; foeThing = null; } if (foeCallbackType.substr(0, 5) === 'onFoe') { eventName = foeCallbackType.substr(5); for (var i = 0; i < allyActive.length; i++) { if (!allyActive[i] || allyActive[i].fainted) continue; statuses = statuses.concat(this.getRelevantEffectsInner(allyActive[i], 'onAlly' + eventName, null, null, false, false, getAll)); statuses = statuses.concat(this.getRelevantEffectsInner(allyActive[i], 'onAny' + eventName, null, null, false, false, getAll)); } for (var i = 0; i < foeActive.length; i++) { if (!foeActive[i] || foeActive[i].fainted) continue; statuses = statuses.concat(this.getRelevantEffectsInner(foeActive[i], 'onAny' + eventName, null, null, false, false, getAll)); } } for (var i = 0; i < foeActive.length; i++) { if (!foeActive[i] || foeActive[i].fainted) continue; statuses = statuses.concat(this.getRelevantEffectsInner(foeActive[i], foeCallbackType, null, null, false, false, getAll)); } } if (bubbleUp) { statuses = statuses.concat(this.getRelevantEffectsInner(thing.side, callbackType, foeCallbackType, null, true, false, getAll)); } return statuses; }; Battle.prototype.getPokemon = function (id) { if (typeof id !== 'string') id = id.id; for (var i = 0; i < this.p1.pokemon.length; i++) { var pokemon = this.p1.pokemon[i]; if (pokemon.id === id) return pokemon; } for (var i = 0; i < this.p2.pokemon.length; i++) { var pokemon = this.p2.pokemon[i]; if (pokemon.id === id) return pokemon; } return null; }; Battle.prototype.makeRequest = function (type, requestDetails) { if (type) { this.currentRequest = type; this.currentRequestDetails = requestDetails || ''; this.rqid++; this.p1.decision = null; this.p2.decision = null; } else { type = this.currentRequest; requestDetails = this.currentRequestDetails; } this.update(); // default to no request var p1request = null; var p2request = null; this.p1.currentRequest = ''; this.p2.currentRequest = ''; switch (type) { case 'switch': var switchTable = []; var active; for (var i = 0, l = this.p1.active.length; i < l; i++) { active = this.p1.active[i]; switchTable.push(!!(active && active.switchFlag)); } if (switchTable.any(true)) { this.p1.currentRequest = 'switch'; p1request = {forceSwitch: switchTable, side: this.p1.getData(), rqid: this.rqid}; } switchTable = []; for (var i = 0, l = this.p2.active.length; i < l; i++) { active = this.p2.active[i]; switchTable.push(!!(active && active.switchFlag)); } if (switchTable.any(true)) { this.p2.currentRequest = 'switch'; p2request = {forceSwitch: switchTable, side: this.p2.getData(), rqid: this.rqid}; } break; case 'teampreview': this.add('teampreview' + (requestDetails ? '|' + requestDetails : '')); this.p1.currentRequest = 'teampreview'; p1request = {teamPreview: true, side: this.p1.getData(), rqid: this.rqid}; this.p2.currentRequest = 'teampreview'; p2request = {teamPreview: true, side: this.p2.getData(), rqid: this.rqid}; break; default: var activeData; this.p1.currentRequest = 'move'; activeData = this.p1.active.map(function (pokemon) { if (pokemon) return pokemon.getRequestData(); }); p1request = {active: activeData, side: this.p1.getData(), rqid: this.rqid}; this.p2.currentRequest = 'move'; activeData = this.p2.active.map(function (pokemon) { if (pokemon) return pokemon.getRequestData(); }); p2request = {active: activeData, side: this.p2.getData(), rqid: this.rqid}; break; } if (this.p1 && this.p2) { var inactiveSide = -1; if (p1request && !p2request) { inactiveSide = 0; } else if (!p1request && p2request) { inactiveSide = 1; } if (inactiveSide !== this.inactiveSide) { this.send('inactiveside', inactiveSide); this.inactiveSide = inactiveSide; } } if (p1request) { if (!this.supportCancel || !p2request) p1request.noCancel = true; this.p1.emitRequest(p1request); } else { this.p1.decision = true; this.p1.emitRequest({wait: true, side: this.p1.getData()}); } if (p2request) { if (!this.supportCancel || !p1request) p2request.noCancel = true; this.p2.emitRequest(p2request); } else { this.p2.decision = true; this.p2.emitRequest({wait: true, side: this.p2.getData()}); } if (this.p2.decision && this.p1.decision) { if (this.p2.decision === true && this.p1.decision === true) { if (type !== 'move') { // TODO: investigate this race condition; should be fixed // properly later return this.makeRequest('move'); } this.add('html', '<div class="broadcast-red"><b>The battle crashed</b></div>'); this.win(); } else { // some kind of weird race condition? this.commitDecisions(); } return; } }; Battle.prototype.tie = function () { this.win(); }; Battle.prototype.win = function (side) { if (this.ended) { return false; } if (side === 'p1' || side === 'p2') { side = this[side]; } else if (side !== this.p1 && side !== this.p2) { side = null; } this.winner = side ? side.name : ''; this.add(''); if (side) { this.add('win', side.name); } else { this.add('tie'); } this.ended = true; this.active = false; this.currentRequest = ''; this.currentRequestDetails = ''; return true; }; Battle.prototype.switchIn = function (pokemon, pos) { if (!pokemon || pokemon.isActive) return false; if (!pos) pos = 0; var side = pokemon.side; if (pos >= side.active.length) { throw new Error("Invalid switch position"); } if (side.active[pos]) { var oldActive = side.active[pos]; var lastMove = null; lastMove = this.getMove(oldActive.lastMove); if (oldActive.switchCopyFlag === 'copyvolatile') { delete oldActive.switchCopyFlag; pokemon.copyVolatileFrom(oldActive); } } this.runEvent('BeforeSwitchIn', pokemon); if (side.active[pos]) { var oldActive = side.active[pos]; oldActive.isActive = false; oldActive.isStarted = false; oldActive.usedItemThisTurn = false; oldActive.position = pokemon.position; pokemon.position = pos; side.pokemon[pokemon.position] = pokemon; side.pokemon[oldActive.position] = oldActive; this.cancelMove(oldActive); oldActive.clearVolatile(); } side.active[pos] = pokemon; pokemon.isActive = true; pokemon.activeTurns = 0; for (var m in pokemon.moveset) { pokemon.moveset[m].used = false; } this.add('switch', pokemon, pokemon.getDetails); pokemon.update(); this.addQueue({pokemon: pokemon, choice: 'runSwitch'}); }; Battle.prototype.canSwitch = function (side) { var canSwitchIn = []; for (var i = side.active.length; i < side.pokemon.length; i++) { var pokemon = side.pokemon[i]; if (!pokemon.fainted) { canSwitchIn.push(pokemon); } } return canSwitchIn.length; }; Battle.prototype.getRandomSwitchable = function (side) { var canSwitchIn = []; for (var i = side.active.length; i < side.pokemon.length; i++) { var pokemon = side.pokemon[i]; if (!pokemon.fainted) { canSwitchIn.push(pokemon); } } if (!canSwitchIn.length) { return null; } return canSwitchIn[this.random(canSwitchIn.length)]; }; Battle.prototype.dragIn = function (side, pos) { if (pos >= side.active.length) return false; var pokemon = this.getRandomSwitchable(side); if (!pos) pos = 0; if (!pokemon || pokemon.isActive) return false; this.runEvent('BeforeSwitchIn', pokemon); if (side.active[pos]) { var oldActive = side.active[pos]; if (!oldActive.hp) { return false; } if (!this.runEvent('DragOut', oldActive)) { return false; } this.runEvent('SwitchOut', oldActive); this.singleEvent('End', this.getAbility(oldActive.ability), oldActive.abilityData, oldActive); oldActive.isActive = false; oldActive.isStarted = false; oldActive.usedItemThisTurn = false; oldActive.position = pokemon.position; pokemon.position = pos; side.pokemon[pokemon.position] = pokemon; side.pokemon[oldActive.position] = oldActive; this.cancelMove(oldActive); oldActive.clearVolatile(); } side.active[pos] = pokemon; pokemon.isActive = true; pokemon.activeTurns = 0; for (var m in pokemon.moveset) { pokemon.moveset[m].used = false; } this.add('drag', pokemon, pokemon.getDetails); pokemon.update(); this.addQueue({pokemon: pokemon, choice: 'runSwitch'}); return true; }; Battle.prototype.swapPosition = function (pokemon, slot, attributes) { if (slot >= pokemon.side.active.length) { throw new Error("Invalid swap position"); } var target = pokemon.side.active[slot]; if (slot !== 1 && (!target || target.fainted)) return false; this.add('swap', pokemon, slot, attributes || ''); var side = pokemon.side; side.pokemon[pokemon.position] = target; side.pokemon[slot] = pokemon; side.active[pokemon.position] = side.pokemon[pokemon.position]; side.active[slot] = side.pokemon[slot]; if (target) target.position = pokemon.position; pokemon.position = slot; return true; }; Battle.prototype.faint = function (pokemon, source, effect) { pokemon.faint(source, effect); }; Battle.prototype.nextTurn = function () { this.turn++; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { var pokemon = this.sides[i].active[j]; if (!pokemon) continue; pokemon.moveThisTurn = ''; pokemon.usedItemThisTurn = false; pokemon.newlySwitched = false; pokemon.disabledMoves = {}; this.runEvent('DisableMove', pokemon); if (pokemon.lastAttackedBy) { if (pokemon.lastAttackedBy.pokemon.isActive) { pokemon.lastAttackedBy.thisTurn = false; } else { pokemon.lastAttackedBy = null; } } pokemon.activeTurns++; } this.sides[i].faintedLastTurn = this.sides[i].faintedThisTurn; this.sides[i].faintedThisTurn = false; } this.add('turn', this.turn); if (this.gameType === 'triples' && this.sides.map('pokemonLeft').count(1) === this.sides.length) { // If both sides have one Pokemon left in triples and they are not adjacent, they are both moved to the center. var center = false; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { if (!this.sides[i].active[j] || this.sides[i].active[j].fainted) continue; if (this.sides[i].active[j].position === 1) break; this.swapPosition(this.sides[i].active[j], 1, '[silent]'); center = true; break; } } if (center) this.add('-message', 'Automatic center!'); } this.makeRequest('move'); }; Battle.prototype.start = function () { if (this.active) return; if (!this.p1 || !this.p1.isActive || !this.p2 || !this.p2.isActive) { // need two players to start return; } this.p2.emitRequest({side: this.p2.getData()}); this.p1.emitRequest({side: this.p1.getData()}); if (this.started) { this.makeRequest(); this.isActive = true; this.activeTurns = 0; return; } this.isActive = true; this.activeTurns = 0; this.started = true; this.p2.foe = this.p1; this.p1.foe = this.p2; this.add('gametype', this.gameType); this.add('gen', this.gen); var format = this.getFormat(); Tools.mod(format.mod).getBanlistTable(format); // fill in format ruleset this.add('tier', format.name); if (this.rated) { this.add('rated'); } if (format && format.ruleset) { for (var i = 0; i < format.ruleset.length; i++) { this.addPseudoWeather(format.ruleset[i]); } } if (!this.p1.pokemon[0] || !this.p2.pokemon[0]) { this.add('message', 'Battle not started: One of you has an empty team.'); return; } this.residualEvent('TeamPreview'); this.addQueue({choice:'start'}); this.midTurn = true; if (!this.currentRequest) this.go(); }; Battle.prototype.boost = function (boost, target, source, effect) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } if (!target || !target.hp) return 0; if (!target.isActive) return false; effect = this.getEffect(effect); boost = this.runEvent('Boost', target, source, effect, Object.clone(boost)); var success = false; for (var i in boost) { var currentBoost = {}; currentBoost[i] = boost[i]; if (boost[i] !== 0 && target.boostBy(currentBoost)) { success = true; var msg = '-boost'; if (boost[i] < 0) { msg = '-unboost'; boost[i] = -boost[i]; } switch (effect.id) { case 'intimidate': case 'gooey': this.add(msg, target, i, boost[i]); break; default: if (effect.effectType === 'Move') { this.add(msg, target, i, boost[i]); } else { this.add(msg, target, i, boost[i], '[from] ' + effect.fullname); } break; } this.runEvent('AfterEachBoost', target, source, effect, currentBoost); } } this.runEvent('AfterBoost', target, source, effect, boost); return success; }; Battle.prototype.damage = function (damage, target, source, effect, instafaint) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } if (!target || !target.hp) return 0; if (!target.isActive) return false; effect = this.getEffect(effect); if (!(damage || damage === 0)) return damage; if (damage !== 0) damage = this.clampIntRange(damage, 1); if (effect.id !== 'struggle-recoil') { // Struggle recoil is not affected by effects if (effect.effectType === 'Weather' && !target.runImmunity(effect.id)) { this.debug('weather immunity'); return 0; } damage = this.runEvent('Damage', target, source, effect, damage); if (!(damage || damage === 0)) { this.debug('damage event failed'); return damage; } if (target.illusion && effect && effect.effectType === 'Move') { this.debug('illusion cleared'); target.illusion = null; this.add('replace', target, target.getDetails); } } if (damage !== 0) damage = this.clampIntRange(damage, 1); damage = target.damage(damage, source, effect); if (source) source.lastDamage = damage; var name = effect.fullname; if (name === 'tox') name = 'psn'; switch (effect.id) { case 'partiallytrapped': this.add('-damage', target, target.getHealth, '[from] ' + this.effectData.sourceEffect.fullname, '[partiallytrapped]'); break; case 'powder': this.add('-damage', target, target.getHealth, '[silent]'); break; default: if (effect.effectType === 'Move') { this.add('-damage', target, target.getHealth); } else if (source && source !== target) { this.add('-damage', target, target.getHealth, '[from] ' + effect.fullname, '[of] ' + source); } else { this.add('-damage', target, target.getHealth, '[from] ' + name); } break; } if (effect.drain && source) { this.heal(Math.ceil(damage * effect.drain[0] / effect.drain[1]), source, target, 'drain'); } if (!effect.flags) effect.flags = {}; if (instafaint && !target.hp) { this.debug('instafaint: ' + this.faintQueue.map('target').map('name')); this.faintMessages(true); } else { damage = this.runEvent('AfterDamage', target, source, effect, damage); } return damage; }; Battle.prototype.directDamage = function (damage, target, source, effect) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } if (!target || !target.hp) return 0; if (!damage) return 0; damage = this.clampIntRange(damage, 1); damage = target.damage(damage, source, effect); switch (effect.id) { case 'strugglerecoil': this.add('-damage', target, target.getHealth, '[from] recoil'); break; case 'confusion': this.add('-damage', target, target.getHealth, '[from] confusion'); break; default: this.add('-damage', target, target.getHealth); break; } if (target.fainted) this.faint(target); return damage; }; Battle.prototype.heal = function (damage, target, source, effect) { if (this.event) { if (!target) target = this.event.target; if (!source) source = this.event.source; if (!effect) effect = this.effect; } effect = this.getEffect(effect); if (damage && damage <= 1) damage = 1; damage = Math.floor(damage); // for things like Liquid Ooze, the Heal event still happens when nothing is healed. damage = this.runEvent('TryHeal', target, source, effect, damage); if (!damage) return 0; if (!target || !target.hp) return 0; if (!target.isActive) return false; if (target.hp >= target.maxhp) return 0; damage = target.heal(damage, source, effect); switch (effect.id) { case 'leechseed': case 'rest': this.add('-heal', target, target.getHealth, '[silent]'); break; case 'drain': this.add('-heal', target, target.getHealth, '[from] drain', '[of] ' + source); break; case 'wish': break; default: if (effect.effectType === 'Move') { this.add('-heal', target, target.getHealth); } else if (source && source !== target) { this.add('-heal', target, target.getHealth, '[from] ' + effect.fullname, '[of] ' + source); } else { this.add('-heal', target, target.getHealth, '[from] ' + effect.fullname); } break; } this.runEvent('Heal', target, source, effect, damage); return damage; }; Battle.prototype.chain = function (previousMod, nextMod) { // previousMod or nextMod can be either a number or an array [numerator, denominator] if (previousMod.length) previousMod = Math.floor(previousMod[0] * 4096 / previousMod[1]); else previousMod = Math.floor(previousMod * 4096); if (nextMod.length) nextMod = Math.floor(nextMod[0] * 4096 / nextMod[1]); else nextMod = Math.floor(nextMod * 4096); return ((previousMod * nextMod + 2048) >> 12) / 4096; // M'' = ((M * M') + 0x800) >> 12 }; Battle.prototype.chainModify = function (numerator, denominator) { var previousMod = Math.floor(this.event.modifier * 4096); if (numerator.length) { denominator = numerator[1]; numerator = numerator[0]; } var nextMod = 0; if (this.event.ceilModifier) { nextMod = Math.ceil(numerator * 4096 / (denominator || 1)); } else { nextMod = Math.floor(numerator * 4096 / (denominator || 1)); } this.event.modifier = ((previousMod * nextMod + 2048) >> 12) / 4096; }; Battle.prototype.modify = function (value, numerator, denominator) { // You can also use: // modify(value, [numerator, denominator]) // modify(value, fraction) - assuming you trust JavaScript's floating-point handler if (!denominator) denominator = 1; if (numerator && numerator.length) { denominator = numerator[1]; numerator = numerator[0]; } var modifier = Math.floor(numerator * 4096 / denominator); return Math.floor((value * modifier + 2048 - 1) / 4096); }; Battle.prototype.getCategory = function (move) { move = this.getMove(move); return move.category || 'Physical'; }; Battle.prototype.getDamage = function (pokemon, target, move, suppressMessages) { if (typeof move === 'string') move = this.getMove(move); if (typeof move === 'number') move = { basePower: move, type: '???', category: 'Physical', flags: {} }; if (!move.ignoreImmunity || (move.ignoreImmunity !== true && !move.ignoreImmunity[move.type])) { if (!target.runImmunity(move.type, !suppressMessages)) { return false; } } if (move.ohko) { return target.maxhp; } if (move.damageCallback) { return move.damageCallback.call(this, pokemon, target); } if (move.damage === 'level') { return pokemon.level; } if (move.damage) { return move.damage; } if (!move) { move = {}; } if (!move.type) move.type = '???'; var type = move.type; // '???' is typeless damage: used for Struggle and Confusion etc var category = this.getCategory(move); var defensiveCategory = move.defensiveCategory || category; var basePower = move.basePower; if (move.basePowerCallback) { basePower = move.basePowerCallback.call(this, pokemon, target, move); } if (!basePower) { if (basePower === 0) return; // returning undefined means not dealing damage return basePower; } basePower = this.clampIntRange(basePower, 1); var critMult; if (this.gen <= 5) { move.critRatio = this.clampIntRange(move.critRatio, 0, 5); critMult = [0, 16, 8, 4, 3, 2]; } else { move.critRatio = this.clampIntRange(move.critRatio, 0, 4); critMult = [0, 16, 8, 2, 1]; } move.crit = move.willCrit || false; if (move.willCrit === undefined) { if (move.critRatio) { move.crit = (this.random(critMult[move.critRatio]) === 0); } } if (move.crit) { move.crit = this.runEvent('CriticalHit', target, null, move); } // happens after crit calculation basePower = this.runEvent('BasePower', pokemon, target, move, basePower, true); if (!basePower) return 0; basePower = this.clampIntRange(basePower, 1); var level = pokemon.level; var attacker = pokemon; var defender = target; var attackStat = category === 'Physical' ? 'atk' : 'spa'; var defenseStat = defensiveCategory === 'Physical' ? 'def' : 'spd'; var statTable = {atk:'Atk', def:'Def', spa:'SpA', spd:'SpD', spe:'Spe'}; var attack; var defense; var atkBoosts = move.useTargetOffensive ? defender.boosts[attackStat] : attacker.boosts[attackStat]; var defBoosts = move.useSourceDefensive ? attacker.boosts[defenseStat] : defender.boosts[defenseStat]; var ignoreNegativeOffensive = !!move.ignoreNegativeOffensive; var ignorePositiveDefensive = !!move.ignorePositiveDefensive; if (move.crit) { ignoreNegativeOffensive = true; ignorePositiveDefensive = true; } var ignoreOffensive = !!(move.ignoreOffensive || (ignoreNegativeOffensive && atkBoosts < 0)); var ignoreDefensive = !!(move.ignoreDefensive || (ignorePositiveDefensive && defBoosts > 0)); if (ignoreOffensive) { this.debug('Negating (sp)atk boost/penalty.'); atkBoosts = 0; } if (ignoreDefensive) { this.debug('Negating (sp)def boost/penalty.'); defBoosts = 0; } if (move.useTargetOffensive) attack = defender.calculateStat(attackStat, atkBoosts); else attack = attacker.calculateStat(attackStat, atkBoosts); if (move.useSourceDefensive) defense = attacker.calculateStat(defenseStat, defBoosts); else defense = defender.calculateStat(defenseStat, defBoosts); // Apply Stat Modifiers attack = this.runEvent('Modify' + statTable[attackStat], attacker, defender, move, attack); defense = this.runEvent('Modify' + statTable[defenseStat], defender, attacker, move, defense); //int(int(int(2 * L / 5 + 2) * A * P / D) / 50); var baseDamage = Math.floor(Math.floor(Math.floor(2 * level / 5 + 2) * basePower * attack / defense) / 50) + 2; // multi-target modifier (doubles only) if (move.spreadHit) { var spreadModifier = move.spreadModifier || 0.75; this.debug('Spread modifier: ' + spreadModifier); baseDamage = this.modify(baseDamage, spreadModifier); } // weather modifier (TODO: relocate here) // crit if (move.crit) { if (!suppressMessages) this.add('-crit', target); baseDamage = this.modify(baseDamage, move.critModifier || (this.gen >= 6 ? 1.5 : 2)); } // randomizer // this is not a modifier if (this.gen <= 5) { baseDamage = Math.floor(baseDamage * (100 - this.random(16)) / 100); } else { baseDamage = Math.floor(baseDamage * (85 + this.random(16)) / 100); } // STAB if (move.hasSTAB || type !== '???' && pokemon.hasType(type)) { // The "???" type never gets STAB // Not even if you Roost in Gen 4 and somehow manage to use // Struggle in the same turn. // (On second thought, it might be easier to get a Missingno.) baseDamage = this.modify(baseDamage, move.stab || 1.5); } // types move.typeMod = 0; if (target.negateImmunity[move.type] !== 'IgnoreEffectiveness' || this.getImmunity(move.type, target)) { move.typeMod = target.runEffectiveness(move); } move.typeMod = this.clampIntRange(move.typeMod, -6, 6); if (move.typeMod > 0) { if (!suppressMessages) this.add('-supereffective', target); for (var i = 0; i < move.typeMod; i++) { baseDamage *= 2; } } if (move.typeMod < 0) { if (!suppressMessages) this.add('-resisted', target); for (var i = 0; i > move.typeMod; i--) { baseDamage = Math.floor(baseDamage / 2); } } if (pokemon.status === 'brn' && basePower && move.category === 'Physical' && !pokemon.hasAbility('guts')) { if (this.gen < 6 || move.id !== 'facade') { baseDamage = this.modify(baseDamage, 0.5); } } // Generation 5 sets damage to 1 before the final damage modifiers only if (this.gen === 5 && basePower && !Math.floor(baseDamage)) { baseDamage = 1; } // Final modifier. Modifiers that modify damage after min damage check, such as Life Orb. baseDamage = this.runEvent('ModifyDamage', pokemon, target, move, baseDamage); if (this.gen !== 5 && basePower && !Math.floor(baseDamage)) { return 1; } return Math.floor(baseDamage); }; /** * Returns whether a proposed target for a move is valid. */ Battle.prototype.validTargetLoc = function (targetLoc, source, targetType) { var numSlots = source.side.active.length; if (!Math.abs(targetLoc) && Math.abs(targetLoc) > numSlots) return false; var sourceLoc = -(source.position + 1); var isFoe = (targetLoc > 0); var isAdjacent = (isFoe ? Math.abs(-(numSlots + 1 - targetLoc) - sourceLoc) <= 1 : Math.abs(targetLoc - sourceLoc) === 1); var isSelf = (sourceLoc === targetLoc); switch (targetType) { case 'randomNormal': case 'normal': return isAdjacent; case 'adjacentAlly': return isAdjacent && !isFoe; case 'adjacentAllyOrSelf': return isAdjacent && !isFoe || isSelf; case 'adjacentFoe': return isAdjacent && isFoe; case 'any': return !isSelf; } return false; }; Battle.prototype.getTargetLoc = function (target, source) { if (target.side === source.side) { return -(target.position + 1); } else { return target.position + 1; } }; Battle.prototype.validTarget = function (target, source, targetType) { return this.validTargetLoc(this.getTargetLoc(target, source), source, targetType); }; Battle.prototype.getTarget = function (decision) { var move = this.getMove(decision.move); var target; if ((move.target !== 'randomNormal') && this.validTargetLoc(decision.targetLoc, decision.pokemon, move.target)) { if (decision.targetLoc > 0) { target = decision.pokemon.side.foe.active[decision.targetLoc - 1]; } else { target = decision.pokemon.side.active[-decision.targetLoc - 1]; } if (target) { if (!target.fainted) { // target exists and is not fainted return target; } else if (target.side === decision.pokemon.side) { // fainted allied targets don't retarget return false; } } // chosen target not valid, retarget randomly with resolveTarget } if (!decision.targetPosition || !decision.targetSide) { target = this.resolveTarget(decision.pokemon, decision.move); decision.targetSide = target.side; decision.targetPosition = target.position; } return decision.targetSide.active[decision.targetPosition]; }; Battle.prototype.resolveTarget = function (pokemon, move) { // A move was used without a chosen target // For instance: Metronome chooses Ice Beam. Since the user didn't // choose a target when choosing Metronome, Ice Beam's target must // be chosen randomly. // The target is chosen randomly from possible targets, EXCEPT that // moves that can target either allies or foes will only target foes // when used without an explicit target. move = this.getMove(move); if (move.target === 'adjacentAlly') { var adjacentAllies = [pokemon.side.active[pokemon.position - 1], pokemon.side.active[pokemon.position + 1]].filter(function (active) { return active && !active.fainted; }); if (adjacentAllies.length) return adjacentAllies[Math.floor(Math.random() * adjacentAllies.length)]; return pokemon; } if (move.target === 'self' || move.target === 'all' || move.target === 'allySide' || move.target === 'allyTeam' || move.target === 'adjacentAllyOrSelf') { return pokemon; } if (pokemon.side.active.length > 2) { if (move.target === 'adjacentFoe' || move.target === 'normal' || move.target === 'randomNormal') { var foeActives = pokemon.side.foe.active; var frontPosition = foeActives.length - 1 - pokemon.position; var adjacentFoes = foeActives.slice(frontPosition < 1 ? 0 : frontPosition - 1, frontPosition + 2).filter(function (active) { return active && !active.fainted; }); if (adjacentFoes.length) return adjacentFoes[Math.floor(Math.random() * adjacentFoes.length)]; // no valid target at all, return a foe for any possible redirection } } return pokemon.side.foe.randomActive() || pokemon.side.foe.active[0]; }; Battle.prototype.checkFainted = function () { function check(a) { if (!a) return; if (a.fainted) { a.status = 'fnt'; a.switchFlag = true; } } this.p1.active.forEach(check); this.p2.active.forEach(check); }; Battle.prototype.faintMessages = function (lastFirst) { if (this.ended) return; if (!this.faintQueue.length) return false; if (lastFirst) { this.faintQueue.unshift(this.faintQueue.pop()); } var faintData; while (this.faintQueue.length) { faintData = this.faintQueue.shift(); if (!faintData.target.fainted) { this.add('faint', faintData.target); this.runEvent('Faint', faintData.target, faintData.source, faintData.effect); this.singleEvent('End', this.getAbility(faintData.target.ability), faintData.target.abilityData, faintData.target); faintData.target.fainted = true; faintData.target.isActive = false; faintData.target.isStarted = false; faintData.target.side.pokemonLeft--; faintData.target.side.faintedThisTurn = true; } } if (this.gen <= 1) { // in gen 1, fainting skips the rest of the turn, including residuals this.queue = []; } else if (this.gen <= 3 && this.gameType === 'singles') { // in gen 3 or earlier, fainting in singles skips to residuals for (var i = 0; i < this.p1.active.length; i++) { this.cancelMove(this.p1.active[i]); } for (var i = 0; i < this.p2.active.length; i++) { this.cancelMove(this.p2.active[i]); } } if (!this.p1.pokemonLeft && !this.p2.pokemonLeft) { this.win(faintData && faintData.target.side); return true; } if (!this.p1.pokemonLeft) { this.win(this.p2); return true; } if (!this.p2.pokemonLeft) { this.win(this.p1); return true; } return false; }; Battle.prototype.addQueue = function (decision, noSort, side) { if (decision) { if (Array.isArray(decision)) { for (var i = 0; i < decision.length; i++) { this.addQueue(decision[i], noSort); } return; } if (!decision.side && side) decision.side = side; if (!decision.side && decision.pokemon) decision.side = decision.pokemon.side; if (!decision.choice && decision.move) decision.choice = 'move'; if (!decision.priority) { var priorities = { 'beforeTurn': 100, 'beforeTurnMove': 99, 'switch': 6, 'runSwitch': 6.1, 'megaEvo': 5.9, 'residual': -100, 'team': 102, 'start': 101 }; if (priorities[decision.choice]) { decision.priority = priorities[decision.choice]; } } if (decision.choice === 'move') { if (this.getMove(decision.move).beforeTurnCallback) { this.addQueue({choice: 'beforeTurnMove', pokemon: decision.pokemon, move: decision.move, targetLoc: decision.targetLoc}, true); } } else if (decision.choice === 'switch') { if (decision.pokemon.switchFlag && decision.pokemon.switchFlag !== true) { decision.pokemon.switchCopyFlag = decision.pokemon.switchFlag; } decision.pokemon.switchFlag = false; if (!decision.speed && decision.pokemon && decision.pokemon.isActive) decision.speed = decision.pokemon.speed; } if (decision.move) { var target; if (!decision.targetPosition) { target = this.resolveTarget(decision.pokemon, decision.move); decision.targetSide = target.side; decision.targetPosition = target.position; } decision.move = this.getMoveCopy(decision.move); if (!decision.priority) { var priority = decision.move.priority; priority = this.runEvent('ModifyPriority', decision.pokemon, target, decision.move, priority); decision.priority = priority; // In Gen 6, Quick Guard blocks moves with artificially enhanced priority. if (this.gen > 5) decision.move.priority = priority; } } if (!decision.pokemon && !decision.speed) decision.speed = 1; if (!decision.speed && decision.choice === 'switch' && decision.target) decision.speed = decision.target.speed; if (!decision.speed) decision.speed = decision.pokemon.speed; if (decision.choice === 'switch' && !decision.side.pokemon[0].isActive) { // if there's no actives, switches happen before activations decision.priority = 6.2; } this.queue.push(decision); } if (!noSort) { this.queue.sort(Battle.comparePriority); } }; Battle.prototype.prioritizeQueue = function (decision, source, sourceEffect) { if (this.event) { if (!source) source = this.event.source; if (!sourceEffect) sourceEffect = this.effect; } for (var i = 0; i < this.queue.length; i++) { if (this.queue[i] === decision) { this.queue.splice(i, 1); break; } } decision.sourceEffect = sourceEffect; this.queue.unshift(decision); }; Battle.prototype.willAct = function () { for (var i = 0; i < this.queue.length; i++) { if (this.queue[i].choice === 'move' || this.queue[i].choice === 'switch' || this.queue[i].choice === 'shift') { return this.queue[i]; } } return null; }; Battle.prototype.willMove = function (pokemon) { for (var i = 0; i < this.queue.length; i++) { if (this.queue[i].choice === 'move' && this.queue[i].pokemon === pokemon) { return this.queue[i]; } } return null; }; Battle.prototype.cancelDecision = function (pokemon) { var success = false; for (var i = 0; i < this.queue.length; i++) { if (this.queue[i].pokemon === pokemon) { this.queue.splice(i, 1); i--; success = true; } } return success; }; Battle.prototype.cancelMove = function (pokemon) { for (var i = 0; i < this.queue.length; i++) { if (this.queue[i].choice === 'move' && this.queue[i].pokemon === pokemon) { this.queue.splice(i, 1); return true; } } return false; }; Battle.prototype.willSwitch = function (pokemon) { for (var i = 0; i < this.queue.length; i++) { if (this.queue[i].choice === 'switch' && this.queue[i].pokemon === pokemon) { return true; } } return false; }; Battle.prototype.runDecision = function (decision) { var pokemon; // returns whether or not we ended in a callback switch (decision.choice) { case 'start': // I GIVE UP, WILL WRESTLE WITH EVENT SYSTEM LATER var beginCallback = this.getFormat().onBegin; if (beginCallback) beginCallback.call(this); this.add('start'); for (var pos = 0; pos < this.p1.active.length; pos++) { this.switchIn(this.p1.pokemon[pos], pos); } for (var pos = 0; pos < this.p2.active.length; pos++) { this.switchIn(this.p2.pokemon[pos], pos); } for (var pos = 0; pos < this.p1.pokemon.length; pos++) { pokemon = this.p1.pokemon[pos]; this.singleEvent('Start', this.getEffect(pokemon.species), pokemon.speciesData, pokemon); } for (var pos = 0; pos < this.p2.pokemon.length; pos++) { pokemon = this.p2.pokemon[pos]; this.singleEvent('Start', this.getEffect(pokemon.species), pokemon.speciesData, pokemon); } this.midTurn = true; break; case 'move': if (!decision.pokemon.isActive) return false; if (decision.pokemon.fainted) return false; this.runMove(decision.move, decision.pokemon, this.getTarget(decision), decision.sourceEffect); break; case 'megaEvo': if (decision.pokemon.canMegaEvo) this.runMegaEvo(decision.pokemon); break; case 'beforeTurnMove': if (!decision.pokemon.isActive) return false; if (decision.pokemon.fainted) return false; this.debug('before turn callback: ' + decision.move.id); var target = this.getTarget(decision); if (!target) return false; decision.move.beforeTurnCallback.call(this, decision.pokemon, target); break; case 'event': this.runEvent(decision.event, decision.pokemon); break; case 'team': var len = decision.side.pokemon.length; var newPokemon = [null, null, null, null, null, null].slice(0, len); for (var j = 0; j < len; j++) { var i = decision.team[j]; newPokemon[j] = decision.side.pokemon[i]; newPokemon[j].position = j; } decision.side.pokemon = newPokemon; // we return here because the update event would crash since there are no active pokemon yet return; case 'pass': if (!decision.priority || decision.priority <= 101) return; if (decision.pokemon) { decision.pokemon.switchFlag = false; } break; case 'switch': if (decision.pokemon) { decision.pokemon.beingCalledBack = true; var lastMove = this.getMove(decision.pokemon.lastMove); if (lastMove.selfSwitch !== 'copyvolatile') { this.runEvent('BeforeSwitchOut', decision.pokemon); } if (!this.runEvent('SwitchOut', decision.pokemon)) { // Warning: DO NOT interrupt a switch-out // if you just want to trap a pokemon. // To trap a pokemon and prevent it from switching out, // (e.g. Mean Look, Magnet Pull) use the 'trapped' flag // instead. // Note: Nothing in BW or earlier interrupts // a switch-out. break; } this.singleEvent('End', this.getAbility(decision.pokemon.ability), decision.pokemon.abilityData, decision.pokemon); } if (decision.pokemon && !decision.pokemon.hp && !decision.pokemon.fainted) { // a pokemon fainted from Pursuit before it could switch if (this.gen <= 4) { // in gen 2-4, the switch still happens decision.priority = -101; this.queue.unshift(decision); this.debug('Pursuit target fainted'); break; } // in gen 5+, the switch is cancelled this.debug('A Pokemon can\'t switch between when it runs out of HP and when it faints'); break; } if (decision.target.isActive) { this.debug('Switch target is already active'); break; } this.switchIn(decision.target, decision.pokemon.position); break; case 'runSwitch': this.runEvent('SwitchIn', decision.pokemon); if (this.gen === 1 && !decision.pokemon.side.faintedThisTurn) this.runEvent('AfterSwitchInSelf', decision.pokemon); if (!decision.pokemon.hp) break; decision.pokemon.isStarted = true; if (!decision.pokemon.fainted) { this.singleEvent('Start', decision.pokemon.getAbility(), decision.pokemon.abilityData, decision.pokemon); this.singleEvent('Start', decision.pokemon.getItem(), decision.pokemon.itemData, decision.pokemon); } break; case 'shift': if (!decision.pokemon.isActive) return false; if (decision.pokemon.fainted) return false; this.swapPosition(decision.pokemon, 1); break; case 'beforeTurn': this.eachEvent('BeforeTurn'); break; case 'residual': this.add(''); this.clearActiveMove(true); this.residualEvent('Residual'); break; } // phazing (Roar, etc) var self = this; function checkForceSwitchFlag(a) { if (!a) return false; if (a.hp && a.forceSwitchFlag) { self.dragIn(a.side, a.position); } delete a.forceSwitchFlag; } this.p1.active.forEach(checkForceSwitchFlag); this.p2.active.forEach(checkForceSwitchFlag); this.clearActiveMove(); // fainting this.faintMessages(); if (this.ended) return true; // switching (fainted pokemon, U-turn, Baton Pass, etc) if (!this.queue.length || (this.gen <= 3 && this.queue[0].choice in {move:1, residual:1})) { // in gen 3 or earlier, switching in fainted pokemon is done after // every move, rather than only at the end of the turn. this.checkFainted(); } else if (decision.choice === 'pass') { this.eachEvent('Update'); return false; } function hasSwitchFlag(a) { return a ? a.switchFlag : false; } function removeSwitchFlag(a) { if (a) a.switchFlag = false; } var p1switch = this.p1.active.any(hasSwitchFlag); var p2switch = this.p2.active.any(hasSwitchFlag); if (p1switch && !this.canSwitch(this.p1)) { this.p1.active.forEach(removeSwitchFlag); p1switch = false; } if (p2switch && !this.canSwitch(this.p2)) { this.p2.active.forEach(removeSwitchFlag); p2switch = false; } if (p1switch || p2switch) { if (this.gen >= 5) { this.eachEvent('Update'); } this.makeRequest('switch'); return true; } this.eachEvent('Update'); return false; }; Battle.prototype.go = function () { this.add(''); if (this.currentRequest) { this.currentRequest = ''; this.currentRequestDetails = ''; } if (!this.midTurn) { this.queue.push({choice:'residual', priority: -100}); this.queue.push({choice:'beforeTurn', priority: 100}); this.midTurn = true; } this.addQueue(null); while (this.queue.length) { var decision = this.queue.shift(); this.runDecision(decision); if (this.currentRequest) { return; } if (this.ended) return; } this.nextTurn(); this.midTurn = false; this.queue = []; }; /** * Changes a pokemon's decision. * * The un-modded game should not use this function for anything, * since it rerolls speed ties (which messes up RNG state). * * You probably want the OverrideDecision event (which doesn't * change priority order). */ Battle.prototype.changeDecision = function (pokemon, decision) { this.cancelDecision(pokemon); if (!decision.pokemon) decision.pokemon = pokemon; this.addQueue(decision); }; /** * Takes a choice string passed from the client. Starts the next * turn if all required choices have been made. */ Battle.prototype.choose = function (sideid, choice, rqid) { var side = null; if (sideid === 'p1' || sideid === 'p2') side = this[sideid]; // This condition should be impossible because the sideid comes // from our forked process and if the player id were invalid, we would // not have even got to this function. if (!side) return; // wtf // This condition can occur if the client sends a decision at the // wrong time. if (!side.currentRequest) return; // Make sure the decision is for the right request. if ((rqid !== undefined) && (parseInt(rqid, 10) !== this.rqid)) { return; } // It should be impossible for choice not to be a string. Choice comes // from splitting the string sent by our forked process, not from the // client. However, just in case, we maintain this check for now. if (typeof choice === 'string') choice = choice.split(','); if (side.decision && side.decision.finalDecision) { this.debug("Can't override decision: the last pokemon could have been trapped or disabled"); return; } side.decision = this.parseChoice(choice, side); if (this.p1.decision && this.p2.decision) { this.commitDecisions(); } }; Battle.prototype.commitDecisions = function () { if (this.p1.decision !== true) { this.addQueue(this.p1.resolveDecision(), true, this.p1); } if (this.p2.decision !== true) { this.addQueue(this.p2.resolveDecision(), true, this.p2); } this.currentRequest = ''; this.currentRequestDetails = ''; this.p1.currentRequest = ''; this.p2.currentRequest = ''; this.p1.decision = true; this.p2.decision = true; this.go(); }; Battle.prototype.undoChoice = function (sideid) { var side = null; if (sideid === 'p1' || sideid === 'p2') side = this[sideid]; // The following condition can never occur for the reasons given in // the choose() function above. if (!side) return; // wtf // This condition can occur. if (!side.currentRequest) return; if (side.decision && side.decision.finalDecision) { this.debug("Can't cancel decision: the last pokemon could have been trapped or disabled"); return; } side.decision = false; }; /** * Parses a choice string passed from a client into a decision object * usable by PS's engine. * * Choice validation is also done here. */ Battle.prototype.parseChoice = function (choices, side) { var prevSwitches = {}; if (!side.currentRequest) return true; if (typeof choices === 'string') choices = choices.split(','); var decisions = []; var len = choices.length; if (side.currentRequest !== 'teampreview') len = side.active.length; var isDefault; var choosableTargets = {normal:1, any:1, adjacentAlly:1, adjacentAllyOrSelf:1, adjacentFoe:1}; var freeSwitchCount = {'switch':0, 'pass':0}; if (side.currentRequest === 'switch') { var canSwitch = side.active.filter(function (mon) {return mon && mon.switchFlag;}).length; freeSwitchCount['switch'] = Math.min(canSwitch, side.pokemon.slice(side.active.length).filter(function (mon) {return !mon.fainted;}).length); freeSwitchCount['pass'] = canSwitch - freeSwitchCount['switch']; } for (var i = 0; i < len; i++) { var choice = (choices[i] || '').trim(); var data = ''; var firstSpaceIndex = choice.indexOf(' '); if (firstSpaceIndex >= 0) { data = choice.substr(firstSpaceIndex + 1).trim(); choice = choice.substr(0, firstSpaceIndex).trim(); } var pokemon = side.pokemon[i]; switch (side.currentRequest) { case 'teampreview': if (choice !== 'team' || i > 0) return false; break; case 'move': if (i >= side.active.length) return false; if (!pokemon || pokemon.fainted) { decisions.push({ choice: 'pass' }); continue; } var lockedMove = pokemon.getLockedMove(); if (lockedMove) { decisions.push({ choice: 'move', pokemon: pokemon, targetLoc: this.runEvent('LockMoveTarget', pokemon) || 0, move: lockedMove }); continue; } if (isDefault || choice === 'default') { isDefault = true; var moves = pokemon.getMoves(); var moveid = 'struggle'; for (var j = 0; j < moves.length; j++) { if (moves[j].disabled) continue; moveid = moves[j].id; break; } decisions.push({ choice: 'move', pokemon: pokemon, targetLoc: 0, move: moveid }); continue; } if (choice !== 'move' && choice !== 'switch' && choice !== 'shift') { if (i === 0) return false; // fallback choice = 'move'; data = '1'; } break; case 'switch': if (i >= side.active.length) return false; if (!side.active[i] || !side.active[i].switchFlag) { if (choice !== 'pass') choices.splice(i, 0, 'pass'); decisions.push({ choice: 'pass', pokemon: side.active[i], priority: 102 }); continue; } if (choice !== 'switch' && choice !== 'pass') return false; freeSwitchCount[choice]--; break; default: return false; } switch (choice) { case 'team': var pokemonLength = side.pokemon.length; if (!data || data.length > pokemonLength) return false; var dataArr = [0, 1, 2, 3, 4, 5].slice(0, pokemonLength); var slotMap = dataArr.slice(); // Inverse of `dataArr` (slotMap[dataArr[x]] === x) var tempSlot; for (var j = 0; j < data.length; j++) { var slot = parseInt(data.charAt(j), 10) - 1; if (slotMap[slot] < j) return false; if (isNaN(slot) || slot < 0 || slot >= pokemonLength) return false; // Keep track of team order so far tempSlot = dataArr[j]; dataArr[j] = slot; dataArr[slotMap[slot]] = tempSlot; // Update its inverse slotMap[tempSlot] = slotMap[slot]; slotMap[slot] = j; } decisions.push({ choice: 'team', side: side, team: dataArr }); break; case 'switch': if (i > side.active.length || i > side.pokemon.length) continue; data = parseInt(data, 10) - 1; if (data < 0) data = 0; if (data > side.pokemon.length - 1) data = side.pokemon.length - 1; if (!side.pokemon[data]) { this.debug("Can't switch: You can't switch to a pokemon that doesn't exist"); return false; } if (data === i) { this.debug("Can't switch: You can't switch to yourself"); return false; } if (data < side.active.length) { this.debug("Can't switch: You can't switch to an active pokemon"); return false; } if (side.pokemon[data].fainted) { this.debug("Can't switch: You can't switch to a fainted pokemon"); return false; } if (prevSwitches[data]) { this.debug("Can't switch: You can't switch to pokemon already queued to be switched"); return false; } prevSwitches[data] = true; if (side.currentRequest === 'move') { if (side.pokemon[i].trapped) { //this.debug("Can't switch: The active pokemon is trapped"); side.emitCallback('trapped', i); return false; } else if (side.pokemon[i].maybeTrapped) { var finalDecision = true; decisions.finalDecision = decisions.finalDecision || side.pokemon[i].isLastActive(); } } decisions.push({ choice: 'switch', priority: (side.currentRequest === 'switch' ? 101 : undefined), pokemon: side.pokemon[i], target: side.pokemon[data] }); break; case 'shift': if (i > side.active.length || i > side.pokemon.length) continue; if (this.gameType !== 'triples') { this.debug("Can't shift: You can't shift a pokemon to the center except in a triple battle"); return false; } if (i === 1) { this.debug("Can't shift: You can't shift a pokemon to its own position"); return false; } decisions.push({ choice: 'shift', pokemon: side.pokemon[i] }); break; case 'move': var moveid = ''; var targetLoc = 0; var pokemon = side.pokemon[i]; if (data.substr(-2) === ' 1') targetLoc = 1; if (data.substr(-2) === ' 2') targetLoc = 2; if (data.substr(-2) === ' 3') targetLoc = 3; if (data.substr(-3) === ' -1') targetLoc = -1; if (data.substr(-3) === ' -2') targetLoc = -2; if (data.substr(-3) === ' -3') targetLoc = -3; if (targetLoc) data = data.substr(0, data.lastIndexOf(' ')); if (data.substr(-5) === ' mega') { decisions.push({ choice: 'megaEvo', pokemon: pokemon }); data = data.substr(0, data.length - 5); } /** * Parse the move identifier (name or index), according to the request sent to the client. * If the move is not found, the decision is invalid without requiring further inspection. */ var requestMoves = pokemon.getRequestData().moves; if (data.search(/^[0-9]+$/) >= 0) { // parse a one-based move index var moveIndex = parseInt(data, 10) - 1; if (!requestMoves[moveIndex]) { this.debug("Can't use an unexpected move"); return false; } moveid = requestMoves[moveIndex].id; if (!targetLoc && side.active.length > 1 && requestMoves[moveIndex].target in choosableTargets) { this.debug("Can't use the move without a target"); return false; } } else { // parse a move name moveid = toId(data); if (moveid.substr(0, 11) === 'hiddenpower') { moveid = 'hiddenpower'; } var isValidMove = false; for (var j = 0; j < requestMoves.length; j++) { if (requestMoves[j].id !== moveid) continue; if (!targetLoc && side.active.length > 1 && requestMoves[j].target in choosableTargets) { this.debug("Can't use the move without a target"); return false; } isValidMove = true; break; } if (!isValidMove) { this.debug("Can't use an unexpected move"); return false; } } /** * Check whether the chosen move is really valid, accounting for effects active in battle, * which could be unknown for the client. */ var moves = pokemon.getMoves(); if (!moves.length) { // Override decision and use Struggle if there are no enabled moves with PP if (this.gen <= 4) side.send('-activate', pokemon, 'move: Struggle'); moveid = 'struggle'; } else { // At least a move is valid. Check if the chosen one is. // This may include Struggle in Hackmons. var isEnabled = false; for (var j = 0; j < moves.length; j++) { if (moves[j].id !== moveid) continue; if (!moves[j].disabled) { isEnabled = true; break; } } if (!isEnabled) { // request a different choice var sourceEffect = pokemon.disabledMoves[moveid] && pokemon.disabledMoves[moveid].sourceEffect; side.emitCallback('cant', pokemon, sourceEffect ? sourceEffect.fullname : '', moveid); return false; } // the chosen move is valid } if (pokemon.maybeDisabled) { decisions.finalDecision = decisions.finalDecision || pokemon.isLastActive(); } decisions.push({ choice: 'move', pokemon: pokemon, targetLoc: targetLoc, move: moveid }); break; case 'pass': if (i > side.active.length || i > side.pokemon.length) continue; if (side.currentRequest !== 'switch') { this.debug("Can't pass the turn"); return false; } decisions.push({ choice: 'pass', priority: 102, pokemon: side.active[i] }); } } if (freeSwitchCount['switch'] !== 0 || freeSwitchCount['pass'] !== 0) return false; if (!this.supportCancel || isDefault) decisions.finalDecision = true; return decisions; }; Battle.prototype.add = function () { var parts = Array.prototype.slice.call(arguments); var functions = parts.map(function (part) { return typeof part === 'function'; }); if (functions.indexOf(true) < 0) { this.log.push('|' + parts.join('|')); } else { this.log.push('|split'); var sides = [null, this.sides[0], this.sides[1], true]; for (var i = 0; i < sides.length; ++i) { var line = ''; for (var j = 0; j < parts.length; ++j) { line += '|'; if (functions[j]) { line += parts[j](sides[i]); } else { line += parts[j]; } } this.log.push(line); } } }; Battle.prototype.addMove = function () { this.lastMoveLine = this.log.length; this.log.push('|' + Array.prototype.slice.call(arguments).join('|')); }; Battle.prototype.attrLastMove = function () { this.log[this.lastMoveLine] += '|' + Array.prototype.slice.call(arguments).join('|'); }; Battle.prototype.debug = function (activity) { if (this.getFormat().debug) { this.add('debug', activity); } }; Battle.prototype.debugError = function (activity) { this.add('debug', activity); }; // players Battle.prototype.join = function (slot, name, avatar, team) { if (this.p1 && this.p1.isActive && this.p2 && this.p2.isActive) return false; if ((this.p1 && this.p1.isActive && this.p1.name === name) || (this.p2 && this.p2.isActive && this.p2.name === name)) return false; if (this.p1 && this.p1.isActive || slot === 'p2') { if (this.started) { this.p2.name = name; } else { //console.log("NEW SIDE: " + name); this.p2 = new BattleSide(name, this, 1, team); this.sides[1] = this.p2; } if (avatar) this.p2.avatar = avatar; this.p2.isActive = true; this.add('player', 'p2', this.p2.name, avatar); } else { if (this.started) { this.p1.name = name; } else { //console.log("NEW SIDE: " + name); this.p1 = new BattleSide(name, this, 0, team); this.sides[0] = this.p1; } if (avatar) this.p1.avatar = avatar; this.p1.isActive = true; this.add('player', 'p1', this.p1.name, avatar); } this.start(); return true; }; Battle.prototype.rename = function (slot, name, avatar) { if (slot === 'p1' || slot === 'p2') { var side = this[slot]; side.name = name; if (avatar) side.avatar = avatar; this.add('player', slot, name, side.avatar); } }; Battle.prototype.leave = function (slot) { if (slot === 'p1' || slot === 'p2') { var side = this[slot]; if (!side) { console.log('**** ' + slot + ' tried to leave before it was possible in ' + this.id); require('./crashlogger.js')({stack: '**** ' + slot + ' tried to leave before it was possible in ' + this.id}, 'A simulator process'); return; } side.emitRequest(null); side.isActive = false; this.add('player', slot); this.active = false; } return true; }; // IPC // Messages sent by this function are received and handled in // Battle.prototype.receive in simulator.js (in another process). Battle.prototype.send = function (type, data) { if (Array.isArray(data)) data = data.join("\n"); process.send(this.id + "\n" + type + "\n" + data); }; // This function is called by this process's 'message' event. Battle.prototype.receive = function (data, more) { this.messageLog.push(data.join(' ')); var logPos = this.log.length; var alreadyEnded = this.ended; switch (data[1]) { case 'join': var team = null; try { if (more) team = Tools.fastUnpackTeam(more); } catch (e) { console.log('TEAM PARSE ERROR: ' + more); team = null; } this.join(data[2], data[3], data[4], team); break; case 'rename': this.rename(data[2], data[3], data[4]); break; case 'leave': this.leave(data[2]); break; case 'chat': this.add('chat', data[2], more); break; case 'win': case 'tie': this.win(data[2]); break; case 'choose': this.choose(data[2], data[3], data[4]); break; case 'undo': this.undoChoice(data[2]); break; case 'eval': var battle = this; var p1 = this.p1; var p2 = this.p2; var p1active = p1 ? p1.active[0] : null; var p2active = p2 ? p2.active[0] : null; var target = data.slice(2).join('|').replace(/\f/g, '\n'); this.add('', '>>> ' + target); try { this.add('', '<<< ' + eval(target)); } catch (e) { this.add('', '<<< error: ' + e.message); } break; } this.sendUpdates(logPos, alreadyEnded); }; Battle.prototype.sendUpdates = function (logPos, alreadyEnded) { if (this.p1 && this.p2) { var inactiveSide = -1; if (!this.p1.isActive && this.p2.isActive) { inactiveSide = 0; } else if (this.p1.isActive && !this.p2.isActive) { inactiveSide = 1; } else if (!this.p1.decision && this.p2.decision) { inactiveSide = 0; } else if (this.p1.decision && !this.p2.decision) { inactiveSide = 1; } if (inactiveSide !== this.inactiveSide) { this.send('inactiveside', inactiveSide); this.inactiveSide = inactiveSide; } } if (this.log.length > logPos) { if (alreadyEnded !== undefined && this.ended && !alreadyEnded) { if (this.rated || Config.logchallenges) { var log = { seed: this.startingSeed, turns: this.turn, p1: this.p1.name, p2: this.p2.name, p1team: this.p1.team, p2team: this.p2.team, log: this.log }; this.send('log', JSON.stringify(log)); } this.send('score', [this.p1.pokemonLeft, this.p2.pokemonLeft]); this.send('winupdate', [this.winner].concat(this.log.slice(logPos))); } else { this.send('update', this.log.slice(logPos)); } } }; Battle.prototype.destroy = function () { // deallocate ourself // deallocate children and get rid of references to them for (var i = 0; i < this.sides.length; i++) { if (this.sides[i]) this.sides[i].destroy(); this.sides[i] = null; } this.p1 = null; this.p2 = null; for (var i = 0; i < this.queue.length; i++) { delete this.queue[i].pokemon; delete this.queue[i].side; this.queue[i] = null; } this.queue = null; // in case the garbage collector really sucks, at least deallocate the log this.log = null; // remove from battle list Battles[this.id] = null; }; return Battle; })(); exports.BattlePokemon = BattlePokemon; exports.BattleSide = BattleSide; exports.Battle = Battle;
exports.Form = Form; var stream = require('readable-stream') , util = require('util') , fs = require('fs') , crypto = require('crypto') , path = require('path') , os = require('os') , StringDecoder = require('string_decoder').StringDecoder , StreamCounter = require('stream-counter') var START = 0 , START_BOUNDARY = 1 , HEADER_FIELD_START = 2 , HEADER_FIELD = 3 , HEADER_VALUE_START = 4 , HEADER_VALUE = 5 , HEADER_VALUE_ALMOST_DONE = 6 , HEADERS_ALMOST_DONE = 7 , PART_DATA_START = 8 , PART_DATA = 9 , PART_END = 10 , CLOSE_BOUNDARY = 11 , END = 12 , LF = 10 , CR = 13 , SPACE = 32 , HYPHEN = 45 , COLON = 58 , A = 97 , Z = 122 var CONTENT_TYPE_RE = /^multipart\/(?:form-data|related)(?:;|$)/i; var CONTENT_TYPE_PARAM_RE = /;\s*(\S+)=(?:"([^"]+)"|([^;]+))/gi; var FILE_EXT_RE = /(\.[_\-a-zA-Z0-9]{0,16}).*/; var LAST_BOUNDARY_SUFFIX_LEN = 4; // --\r\n util.inherits(Form, stream.Writable); function Form(options) { var self = this; stream.Writable.call(self); options = options || {}; self.error = null; self.finished = false; self.autoFields = !!options.autoFields; self.autoFiles = !!options.autoFiles; self.maxFields = options.maxFields || 1000; self.maxFieldsSize = options.maxFieldsSize || 2 * 1024 * 1024; self.maxFilesSize = options.maxFilesSize || Infinity; self.uploadDir = options.uploadDir || os.tmpDir(); self.encoding = options.encoding || 'utf8'; self.hash = options.hash || false; self.bytesReceived = 0; self.bytesExpected = null; self.openedFiles = []; self.totalFieldSize = 0; self.totalFieldCount = 0; self.totalFileSize = 0; self.flushing = 0; self.backpressure = false; self.writeCbs = []; if (options.boundary) setUpParser(self, options.boundary); self.on('newListener', function(eventName) { if (eventName === 'file') { self.autoFiles = true; } else if (eventName === 'field') { self.autoFields = true; } }); } Form.prototype.parse = function(req, cb) { var self = this; // if the user supplies a callback, this implies autoFields and autoFiles if (cb) { self.autoFields = true; self.autoFiles = true; } self.handleError = handleError; self.bytesExpected = getBytesExpected(req.headers); req.on('error', handleError); req.on('aborted', onReqAborted); var contentType = req.headers['content-type']; if (!contentType) { handleError(new Error('missing content-type header')); return; } var m = CONTENT_TYPE_RE.exec(contentType); if (!m) { handleError(new Error('unrecognized content-type: ' + contentType)); return; } var boundary; CONTENT_TYPE_PARAM_RE.lastIndex = m.index + m[0].length - 1; while ((m = CONTENT_TYPE_PARAM_RE.exec(contentType))) { if (m[1].toLowerCase() !== 'boundary') continue; boundary = m[2] || m[3]; break; } if (!boundary) { handleError(new Error('content-type missing boundary: ' + require('util').inspect(m))); return; } setUpParser(self, boundary); req.pipe(self); if (cb) { var fields = {}; var files = {}; self.on('error', function(err) { cb(err); }); self.on('field', function(name, value) { var fieldsArray = fields[name] || (fields[name] = []); fieldsArray.push(value); }); self.on('file', function(name, file) { var filesArray = files[name] || (files[name] = []); filesArray.push(file); }); self.on('close', function() { cb(null, fields, files); }); } function onReqAborted() { self.emit('aborted'); handleError(new Error("Request aborted")); } function handleError(err) { var first = !self.error; if (first) { self.error = err; req.removeListener('aborted', onReqAborted); // welp. 0.8 doesn't support unpipe, too bad so sad. // let's drop support for 0.8 soon. if (req.unpipe) { req.unpipe(self); } } self.openedFiles.forEach(function(file) { destroyFile(self, file); }); self.openedFiles = []; if (first) { self.emit('error', err); } } }; Form.prototype._write = function(buffer, encoding, cb) { var self = this , i = 0 , len = buffer.length , prevIndex = self.index , index = self.index , state = self.state , lookbehind = self.lookbehind , boundary = self.boundary , boundaryChars = self.boundaryChars , boundaryLength = self.boundary.length , boundaryEnd = boundaryLength - 1 , bufferLength = buffer.length , c , cl for (i = 0; i < len; i++) { c = buffer[i]; switch (state) { case START: index = 0; state = START_BOUNDARY; /* falls through */ case START_BOUNDARY: if (index === boundaryLength - 2 && c === HYPHEN) { index = 1; state = CLOSE_BOUNDARY; break; } else if (index === boundaryLength - 2) { if (c !== CR) return self.handleError(new Error("Expected CR Received " + c)); index++; break; } else if (index === boundaryLength - 1) { if (c !== LF) return self.handleError(new Error("Expected LF Received " + c)); index = 0; self.onParsePartBegin(); state = HEADER_FIELD_START; break; } if (c !== boundary[index+2]) index = -2; if (c === boundary[index+2]) index++; break; case HEADER_FIELD_START: state = HEADER_FIELD; self.headerFieldMark = i; index = 0; /* falls through */ case HEADER_FIELD: if (c === CR) { self.headerFieldMark = null; state = HEADERS_ALMOST_DONE; break; } index++; if (c === HYPHEN) break; if (c === COLON) { if (index === 1) { // empty header field self.handleError(new Error("Empty header field")); return; } self.onParseHeaderField(buffer.slice(self.headerFieldMark, i)); self.headerFieldMark = null; state = HEADER_VALUE_START; break; } cl = lower(c); if (cl < A || cl > Z) { self.handleError(new Error("Expected alphabetic character, received " + c)); return; } break; case HEADER_VALUE_START: if (c === SPACE) break; self.headerValueMark = i; state = HEADER_VALUE; /* falls through */ case HEADER_VALUE: if (c === CR) { self.onParseHeaderValue(buffer.slice(self.headerValueMark, i)); self.headerValueMark = null; self.onParseHeaderEnd(); state = HEADER_VALUE_ALMOST_DONE; } break; case HEADER_VALUE_ALMOST_DONE: if (c !== LF) return self.handleError(new Error("Expected LF Received " + c)); state = HEADER_FIELD_START; break; case HEADERS_ALMOST_DONE: if (c !== LF) return self.handleError(new Error("Expected LF Received " + c)); var err = self.onParseHeadersEnd(i + 1); if (err) return self.handleError(err); state = PART_DATA_START; break; case PART_DATA_START: state = PART_DATA; self.partDataMark = i; /* falls through */ case PART_DATA: prevIndex = index; if (index === 0) { // boyer-moore derrived algorithm to safely skip non-boundary data i += boundaryEnd; while (i < bufferLength && !(buffer[i] in boundaryChars)) { i += boundaryLength; } i -= boundaryEnd; c = buffer[i]; } if (index < boundaryLength) { if (boundary[index] === c) { if (index === 0) { self.onParsePartData(buffer.slice(self.partDataMark, i)); self.partDataMark = null; } index++; } else { index = 0; } } else if (index === boundaryLength) { index++; if (c === CR) { // CR = part boundary self.partBoundaryFlag = true; } else if (c === HYPHEN) { index = 1; state = CLOSE_BOUNDARY; break; } else { index = 0; } } else if (index - 1 === boundaryLength) { if (self.partBoundaryFlag) { index = 0; if (c === LF) { self.partBoundaryFlag = false; self.onParsePartEnd(); self.onParsePartBegin(); state = HEADER_FIELD_START; break; } } else { index = 0; } } if (index > 0) { // when matching a possible boundary, keep a lookbehind reference // in case it turns out to be a false lead lookbehind[index-1] = c; } else if (prevIndex > 0) { // if our boundary turned out to be rubbish, the captured lookbehind // belongs to partData self.onParsePartData(lookbehind.slice(0, prevIndex)); prevIndex = 0; self.partDataMark = i; // reconsider the current character even so it interrupted the sequence // it could be the beginning of a new sequence i--; } break; case CLOSE_BOUNDARY: if (c !== HYPHEN) return self.handleError(new Error("Expected HYPHEN Received " + c)); if (index === 1) { self.onParsePartEnd(); self.end(); state = END; } else if (index > 1) { return self.handleError(new Error("Parser has invalid state.")); } index++; break; case END: break; default: self.handleError(new Error("Parser has invalid state.")); return; } } if (self.headerFieldMark != null) { self.onParseHeaderField(buffer.slice(self.headerFieldMark)); self.headerFieldMark = 0; } if (self.headerValueMark != null) { self.onParseHeaderValue(buffer.slice(self.headerValueMark)); self.headerValueMark = 0; } if (self.partDataMark != null) { self.onParsePartData(buffer.slice(self.partDataMark)); self.partDataMark = 0; } self.index = index; self.state = state; self.bytesReceived += buffer.length; self.emit('progress', self.bytesReceived, self.bytesExpected); if (self.backpressure) { self.writeCbs.push(cb); } else { cb(); } }; Form.prototype.onParsePartBegin = function() { clearPartVars(this); } Form.prototype.onParseHeaderField = function(b) { this.headerField += this.headerFieldDecoder.write(b); } Form.prototype.onParseHeaderValue = function(b) { this.headerValue += this.headerValueDecoder.write(b); } Form.prototype.onParseHeaderEnd = function() { this.headerField = this.headerField.toLowerCase(); this.partHeaders[this.headerField] = this.headerValue; var m; if (this.headerField === 'content-disposition') { if (m = this.headerValue.match(/\bname="([^"]+)"/i)) { this.partName = m[1]; } this.partFilename = parseFilename(this.headerValue); } else if (this.headerField === 'content-transfer-encoding') { this.partTransferEncoding = this.headerValue.toLowerCase(); } this.headerFieldDecoder = new StringDecoder(this.encoding); this.headerField = ''; this.headerValueDecoder = new StringDecoder(this.encoding); this.headerValue = ''; } Form.prototype.onParsePartData = function(b) { if (this.partTransferEncoding === 'base64') { this.backpressure = ! this.destStream.write(b.toString('ascii'), 'base64'); } else { this.backpressure = ! this.destStream.write(b); } } Form.prototype.onParsePartEnd = function() { if (this.destStream) { flushWriteCbs(this); var s = this.destStream; process.nextTick(function() { s.end(); }); } clearPartVars(this); } Form.prototype.onParseHeadersEnd = function(offset) { var self = this; switch(self.partTransferEncoding){ case 'binary': case '7bit': case '8bit': self.partTransferEncoding = 'binary'; break; case 'base64': break; default: return new Error("unknown transfer-encoding: " + self.partTransferEncoding); } self.totalFieldCount += 1; if (self.totalFieldCount >= self.maxFields) { return new Error("maxFields " + self.maxFields + " exceeded."); } self.destStream = new stream.PassThrough(); self.destStream.on('drain', function() { flushWriteCbs(self); }); self.destStream.headers = self.partHeaders; self.destStream.name = self.partName; self.destStream.filename = self.partFilename; self.destStream.byteOffset = self.bytesReceived + offset; var partContentLength = self.destStream.headers['content-length']; self.destStream.byteCount = partContentLength ? parseInt(partContentLength, 10) : self.bytesExpected ? (self.bytesExpected - self.destStream.byteOffset - self.boundary.length - LAST_BOUNDARY_SUFFIX_LEN) : undefined; self.emit('part', self.destStream); if (self.destStream.filename == null && self.autoFields) { handleField(self, self.destStream); } else if (self.destStream.filename != null && self.autoFiles) { handleFile(self, self.destStream); } } function flushWriteCbs(self) { self.writeCbs.forEach(function(cb) { process.nextTick(cb); }); self.writeCbs = []; self.backpressure = false; } function getBytesExpected(headers) { var contentLength = headers['content-length']; if (contentLength) { return parseInt(contentLength, 10); } else if (headers['transfer-encoding'] == null) { return 0; } else { return null; } } function beginFlush(self) { self.flushing += 1; } function endFlush(self) { self.flushing -= 1; maybeClose(self); } function maybeClose(self) { if (!self.flushing && self.finished && !self.error) { process.nextTick(function() { self.emit('close'); }); } } function destroyFile(self, file) { if (!file.ws) return; file.ws.removeAllListeners('close'); file.ws.on('close', function() { fs.unlink(file.path, function(err) { if (err && !self.error) self.handleError(err); }); }); file.ws.destroy(); } function handleFile(self, fileStream) { if (self.error) return; beginFlush(self); var file = { fieldName: fileStream.name, originalFilename: fileStream.filename, path: uploadPath(self.uploadDir, fileStream.filename), headers: fileStream.headers, }; file.ws = fs.createWriteStream(file.path); self.openedFiles.push(file); fileStream.pipe(file.ws); var counter = new StreamCounter(); var seenBytes = 0; fileStream.pipe(counter); var hashWorkaroundStream , hash = null; if (self.hash) { // workaround stream because https://github.com/joyent/node/issues/5216 hashWorkaroundStream = stream.Writable(); hash = crypto.createHash(self.hash); hashWorkaroundStream._write = function(buffer, encoding, callback) { hash.update(buffer); callback(); }; fileStream.pipe(hashWorkaroundStream); } counter.on('progress', function() { var deltaBytes = counter.bytes - seenBytes; seenBytes += deltaBytes; self.totalFileSize += deltaBytes; if (self.totalFileSize > self.maxFilesSize) { if (hashWorkaroundStream) fileStream.unpipe(hashWorkaroundStream); fileStream.unpipe(counter); fileStream.unpipe(file.ws); self.handleError(new Error("maxFilesSize " + self.maxFilesSize + " exceeded")); } }); file.ws.on('error', function(err) { if (!self.error) self.handleError(err); }); file.ws.on('close', function() { if (hash) file.hash = hash.digest('hex'); file.size = counter.bytes; self.emit('file', fileStream.name, file); endFlush(self); }); } function handleField(self, fieldStream) { var value = ''; var decoder = new StringDecoder(self.encoding); beginFlush(self); fieldStream.on('readable', function() { var buffer = fieldStream.read(); if (!buffer) return; self.totalFieldSize += buffer.length; if (self.totalFieldSize > self.maxFieldsSize) { self.handleError(new Error("maxFieldsSize " + self.maxFieldsSize + " exceeded")); return; } value += decoder.write(buffer); }); fieldStream.on('end', function() { self.emit('field', fieldStream.name, value); endFlush(self); }); } function clearPartVars(self) { self.partHeaders = {}; self.partName = null; self.partFilename = null; self.partTransferEncoding = 'binary'; self.destStream = null; self.headerFieldDecoder = new StringDecoder(self.encoding); self.headerField = ""; self.headerValueDecoder = new StringDecoder(self.encoding); self.headerValue = ""; } function setUpParser(self, boundary) { self.boundary = new Buffer(boundary.length + 4); self.boundary.write('\r\n--', 0, boundary.length + 4, 'ascii'); self.boundary.write(boundary, 4, boundary.length, 'ascii'); self.lookbehind = new Buffer(self.boundary.length + 8); self.state = START; self.boundaryChars = {}; for (var i = 0; i < self.boundary.length; i++) { self.boundaryChars[self.boundary[i]] = true; } self.index = null; self.partBoundaryFlag = false; self.on('finish', function() { if ((self.state === HEADER_FIELD_START && self.index === 0) || (self.state === PART_DATA && self.index === self.boundary.length)) { self.onParsePartEnd(); } else if (self.state !== END) { self.handleError(new Error('stream ended unexpectedly')); } self.finished = true; maybeClose(self); }); } function uploadPath(baseDir, filename) { var ext = path.extname(filename).replace(FILE_EXT_RE, '$1'); var name = process.pid + '-' + (Math.random() * 0x100000000 + 1).toString(36) + ext; return path.join(baseDir, name); } function parseFilename(headerValue) { var m = headerValue.match(/\bfilename="(.*?)"($|; )/i); if (!m) { m = headerValue.match(/\bfilename\*=utf-8\'\'(.*?)($|; )/i); if (m) { m[1] = decodeURI(m[1]); } else { return; } } var filename = m[1].substr(m[1].lastIndexOf('\\') + 1); filename = filename.replace(/%22/g, '"'); filename = filename.replace(/&#([\d]{4});/g, function(m, code) { return String.fromCharCode(code); }); return filename; } function lower(c) { return c | 0x20; }
/** * Common JS functions for form settings and form editor pages. */ jQuery(document).ready(function($){ gaddon.init(); $(document).on('change', '.gfield_rule_value_dropdown', function(){ SetRuleValueDropDown($(this)); }); // init merge tag auto complete if(typeof form != 'undefined') window.gfMergeTags = new gfMergeTagsObj(form); $(document).ready(function(){ $(".gform_currency").bind("change", function(){ FormatCurrency(this); }).each(function(){ FormatCurrency(this); }); }); /** * Dismiss GF dimissible messages. */ $(document).on( "click", ".notice-dismiss", function(){ var $div = $(this).closest('div.notice'); if ( $div.length > 0 ) { var messageKey = $div.data('gf_dismissible_key'); var nonce = $div.data('gf_dismissible_nonce'); if ( messageKey ) { jQuery.ajax({ url: ajaxurl, data: { action: 'gf_dismiss_message', message_key: messageKey, nonce: nonce } }) } } }); }); function FormatCurrency(element){ if(gf_vars.gf_currency_config){ var currency = new Currency(gf_vars.gf_currency_config); var price = currency.toMoney(jQuery(element).val()); jQuery(element).val(price); } } function ToggleConditionalLogic(isInit, objectType){ var speed = isInit ? "" : "slow"; if(jQuery('#' + objectType + '_conditional_logic').is(":checked")){ var obj = GetConditionalObject(objectType); CreateConditionalLogic(objectType, obj); //Initializing object so it has the default options set SetConditionalProperty(objectType, "actionType", jQuery("#" + objectType + "_action_type").val()); SetConditionalProperty(objectType, "logicType", jQuery("#" + objectType + "_logic_type").val()); SetRule(objectType, 0); jQuery('#' + objectType + '_conditional_logic_container').show(speed); } else{ jQuery('#' + objectType + '_conditional_logic_container').hide(speed); } } function GetConditionalObject(objectType){ var object = false; switch(objectType){ case "page": case "field": object = GetSelectedField(); break; case "next_button" : var field = GetSelectedField(); object = field["nextButton"]; break; case "confirmation": object = confirmation; break; case "notification": object = current_notification; break; default: object = typeof form != 'undefined' ? form.button : false; break; } object = gform.applyFilters( 'gform_conditional_object', object, objectType ) return object; } function CreateConditionalLogic(objectType, obj){ if(!obj.conditionalLogic) obj.conditionalLogic = new ConditionalLogic(); var hideSelected = obj.conditionalLogic.actionType == "hide" ? "selected='selected'" :""; var showSelected = obj.conditionalLogic.actionType == "show" ? "selected='selected'" :""; var allSelected = obj.conditionalLogic.logicType == "all" ? "selected='selected'" :""; var anySelected = obj.conditionalLogic.logicType == "any" ? "selected='selected'" :""; var objText; if (obj['type'] == "section") objText = gf_vars.thisSectionIf; else if(objectType == "field") objText = gf_vars.thisFieldIf; else if(objectType == "page") objText = gf_vars.thisPage; else if(objectType == "confirmation") objText = gf_vars.thisConfirmation; else if(objectType == "notification") objText = gf_vars.thisNotification; else objText = gf_vars.thisFormButton; var descPieces = {}; descPieces.actionType = "<select id='" + objectType + "_action_type' onchange='SetConditionalProperty(\"" + objectType + "\", \"actionType\", jQuery(this).val());'><option value='show' " + showSelected + ">" + gf_vars.show + "</option><option value='hide' " + hideSelected + ">" + gf_vars.hide + "</option></select>"; descPieces.objectDescription = objText; descPieces.logicType = "<select id='" + objectType + "_logic_type' onchange='SetConditionalProperty(\"" + objectType + "\", \"logicType\", jQuery(this).val());'><option value='all' " + allSelected + ">" + gf_vars.all + "</option><option value='any' " + anySelected + ">" + gf_vars.any + "</option></select>"; descPieces.ofTheFollowingMatch = gf_vars.ofTheFollowingMatch; var descPiecesArr = makeArray( descPieces ); var str = descPiecesArr.join(' '); str = gform.applyFilters( 'gform_conditional_logic_description', str, descPieces, objectType, obj ); var i, rule; for(i=0; i < obj.conditionalLogic.rules.length; i++){ rule = obj.conditionalLogic.rules[i]; str += "<div width='100%' class='gf_conditional_logic_rules_container'>"; str += GetRuleFields(objectType, i, rule.fieldId); str += GetRuleOperators(objectType, i, rule.fieldId, rule.operator); str += GetRuleValues(objectType, i, rule.fieldId, rule.value); str += "<a class='add_field_choice' title='add another rule' onclick=\"InsertRule('" + objectType + "', " + (i+1) + ");\" onkeypress=\"InsertRule('" + objectType + "', " + (i+1) + ");\" ><i class='gficon-add'></i></a>"; if(obj.conditionalLogic.rules.length > 1 ) str += "<a class='delete_field_choice' title='remove this rule' onclick=\"DeleteRule('" + objectType + "', " + i + ");\" onkeypress=\"DeleteRule('" + objectType + "', " + i + ");\" ><i class='gficon-subtract'></i></a></li>"; str += "</div>"; } jQuery("#" + objectType + "_conditional_logic_container").html(str); //initializing placeholder script Placeholders.enable(); } function GetRuleOperators( objectType, i, fieldId, selectedOperator ) { var str, supportedOperators, operators, selected; supportedOperators = {"is":"is","isnot":"isNot", ">":"greaterThan", "<":"lessThan", "contains":"contains", "starts_with":"startsWith", "ends_with":"endsWith"}; str = "<select id='" + objectType + "_rule_operator_" + i + "' class='gfield_rule_select' onchange='SetRuleProperty(\"" + objectType + "\", " + i + ", \"operator\", jQuery(this).val());var valueSelector=\"#" + objectType + "_rule_value_" + i + "\"; jQuery(valueSelector).replaceWith(GetRuleValues(\"" + objectType + "\", " + i + ",\"" + fieldId + "\", \"\"));jQuery(valueSelector).change();'>"; operators = IsEntryMeta(fieldId) ? GetOperatorsForMeta(supportedOperators, fieldId) : supportedOperators; operators = gform.applyFilters( 'gform_conditional_logic_operators', operators, objectType, fieldId ); jQuery.each(operators,function(operator, stringKey){ selected = selectedOperator == operator ? "selected='selected'" : ""; str += "<option value='" + operator + "' " + selected + ">" + gf_vars[stringKey] + "</option>" }); str +="</select>"; return str; } function GetOperatorsForMeta(supportedOperators, key){ var operators = {}; if(entry_meta[key] && entry_meta[key].filter && entry_meta[key].filter.operators ){ jQuery.each(supportedOperators,function(operator, stringKey){ if(jQuery.inArray(operator, entry_meta[key].filter.operators) >= 0) operators[operator] = stringKey; }); } else { operators = supportedOperators; } return operators; } function GetRuleFields( objectType, ruleIndex, selectedFieldId ) { var str = "<select id='" + objectType + "_rule_field_" + ruleIndex + "' class='gfield_rule_select' onchange='jQuery(\"#" + objectType + "_rule_operator_" + ruleIndex + "\").replaceWith(GetRuleOperators(\"" + objectType + "\", " + ruleIndex + ", jQuery(this).val()));jQuery(\"#" + objectType + "_rule_value_" + ruleIndex + "\").replaceWith(GetRuleValues(\"" + objectType + "\", " + ruleIndex + ", jQuery(this).val())); SetRule(\"" + objectType + "\", " + ruleIndex + "); '>"; var options = []; for( var i = 0; i < form.fields.length; i++ ) { var field = form.fields[i]; if( IsConditionalLogicField( field ) ) { // @todo: the inputType check will likely go away once we've figured out how we're going to manage inputs moving forward if( field.inputs && jQuery.inArray( GetInputType( field ), [ 'checkbox', 'email' ] ) == -1 ) { for( var j = 0; j < field.inputs.length; j++ ) { var input = field.inputs[j]; if( ! input.isHidden ) { options.push( { label: GetLabel( field, input.id ), value: input.id } ); } } } else { options.push( { label: GetLabel( field ), value: field.id } ); } } } // get entry meta fields and append to existing fields jQuery.merge(options, GetEntryMetaFields( selectedFieldId ) ); options = gform.applyFilters( 'gform_conditional_logic_fields', options, form, selectedFieldId ); str += GetRuleFieldsOptions( options, selectedFieldId ); str += "</select>"; return str; } function GetRuleFieldsOptions( options, selectedFieldId ){ var str = ''; for( var i = 0; i < options.length; i++ ) { var option = options[i]; if ( typeof option.options !== 'undefined' ) { str += '<optgroup label=" ' + option.label + '">'; str += GetRuleFieldsOptions( option.options, selectedFieldId ); str += '</optgroup>'; } else { var selected = option.value == selectedFieldId ? "selected='selected'" : ''; str += "<option value='" + option.value + "' " + selected + ">" + option.label + "</option>"; } } return str; } function GetEntryMetaFields( selectedFieldId ) { var options = [], selected, label; if(typeof entry_meta == 'undefined') return options; jQuery.each( entry_meta, function( key, meta ) { if(typeof meta.filter == 'undefined') return; options.push( { label: meta.label, value: key, isSelected: selectedFieldId == key ? "selected='selected'" : "" } ); }); return options; } function IsConditionalLogicField(field){ var inputType = field.inputType ? field.inputType : field.type; var supported_fields = GetConditionalLogicFields(); var index = jQuery.inArray(inputType, supported_fields); var isConditionalLogicField = index >= 0 ? true : false; isConditionalLogicField = gform.applyFilters( 'gform_is_conditional_logic_field', isConditionalLogicField, field ); return isConditionalLogicField; } function IsEntryMeta(key){ return typeof entry_meta != 'undefined' && typeof entry_meta[key] != 'undefined'; } function GetRuleValues(objectType, ruleIndex, selectedFieldId, selectedValue, inputName){ if(!inputName) inputName = false; var dropdownId = inputName == false ? objectType + '_rule_value_' + ruleIndex : inputName; if(selectedFieldId == 0) selectedFieldId = GetFirstRuleField(); if(selectedFieldId == 0) return ""; var field = GetFieldById(selectedFieldId), isEntryMeta = IsEntryMeta(selectedFieldId), obj = GetConditionalObject(objectType), rule = obj["conditionalLogic"]["rules"][ruleIndex], operator = rule.operator, str = ""; if(field && field["type"] == "post_category" && field["displayAllCategories"]){ var dropdown = jQuery('#' + dropdownId + ".gfield_category_dropdown"); //don't load category drop down if it already exists (to avoid unecessary ajax requests) if(dropdown.length > 0){ var options = dropdown.html(); options = options.replace("value=\"" + selectedValue + "\"", "value=\"" + selectedValue + "\" selected=\"selected\""); str = "<select id='" + dropdownId + "' class='gfield_rule_select gfield_rule_value_dropdown gfield_category_dropdown'>" + options + "</select>"; } else{ var placeholderName = inputName == false ? "gfield_ajax_placeholder_" + ruleIndex : inputName + "_placeholder"; //loading categories via AJAX jQuery.post(ajaxurl,{ action:"gf_get_post_categories", objectType: objectType, ruleIndex: ruleIndex, inputName: inputName, selectedValue: selectedValue}, function(dropdown_string){ if(dropdown_string){ jQuery('#' + placeholderName).replaceWith(dropdown_string.trim()); SetRuleProperty(objectType, ruleIndex, "value", jQuery("#" + dropdownId).val()); } } ); //will be replaced by real drop down during the ajax callback str = "<select id='" + placeholderName + "' class='gfield_rule_select'><option>" + gf_vars["loading"] + "</option></select>"; } } else if(field && field.choices && jQuery.inArray(operator, ["is", "isnot"]) > -1){ var ruleChoices = field.placeholder ? [{ text: field.placeholder, value: '' }].concat(field.choices) : field.choices; str = GetRuleValuesDropDown(ruleChoices, objectType, ruleIndex, selectedValue, inputName); } else if( IsAddressSelect( selectedFieldId, field ) ) { //loading categories via AJAX jQuery.post( ajaxurl, { action: 'gf_get_address_rule_values_select', address_type: field.addressType ? field.addressType : gf_vars.defaultAddressType, value: selectedValue, id: dropdownId, form_id: field.formId }, function( selectMarkup ) { if( selectMarkup ) { $select = jQuery( selectMarkup.trim() ); $placeholder = jQuery( '#' + dropdownId ); $placeholder.replaceWith( $select ); SetRuleProperty( objectType, ruleIndex, 'value', $select.val() ); } } ); // will be replaced by real drop down during the ajax callback str = "<select id='" + dropdownId + "' class='gfield_rule_select'><option>" + gf_vars['loading'] + "</option></select>"; } else if (isEntryMeta && entry_meta && entry_meta[selectedFieldId] && entry_meta[selectedFieldId].filter && typeof entry_meta[selectedFieldId].filter.choices != 'undefined') { str = GetRuleValuesDropDown(entry_meta[selectedFieldId].filter.choices, objectType, ruleIndex, selectedValue, inputName); } else{ selectedValue = selectedValue ? selectedValue.replace(/'/g, "&#039;") : ""; //create a text field for fields that don't have choices (i.e text, textarea, number, email, etc...) str = "<input type='text' placeholder='" + gf_vars["enterValue"] + "' class='gfield_rule_select' id='" + dropdownId + "' name='" + dropdownId + "' value='" + selectedValue.replace(/'/g, "&#039;") + "' onchange='SetRuleProperty(\"" + objectType + "\", " + ruleIndex + ", \"value\", jQuery(this).val());' onkeyup='SetRuleProperty(\"" + objectType + "\", " + ruleIndex + ", \"value\", jQuery(this).val());'>"; } str = gform.applyFilters( 'gform_conditional_logic_values_input', str, objectType, ruleIndex, selectedFieldId, selectedValue ) return str; } /** * Determine if current Address field input ID is a select (i.e. US => State, International => Country) * @param inputId string Address field input ID * @param field object Address field * @returns {boolean} * @constructor */ function IsAddressSelect( inputId, field ) { if( ! field || GetInputType( field ) != 'address' ) { return false; } var addressType = field.addressType ? field.addressType : gf_vars.defaultAddressType; if( ! gf_vars.addressTypes[ addressType ] ) { return false; } var addressTypeObj = gf_vars.addressTypes[ addressType ], isCountryInput = inputId == field.id + '.6', isStateInput = inputId == field.id + '.4'; return ( isCountryInput && addressType == 'international' ) || ( isStateInput && typeof addressTypeObj.states == 'object' ); } function GetFirstRuleField(){ for(var i=0; i<form.fields.length; i++){ if(IsConditionalLogicField(form.fields[i])) return form.fields[i].id; } return 0; } function GetRuleValuesDropDown(choices, objectType, ruleIndex, selectedValue, inputName){ var dropdown_id = inputName == false ? objectType + '_rule_value_' + ruleIndex : inputName; //create a drop down for fields that have choices (i.e. drop down, radio, checkboxes, etc...) var str = "<select class='gfield_rule_select gfield_rule_value_dropdown' id='" + dropdown_id + "' name='" + dropdown_id + "'>"; var isAnySelected = false; for(var i=0; i<choices.length; i++){ var choiceValue = typeof choices[i].value == "undefined" || choices[i].value == null ? choices[i].text + '' : choices[i].value + ''; var isSelected = choiceValue == selectedValue; var selected = isSelected ? "selected='selected'" : ""; if(isSelected) isAnySelected = true; choiceValue = choiceValue.replace(/'/g, "&#039;"); var choiceText = jQuery.trim(jQuery('<div>'+choices[i].text+'</div>').text()) === '' ? choiceValue : choices[i].text; str += "<option value='" + choiceValue.replace(/'/g, "&#039;") + "' " + selected + ">" + choiceText + "</option>"; } if(!isAnySelected && selectedValue && selectedValue != "") str += "<option value='" + selectedValue.replace(/'/g, "&#039;") + "' selected='selected'>" + selectedValue + "</option>"; str += "</select>"; return str; } function isEmpty(str){ return } function SetRuleProperty(objectType, ruleIndex, name, value){ var obj = GetConditionalObject(objectType); obj.conditionalLogic.rules[ruleIndex][name] = value; } function GetFieldById( id ) { id = parseInt( id ); for(var i=0; i<form.fields.length; i++){ if(form.fields[i].id == id) return form.fields[i]; } return null; } function SetConditionalProperty(objectType, name, value){ var obj = GetConditionalObject(objectType); obj.conditionalLogic[name] = value; } function SetRuleValueDropDown(element){ //parsing ID to get objectType and ruleIndex var ary = element.attr("id").split('_rule_value_'); if(ary.length < 2) return; var objectType = ary[0]; var ruleIndex = ary[1]; SetRuleProperty(objectType, ruleIndex, "value", element.val()); } function InsertRule(objectType, ruleIndex){ var obj = GetConditionalObject(objectType); obj.conditionalLogic.rules.splice(ruleIndex, 0, new ConditionalRule()); CreateConditionalLogic(objectType, obj); SetRule(objectType, ruleIndex); } function SetRule(objectType, ruleIndex){ SetRuleProperty(objectType, ruleIndex, "fieldId", jQuery("#" + objectType + "_rule_field_" + ruleIndex).val()); SetRuleProperty(objectType, ruleIndex, "operator", jQuery("#" + objectType + "_rule_operator_" + ruleIndex).val()); SetRuleProperty(objectType, ruleIndex, "value", jQuery("#" + objectType + "_rule_value_" + ruleIndex).val()); } function DeleteRule(objectType, ruleIndex){ var obj = GetConditionalObject(objectType); obj.conditionalLogic.rules.splice(ruleIndex, 1); CreateConditionalLogic(objectType, obj); } function TruncateRuleText(text){ if(!text || text.length <= 18) return text; return text.substr(0, 9) + "..." + text.substr(text.length -8, 9); } function gfAjaxSpinner(elem, imageSrc, inlineStyles) { var imageSrc = typeof imageSrc == 'undefined' ? '/images/ajax-loader.gif': imageSrc; var inlineStyles = typeof inlineStyles != 'undefined' ? inlineStyles : ''; this.elem = elem; this.image = '<img class="gfspinner" src="' + imageSrc + '" style="' + inlineStyles + '" />'; this.init = function() { this.spinner = jQuery(this.image); jQuery(this.elem).after(this.spinner); return this; }; this.destroy = function() { jQuery(this.spinner).remove(); }; return this.init(); } function InsertVariable(element_id, callback, variable) { if(!variable) variable = jQuery('#' + element_id + '_variable_select').val(); var input = document.getElementById (element_id); var $input = jQuery(input); if(document.selection) { // Go the IE way $input[0].focus(); document.selection.createRange().text=variable; } else if('selectionStart' in input) { var startPos = input.selectionStart; input.value = input.value.substr(0, startPos) + variable + input.value.substr(input.selectionEnd, input.value.length); input.selectionStart = startPos + input.value.length; input.selectionEnd = startPos + input.value.length; } else { $input.val(variable + messageElement.val()); } var variableSelect = jQuery('#' + element_id + '_variable_select'); if(variableSelect.length > 0) variableSelect[0].selectedIndex = 0; if(callback && window[callback]){ window[callback].call(null, element_id, variable); } } function InsertEditorVariable( elementId, value ) { if( !value ) { var select = jQuery("#" + elementId + "_variable_select"); select[0].selectedIndex = 0; value = select.val(); } wpActiveEditor = elementId; window.send_to_editor( value ); } function GetInputType(field){ return field.inputType ? field.inputType : field.type; } function HasPostField(){ for(var i=0; i<form.fields.length; i++){ var type = form.fields[i].type; if(type == "post_title" || type == "post_content" || type == "post_excerpt") return true; } return false; } function GetInput(field, id){ if( typeof field['inputs'] != 'undefined' && jQuery.isArray(field['inputs']) ) { for(i in field['inputs']) { if(!field['inputs'].hasOwnProperty(i)) continue; var input = field['inputs'][i]; if(input.id == id) return input; } } return null; } function IsPricingField(fieldType) { return IsProductField(fieldType) || fieldType == 'donation'; } function IsProductField(fieldType) { return jQuery.inArray(fieldType, ["option", "quantity", "product", "total", "shipping", "calculation"]) != -1; } function GetLabel(field, inputId, inputOnly) { if(typeof inputId == 'undefined') inputId = 0; if(typeof inputOnly == 'undefined') inputOnly = false; var input = GetInput(field, inputId); var displayLabel = ""; if (field.adminLabel != undefined && field.adminLabel.length > 0){ //use admin label displayLabel = field.adminLabel; } else{ //use regular label displayLabel = field.label; } if(input != null) { return inputOnly ? input.label : displayLabel + ' (' + input.label + ')'; } else { return displayLabel; } } function DeleteNotification(notificationId) { jQuery('#action_argument').val(notificationId); jQuery('#action').val('delete'); jQuery('#notification_list_form')[0].submit(); } function DuplicateNotification(notificationId) { jQuery('#action_argument').val(notificationId); jQuery('#action').val('duplicate'); jQuery('#notification_list_form')[0].submit(); } function DeleteConfirmation(confirmationId) { jQuery('#action_argument').val(confirmationId); jQuery('#action').val('delete'); jQuery('#confirmation_list_form')[0].submit(); } function DuplicateConfirmation(confirmationId) { jQuery('#action_argument').val(confirmationId); jQuery('#action').val('duplicate'); jQuery('#confirmation_list_form')[0].submit(); } function SetConfirmationConditionalLogic() { confirmation['conditionalLogic'] = jQuery('#conditional_logic').val() ? jQuery.parseJSON(jQuery('#conditional_logic').val()) : new ConditionalLogic(); } function ToggleConfirmation() { var showElement, hideElement = ''; var isRedirect = jQuery("#form_confirmation_redirect").is(":checked"); var isPage = jQuery("#form_confirmation_show_page").is(":checked"); if(isRedirect){ showElement = ".form_confirmation_redirect_container"; hideElement = "#form_confirmation_message_container, .form_confirmation_page_container"; ClearConfirmationSettings(['text', 'page']); } else if(isPage){ showElement = ".form_confirmation_page_container"; hideElement = "#form_confirmation_message_container, .form_confirmation_redirect_container"; ClearConfirmationSettings(['text', 'redirect']); } else{ showElement = "#form_confirmation_message_container"; hideElement = ".form_confirmation_page_container, .form_confirmation_redirect_container"; ClearConfirmationSettings(['page', 'redirect']); } ToggleQueryString(); TogglePageQueryString() jQuery(hideElement).hide(); jQuery(showElement).show(); } function ToggleQueryString() { if(jQuery('#form_redirect_use_querystring').is(":checked")){ jQuery('#form_redirect_querystring_container').show(); } else{ jQuery('#form_redirect_querystring_container').hide(); jQuery("#form_redirect_querystring").val(''); jQuery("#form_redirect_use_querystring").val(''); } } function TogglePageQueryString() { if(jQuery('#form_page_use_querystring').is(":checked")){ jQuery('#form_page_querystring_container').show(); } else{ jQuery('#form_page_querystring_container').hide(); jQuery("#form_page_querystring").val(''); jQuery("#form_page_use_querystring").val(''); } } function ClearConfirmationSettings(type) { var types = jQuery.isArray(type) ? type : [type]; for(i in types) { if(!types.hasOwnProperty(i)) continue; switch(types[i]) { case 'text': jQuery('#form_confirmation_message').val(''); jQuery('#form_disable_autoformatting').prop('checked', false); break; case 'page': jQuery('#form_confirmation_page').val(''); jQuery('#form_page_querystring').val(''); jQuery('#form_page_use_querystring').prop('checked', false); break; case 'redirect': jQuery('#form_confirmation_url').val(''); jQuery('#form_redirect_querystring').val(''); jQuery('#form_redirect_use_querystring').prop('checked', false); break; } } } function StashConditionalLogic() { var string = JSON.stringify(confirmation['conditionalLogic']); jQuery('#conditional_logic').val(string); } function ConfirmationObj() { this.id = false; this.name = gf_vars.confirmationDefaultName; this.type = 'message'; this.message = gf_vars.confirmationDefaultMessage; this.isDefault = 0; } (function (gaddon, $, undefined) { gaddon.init = function () { var defaultVal, valueExists, value; f = window.form; var id = 0; if(isSet(f)){ id = f.id } }; gaddon.toggleFeedActive = function(img, addon_slug, feed_id){ var is_active = img.src.indexOf("active1.png") >=0 ? 0 : 1; img.src = img.src.replace("active1.png", "spinner.gif"); img.src = img.src.replace("active0.png", "spinner.gif"); jQuery.post(ajaxurl, { action: "gf_feed_is_active_" + addon_slug, feed_id: feed_id, is_active: is_active }, function(response){ if(is_active){ img.src = img.src.replace("spinner.gif", "active1.png"); jQuery(img).attr('title',gf_vars.inactive).attr('alt', gf_vars.inactive); } else{ img.src = img.src.replace("spinner.gif", "active0.png"); jQuery(img).attr('title',gf_vars.active).attr('alt', gf_vars.active); } } ); return true; }; gaddon.deleteFeed = function (id) { $("#single_action").val("delete"); $("#single_action_argument").val(id); $("#gform-settings").submit(); }; gaddon.duplicateFeed = function (id) { $("#single_action").val("duplicate"); $("#single_action_argument").val(id); $("#gform-settings").submit(); }; function isValidJson(str) { try { JSON.parse(str); } catch (e) { return false; } return true; } function isSet($var) { if (typeof $var != 'undefined') return true return false } function rgar(array, name) { if (typeof array[name] != 'undefined') return array[name]; return ''; } }(window.gaddon = window.gaddon || {}, jQuery)); function Copy(variable){ if(!variable) return variable; else if(typeof variable != 'object') return variable; variable = jQuery.isArray(variable) ? variable.slice() : jQuery.extend({}, variable); for(i in variable) { variable[i] = Copy(variable[i]); } return variable; } var gfMergeTagsObj = function(form) { this.form = form; this.init = function() { var gfMergeTags = this; this.mergeTagList = jQuery('<ul id="gf_merge_tag_list" class=""></ul>'); this.mergeTagListHover = false; if(jQuery('.merge-tag-support').length <= 0) return; jQuery( ".merge-tag-support" ) // don't navigate away from the field on tab when selecting an item .bind( "keydown", function( event ) { var menuActive = jQuery( this ).data( "autocomplete" ) && jQuery( this ).data( "autocomplete" ).menu ? jQuery( this ).data( "autocomplete" ).menu.active : false; if ( event.keyCode === jQuery.ui.keyCode.TAB && menuActive ) { event.preventDefault(); } }) .each(function(){ var elem = jQuery(this); var classStr = elem.is('input') ? 'input' : 'textarea'; elem.autocomplete({ minLength: 1, source: function( request, response ) { // delegate back to autocomplete, but extract the last term var term = gfMergeTags.extractLast( request.term ); if(term.length < elem.autocomplete('option', 'minLength')) { response( [] ); return; } var tags = jQuery.map( gfMergeTags.getAutoCompleteMergeTags(elem), function(item) { return gfMergeTags.startsWith( item, term ) ? item : null; }); response( tags ); }, focus: function() { // prevent value inserted on focus return false; }, select: function( event, ui ) { var terms = gfMergeTags.split( this.value ); // remove the current input terms.pop(); // add the selected item terms.push( ui.item.value ); this.value = terms.join( " " ); elem.trigger('input').trigger('propertychange'); return false; } }); var positionClass = gfMergeTags.getClassProperty(this, 'position'); var mergeTagIcon = jQuery('<span class="all-merge-tags ' + positionClass + ' ' + classStr + '"><a class="open-list tooltip-merge-tag" title="' + gf_vars.mergeTagsTooltip + '"></a></span>'); // add the target element to the merge tag icon data for reference later when determining where the selected merge tag should be inserted mergeTagIcon.data('targetElement', elem.attr('id') ); // if "mt-manual_position" class prop is set, look for manual elem with correct class if( gfMergeTags.getClassProperty( this, 'manual_position' ) ) { var manualClass = '.mt-' + elem.attr('id'); jQuery(manualClass).append( mergeTagIcon ); } else { elem.after( mergeTagIcon ); } }); jQuery('.tooltip-merge-tag').tooltip({ show: {delay:1250}, content: function () { return jQuery(this).prop('title'); } }); jQuery('.all-merge-tags a.open-list').click(function() { var trigger = jQuery(this); var input = gfMergeTags.getTargetElement( trigger ); gfMergeTags.mergeTagList.html( gfMergeTags.getMergeTagListItems( input ) ); gfMergeTags.mergeTagList.insertAfter( trigger ).show(); jQuery('ul#gf_merge_tag_list a').click(function(){ var value = jQuery(this).data('value'); var input = gfMergeTags.getTargetElement( this ); // if input has "mt-wp_editor" class, use WP Editor insert function if( gfMergeTags.isWpEditor( input ) ) { InsertEditorVariable( input.attr('id'), value ); } else { InsertVariable( input.attr('id'), null, value ); } input.trigger('input').trigger('propertychange'); gfMergeTags.mergeTagList.hide(); }); }); this.getTargetElement = function( elem ) { var elem = jQuery( elem ); return jQuery( '#' + elem.parents('span.all-merge-tags').data('targetElement') ); } // hide merge tag list on off click this.mergeTagList.hover(function(){ gfMergeTags.mergeTagListHover = true; }, function(){ gfMergeTags.mergeTagListHover = false; }); jQuery('body').mouseup(function(){ if(!gfMergeTags.mergeTagListHover) gfMergeTags.mergeTagList.hide(); }); }; this.split = function( val ) { return val.split(' '); }; this.extractLast = function( term ) { return this.split( term ).pop(); }; this.startsWith = function(string, value) { return string.indexOf(value) === 0; }; this.getMergeTags = function(fields, elementId, hideAllFields, excludeFieldTypes, isPrepop, option) { if(typeof fields == 'undefined') fields = []; if(typeof excludeFieldTypes == 'undefined') excludeFieldTypes = []; var requiredFields = [], optionalFields = [], pricingFields = []; var ungrouped = [], requiredGroup = [], optionalGroup = [], pricingGroup = [], otherGroup = [], customGroup = []; if(!hideAllFields) ungrouped.push({ tag: '{all_fields}', 'label': this.getMergeTagLabel('{all_fields}') }); if(!isPrepop) { // group fields by required, optional and pricing for(i in fields) { if(!fields.hasOwnProperty(i)) continue; var field = fields[i]; if(field['displayOnly']) continue; var inputType = GetInputType(field); if(jQuery.inArray(inputType, excludeFieldTypes) != -1) continue; if(field.isRequired) { switch(inputType) { case 'name': var requiredField = Copy(field); var prefix, middle, suffix, optionalField; if(field['nameFormat'] == 'extended') { prefix = GetInput(field, field.id + '.2'); suffix = GetInput(field, field.id + '.8'); optionalField = Copy(field); optionalField['inputs'] = [prefix, suffix]; // add optional name fields to optional list optionalFields.push(optionalField); // remove optional name fields from required list delete requiredField.inputs[0]; delete requiredField.inputs[3]; } else if(field['nameFormat'] == 'advanced') { prefix = GetInput(field, field.id + '.2'); middle = GetInput(field, field.id + '.4'); suffix = GetInput(field, field.id + '.8'); optionalField = Copy(field); optionalField['inputs'] = [prefix, middle, suffix]; // add optional name fields to optional list optionalFields.push(optionalField); // remove optional name fields from required list delete requiredField.inputs[0]; delete requiredField.inputs[2]; delete requiredField.inputs[4]; } requiredFields.push(requiredField); break; default: requiredFields.push(field); } } else { optionalFields.push(field); } if(IsPricingField(field.type)) { pricingFields.push(field); } } if(requiredFields.length > 0) { for(i in requiredFields) { if(! requiredFields.hasOwnProperty(i)) continue; requiredGroup = requiredGroup.concat(this.getFieldMergeTags(requiredFields[i], option)); } } if(optionalFields.length > 0) { for(i in optionalFields) { if(!optionalFields.hasOwnProperty(i)) continue; optionalGroup = optionalGroup.concat(this.getFieldMergeTags(optionalFields[i], option)); } } if(pricingFields.length > 0) { if(!hideAllFields) pricingGroup.push({ tag: '{pricing_fields}', 'label': this.getMergeTagLabel('{pricing_fields}') }); for(i in pricingFields) { if(!pricingFields.hasOwnProperty(i)) continue; pricingGroup.concat(this.getFieldMergeTags(pricingFields[i], option)); } } } otherGroup.push( { tag: '{ip}', label: this.getMergeTagLabel('{ip}') }); otherGroup.push( { tag: '{date_mdy}', label: this.getMergeTagLabel('{date_mdy}') }); otherGroup.push( { tag: '{date_dmy}', label: this.getMergeTagLabel('{date_dmy}') }); otherGroup.push( { tag: '{embed_post:ID}', label: this.getMergeTagLabel('{embed_post:ID}') }); otherGroup.push( { tag: '{embed_post:post_title}', label: this.getMergeTagLabel('{embed_post:post_title}') }); otherGroup.push( { tag: '{embed_url}', label: this.getMergeTagLabel('{embed_url}') }); // the form and entry objects are not available during replacement of pre-population merge tags if (!isPrepop) { otherGroup.push({tag: '{entry_id}', label: this.getMergeTagLabel('{entry_id}')}); otherGroup.push({tag: '{entry_url}', label: this.getMergeTagLabel('{entry_url}')}); otherGroup.push({tag: '{form_id}', label: this.getMergeTagLabel('{form_id}')}); otherGroup.push({tag: '{form_title}', label: this.getMergeTagLabel('{form_title}')}); } otherGroup.push( { tag: '{user_agent}', label: this.getMergeTagLabel('{user_agent}') }); otherGroup.push( { tag: '{referer}', label: this.getMergeTagLabel('{referer}') }); if(HasPostField() && !isPrepop) { // TODO: consider adding support for passing form object or fields array otherGroup.push( { tag: '{post_id}', label: this.getMergeTagLabel('{post_id}') }); otherGroup.push( { tag: '{post_edit_url}', label: this.getMergeTagLabel('{post_edit_url}') }); } otherGroup.push( { tag: '{user:display_name}', label: this.getMergeTagLabel('{user:display_name}') }); otherGroup.push( { tag: '{user:user_email}', label: this.getMergeTagLabel('{user:user_email}') }); otherGroup.push( { tag: '{user:user_login}', label: this.getMergeTagLabel('{user:user_login}') }); var customMergeTags = this.getCustomMergeTags(); if( customMergeTags.tags.length > 0 ) { for( i in customMergeTags.tags ) { if(! customMergeTags.tags.hasOwnProperty(i)) continue; var customMergeTag = customMergeTags.tags[i]; customGroup.push( { tag: customMergeTag.tag, label: customMergeTag.label } ); } } var mergeTags = { ungrouped: { label: this.getMergeGroupLabel('ungrouped'), tags: ungrouped }, required: { label: this.getMergeGroupLabel('required'), tags: requiredGroup }, optional: { label: this.getMergeGroupLabel('optional'), tags: optionalGroup }, pricing: { label: this.getMergeGroupLabel('pricing'), tags: pricingGroup }, other: { label: this.getMergeGroupLabel('other'), tags: otherGroup }, custom: { label: this.getMergeGroupLabel('custom'), tags: customGroup } }; mergeTags = gform.applyFilters('gform_merge_tags', mergeTags, elementId, hideAllFields, excludeFieldTypes, isPrepop, option, this ); return mergeTags; }; this.getMergeTagLabel = function(tag) { for(groupName in gf_vars.mergeTags) { if(!gf_vars.mergeTags.hasOwnProperty(groupName)) continue; var tags = gf_vars.mergeTags[groupName].tags; for(i in tags) { if(!tags.hasOwnProperty(i)) continue; if(tags[i].tag == tag) return tags[i].label; } } return ''; }; this.getMergeGroupLabel = function(group) { return gf_vars.mergeTags[group].label; }; this.getFieldMergeTags = function(field, option) { if(typeof option == 'undefined') option = ''; var mergeTags = []; var inputType = GetInputType(field); var tagArgs = inputType == "list" ? ":" + option : ""; //option currently only supported by list field var value = '', label = ''; if(jQuery.inArray(inputType, ['date', 'email', 'time', 'password'])>-1){ field['inputs'] = null; } if( typeof field['inputs'] != 'undefined' && jQuery.isArray(field['inputs']) ) { if(inputType == 'checkbox') { label = GetLabel(field, field.id).replace("'", "\\'"); value = "{" + label + ":" + field.id + tagArgs + "}"; mergeTags.push( { tag: value, label: label } ); } for(i in field.inputs) { if(!field.inputs.hasOwnProperty(i)) continue; var input = field.inputs[i]; if(inputType == "creditcard" && jQuery.inArray(parseFloat(input.id),[parseFloat(field.id + ".2"), parseFloat(field.id + ".3"), parseFloat(field.id + ".5")]) > -1) continue; label = GetLabel(field, input.id).replace("'", "\\'"); value = "{" + label + ":" + input.id + tagArgs + "}"; mergeTags.push( { tag: value, label: label } ); } } else { label = GetLabel(field).replace("'", "\\'"); value = "{" + label + ":" + field.id + tagArgs + "}"; mergeTags.push( { tag: value, label: label } ); } return mergeTags; }; this.getCustomMergeTags = function() { for(groupName in gf_vars.mergeTags) { if(!gf_vars.mergeTags.hasOwnProperty(groupName)) continue; if(groupName == 'custom') return gf_vars.mergeTags[groupName]; } return []; }; this.getAutoCompleteMergeTags = function(elem) { var fields = this.form.fields; var elementId = elem.attr('id'); var hideAllFields = this.getClassProperty(elem, 'hide_all_fields') == true; var excludeFieldTypes = this.getClassProperty(elem, 'exclude'); var option = this.getClassProperty(elem, 'option'); var isPrepop = this.getClassProperty(elem, 'prepopulate'); if(isPrepop) { hideAllFields = true; } var mergeTags = this.getMergeTags(fields, elementId, hideAllFields, excludeFieldTypes, isPrepop, option); var autoCompleteTags = []; for(group in mergeTags) { if(! mergeTags.hasOwnProperty(group)) continue; var tags = mergeTags[group].tags; for(i in tags) { if(!tags.hasOwnProperty(i)) continue; autoCompleteTags.push(tags[i].tag); } } return autoCompleteTags; }; this.getMergeTagListItems = function(elem) { var fields = this.form.fields; var elementId = elem.attr('id'); var hideAllFields = this.getClassProperty(elem, 'hide_all_fields') == true; var excludeFieldTypes = this.getClassProperty(elem, 'exclude'); var isPrepop = this.getClassProperty(elem, 'prepopulate'); var option = this.getClassProperty(elem, 'option'); if(isPrepop) { hideAllFields = true; } var mergeTags = this.getMergeTags(fields, elementId, hideAllFields, excludeFieldTypes, isPrepop, option); var hasMultipleGroups = this.hasMultipleGroups(mergeTags); var optionsHTML = ''; for(group in mergeTags) { if(! mergeTags.hasOwnProperty(group)) continue; var label = mergeTags[group].label var tags = mergeTags[group].tags; // skip groups without any tags if(tags.length <= 0) continue; // if group name provided if(label && hasMultipleGroups) optionsHTML += '<li class="group-header">' + label + '</li>'; for(i in tags) { if(!tags.hasOwnProperty(i)) continue; var tag = tags[i]; optionsHTML += '<li class=""><a class="" data-value="' + tag.tag + '">' + tag.label + '</a></li>'; } } return optionsHTML; }; this.hasMultipleGroups = function(mergeTags) { var count = 0; for(group in mergeTags) { if(!mergeTags.hasOwnProperty(group)) continue; if(mergeTags[group].tags.length > 0) count++; } return count > 1; }; /** * Merge Tag inputs support a system for setting various properties for the merge tags via classes. * e.g. mt-{property}-{value} * * You can pass multiple values for a property like so: * e.g. mt-{property}-{value1}-{value2}-{value3} * * Current classes: * mt-hide_all_fields * mt-exclude-{field_type} e.g. mt-exlude-paragraph * mt-option-{option_value} e.g. mt-option-url * mt-position-{position_value} e.g. mt-position-right * */ this.getClassProperty = function(elem, property) { var elem = jQuery(elem); var classStr = elem.attr('class'); if(!classStr) return ''; var classes = classStr.split(' '); for(i in classes) { if(!classes.hasOwnProperty(i)) continue; var pieces = classes[i].split('-'); // if this is not a merge tag class or not the property we are looking for, skip if(pieces[0] != 'mt' || pieces[1] != property) continue; // if more than one value passed, return all values if(pieces.length > 3) { delete pieces[0]; delete pieces[1]; return pieces; } // if just a property is passed, assume we are looking for boolean, return true else if(pieces.length == 2){ return true; // in all other cases, return the value } else { return pieces[2]; } } return ''; }; this.isWpEditor = function( mergeTagIcon ) { var mergeTagIcon = jQuery( mergeTagIcon ); return this.getClassProperty( mergeTagIcon, 'wp_editor' ) == true; }; this.init(); }; var FeedConditionObj = function( args ) { this.strings = isSet( args.strings ) ? args.strings : {}; this.logicObject = args.logicObject; this.init = function() { var fcobj = this; gform.addFilter( 'gform_conditional_object', 'FeedConditionConditionalObject' ); gform.addFilter( 'gform_conditional_logic_description', 'FeedConditionConditionalDescription' ); jQuery(document).ready(function(){ ToggleConditionalLogic( true, "feed_condition" ); }); jQuery('input#feed_condition_conditional_logic').parents('form').on('submit', function(){ jQuery('input#feed_condition_conditional_logic_object').val( JSON.stringify( fcobj.logicObject ) ); }); }; this.init(); }; function SimpleConditionObject( object, objectType ) { if( objectType.indexOf('simple_condition') < 0 ) return object; var objectName = objectType.substring(17) + "_object"; return window[objectName]; } function FeedConditionConditionalObject( object, objectType ) { if( objectType != 'feed_condition' ) return object; return feedCondition.logicObject; } function FeedConditionConditionalDescription( description, descPieces, objectType, obj ) { if( objectType != 'feed_condition' ) return description; descPieces.actionType = descPieces.actionType.replace('<select', '<select style="display:none;"'); descPieces.objectDescription = feedCondition.strings.objectDescription; var descPiecesArr = makeArray( descPieces ); return descPiecesArr.join(' '); } function makeArray( object ) { var array = []; for( i in object ) { array.push( object[i] ); } return array; } function isSet( $var ) { return typeof $var != 'undefined'; }
'use strict'; var InteractionManager = require('./InteractionManager'); var TouchHistoryMath = require('TouchHistoryMath'); var currentCentroidXOfTouchesChangedAfter = TouchHistoryMath.currentCentroidXOfTouchesChangedAfter; var currentCentroidYOfTouchesChangedAfter = TouchHistoryMath.currentCentroidYOfTouchesChangedAfter; var previousCentroidXOfTouchesChangedAfter = TouchHistoryMath.previousCentroidXOfTouchesChangedAfter; var previousCentroidYOfTouchesChangedAfter = TouchHistoryMath.previousCentroidYOfTouchesChangedAfter; var currentCentroidX = TouchHistoryMath.currentCentroidX; var currentCentroidY = TouchHistoryMath.currentCentroidY; var PanResponder = { _initializeGestureState: function _initializeGestureState(gestureState) { gestureState.moveX = 0; gestureState.moveY = 0; gestureState.x0 = 0; gestureState.y0 = 0; gestureState.dx = 0; gestureState.dy = 0; gestureState.vx = 0; gestureState.vy = 0; gestureState.numberActiveTouches = 0; gestureState._accountsForMovesUpTo = 0; }, _updateGestureStateOnMove: function _updateGestureStateOnMove(gestureState, touchHistory) { gestureState.numberActiveTouches = touchHistory.numberActiveTouches; gestureState.moveX = currentCentroidXOfTouchesChangedAfter(touchHistory, gestureState._accountsForMovesUpTo); gestureState.moveY = currentCentroidYOfTouchesChangedAfter(touchHistory, gestureState._accountsForMovesUpTo); var movedAfter = gestureState._accountsForMovesUpTo; var prevX = previousCentroidXOfTouchesChangedAfter(touchHistory, movedAfter); var x = currentCentroidXOfTouchesChangedAfter(touchHistory, movedAfter); var prevY = previousCentroidYOfTouchesChangedAfter(touchHistory, movedAfter); var y = currentCentroidYOfTouchesChangedAfter(touchHistory, movedAfter); var nextDX = gestureState.dx + (x - prevX); var nextDY = gestureState.dy + (y - prevY); var dt = touchHistory.mostRecentTimeStamp - gestureState._accountsForMovesUpTo; gestureState.vx = (nextDX - gestureState.dx) / dt; gestureState.vy = (nextDY - gestureState.dy) / dt; gestureState.dx = nextDX; gestureState.dy = nextDY; gestureState._accountsForMovesUpTo = touchHistory.mostRecentTimeStamp; }, create: function create(config) { var interactionState = { handle: null }; var gestureState = { stateID: Math.random() }; PanResponder._initializeGestureState(gestureState); var panHandlers = { onStartShouldSetResponder: function onStartShouldSetResponder(e) { return config.onStartShouldSetPanResponder === undefined ? false : config.onStartShouldSetPanResponder(e, gestureState); }, onMoveShouldSetResponder: function onMoveShouldSetResponder(e) { return config.onMoveShouldSetPanResponder === undefined ? false : config.onMoveShouldSetPanResponder(e, gestureState); }, onStartShouldSetResponderCapture: function onStartShouldSetResponderCapture(e) { if (e.nativeEvent.touches.length === 1) { PanResponder._initializeGestureState(gestureState); } gestureState.numberActiveTouches = e.touchHistory.numberActiveTouches; return config.onStartShouldSetPanResponderCapture !== undefined ? config.onStartShouldSetPanResponderCapture(e, gestureState) : false; }, onMoveShouldSetResponderCapture: function onMoveShouldSetResponderCapture(e) { var touchHistory = e.touchHistory; if (gestureState._accountsForMovesUpTo === touchHistory.mostRecentTimeStamp) { return false; } PanResponder._updateGestureStateOnMove(gestureState, touchHistory); return config.onMoveShouldSetPanResponderCapture ? config.onMoveShouldSetPanResponderCapture(e, gestureState) : false; }, onResponderGrant: function onResponderGrant(e) { if (!interactionState.handle) { interactionState.handle = InteractionManager.createInteractionHandle(); } gestureState.x0 = currentCentroidX(e.touchHistory); gestureState.y0 = currentCentroidY(e.touchHistory); gestureState.dx = 0; gestureState.dy = 0; if (config.onPanResponderGrant) { config.onPanResponderGrant(e, gestureState); } return config.onShouldBlockNativeResponder === undefined ? true : config.onShouldBlockNativeResponder(); }, onResponderReject: function onResponderReject(e) { clearInteractionHandle(interactionState, config.onPanResponderReject, e, gestureState); }, onResponderRelease: function onResponderRelease(e) { clearInteractionHandle(interactionState, config.onPanResponderRelease, e, gestureState); PanResponder._initializeGestureState(gestureState); }, onResponderStart: function onResponderStart(e) { var touchHistory = e.touchHistory; gestureState.numberActiveTouches = touchHistory.numberActiveTouches; if (config.onPanResponderStart) { config.onPanResponderStart(e, gestureState); } }, onResponderMove: function onResponderMove(e) { var touchHistory = e.touchHistory; if (gestureState._accountsForMovesUpTo === touchHistory.mostRecentTimeStamp) { return; } PanResponder._updateGestureStateOnMove(gestureState, touchHistory); if (config.onPanResponderMove) { config.onPanResponderMove(e, gestureState); } }, onResponderEnd: function onResponderEnd(e) { var touchHistory = e.touchHistory; gestureState.numberActiveTouches = touchHistory.numberActiveTouches; clearInteractionHandle(interactionState, config.onPanResponderEnd, e, gestureState); }, onResponderTerminate: function onResponderTerminate(e) { clearInteractionHandle(interactionState, config.onPanResponderTerminate, e, gestureState); PanResponder._initializeGestureState(gestureState); }, onResponderTerminationRequest: function onResponderTerminationRequest(e) { return config.onPanResponderTerminationRequest === undefined ? true : config.onPanResponderTerminationRequest(e, gestureState); } }; return { panHandlers: panHandlers, getInteractionHandle: function getInteractionHandle() { return interactionState.handle; } }; } }; function clearInteractionHandle(interactionState, callback, event, gestureState) { if (interactionState.handle) { InteractionManager.clearInteractionHandle(interactionState.handle); interactionState.handle = null; } if (callback) { callback(event, gestureState); } } module.exports = PanResponder;
import BigInt from './big-integer'; describe('The big-integer module\'s returned object', () => { let bigI; beforeEach(() => { bigI = BigInt(42); }); afterEach(() => { bigI = null; }); it('is not a number', () => { expect(typeof 42).toBe('number'); expect(typeof bigI).not.toBe('number'); expect(typeof bigI).toBe('object'); }); it('can be compared to a stringified number by calling \'.toString()\'', () => { expect(bigI).not.toBe(42); expect(bigI).not.toBe('42'); expect(bigI.toString()).toBe('42'); // NOTE: // The '==' operator calls '.toString()' here in order to compare. expect(bigI == '42').toBe(true); // While the line above is easier to write and read, we will use the // 'expect(bigI.toString()).toBe(expected)' way so that test failure // messages will be more informative. Eg, // "Expected '84' to be '42'." instead of // "Expected false to be true." }); it('is immutable', () => { bigI.add(10); expect(bigI.toString()).toBe('42'); bigI.subtract(10); expect(bigI.toString()).toBe('42'); }); it('can add', () => { bigI = bigI.add(42); expect(bigI.toString()).toBe('84'); }); it('can perform power operations', () => { bigI = BigInt(10); bigI = bigI.pow(2); expect(bigI.toString()).toBe('100'); }); // ...see the official docs for more info, if you want. // The "Methods" section of the README is especially useful: // // https://github.com/peterolson/BigInteger.js#methods });
if(!window.calendar_languages) { window.calendar_languages = {}; } window.calendar_languages['de-DE'] = { error_noview: 'Kalender: Ansicht {0} nicht gefunden', error_dateformat: 'Kalender: Falsches Datumsformat {0}. Sollte entweder "now" oder "yyyy-mm-dd" sein', error_loadurl: 'Kalender: Event-URL nicht gesetzt.', error_where: 'Kalender: Falsche Navigationsrichtung {0}. Nur "next", "prev" oder "today" sind erlaubt', error_timedevide: 'Kalender: Parameter für die Zeiteinteilung muss ein Teiler von 60 sein. Beispielsweise 10, 15, 30', no_events_in_day: 'Keine Ereignisse an diesem Tag.', title_year: '{0}', title_month: '{0} {1}', title_week: '{0}. Kalenderwoche {1}', title_day: '{0}, der {1}. {2} {3}', week: 'KW {0}', all_day: 'Ganztägig', time: 'Zeit', events: 'Ereignisse', before_time: 'Endet vor Zeitspanne', after_time: 'Beginnt nach Zeitspanne', m0: 'Januar', m1: 'Februar', m2: 'März', m3: 'April', m4: 'Mai', m5: 'Juni', m6: 'Juli', m7: 'August', m8: 'September', m9: 'Oktober', m10: 'November', m11: 'Dezember', ms0: 'Jan', ms1: 'Feb', ms2: 'Mär', ms3: 'Apr', ms4: 'Mai', ms5: 'Jun', ms6: 'Jul', ms7: 'Aug', ms8: 'Sep', ms9: 'Okt', ms10: 'Nov', ms11: 'Dez', d0: 'Sonntag', d1: 'Montag', d2: 'Dienstag', d3: 'Mittwoch', d4: 'Donnerstag', d5: 'Freitag', d6: 'Samstag', first_day: 1, week_numbers_iso_8601: true, holidays: { '01-01': 'Neujahr', '06-01': 'Heilige Drei Könige', 'easter-3': 'Gründonnerstag', 'easter-2': 'Karfreitag', 'easter': 'Ostersonntag', 'easter+1': 'Ostermontag', '01-05': 'Tag der Arbeit', 'easter+39': 'Himmelfahrt', 'easter+49': 'Pfingstsonntag', 'easter+50': 'Pfingstmontag', '15-08': 'Mariä Himmelfahrt', '03-10': 'Tag der Deutschen Einheit', '01-11': 'Allerheiligen', '25-12': 'Erster Weihnachtsfeiertag', '26-12': 'Zweiter Weihnachtsfeiertag', } };
const NodeParentInterface = Jymfony.Component.Config.Definition.Builder.NodeParentInterface; const ExprBuilder = Jymfony.Component.Config.Definition.Builder.ExprBuilder; const MergeBuilder = Jymfony.Component.Config.Definition.Builder.MergeBuilder; const NormalizationBuilder = Jymfony.Component.Config.Definition.Builder.NormalizationBuilder; const ValidationBuilder = Jymfony.Component.Config.Definition.Builder.ValidationBuilder; /** * This class provides a fluent interface for defining a node. * * @memberOf Jymfony.Component.Config.Definition.Builder * @abstract */ export default class NodeDefinition extends implementationOf(NodeParentInterface) { /** * Constructor. * * @param {string} name * @param {Jymfony.Component.Config.Definition.Builder.NodeParentInterface} [parent] */ __construct(name, parent = undefined) { /** * @type {Jymfony.Component.Config.Definition.Builder.NodeParentInterface|undefined} * * @protected */ this._parent = parent; /** * @type {string} * * @protected */ this._name = name; /** * @type {Jymfony.Component.Config.Definition.Builder.NormalizationBuilder|undefined} * * @protected */ this._normalization = undefined; /** * @type {Jymfony.Component.Config.Definition.Builder.ValidationBuilder|undefined} * * @protected */ this._validation = undefined; /** * @type {*} * * @protected */ this._default = undefined; /** * @type {boolean} * * @protected */ this._isDefault = false; /** * @type {boolean} * * @protected */ this._required = false; /** * @type {string|undefined} * * @protected */ this._deprecationMessage = undefined; /** * @type {Jymfony.Component.Config.Definition.Builder.MergeBuilder|undefined} * * @protected */ this._merge = undefined; /** * @type {boolean} * * @protected */ this._allowEmptyValue = true; /** * @type {*} * * @protected */ this._nullEquivalent = undefined; /** * @type {*} * * @protected */ this._trueEquivalent = true; /** * @type {*} * * @protected */ this._falseEquivalent = false; /** * @type {Object} * * @protected */ this._attributes = {}; } /** * Sets the parent node. * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ setParent(parent) { this._parent = parent; return this; } /** * Sets info message. * * @param {string} info The info text * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ info(info) { return this.attribute('info', info); } /** * Sets example configuration. * * @param {string|array|Object} example * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ example(example) { return this.attribute('example', example); } /** * Sets an attribute on the node. * * @param {string} key * @param {*} value * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ attribute(key, value) { this._attributes[key] = value; return this; } /** * Returns the parent node. * * @returns {Jymfony.Component.Config.Definition.Builder.NodeParentInterface|undefined} */ end() { return this._parent; } /** * Creates the node. * * @param {boolean} [forceRootNode = false] Whether to force this node as the root node * * @returns {Jymfony.Component.Config.Definition.NodeInterface} */ getNode(forceRootNode = false) { if (forceRootNode) { this._parent = undefined; } if (undefined !== this._normalization) { this._normalization.$before = ExprBuilder.buildExpressions(this._normalization.$before); } if (undefined !== this._validation) { this._validation.rules = ExprBuilder.buildExpressions(this._validation.rules); } const node = this.createNode(); node.setAttributes(this._attributes); return node; } /** * Sets the default value. * * @param {*} value The default value * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ defaultValue(value) { this._isDefault = true; this._default = value; return this; } /** * Sets the node as required. * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ isRequired() { this._required = true; return this; } /** * Sets the node as deprecated. * * You can use %node% and %path% placeholders in your message to display, * respectively, the node name and its complete path. * * @param {string} [message = 'The child node "%node%" at path "%path%" is deprecated.'] Deprecation message * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ setDeprecated(message = 'The child node "%node%" at path "%path%" is deprecated.') { this._deprecationMessage = message; return this; } /** * Sets the equivalent value used when the node contains null. * * @param {*} value * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ treatNullLike(value) { this._nullEquivalent = value; return this; } /** * Sets the equivalent value used when the node contains true. * * @param {*} value * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ treatTrueLike(value) { this._trueEquivalent = value; return this; } /** * Sets the equivalent value used when the node contains false. * * @param {*} value * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ treatFalseLike(value) { this._falseEquivalent = value; return this; } /** * Sets null as the default value. * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ defaultNull() { return this.defaultValue(null); } /** * Sets undefined as the default value. * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ defaultUndefined() { return this.defaultValue(undefined); } /** * Sets true as the default value. * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ defaultTrue() { return this.defaultValue(true); } /** * Sets false as the default value. * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ defaultFalse() { return this.defaultValue(false); } /** * Sets an expression to run before the normalization. * * @returns {Jymfony.Component.Config.Definition.Builder.ExprBuilder} */ beforeNormalization() { return this.normalization().before(); } /** * Denies the node value being empty. * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ cannotBeEmpty() { this._allowEmptyValue = false; return this; } /** * Sets an expression to run for the validation. * * The expression receives the value of the node and must return it. It can modify it. * An exception should be thrown when the node is not valid. * * @returns {Jymfony.Component.Config.Definition.Builder.ExprBuilder} */ validate() { return this.validation().rule(); } /** * Sets whether the node can be overwritten. * * @param {boolean} [deny = true] Whether the overwriting is forbidden or not * * @returns {Jymfony.Component.Config.Definition.Builder.NodeDefinition} */ cannotBeOverwritten(deny = true) { this.merge().denyOverwrite(deny); return this; } /** * Gets the builder for validation rules. * * @returns {Jymfony.Component.Config.Definition.Builder.ValidationBuilder} * * @protected */ validation() { if (undefined === this._validation) { this._validation = new ValidationBuilder(this); } return this._validation; } /** * Gets the builder for merging rules. * * @returns {Jymfony.Component.Config.Definition.Builder.MergeBuilder} * * @protected */ merge() { if (undefined === this._merge) { this._merge = new MergeBuilder(this); } return this._merge; } /** * Gets the builder for normalization rules. * * @returns {Jymfony.Component.Config.Definition.Builder.NormalizationBuilder} * * @protected */ normalization() { if (undefined === this._normalization) { this._normalization = new NormalizationBuilder(this); } return this._normalization; } /** * Instantiate and configure the node according to this definition. * * @returns {Jymfony.Component.Config.Definition.NodeInterface} * * @throws {Jymfony.Component.Config.Exception.InvalidDefinitionException} When the definition is invalid * * @abstract * * @protected */ createNode() { throw new Error('createNode method must be implemented'); } }
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; // Simple tests of most basic domain functionality. const common = require('../common'); const assert = require('assert'); const domain = require('domain'); const d = new domain.Domain(); d.on('error', common.mustCall(function(er) { console.error('caught', er); assert.strictEqual(er.domain, d); assert.strictEqual(er.domainThrown, true); assert.ok(!er.domainEmitter); assert.strictEqual(er.code, 'ENOENT'); assert.ok(/\bthis file does not exist\b/i.test(er.path)); assert.strictEqual(typeof er.errno, 'number'); })); // implicit handling of thrown errors while in a domain, via the // single entry points of ReqWrap and MakeCallback. Even if // we try very hard to escape, there should be no way to, even if // we go many levels deep through timeouts and multiple IO calls. // Everything that happens between the domain.enter() and domain.exit() // calls will be bound to the domain, even if multiple levels of // handles are created. d.run(function() { setTimeout(function() { const fs = require('fs'); fs.readdir(__dirname, function() { fs.open('this file does not exist', 'r', function(er) { assert.ifError(er); throw new Error('should not get here!'); }); }); }, 100); });
import { RxApolloClient } from './RxApolloClient'; import { RxObservableQuery } from './RxObservableQuery'; import { rxify } from './rxify'; export { RxApolloClient, RxObservableQuery, rxify }; //# sourceMappingURL=index.js.map
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.io=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.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 = _dereq_('./lib/'); },{"./lib/":2}],2:[function(_dereq_,module,exports){ /** * Module dependencies. */ var url = _dereq_('./url'); var parser = _dereq_('socket.io-parser'); var Manager = _dereq_('./manager'); var debug = _dereq_('debug')('socket.io-client'); /** * Module exports. */ module.exports = exports = lookup; /** * Managers cache. */ var cache = exports.managers = {}; /** * Looks up an existing `Manager` for multiplexing. * If the user summons: * * `io('http://localhost/a');` * `io('http://localhost/b');` * * We reuse the existing instance based on same scheme/port/host, * and we initialize sockets for each namespace. * * @api public */ function lookup(uri, opts) { if (typeof uri == 'object') { opts = uri; uri = undefined; } opts = opts || {}; var parsed = url(uri); var source = parsed.source; var id = parsed.id; var io; if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) { debug('ignoring socket cache for %s', source); io = Manager(source, opts); } else { if (!cache[id]) { debug('new io instance for %s', source); cache[id] = Manager(source, opts); } io = cache[id]; } return io.socket(parsed.path); } /** * Protocol version. * * @api public */ exports.protocol = parser.protocol; /** * `connect`. * * @param {String} uri * @api public */ exports.connect = lookup; /** * Expose constructors for standalone build. * * @api public */ exports.Manager = _dereq_('./manager'); exports.Socket = _dereq_('./socket'); },{"./manager":3,"./socket":5,"./url":6,"debug":10,"socket.io-parser":44}],3:[function(_dereq_,module,exports){ /** * Module dependencies. */ var url = _dereq_('./url'); var eio = _dereq_('engine.io-client'); var Socket = _dereq_('./socket'); var Emitter = _dereq_('component-emitter'); var parser = _dereq_('socket.io-parser'); var on = _dereq_('./on'); var bind = _dereq_('component-bind'); var object = _dereq_('object-component'); var debug = _dereq_('debug')('socket.io-client:manager'); var indexOf = _dereq_('indexof'); var Backoff = _dereq_('backo2'); /** * Module exports */ module.exports = Manager; /** * `Manager` constructor. * * @param {String} engine instance or engine uri/opts * @param {Object} options * @api public */ function Manager(uri, opts){ if (!(this instanceof Manager)) return new Manager(uri, opts); if (uri && ('object' == typeof uri)) { opts = uri; uri = undefined; } opts = opts || {}; opts.path = opts.path || '/socket.io'; this.nsps = {}; this.subs = []; this.opts = opts; this.reconnection(opts.reconnection !== false); this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); this.reconnectionDelay(opts.reconnectionDelay || 1000); this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); this.randomizationFactor(opts.randomizationFactor || 0.5); this.backoff = new Backoff({ min: this.reconnectionDelay(), max: this.reconnectionDelayMax(), jitter: this.randomizationFactor() }); this.timeout(null == opts.timeout ? 20000 : opts.timeout); this.readyState = 'closed'; this.uri = uri; this.connected = []; this.encoding = false; this.packetBuffer = []; this.encoder = new parser.Encoder(); this.decoder = new parser.Decoder(); this.autoConnect = opts.autoConnect !== false; if (this.autoConnect) this.open(); } /** * Propagate given event to sockets and emit on `this` * * @api private */ Manager.prototype.emitAll = function() { this.emit.apply(this, arguments); for (var nsp in this.nsps) { this.nsps[nsp].emit.apply(this.nsps[nsp], arguments); } }; /** * Update `socket.id` of all sockets * * @api private */ Manager.prototype.updateSocketIds = function(){ for (var nsp in this.nsps) { this.nsps[nsp].id = this.engine.id; } }; /** * Mix in `Emitter`. */ Emitter(Manager.prototype); /** * Sets the `reconnection` config. * * @param {Boolean} true/false if it should automatically reconnect * @return {Manager} self or value * @api public */ Manager.prototype.reconnection = function(v){ if (!arguments.length) return this._reconnection; this._reconnection = !!v; return this; }; /** * Sets the reconnection attempts config. * * @param {Number} max reconnection attempts before giving up * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionAttempts = function(v){ if (!arguments.length) return this._reconnectionAttempts; this._reconnectionAttempts = v; return this; }; /** * Sets the delay between reconnections. * * @param {Number} delay * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionDelay = function(v){ if (!arguments.length) return this._reconnectionDelay; this._reconnectionDelay = v; this.backoff && this.backoff.setMin(v); return this; }; Manager.prototype.randomizationFactor = function(v){ if (!arguments.length) return this._randomizationFactor; this._randomizationFactor = v; this.backoff && this.backoff.setJitter(v); return this; }; /** * Sets the maximum delay between reconnections. * * @param {Number} delay * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionDelayMax = function(v){ if (!arguments.length) return this._reconnectionDelayMax; this._reconnectionDelayMax = v; this.backoff && this.backoff.setMax(v); return this; }; /** * Sets the connection timeout. `false` to disable * * @return {Manager} self or value * @api public */ Manager.prototype.timeout = function(v){ if (!arguments.length) return this._timeout; this._timeout = v; return this; }; /** * Starts trying to reconnect if reconnection is enabled and we have not * started reconnecting yet * * @api private */ Manager.prototype.maybeReconnectOnOpen = function() { // Only try to reconnect if it's the first time we're connecting if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) { // keeps reconnection from firing twice for the same reconnection loop this.reconnect(); } }; /** * Sets the current transport `socket`. * * @param {Function} optional, callback * @return {Manager} self * @api public */ Manager.prototype.open = Manager.prototype.connect = function(fn){ debug('readyState %s', this.readyState); if (~this.readyState.indexOf('open')) return this; debug('opening %s', this.uri); this.engine = eio(this.uri, this.opts); var socket = this.engine; var self = this; this.readyState = 'opening'; this.skipReconnect = false; // emit `open` var openSub = on(socket, 'open', function() { self.onopen(); fn && fn(); }); // emit `connect_error` var errorSub = on(socket, 'error', function(data){ debug('connect_error'); self.cleanup(); self.readyState = 'closed'; self.emitAll('connect_error', data); if (fn) { var err = new Error('Connection error'); err.data = data; fn(err); } else { // Only do this if there is no fn to handle the error self.maybeReconnectOnOpen(); } }); // emit `connect_timeout` if (false !== this._timeout) { var timeout = this._timeout; debug('connect attempt will timeout after %d', timeout); // set timer var timer = setTimeout(function(){ debug('connect attempt timed out after %d', timeout); openSub.destroy(); socket.close(); socket.emit('error', 'timeout'); self.emitAll('connect_timeout', timeout); }, timeout); this.subs.push({ destroy: function(){ clearTimeout(timer); } }); } this.subs.push(openSub); this.subs.push(errorSub); return this; }; /** * Called upon transport open. * * @api private */ Manager.prototype.onopen = function(){ debug('open'); // clear old subs this.cleanup(); // mark as open this.readyState = 'open'; this.emit('open'); // add new subs var socket = this.engine; this.subs.push(on(socket, 'data', bind(this, 'ondata'))); this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded'))); this.subs.push(on(socket, 'error', bind(this, 'onerror'))); this.subs.push(on(socket, 'close', bind(this, 'onclose'))); }; /** * Called with data. * * @api private */ Manager.prototype.ondata = function(data){ this.decoder.add(data); }; /** * Called when parser fully decodes a packet. * * @api private */ Manager.prototype.ondecoded = function(packet) { this.emit('packet', packet); }; /** * Called upon socket error. * * @api private */ Manager.prototype.onerror = function(err){ debug('error', err); this.emitAll('error', err); }; /** * Creates a new socket for the given `nsp`. * * @return {Socket} * @api public */ Manager.prototype.socket = function(nsp){ var socket = this.nsps[nsp]; if (!socket) { socket = new Socket(this, nsp); this.nsps[nsp] = socket; var self = this; socket.on('connect', function(){ socket.id = self.engine.id; if (!~indexOf(self.connected, socket)) { self.connected.push(socket); } }); } return socket; }; /** * Called upon a socket close. * * @param {Socket} socket */ Manager.prototype.destroy = function(socket){ var index = indexOf(this.connected, socket); if (~index) this.connected.splice(index, 1); if (this.connected.length) return; this.close(); }; /** * Writes a packet. * * @param {Object} packet * @api private */ Manager.prototype.packet = function(packet){ debug('writing packet %j', packet); var self = this; if (!self.encoding) { // encode, then write to engine with result self.encoding = true; this.encoder.encode(packet, function(encodedPackets) { for (var i = 0; i < encodedPackets.length; i++) { self.engine.write(encodedPackets[i]); } self.encoding = false; self.processPacketQueue(); }); } else { // add packet to the queue self.packetBuffer.push(packet); } }; /** * If packet buffer is non-empty, begins encoding the * next packet in line. * * @api private */ Manager.prototype.processPacketQueue = function() { if (this.packetBuffer.length > 0 && !this.encoding) { var pack = this.packetBuffer.shift(); this.packet(pack); } }; /** * Clean up transport subscriptions and packet buffer. * * @api private */ Manager.prototype.cleanup = function(){ var sub; while (sub = this.subs.shift()) sub.destroy(); this.packetBuffer = []; this.encoding = false; this.decoder.destroy(); }; /** * Close the current socket. * * @api private */ Manager.prototype.close = Manager.prototype.disconnect = function(){ this.skipReconnect = true; this.backoff.reset(); this.readyState = 'closed'; this.engine && this.engine.close(); }; /** * Called upon engine close. * * @api private */ Manager.prototype.onclose = function(reason){ debug('close'); this.cleanup(); this.backoff.reset(); this.readyState = 'closed'; this.emit('close', reason); if (this._reconnection && !this.skipReconnect) { this.reconnect(); } }; /** * Attempt a reconnection. * * @api private */ Manager.prototype.reconnect = function(){ if (this.reconnecting || this.skipReconnect) return this; var self = this; if (this.backoff.attempts >= this._reconnectionAttempts) { debug('reconnect failed'); this.backoff.reset(); this.emitAll('reconnect_failed'); this.reconnecting = false; } else { var delay = this.backoff.duration(); debug('will wait %dms before reconnect attempt', delay); this.reconnecting = true; var timer = setTimeout(function(){ if (self.skipReconnect) return; debug('attempting reconnect'); self.emitAll('reconnect_attempt', self.backoff.attempts); self.emitAll('reconnecting', self.backoff.attempts); // check again for the case socket closed in above events if (self.skipReconnect) return; self.open(function(err){ if (err) { debug('reconnect attempt error'); self.reconnecting = false; self.reconnect(); self.emitAll('reconnect_error', err.data); } else { debug('reconnect success'); self.onreconnect(); } }); }, delay); this.subs.push({ destroy: function(){ clearTimeout(timer); } }); } }; /** * Called upon successful reconnect. * * @api private */ Manager.prototype.onreconnect = function(){ var attempt = this.backoff.attempts; this.reconnecting = false; this.backoff.reset(); this.updateSocketIds(); this.emitAll('reconnect', attempt); }; },{"./on":4,"./socket":5,"./url":6,"backo2":7,"component-bind":8,"component-emitter":9,"debug":10,"engine.io-client":11,"indexof":40,"object-component":41,"socket.io-parser":44}],4:[function(_dereq_,module,exports){ /** * Module exports. */ module.exports = on; /** * Helper for subscriptions. * * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter` * @param {String} event name * @param {Function} callback * @api public */ function on(obj, ev, fn) { obj.on(ev, fn); return { destroy: function(){ obj.removeListener(ev, fn); } }; } },{}],5:[function(_dereq_,module,exports){ /** * Module dependencies. */ var parser = _dereq_('socket.io-parser'); var Emitter = _dereq_('component-emitter'); var toArray = _dereq_('to-array'); var on = _dereq_('./on'); var bind = _dereq_('component-bind'); var debug = _dereq_('debug')('socket.io-client:socket'); var hasBin = _dereq_('has-binary'); /** * Module exports. */ module.exports = exports = Socket; /** * Internal events (blacklisted). * These events can't be emitted by the user. * * @api private */ var events = { connect: 1, connect_error: 1, connect_timeout: 1, disconnect: 1, error: 1, reconnect: 1, reconnect_attempt: 1, reconnect_failed: 1, reconnect_error: 1, reconnecting: 1 }; /** * Shortcut to `Emitter#emit`. */ var emit = Emitter.prototype.emit; /** * `Socket` constructor. * * @api public */ function Socket(io, nsp){ this.io = io; this.nsp = nsp; this.json = this; // compat this.ids = 0; this.acks = {}; if (this.io.autoConnect) this.open(); this.receiveBuffer = []; this.sendBuffer = []; this.connected = false; this.disconnected = true; } /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Subscribe to open, close and packet events * * @api private */ Socket.prototype.subEvents = function() { if (this.subs) return; var io = this.io; this.subs = [ on(io, 'open', bind(this, 'onopen')), on(io, 'packet', bind(this, 'onpacket')), on(io, 'close', bind(this, 'onclose')) ]; }; /** * "Opens" the socket. * * @api public */ Socket.prototype.open = Socket.prototype.connect = function(){ if (this.connected) return this; this.subEvents(); this.io.open(); // ensure open if ('open' == this.io.readyState) this.onopen(); return this; }; /** * Sends a `message` event. * * @return {Socket} self * @api public */ Socket.prototype.send = function(){ var args = toArray(arguments); args.unshift('message'); this.emit.apply(this, args); return this; }; /** * Override `emit`. * If the event is in `events`, it's emitted normally. * * @param {String} event name * @return {Socket} self * @api public */ Socket.prototype.emit = function(ev){ if (events.hasOwnProperty(ev)) { emit.apply(this, arguments); return this; } var args = toArray(arguments); var parserType = parser.EVENT; // default if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary var packet = { type: parserType, data: args }; // event ack callback if ('function' == typeof args[args.length - 1]) { debug('emitting packet with ack id %d', this.ids); this.acks[this.ids] = args.pop(); packet.id = this.ids++; } if (this.connected) { this.packet(packet); } else { this.sendBuffer.push(packet); } return this; }; /** * Sends a packet. * * @param {Object} packet * @api private */ Socket.prototype.packet = function(packet){ packet.nsp = this.nsp; this.io.packet(packet); }; /** * Called upon engine `open`. * * @api private */ Socket.prototype.onopen = function(){ debug('transport is open - connecting'); // write connect packet if necessary if ('/' != this.nsp) { this.packet({ type: parser.CONNECT }); } }; /** * Called upon engine `close`. * * @param {String} reason * @api private */ Socket.prototype.onclose = function(reason){ debug('close (%s)', reason); this.connected = false; this.disconnected = true; delete this.id; this.emit('disconnect', reason); }; /** * Called with socket packet. * * @param {Object} packet * @api private */ Socket.prototype.onpacket = function(packet){ if (packet.nsp != this.nsp) return; switch (packet.type) { case parser.CONNECT: this.onconnect(); break; case parser.EVENT: this.onevent(packet); break; case parser.BINARY_EVENT: this.onevent(packet); break; case parser.ACK: this.onack(packet); break; case parser.BINARY_ACK: this.onack(packet); break; case parser.DISCONNECT: this.ondisconnect(); break; case parser.ERROR: this.emit('error', packet.data); break; } }; /** * Called upon a server event. * * @param {Object} packet * @api private */ Socket.prototype.onevent = function(packet){ var args = packet.data || []; debug('emitting event %j', args); if (null != packet.id) { debug('attaching ack callback to event'); args.push(this.ack(packet.id)); } if (this.connected) { emit.apply(this, args); } else { this.receiveBuffer.push(args); } }; /** * Produces an ack callback to emit with an event. * * @api private */ Socket.prototype.ack = function(id){ var self = this; var sent = false; return function(){ // prevent double callbacks if (sent) return; sent = true; var args = toArray(arguments); debug('sending ack %j', args); var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK; self.packet({ type: type, id: id, data: args }); }; }; /** * Called upon a server acknowlegement. * * @param {Object} packet * @api private */ Socket.prototype.onack = function(packet){ debug('calling ack %s with %j', packet.id, packet.data); var fn = this.acks[packet.id]; fn.apply(this, packet.data); delete this.acks[packet.id]; }; /** * Called upon server connect. * * @api private */ Socket.prototype.onconnect = function(){ this.connected = true; this.disconnected = false; this.emit('connect'); this.emitBuffered(); }; /** * Emit buffered events (received and emitted). * * @api private */ Socket.prototype.emitBuffered = function(){ var i; for (i = 0; i < this.receiveBuffer.length; i++) { emit.apply(this, this.receiveBuffer[i]); } this.receiveBuffer = []; for (i = 0; i < this.sendBuffer.length; i++) { this.packet(this.sendBuffer[i]); } this.sendBuffer = []; }; /** * Called upon server disconnect. * * @api private */ Socket.prototype.ondisconnect = function(){ debug('server disconnect (%s)', this.nsp); this.destroy(); this.onclose('io server disconnect'); }; /** * Called upon forced client/server side disconnections, * this method ensures the manager stops tracking us and * that reconnections don't get triggered for this. * * @api private. */ Socket.prototype.destroy = function(){ if (this.subs) { // clean subscriptions to avoid reconnections for (var i = 0; i < this.subs.length; i++) { this.subs[i].destroy(); } this.subs = null; } this.io.destroy(this); }; /** * Disconnects the socket manually. * * @return {Socket} self * @api public */ Socket.prototype.close = Socket.prototype.disconnect = function(){ if (this.connected) { debug('performing disconnect (%s)', this.nsp); this.packet({ type: parser.DISCONNECT }); } // remove socket from pool this.destroy(); if (this.connected) { // fire events this.onclose('io client disconnect'); } return this; }; },{"./on":4,"component-bind":8,"component-emitter":9,"debug":10,"has-binary":36,"socket.io-parser":44,"to-array":48}],6:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies. */ var parseuri = _dereq_('parseuri'); var debug = _dereq_('debug')('socket.io-client:url'); /** * Module exports. */ module.exports = url; /** * URL parser. * * @param {String} url * @param {Object} An object meant to mimic window.location. * Defaults to window.location. * @api public */ function url(uri, loc){ var obj = uri; // default to window.location var loc = loc || global.location; if (null == uri) uri = loc.protocol + '//' + loc.host; // relative path support if ('string' == typeof uri) { if ('/' == uri.charAt(0)) { if ('/' == uri.charAt(1)) { uri = loc.protocol + uri; } else { uri = loc.hostname + uri; } } if (!/^(https?|wss?):\/\//.test(uri)) { debug('protocol-less url %s', uri); if ('undefined' != typeof loc) { uri = loc.protocol + '//' + uri; } else { uri = 'https://' + uri; } } // parse debug('parse %s', uri); obj = parseuri(uri); } // make sure we treat `localhost:80` and `localhost` equally if (!obj.port) { if (/^(http|ws)$/.test(obj.protocol)) { obj.port = '80'; } else if (/^(http|ws)s$/.test(obj.protocol)) { obj.port = '443'; } } obj.path = obj.path || '/'; // define unique id obj.id = obj.protocol + '://' + obj.host + ':' + obj.port; // define href obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port)); return obj; } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"debug":10,"parseuri":42}],7:[function(_dereq_,module,exports){ /** * Expose `Backoff`. */ module.exports = Backoff; /** * Initialize backoff timer with `opts`. * * - `min` initial timeout in milliseconds [100] * - `max` max timeout [10000] * - `jitter` [0] * - `factor` [2] * * @param {Object} opts * @api public */ function Backoff(opts) { opts = opts || {}; this.ms = opts.min || 100; this.max = opts.max || 10000; this.factor = opts.factor || 2; this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; this.attempts = 0; } /** * Return the backoff duration. * * @return {Number} * @api public */ Backoff.prototype.duration = function(){ var ms = this.ms * Math.pow(this.factor, this.attempts++); if (this.jitter) { var rand = Math.random(); var deviation = Math.floor(rand * this.jitter * ms); ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; } return Math.min(ms, this.max) | 0; }; /** * Reset the number of attempts. * * @api public */ Backoff.prototype.reset = function(){ this.attempts = 0; }; /** * Set the minimum duration * * @api public */ Backoff.prototype.setMin = function(min){ this.ms = min; }; /** * Set the maximum duration * * @api public */ Backoff.prototype.setMax = function(max){ this.max = max; }; /** * Set the jitter * * @api public */ Backoff.prototype.setJitter = function(jitter){ this.jitter = jitter; }; },{}],8:[function(_dereq_,module,exports){ /** * Slice reference. */ var slice = [].slice; /** * Bind `obj` to `fn`. * * @param {Object} obj * @param {Function|String} fn or string * @return {Function} * @api public */ module.exports = function(obj, fn){ if ('string' == typeof fn) fn = obj[fn]; if ('function' != typeof fn) throw new Error('bind() requires a function'); var args = slice.call(arguments, 2); return function(){ return fn.apply(obj, args.concat(slice.call(arguments))); } }; },{}],9:[function(_dereq_,module,exports){ /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{}],10:[function(_dereq_,module,exports){ /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { if (!debug.enabled(name)) return function(){}; return function(fmt){ fmt = coerce(fmt); var curr = new Date; var ms = curr - (debug[name] || curr); debug[name] = curr; fmt = name + ' ' + fmt + ' +' + debug.humanize(ms); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ debug.enable = function(name) { try { localStorage.debug = name; } catch(e){} var split = (name || '').split(/[\s,]+/) , len = split.length; for (var i = 0; i < len; i++) { name = split[i].replace('*', '.*?'); if (name[0] === '-') { debug.skips.push(new RegExp('^' + name.substr(1) + '$')); } else { debug.names.push(new RegExp('^' + name + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ debug.enabled = function(name) { for (var i = 0, len = debug.skips.length; i < len; i++) { if (debug.skips[i].test(name)) { return false; } } for (var i = 0, len = debug.names.length; i < len; i++) { if (debug.names[i].test(name)) { return true; } } return false; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} },{}],11:[function(_dereq_,module,exports){ module.exports = _dereq_('./lib/'); },{"./lib/":12}],12:[function(_dereq_,module,exports){ module.exports = _dereq_('./socket'); /** * Exports parser * * @api public * */ module.exports.parser = _dereq_('engine.io-parser'); },{"./socket":13,"engine.io-parser":25}],13:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies. */ var transports = _dereq_('./transports'); var Emitter = _dereq_('component-emitter'); var debug = _dereq_('debug')('engine.io-client:socket'); var index = _dereq_('indexof'); var parser = _dereq_('engine.io-parser'); var parseuri = _dereq_('parseuri'); var parsejson = _dereq_('parsejson'); var parseqs = _dereq_('parseqs'); /** * Module exports. */ module.exports = Socket; /** * Noop function. * * @api private */ function noop(){} /** * Socket constructor. * * @param {String|Object} uri or options * @param {Object} options * @api public */ function Socket(uri, opts){ if (!(this instanceof Socket)) return new Socket(uri, opts); opts = opts || {}; if (uri && 'object' == typeof uri) { opts = uri; uri = null; } if (uri) { uri = parseuri(uri); opts.host = uri.host; opts.secure = uri.protocol == 'https' || uri.protocol == 'wss'; opts.port = uri.port; if (uri.query) opts.query = uri.query; } this.secure = null != opts.secure ? opts.secure : (global.location && 'https:' == location.protocol); if (opts.host) { var pieces = opts.host.split(':'); opts.hostname = pieces.shift(); if (pieces.length) { opts.port = pieces.pop(); } else if (!opts.port) { // if no port is specified manually, use the protocol default opts.port = this.secure ? '443' : '80'; } } this.agent = opts.agent || false; this.hostname = opts.hostname || (global.location ? location.hostname : 'localhost'); this.port = opts.port || (global.location && location.port ? location.port : (this.secure ? 443 : 80)); this.query = opts.query || {}; if ('string' == typeof this.query) this.query = parseqs.decode(this.query); this.upgrade = false !== opts.upgrade; this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; this.forceJSONP = !!opts.forceJSONP; this.jsonp = false !== opts.jsonp; this.forceBase64 = !!opts.forceBase64; this.enablesXDR = !!opts.enablesXDR; this.timestampParam = opts.timestampParam || 't'; this.timestampRequests = opts.timestampRequests; this.transports = opts.transports || ['polling', 'websocket']; this.readyState = ''; this.writeBuffer = []; this.callbackBuffer = []; this.policyPort = opts.policyPort || 843; this.rememberUpgrade = opts.rememberUpgrade || false; this.binaryType = null; this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; // SSL options for Node.js client this.pfx = opts.pfx || null; this.key = opts.key || null; this.passphrase = opts.passphrase || null; this.cert = opts.cert || null; this.ca = opts.ca || null; this.ciphers = opts.ciphers || null; this.rejectUnauthorized = opts.rejectUnauthorized || null; this.open(); } Socket.priorWebsocketSuccess = false; /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Protocol version. * * @api public */ Socket.protocol = parser.protocol; // this is an int /** * Expose deps for legacy compatibility * and standalone browser access. */ Socket.Socket = Socket; Socket.Transport = _dereq_('./transport'); Socket.transports = _dereq_('./transports'); Socket.parser = _dereq_('engine.io-parser'); /** * Creates transport of the given type. * * @param {String} transport name * @return {Transport} * @api private */ Socket.prototype.createTransport = function (name) { debug('creating transport "%s"', name); var query = clone(this.query); // append engine.io protocol identifier query.EIO = parser.protocol; // transport name query.transport = name; // session id if we already have one if (this.id) query.sid = this.id; var transport = new transports[name]({ agent: this.agent, hostname: this.hostname, port: this.port, secure: this.secure, path: this.path, query: query, forceJSONP: this.forceJSONP, jsonp: this.jsonp, forceBase64: this.forceBase64, enablesXDR: this.enablesXDR, timestampRequests: this.timestampRequests, timestampParam: this.timestampParam, policyPort: this.policyPort, socket: this, pfx: this.pfx, key: this.key, passphrase: this.passphrase, cert: this.cert, ca: this.ca, ciphers: this.ciphers, rejectUnauthorized: this.rejectUnauthorized }); return transport; }; function clone (obj) { var o = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { o[i] = obj[i]; } } return o; } /** * Initializes transport to use and starts probe. * * @api private */ Socket.prototype.open = function () { var transport; if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) { transport = 'websocket'; } else if (0 == this.transports.length) { // Emit error on next tick so it can be listened to var self = this; setTimeout(function() { self.emit('error', 'No transports available'); }, 0); return; } else { transport = this.transports[0]; } this.readyState = 'opening'; // Retry with the next transport if the transport is disabled (jsonp: false) var transport; try { transport = this.createTransport(transport); } catch (e) { this.transports.shift(); this.open(); return; } transport.open(); this.setTransport(transport); }; /** * Sets the current transport. Disables the existing one (if any). * * @api private */ Socket.prototype.setTransport = function(transport){ debug('setting transport %s', transport.name); var self = this; if (this.transport) { debug('clearing existing transport %s', this.transport.name); this.transport.removeAllListeners(); } // set up transport this.transport = transport; // set up transport listeners transport .on('drain', function(){ self.onDrain(); }) .on('packet', function(packet){ self.onPacket(packet); }) .on('error', function(e){ self.onError(e); }) .on('close', function(){ self.onClose('transport close'); }); }; /** * Probes a transport. * * @param {String} transport name * @api private */ Socket.prototype.probe = function (name) { debug('probing transport "%s"', name); var transport = this.createTransport(name, { probe: 1 }) , failed = false , self = this; Socket.priorWebsocketSuccess = false; function onTransportOpen(){ if (self.onlyBinaryUpgrades) { var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; failed = failed || upgradeLosesBinary; } if (failed) return; debug('probe transport "%s" opened', name); transport.send([{ type: 'ping', data: 'probe' }]); transport.once('packet', function (msg) { if (failed) return; if ('pong' == msg.type && 'probe' == msg.data) { debug('probe transport "%s" pong', name); self.upgrading = true; self.emit('upgrading', transport); if (!transport) return; Socket.priorWebsocketSuccess = 'websocket' == transport.name; debug('pausing current transport "%s"', self.transport.name); self.transport.pause(function () { if (failed) return; if ('closed' == self.readyState) return; debug('changing transport and sending upgrade packet'); cleanup(); self.setTransport(transport); transport.send([{ type: 'upgrade' }]); self.emit('upgrade', transport); transport = null; self.upgrading = false; self.flush(); }); } else { debug('probe transport "%s" failed', name); var err = new Error('probe error'); err.transport = transport.name; self.emit('upgradeError', err); } }); } function freezeTransport() { if (failed) return; // Any callback called by transport should be ignored since now failed = true; cleanup(); transport.close(); transport = null; } //Handle any error that happens while probing function onerror(err) { var error = new Error('probe error: ' + err); error.transport = transport.name; freezeTransport(); debug('probe transport "%s" failed because of error: %s', name, err); self.emit('upgradeError', error); } function onTransportClose(){ onerror("transport closed"); } //When the socket is closed while we're probing function onclose(){ onerror("socket closed"); } //When the socket is upgraded while we're probing function onupgrade(to){ if (transport && to.name != transport.name) { debug('"%s" works - aborting "%s"', to.name, transport.name); freezeTransport(); } } //Remove all listeners on the transport and on self function cleanup(){ transport.removeListener('open', onTransportOpen); transport.removeListener('error', onerror); transport.removeListener('close', onTransportClose); self.removeListener('close', onclose); self.removeListener('upgrading', onupgrade); } transport.once('open', onTransportOpen); transport.once('error', onerror); transport.once('close', onTransportClose); this.once('close', onclose); this.once('upgrading', onupgrade); transport.open(); }; /** * Called when connection is deemed open. * * @api public */ Socket.prototype.onOpen = function () { debug('socket open'); this.readyState = 'open'; Socket.priorWebsocketSuccess = 'websocket' == this.transport.name; this.emit('open'); this.flush(); // we check for `readyState` in case an `open` // listener already closed the socket if ('open' == this.readyState && this.upgrade && this.transport.pause) { debug('starting upgrade probes'); for (var i = 0, l = this.upgrades.length; i < l; i++) { this.probe(this.upgrades[i]); } } }; /** * Handles a packet. * * @api private */ Socket.prototype.onPacket = function (packet) { if ('opening' == this.readyState || 'open' == this.readyState) { debug('socket receive: type "%s", data "%s"', packet.type, packet.data); this.emit('packet', packet); // Socket is live - any packet counts this.emit('heartbeat'); switch (packet.type) { case 'open': this.onHandshake(parsejson(packet.data)); break; case 'pong': this.setPing(); break; case 'error': var err = new Error('server error'); err.code = packet.data; this.emit('error', err); break; case 'message': this.emit('data', packet.data); this.emit('message', packet.data); break; } } else { debug('packet received with socket readyState "%s"', this.readyState); } }; /** * Called upon handshake completion. * * @param {Object} handshake obj * @api private */ Socket.prototype.onHandshake = function (data) { this.emit('handshake', data); this.id = data.sid; this.transport.query.sid = data.sid; this.upgrades = this.filterUpgrades(data.upgrades); this.pingInterval = data.pingInterval; this.pingTimeout = data.pingTimeout; this.onOpen(); // In case open handler closes socket if ('closed' == this.readyState) return; this.setPing(); // Prolong liveness of socket on heartbeat this.removeListener('heartbeat', this.onHeartbeat); this.on('heartbeat', this.onHeartbeat); }; /** * Resets ping timeout. * * @api private */ Socket.prototype.onHeartbeat = function (timeout) { clearTimeout(this.pingTimeoutTimer); var self = this; self.pingTimeoutTimer = setTimeout(function () { if ('closed' == self.readyState) return; self.onClose('ping timeout'); }, timeout || (self.pingInterval + self.pingTimeout)); }; /** * Pings server every `this.pingInterval` and expects response * within `this.pingTimeout` or closes connection. * * @api private */ Socket.prototype.setPing = function () { var self = this; clearTimeout(self.pingIntervalTimer); self.pingIntervalTimer = setTimeout(function () { debug('writing ping packet - expecting pong within %sms', self.pingTimeout); self.ping(); self.onHeartbeat(self.pingTimeout); }, self.pingInterval); }; /** * Sends a ping packet. * * @api public */ Socket.prototype.ping = function () { this.sendPacket('ping'); }; /** * Called on `drain` event * * @api private */ Socket.prototype.onDrain = function() { for (var i = 0; i < this.prevBufferLen; i++) { if (this.callbackBuffer[i]) { this.callbackBuffer[i](); } } this.writeBuffer.splice(0, this.prevBufferLen); this.callbackBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important // for example, when upgrading, upgrade packet is sent over, // and a nonzero prevBufferLen could cause problems on `drain` this.prevBufferLen = 0; if (this.writeBuffer.length == 0) { this.emit('drain'); } else { this.flush(); } }; /** * Flush write buffers. * * @api private */ Socket.prototype.flush = function () { if ('closed' != this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) { debug('flushing %d packets in socket', this.writeBuffer.length); this.transport.send(this.writeBuffer); // keep track of current length of writeBuffer // splice writeBuffer and callbackBuffer on `drain` this.prevBufferLen = this.writeBuffer.length; this.emit('flush'); } }; /** * Sends a message. * * @param {String} message. * @param {Function} callback function. * @return {Socket} for chaining. * @api public */ Socket.prototype.write = Socket.prototype.send = function (msg, fn) { this.sendPacket('message', msg, fn); return this; }; /** * Sends a packet. * * @param {String} packet type. * @param {String} data. * @param {Function} callback function. * @api private */ Socket.prototype.sendPacket = function (type, data, fn) { if ('closing' == this.readyState || 'closed' == this.readyState) { return; } var packet = { type: type, data: data }; this.emit('packetCreate', packet); this.writeBuffer.push(packet); this.callbackBuffer.push(fn); this.flush(); }; /** * Closes the connection. * * @api private */ Socket.prototype.close = function () { if ('opening' == this.readyState || 'open' == this.readyState) { this.readyState = 'closing'; var self = this; function close() { self.onClose('forced close'); debug('socket closing - telling transport to close'); self.transport.close(); } function cleanupAndClose() { self.removeListener('upgrade', cleanupAndClose); self.removeListener('upgradeError', cleanupAndClose); close(); } function waitForUpgrade() { // wait for upgrade to finish since we can't send packets while pausing a transport self.once('upgrade', cleanupAndClose); self.once('upgradeError', cleanupAndClose); } if (this.writeBuffer.length) { this.once('drain', function() { if (this.upgrading) { waitForUpgrade(); } else { close(); } }); } else if (this.upgrading) { waitForUpgrade(); } else { close(); } } return this; }; /** * Called upon transport error * * @api private */ Socket.prototype.onError = function (err) { debug('socket error %j', err); Socket.priorWebsocketSuccess = false; this.emit('error', err); this.onClose('transport error', err); }; /** * Called upon transport close. * * @api private */ Socket.prototype.onClose = function (reason, desc) { if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) { debug('socket close with reason: "%s"', reason); var self = this; // clear timers clearTimeout(this.pingIntervalTimer); clearTimeout(this.pingTimeoutTimer); // clean buffers in next tick, so developers can still // grab the buffers on `close` event setTimeout(function() { self.writeBuffer = []; self.callbackBuffer = []; self.prevBufferLen = 0; }, 0); // stop event from firing again for transport this.transport.removeAllListeners('close'); // ensure transport won't stay open this.transport.close(); // ignore further transport communication this.transport.removeAllListeners(); // set ready state this.readyState = 'closed'; // clear session id this.id = null; // emit close event this.emit('close', reason, desc); } }; /** * Filters upgrades, returning only those matching client transports. * * @param {Array} server upgrades * @api private * */ Socket.prototype.filterUpgrades = function (upgrades) { var filteredUpgrades = []; for (var i = 0, j = upgrades.length; i<j; i++) { if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); } return filteredUpgrades; }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./transport":14,"./transports":15,"component-emitter":9,"debug":22,"engine.io-parser":25,"indexof":40,"parsejson":32,"parseqs":33,"parseuri":34}],14:[function(_dereq_,module,exports){ /** * Module dependencies. */ var parser = _dereq_('engine.io-parser'); var Emitter = _dereq_('component-emitter'); /** * Module exports. */ module.exports = Transport; /** * Transport abstract constructor. * * @param {Object} options. * @api private */ function Transport (opts) { this.path = opts.path; this.hostname = opts.hostname; this.port = opts.port; this.secure = opts.secure; this.query = opts.query; this.timestampParam = opts.timestampParam; this.timestampRequests = opts.timestampRequests; this.readyState = ''; this.agent = opts.agent || false; this.socket = opts.socket; this.enablesXDR = opts.enablesXDR; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; } /** * Mix in `Emitter`. */ Emitter(Transport.prototype); /** * A counter used to prevent collisions in the timestamps used * for cache busting. */ Transport.timestamps = 0; /** * Emits an error. * * @param {String} str * @return {Transport} for chaining * @api public */ Transport.prototype.onError = function (msg, desc) { var err = new Error(msg); err.type = 'TransportError'; err.description = desc; this.emit('error', err); return this; }; /** * Opens the transport. * * @api public */ Transport.prototype.open = function () { if ('closed' == this.readyState || '' == this.readyState) { this.readyState = 'opening'; this.doOpen(); } return this; }; /** * Closes the transport. * * @api private */ Transport.prototype.close = function () { if ('opening' == this.readyState || 'open' == this.readyState) { this.doClose(); this.onClose(); } return this; }; /** * Sends multiple packets. * * @param {Array} packets * @api private */ Transport.prototype.send = function(packets){ if ('open' == this.readyState) { this.write(packets); } else { throw new Error('Transport not open'); } }; /** * Called upon open * * @api private */ Transport.prototype.onOpen = function () { this.readyState = 'open'; this.writable = true; this.emit('open'); }; /** * Called with data. * * @param {String} data * @api private */ Transport.prototype.onData = function(data){ var packet = parser.decodePacket(data, this.socket.binaryType); this.onPacket(packet); }; /** * Called with a decoded packet. */ Transport.prototype.onPacket = function (packet) { this.emit('packet', packet); }; /** * Called upon close. * * @api private */ Transport.prototype.onClose = function () { this.readyState = 'closed'; this.emit('close'); }; },{"component-emitter":9,"engine.io-parser":25}],15:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies */ var XMLHttpRequest = _dereq_('xmlhttprequest'); var XHR = _dereq_('./polling-xhr'); var JSONP = _dereq_('./polling-jsonp'); var websocket = _dereq_('./websocket'); /** * Export transports. */ exports.polling = polling; exports.websocket = websocket; /** * Polling transport polymorphic constructor. * Decides on xhr vs jsonp based on feature detection. * * @api private */ function polling(opts){ var xhr; var xd = false; var xs = false; var jsonp = false !== opts.jsonp; if (global.location) { var isSSL = 'https:' == location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } xd = opts.hostname != location.hostname || port != opts.port; xs = opts.secure != isSSL; } opts.xdomain = xd; opts.xscheme = xs; xhr = new XMLHttpRequest(opts); if ('open' in xhr && !opts.forceJSONP) { return new XHR(opts); } else { if (!jsonp) throw new Error('JSONP disabled'); return new JSONP(opts); } } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./polling-jsonp":16,"./polling-xhr":17,"./websocket":19,"xmlhttprequest":20}],16:[function(_dereq_,module,exports){ (function (global){ /** * Module requirements. */ var Polling = _dereq_('./polling'); var inherit = _dereq_('component-inherit'); /** * Module exports. */ module.exports = JSONPPolling; /** * Cached regular expressions. */ var rNewline = /\n/g; var rEscapedNewline = /\\n/g; /** * Global JSONP callbacks. */ var callbacks; /** * Callbacks count. */ var index = 0; /** * Noop. */ function empty () { } /** * JSONP Polling constructor. * * @param {Object} opts. * @api public */ function JSONPPolling (opts) { Polling.call(this, opts); this.query = this.query || {}; // define global callbacks array if not present // we do this here (lazily) to avoid unneeded global pollution if (!callbacks) { // we need to consider multiple engines in the same page if (!global.___eio) global.___eio = []; callbacks = global.___eio; } // callback identifier this.index = callbacks.length; // add callback to jsonp global var self = this; callbacks.push(function (msg) { self.onData(msg); }); // append to query string this.query.j = this.index; // prevent spurious errors from being emitted when the window is unloaded if (global.document && global.addEventListener) { global.addEventListener('beforeunload', function () { if (self.script) self.script.onerror = empty; }, false); } } /** * Inherits from Polling. */ inherit(JSONPPolling, Polling); /* * JSONP only supports binary as base64 encoded strings */ JSONPPolling.prototype.supportsBinary = false; /** * Closes the socket. * * @api private */ JSONPPolling.prototype.doClose = function () { if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } if (this.form) { this.form.parentNode.removeChild(this.form); this.form = null; this.iframe = null; } Polling.prototype.doClose.call(this); }; /** * Starts a poll cycle. * * @api private */ JSONPPolling.prototype.doPoll = function () { var self = this; var script = document.createElement('script'); if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } script.async = true; script.src = this.uri(); script.onerror = function(e){ self.onError('jsonp poll error',e); }; var insertAt = document.getElementsByTagName('script')[0]; insertAt.parentNode.insertBefore(script, insertAt); this.script = script; var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent); if (isUAgecko) { setTimeout(function () { var iframe = document.createElement('iframe'); document.body.appendChild(iframe); document.body.removeChild(iframe); }, 100); } }; /** * Writes with a hidden iframe. * * @param {String} data to send * @param {Function} called upon flush. * @api private */ JSONPPolling.prototype.doWrite = function (data, fn) { var self = this; if (!this.form) { var form = document.createElement('form'); var area = document.createElement('textarea'); var id = this.iframeId = 'eio_iframe_' + this.index; var iframe; form.className = 'socketio'; form.style.position = 'absolute'; form.style.top = '-1000px'; form.style.left = '-1000px'; form.target = id; form.method = 'POST'; form.setAttribute('accept-charset', 'utf-8'); area.name = 'd'; form.appendChild(area); document.body.appendChild(form); this.form = form; this.area = area; } this.form.action = this.uri(); function complete () { initIframe(); fn(); } function initIframe () { if (self.iframe) { try { self.form.removeChild(self.iframe); } catch (e) { self.onError('jsonp polling iframe removal error', e); } } try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">'; iframe = document.createElement(html); } catch (e) { iframe = document.createElement('iframe'); iframe.name = self.iframeId; iframe.src = 'javascript:0'; } iframe.id = self.iframeId; self.form.appendChild(iframe); self.iframe = iframe; } initIframe(); // escape \n to prevent it from being converted into \r\n by some UAs // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side data = data.replace(rEscapedNewline, '\\\n'); this.area.value = data.replace(rNewline, '\\n'); try { this.form.submit(); } catch(e) {} if (this.iframe.attachEvent) { this.iframe.onreadystatechange = function(){ if (self.iframe.readyState == 'complete') { complete(); } }; } else { this.iframe.onload = complete; } }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./polling":18,"component-inherit":21}],17:[function(_dereq_,module,exports){ (function (global){ /** * Module requirements. */ var XMLHttpRequest = _dereq_('xmlhttprequest'); var Polling = _dereq_('./polling'); var Emitter = _dereq_('component-emitter'); var inherit = _dereq_('component-inherit'); var debug = _dereq_('debug')('engine.io-client:polling-xhr'); /** * Module exports. */ module.exports = XHR; module.exports.Request = Request; /** * Empty function */ function empty(){} /** * XHR Polling constructor. * * @param {Object} opts * @api public */ function XHR(opts){ Polling.call(this, opts); if (global.location) { var isSSL = 'https:' == location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } this.xd = opts.hostname != global.location.hostname || port != opts.port; this.xs = opts.secure != isSSL; } } /** * Inherits from Polling. */ inherit(XHR, Polling); /** * XHR supports binary */ XHR.prototype.supportsBinary = true; /** * Creates a request. * * @param {String} method * @api private */ XHR.prototype.request = function(opts){ opts = opts || {}; opts.uri = this.uri(); opts.xd = this.xd; opts.xs = this.xs; opts.agent = this.agent || false; opts.supportsBinary = this.supportsBinary; opts.enablesXDR = this.enablesXDR; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; return new Request(opts); }; /** * Sends data. * * @param {String} data to send. * @param {Function} called upon flush. * @api private */ XHR.prototype.doWrite = function(data, fn){ var isBinary = typeof data !== 'string' && data !== undefined; var req = this.request({ method: 'POST', data: data, isBinary: isBinary }); var self = this; req.on('success', fn); req.on('error', function(err){ self.onError('xhr post error', err); }); this.sendXhr = req; }; /** * Starts a poll cycle. * * @api private */ XHR.prototype.doPoll = function(){ debug('xhr poll'); var req = this.request(); var self = this; req.on('data', function(data){ self.onData(data); }); req.on('error', function(err){ self.onError('xhr poll error', err); }); this.pollXhr = req; }; /** * Request constructor * * @param {Object} options * @api public */ function Request(opts){ this.method = opts.method || 'GET'; this.uri = opts.uri; this.xd = !!opts.xd; this.xs = !!opts.xs; this.async = false !== opts.async; this.data = undefined != opts.data ? opts.data : null; this.agent = opts.agent; this.isBinary = opts.isBinary; this.supportsBinary = opts.supportsBinary; this.enablesXDR = opts.enablesXDR; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; this.create(); } /** * Mix in `Emitter`. */ Emitter(Request.prototype); /** * Creates the XHR object and sends the request. * * @api private */ Request.prototype.create = function(){ var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR }; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; var xhr = this.xhr = new XMLHttpRequest(opts); var self = this; try { debug('xhr open %s: %s', this.method, this.uri); xhr.open(this.method, this.uri, this.async); if (this.supportsBinary) { // This has to be done after open because Firefox is stupid // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension xhr.responseType = 'arraybuffer'; } if ('POST' == this.method) { try { if (this.isBinary) { xhr.setRequestHeader('Content-type', 'application/octet-stream'); } else { xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8'); } } catch (e) {} } // ie6 check if ('withCredentials' in xhr) { xhr.withCredentials = true; } if (this.hasXDR()) { xhr.onload = function(){ self.onLoad(); }; xhr.onerror = function(){ self.onError(xhr.responseText); }; } else { xhr.onreadystatechange = function(){ if (4 != xhr.readyState) return; if (200 == xhr.status || 1223 == xhr.status) { self.onLoad(); } else { // make sure the `error` event handler that's user-set // does not throw in the same tick and gets caught here setTimeout(function(){ self.onError(xhr.status); }, 0); } }; } debug('xhr data %s', this.data); xhr.send(this.data); } catch (e) { // Need to defer since .create() is called directly fhrom the constructor // and thus the 'error' event can only be only bound *after* this exception // occurs. Therefore, also, we cannot throw here at all. setTimeout(function() { self.onError(e); }, 0); return; } if (global.document) { this.index = Request.requestsCount++; Request.requests[this.index] = this; } }; /** * Called upon successful response. * * @api private */ Request.prototype.onSuccess = function(){ this.emit('success'); this.cleanup(); }; /** * Called if we have data. * * @api private */ Request.prototype.onData = function(data){ this.emit('data', data); this.onSuccess(); }; /** * Called upon error. * * @api private */ Request.prototype.onError = function(err){ this.emit('error', err); this.cleanup(true); }; /** * Cleans up house. * * @api private */ Request.prototype.cleanup = function(fromError){ if ('undefined' == typeof this.xhr || null === this.xhr) { return; } // xmlhttprequest if (this.hasXDR()) { this.xhr.onload = this.xhr.onerror = empty; } else { this.xhr.onreadystatechange = empty; } if (fromError) { try { this.xhr.abort(); } catch(e) {} } if (global.document) { delete Request.requests[this.index]; } this.xhr = null; }; /** * Called upon load. * * @api private */ Request.prototype.onLoad = function(){ var data; try { var contentType; try { contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0]; } catch (e) {} if (contentType === 'application/octet-stream') { data = this.xhr.response; } else { if (!this.supportsBinary) { data = this.xhr.responseText; } else { data = 'ok'; } } } catch (e) { this.onError(e); } if (null != data) { this.onData(data); } }; /** * Check if it has XDomainRequest. * * @api private */ Request.prototype.hasXDR = function(){ return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR; }; /** * Aborts the request. * * @api public */ Request.prototype.abort = function(){ this.cleanup(); }; /** * Aborts pending requests when unloading the window. This is needed to prevent * memory leaks (e.g. when using IE) and to ensure that no spurious error is * emitted. */ if (global.document) { Request.requestsCount = 0; Request.requests = {}; if (global.attachEvent) { global.attachEvent('onunload', unloadHandler); } else if (global.addEventListener) { global.addEventListener('beforeunload', unloadHandler, false); } } function unloadHandler() { for (var i in Request.requests) { if (Request.requests.hasOwnProperty(i)) { Request.requests[i].abort(); } } } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./polling":18,"component-emitter":9,"component-inherit":21,"debug":22,"xmlhttprequest":20}],18:[function(_dereq_,module,exports){ /** * Module dependencies. */ var Transport = _dereq_('../transport'); var parseqs = _dereq_('parseqs'); var parser = _dereq_('engine.io-parser'); var inherit = _dereq_('component-inherit'); var debug = _dereq_('debug')('engine.io-client:polling'); /** * Module exports. */ module.exports = Polling; /** * Is XHR2 supported? */ var hasXHR2 = (function() { var XMLHttpRequest = _dereq_('xmlhttprequest'); var xhr = new XMLHttpRequest({ xdomain: false }); return null != xhr.responseType; })(); /** * Polling interface. * * @param {Object} opts * @api private */ function Polling(opts){ var forceBase64 = (opts && opts.forceBase64); if (!hasXHR2 || forceBase64) { this.supportsBinary = false; } Transport.call(this, opts); } /** * Inherits from Transport. */ inherit(Polling, Transport); /** * Transport name. */ Polling.prototype.name = 'polling'; /** * Opens the socket (triggers polling). We write a PING message to determine * when the transport is open. * * @api private */ Polling.prototype.doOpen = function(){ this.poll(); }; /** * Pauses polling. * * @param {Function} callback upon buffers are flushed and transport is paused * @api private */ Polling.prototype.pause = function(onPause){ var pending = 0; var self = this; this.readyState = 'pausing'; function pause(){ debug('paused'); self.readyState = 'paused'; onPause(); } if (this.polling || !this.writable) { var total = 0; if (this.polling) { debug('we are currently polling - waiting to pause'); total++; this.once('pollComplete', function(){ debug('pre-pause polling complete'); --total || pause(); }); } if (!this.writable) { debug('we are currently writing - waiting to pause'); total++; this.once('drain', function(){ debug('pre-pause writing complete'); --total || pause(); }); } } else { pause(); } }; /** * Starts polling cycle. * * @api public */ Polling.prototype.poll = function(){ debug('polling'); this.polling = true; this.doPoll(); this.emit('poll'); }; /** * Overloads onData to detect payloads. * * @api private */ Polling.prototype.onData = function(data){ var self = this; debug('polling got data %s', data); var callback = function(packet, index, total) { // if its the first message we consider the transport open if ('opening' == self.readyState) { self.onOpen(); } // if its a close packet, we close the ongoing requests if ('close' == packet.type) { self.onClose(); return false; } // otherwise bypass onData and handle the message self.onPacket(packet); }; // decode payload parser.decodePayload(data, this.socket.binaryType, callback); // if an event did not trigger closing if ('closed' != this.readyState) { // if we got data we're not polling this.polling = false; this.emit('pollComplete'); if ('open' == this.readyState) { this.poll(); } else { debug('ignoring poll - transport state "%s"', this.readyState); } } }; /** * For polling, send a close packet. * * @api private */ Polling.prototype.doClose = function(){ var self = this; function close(){ debug('writing close packet'); self.write([{ type: 'close' }]); } if ('open' == this.readyState) { debug('transport open - closing'); close(); } else { // in case we're trying to close while // handshaking is in progress (GH-164) debug('transport not open - deferring close'); this.once('open', close); } }; /** * Writes a packets payload. * * @param {Array} data packets * @param {Function} drain callback * @api private */ Polling.prototype.write = function(packets){ var self = this; this.writable = false; var callbackfn = function() { self.writable = true; self.emit('drain'); }; var self = this; parser.encodePayload(packets, this.supportsBinary, function(data) { self.doWrite(data, callbackfn); }); }; /** * Generates uri for connection. * * @api private */ Polling.prototype.uri = function(){ var query = this.query || {}; var schema = this.secure ? 'https' : 'http'; var port = ''; // cache busting is forced if (false !== this.timestampRequests) { query[this.timestampParam] = +new Date + '-' + Transport.timestamps++; } if (!this.supportsBinary && !query.sid) { query.b64 = 1; } query = parseqs.encode(query); // avoid port if default for schema if (this.port && (('https' == schema && this.port != 443) || ('http' == schema && this.port != 80))) { port = ':' + this.port; } // prepend ? to query if (query.length) { query = '?' + query; } return schema + '://' + this.hostname + port + this.path + query; }; },{"../transport":14,"component-inherit":21,"debug":22,"engine.io-parser":25,"parseqs":33,"xmlhttprequest":20}],19:[function(_dereq_,module,exports){ /** * Module dependencies. */ var Transport = _dereq_('../transport'); var parser = _dereq_('engine.io-parser'); var parseqs = _dereq_('parseqs'); var inherit = _dereq_('component-inherit'); var debug = _dereq_('debug')('engine.io-client:websocket'); /** * `ws` exposes a WebSocket-compatible interface in * Node, or the `WebSocket` or `MozWebSocket` globals * in the browser. */ var WebSocket = _dereq_('ws'); /** * Module exports. */ module.exports = WS; /** * WebSocket transport constructor. * * @api {Object} connection options * @api public */ function WS(opts){ var forceBase64 = (opts && opts.forceBase64); if (forceBase64) { this.supportsBinary = false; } Transport.call(this, opts); } /** * Inherits from Transport. */ inherit(WS, Transport); /** * Transport name. * * @api public */ WS.prototype.name = 'websocket'; /* * WebSockets support binary */ WS.prototype.supportsBinary = true; /** * Opens socket. * * @api private */ WS.prototype.doOpen = function(){ if (!this.check()) { // let probe timeout return; } var self = this; var uri = this.uri(); var protocols = void(0); var opts = { agent: this.agent }; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; this.ws = new WebSocket(uri, protocols, opts); if (this.ws.binaryType === undefined) { this.supportsBinary = false; } this.ws.binaryType = 'arraybuffer'; this.addEventListeners(); }; /** * Adds event listeners to the socket * * @api private */ WS.prototype.addEventListeners = function(){ var self = this; this.ws.onopen = function(){ self.onOpen(); }; this.ws.onclose = function(){ self.onClose(); }; this.ws.onmessage = function(ev){ self.onData(ev.data); }; this.ws.onerror = function(e){ self.onError('websocket error', e); }; }; /** * Override `onData` to use a timer on iOS. * See: https://gist.github.com/mloughran/2052006 * * @api private */ if ('undefined' != typeof navigator && /iPad|iPhone|iPod/i.test(navigator.userAgent)) { WS.prototype.onData = function(data){ var self = this; setTimeout(function(){ Transport.prototype.onData.call(self, data); }, 0); }; } /** * Writes data to socket. * * @param {Array} array of packets. * @api private */ WS.prototype.write = function(packets){ var self = this; this.writable = false; // encodePacket efficient as it uses WS framing // no need for encodePayload for (var i = 0, l = packets.length; i < l; i++) { parser.encodePacket(packets[i], this.supportsBinary, function(data) { //Sometimes the websocket has already been closed but the browser didn't //have a chance of informing us about it yet, in that case send will //throw an error try { self.ws.send(data); } catch (e){ debug('websocket closed before onclose event'); } }); } function ondrain() { self.writable = true; self.emit('drain'); } // fake drain // defer to next tick to allow Socket to clear writeBuffer setTimeout(ondrain, 0); }; /** * Called upon close * * @api private */ WS.prototype.onClose = function(){ Transport.prototype.onClose.call(this); }; /** * Closes socket. * * @api private */ WS.prototype.doClose = function(){ if (typeof this.ws !== 'undefined') { this.ws.close(); } }; /** * Generates uri for connection. * * @api private */ WS.prototype.uri = function(){ var query = this.query || {}; var schema = this.secure ? 'wss' : 'ws'; var port = ''; // avoid port if default for schema if (this.port && (('wss' == schema && this.port != 443) || ('ws' == schema && this.port != 80))) { port = ':' + this.port; } // append timestamp to URI if (this.timestampRequests) { query[this.timestampParam] = +new Date; } // communicate binary support capabilities if (!this.supportsBinary) { query.b64 = 1; } query = parseqs.encode(query); // prepend ? to query if (query.length) { query = '?' + query; } return schema + '://' + this.hostname + port + this.path + query; }; /** * Feature detection for WebSocket. * * @return {Boolean} whether this transport is available. * @api public */ WS.prototype.check = function(){ return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name); }; },{"../transport":14,"component-inherit":21,"debug":22,"engine.io-parser":25,"parseqs":33,"ws":35}],20:[function(_dereq_,module,exports){ // browser shim for xmlhttprequest module var hasCORS = _dereq_('has-cors'); module.exports = function(opts) { var xdomain = opts.xdomain; // scheme must be same when usign XDomainRequest // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx var xscheme = opts.xscheme; // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default. // https://github.com/Automattic/engine.io-client/pull/217 var enablesXDR = opts.enablesXDR; // XMLHttpRequest can be disabled on IE try { if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) { return new XMLHttpRequest(); } } catch (e) { } // Use XDomainRequest for IE8 if enablesXDR is true // because loading bar keeps flashing when using jsonp-polling // https://github.com/yujiosaka/socke.io-ie8-loading-example try { if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) { return new XDomainRequest(); } } catch (e) { } if (!xdomain) { try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) { } } } },{"has-cors":38}],21:[function(_dereq_,module,exports){ module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; },{}],22:[function(_dereq_,module,exports){ /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = _dereq_('./debug'); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // is webkit? http://stackoverflow.com/a/16459606/376773 return ('WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { return JSON.stringify(v); }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); return args; } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // This hackery is required for IE8, // where the `console.log` function doesn't have 'apply' return 'object' == typeof console && 'function' == typeof console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { localStorage.removeItem('debug'); } else { localStorage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = localStorage.debug; } catch(e) {} return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); },{"./debug":23}],23:[function(_dereq_,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = _dereq_('ms'); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = Array.prototype.slice.call(arguments); args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); if ('function' === typeof exports.formatArgs) { args = exports.formatArgs.apply(self, args); } var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } },{"ms":24}],24:[function(_dereq_,module,exports){ /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @return {String|Number} * @api public */ module.exports = function(val, options){ options = options || {}; if ('string' == typeof val) return parse(val); return options.long ? long(val) : short(val); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); if (!match) return; var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'h': return n * h; case 'minutes': case 'minute': case 'm': return n * m; case 'seconds': case 'second': case 's': return n * s; case 'ms': return n; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function short(ms) { if (ms >= d) return Math.round(ms / d) + 'd'; if (ms >= h) return Math.round(ms / h) + 'h'; if (ms >= m) return Math.round(ms / m) + 'm'; if (ms >= s) return Math.round(ms / s) + 's'; return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function long(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) return; if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; return Math.ceil(ms / n) + ' ' + name + 's'; } },{}],25:[function(_dereq_,module,exports){ (function (global){ /** * Module dependencies. */ var keys = _dereq_('./keys'); var hasBinary = _dereq_('has-binary'); var sliceBuffer = _dereq_('arraybuffer.slice'); var base64encoder = _dereq_('base64-arraybuffer'); var after = _dereq_('after'); var utf8 = _dereq_('utf8'); /** * Check if we are running an android browser. That requires us to use * ArrayBuffer with polling transports... * * http://ghinda.net/jpeg-blob-ajax-android/ */ var isAndroid = navigator.userAgent.match(/Android/i); /** * Check if we are running in PhantomJS. * Uploading a Blob with PhantomJS does not work correctly, as reported here: * https://github.com/ariya/phantomjs/issues/11395 * @type boolean */ var isPhantomJS = /PhantomJS/i.test(navigator.userAgent); /** * When true, avoids using Blobs to encode payloads. * @type boolean */ var dontSendBlobs = isAndroid || isPhantomJS; /** * Current protocol version. */ exports.protocol = 3; /** * Packet types. */ var packets = exports.packets = { open: 0 // non-ws , close: 1 // non-ws , ping: 2 , pong: 3 , message: 4 , upgrade: 5 , noop: 6 }; var packetslist = keys(packets); /** * Premade error packet. */ var err = { type: 'error', data: 'parser error' }; /** * Create a blob api even for blob builder when vendor prefixes exist */ var Blob = _dereq_('blob'); /** * Encodes a packet. * * <packet type id> [ <data> ] * * Example: * * 5hello world * 3 * 4 * * Binary is encoded in an identical principle * * @api private */ exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) { if ('function' == typeof supportsBinary) { callback = supportsBinary; supportsBinary = false; } if ('function' == typeof utf8encode) { callback = utf8encode; utf8encode = null; } var data = (packet.data === undefined) ? undefined : packet.data.buffer || packet.data; if (global.ArrayBuffer && data instanceof ArrayBuffer) { return encodeArrayBuffer(packet, supportsBinary, callback); } else if (Blob && data instanceof global.Blob) { return encodeBlob(packet, supportsBinary, callback); } // might be an object with { base64: true, data: dataAsBase64String } if (data && data.base64) { return encodeBase64Object(packet, callback); } // Sending data as a utf-8 string var encoded = packets[packet.type]; // data fragment is optional if (undefined !== packet.data) { encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data); } return callback('' + encoded); }; function encodeBase64Object(packet, callback) { // packet data is an object { base64: true, data: dataAsBase64String } var message = 'b' + exports.packets[packet.type] + packet.data.data; return callback(message); } /** * Encode packet helpers for binary types */ function encodeArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var data = packet.data; var contentArray = new Uint8Array(data); var resultBuffer = new Uint8Array(1 + data.byteLength); resultBuffer[0] = packets[packet.type]; for (var i = 0; i < contentArray.length; i++) { resultBuffer[i+1] = contentArray[i]; } return callback(resultBuffer.buffer); } function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var fr = new FileReader(); fr.onload = function() { packet.data = fr.result; exports.encodePacket(packet, supportsBinary, true, callback); }; return fr.readAsArrayBuffer(packet.data); } function encodeBlob(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } if (dontSendBlobs) { return encodeBlobAsArrayBuffer(packet, supportsBinary, callback); } var length = new Uint8Array(1); length[0] = packets[packet.type]; var blob = new Blob([length.buffer, packet.data]); return callback(blob); } /** * Encodes a packet with binary data in a base64 string * * @param {Object} packet, has `type` and `data` * @return {String} base64 encoded message */ exports.encodeBase64Packet = function(packet, callback) { var message = 'b' + exports.packets[packet.type]; if (Blob && packet.data instanceof Blob) { var fr = new FileReader(); fr.onload = function() { var b64 = fr.result.split(',')[1]; callback(message + b64); }; return fr.readAsDataURL(packet.data); } var b64data; try { b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data)); } catch (e) { // iPhone Safari doesn't let you apply with typed arrays var typed = new Uint8Array(packet.data); var basic = new Array(typed.length); for (var i = 0; i < typed.length; i++) { basic[i] = typed[i]; } b64data = String.fromCharCode.apply(null, basic); } message += global.btoa(b64data); return callback(message); }; /** * Decodes a packet. Changes format to Blob if requested. * * @return {Object} with `type` and `data` (if any) * @api private */ exports.decodePacket = function (data, binaryType, utf8decode) { // String data if (typeof data == 'string' || data === undefined) { if (data.charAt(0) == 'b') { return exports.decodeBase64Packet(data.substr(1), binaryType); } if (utf8decode) { try { data = utf8.decode(data); } catch (e) { return err; } } var type = data.charAt(0); if (Number(type) != type || !packetslist[type]) { return err; } if (data.length > 1) { return { type: packetslist[type], data: data.substring(1) }; } else { return { type: packetslist[type] }; } } var asArray = new Uint8Array(data); var type = asArray[0]; var rest = sliceBuffer(data, 1); if (Blob && binaryType === 'blob') { rest = new Blob([rest]); } return { type: packetslist[type], data: rest }; }; /** * Decodes a packet encoded in a base64 string * * @param {String} base64 encoded message * @return {Object} with `type` and `data` (if any) */ exports.decodeBase64Packet = function(msg, binaryType) { var type = packetslist[msg.charAt(0)]; if (!global.ArrayBuffer) { return { type: type, data: { base64: true, data: msg.substr(1) } }; } var data = base64encoder.decode(msg.substr(1)); if (binaryType === 'blob' && Blob) { data = new Blob([data]); } return { type: type, data: data }; }; /** * Encodes multiple messages (payload). * * <length>:data * * Example: * * 11:hello world2:hi * * If any contents are binary, they will be encoded as base64 strings. Base64 * encoded strings are marked with a b before the length specifier * * @param {Array} packets * @api private */ exports.encodePayload = function (packets, supportsBinary, callback) { if (typeof supportsBinary == 'function') { callback = supportsBinary; supportsBinary = null; } var isBinary = hasBinary(packets); if (supportsBinary && isBinary) { if (Blob && !dontSendBlobs) { return exports.encodePayloadAsBlob(packets, callback); } return exports.encodePayloadAsArrayBuffer(packets, callback); } if (!packets.length) { return callback('0:'); } function setLengthHeader(message) { return message.length + ':' + message; } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) { doneCallback(null, setLengthHeader(message)); }); } map(packets, encodeOne, function(err, results) { return callback(results.join('')); }); }; /** * Async array map using after */ function map(ary, each, done) { var result = new Array(ary.length); var next = after(ary.length, done); var eachWithIndex = function(i, el, cb) { each(el, function(error, msg) { result[i] = msg; cb(error, result); }); }; for (var i = 0; i < ary.length; i++) { eachWithIndex(i, ary[i], next); } } /* * Decodes data when a payload is maybe expected. Possible binary contents are * decoded from their base64 representation * * @param {String} data, callback method * @api public */ exports.decodePayload = function (data, binaryType, callback) { if (typeof data != 'string') { return exports.decodePayloadAsBinary(data, binaryType, callback); } if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var packet; if (data == '') { // parser error - ignoring payload return callback(err, 0, 1); } var length = '' , n, msg; for (var i = 0, l = data.length; i < l; i++) { var chr = data.charAt(i); if (':' != chr) { length += chr; } else { if ('' == length || (length != (n = Number(length)))) { // parser error - ignoring payload return callback(err, 0, 1); } msg = data.substr(i + 1, n); if (length != msg.length) { // parser error - ignoring payload return callback(err, 0, 1); } if (msg.length) { packet = exports.decodePacket(msg, binaryType, true); if (err.type == packet.type && err.data == packet.data) { // parser error in individual packet - ignoring payload return callback(err, 0, 1); } var ret = callback(packet, i + n, l); if (false === ret) return; } // advance cursor i += n; length = ''; } } if (length != '') { // parser error - ignoring payload return callback(err, 0, 1); } }; /** * Encodes multiple messages (payload) as binary. * * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number * 255><data> * * Example: * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers * * @param {Array} packets * @return {ArrayBuffer} encoded payload * @api private */ exports.encodePayloadAsArrayBuffer = function(packets, callback) { if (!packets.length) { return callback(new ArrayBuffer(0)); } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, true, function(data) { return doneCallback(null, data); }); } map(packets, encodeOne, function(err, encodedPackets) { var totalLength = encodedPackets.reduce(function(acc, p) { var len; if (typeof p === 'string'){ len = p.length; } else { len = p.byteLength; } return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2 }, 0); var resultArray = new Uint8Array(totalLength); var bufferIndex = 0; encodedPackets.forEach(function(p) { var isString = typeof p === 'string'; var ab = p; if (isString) { var view = new Uint8Array(p.length); for (var i = 0; i < p.length; i++) { view[i] = p.charCodeAt(i); } ab = view.buffer; } if (isString) { // not true binary resultArray[bufferIndex++] = 0; } else { // true binary resultArray[bufferIndex++] = 1; } var lenStr = ab.byteLength.toString(); for (var i = 0; i < lenStr.length; i++) { resultArray[bufferIndex++] = parseInt(lenStr[i]); } resultArray[bufferIndex++] = 255; var view = new Uint8Array(ab); for (var i = 0; i < view.length; i++) { resultArray[bufferIndex++] = view[i]; } }); return callback(resultArray.buffer); }); }; /** * Encode as Blob */ exports.encodePayloadAsBlob = function(packets, callback) { function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, true, function(encoded) { var binaryIdentifier = new Uint8Array(1); binaryIdentifier[0] = 1; if (typeof encoded === 'string') { var view = new Uint8Array(encoded.length); for (var i = 0; i < encoded.length; i++) { view[i] = encoded.charCodeAt(i); } encoded = view.buffer; binaryIdentifier[0] = 0; } var len = (encoded instanceof ArrayBuffer) ? encoded.byteLength : encoded.size; var lenStr = len.toString(); var lengthAry = new Uint8Array(lenStr.length + 1); for (var i = 0; i < lenStr.length; i++) { lengthAry[i] = parseInt(lenStr[i]); } lengthAry[lenStr.length] = 255; if (Blob) { var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]); doneCallback(null, blob); } }); } map(packets, encodeOne, function(err, results) { return callback(new Blob(results)); }); }; /* * Decodes data when a payload is maybe expected. Strings are decoded by * interpreting each byte as a key code for entries marked to start with 0. See * description of encodePayloadAsBinary * * @param {ArrayBuffer} data, callback method * @api public */ exports.decodePayloadAsBinary = function (data, binaryType, callback) { if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var bufferTail = data; var buffers = []; var numberTooLong = false; while (bufferTail.byteLength > 0) { var tailArray = new Uint8Array(bufferTail); var isString = tailArray[0] === 0; var msgLength = ''; for (var i = 1; ; i++) { if (tailArray[i] == 255) break; if (msgLength.length > 310) { numberTooLong = true; break; } msgLength += tailArray[i]; } if(numberTooLong) return callback(err, 0, 1); bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length); msgLength = parseInt(msgLength); var msg = sliceBuffer(bufferTail, 0, msgLength); if (isString) { try { msg = String.fromCharCode.apply(null, new Uint8Array(msg)); } catch (e) { // iPhone Safari doesn't let you apply to typed arrays var typed = new Uint8Array(msg); msg = ''; for (var i = 0; i < typed.length; i++) { msg += String.fromCharCode(typed[i]); } } } buffers.push(msg); bufferTail = sliceBuffer(bufferTail, msgLength); } var total = buffers.length; buffers.forEach(function(buffer, i) { callback(exports.decodePacket(buffer, binaryType, true), i, total); }); }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./keys":26,"after":27,"arraybuffer.slice":28,"base64-arraybuffer":29,"blob":30,"has-binary":36,"utf8":31}],26:[function(_dereq_,module,exports){ /** * Gets the keys for an object. * * @return {Array} keys * @api private */ module.exports = Object.keys || function keys (obj){ var arr = []; var has = Object.prototype.hasOwnProperty; for (var i in obj) { if (has.call(obj, i)) { arr.push(i); } } return arr; }; },{}],27:[function(_dereq_,module,exports){ module.exports = after function after(count, callback, err_cb) { var bail = false err_cb = err_cb || noop proxy.count = count return (count === 0) ? callback() : proxy function proxy(err, result) { if (proxy.count <= 0) { throw new Error('after called too many times') } --proxy.count // after first error, rest are passed to err_cb if (err) { bail = true callback(err) // future error callbacks will go to error handler callback = err_cb } else if (proxy.count === 0 && !bail) { callback(null, result) } } } function noop() {} },{}],28:[function(_dereq_,module,exports){ /** * An abstraction for slicing an arraybuffer even when * ArrayBuffer.prototype.slice is not supported * * @api public */ module.exports = function(arraybuffer, start, end) { var bytes = arraybuffer.byteLength; start = start || 0; end = end || bytes; if (arraybuffer.slice) { return arraybuffer.slice(start, end); } if (start < 0) { start += bytes; } if (end < 0) { end += bytes; } if (end > bytes) { end = bytes; } if (start >= bytes || start >= end || bytes === 0) { return new ArrayBuffer(0); } var abv = new Uint8Array(arraybuffer); var result = new Uint8Array(end - start); for (var i = start, ii = 0; i < end; i++, ii++) { result[ii] = abv[i]; } return result.buffer; }; },{}],29:[function(_dereq_,module,exports){ /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function(chars){ "use strict"; exports.encode = function(arraybuffer) { var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ""; for (i = 0; i < len; i+=3) { base64 += chars[bytes[i] >> 2]; base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64 += chars[bytes[i + 2] & 63]; } if ((len % 3) === 2) { base64 = base64.substring(0, base64.length - 1) + "="; } else if (len % 3 === 1) { base64 = base64.substring(0, base64.length - 2) + "=="; } return base64; }; exports.decode = function(base64) { var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; if (base64[base64.length - 1] === "=") { bufferLength--; if (base64[base64.length - 2] === "=") { bufferLength--; } } var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); for (i = 0; i < len; i+=4) { encoded1 = chars.indexOf(base64[i]); encoded2 = chars.indexOf(base64[i+1]); encoded3 = chars.indexOf(base64[i+2]); encoded4 = chars.indexOf(base64[i+3]); bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return arraybuffer; }; })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); },{}],30:[function(_dereq_,module,exports){ (function (global){ /** * Create a blob builder even when vendor prefixes exist */ var BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MSBlobBuilder || global.MozBlobBuilder; /** * Check if Blob constructor is supported */ var blobSupported = (function() { try { var a = new Blob(['hi']); return a.size === 2; } catch(e) { return false; } })(); /** * Check if Blob constructor supports ArrayBufferViews * Fails in Safari 6, so we need to map to ArrayBuffers there. */ var blobSupportsArrayBufferView = blobSupported && (function() { try { var b = new Blob([new Uint8Array([1,2])]); return b.size === 2; } catch(e) { return false; } })(); /** * Check if BlobBuilder is supported */ var blobBuilderSupported = BlobBuilder && BlobBuilder.prototype.append && BlobBuilder.prototype.getBlob; /** * Helper function that maps ArrayBufferViews to ArrayBuffers * Used by BlobBuilder constructor and old browsers that didn't * support it in the Blob constructor. */ function mapArrayBufferViews(ary) { for (var i = 0; i < ary.length; i++) { var chunk = ary[i]; if (chunk.buffer instanceof ArrayBuffer) { var buf = chunk.buffer; // if this is a subarray, make a copy so we only // include the subarray region from the underlying buffer if (chunk.byteLength !== buf.byteLength) { var copy = new Uint8Array(chunk.byteLength); copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); buf = copy.buffer; } ary[i] = buf; } } } function BlobBuilderConstructor(ary, options) { options = options || {}; var bb = new BlobBuilder(); mapArrayBufferViews(ary); for (var i = 0; i < ary.length; i++) { bb.append(ary[i]); } return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); }; function BlobConstructor(ary, options) { mapArrayBufferViews(ary); return new Blob(ary, options || {}); }; module.exports = (function() { if (blobSupported) { return blobSupportsArrayBufferView ? global.Blob : BlobConstructor; } else if (blobBuilderSupported) { return BlobBuilderConstructor; } else { return undefined; } })(); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],31:[function(_dereq_,module,exports){ (function (global){ /*! https://mths.be/utf8js v2.0.0 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) { var 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 & 0x0F) << 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.0.0', 'encode': utf8encode, 'decode': utf8decode }; // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define(function() { return utf8; }); } else if (freeExports && !freeExports.nodeType) { if (freeModule) { // in Node.js or RingoJS v0.8.0+ freeModule.exports = utf8; } else { // in Narwhal or RingoJS v0.7.0- var object = {}; var hasOwnProperty = object.hasOwnProperty; for (var key in utf8) { hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]); } } } else { // in Rhino or a web browser root.utf8 = utf8; } }(this)); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],32:[function(_dereq_,module,exports){ (function (global){ /** * JSON parse. * * @see Based on jQuery#parseJSON (MIT) and JSON2 * @api private */ var rvalidchars = /^[\],:{}\s]*$/; var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g; var rtrimLeft = /^\s+/; var rtrimRight = /\s+$/; module.exports = function parsejson(data) { if ('string' != typeof data || !data) { return null; } data = data.replace(rtrimLeft, '').replace(rtrimRight, ''); // Attempt to parse using the native JSON parser first if (global.JSON && JSON.parse) { return JSON.parse(data); } if (rvalidchars.test(data.replace(rvalidescape, '@') .replace(rvalidtokens, ']') .replace(rvalidbraces, ''))) { return (new Function('return ' + data))(); } }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],33:[function(_dereq_,module,exports){ /** * Compiles a querystring * Returns string representation of the object * * @param {Object} * @api private */ exports.encode = function (obj) { var str = ''; for (var i in obj) { if (obj.hasOwnProperty(i)) { if (str.length) str += '&'; str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); } } return str; }; /** * Parses a simple querystring into an object * * @param {String} qs * @api private */ exports.decode = function(qs){ var qry = {}; var pairs = qs.split('&'); for (var i = 0, l = pairs.length; i < l; i++) { var pair = pairs[i].split('='); qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return qry; }; },{}],34:[function(_dereq_,module,exports){ /** * Parses an URI * * @author Steven Levithan <stevenlevithan.com> (MIT license) * @api private */ var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; var parts = [ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' ]; module.exports = function parseuri(str) { var src = str, b = str.indexOf('['), e = str.indexOf(']'); if (b != -1 && e != -1) { str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); } var m = re.exec(str || ''), uri = {}, i = 14; while (i--) { uri[parts[i]] = m[i] || ''; } if (b != -1 && e != -1) { uri.source = src; uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); uri.ipv6uri = true; } return uri; }; },{}],35:[function(_dereq_,module,exports){ /** * Module dependencies. */ var global = (function() { return this; })(); /** * WebSocket constructor. */ var WebSocket = global.WebSocket || global.MozWebSocket; /** * Module exports. */ module.exports = WebSocket ? ws : null; /** * WebSocket constructor. * * The third `opts` options object gets ignored in web browsers, since it's * non-standard, and throws a TypeError if passed to the constructor. * See: https://github.com/einaros/ws/issues/227 * * @param {String} uri * @param {Array} protocols (optional) * @param {Object) opts (optional) * @api public */ function ws(uri, protocols, opts) { var instance; if (protocols) { instance = new WebSocket(uri, protocols); } else { instance = new WebSocket(uri); } return instance; } if (WebSocket) ws.prototype = WebSocket.prototype; },{}],36:[function(_dereq_,module,exports){ (function (global){ /* * Module requirements. */ var isArray = _dereq_('isarray'); /** * Module exports. */ module.exports = hasBinary; /** * Checks for binary data. * * Right now only Buffer and ArrayBuffer are supported.. * * @param {Object} anything * @api public */ function hasBinary(data) { function _hasBinary(obj) { if (!obj) return false; if ( (global.Buffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || (global.Blob && obj instanceof Blob) || (global.File && obj instanceof File) ) { return true; } if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (_hasBinary(obj[i])) { return true; } } } else if (obj && 'object' == typeof obj) { if (obj.toJSON) { obj = obj.toJSON(); } for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) { return true; } } } return false; } return _hasBinary(data); } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"isarray":37}],37:[function(_dereq_,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; },{}],38:[function(_dereq_,module,exports){ /** * Module dependencies. */ var global = _dereq_('global'); /** * Module exports. * * Logic borrowed from Modernizr: * * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js */ try { module.exports = 'XMLHttpRequest' in global && 'withCredentials' in new global.XMLHttpRequest(); } catch (err) { // if XMLHttp support is disabled in IE then it will throw // when trying to create module.exports = false; } },{"global":39}],39:[function(_dereq_,module,exports){ /** * Returns `this`. Execute this without a "context" (i.e. without it being * attached to an object of the left-hand side), and `this` points to the * "global" scope of the current JS execution. */ module.exports = (function () { return this; })(); },{}],40:[function(_dereq_,module,exports){ var indexOf = [].indexOf; module.exports = function(arr, obj){ if (indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; },{}],41:[function(_dereq_,module,exports){ /** * HOP ref. */ var has = Object.prototype.hasOwnProperty; /** * Return own keys in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.keys = Object.keys || function(obj){ var keys = []; for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; /** * Return own values in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.values = function(obj){ var vals = []; for (var key in obj) { if (has.call(obj, key)) { vals.push(obj[key]); } } return vals; }; /** * Merge `b` into `a`. * * @param {Object} a * @param {Object} b * @return {Object} a * @api public */ exports.merge = function(a, b){ for (var key in b) { if (has.call(b, key)) { a[key] = b[key]; } } return a; }; /** * Return length of `obj`. * * @param {Object} obj * @return {Number} * @api public */ exports.length = function(obj){ return exports.keys(obj).length; }; /** * Check if `obj` is empty. * * @param {Object} obj * @return {Boolean} * @api public */ exports.isEmpty = function(obj){ return 0 == exports.length(obj); }; },{}],42:[function(_dereq_,module,exports){ /** * Parses an URI * * @author Steven Levithan <stevenlevithan.com> (MIT license) * @api private */ var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; var parts = [ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host' , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' ]; module.exports = function parseuri(str) { var m = re.exec(str || '') , uri = {} , i = 14; while (i--) { uri[parts[i]] = m[i] || ''; } return uri; }; },{}],43:[function(_dereq_,module,exports){ (function (global){ /*global Blob,File*/ /** * Module requirements */ var isArray = _dereq_('isarray'); var isBuf = _dereq_('./is-buffer'); /** * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder. * Anything with blobs or files should be fed through removeBlobs before coming * here. * * @param {Object} packet - socket.io event packet * @return {Object} with deconstructed packet and list of buffers * @api public */ exports.deconstructPacket = function(packet){ var buffers = []; var packetData = packet.data; function _deconstructPacket(data) { if (!data) return data; if (isBuf(data)) { var placeholder = { _placeholder: true, num: buffers.length }; buffers.push(data); return placeholder; } else if (isArray(data)) { var newData = new Array(data.length); for (var i = 0; i < data.length; i++) { newData[i] = _deconstructPacket(data[i]); } return newData; } else if ('object' == typeof data && !(data instanceof Date)) { var newData = {}; for (var key in data) { newData[key] = _deconstructPacket(data[key]); } return newData; } return data; } var pack = packet; pack.data = _deconstructPacket(packetData); pack.attachments = buffers.length; // number of binary 'attachments' return {packet: pack, buffers: buffers}; }; /** * Reconstructs a binary packet from its placeholder packet and buffers * * @param {Object} packet - event packet with placeholders * @param {Array} buffers - binary buffers to put in placeholder positions * @return {Object} reconstructed packet * @api public */ exports.reconstructPacket = function(packet, buffers) { var curPlaceHolder = 0; function _reconstructPacket(data) { if (data && data._placeholder) { var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway) return buf; } else if (isArray(data)) { for (var i = 0; i < data.length; i++) { data[i] = _reconstructPacket(data[i]); } return data; } else if (data && 'object' == typeof data) { for (var key in data) { data[key] = _reconstructPacket(data[key]); } return data; } return data; } packet.data = _reconstructPacket(packet.data); packet.attachments = undefined; // no longer useful return packet; }; /** * Asynchronously removes Blobs or Files from data via * FileReader's readAsArrayBuffer method. Used before encoding * data as msgpack. Calls callback with the blobless data. * * @param {Object} data * @param {Function} callback * @api private */ exports.removeBlobs = function(data, callback) { function _removeBlobs(obj, curKey, containingObject) { if (!obj) return obj; // convert any blob if ((global.Blob && obj instanceof Blob) || (global.File && obj instanceof File)) { pendingBlobs++; // async filereader var fileReader = new FileReader(); fileReader.onload = function() { // this.result == arraybuffer if (containingObject) { containingObject[curKey] = this.result; } else { bloblessData = this.result; } // if nothing pending its callback time if(! --pendingBlobs) { callback(bloblessData); } }; fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer } else if (isArray(obj)) { // handle array for (var i = 0; i < obj.length; i++) { _removeBlobs(obj[i], i, obj); } } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object for (var key in obj) { _removeBlobs(obj[key], key, obj); } } } var pendingBlobs = 0; var bloblessData = data; _removeBlobs(bloblessData); if (!pendingBlobs) { callback(bloblessData); } }; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./is-buffer":45,"isarray":46}],44:[function(_dereq_,module,exports){ /** * Module dependencies. */ var debug = _dereq_('debug')('socket.io-parser'); var json = _dereq_('json3'); var isArray = _dereq_('isarray'); var Emitter = _dereq_('component-emitter'); var binary = _dereq_('./binary'); var isBuf = _dereq_('./is-buffer'); /** * Protocol version. * * @api public */ exports.protocol = 4; /** * Packet types. * * @api public */ exports.types = [ 'CONNECT', 'DISCONNECT', 'EVENT', 'BINARY_EVENT', 'ACK', 'BINARY_ACK', 'ERROR' ]; /** * Packet type `connect`. * * @api public */ exports.CONNECT = 0; /** * Packet type `disconnect`. * * @api public */ exports.DISCONNECT = 1; /** * Packet type `event`. * * @api public */ exports.EVENT = 2; /** * Packet type `ack`. * * @api public */ exports.ACK = 3; /** * Packet type `error`. * * @api public */ exports.ERROR = 4; /** * Packet type 'binary event' * * @api public */ exports.BINARY_EVENT = 5; /** * Packet type `binary ack`. For acks with binary arguments. * * @api public */ exports.BINARY_ACK = 6; /** * Encoder constructor. * * @api public */ exports.Encoder = Encoder; /** * Decoder constructor. * * @api public */ exports.Decoder = Decoder; /** * A socket.io Encoder instance * * @api public */ function Encoder() {} /** * Encode a packet as a single string if non-binary, or as a * buffer sequence, depending on packet type. * * @param {Object} obj - packet object * @param {Function} callback - function to handle encodings (likely engine.write) * @return Calls callback with Array of encodings * @api public */ Encoder.prototype.encode = function(obj, callback){ debug('encoding packet %j', obj); if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) { encodeAsBinary(obj, callback); } else { var encoding = encodeAsString(obj); callback([encoding]); } }; /** * Encode packet as string. * * @param {Object} packet * @return {String} encoded * @api private */ function encodeAsString(obj) { var str = ''; var nsp = false; // first is type str += obj.type; // attachments if we have them if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) { str += obj.attachments; str += '-'; } // if we have a namespace other than `/` // we append it followed by a comma `,` if (obj.nsp && '/' != obj.nsp) { nsp = true; str += obj.nsp; } // immediately followed by the id if (null != obj.id) { if (nsp) { str += ','; nsp = false; } str += obj.id; } // json data if (null != obj.data) { if (nsp) str += ','; str += json.stringify(obj.data); } debug('encoded %j as %s', obj, str); return str; } /** * Encode packet as 'buffer sequence' by removing blobs, and * deconstructing packet into object with placeholders and * a list of buffers. * * @param {Object} packet * @return {Buffer} encoded * @api private */ function encodeAsBinary(obj, callback) { function writeEncoding(bloblessData) { var deconstruction = binary.deconstructPacket(bloblessData); var pack = encodeAsString(deconstruction.packet); var buffers = deconstruction.buffers; buffers.unshift(pack); // add packet info to beginning of data list callback(buffers); // write all the buffers } binary.removeBlobs(obj, writeEncoding); } /** * A socket.io Decoder instance * * @return {Object} decoder * @api public */ function Decoder() { this.reconstructor = null; } /** * Mix in `Emitter` with Decoder. */ Emitter(Decoder.prototype); /** * Decodes an ecoded packet string into packet JSON. * * @param {String} obj - encoded packet * @return {Object} packet * @api public */ Decoder.prototype.add = function(obj) { var packet; if ('string' == typeof obj) { packet = decodeString(obj); if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json this.reconstructor = new BinaryReconstructor(packet); // no attachments, labeled binary but no binary data to follow if (this.reconstructor.reconPack.attachments === 0) { this.emit('decoded', packet); } } else { // non-binary full packet this.emit('decoded', packet); } } else if (isBuf(obj) || obj.base64) { // raw binary data if (!this.reconstructor) { throw new Error('got binary data when not reconstructing a packet'); } else { packet = this.reconstructor.takeBinaryData(obj); if (packet) { // received final buffer this.reconstructor = null; this.emit('decoded', packet); } } } else { throw new Error('Unknown type: ' + obj); } }; /** * Decode a packet String (JSON data) * * @param {String} str * @return {Object} packet * @api private */ function decodeString(str) { var p = {}; var i = 0; // look up type p.type = Number(str.charAt(0)); if (null == exports.types[p.type]) return error(); // look up attachments if type binary if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) { var buf = ''; while (str.charAt(++i) != '-') { buf += str.charAt(i); if (i == str.length) break; } if (buf != Number(buf) || str.charAt(i) != '-') { throw new Error('Illegal attachments'); } p.attachments = Number(buf); } // look up namespace (if any) if ('/' == str.charAt(i + 1)) { p.nsp = ''; while (++i) { var c = str.charAt(i); if (',' == c) break; p.nsp += c; if (i == str.length) break; } } else { p.nsp = '/'; } // look up id var next = str.charAt(i + 1); if ('' !== next && Number(next) == next) { p.id = ''; while (++i) { var c = str.charAt(i); if (null == c || Number(c) != c) { --i; break; } p.id += str.charAt(i); if (i == str.length) break; } p.id = Number(p.id); } // look up json data if (str.charAt(++i)) { try { p.data = json.parse(str.substr(i)); } catch(e){ return error(); } } debug('decoded %s as %j', str, p); return p; } /** * Deallocates a parser's resources * * @api public */ Decoder.prototype.destroy = function() { if (this.reconstructor) { this.reconstructor.finishedReconstruction(); } }; /** * A manager of a binary event's 'buffer sequence'. Should * be constructed whenever a packet of type BINARY_EVENT is * decoded. * * @param {Object} packet * @return {BinaryReconstructor} initialized reconstructor * @api private */ function BinaryReconstructor(packet) { this.reconPack = packet; this.buffers = []; } /** * Method to be called when binary data received from connection * after a BINARY_EVENT packet. * * @param {Buffer | ArrayBuffer} binData - the raw binary data received * @return {null | Object} returns null if more binary data is expected or * a reconstructed packet object if all buffers have been received. * @api private */ BinaryReconstructor.prototype.takeBinaryData = function(binData) { this.buffers.push(binData); if (this.buffers.length == this.reconPack.attachments) { // done with buffer list var packet = binary.reconstructPacket(this.reconPack, this.buffers); this.finishedReconstruction(); return packet; } return null; }; /** * Cleans up binary packet reconstruction variables. * * @api private */ BinaryReconstructor.prototype.finishedReconstruction = function() { this.reconPack = null; this.buffers = []; }; function error(data){ return { type: exports.ERROR, data: 'parser error' }; } },{"./binary":43,"./is-buffer":45,"component-emitter":9,"debug":10,"isarray":46,"json3":47}],45:[function(_dereq_,module,exports){ (function (global){ module.exports = isBuf; /** * Returns true if obj is a buffer or an arraybuffer. * * @api private */ function isBuf(obj) { return (global.Buffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer); } }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],46:[function(_dereq_,module,exports){ module.exports=_dereq_(37) },{}],47:[function(_dereq_,module,exports){ /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */ ;(function (window) { // Convenience aliases. var getClass = {}.toString, isProperty, forEach, undef; // Detect the `define` function exposed by asynchronous module loaders. The // strict `define` check is necessary for compatibility with `r.js`. var isLoader = typeof define === "function" && define.amd; // Detect native implementations. var nativeJSON = typeof JSON == "object" && JSON; // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if // available. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports; if (JSON3 && nativeJSON) { // Explicitly delegate to the native `stringify` and `parse` // implementations in CommonJS environments. JSON3.stringify = nativeJSON.stringify; JSON3.parse = nativeJSON.parse; } else { // Export for web browsers, JavaScript engines, and asynchronous module // loaders, using the global `JSON` object if available. JSON3 = window.JSON = nativeJSON || {}; } // Test the `Date#getUTC*` methods. Based on work by @Yaffle. var isExtended = new Date(-3509827334573292); try { // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical // results for certain dates in Opera >= 10.53. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && // Safari < 2.0.2 stores the internal millisecond time value correctly, // but clips the values returned by the date methods to the range of // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]). isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; } catch (exception) {} // Internal: Determines whether the native `JSON.stringify` and `parse` // implementations are spec-compliant. Based on work by Ken Snyder. function has(name) { if (has[name] !== undef) { // Return cached feature test result. return has[name]; } var isSupported; if (name == "bug-string-char-index") { // IE <= 7 doesn't support accessing string characters using square // bracket notation. IE 8 only supports this for primitives. isSupported = "a"[0] != "a"; } else if (name == "json") { // Indicates whether both `JSON.stringify` and `JSON.parse` are // supported. isSupported = has("json-stringify") && has("json-parse"); } else { var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; // Test `JSON.stringify`. if (name == "json-stringify") { var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended; if (stringifySupported) { // A test function object with a custom `toJSON` method. (value = function () { return 1; }).toJSON = value; try { stringifySupported = // Firefox 3.1b1 and b2 serialize string, number, and boolean // primitives as object literals. stringify(0) === "0" && // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object // literals. stringify(new Number()) === "0" && stringify(new String()) == '""' && // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or // does not define a canonical JSON representation (this applies to // objects with `toJSON` properties as well, *unless* they are nested // within an object or array). stringify(getClass) === undef && // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and // FF 3.1b3 pass this test. stringify(undef) === undef && // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s, // respectively, if the value is omitted entirely. stringify() === undef && // FF 3.1b1, 2 throw an error if the given value is not a number, // string, array, object, Boolean, or `null` literal. This applies to // objects with custom `toJSON` methods as well, unless they are nested // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON` // methods entirely. stringify(value) === "1" && stringify([value]) == "[1]" && // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of // `"[null]"`. stringify([undef]) == "[null]" && // YUI 3.0.0b1 fails to serialize `null` literals. stringify(null) == "null" && // FF 3.1b1, 2 halts serialization if an array contains a function: // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3 // elides non-JSON values from objects and arrays, unless they // define custom `toJSON` methods. stringify([undef, getClass, null]) == "[null,null,null]" && // Simple serialization test. FF 3.1b1 uses Unicode escape sequences // where character escape codes are expected (e.g., `\b` => `\u0008`). stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && // FF 3.1b1 and b2 ignore the `filter` and `width` arguments. stringify(null, value) === "1" && stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly // serialize extended years. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && // The milliseconds are optional in ES 5, but required in 5.1. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative // four-digit years instead of six-digit years. Credits: @Yaffle. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond // values less than 1000. Credits: @Yaffle. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; } catch (exception) { stringifySupported = false; } } isSupported = stringifySupported; } // Test `JSON.parse`. if (name == "json-parse") { var parse = JSON3.parse; if (typeof parse == "function") { try { // FF 3.1b1, b2 will throw an exception if a bare literal is provided. // Conforming implementations should also coerce the initial argument to // a string prior to parsing. if (parse("0") === 0 && !parse(false)) { // Simple parsing test. value = parse(serialized); var parseSupported = value["a"].length == 5 && value["a"][0] === 1; if (parseSupported) { try { // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings. parseSupported = !parse('"\t"'); } catch (exception) {} if (parseSupported) { try { // FF 4.0 and 4.0.1 allow leading `+` signs and leading // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow // certain octal literals. parseSupported = parse("01") !== 1; } catch (exception) {} } if (parseSupported) { try { // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal // points. These environments, along with FF 3.1b1 and 2, // also allow trailing commas in JSON objects and arrays. parseSupported = parse("1.") !== 1; } catch (exception) {} } } } } catch (exception) { parseSupported = false; } } isSupported = parseSupported; } } return has[name] = !!isSupported; } if (!has("json")) { // Common `[[Class]]` name aliases. var functionClass = "[object Function]"; var dateClass = "[object Date]"; var numberClass = "[object Number]"; var stringClass = "[object String]"; var arrayClass = "[object Array]"; var booleanClass = "[object Boolean]"; // Detect incomplete support for accessing string characters by index. var charIndexBuggy = has("bug-string-char-index"); // Define additional utility methods if the `Date` methods are buggy. if (!isExtended) { var floor = Math.floor; // A mapping between the months of the year and the number of days between // January 1st and the first of the respective month. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; // Internal: Calculates the number of days between the Unix epoch and the // first day of the given month. var getDay = function (year, month) { return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); }; } // Internal: Determines if a property is a direct property of the given // object. Delegates to the native `Object#hasOwnProperty` method. if (!(isProperty = {}.hasOwnProperty)) { isProperty = function (property) { var members = {}, constructor; if ((members.__proto__ = null, members.__proto__ = { // The *proto* property cannot be set multiple times in recent // versions of Firefox and SeaMonkey. "toString": 1 }, members).toString != getClass) { // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but // supports the mutable *proto* property. isProperty = function (property) { // Capture and break the object's prototype chain (see section 8.6.2 // of the ES 5.1 spec). The parenthesized expression prevents an // unsafe transformation by the Closure Compiler. var original = this.__proto__, result = property in (this.__proto__ = null, this); // Restore the original prototype chain. this.__proto__ = original; return result; }; } else { // Capture a reference to the top-level `Object` constructor. constructor = members.constructor; // Use the `constructor` property to simulate `Object#hasOwnProperty` in // other environments. isProperty = function (property) { var parent = (this.constructor || constructor).prototype; return property in this && !(property in parent && this[property] === parent[property]); }; } members = null; return isProperty.call(this, property); }; } // Internal: A set of primitive types used by `isHostType`. var PrimitiveTypes = { 'boolean': 1, 'number': 1, 'string': 1, 'undefined': 1 }; // Internal: Determines if the given object `property` value is a // non-primitive. var isHostType = function (object, property) { var type = typeof object[property]; return type == 'object' ? !!object[property] : !PrimitiveTypes[type]; }; // Internal: Normalizes the `for...in` iteration algorithm across // environments. Each enumerated key is yielded to a `callback` function. forEach = function (object, callback) { var size = 0, Properties, members, property; // Tests for bugs in the current environment's `for...in` algorithm. The // `valueOf` property inherits the non-enumerable flag from // `Object.prototype` in older versions of IE, Netscape, and Mozilla. (Properties = function () { this.valueOf = 0; }).prototype.valueOf = 0; // Iterate over a new instance of the `Properties` class. members = new Properties(); for (property in members) { // Ignore all properties inherited from `Object.prototype`. if (isProperty.call(members, property)) { size++; } } Properties = members = null; // Normalize the iteration algorithm. if (!size) { // A list of non-enumerable properties inherited from `Object.prototype`. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable // properties. forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, length; var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty; for (property in object) { // Gecko <= 1.0 enumerates the `prototype` property of functions under // certain conditions; IE does not. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { callback(property); } } // Manually invoke the callback for each non-enumerable property. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); }; } else if (size == 2) { // Safari <= 2.0.4 enumerates shadowed properties twice. forEach = function (object, callback) { // Create a set of iterated properties. var members = {}, isFunction = getClass.call(object) == functionClass, property; for (property in object) { // Store each property name to prevent double enumeration. The // `prototype` property of functions is not enumerated due to cross- // environment inconsistencies. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { callback(property); } } }; } else { // No bugs detected; use the standard `for...in` algorithm. forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, isConstructor; for (property in object) { if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { callback(property); } } // Manually invoke the callback for the `constructor` property due to // cross-environment inconsistencies. if (isConstructor || isProperty.call(object, (property = "constructor"))) { callback(property); } }; } return forEach(object, callback); }; // Public: Serializes a JavaScript `value` as a JSON string. The optional // `filter` argument may specify either a function that alters how object and // array members are serialized, or an array of strings and numbers that // indicates which properties should be serialized. The optional `width` // argument may be either a string or number that specifies the indentation // level of the output. if (!has("json-stringify")) { // Internal: A map of control characters and their escaped equivalents. var Escapes = { 92: "\\\\", 34: '\\"', 8: "\\b", 12: "\\f", 10: "\\n", 13: "\\r", 9: "\\t" }; // Internal: Converts `value` into a zero-padded string such that its // length is at least equal to `width`. The `width` must be <= 6. var leadingZeroes = "000000"; var toPaddedString = function (width, value) { // The `|| 0` expression is necessary to work around a bug in // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`. return (leadingZeroes + (value || 0)).slice(-width); }; // Internal: Double-quotes a string `value`, replacing all ASCII control // characters (characters with code unit values between 0 and 31) with // their escaped equivalents. This is an implementation of the // `Quote(value)` operation defined in ES 5.1 section 15.12.3. var unicodePrefix = "\\u00"; var quote = function (value) { var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols; if (isLarge) { symbols = value.split(""); } for (; index < length; index++) { var charCode = value.charCodeAt(index); // If the character is a control character, append its Unicode or // shorthand escape sequence; otherwise, append the character as-is. switch (charCode) { case 8: case 9: case 10: case 12: case 13: case 34: case 92: result += Escapes[charCode]; break; default: if (charCode < 32) { result += unicodePrefix + toPaddedString(2, charCode.toString(16)); break; } result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index]; } } return result + '"'; }; // Internal: Recursively serializes an object. Implements the // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; try { // Necessary for host object support. value = object[property]; } catch (exception) {} if (typeof value == "object" && value) { className = getClass.call(value); if (className == dateClass && !isProperty.call(value, "toJSON")) { if (value > -1 / 0 && value < 1 / 0) { // Dates are serialized according to the `Date#toJSON` method // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15 // for the ISO 8601 date time string format. if (getDay) { // Manually compute the year, month, date, hours, minutes, // seconds, and milliseconds if the `getUTC*` methods are // buggy. Adapted from @Yaffle's `date-shim` project. date = floor(value / 864e5); for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); date = 1 + date - getDay(year, month); // The `time` value specifies the time within the day (see ES // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used // to compute `A modulo B`, as the `%` operator does not // correspond to the `modulo` operation for negative numbers. time = (value % 864e5 + 864e5) % 864e5; // The hours, minutes, seconds, and milliseconds are obtained by // decomposing the time within the day. See section 15.9.1.10. hours = floor(time / 36e5) % 24; minutes = floor(time / 6e4) % 60; seconds = floor(time / 1e3) % 60; milliseconds = time % 1e3; } else { year = value.getUTCFullYear(); month = value.getUTCMonth(); date = value.getUTCDate(); hours = value.getUTCHours(); minutes = value.getUTCMinutes(); seconds = value.getUTCSeconds(); milliseconds = value.getUTCMilliseconds(); } // Serialize extended years correctly. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + // Months, dates, hours, minutes, and seconds should have two // digits; milliseconds should have three. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + // Milliseconds are optional in ES 5.0, but required in 5.1. "." + toPaddedString(3, milliseconds) + "Z"; } else { value = null; } } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3 // ignores all `toJSON` methods on these objects unless they are // defined directly on an instance. value = value.toJSON(property); } } if (callback) { // If a replacement function was provided, call it to obtain the value // for serialization. value = callback.call(object, property, value); } if (value === null) { return "null"; } className = getClass.call(value); if (className == booleanClass) { // Booleans are represented literally. return "" + value; } else if (className == numberClass) { // JSON numbers must be finite. `Infinity` and `NaN` are serialized as // `"null"`. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; } else if (className == stringClass) { // Strings are double-quoted and escaped. return quote("" + value); } // Recursively serialize objects and arrays. if (typeof value == "object") { // Check for cyclic structures. This is a linear search; performance // is inversely proportional to the number of unique nested objects. for (length = stack.length; length--;) { if (stack[length] === value) { // Cyclic structures cannot be serialized by `JSON.stringify`. throw TypeError(); } } // Add the object to the stack of traversed objects. stack.push(value); results = []; // Save the current indentation level and indent one additional level. prefix = indentation; indentation += whitespace; if (className == arrayClass) { // Recursively serialize array elements. for (index = 0, length = value.length; index < length; index++) { element = serialize(index, value, callback, properties, whitespace, indentation, stack); results.push(element === undef ? "null" : element); } result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; } else { // Recursively serialize object members. Members are selected from // either a user-specified list of property names, or the object // itself. forEach(properties || value, function (property) { var element = serialize(property, value, callback, properties, whitespace, indentation, stack); if (element !== undef) { // According to ES 5.1 section 15.12.3: "If `gap` {whitespace} // is not the empty string, let `member` {quote(property) + ":"} // be the concatenation of `member` and the `space` character." // The "`space` character" refers to the literal space // character, not the `space` {width} argument provided to // `JSON.stringify`. results.push(quote(property) + ":" + (whitespace ? " " : "") + element); } }); result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; } // Remove the object from the traversed object stack. stack.pop(); return result; } }; // Public: `JSON.stringify`. See ES 5.1 section 15.12.3. JSON3.stringify = function (source, filter, width) { var whitespace, callback, properties, className; if (typeof filter == "function" || typeof filter == "object" && filter) { if ((className = getClass.call(filter)) == functionClass) { callback = filter; } else if (className == arrayClass) { // Convert the property names array into a makeshift set. properties = {}; for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); } } if (width) { if ((className = getClass.call(width)) == numberClass) { // Convert the `width` to an integer and create a string containing // `width` number of space characters. if ((width -= width % 1) > 0) { for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); } } else if (className == stringClass) { whitespace = width.length <= 10 ? width : width.slice(0, 10); } } // Opera <= 7.54u2 discards the values associated with empty string keys // (`""`) only if they are used directly within an object member list // (e.g., `!("" in { "": 1})`). return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); }; } // Public: Parses a JSON source string. if (!has("json-parse")) { var fromCharCode = String.fromCharCode; // Internal: A map of escaped control characters and their unescaped // equivalents. var Unescapes = { 92: "\\", 34: '"', 47: "/", 98: "\b", 116: "\t", 110: "\n", 102: "\f", 114: "\r" }; // Internal: Stores the parser state. var Index, Source; // Internal: Resets the parser state and throws a `SyntaxError`. var abort = function() { Index = Source = null; throw SyntaxError(); }; // Internal: Returns the next token, or `"$"` if the parser has reached // the end of the source string. A token may be a string, number, `null` // literal, or Boolean literal. var lex = function () { var source = Source, length = source.length, value, begin, position, isSigned, charCode; while (Index < length) { charCode = source.charCodeAt(Index); switch (charCode) { case 9: case 10: case 13: case 32: // Skip whitespace tokens, including tabs, carriage returns, line // feeds, and space characters. Index++; break; case 123: case 125: case 91: case 93: case 58: case 44: // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at // the current position. value = charIndexBuggy ? source.charAt(Index) : source[Index]; Index++; return value; case 34: // `"` delimits a JSON string; advance to the next character and // begin parsing the string. String tokens are prefixed with the // sentinel `@` character to distinguish them from punctuators and // end-of-string tokens. for (value = "@", Index++; Index < length;) { charCode = source.charCodeAt(Index); if (charCode < 32) { // Unescaped ASCII control characters (those with a code unit // less than the space character) are not permitted. abort(); } else if (charCode == 92) { // A reverse solidus (`\`) marks the beginning of an escaped // control character (including `"`, `\`, and `/`) or Unicode // escape sequence. charCode = source.charCodeAt(++Index); switch (charCode) { case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: // Revive escaped control characters. value += Unescapes[charCode]; Index++; break; case 117: // `\u` marks the beginning of a Unicode escape sequence. // Advance to the first character and validate the // four-digit code point. begin = ++Index; for (position = Index + 4; Index < position; Index++) { charCode = source.charCodeAt(Index); // A valid sequence comprises four hexdigits (case- // insensitive) that form a single hexadecimal value. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { // Invalid Unicode escape sequence. abort(); } } // Revive the escaped character. value += fromCharCode("0x" + source.slice(begin, Index)); break; default: // Invalid escape sequence. abort(); } } else { if (charCode == 34) { // An unescaped double-quote character marks the end of the // string. break; } charCode = source.charCodeAt(Index); begin = Index; // Optimize for the common case where a string is valid. while (charCode >= 32 && charCode != 92 && charCode != 34) { charCode = source.charCodeAt(++Index); } // Append the string as-is. value += source.slice(begin, Index); } } if (source.charCodeAt(Index) == 34) { // Advance to the next character and return the revived string. Index++; return value; } // Unterminated string. abort(); default: // Parse numbers and literals. begin = Index; // Advance past the negative sign, if one is specified. if (charCode == 45) { isSigned = true; charCode = source.charCodeAt(++Index); } // Parse an integer or floating-point value. if (charCode >= 48 && charCode <= 57) { // Leading zeroes are interpreted as octal literals. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { // Illegal octal literal. abort(); } isSigned = false; // Parse the integer component. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); // Floats cannot contain a leading decimal point; however, this // case is already accounted for by the parser. if (source.charCodeAt(Index) == 46) { position = ++Index; // Parse the decimal component. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { // Illegal trailing decimal. abort(); } Index = position; } // Parse exponents. The `e` denoting the exponent is // case-insensitive. charCode = source.charCodeAt(Index); if (charCode == 101 || charCode == 69) { charCode = source.charCodeAt(++Index); // Skip past the sign following the exponent, if one is // specified. if (charCode == 43 || charCode == 45) { Index++; } // Parse the exponential component. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { // Illegal empty exponent. abort(); } Index = position; } // Coerce the parsed value to a JavaScript number. return +source.slice(begin, Index); } // A negative sign may only precede numbers. if (isSigned) { abort(); } // `true`, `false`, and `null` literals. if (source.slice(Index, Index + 4) == "true") { Index += 4; return true; } else if (source.slice(Index, Index + 5) == "false") { Index += 5; return false; } else if (source.slice(Index, Index + 4) == "null") { Index += 4; return null; } // Unrecognized token. abort(); } } // Return the sentinel `$` character if the parser has reached the end // of the source string. return "$"; }; // Internal: Parses a JSON `value` token. var get = function (value) { var results, hasMembers; if (value == "$") { // Unexpected end of input. abort(); } if (typeof value == "string") { if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { // Remove the sentinel `@` character. return value.slice(1); } // Parse object and array literals. if (value == "[") { // Parses a JSON array, returning a new JavaScript array. results = []; for (;; hasMembers || (hasMembers = true)) { value = lex(); // A closing square bracket marks the end of the array literal. if (value == "]") { break; } // If the array literal contains elements, the current token // should be a comma separating the previous element from the // next. if (hasMembers) { if (value == ",") { value = lex(); if (value == "]") { // Unexpected trailing `,` in array literal. abort(); } } else { // A `,` must separate each array element. abort(); } } // Elisions and leading commas are not permitted. if (value == ",") { abort(); } results.push(get(value)); } return results; } else if (value == "{") { // Parses a JSON object, returning a new JavaScript object. results = {}; for (;; hasMembers || (hasMembers = true)) { value = lex(); // A closing curly brace marks the end of the object literal. if (value == "}") { break; } // If the object literal contains members, the current token // should be a comma separator. if (hasMembers) { if (value == ",") { value = lex(); if (value == "}") { // Unexpected trailing `,` in object literal. abort(); } } else { // A `,` must separate each object member. abort(); } } // Leading commas are not permitted, object property names must be // double-quoted strings, and a `:` must separate each property // name and value. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { abort(); } results[value.slice(1)] = get(lex()); } return results; } // Unexpected token encountered. abort(); } return value; }; // Internal: Updates a traversed object member. var update = function(source, property, callback) { var element = walk(source, property, callback); if (element === undef) { delete source[property]; } else { source[property] = element; } }; // Internal: Recursively traverses a parsed JSON object, invoking the // `callback` function for each value. This is an implementation of the // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2. var walk = function (source, property, callback) { var value = source[property], length; if (typeof value == "object" && value) { // `forEach` can't be used to traverse an array in Opera <= 8.54 // because its `Object#hasOwnProperty` implementation returns `false` // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`). if (getClass.call(value) == arrayClass) { for (length = value.length; length--;) { update(value, length, callback); } } else { forEach(value, function (property) { update(value, property, callback); }); } } return callback.call(source, property, value); }; // Public: `JSON.parse`. See ES 5.1 section 15.12.2. JSON3.parse = function (source, callback) { var result, value; Index = 0; Source = "" + source; result = get(lex()); // If a JSON string contains multiple tokens, it is invalid. if (lex() != "$") { abort(); } // Reset the parser state. Index = Source = null; return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; }; } } // Export for asynchronous module loaders. if (isLoader) { define(function () { return JSON3; }); } }(this)); },{}],48:[function(_dereq_,module,exports){ module.exports = toArray function toArray(list, index) { var array = [] index = index || 0 for (var i = index || 0; i < list.length; i++) { array[i - index] = list[i] } return array } },{}]},{},[1]) (1) });
/* (c) 2011-2014, Vladimir Agafonkin SunCalc is a JavaScript library for calculating sun/mooon position and light phases. https://github.com/mourner/suncalc */ (function () { 'use strict'; // shortcuts for easier to read formulas var PI = Math.PI, sin = Math.sin, cos = Math.cos, tan = Math.tan, asin = Math.asin, atan = Math.atan2, acos = Math.acos, rad = PI / 180; // sun calculations are based on http://aa.quae.nl/en/reken/zonpositie.html formulas // date/time constants and conversions var dayMs = 1000 * 60 * 60 * 24, J1970 = 2440588, J2000 = 2451545; function toJulian(date) { return date.valueOf() / dayMs - 0.5 + J1970; } function fromJulian(j) { return new Date((j + 0.5 - J1970) * dayMs); } function toDays(date) { return toJulian(date) - J2000; } // general calculations for position var e = rad * 23.4397; // obliquity of the Earth function rightAscension(l, b) { return atan(sin(l) * cos(e) - tan(b) * sin(e), cos(l)); } function declination(l, b) { return asin(sin(b) * cos(e) + cos(b) * sin(e) * sin(l)); } function azimuth(H, phi, dec) { return atan(sin(H), cos(H) * sin(phi) - tan(dec) * cos(phi)); } function altitude(H, phi, dec) { return asin(sin(phi) * sin(dec) + cos(phi) * cos(dec) * cos(H)); } function siderealTime(d, lw) { return rad * (280.16 + 360.9856235 * d) - lw; } // general sun calculations function solarMeanAnomaly(d) { return rad * (357.5291 + 0.98560028 * d); } function eclipticLongitude(M) { var C = rad * (1.9148 * sin(M) + 0.02 * sin(2 * M) + 0.0003 * sin(3 * M)), // equation of center P = rad * 102.9372; // perihelion of the Earth return M + C + P + PI; } function sunCoords(d) { var M = solarMeanAnomaly(d), L = eclipticLongitude(M); return { dec: declination(L, 0), ra: rightAscension(L, 0) }; } var SunCalc = {}; // calculates sun position for a given date and latitude/longitude SunCalc.getPosition = function (date, lat, lng) { var lw = rad * -lng, phi = rad * lat, d = toDays(date), c = sunCoords(d), H = siderealTime(d, lw) - c.ra; return { azimuth: azimuth(H, phi, c.dec), altitude: altitude(H, phi, c.dec) }; }; // sun times configuration (angle, morning name, evening name) var times = SunCalc.times = [ [-0.833, 'sunrise', 'sunset' ], [ -0.3, 'sunriseEnd', 'sunsetStart' ], [ -6, 'dawn', 'dusk' ], [ -12, 'nauticalDawn', 'nauticalDusk'], [ -18, 'nightEnd', 'night' ], [ 6, 'goldenHourEnd', 'goldenHour' ] ]; // adds a custom time to the times config SunCalc.addTime = function (angle, riseName, setName) { times.push([angle, riseName, setName]); }; // calculations for sun times var J0 = 0.0009; function julianCycle(d, lw) { return Math.round(d - J0 - lw / (2 * PI)); } function approxTransit(Ht, lw, n) { return J0 + (Ht + lw) / (2 * PI) + n; } function solarTransitJ(ds, M, L) { return J2000 + ds + 0.0053 * sin(M) - 0.0069 * sin(2 * L); } function hourAngle(h, phi, d) { return acos((sin(h) - sin(phi) * sin(d)) / (cos(phi) * cos(d))); } // returns set time for the given sun altitude function getSetJ(h, lw, phi, dec, n, M, L) { var w = hourAngle(h, phi, dec), a = approxTransit(w, lw, n); return solarTransitJ(a, M, L); } // calculates sun times for a given date and latitude/longitude SunCalc.getTimes = function (date, lat, lng) { var lw = rad * -lng, phi = rad * lat, d = toDays(date), n = julianCycle(d, lw), ds = approxTransit(0, lw, n), M = solarMeanAnomaly(ds), L = eclipticLongitude(M), dec = declination(L, 0), Jnoon = solarTransitJ(ds, M, L), i, len, time, Jset, Jrise; var result = { solarNoon: fromJulian(Jnoon), nadir: fromJulian(Jnoon - 0.5) }; for (i = 0, len = times.length; i < len; i += 1) { time = times[i]; Jset = getSetJ(time[0] * rad, lw, phi, dec, n, M, L); Jrise = Jnoon - (Jset - Jnoon); result[time[1]] = fromJulian(Jrise); result[time[2]] = fromJulian(Jset); } return result; }; // moon calculations, based on http://aa.quae.nl/en/reken/hemelpositie.html formulas function moonCoords(d) { // geocentric ecliptic coordinates of the moon var L = rad * (218.316 + 13.176396 * d), // ecliptic longitude M = rad * (134.963 + 13.064993 * d), // mean anomaly F = rad * (93.272 + 13.229350 * d), // mean distance l = L + rad * 6.289 * sin(M), // longitude b = rad * 5.128 * sin(F), // latitude dt = 385001 - 20905 * cos(M); // distance to the moon in km return { ra: rightAscension(l, b), dec: declination(l, b), dist: dt }; } SunCalc.getMoonPosition = function (date, lat, lng) { var lw = rad * -lng, phi = rad * lat, d = toDays(date), c = moonCoords(d), H = siderealTime(d, lw) - c.ra, h = altitude(H, phi, c.dec); // altitude correction for refraction h = h + rad * 0.017 / tan(h + rad * 10.26 / (h + rad * 5.10)); return { azimuth: azimuth(H, phi, c.dec), altitude: h, distance: c.dist }; }; // calculations for illumination parameters of the moon, // based on http://idlastro.gsfc.nasa.gov/ftp/pro/astro/mphase.pro formulas and // Chapter 48 of "Astronomical Algorithms" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998. SunCalc.getMoonIllumination = function (date) { var d = toDays(date), s = sunCoords(d), m = moonCoords(d), sdist = 149598000, // distance from Earth to Sun in km phi = acos(sin(s.dec) * sin(m.dec) + cos(s.dec) * cos(m.dec) * cos(s.ra - m.ra)), inc = atan(sdist * sin(phi), m.dist - sdist * cos(phi)), angle = atan(cos(s.dec) * sin(s.ra - m.ra), sin(s.dec) * cos(m.dec) - cos(s.dec) * sin(m.dec) * cos(s.ra - m.ra)); return { fraction: (1 + cos(inc)) / 2, phase: 0.5 + 0.5 * inc * (angle < 0 ? -1 : 1) / Math.PI, angle: angle }; }; function hoursLater(date, h) { return new Date(date.valueOf() + h * dayMs / 24); } // calculations for moon rise/set times are based on http://www.stargazing.net/kepler/moonrise.html article SunCalc.getMoonTimes = function (date, lat, lng) { var t = new Date(date); t.setHours(0); t.setMinutes(0); t.setSeconds(0); t.setMilliseconds(0); var hc = 0.133 * rad, h0 = SunCalc.getMoonPosition(t, lat, lng).altitude - hc, h1, h2, rise, set, a, b, xe, ye, d, roots, x1, x2, dx; // go in 2-hour chunks, each time seeing if a 3-point quadratic curve crosses zero (which means rise or set) for (var i = 1; i <= 24; i += 2) { h1 = SunCalc.getMoonPosition(hoursLater(t, i), lat, lng).altitude - hc; h2 = SunCalc.getMoonPosition(hoursLater(t, i + 1), lat, lng).altitude - hc; a = (h0 + h2) / 2 - h1; b = (h2 - h0) / 2; xe = -b / (2 * a); ye = (a * xe + b) * xe + h1; d = b * b - 4 * a * h1; roots = 0; if (d >= 0) { dx = Math.sqrt(d) / (Math.abs(a) * 2); x1 = xe - dx; x2 = xe + dx; if (Math.abs(x1) <= 1) roots++; if (Math.abs(x2) <= 1) roots++; if (x1 < -1) x1 = x2; } if (roots === 1) { if (h0 < 0) rise = i + x1; else set = i + x1; } else if (roots === 2) { rise = i + (ye < 0 ? x2 : x1); set = i + (ye < 0 ? x1 : x2); } if (rise && set) break; h0 = h2; } var result = {}; if (rise) result.rise = hoursLater(t, rise); if (set) result.set = hoursLater(t, set); if (!rise && !set) result[ye > 0 ? 'alwaysUp' : 'alwaysDown'] = true; return result; }; // export as AMD module / Node module / browser variable if (typeof define === 'function' && define.amd) define(SunCalc); else if (typeof module !== 'undefined') module.exports = SunCalc; else window.SunCalc = SunCalc; }());
~a
'use strict'; flnd.locationCreate = { configureSubmit: function($scope, config, messenger, authService, $uibModalInstance) { return function() { $scope.loading = true; authService.post(config.locations, $scope.location) .then(function success() { $uibModalInstance.close(); }, function error(response) { messenger.displayErrorResponse($scope, response); }) .finally(function() { $scope.loading = false; }); }; } }; /** * @ngdoc function * @name flightNodeApp.controller.location:LocationCreateController * @description * # LocationCreateController * Controller for the create work type page. */ angular.module('flightNodeApp') .controller('LocationCreateController', ['$scope', '$http', '$log', '$location', 'messenger', 'authService', 'config', '$uibModalInstance', function($scope, $http, $log, $location, messenger, authService, config, $uibModalInstance) { if (!authService.isAdministrator()) { $log.warn('not authorized to access this path'); $location.path('/'); return; } $scope.loading = true; $scope.cancel = function() { $uibModalInstance.dismiss('cancel'); }; $scope.submit = flnd.locationCreate.configureSubmit($scope, config, messenger, authService, $uibModalInstance); $scope.loading = false; } ]);
define({ "taskUrl": "URL adresa zadatka", "serviceURLPlaceholder": "Unesite URL adresu zadatka geoprocesiranja", "layerOrder": "Redosled sloja", "defaultValue": "Podrazumevana vrednost", "inputFeatureBy": "Unos geoobjekata po", "inputRecordBy": "Unesite zapis po", "renderer": "Prikazivač", "displayType": "Tip prikaza", "helpUrl": "URL adresa pomoći", "useResultMapService": "Prikaži rezultat pomoću servisa mape", "drawOnMap": "Interaktivno crtajte na mapi", "selectLayer": "Izaberite sloj sa mape", "selectTable": "Izaberite tabelu sa mape", "shareResults": "Dodaj rezultate kao operativni sloj", "setTask": "Postavi", "setTaskTitle": "Postavi zadatak GP", "enablePopup": "Omogući iskačuće prozore", "unSupportGeometryType": "Ne može da postavi renderovanje zbog nepoznatog geometrijskog tipa.", "useUrlForGPInput": "URL adresa", "useUploadForGPInput": "Otpremi datoteku", "selectFileToUpload": "Izaberite datoteku...", "rasterFormat": "Format rasterskih podataka", "noFileSelected": "Nema izabrane datoteke!", "uploadSuccess": "Datoteka uspešno otpremljena!", "showLayerContent": "Prikaži sadržaj sloja", "urlPlaceholder": "URL adresa za pristup podacima", "useShapefile": "Koristite datoteku „shapefile“ u lokalnom sistemu datoteka", "allowToExport": "Dozvoli izvoz rezultata", "useDynamicSchema": "Izvoz može da ima različitu šemu, koristite dinamičnu šemu umesto predefinisane.", "useCurrentMapExtent": "Koristi trenutni obuhvat mape", "ignoreOutput": "Zanemari ovaj izlazni rezultat", "turnOffOutput": "Podrazumevano isključi ovaj sloj", "inputJSONString": "Unesite JSON nisku" });
/* globals slug:true, slugify, LDAP, getLdapUsername:true, getLdapUserUniqueID:true, getDataToSyncUserData:true, syncUserData:true, sync:true, addLdapUser:true */ const logger = new Logger('LDAPSync', {}); slug = function slug(text) { if (RocketChat.settings.get('UTF8_Names_Slugify') !== true) { return text; } text = slugify(text, '.'); return text.replace(/[^0-9a-z-_.]/g, ''); }; getLdapUsername = function getLdapUsername(ldapUser) { const usernameField = RocketChat.settings.get('LDAP_Username_Field'); if (usernameField.indexOf('#{') > -1) { return usernameField.replace(/#{(.+?)}/g, function(match, field) { return ldapUser.object[field]; }); } return ldapUser.object[usernameField]; }; getLdapUserUniqueID = function getLdapUserUniqueID(ldapUser) { let Unique_Identifier_Field = RocketChat.settings.get('LDAP_Unique_Identifier_Field'); if (Unique_Identifier_Field !== '') { Unique_Identifier_Field = Unique_Identifier_Field.replace(/\s/g, '').split(','); } else { Unique_Identifier_Field = []; } let LDAP_Domain_Search_User_ID = RocketChat.settings.get('LDAP_Domain_Search_User_ID'); if (LDAP_Domain_Search_User_ID !== '') { LDAP_Domain_Search_User_ID = LDAP_Domain_Search_User_ID.replace(/\s/g, '').split(','); } else { LDAP_Domain_Search_User_ID = []; } Unique_Identifier_Field = Unique_Identifier_Field.concat(LDAP_Domain_Search_User_ID); if (Unique_Identifier_Field.length > 0) { Unique_Identifier_Field = Unique_Identifier_Field.find((field) => { return !_.isEmpty(ldapUser.object[field]); }); if (Unique_Identifier_Field) { Unique_Identifier_Field = { attribute: Unique_Identifier_Field, value: ldapUser.raw[Unique_Identifier_Field].toString('hex') }; } return Unique_Identifier_Field; } }; getDataToSyncUserData = function getDataToSyncUserData(ldapUser, user) { const syncUserData = RocketChat.settings.get('LDAP_Sync_User_Data'); const syncUserDataFieldMap = RocketChat.settings.get('LDAP_Sync_User_Data_FieldMap').trim(); if (syncUserData && syncUserDataFieldMap) { const fieldMap = JSON.parse(syncUserDataFieldMap); const userData = {}; const emailList = []; _.map(fieldMap, function(userField, ldapField) { switch (userField) { case 'email': if (!ldapUser.object.hasOwnProperty(ldapField)) { logger.debug(`user does not have attribute: ${ ldapField }`); return; } if (_.isObject(ldapUser.object[ldapField])) { _.map(ldapUser.object[ldapField], function(item) { emailList.push({ address: item, verified: true }); }); } else { emailList.push({ address: ldapUser.object[ldapField], verified: true }); } break; case 'name': const templateRegex = /#{(\w+)}/gi; let match = templateRegex.exec(ldapField); let tmpLdapField = ldapField; if (match == null) { if (!ldapUser.object.hasOwnProperty(ldapField)) { logger.debug(`user does not have attribute: ${ ldapField }`); return; } tmpLdapField = ldapUser.object[ldapField]; } else { logger.debug('template found. replacing values'); while (match != null) { const tmplVar = match[0]; const tmplAttrName = match[1]; if (!ldapUser.object.hasOwnProperty(tmplAttrName)) { logger.debug(`user does not have attribute: ${ tmplAttrName }`); return; } const attrVal = ldapUser.object[tmplAttrName]; logger.debug(`replacing template var: ${ tmplVar } with value from ldap: ${ attrVal }`); tmpLdapField = tmpLdapField.replace(tmplVar, attrVal); match = templateRegex.exec(ldapField); } } if (user.name !== tmpLdapField) { userData.name = tmpLdapField; logger.debug(`user.name changed to: ${ tmpLdapField }`); } break; } }); if (emailList.length > 0) { if (JSON.stringify(user.emails) !== JSON.stringify(emailList)) { userData.emails = emailList; } } const uniqueId = getLdapUserUniqueID(ldapUser); if (uniqueId && (!user.services || !user.services.ldap || user.services.ldap.id !== uniqueId.value || user.services.ldap.idAttribute !== uniqueId.attribute)) { userData['services.ldap.id'] = uniqueId.value; userData['services.ldap.idAttribute'] = uniqueId.attribute; } if (user.ldap !== true) { userData.ldap = true; } if (_.size(userData)) { return userData; } } }; syncUserData = function syncUserData(user, ldapUser) { logger.info('Syncing user data'); logger.debug('user', {'email': user.email, '_id': user._id}); logger.debug('ldapUser', ldapUser); const userData = getDataToSyncUserData(ldapUser, user); if (user && user._id && userData) { logger.debug('setting', JSON.stringify(userData, null, 2)); if (userData.name) { RocketChat._setRealName(user._id, userData.name); delete userData.name; } Meteor.users.update(user._id, { $set: userData }); user = Meteor.users.findOne({_id: user._id}); } if (RocketChat.settings.get('LDAP_Username_Field') !== '') { const username = slug(getLdapUsername(ldapUser)); if (user && user._id && username !== user.username) { logger.info('Syncing user username', user.username, '->', username); RocketChat._setUsername(user._id, username); } } if (user && user._id && RocketChat.settings.get('LDAP_Sync_User_Avatar') === true) { const avatar = ldapUser.raw.thumbnailPhoto || ldapUser.raw.jpegPhoto; if (avatar) { logger.info('Syncing user avatar'); const rs = RocketChatFile.bufferToStream(avatar); RocketChatFileAvatarInstance.deleteFile(encodeURIComponent(`${ user.username }.jpg`)); const ws = RocketChatFileAvatarInstance.createWriteStream(encodeURIComponent(`${ user.username }.jpg`), 'image/jpeg'); ws.on('end', Meteor.bindEnvironment(function() { Meteor.setTimeout(function() { RocketChat.models.Users.setAvatarOrigin(user._id, 'ldap'); RocketChat.Notifications.notifyLogged('updateAvatar', {username: user.username}); }, 500); })); rs.pipe(ws); } } }; addLdapUser = function addLdapUser(ldapUser, username, password) { const userObject = { username }; const userData = getDataToSyncUserData(ldapUser, {}); if (userData && userData.emails) { userObject.email = userData.emails[0].address; } else if (ldapUser.object.mail && ldapUser.object.mail.indexOf('@') > -1) { userObject.email = ldapUser.object.mail; } else if (RocketChat.settings.get('LDAP_Default_Domain') !== '') { userObject.email = `${ username }@${ RocketChat.settings.get('LDAP_Default_Domain') }`; } else { const error = new Meteor.Error('LDAP-login-error', 'LDAP Authentication succeded, there is no email to create an account. Have you tried setting your Default Domain in LDAP Settings?'); logger.error(error); throw error; } logger.debug('New user data', userObject); if (password) { userObject.password = password; } try { userObject._id = Accounts.createUser(userObject); } catch (error) { logger.error('Error creating user', error); throw error; } syncUserData(userObject, ldapUser); return { userId: userObject._id }; }; sync = function sync() { if (RocketChat.settings.get('LDAP_Enable') !== true) { return; } const ldap = new LDAP(); try { ldap.connectSync(); const users = RocketChat.models.Users.findLDAPUsers(); if (RocketChat.settings.get('LDAP_Import_Users') === true && RocketChat.settings.get('LDAP_Username_Field') !== '') { const ldapUsers = ldap.searchUsersSync('*'); ldapUsers.forEach(function(ldapUser) { const username = slug(getLdapUsername(ldapUser)); // Look to see if user already exists const userQuery = { username }; logger.debug('userQuery', userQuery); const user = Meteor.users.findOne(userQuery); if (!user) { addLdapUser(ldapUser, username); } else if (user.ldap !== true && RocketChat.settings.get('LDAP_Merge_Existing_Users') === true) { syncUserData(user, ldapUser); } }); } users.forEach(function(user) { let ldapUser; if (user.services && user.services.ldap && user.services.ldap.id) { ldapUser = ldap.getUserByIdSync(user.services.ldap.id, user.services.ldap.idAttribute); } else { ldapUser = ldap.getUserByUsernameSync(user.username); } if (ldapUser) { syncUserData(user, ldapUser); } else { logger.info('Can\'t sync user', user.username); } }); } catch (error) { logger.error(error); return error; } ldap.disconnect(); return true; }; let interval; let timeout; RocketChat.settings.get('LDAP_Sync_User_Data', function(key, value) { Meteor.clearInterval(interval); Meteor.clearTimeout(timeout); if (value === true) { logger.info('Enabling LDAP user sync'); interval = Meteor.setInterval(sync, 1000 * 60 * 60); timeout = Meteor.setTimeout(function() { sync(); }, 1000 * 60 * 10); } else { logger.info('Disabling LDAP user sync'); } });
// JavaScript Document function checkConnection() { var states = {}; states[Connection.UNKNOWN] = 'Unknown connection'; states[Connection.ETHERNET] = 'Ethernet connection'; states[Connection.WIFI] = 'WiFi connection'; states[Connection.CELL_2G] = 'Cell 2G connection'; states[Connection.CELL_3G] = 'Cell 3G connection'; states[Connection.CELL_4G] = 'Cell 4G connection'; states[Connection.CELL] = 'Cell generic connection'; states[Connection.NONE] = 'No network connection'; } var networkState; var app = { initialize: function() { this.bindEvents(); }, bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, onDeviceReady: function() { networkState = navigator.connection.type; checkConnection(); if(networkState==Connection.NONE) alert("SIN ACCESO A INTERNET"); else { app.receivedEvent('deviceready'); } }, receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); var pushNotification = window.plugins.pushNotification; if (device.platform == 'android' || device.platform == 'Android') { alert("Bienvenido al Aquarium"); //tu Project ID aca!! pushNotification.register(this.successHandler, this.errorHandler,{"senderID":"4153173290","ecb":"app.onNotificationGCM"}); } else { alert("Bienvenido al Aquarium"); pushNotification.register(this.successHandler,this.errorHandler,{"badge":"true","sound":"true","alert":"true","ecb":"app.onNotificationAPN"}); } }, // result contains any message sent from the plugin call successHandler: function(result) { //alert('Callback Success! Result = '+result) }, errorHandler:function(error) { alert(error); }, onNotificationGCM: function(e) { switch( e.event ) { case 'registered': if ( e.regid.length > 0 ) { console.log("Regid " + e.regid); //alert('registration id = '+e.regid); //Cuando se registre le pasamos el regid al input document.getElementById('regId').value = e.regid; } break; case 'message': // NOTIFICACION!!! alert('message = '+e.message); break; case 'error': alert('Eror de Coenxion = '+e.msg); break; default: alert('Sin Mensajes'); break; } }, onNotificationAPN: function(event) { var pushNotification = window.plugins.pushNotification; alert("Running in JS - onNotificationAPN - Received a notification! " + event.alert); if (event.alert) { navigator.notification.alert(event.alert); } if (event.badge) { pushNotification.setApplicationIconBadgeNumber(this.successHandler, this.errorHandler, event.badge); } if (event.sound) { var snd = new Media(event.sound); snd.play(); } } };
'use strict'; module.exports = { try: require('./try'), 'try:testall': require('./testall'), 'try:reset': require('./reset'), 'try:each': require('./try-each'), 'try:one': require('./try-one'), 'try:ember': require('./try-ember'), 'try:config': require('./config') };
'use strict'; // 0.10.x versions of Node serialize Buffers as arrays instead of objects if (process.version.substring(0, 6) === 'v0.10.') { Buffer.prototype.toJSON = function() { return { type: 'Buffer', data: Array.prototype.slice.call(this, 0) }; }; }
module.exports={A:{A:{"8":"H E G C WB","900":"B","1924":"A"},B:{"1":"D u g I J"},C:{"1":"0 1 2 3 4 5 6 V W X v Z a b c d N f M h i j k l m n o p q r s t y K","8":"UB x SB","516":"T U","772":"F L H E G C B A D u g I J Y O e P Q R S RB"},D:{"1":"0 1 2 3 4 5 6 X v Z a b c d N f M h i j k l m n o p q r s t y K GB AB CB VB DB EB","8":"F L H E","516":"T U V W","772":"S","900":"G C B A D u g I J Y O e P Q R"},E:{"1":"E G C B A JB KB LB MB","8":"9 F L FB","900":"H HB IB"},F:{"1":"I J Y O e P Q R S T U V W X v Z a b c d N f M h i j k l m n o p q r s t","8":"8 C A NB OB PB QB","900":"7 D TB w"},G:{"1":"G A ZB aB bB cB dB eB","8":"9 BB z","900":"XB YB"},H:{"900":"fB"},I:{"1":"K kB lB","8":"gB hB iB","900":"x F jB z"},J:{"1":"B","900":"E"},K:{"1":"M","8":"B A","900":"7 8 D w"},L:{"1":"AB"},M:{"1":"K"},N:{"900":"B A"},O:{"1":"mB"},P:{"1":"F L"},Q:{"1":"nB"},R:{"1":"oB"}},B:1,C:"classList (DOMTokenList)"};
'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _Observable2 = require('./Observable'); var _Observable3 = _interopRequireDefault(_Observable2); var _Subscriber = require('./Subscriber'); var _Subscriber2 = _interopRequireDefault(_Subscriber); var _Subscription = require('./Subscription'); var _Subscription2 = _interopRequireDefault(_Subscription); var _subjectsSubjectSubscription = require('./subjects/SubjectSubscription'); var _subjectsSubjectSubscription2 = _interopRequireDefault(_subjectsSubjectSubscription); var subscriptionAdd = _Subscription2['default'].prototype.add; var subscriptionRemove = _Subscription2['default'].prototype.remove; var subscriptionUnsubscribe = _Subscription2['default'].prototype.unsubscribe; var subscriberNext = _Subscriber2['default'].prototype.next; var subscriberError = _Subscriber2['default'].prototype.error; var subscriberComplete = _Subscriber2['default'].prototype.complete; var _subscriberNext = _Subscriber2['default'].prototype._next; var _subscriberError = _Subscriber2['default'].prototype._error; var _subscriberComplete = _Subscriber2['default'].prototype._complete; var Subject = (function (_Observable) { _inherits(Subject, _Observable); function Subject() { _classCallCheck(this, Subject); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _Observable.call.apply(_Observable, [this].concat(args)); this.observers = []; this.isUnsubscribed = false; this.dispatching = false; this.errorSignal = false; this.completeSignal = false; } Subject.create = function create(source, destination) { return new BidirectionalSubject(source, destination); }; Subject.prototype.lift = function lift(operator) { var subject = new BidirectionalSubject(this, this.destination || this); subject.operator = operator; return subject; }; Subject.prototype._subscribe = function _subscribe(subscriber) { if (subscriber.isUnsubscribed) { return; } else if (this.errorSignal) { subscriber.error(this.errorInstance); return; } else if (this.completeSignal) { subscriber.complete(); return; } else if (this.isUnsubscribed) { throw new Error("Cannot subscribe to a disposed Subject."); } this.observers.push(subscriber); return new _subjectsSubjectSubscription2['default'](this, subscriber); }; Subject.prototype.add = function add(subscription) { subscriptionAdd.call(this, subscription); }; Subject.prototype.remove = function remove(subscription) { subscriptionRemove.call(this, subscription); }; Subject.prototype.unsubscribe = function unsubscribe() { this.observers = void 0; subscriptionUnsubscribe.call(this); }; Subject.prototype.next = function next(value) { if (this.isUnsubscribed) { return; } this.dispatching = true; this._next(value); this.dispatching = false; if (this.errorSignal) { this.error(this.errorInstance); } else if (this.completeSignal) { this.complete(); } }; Subject.prototype.error = function error(_error) { if (this.isUnsubscribed || this.completeSignal) { return; } this.errorSignal = true; this.errorInstance = _error; if (this.dispatching) { return; } this._error(_error); this.unsubscribe(); }; Subject.prototype.complete = function complete() { if (this.isUnsubscribed || this.errorSignal) { return; } this.completeSignal = true; if (this.dispatching) { return; } this._complete(); this.unsubscribe(); }; Subject.prototype._next = function _next(value) { var index = -1; var observers = this.observers.slice(0); var len = observers.length; while (++index < len) { observers[index].next(value); } }; Subject.prototype._error = function _error(error) { var index = -1; var observers = this.observers; var len = observers.length; // optimization -- block next, complete, and unsubscribe while dispatching this.observers = void 0; this.isUnsubscribed = true; while (++index < len) { observers[index].error(error); } this.isUnsubscribed = false; }; Subject.prototype._complete = function _complete() { var index = -1; var observers = this.observers; var len = observers.length; // optimization -- block next, complete, and unsubscribe while dispatching this.observers = void 0; // optimization this.isUnsubscribed = true; while (++index < len) { observers[index].complete(); } this.isUnsubscribed = false; }; return Subject; })(_Observable3['default']); exports['default'] = Subject; var BidirectionalSubject = (function (_Subject) { _inherits(BidirectionalSubject, _Subject); function BidirectionalSubject(source, destination) { _classCallCheck(this, BidirectionalSubject); _Subject.call(this); this.source = source; this.destination = destination; } //# sourceMappingURL=Subject.js.map BidirectionalSubject.prototype._subscribe = function _subscribe(subscriber) { var operator = this.operator; return this.source._subscribe.call(this.source, operator ? operator.call(subscriber) : subscriber); }; BidirectionalSubject.prototype.next = function next(x) { subscriberNext.call(this, x); }; BidirectionalSubject.prototype.error = function error(e) { subscriberError.call(this, e); }; BidirectionalSubject.prototype.complete = function complete() { subscriberComplete.call(this); }; BidirectionalSubject.prototype._next = function _next(x) { _subscriberNext.call(this, x); }; BidirectionalSubject.prototype._error = function _error(e) { _subscriberError.call(this, e); }; BidirectionalSubject.prototype._complete = function _complete() { _subscriberComplete.call(this); }; return BidirectionalSubject; })(Subject); module.exports = exports['default']; //# sourceMappingURL=Subject.js.map
import React from "react"; import { BrowserRouter as Router, Switch, Route, Link, useParams, useRouteMatch } from "react-router-dom"; // Since routes are regular React components, they // may be rendered anywhere in the app, including in // child elements. // // This helps when it's time to code-split your app // into multiple bundles because code-splitting a // React Router app is the same as code-splitting // any other React app. export default function NestingExample() { return ( <Router> <div> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/topics">Topics</Link> </li> </ul> <hr /> <Switch> <Route exact path="/"> <Home /> </Route> <Route path="/topics"> <Topics /> </Route> </Switch> </div> </Router> ); } function Home() { return ( <div> <h2>Home</h2> </div> ); } function Topics() { // The `path` lets us build <Route> paths that are // relative to the parent route, while the `url` lets // us build relative links. let { path, url } = useRouteMatch(); return ( <div> <h2>Topics</h2> <ul> <li> <Link to={`${url}/rendering`}>Rendering with React</Link> </li> <li> <Link to={`${url}/components`}>Components</Link> </li> <li> <Link to={`${url}/props-v-state`}>Props v. State</Link> </li> </ul> <Switch> <Route exact path={path}> <h3>Please select a topic.</h3> </Route> <Route path={`${path}/:topicId`}> <Topic /> </Route> </Switch> </div> ); } function Topic() { // The <Route> that rendered this component has a // path of `/topics/:topicId`. The `:topicId` portion // of the URL indicates a placeholder that we can // get from `useParams()`. let { topicId } = useParams(); return ( <div> <h3>{topicId}</h3> </div> ); }
/*jshint node:true, laxcomma:true */ var process_metrics = function (metrics, flushInterval, ts, flushCallback) { var starttime = Date.now(); var key; var counter_rates = {}; var timer_data = {}; var statsd_metrics = {}; var counters = metrics.counters; var timers = metrics.timers; var timer_counters = metrics.timer_counters; var pctThreshold = metrics.pctThreshold; var histogram = metrics.histogram; for (key in counters) { var value = counters[key]; // calculate "per second" rate counter_rates[key] = value / (flushInterval / 1000); } for (key in timers) { if (timers[key].length > 0) { timer_data[key] = {}; var current_timer_data = {}; var values = timers[key].sort(function (a,b) { return a-b; }); var count = values.length; var min = values[0]; var max = values[count - 1]; var cumulativeValues = [min]; for (var i = 1; i < count; i++) { cumulativeValues.push(values[i] + cumulativeValues[i-1]); } var sum = min; var mean = min; var thresholdBoundary = max; var key2; for (key2 in pctThreshold) { var pct = pctThreshold[key2]; if (count > 1) { var numInThreshold = Math.round(Math.abs(pct) / 100 * count); if (numInThreshold === 0) { continue; } if (pct > 0) { thresholdBoundary = values[numInThreshold - 1]; sum = cumulativeValues[numInThreshold - 1]; } else { thresholdBoundary = values[count - numInThreshold]; sum = cumulativeValues[count - 1] - cumulativeValues[count - numInThreshold - 1]; } mean = sum / numInThreshold; } var clean_pct = '' + pct; clean_pct = clean_pct.replace('.', '_').replace('-', 'top'); current_timer_data["mean_" + clean_pct] = mean; current_timer_data[(pct > 0 ? "upper_" : "lower_") + clean_pct] = thresholdBoundary; current_timer_data["sum_" + clean_pct] = sum; } sum = cumulativeValues[count-1]; mean = sum / count; var sumOfDiffs = 0; for (var i = 0; i < count; i++) { sumOfDiffs += (values[i] - mean) * (values[i] - mean); } var mid = Math.floor(count/2); var median = (count % 2) ? values[mid] : (values[mid-1] + values[mid])/2; var stddev = Math.sqrt(sumOfDiffs / count); current_timer_data["std"] = stddev; current_timer_data["upper"] = max; current_timer_data["lower"] = min; current_timer_data["count"] = timer_counters[key]; current_timer_data["count_ps"] = timer_counters[key] / (flushInterval / 1000); current_timer_data["sum"] = sum; current_timer_data["mean"] = mean; current_timer_data["median"] = median; // note: values bigger than the upper limit of the last bin are ignored, by design conf = histogram || []; bins = []; for (var i = 0; i < conf.length; i++) { if (key.indexOf(conf[i].metric) > -1) { bins = conf[i].bins; break; } } if(bins.length) { current_timer_data['histogram'] = {}; } // the outer loop iterates bins, the inner loop iterates timer values; // within each run of the inner loop we should only consider the timer value range that's within the scope of the current bin // so we leverage the fact that the values are already sorted to end up with only full 1 iteration of the entire values range var i = 0; for (var bin_i = 0; bin_i < bins.length; bin_i++) { var freq = 0; for (; i < count && (bins[bin_i] == 'inf' || values[i] < bins[bin_i]); i++) { freq += 1; } bin_name = 'bin_' + bins[bin_i]; current_timer_data['histogram'][bin_name] = freq; } timer_data[key] = current_timer_data; } } statsd_metrics["processing_time"] = (Date.now() - starttime); //add processed metrics to the metrics_hash metrics.counter_rates = counter_rates; metrics.timer_data = timer_data; metrics.statsd_metrics = statsd_metrics; flushCallback(metrics); }; exports.process_metrics = process_metrics;
System.register(["babel-runtime/helpers/to-consumable-array"], function (_export) { var _toConsumableArray; return { setters: [function (_babelRuntimeHelpersToConsumableArray) { _toConsumableArray = _babelRuntimeHelpersToConsumableArray["default"]; }], execute: function () { "use strict"; foo.apply(undefined, _toConsumableArray(bar)); } }; });
const Event = require('./event.js'); class GroupedCardEvent extends Event { allowAutomaticSave() { return false; } saveCard(card) { this.removeCard(card); card.markAsSaved(); card.game.raiseEvent('onCardSaved', { card: card }); } removeCard(card) { this.cards = this.cards.filter(c => c !== card); let primaryEvents = this.childEvents.map(event => event.getPrimaryEvent()); for(let event of primaryEvents) { if(event.card === card) { event.cancel(); } } if(this.cards.length === 0) { this.cancel(); } } replaceCards(newCards) { if(newCards.length !== this.childEvents.length) { return; } let index = 0; for(let card of newCards) { this.childEvents[index].card = card; ++index; } this.cards = newCards; } onChildCancelled(event) { super.onChildCancelled(event); this.removeCard(event.card); } } module.exports = GroupedCardEvent;
"use strict"; // checks basic globals to help determine which environment we are in exports.isNode = function() { return typeof require === "function" && typeof exports === "object" && typeof module === "object" && typeof window === "undefined"; };
/********************************************************************** * ELYCHARTS * A Javascript library to generate interactive charts with vectorial graphics. * * Copyright (c) 2010-2014 Void Labs s.n.c. (http://void.it) * Licensed under the MIT (http://creativecommons.org/licenses/MIT/) license. **********************************************************************/ (function($) { var common = $.elycharts.common; /*********************************************************************** * CHART: BARLINE * * Singola barra orizzontale contenente vari valori. * * L'idea è che possa essere vista come una linechart orizzontale * invece di verticale, con solo serie di tipo bar e con un solo valore. * In futuro (quando sarà possibile far linechart orizzontali) potrebbe * proprio essere renderizzata in questo modo. **********************************************************************/ $.elycharts.barline = { init : function($env) { }, draw : function(env) { var paper = env.paper; var opt = env.opt; env.xmin = opt.margins[3]; env.xmax = env.width - opt.margins[1]; env.ymin = opt.margins[0]; env.ymax = env.height - opt.margins[2]; var maxvalue = 0; for (var serie in opt.values) { var values = opt.values[serie]; var value = values[0]; var plot = { props : common.areaProps(env, 'Series', serie) }; env.plots[serie] = plot; if (!plot.props.stacked || !env.plots[plot.props.stacked]) { plot.from = 0; } else { plot.from = env.plots[plot.props.stacked].to; } plot.to = plot.from + value; if (plot.to > maxvalue) maxvalue = plot.to; } // TODO opt.max dovrebbe essere opt.axis[?].max ? if (typeof opt.max != 'undefined') maxvalue = opt.max; if (!maxvalue) maxvalue = 1; var pieces = []; for (serie in opt.values) { plot = env.plots[serie]; var d = (env.xmax - env.xmin) / maxvalue; if (opt.direction != 'rtl') pieces.push({ paths : [ { path : [ [ 'RECT', env.xmin + d * plot.from, env.ymin, env.xmin + d * plot.to, env.ymax] ], attr : plot.props.plotProps } ], section: 'Series', serie: serie, subSection : 'Plot', mousearea : 'paths' }); else pieces.push({ paths : [ { path : [ [ 'RECT', env.xmax - d * plot.from, env.ymin, env.xmax - d * plot.to, env.ymax] ], attr : plot.props.plotProps } ], section: 'Series', serie: serie, subSection : 'Plot', mousearea : 'paths' }); } return pieces; } }; })(jQuery);
'use strict'; var toString = Object.prototype.toString; /** * Extract names from functions. * * @param {Function} fn The function who's name we need to extract. * @returns {String} * @api public */ module.exports = function name(fn) { if ('string' === typeof fn.displayName && fn.constructor.name) { return fn.displayName; } else if ('string' === typeof fn.name && fn.name) { return fn.name; } // // Check to see if the constructor has a name. // if ( 'object' === typeof fn && fn.constructor && 'string' === typeof fn.constructor.name ) return fn.constructor.name; // // toString the given function and attempt to parse it out of it, or determine // the class. // var named = fn.toString() , type = toString.call(fn).slice(8, -1); if ('Function' === type) { named = named.substring(named.indexOf('(') + 1, named.indexOf(')')); } else { named = type; } return named || 'anonymous'; };
version https://git-lfs.github.com/spec/v1 oid sha256:cc822d3b1de21728d5eb668bf12f69f8a22270146e02fa260cc4ee66d2b12021 size 14724
"use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(require("./role")); __export(require("./policy")); __export(require("./user")); __export(require("./group")); // AWS::IAM CloudFormation Resources: __export(require("./iam.generated")); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLDRCQUF1QjtBQUN2Qiw4QkFBeUI7QUFDekIsNEJBQXVCO0FBQ3ZCLDZCQUF3QjtBQUV4QixxQ0FBcUM7QUFDckMscUNBQWdDIn0=
/** * Module dependencies. */ var EventEmitter = require('events').EventEmitter , MongooseError = require('./error') , MixedSchema = require('./schema/mixed') , Schema = require('./schema') , ValidatorError = require('./schematype').ValidatorError , utils = require('./utils') , clone = utils.clone , isMongooseObject = utils.isMongooseObject , inspect = require('util').inspect , StateMachine = require('./statemachine') , ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default') , deepEqual = utils.deepEqual , hooks = require('hooks') , DocumentArray /** * Document constructor. * * @param {Object} values to set * @api private */ function Document (obj, fields) { // node <0.4.3 bug if (!this._events) this._events = {}; this.setMaxListeners(0); this._strictMode = this.schema.options && this.schema.options.strict; if ('boolean' === typeof fields) { this._strictMode = fields; fields = undefined; } else { this._selected = fields; } this._activePaths = new ActiveRoster(); this._doc = this.buildDoc(fields); var self = this; this.schema.requiredPaths.forEach(function (path) { self._activePaths.require(path); }); this._saveError = null; this._validationError = null; this.isNew = true; if (obj) this.set(obj, undefined, true); this._registerHooks(); this.doQueue(); this.errors = undefined; this._shardval = undefined; }; /** * Inherit from EventEmitter. */ Document.prototype.__proto__ = EventEmitter.prototype; /** * Base Mongoose instance for the model. Set by the Mongoose instance upon * pre-compilation. * * @api public */ Document.prototype.base; /** * Document schema as a nested structure. * * @api public */ Document.prototype.schema; /** * Whether the document is new. * * @api public */ Document.prototype.isNew; /** * Validation errors. * * @api public */ Document.prototype.errors; /** * Builds the default doc structure * * @api private */ Document.prototype.buildDoc = function (fields) { var doc = {} , self = this , exclude , keys , key , ki // determine if this doc is a result of a query with // excluded fields if (fields && 'Object' === fields.constructor.name) { keys = Object.keys(fields); ki = keys.length; while (ki--) { if ('_id' !== keys[ki]) { exclude = 0 === fields[keys[ki]]; break; } } } var paths = Object.keys(this.schema.paths) , plen = paths.length , ii = 0 for (; ii < plen; ++ii) { var p = paths[ii] , type = this.schema.paths[p] , path = p.split('.') , len = path.length , last = len-1 , doc_ = doc , i = 0 for (; i < len; ++i) { var piece = path[i] , def if (i === last) { if (fields) { if (exclude) { // apply defaults to all non-excluded fields if (p in fields) continue; def = type.getDefault(self, true); if ('undefined' !== typeof def) { doc_[piece] = def; self._activePaths.default(p); } } else if (p in fields) { // selected field def = type.getDefault(self, true); if ('undefined' !== typeof def) { doc_[piece] = def; self._activePaths.default(p); } } } else { def = type.getDefault(self, true); if ('undefined' !== typeof def) { doc_[piece] = def; self._activePaths.default(p); } } } else { doc_ = doc_[piece] || (doc_[piece] = {}); } } }; return doc; }; /** * Inits (hydrates) the document without setters. * * Called internally after a document is returned * from mongodb. * * @param {Object} document returned by mongo * @param {Function} callback * @api private */ Document.prototype.init = function (doc, fn) { this.isNew = false; init(this, doc, this._doc); this._storeShard(); this.emit('init'); if (fn) fn(null); return this; }; /** * Init helper. * @param {Object} instance * @param {Object} obj - raw mongodb doc * @param {Object} doc - object we are initializing * @private */ function init (self, obj, doc, prefix) { prefix = prefix || ''; var keys = Object.keys(obj) , len = keys.length , schema , path , i; while (len--) { i = keys[len]; path = prefix + i; schema = self.schema.path(path); if (!schema && obj[i] && 'Object' === obj[i].constructor.name) { // assume nested object doc[i] = {}; init(self, obj[i], doc[i], path + '.'); } else { if (obj[i] === null) { doc[i] = null; } else if (obj[i] !== undefined) { if (schema) { self.try(function(){ doc[i] = schema.cast(obj[i], self, true); }); } else { doc[i] = obj[i]; } } // mark as hydrated self._activePaths.init(path); } } }; /** * _storeShard * * Stores the current values of the shard keys * for use later in the doc.save() where clause. * * Shard key values do not / are not allowed to change. * * @param {Object} document * @private */ Document.prototype._storeShard = function _storeShard () { var key = this.schema.options.shardkey; if (!(key && 'Object' == key.constructor.name)) return; var orig = this._shardval = {} , paths = Object.keys(key) , len = paths.length , val for (var i = 0; i < len; ++i) { val = this.getValue(paths[i]); if (isMongooseObject(val)) { orig[paths[i]] = val.toObject({ depopulate: true }) } else if (null != val && val.valueOf) { orig[paths[i]] = val.valueOf(); } else { orig[paths[i]] = val; } } } // Set up middleware support for (var k in hooks) { Document.prototype[k] = Document[k] = hooks[k]; } /** * Sets a path, or many paths * * Examples: * // path, value * doc.set(path, value) * * // object * doc.set({ * path : value * , path2 : { * path : value * } * } * * @param {String|Object} key path, or object * @param {Object} value, or undefined or a prefix if first parameter is an object * @param @optional {Schema|String|...} specify a type if this is an on-the-fly attribute * @api public */ Document.prototype.set = function (path, val, type) { var constructing = true === type , adhoc = type && true !== type , adhocs if (adhoc) { adhocs = this._adhocPaths || (this._adhocPaths = {}); adhocs[path] = Schema.interpretAsType(path, type); } if ('string' !== typeof path) { // new Document({ key: val }) if (null === path || undefined === path) { var _ = path; path = val; val = _; } else { var prefix = val ? val + '.' : ''; if (path instanceof Document) path = path._doc; var keys = Object.keys(path) , i = keys.length , pathtype , key while (i--) { key = keys[i]; if (null != path[key] && 'Object' === path[key].constructor.name && !(this._path(prefix + key) instanceof MixedSchema)) { this.set(path[key], prefix + key, constructing); } else if (this._strictMode) { pathtype = this.schema.pathType(prefix + key); if ('real' === pathtype || 'virtual' === pathtype) { this.set(prefix + key, path[key], constructing); } } else if (undefined !== path[key]) { this.set(prefix + key, path[key], constructing); } } return this; } } // ensure _strict is honored for obj props // docschema = new Schema({ path: { nest: 'string' }}) // doc.set('path', obj); var pathType = this.schema.pathType(path); if ('nested' == pathType && val && 'Object' == val.constructor.name) { this.setValue(path, null); this.set(val, path, constructing); return this; } var schema; if ('adhocOrUndefined' == pathType && this._strictMode) { return this; } else if ('virtual' == pathType) { schema = this.schema.virtualpath(path); schema.applySetters(val, this); return this; } else { schema = this._path(path); } var parts = path.split('.') , obj = this._doc , self = this , pathToMark , subpaths , subpath // When using the $set operator the path to the field must already exist. // Else mongodb throws: "LEFT_SUBFIELD only supports Object" if (parts.length <= 1) { pathToMark = path; } else { subpaths = parts.map(function (part, i) { return parts.slice(0, i).concat(part).join('.'); }); for (var i = 0, l = subpaths.length; i < l; i++) { subpath = subpaths[i]; if (this.isDirectModified(subpath) // earlier prefixes that are already // marked as dirty have precedence || this.get(subpath) === null) { pathToMark = subpath; break; } } if (!pathToMark) pathToMark = path; } if ((!schema || null === val || undefined === val) || this.try(function(){ // if this doc is being constructed we should not // trigger getters. var cur = constructing ? undefined : self.get(path); var casted = schema.cast(val, self, false, cur); val = schema.applySetters(casted, self); })) { if (this.isNew) { this.markModified(pathToMark); } else { var priorVal = this.get(path); if (!this.isDirectModified(pathToMark)) { if (undefined === val && !this.isSelected(path)) { // special case: // when a path is not selected in a query its initial // value will be undefined. this.markModified(pathToMark); } else if (!deepEqual(val, priorVal)) { this.markModified(pathToMark); } else if (!constructing && null != val && path in this._activePaths.states.default && deepEqual(val, schema.getDefault(this, constructing))) { // special case: // a path with a default was $unset on the server // and the user is setting it to the same value again this.markModified(pathToMark); } } } for (var i = 0, l = parts.length; i < l; i++) { var next = i + 1 , last = next === l; if (last) { obj[parts[i]] = val; } else { if (obj[parts[i]] && 'Object' === obj[parts[i]].constructor.name) { obj = obj[parts[i]]; } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { obj = obj[parts[i]]; } else { obj = obj[parts[i]] = {}; } } } } return this; }; /** * Gets a raw value from a path (no getters) * * @param {String} path * @api private */ Document.prototype.getValue = function (path) { var parts = path.split('.') , obj = this._doc , part; for (var i = 0, l = parts.length; i < l-1; i++) { part = parts[i]; path = convertIfInt(path); obj = obj.getValue ? obj.getValue(part) // If we have an embedded array document member : obj[part]; if (!obj) return obj; } part = parts[l-1]; path = convertIfInt(path); return obj.getValue ? obj.getValue(part) // If we have an embedded array document member : obj[part]; }; function convertIfInt (string) { if (/^\d+$/.test(string)) { return parseInt(string, 10); } return string; } /** * Sets a raw value for a path (no casting, setters, transformations) * * @param {String} path * @param {Object} value * @api private */ Document.prototype.setValue = function (path, val) { var parts = path.split('.') , obj = this._doc; for (var i = 0, l = parts.length; i < l-1; i++) { obj = obj[parts[i]]; } obj[parts[l-1]] = val; return this; }; /** * Triggers casting on a specific path * * @todo - deprecate? not used anywhere * @param {String} path * @api public */ Document.prototype.doCast = function (path) { var schema = this.schema.path(path); if (schema) this.setValue(path, this.getValue(path)); }; /** * Gets a path * * @param {String} key path * @param @optional {Schema|String|...} specify a type if this is an on-the-fly attribute * @api public */ Document.prototype.get = function (path, type) { var adhocs; if (type) { adhocs = this._adhocPaths || (this._adhocPaths = {}); adhocs[path] = Schema.interpretAsType(path, type); } var schema = this._path(path) || this.schema.virtualpath(path) , pieces = path.split('.') , obj = this._doc; for (var i = 0, l = pieces.length; i < l; i++) { obj = null == obj ? null : obj[pieces[i]]; } if (schema) { obj = schema.applyGetters(obj, this); } return obj; }; /** * Finds the path in the ad hoc type schema list or * in the schema's list of type schemas * @param {String} path * @api private */ Document.prototype._path = function (path) { var adhocs = this._adhocPaths , adhocType = adhocs && adhocs[path]; if (adhocType) { return adhocType; } else { return this.schema.path(path); } }; /** * Commits a path, marking as modified if needed. Useful for mixed keys * * @api public */ Document.prototype.markModified = function (path) { this._activePaths.modify(path); }; /** * commit * * Alias on markModified * * @deprecated */ Document.prototype.commit = utils.dep('Document#commit' , 'Document#markModified' , Document.prototype.markModified); /** * Captures an exception that will be bubbled to `save` * * @param {Function} function to execute * @param {Object} scope */ Document.prototype.try = function (fn, scope) { var res; try { fn.call(scope); res = true; } catch (e) { this.error(e); res = false; } return res; }; /** * modifiedPaths * * Returns the list of paths that have been modified. * * If we set `documents.0.title` to 'newTitle' * then `documents`, `documents.0`, and `documents.0.title` * are modified. * * @api public * @returns Boolean */ Document.prototype.__defineGetter__('modifiedPaths', function () { var directModifiedPaths = Object.keys(this._activePaths.states.modify); return directModifiedPaths.reduce(function (list, path) { var parts = path.split('.'); return list.concat(parts.reduce(function (chains, part, i) { return chains.concat(parts.slice(0, i).concat(part).join('.')); }, [])); }, []); }); /** * Checks if a path or any full path containing path as part of * its path chain has been directly modified. * * e.g., if we set `documents.0.title` to 'newTitle' * then we have directly modified `documents.0.title` * but not directly modified `documents` or `documents.0`. * Nonetheless, we still say `documents` and `documents.0` * are modified. They just are not considered direct modified. * The distinction is important because we need to distinguish * between what has been directly modified and what hasn't so * that we can determine the MINIMUM set of dirty data * that we want to send to MongoDB on a Document save. * * @param {String} path * @returns Boolean * @api public */ Document.prototype.isModified = function (path) { return !!~this.modifiedPaths.indexOf(path); }; /** * Checks if a path has been directly set and modified. False if * the path is only part of a larger path that was directly set. * * e.g., if we set `documents.0.title` to 'newTitle' * then we have directly modified `documents.0.title` * but not directly modified `documents` or `documents.0`. * Nonetheless, we still say `documents` and `documents.0` * are modified. They just are not considered direct modified. * The distinction is important because we need to distinguish * between what has been directly modified and what hasn't so * that we can determine the MINIMUM set of dirty data * that we want to send to MongoDB on a Document save. * * @param {String} path * @returns Boolean * @api public */ Document.prototype.isDirectModified = function (path) { return (path in this._activePaths.states.modify); }; /** * Checks if a certain path was initialized * * @param {String} path * @returns Boolean * @api public */ Document.prototype.isInit = function (path) { return (path in this._activePaths.states.init); }; /** * Checks if a path was selected. * @param {String} path * @return Boolean * @api public */ Document.prototype.isSelected = function isSelected (path) { if (this._selected) { if ('_id' === path) { return 0 !== this._selected._id; } var paths = Object.keys(this._selected) , i = paths.length , inclusive = false , cur if (1 === i && '_id' === paths[0]) { // only _id was selected. return 0 === this._selected._id; } while (i--) { cur = paths[i]; if ('_id' == cur) continue; inclusive = !! this._selected[cur]; break; } if (path in this._selected) { return inclusive; } i = paths.length; while (i--) { cur = paths[i]; if ('_id' == cur) continue; if (0 === cur.indexOf(path + '.')) { return inclusive; } if (0 === (path + '.').indexOf(cur)) { return inclusive; } } return ! inclusive; } return true; } /** * Validation middleware * * @param {Function} next * @api public */ Document.prototype.validate = function (next) { var total = 0 , self = this , validating = {} if (!this._activePaths.some('require', 'init', 'modify')) { return complete(); } function complete () { next(self._validationError); self._validationError = null; } this._activePaths.forEach('require', 'init', 'modify', function validatePath (path) { if (validating[path]) return; validating[path] = true; total++; process.nextTick(function(){ var p = self.schema.path(path); if (!p) return --total || complete(); p.doValidate(self.getValue(path), function (err) { if (err) self.invalidate(path, err); --total || complete(); }, self); }); }); return this; }; /** * Marks a path as invalid, causing a subsequent validation to fail. * * @param {String} path of the field to invalidate * @param {String/Error} error of the path. * @api public */ Document.prototype.invalidate = function (path, err) { if (!this._validationError) { this._validationError = new ValidationError(this); } if (!err || 'string' === typeof err) { err = new ValidatorError(path, err); } this._validationError.errors[path] = err; } /** * Resets the atomics and modified states of this document. * * @private * @return {this} */ Document.prototype._reset = function reset () { var self = this; DocumentArray || (DocumentArray = require('./types/documentarray')); this._activePaths .map('init', 'modify', function (i) { return self.getValue(i); }) .filter(function (val) { return (val && val instanceof DocumentArray && val.length); }) .forEach(function (array) { array.forEach(function (doc) { doc._reset(); }); }); // clear atomics this._dirty().forEach(function (dirt) { var type = dirt.value; if (type && type._path && type.doAtomics) { type._atomics = {}; } }); // Clear 'modify'('dirty') cache this._activePaths.clear('modify'); var self = this; this.schema.requiredPaths.forEach(function (path) { self._activePaths.require(path); }); return this; } /** * Returns the dirty paths / vals * * @api private */ Document.prototype._dirty = function _dirty () { var self = this; var all = this._activePaths.map('modify', function (path) { return { path: path , value: self.getValue(path) , schema: self._path(path) }; }); // Sort dirty paths in a flat hierarchy. all.sort(function (a, b) { return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0)); }); // Ignore "foo.a" if "foo" is dirty already. var minimal = [] , lastPath , top; all.forEach(function (item, i) { if (item.path.indexOf(lastPath) !== 0) { lastPath = item.path + '.'; minimal.push(item); top = item; } else { if (!(item.value && top.value)) return; // special case for top level MongooseArrays if (top.value._path && top.value.doAtomics) { // the `top` array itself and a sub path of `top` are being modified. // the only way to honor all of both modifications is through a $set // of entire array. top.value._atomics = {}; top.value._atomics.$set = top.value; } } }); top = lastPath = null; return minimal; } /** * Returns if the document has been modified * * @return {Boolean} * @api public */ Document.prototype.__defineGetter__('modified', function () { return this._activePaths.some('modify'); }); /** * Compiles schemas. * @api private */ function compile (tree, proto, prefix) { var keys = Object.keys(tree) , i = keys.length , limb , key; while (i--) { key = keys[i]; limb = tree[key]; define(key , (('Object' === limb.constructor.name && Object.keys(limb).length) && (!limb.type || limb.type.type) ? limb : null) , proto , prefix , keys); } }; /** * Defines the accessor named prop on the incoming prototype. * @api private */ function define (prop, subprops, prototype, prefix, keys) { var prefix = prefix || '' , path = (prefix ? prefix + '.' : '') + prop; if (subprops) { Object.defineProperty(prototype, prop, { enumerable: true , get: function () { if (!this.__getters) this.__getters = {}; if (!this.__getters[path]) { var nested = Object.create(this); // save scope for nested getters/setters if (!prefix) nested._scope = this; // shadow inherited getters from sub-objects so // thing.nested.nested.nested... doesn't occur (gh-366) var i = 0 , len = keys.length; for (; i < len; ++i) { // over-write the parents getter without triggering it Object.defineProperty(nested, keys[i], { enumerable: false // It doesn't show up. , writable: true // We can set it later. , configurable: true // We can Object.defineProperty again. , value: undefined // It shadows its parent. }); } nested.toObject = function () { return this.get(path); }; compile(subprops, nested, path); this.__getters[path] = nested; } return this.__getters[path]; } , set: function (v) { return this.set(path, v); } }); } else { Object.defineProperty(prototype, prop, { enumerable: true , get: function ( ) { return this.get.call(this._scope || this, path); } , set: function (v) { return this.set.call(this._scope || this, path, v); } }); } }; /** * We override the schema setter to compile accessors * * @api private */ Document.prototype.__defineSetter__('schema', function (schema) { compile(schema.tree, this); this._schema = schema; }); /** * We override the schema getter to return the internal reference * * @api private */ Document.prototype.__defineGetter__('schema', function () { return this._schema; }); /** * Register default hooks * * @api private */ Document.prototype._registerHooks = function _registerHooks () { if (!this.save) return; DocumentArray || (DocumentArray = require('./types/documentarray')); this.pre('save', function (next) { // we keep the error semaphore to make sure we don't // call `save` unnecessarily (we only need 1 error) var subdocs = 0 , error = false , self = this; var arrays = this._activePaths .map('init', 'modify', function (i) { return self.getValue(i); }) .filter(function (val) { return (val && val instanceof DocumentArray && val.length); }); if (!arrays.length) return next(); arrays.forEach(function (array) { subdocs += array.length; array.forEach(function (value) { if (!error) value.save(function (err) { if (!error) { if (err) { error = true; next(err); } else --subdocs || next(); } }); }); }); }, function (err) { this.db.emit('error', err); }).pre('save', function checkForExistingErrors (next) { if (this._saveError) { next(this._saveError); this._saveError = null; } else { next(); } }).pre('save', function validation (next) { return this.validate(next); }); }; /** * Registers an error * * @TODO underscore this method * @param {Error} error * @api private */ Document.prototype.error = function (err) { this._saveError = err; return this; }; /** * Executes methods queued from the Schema definition * * @TODO underscore this method * @api private */ Document.prototype.doQueue = function () { if (this.schema && this.schema.callQueue) for (var i = 0, l = this.schema.callQueue.length; i < l; i++) { this[this.schema.callQueue[i][0]].apply(this, this.schema.callQueue[i][1]); } return this; }; /** * Gets the document * * Available options: * * - getters: apply all getters (path and virtual getters) * - virtuals: apply virtual getters (can override `getters` option) * * Example of only applying path getters: * * doc.toObject({ getters: true, virtuals: false }) * * Example of only applying virtual getters: * * doc.toObject({ virtuals: true }) * * Example of applying both path and virtual getters: * * doc.toObject({ getters: true }) * * @return {Object} plain object * @api public */ Document.prototype.toObject = function (options) { options || (options = {}); options.minimize = true; var ret = clone(this._doc, options); if (options.virtuals || options.getters && false !== options.virtuals) { applyGetters(this, ret, 'virtuals', options); } if (options.getters) { applyGetters(this, ret, 'paths', options); } return ret; }; /** * Applies virtuals properties to `json`. * * @param {Document} self * @param {Object} json * @param {String} either `virtuals` or `paths` * @return json * @private */ function applyGetters (self, json, type, options) { var schema = self.schema , paths = Object.keys(schema[type]) , i = paths.length , path while (i--) { path = paths[i]; var parts = path.split('.') , plen = parts.length , last = plen - 1 , branch = json , part for (var ii = 0; ii < plen; ++ii) { part = parts[ii]; if (ii === last) { branch[part] = clone(self.get(path), options); } else { branch = branch[part] || (branch[part] = {}); } } } return json; } /** * JSON.stringify helper. * * Implicitly called when a document is passed * to JSON.stringify() * * @return {Object} * @api public */ Document.prototype.toJSON = function (options) { if ('undefined' === typeof options) options = {}; options.json = true; return this.toObject(options); }; /** * Helper for console.log * * @api public */ Document.prototype.toString = Document.prototype.inspect = function (options) { return inspect(this.toObject(options)); }; /** * Returns true if the Document stores the same data as doc. * @param {Document} doc to compare to * @return {Boolean} * @api public */ Document.prototype.equals = function (doc) { return this.get('_id') === doc.get('_id'); }; /** * Module exports. */ module.exports = Document; /** * Document Validation Error */ function ValidationError (instance) { MongooseError.call(this, "Validation failed"); Error.captureStackTrace(this, arguments.callee); this.name = 'ValidationError'; this.errors = instance.errors = {}; }; ValidationError.prototype.toString = function () { return this.name + ': ' + Object.keys(this.errors).map(function (key) { return String(this.errors[key]); }, this).join(', '); }; /** * Inherits from MongooseError. */ ValidationError.prototype.__proto__ = MongooseError.prototype; Document.ValidationError = ValidationError; /** * Document Error * * @param text */ function DocumentError () { MongooseError.call(this, msg); Error.captureStackTrace(this, arguments.callee); this.name = 'DocumentError'; }; /** * Inherits from MongooseError. */ DocumentError.prototype.__proto__ = MongooseError.prototype; exports.Error = DocumentError;
import _extends from "@babel/runtime/helpers/esm/extends"; import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import Paper from '../Paper'; import capitalize from '../utils/capitalize'; import LinearProgress from '../LinearProgress'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', background: theme.palette.background.default, padding: 8 }, /* Styles applied to the root element if `position="bottom"`. */ positionBottom: { position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: theme.zIndex.mobileStepper }, /* Styles applied to the root element if `position="top"`. */ positionTop: { position: 'fixed', top: 0, left: 0, right: 0, zIndex: theme.zIndex.mobileStepper }, /* Styles applied to the root element if `position="static"`. */ positionStatic: {}, /* Styles applied to the dots container if `variant="dots"`. */ dots: { display: 'flex', flexDirection: 'row' }, /* Styles applied to each dot if `variant="dots"`. */ dot: { backgroundColor: theme.palette.action.disabled, borderRadius: '50%', width: 8, height: 8, margin: '0 2px' }, /* Styles applied to a dot if `variant="dots"` and this is the active step. */ dotActive: { backgroundColor: theme.palette.primary.main }, /* Styles applied to the Linear Progress component if `variant="progress"`. */ progress: { width: '50%' } }; }; var MobileStepper = React.forwardRef(function MobileStepper(props, ref) { var _props$activeStep = props.activeStep, activeStep = _props$activeStep === void 0 ? 0 : _props$activeStep, backButton = props.backButton, classes = props.classes, className = props.className, LinearProgressProps = props.LinearProgressProps, nextButton = props.nextButton, _props$position = props.position, position = _props$position === void 0 ? 'bottom' : _props$position, steps = props.steps, _props$variant = props.variant, variant = _props$variant === void 0 ? 'dots' : _props$variant, other = _objectWithoutProperties(props, ["activeStep", "backButton", "classes", "className", "LinearProgressProps", "nextButton", "position", "steps", "variant"]); return React.createElement(Paper, _extends({ square: true, elevation: 0, className: clsx(classes.root, classes["position".concat(capitalize(position))], className), ref: ref }, other), backButton, variant === 'text' && React.createElement(React.Fragment, null, activeStep + 1, " / ", steps), variant === 'dots' && React.createElement("div", { className: classes.dots }, _toConsumableArray(new Array(steps)).map(function (_, index) { return React.createElement("div", { key: index, className: clsx(classes.dot, index === activeStep && classes.dotActive) }); })), variant === 'progress' && React.createElement(LinearProgress, _extends({ className: classes.progress, variant: "determinate", value: Math.ceil(activeStep / (steps - 1) * 100) }, LinearProgressProps)), nextButton); }); process.env.NODE_ENV !== "production" ? MobileStepper.propTypes = { /** * Set the active step (zero based index). * Defines which dot is highlighted when the variant is 'dots'. */ activeStep: PropTypes.number, /** * A back button element. For instance, it can be a `Button` or an `IconButton`. */ backButton: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * Props applied to the `LinearProgress` element. */ LinearProgressProps: PropTypes.object, /** * A next button element. For instance, it can be a `Button` or an `IconButton`. */ nextButton: PropTypes.node, /** * Set the positioning type. */ position: PropTypes.oneOf(['bottom', 'top', 'static']), /** * The total steps. */ steps: PropTypes.number.isRequired, /** * The variant to use. */ variant: PropTypes.oneOf(['text', 'dots', 'progress']) } : void 0; export default withStyles(styles, { name: 'MuiMobileStepper' })(MobileStepper);
angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "vorm.", "nachm." ], "DAY": [ "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag" ], "MONTH": [ "Januar", "Februar", "M\u00e4rz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember" ], "SHORTDAY": [ "So.", "Mo.", "Di.", "Mi.", "Do.", "Fr.", "Sa." ], "SHORTMONTH": [ "Jan", "Feb", "M\u00e4r", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez" ], "fullDate": "EEEE, d. MMMM y", "longDate": "d. MMMM y", "medium": "dd.MM.yyyy HH:mm:ss", "mediumDate": "dd.MM.yyyy", "mediumTime": "HH:mm:ss", "short": "dd.MM.yy HH:mm", "shortDate": "dd.MM.yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u20ac", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "de-lu", "pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
'use strict'; angular.module('depthyApp') .directive('fileselect', function ($parse) { return { restrict: 'A', scope: true, link: function postLink(scope, element, attrs) { var fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.style.visibility = 'hidden'; fileInput.style.position = 'absolute'; fileInput.style.left = '-9000px'; element.append(fileInput); var onDrag = function(e) { e.stopPropagation(); e.preventDefault(); }; var onDrop = function(e) { e.stopPropagation(); e.preventDefault(); console.log(e); var dt = e.originalEvent.dataTransfer; var files = dt.files; handleFiles(files); scope.$apply(); }; function handleFiles(files) { scope.$broadcast('fileselect', files); if (attrs.fileselect) { $parse(attrs.fileselect).assign(scope, files); } } scope.selectFile = function(e) { fileInput.click(); if (e) e.preventDefault(); }; element.on('dragenter', onDrag); element.on('dragover', onDrag); element.on('drop', onDrop); fileInput.addEventListener('change', function() { handleFiles(_.filter(this.files)); fileInput.value = ''; scope.$apply(); }, false); } }; });
define({ "_widgetLabel": "打印", "title": "地图切片", "format": "格式", "layout": "布局", "settings": "高级", "labels": "标注", "showLabels": "显示标注", "mapScaleExtent": "地图比例/范围", "preserve": "保留", "mapScale": "地图比例", "mapExtent": "地图范围", "forceScale": "强制比例", "getCurrentScale": "当前", "mapMetadata": "布局元数据", "author": "作者", "copyright": "版权所有", "fullLayoutOptions": "完整布局选项", "scaleBarUnit": "比例尺单位", "scaleBarUnitsMetric": "比例尺单位(公制)", "scaleBarUnitsNonMetric": "比例尺单位(非公制)", "unitsMiles": "英里", "unitsKilometers": "千米", "unitsMeters": "米", "unitsFeet": "英尺", "unitsYards": "码", "unitsNauticalMiles": "海里", "lncludeLegend": "包括图例", "printQualityOptions": "打印质量", "dpi": "DPI", "mapOnlyOptions": "MAP_ONLY 大小", "width": "宽度(px)", "height": "高度(px)", "print": "打印", "clearList": "清除打印", "creatingPrint": "正在创建打印", "printError": "出现错误,请重试", "forceFeatureAttributes": "要素属性", "includeFeatureAttributes": "包括属性", "outputSR": "输出空间参考", "invalidWkid": "无效的 wkid" });
import { run } from 'ember-metal'; import { jQuery } from 'ember-views'; import { Application } from 'ember-application'; import { Router } from 'ember-routing'; import { compile } from 'ember-template-compiler'; import AbstractTestCase from './abstract'; import { runDestroy } from '../run'; export default class AbstractApplicationTestCase extends AbstractTestCase { constructor() { super(); this.element = jQuery('#qunit-fixture')[0]; this.application = run(Application, 'create', this.applicationOptions); this.router = this.application.Router = Router.extend(this.routerOptions); this.applicationInstance = null; } get applicationOptions() { return { rootElement: '#qunit-fixture', autoboot: false }; } get routerOptions() { return { location: 'none' }; } teardown() { if (this.applicationInstance) { runDestroy(this.applicationInstance); } runDestroy(this.application); } visit(url, options) { let { applicationInstance } = this; if (applicationInstance) { return run(applicationInstance, 'visit', url, options); } else { return run(this.application, 'visit', url, options).then(instance => { this.applicationInstance = instance; }); } } compile(string, options) { return compile(...arguments); } registerRoute(name, route) { this.application.register(`route:${name}`, route); } registerTemplate(name, template) { this.application.register(`template:${name}`, this.compile(template, { moduleName: name })); } registerComponent(name, { ComponentClass = null, template = null }) { if (ComponentClass) { this.application.register(`component:${name}`, ComponentClass); } if (typeof template === 'string') { this.application.register(`template:components/${name}`, this.compile(template, { moduleName: `components/${name}` })); } } registerController(name, controller) { this.application.register(`controller:${name}`, controller); } registerEngine(name, engine) { this.application.register(`engine:${name}`, engine); } }
game.SpendGold = Object.extend({ init: function(x, y, settings) { this.now = new Date().getTime(); this.lastBuy = new Date().getTime(); this.paused = false; this.alwaysUpdate = true; this.updateWhenPaused = true; this.buying = false; }, update: function() { this.now = new Date().getTime(); if (me.input.isKeyPressed("buy") && this.now - this.lastBuy >= 1000) { this.lastBuy = this.now; if (!this.buying) { this.startBuying(); } else { this.stopBuying(); } } this.checkBuyKeys(); return true; }, startBuying: function() { this.buying = true; me.state.pause(me.state.PLAY); game.data.pausePos = me.game.viewport.localToWorld(0, 0); game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage("gold-screen")); game.data.buyscreen.updateWhenPaused = true; game.data.buyscreen.setOpacity(0.8); me.game.world.addChild(game.data.buyscreen, 34); game.data.player.body.setVelocity(0, 0); me.input.bindKey(me.input.KEY.F1, "F1", true); me.input.bindKey(me.input.KEY.F2, "F2", true); me.input.bindKey(me.input.KEY.F3, "F3", true); me.input.bindKey(me.input.KEY.F4, "F4", true); me.input.bindKey(me.input.KEY.F5, "F5", true); me.input.bindKey(me.input.KEY.F6, "F6", true); this.setBuyText(); }, setBuyText: function() { game.data.buytext = new (me.Renderable.extend({ init: function() { this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]); this.font = new me.Font("Arial", 26, "white"); this.updateWhenPaused = true; this.alwaysUpdate; }, draw: function(renderer) { this.font.draw(renderer.getContext(), "Press F1-F6 to Buy, Press B to Exit. Current Gold: " + game.data.gold, this.pos.x, this.pos.y); this.font.draw(renderer.getContext(), "Skill 1: Increase Attack. Current Level: " + game.data.skill1 + "Cost: " + ((game.data.skill1 + 1) * 10), this.pos.x, this.pos.y + 40); this.font.draw(renderer.getContext(), "Skill 2: Increase Speed. Current Level: " + game.data.skill2 + "Cost: " + ((game.data.skill2 + 1) * 10), this.pos.x, this.pos.y + 80); this.font.draw(renderer.getContext(), "Skill 3: Increase Health. Current Level: " + game.data.skill3 + "Cost: " + ((game.data.skill3 + 1) * 10), this.pos.x, this.pos.y + 120); this.font.draw(renderer.getContext(), "Q Ability: Speed Burst! Current Level: " + game.data.ability1 + "Cost: " + ((game.data.ability1 + 1) * 10), this.pos.x, this.pos.y + 160); this.font.draw(renderer.getContext(), "W Ability: Eat Creep for Health! Current Level:" + game.data.ability2 + "Cost: " + ((game.data.ability2 + 1) * 10), this.pos.x, this.pos.y + 200); this.font.draw(renderer.getContext(), "E Ability: Throw your Spear! Current Level:" + game.data.ability3 + "Cost: " + ((game.data.ability3 + 1) * 10), this.pos.x, this.pos.y + 240); } })); me.game.world.addChild(game.data.buytext, 35); }, stopBuying: function() { this.buying = false; me.state.resume(me.state.PLAY); game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20); me.game.world.removeChild(game.data.buyscreen); me.input.unbindKey(me.input.KEY.F1, "F1", true); me.input.unbindKey(me.input.KEY.F2, "F2", true); me.input.unbindKey(me.input.KEY.F3, "F3", true); me.input.unbindKey(me.input.KEY.F4, "F4", true); me.input.unbindKey(me.input.KEY.F5, "F5", true); me.input.unbindKey(me.input.KEY.F6, "F6", true); me.game.world.removeChild(game.data.buytext); }, checkBuyKeys: function() { if (me.input.isKeyPressed("F1")) { if (this.checkCost(1)) { this.makePurchase(1); } } else if (me.input.isKeyPressed("F2")) { if (this.checkCost(2)) { this.makePurchase(2); } } else if (me.input.isKeyPressed("F2")) { if (this.checkCost(2)) { this.makePurchase(2); } } else if (me.input.isKeyPressed("F3")) { if (this.checkCost(3)) { this.makePurchase(3); } } else if (me.input.isKeyPressed("F4")) { if (this.checkCost(4)) { this.makePurchase(4); } } else if (me.input.isKeyPressed("F5")) { if (this.checkCost(5)) { this.makePurchase(5); } } else if (me.input.isKeyPressed("F6")) { if (this.checkCost(6)) { this.makePurchase(6); } } }, checkCost: function(skill) { if (skill === 1 && (game.data.gold >= ((game.data.skill1 + 1) * 10))) { return true; } else if (skill === 2 && (game.data.gold >= ((game.data.skill2 + 1) * 10))) { return true; } else if (skill === 3 && (game.data.gold >= ((game.data.skill3 + 1) * 10))) { return true; } else if (skill === 4 && (game.data.gold >= ((game.data.skill4 + 1) * 10))) { return true; } else if (skill === 5 && (game.data.gold >= ((game.data.skill5 + 1) * 10))) { return true; } else if (skill === 6 && (game.data.gold >= ((game.data.skill6 + 1) * 10))) { return true; } else { return false; } }, makePurchase: function(skill) { if (skill === 1) { game.data.gold -= ((game.data.skill1 + 1) * 10); game.data.skill1 += 1; game.data.playerAttack += 1; } else if (skill === 2) { game.data.gold -= ((game.data.skill1 + 1) * 10); game.data.skill2 += 1; game.data.playerMoveSpeed += 1; } else if (skill === 3) { game.data.gold -= ((game.data.skill1 + 1) * 10); game.data.skill3 += 1; game.data.playerHealth += 1; } else if (skill === 4) { game.data.gold -= ((game.data.skill1 + 1) * 10); game.data.ability1 += 1; } else if (skill === 5) { game.data.gold -= ((game.data.skill1 + 1) * 10); game.data.ability2 += 1; } else if (skill === 6) { game.data.gold -= ((game.data.skill1 + 1) * 10); game.data.ability3 += 1; } } });
import { __decorate } from 'tslib'; import { ɵɵdefineInjectable, ɵɵinject, Injectable } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { Angulartics2 } from 'angulartics2'; let Angulartics2Clicky = class Angulartics2Clicky { constructor(angulartics2, titleService) { this.angulartics2 = angulartics2; this.titleService = titleService; if (typeof clicky === 'undefined') { console.warn('Angulartics 2 Clicky Plugin: clicky global not found'); } } startTracking() { this.angulartics2.pageTrack .pipe(this.angulartics2.filterDeveloperMode()) .subscribe((x) => this.pageTrack(x.path)); this.angulartics2.eventTrack .pipe(this.angulartics2.filterDeveloperMode()) .subscribe((x) => this.eventOrGoalTrack(x.action, x.properties)); } /** * Track Page in Clicky * * @param path location * * @link https://clicky.com/help/custom/manual#log */ pageTrack(path) { const title = this.titleService.getTitle(); clicky.log(path, title, 'pageview'); } /** * Track Event Or Goal in Clicky * * @param action Action name * @param properties Definition of 'properties.goal' determines goal vs event tracking * * @link https://clicky.com/help/custom/manual#log * @link https://clicky.com/help/custom/manual#goal */ eventOrGoalTrack(action, properties) { if (typeof properties.goal === 'undefined') { const title = properties.title || null; const type = properties.type != null ? this.validateType(properties.type) : null; clicky.log(action, title, type); } else { const goalId = properties.goal; const revenue = properties.revenue; clicky.goal(goalId, revenue, !!properties.noQueue); } } validateType(type) { const EventType = ['pageview', 'click', 'download', 'outbound']; return EventType.indexOf(type) > -1 ? type : 'pageview'; } }; Angulartics2Clicky.ctorParameters = () => [ { type: Angulartics2 }, { type: Title } ]; Angulartics2Clicky.ɵprov = ɵɵdefineInjectable({ factory: function Angulartics2Clicky_Factory() { return new Angulartics2Clicky(ɵɵinject(Angulartics2), ɵɵinject(Title)); }, token: Angulartics2Clicky, providedIn: "root" }); Angulartics2Clicky = __decorate([ Injectable({ providedIn: 'root' }) ], Angulartics2Clicky); /** * Generated bundle index. Do not edit. */ export { Angulartics2Clicky }; //# sourceMappingURL=angulartics2-clicky.js.map
import WKTParser from './WKTParser' import extend from '../../../../extend' /** * Writes the Well-Known Text representation of a {@link Geometry}. The * Well-Known Text format is defined in the <A * HREF="http://www.opengis.org/techno/specs.htm"> OGC Simple Features * Specification for SQL</A>. * <p> * The <code>WKTWriter</code> outputs coordinates rounded to the precision * model. Only the maximum number of decimal places necessary to represent the * ordinates to the required precision will be output. * <p> * The SFS WKT spec does not define a special tag for {@link LinearRing}s. * Under the spec, rings are output as <code>LINESTRING</code>s. */ /** * @param {GeometryFactory} geometryFactory * @constructor */ export default function WKTWriter (geometryFactory) { this.parser = new WKTParser(geometryFactory) } extend(WKTWriter.prototype, { /** * Converts a <code>Geometry</code> to its Well-known Text representation. * * @param {Geometry} geometry a <code>Geometry</code> to process. * @return {string} a <Geometry Tagged Text> string (see the OpenGIS Simple * Features Specification). * @memberof WKTWriter */ write (geometry) { return this.parser.write(geometry) } }) extend(WKTWriter, { /** * Generates the WKT for a <tt>LINESTRING</tt> specified by two * {@link Coordinate}s. * * @param p0 the first coordinate. * @param p1 the second coordinate. * * @return the WKT. * @private */ toLineString (p0, p1) { if (arguments.length !== 2) { throw new Error('Not implemented') } return 'LINESTRING ( ' + p0.x + ' ' + p0.y + ', ' + p1.x + ' ' + p1.y + ' )' } })
define(function(require) { var test = require('../../../test') var compatibleElement = document.getElementsByTagName('meta')[2] var baseElement = document.getElementsByTagName('base')[0] var head = document.getElementsByTagName('head')[0] var scripts = head.getElementsByTagName('script') var firstScript = scripts[0] var lastScript = scripts[scripts.length - 1] var nextElement = nextSiblingElement(compatibleElement) test.assert(nextElement === firstScript, 'script after compatible meta') var linkElement = previousSiblingElement(baseElement) var prevElement = previousSiblingElement(linkElement) test.assert(prevElement === lastScript, 'script before base element') test.next() function nextSiblingElement(node) { var sibling = node do { sibling = sibling.nextSibling } while (sibling && sibling.nodeType !== 1) return sibling } function previousSiblingElement(node) { var sibling = node do { sibling = sibling.previousSibling } while (sibling && sibling.nodeType !== 1) return sibling } });
var express=require('express'); var fs=require('fs'); var bodyParse=require('body-parser'); var db='./users.json'; var app=express(); app.use(express.static(__dirname)); app.use(bodyParse.urlencoded({extended:true})); app.get('/', function (req,res) { fs.createReadStream('./index.html').pipe(res); }); app.get('/users', function (req,res) { fs.createReadStream('./users.json').pipe(res); }); app.get('/users/:movie', function (req,res) { var arr=[]; var movie=req.params.movie; //var results=require(db); var results=JSON.parse(fs.readFileSync(db,'utf8')); var result=results.filter(function(result){ return result.movie==movie; })[0]; arr.push(result); res.send(arr); }); app.post('/users', function (req,res) { var user=req.body; var users=JSON.parse(fs.readFileSync(db,'utf8')); if(users.length==0){ user.id=1; }else { user.id=users[users.length-1].id+1; } users.push(user); fs.writeFile(db,JSON.stringify(users), function (err) { res.send(user); }) }); app.delete('/users/:id', function (req,res) { var id=req.params.id; var users=JSON.parse(fs.readFileSync(db,'utf8')); fs.readFile(db, function (err,data) { users=data; console.log(users); }); var newUsers=users.filter(function (user) { return user.id != id; }); fs.writeFile(db,JSON.stringify(newUsers),function(){ res.send(newUsers); }) }); app.put('/users/:id', function (req,res) { var newMovie=req.body; var users=JSON.parse(fs.readFileSync(db,'utf8')); users=users.map(function (user) { if(user.id==req.params.id){ return newMovie; }else { return user; } }); fs.writeFile(db,JSON.stringify(users),function(){ res.send(newMovie); }) }); app.listen(9090);
angular.module("app").factory("workersStopListener",["$rootScope",function(a){"use strict";var b=new SocketListener(a,"shutdown");return b}]);
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Category = mongoose.model('Category'), _ = require('lodash'); /** * Create a Category */ exports.create = function(req, res) { var category = new Category(req.body); category.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.status(201).json(category); } }); }; /** * Show the current Category */ exports.read = function(req, res) { res.json(req.category); }; /** * Update a Category */ exports.update = function(req, res) { var category = req.category; category = _.extend(category, req.body); category.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(category); } }); }; /** * Delete an Category */ exports.delete = function(req, res) { var category = req.category; category.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(category); } }); }; /** * List of Categories */ exports.list = function(req, res) { Category.find().sort('name').exec(function(err, categories) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(categories); } }); }; /** * Category middleware */ exports.categoryByID = function(req, res, next, id) { if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).send({ message: 'Category is invalid' }); } Category.findById(id).exec(function(err, category) { if (err) return next(err); if (!category) { return res.status(404).send({ message: 'Category not found' }); } req.category = category; next(); }); };
'use strict'; var utils = require('../utils'); /** * @class RefreshToken * * @description * * Encapsulates a Stormpath OAuth Refresh Token Resource. For full documentation * of this resource, please see * [REST API Reference: Refresh Token](https://docs.stormpath.com/rest/product-guide/latest/reference.html?#password-policy). * For a high-level overview of token management, please see * {@link https://docs.stormpath.com/rest/product-guide/latest/auth_n.html#introduction-to-token-based-authentication Introduction to Token-Based Authentication}. * * This class should not be manually constructed. It should be obtained from one * of these methods: * * - {@link Client#getRefreshToken Client.getRefreshToken()} * - {@link Account#getRefreshTokens Account.getRefreshTokens()} * * To revoke a refresh token, invoke the `delete()` method on an instance of * this class. * * @param {Object} refreshTokenResource * * The JSON representation of this resource, retrieved the Stormpath REST API. */ function RefreshToken() { RefreshToken.super_.apply(this, arguments); } utils.inherits(RefreshToken, require('./InstanceResource')); module.exports = RefreshToken; /** * Deletes this resource from the API. * * @method RefreshToken.delete * * @param {Function} callback * The function to call when the delete operation is complete. Will be called * with the parameter (err). */
exports.MailChimpAPI = require('./MailChimpAPI.js'); exports.MailChimpExportAPI = require('./MailChimpExportAPI.js'); exports.MailChimpWebhook = require('./MailChimpWebhook.js'); exports.MailChimpSTSAPI = require('./MailChimpSTSAPI.js'); exports.MailChimpOAuth = require('./MailChimpOAuth.js');
// Generated by uRequire v{NO_VERSION} - template: 'nodejs' (function (window, global) { var __isAMD = !!(typeof define === 'function' && define.amd), __isNode = (typeof exports === 'object'), __isWeb = !__isNode; Polygon = require('./polygon'), O = require('./ops'); module.exports = (function () { return function (_arg) { var angle, center, points, radii; center = _arg.center, radii = _arg.radii; angle = 2 * Math.PI / radii.length; points = radii.map(function (r, i) { return O.plus(center, O.on_circle(r, i * angle)); }); return Polygon({ points: points, closed: true }); }; }).call(this); }).call(this, (typeof exports === 'object' ? global : window), (typeof exports === 'object' ? global : window))
'use strict'; const crypto = require('crypto'), bcrypt = require('bcrypt-nodejs'), JWT = require('jsonwebtoken'); module.exports = { tableName: 'users', connection: 'deploy', attributes: { email: { type: 'string' }, password: { type: 'string' }, salt: { type: 'string' }, // key: { // type: 'string' // }, medications: { collection: 'medications', via: 'owner' }, logs: { collection: 'logs', via: 'owner' } }, hashPassword(password, callback) { bcrypt.hash(password, null, null, (err, hash) => { callback(hash); }); }, comparePassword(password, hash, callback) { bcrypt.compare(password, hash, (err, res) => { callback(res); }); }, generateSalt() { return crypto.randomBytes(32).toString('base64'); }, generateKey(password, salt, callback) { crypto.pbkdf2(password, salt, 10000, 64, 'sha512', (err, key) => { callback(key); }); }, signToken(session, callback) { JWT.sign(session, process.env.tokenSecret, { algorithm: 'HS256' }, (token) => { callback(token); }); } };
/*global defineSuite*/ defineSuite([ 'Widgets/CesiumWidget/CesiumWidget', 'Core/Clock', 'Core/EllipsoidTerrainProvider', 'Core/ScreenSpaceEventHandler', 'Core/WebMercatorProjection', 'Scene/Camera', 'Scene/ImageryLayerCollection', 'Scene/Scene', 'Scene/SceneMode', 'Scene/SkyBox', 'Scene/TileCoordinatesImageryProvider', 'Specs/DomEventSimulator' ], function( CesiumWidget, Clock, EllipsoidTerrainProvider, ScreenSpaceEventHandler, WebMercatorProjection, Camera, ImageryLayerCollection, Scene, SceneMode, SkyBox, TileCoordinatesImageryProvider, DomEventSimulator) { "use strict"; /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn,runs,waits,waitsFor*/ var container; var widget; beforeEach(function() { container = document.createElement('div'); container.id = 'container'; container.style.width = '1px'; container.style.height = '1px'; container.style.overflow = 'hidden'; container.style.position = 'relative'; document.body.appendChild(container); }); afterEach(function() { if (widget && !widget.isDestroyed()) { widget = widget.destroy(); } document.body.removeChild(container); }); it('can create, render, and destroy', function() { widget = new CesiumWidget(container); expect(widget.isDestroyed()).toEqual(false); expect(widget.container).toBeInstanceOf(HTMLElement); expect(widget.canvas).toBeInstanceOf(HTMLElement); expect(widget.creditContainer).toBeInstanceOf(HTMLElement); expect(widget.scene).toBeInstanceOf(Scene); expect(widget.imageryLayers).toBeInstanceOf(ImageryLayerCollection); expect(widget.terrainProvider).toBeInstanceOf(EllipsoidTerrainProvider); expect(widget.camera).toBeInstanceOf(Camera); expect(widget.clock).toBeInstanceOf(Clock); expect(widget.screenSpaceEventHandler).toBeInstanceOf(ScreenSpaceEventHandler); widget.render(); widget.destroy(); expect(widget.isDestroyed()).toEqual(true); }); it('can pass id string for container', function() { widget = new CesiumWidget('container'); }); it('sets expected options clock', function() { var options = { clock : new Clock() }; widget = new CesiumWidget(container, options); expect(widget.clock).toBe(options.clock); }); it('can set scene mode 2D', function() { widget = new CesiumWidget(container, { sceneMode : SceneMode.SCENE2D }); widget.scene.completeMorph(); expect(widget.scene.mode).toBe(SceneMode.SCENE2D); }); it('can set map projection', function() { var mapProjection = new WebMercatorProjection(); widget = new CesiumWidget(container, { mapProjection : mapProjection }); expect(widget.scene.mapProjection).toEqual(mapProjection); }); it('can set scene mode Columbus', function() { widget = new CesiumWidget(container, { sceneMode : SceneMode.COLUMBUS_VIEW }); widget.scene.completeMorph(); expect(widget.scene.mode).toBe(SceneMode.COLUMBUS_VIEW); }); it('can disable render loop', function() { widget = new CesiumWidget(container, { useDefaultRenderLoop : false }); expect(widget.useDefaultRenderLoop).toBe(false); }); it('can set target frame rate', function() { widget = new CesiumWidget(container, { targetFrameRate : 23 }); expect(widget.targetFrameRate).toBe(23); }); it('sets expected options imageryProvider', function() { var options = { imageryProvider : new TileCoordinatesImageryProvider() }; widget = new CesiumWidget(container, options); var imageryLayers = widget.scene.imageryLayers; expect(imageryLayers.length).toEqual(1); expect(imageryLayers.get(0).imageryProvider).toBe(options.imageryProvider); }); it('does not create an ImageryProvider if option is false', function() { widget = new CesiumWidget(container, { imageryProvider : false }); var imageryLayers = widget.scene.imageryLayers; expect(imageryLayers.length).toEqual(0); }); it('sets expected options terrainProvider', function() { var options = { terrainProvider : new EllipsoidTerrainProvider() }; widget = new CesiumWidget(container, options); expect(widget.terrainProvider).toBe(options.terrainProvider); var anotherProvider = new EllipsoidTerrainProvider(); widget.terrainProvider = anotherProvider; expect(widget.terrainProvider).toBe(anotherProvider); }); it('sets expected options skyBox', function() { var options = { skyBox : new SkyBox({ sources : { positiveX : './Data/Images/Blue.png', negativeX : './Data/Images/Green.png', positiveY : './Data/Images/Blue.png', negativeY : './Data/Images/Green.png', positiveZ : './Data/Images/Blue.png', negativeZ : './Data/Images/Green.png' } }) }; widget = new CesiumWidget(container, options); expect(widget.scene.skyBox).toBe(options.skyBox); }); it('can set contextOptions', function() { var webglOptions = { alpha : true, depth : true, //TODO Change to false when https://bugzilla.mozilla.org/show_bug.cgi?id=745912 is fixed. stencil : true, antialias : false, premultipliedAlpha : true, // Workaround IE 11.0.8, which does not honor false. preserveDrawingBuffer : true }; var contextOptions = { allowTextureFilterAnisotropic : false, webgl : webglOptions }; widget = new CesiumWidget(container, { contextOptions : contextOptions }); var context = widget.scene.context; var contextAttributes = context._gl.getContextAttributes(); expect(context.options.allowTextureFilterAnisotropic).toEqual(false); expect(contextAttributes.alpha).toEqual(webglOptions.alpha); expect(contextAttributes.depth).toEqual(webglOptions.depth); expect(contextAttributes.stencil).toEqual(webglOptions.stencil); expect(contextAttributes.antialias).toEqual(webglOptions.antialias); expect(contextAttributes.premultipliedAlpha).toEqual(webglOptions.premultipliedAlpha); expect(contextAttributes.preserveDrawingBuffer).toEqual(webglOptions.preserveDrawingBuffer); }); it('can enable Order Independent Translucency', function() { widget = new CesiumWidget(container, { orderIndependentTranslucency : true }); expect(widget.scene.orderIndependentTranslucency).toBe(true); }); it('can disable Order Independent Translucency', function() { widget = new CesiumWidget(container, { orderIndependentTranslucency : false }); expect(widget.scene.orderIndependentTranslucency).toBe(false); }); it('throws if no container provided', function() { expect(function() { return new CesiumWidget(undefined); }).toThrowDeveloperError(); }); it('throws if targetFrameRate less than 0', function() { widget = new CesiumWidget(container); expect(function() { widget.targetFrameRate = -1; }).toThrowDeveloperError(); }); it('can set resolutionScale', function() { widget = new CesiumWidget(container); widget.resolutionScale = 0.5; expect(widget.resolutionScale).toBe(0.5); }); it('throws if resolutionScale is less than 0', function() { widget = new CesiumWidget(container); expect(function() { widget.resolutionScale = -1; }).toThrowDeveloperError(); }); it('throws if no container id does not exist', function() { expect(function() { return new CesiumWidget('doesnotexist'); }).toThrowDeveloperError(); }); it('stops the render loop when render throws', function() { widget = new CesiumWidget(container); expect(widget.useDefaultRenderLoop).toEqual(true); var error = 'foo'; widget.scene.primitives.update = function() { throw error; }; waitsFor(function() { return !widget.useDefaultRenderLoop; }, 'render loop to be disabled.'); }); it('shows the error panel when render throws', function() { widget = new CesiumWidget(container); var error = 'foo'; widget.scene.primitives.update = function() { throw error; }; waitsFor(function() { return !widget.useDefaultRenderLoop; }); runs(function() { expect(widget._element.querySelector('.cesium-widget-errorPanel')).not.toBeNull(); var messages = widget._element.querySelectorAll('.cesium-widget-errorPanel-message'); var found = false; for (var i = 0; i < messages.length; ++i) { if (messages[i].textContent === error) { found = true; } } expect(found).toBe(true); // click the OK button to dismiss the panel DomEventSimulator.fireClick(widget._element.querySelector('.cesium-button')); expect(widget._element.querySelector('.cesium-widget-errorPanel')).toBeNull(); }); }); it('does not show the error panel if disabled', function() { widget = new CesiumWidget(container, { showRenderLoopErrors : false }); var error = 'foo'; widget.scene.primitives.update = function() { throw error; }; waitsFor(function() { return !widget.useDefaultRenderLoop; }); runs(function() { expect(widget._element.querySelector('.cesium-widget-errorPanel')).toBeNull(); }); }); }, 'WebGL');
/* */ var $export = require("./$.export"), $imul = Math.imul; $export($export.S + $export.F * require("./$.fails")(function() { return $imul(0xffffffff, 5) != -5 || $imul.length != 2; }), 'Math', {imul: function imul(x, y) { var UINT16 = 0xffff, xn = +x, yn = +y, xl = UINT16 & xn, yl = UINT16 & yn; return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); }});
/** * @fileoverview Prevent missing props validation in a React component definition * @author Yannick Croissant */ 'use strict'; // As for exceptions for props.children or props.className (and alike) look at // https://github.com/yannickcr/eslint-plugin-react/issues/7 const has = require('has'); const Components = require('../util/Components'); const variable = require('../util/variable'); const annotations = require('../util/annotations'); // ------------------------------------------------------------------------------ // Constants // ------------------------------------------------------------------------------ const PROPS_REGEX = /^(props|nextProps)$/; const DIRECT_PROPS_REGEX = /^(props|nextProps)\s*(\.|\[)/; // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: 'Prevent missing props validation in a React component definition', category: 'Best Practices', recommended: true }, schema: [{ type: 'object', properties: { ignore: { type: 'array', items: { type: 'string' } }, customValidators: { type: 'array', items: { type: 'string' } }, skipUndeclared: { type: 'boolean' } }, additionalProperties: false }] }, create: Components.detect((context, components, utils) => { const sourceCode = context.getSourceCode(); const configuration = context.options[0] || {}; const propWrapperFunctions = new Set(context.settings.propWrapperFunctions || []); const ignored = configuration.ignore || []; const customValidators = configuration.customValidators || []; const skipUndeclared = configuration.skipUndeclared || false; // Used to track the type annotations in scope. // Necessary because babel's scopes do not track type annotations. let stack = null; const MISSING_MESSAGE = '\'{{name}}\' is missing in props validation'; /** * Helper for accessing the current scope in the stack. * @param {string} key The name of the identifier to access. If omitted, returns the full scope. * @param {ASTNode} value If provided sets the new value for the identifier. * @returns {Object|ASTNode} Either the whole scope or the ASTNode associated with the given identifier. */ function typeScope(key, value) { if (arguments.length === 0) { return stack[stack.length - 1]; } else if (arguments.length === 1) { return stack[stack.length - 1][key]; } stack[stack.length - 1][key] = value; return value; } /** * Check if we are in a class constructor * @return {boolean} true if we are in a class constructor, false if not */ function inConstructor() { let scope = context.getScope(); while (scope) { if (scope.block && scope.block.parent && scope.block.parent.kind === 'constructor') { return true; } scope = scope.upper; } return false; } /** * Check if we are in a class constructor * @return {boolean} true if we are in a class constructor, false if not */ function inComponentWillReceiveProps() { let scope = context.getScope(); while (scope) { if ( scope.block && scope.block.parent && scope.block.parent.key && scope.block.parent.key.name === 'componentWillReceiveProps' ) { return true; } scope = scope.upper; } return false; } /** * Checks if a prop is being assigned a value props.bar = 'bar' * @param {ASTNode} node The AST node being checked. * @returns {Boolean} */ function isAssignmentToProp(node) { return ( node.parent && node.parent.type === 'AssignmentExpression' && node.parent.left === node ); } /** * Checks if we are using a prop * @param {ASTNode} node The AST node being checked. * @returns {Boolean} True if we are using a prop, false if not. */ function isPropTypesUsage(node) { const isClassUsage = ( (utils.getParentES6Component() || utils.getParentES5Component()) && node.object.type === 'ThisExpression' && node.property.name === 'props' ); const isStatelessFunctionUsage = node.object.name === 'props' && !isAssignmentToProp(node); const isNextPropsUsage = node.object.name === 'nextProps' && inComponentWillReceiveProps(); return isClassUsage || isStatelessFunctionUsage || isNextPropsUsage; } /** * Checks if we are declaring a `props` class property with a flow type annotation. * @param {ASTNode} node The AST node being checked. * @returns {Boolean} True if the node is a type annotated props declaration, false if not. */ function isAnnotatedClassPropsDeclaration(node) { if (node && node.type === 'ClassProperty') { const tokens = context.getFirstTokens(node, 2); if ( node.typeAnnotation && ( tokens[0].value === 'props' || (tokens[1] && tokens[1].value === 'props') ) ) { return true; } } return false; } /** * Checks if we are declaring a props as a generic type in a flow-annotated class. * * @param {ASTNode} node the AST node being checked. * @returns {Boolean} True if the node is a class with generic prop types, false if not. */ function isSuperTypeParameterPropsDeclaration(node) { if (node && node.type === 'ClassDeclaration') { if (node.superTypeParameters && node.superTypeParameters.params.length >= 2) { return true; } } return false; } /** * Checks if we are declaring a prop * @param {ASTNode} node The AST node being checked. * @returns {Boolean} True if we are declaring a prop, false if not. */ function isPropTypesDeclaration(node) { // Special case for class properties // (babel-eslint does not expose property name so we have to rely on tokens) if (node && node.type === 'ClassProperty') { const tokens = context.getFirstTokens(node, 2); if ( tokens[0].value === 'propTypes' || (tokens[1] && tokens[1].value === 'propTypes') ) { return true; } return false; } return Boolean( node && node.name === 'propTypes' ); } /** * Checks if the prop is ignored * @param {String} name Name of the prop to check. * @returns {Boolean} True if the prop is ignored, false if not. */ function isIgnored(name) { return ignored.indexOf(name) !== -1; } /** * Checks if prop should be validated by plugin-react-proptypes * @param {String} validator Name of validator to check. * @returns {Boolean} True if validator should be checked by custom validator. */ function hasCustomValidator(validator) { return customValidators.indexOf(validator) !== -1; } /** * Checks if the component must be validated * @param {Object} component The component to process * @returns {Boolean} True if the component must be validated, false if not. */ function mustBeValidated(component) { const isSkippedByConfig = skipUndeclared && typeof component.declaredPropTypes === 'undefined'; return Boolean( component && component.usedPropTypes && !component.ignorePropsValidation && !isSkippedByConfig ); } /** * Internal: Checks if the prop is declared * @param {Object} declaredPropTypes Description of propTypes declared in the current component * @param {String[]} keyList Dot separated name of the prop to check. * @returns {Boolean} True if the prop is declared, false if not. */ function _isDeclaredInComponent(declaredPropTypes, keyList) { for (let i = 0, j = keyList.length; i < j; i++) { const key = keyList[i]; const propType = ( declaredPropTypes && ( // Check if this key is declared (declaredPropTypes[key] || // If not, check if this type accepts any key declaredPropTypes.__ANY_KEY__) ) ); if (!propType) { // If it's a computed property, we can't make any further analysis, but is valid return key === '__COMPUTED_PROP__'; } if (propType === true) { return true; } // Consider every children as declared if (propType.children === true) { return true; } if (propType.acceptedProperties) { return key in propType.acceptedProperties; } if (propType.type === 'union') { // If we fall in this case, we know there is at least one complex type in the union if (i + 1 >= j) { // this is the last key, accept everything return true; } // non trivial, check all of them const unionTypes = propType.children; const unionPropType = {}; for (let k = 0, z = unionTypes.length; k < z; k++) { unionPropType[key] = unionTypes[k]; const isValid = _isDeclaredInComponent( unionPropType, keyList.slice(i) ); if (isValid) { return true; } } // every possible union were invalid return false; } declaredPropTypes = propType.children; } return true; } /** * Checks if the prop is declared * @param {ASTNode} node The AST node being checked. * @param {String[]} names List of names of the prop to check. * @returns {Boolean} True if the prop is declared, false if not. */ function isDeclaredInComponent(node, names) { while (node) { const component = components.get(node); const isDeclared = component && component.confidence === 2 && _isDeclaredInComponent(component.declaredPropTypes || {}, names) ; if (isDeclared) { return true; } node = node.parent; } return false; } /** * Checks if the prop has spread operator. * @param {ASTNode} node The AST node being marked. * @returns {Boolean} True if the prop has spread operator, false if not. */ function hasSpreadOperator(node) { const tokens = sourceCode.getTokens(node); return tokens.length && tokens[0].value === '...'; } /** * Removes quotes from around an identifier. * @param {string} the identifier to strip */ function stripQuotes(string) { if (string[0] === '\'' || string[0] === '"' && string[0] === string[string.length - 1]) { return string.slice(1, string.length - 1); } return string; } /** * Retrieve the name of a key node * @param {ASTNode} node The AST node with the key. * @return {string} the name of the key */ function getKeyValue(node) { if (node.type === 'ObjectTypeProperty') { const tokens = context.getFirstTokens(node, 2); return (tokens[0].value === '+' || tokens[0].value === '-' ? tokens[1].value : stripQuotes(tokens[0].value) ); } const key = node.key || node.argument; return key.type === 'Identifier' ? key.name : key.value; } /** * Iterates through a properties node, like a customized forEach. * @param {Object[]} properties Array of properties to iterate. * @param {Function} fn Function to call on each property, receives property key and property value. (key, value) => void */ function iterateProperties(properties, fn) { if (properties.length && typeof fn === 'function') { for (let i = 0, j = properties.length; i < j; i++) { const node = properties[i]; const key = getKeyValue(node); const value = node.value; fn(key, value); } } } /** * Creates the representation of the React propTypes for the component. * The representation is used to verify nested used properties. * @param {ASTNode} value Node of the PropTypes for the desired property * @return {Object|Boolean} The representation of the declaration, true means * the property is declared without the need for further analysis. */ function buildReactDeclarationTypes(value) { if ( value && value.callee && value.callee.object && hasCustomValidator(value.callee.object.name) ) { return true; } if ( value && value.type === 'MemberExpression' && value.property && value.property.name && value.property.name === 'isRequired' ) { value = value.object; } // Verify PropTypes that are functions if ( value && value.type === 'CallExpression' && value.callee && value.callee.property && value.callee.property.name && value.arguments && value.arguments.length > 0 ) { const callName = value.callee.property.name; const argument = value.arguments[0]; switch (callName) { case 'shape': if (argument.type !== 'ObjectExpression') { // Invalid proptype or cannot analyse statically return true; } const shapeTypeDefinition = { type: 'shape', children: {} }; iterateProperties(argument.properties, (childKey, childValue) => { shapeTypeDefinition.children[childKey] = buildReactDeclarationTypes(childValue); }); return shapeTypeDefinition; case 'arrayOf': case 'objectOf': return { type: 'object', children: { __ANY_KEY__: buildReactDeclarationTypes(argument) } }; case 'oneOfType': if ( !argument.elements || !argument.elements.length ) { // Invalid proptype or cannot analyse statically return true; } const unionTypeDefinition = { type: 'union', children: [] }; for (let i = 0, j = argument.elements.length; i < j; i++) { const type = buildReactDeclarationTypes(argument.elements[i]); // keep only complex type if (type !== true) { if (type.children === true) { // every child is accepted for one type, abort type analysis unionTypeDefinition.children = true; return unionTypeDefinition; } } unionTypeDefinition.children.push(type); } if (unionTypeDefinition.length === 0) { // no complex type found, simply accept everything return true; } return unionTypeDefinition; case 'instanceOf': return { type: 'instance', // Accept all children because we can't know what type they are children: true }; case 'oneOf': default: return true; } } // Unknown property or accepts everything (any, object, ...) return true; } /** * Creates the representation of the React props type annotation for the component. * The representation is used to verify nested used properties. * @param {ASTNode} annotation Type annotation for the props class property. * @return {Object|Boolean} The representation of the declaration, true means * the property is declared without the need for further analysis. */ function buildTypeAnnotationDeclarationTypes(annotation) { switch (annotation.type) { case 'GenericTypeAnnotation': if (typeScope(annotation.id.name)) { return buildTypeAnnotationDeclarationTypes(typeScope(annotation.id.name)); } return true; case 'ObjectTypeAnnotation': let containsObjectTypeSpread = false; const shapeTypeDefinition = { type: 'shape', children: {} }; iterateProperties(annotation.properties, (childKey, childValue) => { if (!childKey && !childValue) { containsObjectTypeSpread = true; } else { shapeTypeDefinition.children[childKey] = buildTypeAnnotationDeclarationTypes(childValue); } }); // nested object type spread means we need to ignore/accept everything in this object if (containsObjectTypeSpread) { return true; } return shapeTypeDefinition; case 'UnionTypeAnnotation': const unionTypeDefinition = { type: 'union', children: [] }; for (let i = 0, j = annotation.types.length; i < j; i++) { const type = buildTypeAnnotationDeclarationTypes(annotation.types[i]); // keep only complex type if (type !== true) { if (type.children === true) { // every child is accepted for one type, abort type analysis unionTypeDefinition.children = true; return unionTypeDefinition; } } unionTypeDefinition.children.push(type); } if (unionTypeDefinition.children.length === 0) { // no complex type found, simply accept everything return true; } return unionTypeDefinition; case 'ArrayTypeAnnotation': return { type: 'object', children: { __ANY_KEY__: buildTypeAnnotationDeclarationTypes(annotation.elementType) } }; default: // Unknown or accepts everything. return true; } } /** * Retrieve the name of a property node * @param {ASTNode} node The AST node with the property. * @return {string} the name of the property or undefined if not found */ function getPropertyName(node) { const isDirectProp = DIRECT_PROPS_REGEX.test(sourceCode.getText(node)); const isInClassComponent = utils.getParentES6Component() || utils.getParentES5Component(); const isNotInConstructor = !inConstructor(); const isNotInComponentWillReceiveProps = !inComponentWillReceiveProps(); if (isDirectProp && isInClassComponent && isNotInConstructor && isNotInComponentWillReceiveProps) { return void 0; } if (!isDirectProp) { node = node.parent; } const property = node.property; if (property) { switch (property.type) { case 'Identifier': if (node.computed) { return '__COMPUTED_PROP__'; } return property.name; case 'MemberExpression': return void 0; case 'Literal': // Accept computed properties that are literal strings if (typeof property.value === 'string') { return property.value; } // falls through default: if (node.computed) { return '__COMPUTED_PROP__'; } break; } } return void 0; } /** * Mark a prop type as used * @param {ASTNode} node The AST node being marked. */ function markPropTypesAsUsed(node, parentNames) { parentNames = parentNames || []; let type; let name; let allNames; let properties; switch (node.type) { case 'MemberExpression': name = getPropertyName(node); if (name) { allNames = parentNames.concat(name); if (node.parent.type === 'MemberExpression') { markPropTypesAsUsed(node.parent, allNames); } // Do not mark computed props as used. type = name !== '__COMPUTED_PROP__' ? 'direct' : null; } else if ( node.parent.id && node.parent.id.properties && node.parent.id.properties.length && getKeyValue(node.parent.id.properties[0]) ) { type = 'destructuring'; properties = node.parent.id.properties; } break; case 'ArrowFunctionExpression': case 'FunctionDeclaration': case 'FunctionExpression': type = 'destructuring'; properties = node.params[0].properties; break; case 'VariableDeclarator': for (let i = 0, j = node.id.properties.length; i < j; i++) { // let {props: {firstname}} = this const thisDestructuring = ( !hasSpreadOperator(node.id.properties[i]) && (PROPS_REGEX.test(node.id.properties[i].key.name) || PROPS_REGEX.test(node.id.properties[i].key.value)) && node.id.properties[i].value.type === 'ObjectPattern' ); // let {firstname} = props const directDestructuring = PROPS_REGEX.test(node.init.name) && (utils.getParentStatelessComponent() || inConstructor() || inComponentWillReceiveProps()) ; if (thisDestructuring) { properties = node.id.properties[i].value.properties; } else if (directDestructuring) { properties = node.id.properties; } else { continue; } type = 'destructuring'; break; } break; default: throw new Error(`${node.type} ASTNodes are not handled by markPropTypesAsUsed`); } const component = components.get(utils.getParentComponent()); const usedPropTypes = (component && component.usedPropTypes || []).slice(); switch (type) { case 'direct': // Ignore Object methods if (Object.prototype[name]) { break; } const isDirectProp = DIRECT_PROPS_REGEX.test(sourceCode.getText(node)); usedPropTypes.push({ name: name, allNames: allNames, node: ( !isDirectProp && !inConstructor() && !inComponentWillReceiveProps() ? node.parent.property : node.property ) }); break; case 'destructuring': for (let k = 0, l = properties.length; k < l; k++) { if (hasSpreadOperator(properties[k]) || properties[k].computed) { continue; } const propName = getKeyValue(properties[k]); let currentNode = node; allNames = []; while (currentNode.property && !PROPS_REGEX.test(currentNode.property.name)) { allNames.unshift(currentNode.property.name); currentNode = currentNode.object; } allNames.push(propName); if (propName) { usedPropTypes.push({ name: propName, allNames: allNames, node: properties[k] }); } } break; default: break; } components.set(node, { usedPropTypes: usedPropTypes }); } /** * Mark a prop type as declared * @param {ASTNode} node The AST node being checked. * @param {propTypes} node The AST node containing the proptypes */ function markPropTypesAsDeclared(node, propTypes) { let componentNode = node; while (componentNode && !components.get(componentNode)) { componentNode = componentNode.parent; } const component = components.get(componentNode); const declaredPropTypes = component && component.declaredPropTypes || {}; let ignorePropsValidation = false; switch (propTypes && propTypes.type) { case 'ObjectTypeAnnotation': iterateProperties(propTypes.properties, (key, value) => { if (!value) { ignorePropsValidation = true; return; } declaredPropTypes[key] = buildTypeAnnotationDeclarationTypes(value); }); break; case 'ObjectExpression': iterateProperties(propTypes.properties, (key, value) => { if (!value) { ignorePropsValidation = true; return; } declaredPropTypes[key] = buildReactDeclarationTypes(value); }); break; case 'MemberExpression': let curDeclaredPropTypes = declaredPropTypes; // Walk the list of properties, until we reach the assignment // ie: ClassX.propTypes.a.b.c = ... while ( propTypes && propTypes.parent && propTypes.parent.type !== 'AssignmentExpression' && propTypes.property && curDeclaredPropTypes ) { const propName = propTypes.property.name; if (propName in curDeclaredPropTypes) { curDeclaredPropTypes = curDeclaredPropTypes[propName].children; propTypes = propTypes.parent; } else { // This will crash at runtime because we haven't seen this key before // stop this and do not declare it propTypes = null; } } if (propTypes && propTypes.parent && propTypes.property) { curDeclaredPropTypes[propTypes.property.name] = buildReactDeclarationTypes(propTypes.parent.right); } else { ignorePropsValidation = true; } break; case 'Identifier': const variablesInScope = variable.variablesInScope(context); for (let i = 0, j = variablesInScope.length; i < j; i++) { if (variablesInScope[i].name !== propTypes.name) { continue; } const defInScope = variablesInScope[i].defs[variablesInScope[i].defs.length - 1]; markPropTypesAsDeclared(node, defInScope.node && defInScope.node.init); return; } ignorePropsValidation = true; break; case 'CallExpression': if ( propWrapperFunctions.has(sourceCode.getText(propTypes.callee)) && propTypes.arguments && propTypes.arguments[0] ) { markPropTypesAsDeclared(node, propTypes.arguments[0]); return; } break; case null: break; default: ignorePropsValidation = true; break; } components.set(node, { declaredPropTypes: declaredPropTypes, ignorePropsValidation: ignorePropsValidation }); } /** * Reports undeclared proptypes for a given component * @param {Object} component The component to process */ function reportUndeclaredPropTypes(component) { let allNames; for (let i = 0, j = component.usedPropTypes.length; i < j; i++) { allNames = component.usedPropTypes[i].allNames; if ( isIgnored(allNames[0]) || isDeclaredInComponent(component.node, allNames) ) { continue; } context.report( component.usedPropTypes[i].node, MISSING_MESSAGE, { name: allNames.join('.').replace(/\.__COMPUTED_PROP__/g, '[]') } ); } } /** * Resolve the type annotation for a given node. * Flow annotations are sometimes wrapped in outer `TypeAnnotation` * and `NullableTypeAnnotation` nodes which obscure the annotation we're * interested in. * This method also resolves type aliases where possible. * * @param {ASTNode} node The annotation or a node containing the type annotation. * @returns {ASTNode} The resolved type annotation for the node. */ function resolveTypeAnnotation(node) { let annotation = node.typeAnnotation || node; while (annotation && (annotation.type === 'TypeAnnotation' || annotation.type === 'NullableTypeAnnotation')) { annotation = annotation.typeAnnotation; } if (annotation.type === 'GenericTypeAnnotation' && typeScope(annotation.id.name)) { return typeScope(annotation.id.name); } return annotation; } /** * Resolve the type annotation for a given class declaration node with superTypeParameters. * * @param {ASTNode} node The annotation or a node containing the type annotation. * @returns {ASTNode} The resolved type annotation for the node. */ function resolveSuperParameterPropsType(node) { let annotation = node.superTypeParameters.params[1]; while (annotation && (annotation.type === 'TypeAnnotation' || annotation.type === 'NullableTypeAnnotation')) { annotation = annotation.typeAnnotation; } if (annotation.type === 'GenericTypeAnnotation' && typeScope(annotation.id.name)) { return typeScope(annotation.id.name); } return annotation; } /** * @param {ASTNode} node We expect either an ArrowFunctionExpression, * FunctionDeclaration, or FunctionExpression */ function markDestructuredFunctionArgumentsAsUsed(node) { const destructuring = node.params && node.params[0] && node.params[0].type === 'ObjectPattern'; if (destructuring && components.get(node)) { markPropTypesAsUsed(node); } } /** * @param {ASTNode} node We expect either an ArrowFunctionExpression, * FunctionDeclaration, or FunctionExpression */ function markAnnotatedFunctionArgumentsAsDeclared(node) { if (!node.params || !node.params.length || !annotations.isAnnotatedFunctionPropsDeclaration(node, context)) { return; } markPropTypesAsDeclared(node, resolveTypeAnnotation(node.params[0])); } /** * @param {ASTNode} node We expect either an ArrowFunctionExpression, * FunctionDeclaration, or FunctionExpression */ function handleStatelessComponent(node) { markDestructuredFunctionArgumentsAsUsed(node); markAnnotatedFunctionArgumentsAsDeclared(node); } // -------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- return { ClassDeclaration: function(node) { if (isSuperTypeParameterPropsDeclaration(node)) { markPropTypesAsDeclared(node, resolveSuperParameterPropsType(node)); } }, ClassProperty: function(node) { if (isAnnotatedClassPropsDeclaration(node)) { markPropTypesAsDeclared(node, resolveTypeAnnotation(node)); } else if (isPropTypesDeclaration(node)) { markPropTypesAsDeclared(node, node.value); } }, VariableDeclarator: function(node) { const destructuring = node.init && node.id && node.id.type === 'ObjectPattern'; // let {props: {firstname}} = this const thisDestructuring = destructuring && node.init.type === 'ThisExpression'; // let {firstname} = props const directDestructuring = destructuring && PROPS_REGEX.test(node.init.name) && (utils.getParentStatelessComponent() || inConstructor() || inComponentWillReceiveProps()) ; if (!thisDestructuring && !directDestructuring) { return; } markPropTypesAsUsed(node); }, FunctionDeclaration: handleStatelessComponent, ArrowFunctionExpression: handleStatelessComponent, FunctionExpression: function(node) { if (node.parent.type === 'MethodDefinition') { return; } handleStatelessComponent(node); }, MemberExpression: function(node) { let type; if (isPropTypesUsage(node)) { type = 'usage'; } else if (isPropTypesDeclaration(node.property)) { type = 'declaration'; } switch (type) { case 'usage': markPropTypesAsUsed(node); break; case 'declaration': const component = utils.getRelatedComponent(node); if (!component) { return; } markPropTypesAsDeclared(component.node, node.parent.right || node.parent); break; default: break; } }, MethodDefinition: function(node) { if (!node.static || node.kind !== 'get' || !isPropTypesDeclaration(node.key)) { return; } let i = node.value.body.body.length - 1; for (; i >= 0; i--) { if (node.value.body.body[i].type === 'ReturnStatement') { break; } } if (i >= 0) { markPropTypesAsDeclared(node, node.value.body.body[i].argument); } }, ObjectExpression: function(node) { // Search for the proptypes declaration node.properties.forEach(property => { if (!isPropTypesDeclaration(property.key)) { return; } markPropTypesAsDeclared(node, property.value); }); }, TypeAlias: function(node) { typeScope(node.id.name, node.right); }, Program: function() { stack = [{}]; }, BlockStatement: function () { stack.push(Object.create(typeScope())); }, 'BlockStatement:exit': function () { stack.pop(); }, 'Program:exit': function() { stack = null; const list = components.list(); // Report undeclared proptypes for all classes for (const component in list) { if (!has(list, component) || !mustBeValidated(list[component])) { continue; } reportUndeclaredPropTypes(list[component]); } } }; }) };
"use strict"; class A { [() => (void 0).name]() {} }
(function() { 'use strict'; /* * * @name lineSeries */ d4.feature('lineSeries', function(name) { var line = d3.svg.line(); line.interpolate('linear'); return { accessors: { classes: function(d, n) { return 'line stroke series' + n; }, key: d4.functor(d4.defaultKey), x: function(d) { return this.x(d[this.x.$key]); }, y: function(d) { return this.y(d[this.y.$key]); } }, proxies: [{ target: line }], render: function(scope, data, selection) { var group = d4.appendOnce(selection, 'g.' + name); line .x(d4.functor(scope.accessors.x).bind(this)) .y(d4.functor(scope.accessors.y).bind(this)); var lineGroups = group.selectAll('g') .data(data, d4.functor(scope.accessors.key).bind(this)); lineGroups.enter().append('g') .attr('data-key', function(d) { return d.key; }) .attr('class', d4.functor(scope.accessors.classes).bind(this)); var lines = lineGroups.selectAll('path') .data(function(d) { return [d]; }); lines.enter().append('path'); lines.attr('d', function(d) { return line(d.values); }); lines.exit().remove(); lineGroups.exit().remove(); return lineGroups; } }; }); }).call(this);
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: String.prototype.substring (start, end) returns a string value(not object) es5id: 15.5.4.15_A2_T8 description: start is tested_string.length+1, end is 0 ---*/ var __string = new String("this is a string object"); ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if (__string.substring(__string.length+1, 0) !== "this is a string object") { $ERROR('#1: __string = new String("this is a string object"); __string.substring(__string.length+1, 0) === "this is a string object". Actual: '+__string.substring(__string.length+1, 0) ); } // //////////////////////////////////////////////////////////////////////////////
/** * refer: * * @atimb "Real keep-alive HTTP agent": https://gist.github.com/2963672 * * https://github.com/joyent/node/blob/master/lib/http.js * * https://github.com/joyent/node/blob/master/lib/https.js * * https://github.com/joyent/node/blob/master/lib/_http_agent.js */ 'use strict'; const OriginalAgent = require('./_http_agent').Agent; const ms = require('humanize-ms'); class Agent extends OriginalAgent { constructor(options) { options = options || {}; options.keepAlive = options.keepAlive !== false; // default is keep-alive and 15s free socket timeout if (options.freeSocketKeepAliveTimeout === undefined) { options.freeSocketKeepAliveTimeout = 15000; } // Legacy API: keepAliveTimeout should be rename to `freeSocketKeepAliveTimeout` if (options.keepAliveTimeout) { options.freeSocketKeepAliveTimeout = options.keepAliveTimeout; } options.freeSocketKeepAliveTimeout = ms(options.freeSocketKeepAliveTimeout); // Sets the socket to timeout after timeout milliseconds of inactivity on the socket. // By default is double free socket keepalive timeout. if (options.timeout === undefined) { options.timeout = options.freeSocketKeepAliveTimeout * 2; // make sure socket default inactivity timeout >= 30s if (options.timeout < 30000) { options.timeout = 30000; } } options.timeout = ms(options.timeout); super(options); this.createSocketCount = 0; this.createSocketErrorCount = 0; this.closeSocketCount = 0; // socket error event count this.errorSocketCount = 0; this.requestCount = 0; this.timeoutSocketCount = 0; this.on('free', s => { this.requestCount++; // last enter free queue timestamp s.lastFreeTime = Date.now(); }); this.on('timeout', () => { this.timeoutSocketCount++; }); this.on('close', () => { this.closeSocketCount++; }); this.on('error', () => { this.errorSocketCount++; }); } createSocket(req, options, cb) { super.createSocket(req, options, (err, socket) => { if (err) { this.createSocketErrorCount++; return cb(err); } if (this.keepAlive) { // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/ // https://fengmk2.com/benchmark/nagle-algorithm-delayed-ack-mock.html socket.setNoDelay(true); } this.createSocketCount++; cb(null, socket); }); } getCurrentStatus() { return { createSocketCount: this.createSocketCount, createSocketErrorCount: this.createSocketErrorCount, closeSocketCount: this.closeSocketCount, errorSocketCount: this.errorSocketCount, timeoutSocketCount: this.timeoutSocketCount, requestCount: this.requestCount, freeSockets: inspect(this.freeSockets), sockets: inspect(this.sockets), requests: inspect(this.requests), }; } } module.exports = Agent; function inspect(obj) { const res = {}; for (const key in obj) { res[key] = obj[key].length; } return res; }
/** * Copyright 2015 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["ar-JO"] = { name: "ar-JO", numberFormat: { pattern: ["n-"], decimals: 3, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 3, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$n-","$ n"], decimals: 3, ",": ",", ".": ".", groupSize: [3], symbol: "د.ا.‏" } }, calendars: { standard: { days: { names: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"], namesAbbr: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"], namesShort: ["ح","ن","ث","ر","خ","ج","س"] }, months: { names: ["كانون الثاني","شباط","آذار","نيسان","أيار","حزيران","تموز","آب","أيلول","تشرين الأول","تشرين الثاني","كانون الأول",""], namesAbbr: ["كانون الثاني","شباط","آذار","نيسان","أيار","حزيران","تموز","آب","أيلول","تشرين الأول","تشرين الثاني","كانون الأول",""] }, AM: ["ص","ص","ص"], PM: ["م","م","م"], patterns: { d: "dd/MM/yyyy", D: "dd MMMM, yyyy", F: "dd MMMM, yyyy hh:mm:ss tt", g: "dd/MM/yyyy hh:mm tt", G: "dd/MM/yyyy hh:mm:ss tt", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "hh:mm tt", T: "hh:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "/", ":": ":", firstDay: 6 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
//generating session info var uuid = require('win-utils').cuid; module.exports = winiec; function winiec(backbone, globalConfig, localConfig) { //pull in backbone info, we gotta set our logger/emitter up var self = this; self.winFunction = "evolution"; if(!localConfig.genomeType) throw new Error("win-IEC needs a genome type specified."); //this is how we talk to win-backbone self.backEmit = backbone.getEmitter(self); //grab our logger self.log = backbone.getLogger(self); //only vital stuff goes out for normal logs self.log.logLevel = localConfig.logLevel || self.log.normal; //we have logger and emitter, set up some of our functions function clearEvolution(genomeType) { //optionally, we can change types if we need to if(genomeType) self.genomeType = genomeType; self.log("clear evo to type: ", self.genomeType) self.selectedParents = {}; //all the evo objects we ceated -- parents are a subset self.evolutionObjects = {}; //count it up self.parentCount = 0; //session information -- new nodes and connections yo! that's all we care about after all-- new innovative stuff //i rambled just then. For no reason. Still doing it. Sucks that you're reading this. trolololol self.sessionObject = {}; //everything we publish is linked by this session information self.evolutionSessionID = uuid(); //save our seeds! self.seeds = {}; //map children to parents for all objects self.childrenToParents = {}; self.seedParents = {}; } //we setup all our basic clearEvolution(localConfig.genomeType); //what events do we need? self.requiredEvents = function() { return [ //need to be able to create artifacts "generator:createArtifacts", "schema:replaceParentReferences", "schema:getReferencesAndParents", "publish:publishArtifacts", //in the future we will also need to save objects according to our save tendencies //for now, we'll offload that to UI decisions ]; } //what events do we respond to? self.eventCallbacks = function() { return { "evolution:selectParents" : self.selectParents, "evolution:unselectParents" : self.unselectParents, "evolution:publishArtifact" : self.publishArtifact, //we fetch a list of objects based on IDs, if they don't exist we create them "evolution:getOrCreateOffspring" : self.getOrCreateOffspring, "evolution:loadSeeds" : self.loadSeeds, "evolution:resetEvolution" : clearEvolution }; } // self.findSeedOrigins = function(eID) // { // //let's look through parents until we find the seed you originated from -- then you are considered a decendant // var alreadyChecked = {}; // var originObjects = {}; // var startingParents = self.childrenToParents[eID]; // while(startingParents.length) // { // var nextCheck = []; // for(var i=0; i < startingParents.length; i++) // { // var parentWID = startingParents[i]; // if(!alreadyChecked[parentWID]) // { // //mark it as checked // alreadyChecked[parentWID] = true; // if(self.seeds[parentWID]) // { // //this is a seed! // originObjects[parentWID] = self.seeds[parentWID]; // } // //otherwise, it's not of interested, but perhaps it's parents are! // //let's look at the parents parents // var grandparents = self.childrenToParents[parentWID]; // if(grandparents) // { // nextCheck = nextCheck.concat(grandparents); // } // } // } // //continue the process - don't worry about loops, we're checking! // startingParents = nextCheck; // } // //send back all the seed objects // return originObjects // } self.publishArtifact = function(id, meta, finished) { //don't always have to send meta info -- since we don't know what to do with it anyways if(typeof meta == "function") { finished = meta; meta = {}; } //we fetch the object from the id var evoObject = self.evolutionObjects[id]; if(!evoObject) { finished("Evolutionary artifactID to publish is invalid: " + id); return; } //we also want to store some meta info -- don't do anything about that for now // var seedParents = self.findSeedOrigins(id); // var seedList = []; //here is what needs to happen, the incoming evo object has the "wrong" parents //the right parents are the published parents -- the other parents //this will need to be fixed in the future -- we need to know private vs public parents //but for now, we simply send in the public parents -- good enough for picbreeder iec applications //other types of applications might need more info. var widObject = {}; widObject[evoObject.wid] = evoObject; self.backEmit("schema:getReferencesAndParents", self.genomeType, widObject, function(err, refsAndParents){ //now we know our references var refParents = refsAndParents[evoObject.wid]; //so we simply fetch our appropraite seed parents var evoSeedParents = self.noDuplicatSeedParents(refParents); //now we have all the info we need to replace all our parent refs self.backEmit("schema:replaceParentReferences", self.genomeType, evoObject, evoSeedParents, function(err, cloned) { //now we have a cloned version for publishing, where it has public seeds //just publish everything public for now! var session = {sessionID: self.evolutionSessionID, publish: true}; //we can also save private info //this is where we would grab all the parents of the individual var privateObjects = []; self.backEmit("publish:publishArtifacts", self.genomeType, session, [cloned], [], function(err) { if(err) { finished(err); } else //no error publishing, hooray! finished(undefined, cloned); }) }) }); } //no need for a callback here -- nuffin to do but load self.loadSeeds = function(idAndSeeds, finished) { //we have all the seeds and their ids, we just absorb them immediately for(var eID in idAndSeeds) { var seed = idAndSeeds[eID]; //grab the objects and save them self.evolutionObjects[eID] = seed; //save our seeds self.seeds[seed.wid] = seed; } self.log("seed objects: ", self.seeds); self.backEmit("schema:getReferencesAndParents", self.genomeType, self.seeds, function(err, refsAndParents) { if(err) { //pass on the error if it happened if(finished) finished(err); else throw err; return; } //there are no parent refs for seeds, just the refs themselves which are important for(var wid in self.seeds) { var refs = Object.keys(refsAndParents[wid]); for(var i=0; i < refs.length; i++) { //who is the parent seed of a particular wid? why itself duh! self.seedParents[refs[i]] = [refs[i]]; } } // self.log("Seed parents: ", self.seedParents); //note, there is no default behavior with seeds -- as usual, you must still tell iec to select parents //there is no subsitute for parent selection if(finished) finished(); }); } //just grab from evo objects -- throw error if issue self.selectParents = function(eIDList, finished) { if(typeof eIDList == "string") eIDList = [eIDList]; var selectedObjects = {}; for(var i=0; i < eIDList.length; i++) { var eID = eIDList[i]; //grab from evo var evoObject = self.evolutionObjects[eID]; if(!evoObject){ //wrong id finished("Invalid parent selection: " + eID); return; } selectedObjects[eID] = evoObject; //save as a selected parent self.selectedParents[eID] = evoObject; self.parentCount++; } //send back the evolutionary object that is linked to this parentID finished(undefined, selectedObjects); } self.unselectParents = function(eIDList, finished) { if(typeof eIDList == "string") eIDList = [eIDList]; for(var i=0; i < eIDList.length; i++) { var eID = eIDList[i]; //remove this parent from the selected parents -- doesn't delete from all the individuals if(self.selectedParents[eID]) self.parentCount--; delete self.selectedParents[eID]; } //callback optional really, here for backwards compat if(finished) finished(); } self.noDuplicatSeedParents = function(refsAndParents) { var allSeedNoDup = {}; //this is a map from the wid to the associated parent wids for(var refWID in refsAndParents) { var parents = refsAndParents[refWID]; var mergeParents = []; for(var i=0; i < parents.length; i++) { var seedsForEachParent = self.seedParents[parents[i]]; //now we just merge all these together mergeParents = mergeParents.concat(seedsForEachParent); } //then we get rid of any duplicates var nodups = {}; for(var i=0; i < mergeParents.length; i++) nodups[mergeParents[i]] = true; //by induction, each wid generated knows it's seed parents (where each seed reference wid references itself in array form) //therefore, you just look at your reference's parents to see who they believe is their seed //and concat those results together -- pretty simple, just remove duplicates allSeedNoDup[refWID] = Object.keys(nodups); } return allSeedNoDup; } self.callGenerator = function(allObjects, toCreate, finished) { var parents = self.getOffspringParents(); //we need to go fetch some stuff self.backEmit("generator:createArtifacts", self.genomeType, toCreate.length, parents, self.sessionObject, function(err, artifacts) { if(err) { //pass on the error if it happened finished(err); return; } // self.log("iec generated " + toCreate.length + " individuals: ", artifacts); //otherwise, let's do this thang! match artifacts to offspring -- arbitrary don't worry var off = artifacts.offspring; var widOffspring = {}; for(var i=0; i < off.length; i++) { var oObject = off[i]; var eID = toCreate[i]; //save our evolution object internally -- no more fetches required self.evolutionObjects[eID] = oObject; //store objects relateive to their requested ids for return allObjects[eID] = (oObject); //clone the parent objects for the child! widOffspring[oObject.wid] = oObject; // var util = require('util') // self.log("off returned: ".magenta, util.inspect(oObject, false, 3)); } self.backEmit("schema:getReferencesAndParents", self.genomeType, widOffspring, function(err, refsAndParents) { if(err) { finished(err); return; } //check the refs for each object for(var wid in widOffspring) { //here we are with refs and parents var rAndP = refsAndParents[wid]; var widSeedParents = self.noDuplicatSeedParents(rAndP); // self.log("\n\nwid seed parents: ".magenta, rAndP); //for each key, we set our seed parents appropriately for(var key in widSeedParents) { self.seedParents[key] = widSeedParents[key]; } } // self.log("\n\nSeed parents: ".magenta, self.seedParents); //mark the offspring as the list objects finished(undefined, allObjects); }); }); } //generator yo face! self.getOrCreateOffspring = function(eIDList, finished) { //don't bother doing anything if you havne't selected parents if(self.parentCount ==0){ finished("Cannot generate offspring without parents"); return; } //we need to make a bunch, as many as requested var toCreate = []; var allObjects = {}; //first we check to see which ids we already know for(var i=0; i < eIDList.length; i++) { var eID = eIDList[i]; var evoObject = self.evolutionObjects[eID]; if(!evoObject) { toCreate.push(eID); } else { //otherwise add to objects that will be sent back allObjects[eID] = evoObject; } } //now we have a list of objects that must be created if(toCreate.length) { //this will handle the finished call for us -- after it gets artifacts from the generator self.callGenerator(allObjects, toCreate, finished); } else { //all ready to go -- send back our objects finished(undefined, allObjects) } } self.getOffspringParents = function() { var parents = []; for(var key in self.selectedParents) parents.push(self.selectedParents[key]); return parents; } return self; }
/** * Numeric cell renderer * * @private * @renderer * @component NumericRenderer * @dependencies numeral * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properties (shared by cell renderer and editor) */ import * as dom from './../dom.js'; import * as helper from './../helpers.js'; import numeral from 'numeral'; import {getRenderer, registerRenderer} from './../renderers.js'; export {numericRenderer}; registerRenderer('numeric', numericRenderer); function numericRenderer(instance, TD, row, col, prop, value, cellProperties) { if (helper.isNumeric(value)) { if (typeof cellProperties.language !== 'undefined') { numeral.language(cellProperties.language); } value = numeral(value).format(cellProperties.format || '0'); //docs: http://numeraljs.com/ dom.addClass(TD, 'htNumeric'); } getRenderer('text')(instance, TD, row, col, prop, value, cellProperties); }
'use strict'; module.exports = (srcPath) => { const Broadcast = require(srcPath + 'Broadcast'); return { listeners: { playerEnter: state => function (player) { const quest = state.QuestFactory.create(state, 'limbo:1', player); if (player.questTracker.canStart(quest)) { player.questTracker.start(quest); } } } }; };
(function(){ window.JST = window.JST || {}; var template = function(str){var fn = new Function('obj', 'var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push(\''+str.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/<%=([\s\S]+?)%>/g,function(match,code){return "',"+code.replace(/\\'/g, "'")+",'";}).replace(/<%([\s\S]+?)%>/g,function(match,code){return "');"+code.replace(/\\'/g, "'").replace(/[\r\n\t]/g,' ')+"__p.push('";}).replace(/\r/g,'\\r').replace(/\n/g,'\\n').replace(/\t/g,'\\t')+"');}return __p.join('');");return fn;}; window.JST['template1'] = template('<a href="<%= to_somewhere %>"><%= saying_something %></a>'); window.JST['template2'] = template('<% _([1,2,3]).each(function(num) { %>\n <li class="number">\n <%= num %>\n </li>\n<% }) %>'); })();
/** * Copyright 2015 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["is"] = { name: "is", numberFormat: { pattern: ["-n"], decimals: 2, ",": ".", ".": ",", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": ".", ".": ",", groupSize: [3], symbol: "%" }, currency: { pattern: ["-n $","n $"], decimals: 0, ",": ".", ".": ",", groupSize: [3], symbol: "kr." } }, calendars: { standard: { days: { names: ["sunnudagur","mánudagur","þriðjudagur","miðvikudagur","fimmtudagur","föstudagur","laugardagur"], namesAbbr: ["sun.","mán.","þri.","mið.","fim.","fös.","lau."], namesShort: ["su","má","þr","mi","fi","fö","la"] }, months: { names: ["janúar","febrúar","mars","apríl","maí","júní","júlí","ágúst","september","október","nóvember","desember",""], namesAbbr: ["jan.","feb.","mar.","apr.","maí","jún.","júl.","ágú.","sep.","okt.","nóv.","des.",""] }, AM: [""], PM: [""], patterns: { d: "d.M.yyyy", D: "d. MMMM yyyy", F: "d. MMMM yyyy HH:mm:ss", g: "d.M.yyyy HH:mm", G: "d.M.yyyy HH:mm:ss", m: "d. MMMM", M: "d. MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": ".", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
import 'react-native' import React from 'react' import Index from '../index.android.js' // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer' it('renders correctly', () => { const tree = renderer.create( <Index /> ) })
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<7488a05d95fdcc843c9e4de00db63c46>> * @flow * @lightSyntaxTransform * @nogrep */ /* eslint-disable */ 'use strict'; /*:: import type { ConcreteRequest, Query } from 'relay-runtime'; type RelayMockPayloadGeneratorTestFragment$fragmentType = any; export type RelayMockPayloadGeneratorTest1Query$variables = {||}; export type RelayMockPayloadGeneratorTest1Query$data = {| +node: ?{| +$fragmentSpreads: RelayMockPayloadGeneratorTestFragment$fragmentType, |}, |}; export type RelayMockPayloadGeneratorTest1Query = {| variables: RelayMockPayloadGeneratorTest1Query$variables, response: RelayMockPayloadGeneratorTest1Query$data, |}; */ var node/*: ConcreteRequest*/ = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "my-id" } ]; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "RelayMockPayloadGeneratorTest1Query", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "RelayMockPayloadGeneratorTestFragment" } ], "storageKey": "node(id:\"my-id\")" } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "RelayMockPayloadGeneratorTest1Query", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, { "kind": "InlineFragment", "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "profile_picture", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "uri", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "width", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "height", "storageKey": null } ], "storageKey": null } ], "type": "User", "abstractKey": null } ], "storageKey": "node(id:\"my-id\")" } ] }, "params": { "cacheID": "f39283a2ef7a702acb5069d604584178", "id": null, "metadata": {}, "name": "RelayMockPayloadGeneratorTest1Query", "operationKind": "query", "text": "query RelayMockPayloadGeneratorTest1Query {\n node(id: \"my-id\") {\n __typename\n ...RelayMockPayloadGeneratorTestFragment\n id\n }\n}\n\nfragment RelayMockPayloadGeneratorTestFragment on User {\n id\n name\n profile_picture {\n uri\n width\n height\n }\n}\n" } }; })(); if (__DEV__) { (node/*: any*/).hash = "84c1a5848aae26089f4aaaaa74c56543"; } module.exports = ((node/*: any*/)/*: Query< RelayMockPayloadGeneratorTest1Query$variables, RelayMockPayloadGeneratorTest1Query$data, >*/);
/**************************************************************************** global-events, a plugin to administrate any events (c) 2015, FCOO https://github.com/FCOO/global-events https://github.com/FCOO ****************************************************************************/ (function ($, window/*, document, undefined*/) { "use strict"; function GlobalEvents( ) { this.events = {}; this._loop = function( eventNames, func, reverse ){ var eventName, j; eventNames = ( eventNames || "" ).match( (/\S+/g) ) || [ "" ]; for (j=0; j<eventNames.length; j++ ){ eventName = eventNames[j]; if (eventName){ this.events[eventName] = this.events[eventName] || []; var i, lgd = this.events[eventName].length; if (reverse){ for (i=lgd-1; i>=0; i-- ) if (func( this.events[eventName][i], i, this.events[eventName] )) break; } else { for (i=0; i<lgd; i++ ) if (func( this.events[eventName][i], i, this.events[eventName] )) break; } } } }; this.on = function(eventNames, callback, context, options){ var eventName, i; eventNames = ( eventNames || "" ).match( (/\S+/g) ) || [ "" ]; for (i=0; i<eventNames.length; i++ ){ eventName = eventNames[i]; if (eventName){ this.events[eventName] = this.events[eventName] || []; this.events[eventName].push( { callback: callback, context : context || null, options : $.extend( {once:false, first:false, last:false}, options ) }); } } }; this.once = function( eventName, callback, context ) { this.on( eventName, callback, context, { once:true } ); }; this.onFirst = function( eventName, callback, context ) { this.on( eventName, callback, context, { first:true } ); }; this.onLast = function( eventName, callback, context ) { this.on( eventName, callback, context, { last:true } ); }; this.onceFirst = function( eventName, callback, context ) { this.on( eventName, callback, context, { once:true, first:true } ); }; this.onceLast = function( eventName, callback, context ) { this.on( eventName, callback, context, { once:true, last:true } ); }; this.off = function(eventNames, callback, context){ var eventName, i, _loop_func; eventNames = ( eventNames || "" ).match( (/\S+/g) ) || [ "" ]; _loop_func = function( eventObj, index, list ){ if ( (callback == eventObj.callback) && (!context || (context == eventObj.context)) ){ list.splice(index, 1); return true; } }; for (i=0; i<eventNames.length; i++ ){ eventName = eventNames[i]; if (eventName){ this._loop( eventName, _loop_func ); } } }; this.fire = function( eventName /*, arg1, arg2, .., argN */ ){ var newArguments = []; for (var i=1; i < arguments.length; i++) { newArguments.push(arguments[i]); } //Fire the functions marked 'first' this._loop( eventName, function( eventObj ){ if (eventObj.options.first) eventObj.callback.apply( eventObj.context, newArguments ); }); //Fire the functions not marked 'first' or 'last' this._loop( eventName, function( eventObj ){ if (!eventObj.options.first && !eventObj.options.last) eventObj.callback.apply( eventObj.context, newArguments ); }); //Fire the functions marked 'last' this._loop( eventName, function( eventObj ){ if (eventObj.options.last) eventObj.callback.apply( eventObj.context, newArguments ); }); //Remove all functions marked 'once' this._loop( eventName, function( eventObj, index, list ){ if (eventObj.options.once) list.splice(index, 1); }, true); }; this.trigger = function(){ this.fire( arguments ); }; this.one = function(){ this.once( arguments ); }; this.oneFirst = function(){ this.onceFirst( arguments ); }; this.oneLast = function(){ this.onceLast( arguments ); }; } // expose access to the constructor window.GlobalEvents = GlobalEvents; }(jQuery, this, document));
import { x00, x01, x02, x03, x04, x05, x06, x07, x08, x09, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22, x23, x24, x25, x26, x27, x28, x29, x30, x31, x32, x33, x34, x35, x36, x37, x38, x39, x40, x41, x42, x43, x44, x45, x46, x47, x48, x49 } from "./module"; export default () => { expect(x00).toBe("x00"); expect(x01).toBe("x01"); expect(x02).toBe("x02"); expect(x03).toBe("x03"); expect(x04).toBe("x04"); expect(x05).toBe("x05"); expect(x06).toBe("x06"); expect(x07).toBe("x07"); expect(x08).toBe("x08"); expect(x09).toBe("x09"); expect(x10).toBe("x10"); expect(x11).toBe("x11"); expect(x12).toBe("x12"); expect(x13).toBe("x13"); expect(x14).toBe("x14"); expect(x15).toBe("x15"); expect(x16).toBe("x16"); expect(x17).toBe("x17"); expect(x18).toBe("x18"); expect(x19).toBe("x19"); expect(x20).toBe("x20"); expect(x21).toBe("x21"); expect(x22).toBe("x22"); expect(x23).toBe("x23"); expect(x24).toBe("x24"); expect(x25).toBe("x25"); expect(x26).toBe("x26"); expect(x27).toBe("x27"); expect(x28).toBe("x28"); expect(x29).toBe("x29"); expect(x30).toBe("x30"); expect(x31).toBe("x31"); expect(x32).toBe("x32"); expect(x33).toBe("x33"); expect(x34).toBe("x34"); expect(x35).toBe("x35"); expect(x36).toBe("x36"); expect(x37).toBe("x37"); expect(x38).toBe("x38"); expect(x39).toBe("x39"); expect(x40).toBe("x40"); expect(x41).toBe("x41"); expect(x42).toBe("x42"); expect(x43).toBe("x43"); expect(x44).toBe("x44"); expect(x45).toBe("x45"); expect(x46).toBe("x46"); expect(x47).toBe("x47"); expect(x48).toBe("x48"); expect(x49).toBe("x49"); };
var CoreObject = require('core-object'); var SilentError = require('silent-error'); var PluginRegistry = require('./plugin-registry'); module.exports = CoreObject.extend({ init: function(project, ui, config) { this._super(); this._registry = new PluginRegistry(project, ui, config); this._config = config; this._project = project; if (this._isUsingOldPluginControl()) { if (this._isUsingNewPluginControl()) { var message = 'Use of the old and new plugin controls simultaneously does not make sense.\n' + 'Please use the new plugin controls\n' + 'See the following page for information:\n\n' + 'http://ember-cli-deploy.com/docs/v1.0.x/configuration/\n'; throw new SilentError(message); } else { ui.writeError('Use of the `config.plugins` property has been deprecated. Please use the new plugin run controls.'); ui.writeError('See the following page for information:\n'); ui.writeError('http://ember-cli-deploy.com/docs/v1.0.x/configuration/#advanced-plugin-configuration'); } } }, pluginInstances: function() { var addons = this._project.addons || []; var plugins = this._registry._plugins(addons); return this._config.plugins.map(function(entry) { var parts = entry.split(':'); var name = parts[0]; var alias = parts[1] || name; var addon = plugins[name]; if (addon) { return addon.createDeployPlugin({ name: alias }); } }, []) .filter(function(item) { return !!item; }); }, _isUsingOldPluginControl: function() { return this._config.plugins; }, _isUsingNewPluginControl: function() { var aliasConfig = Object.keys(this._registry._aliasConfig).length; var disabledConfig = Object.keys(this._registry._disabledConfig).length; var runOrderConfig = Object.keys(this._registry._runOrderConfig).length; return aliasConfig || disabledConfig || runOrderConfig; }, });
// Created by: Farukham: (https://github.com/farukham/Bootstrap-Animated-Progress-Bars) // Progress Bar var ProgressBar = function() { "use strict"; // Handle Progress Bar Horizontal var handleProgressBars = function() { $(document).ready(function() { $('.progress').each(function() { $(this).appear(function() { $(this).animate({ opacity: 1, left: "0px" }, 800); var w = $(this).find(".progress-bar").attr("data-width"); var h = $(this).find(".progress-bar").attr("data-height"); $(this).find(".progress-bar").animate({ width: w + "%", height: h + "%" }, 100, "linear"); }); }); }); } return { init: function() { handleProgressBars(); // initial setup for progressbars } } }(); $(document).ready(function() { ProgressBar.init(); });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pastefromword', 'gu', { confirmCleanup: 'તમે જે ટેક્ષ્ત્ કોપી કરી રહ્યા છો ટે વર્ડ ની છે. કોપી કરતા પેહલા સાફ કરવી છે?', error: 'પેસ્ટ કરેલો ડેટા ઇન્ટરનલ એરર ના લીથે સાફ કરી શકાયો નથી.', title: 'પેસ્ટ (વડૅ ટેક્સ્ટ)', toolbar: 'પેસ્ટ (વડૅ ટેક્સ્ટ)' });
version https://git-lfs.github.com/spec/v1 oid sha256:c6698a8288287cf30c479880dedaa4dc9505b4c547141d27cba4816efd5bf766 size 5021
/* * * * (c) 2010-2021 Sebastian Bochan * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); import ColumnSeries from '../Column/ColumnSeries.js'; var colProto = ColumnSeries.prototype; import SeriesRegistry from '../../Core/Series/SeriesRegistry.js'; import U from '../../Core/Utilities.js'; var clamp = U.clamp, extend = U.extend, merge = U.merge, pick = U.pick; /** * The ColumnPyramidSeries class * * @private * @class * @name Highcharts.seriesTypes.columnpyramid * * @augments Highcharts.Series */ var ColumnPyramidSeries = /** @class */ (function (_super) { __extends(ColumnPyramidSeries, _super); function ColumnPyramidSeries() { /* * * * Static properties * * */ var _this = _super !== null && _super.apply(this, arguments) || this; /* * * * Properties * * */ _this.data = void 0; _this.options = void 0; _this.points = void 0; return _this; } /* * * * Functions * * */ /* eslint-disable-next-line valid-jsdoc */ /** * Overrides the column translate method * @private */ ColumnPyramidSeries.prototype.translate = function () { var series = this, chart = series.chart, options = series.options, dense = series.dense = series.closestPointRange * series.xAxis.transA < 2, borderWidth = series.borderWidth = pick(options.borderWidth, dense ? 0 : 1 // #3635 ), yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, // postprocessed for border width seriesBarW = series.barW = Math.max(pointWidth, 1 + 2 * borderWidth), pointXOffset = series.pointXOffset = metrics.offset; if (chart.inverted) { translatedThreshold -= 0.5; // #3355 } // When the pointPadding is 0, // we want the pyramids to be packed tightly, // so we allow individual pyramids to have individual sizes. // When pointPadding is greater, // we strive for equal-width columns (#2694). if (options.pointPadding) { seriesBarW = Math.ceil(seriesBarW); } colProto.translate.apply(series); // Record the new values series.points.forEach(function (point) { var yBottom = pick(point.yBottom, translatedThreshold), safeDistance = 999 + Math.abs(yBottom), plotY = clamp(point.plotY, -safeDistance, yAxis.len + safeDistance), // Don't draw too far outside plot area // (#1303, #2241, #4264) barX = point.plotX + pointXOffset, barW = seriesBarW / 2, barY = Math.min(plotY, yBottom), barH = Math.max(plotY, yBottom) - barY, stackTotal, stackHeight, topPointY, topXwidth, bottomXwidth, invBarPos, x1, x2, x3, x4, y1, y2; point.barX = barX; point.pointWidth = pointWidth; // Fix the tooltip on center of grouped pyramids // (#1216, #424, #3648) point.tooltipPos = chart.inverted ? [ yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW, barH ] : [ barX + barW, plotY + yAxis.pos - chart.plotTop, barH ]; stackTotal = threshold + (point.total || point.y); // overwrite stacktotal (always 100 / -100) if (options.stacking === 'percent') { stackTotal = threshold + (point.y < 0) ? -100 : 100; } // get the highest point (if stack, extract from total) topPointY = yAxis.toPixels((stackTotal), true); // calculate height of stack (in pixels) stackHeight = chart.plotHeight - topPointY - (chart.plotHeight - translatedThreshold); // topXwidth and bottomXwidth = width of lines from the center // calculated from tanges proportion. // Can not be a NaN #12514 topXwidth = stackHeight ? (barW * (barY - topPointY)) / stackHeight : 0; // like topXwidth, but with height of point bottomXwidth = stackHeight ? (barW * (barY + barH - topPointY)) / stackHeight : 0; /* /\ / \ x1,y1,------ x2,y1 / \ ---------- x4,y2 x3,y2 */ x1 = barX - topXwidth + barW; x2 = barX + topXwidth + barW; x3 = barX + bottomXwidth + barW; x4 = barX - bottomXwidth + barW; y1 = barY - minPointLength; y2 = barY + barH; if (point.y < 0) { y1 = barY; y2 = barY + barH + minPointLength; } // inverted chart if (chart.inverted) { invBarPos = yAxis.width - barY; stackHeight = topPointY - (yAxis.width - translatedThreshold); // proportion tanges topXwidth = (barW * (topPointY - invBarPos)) / stackHeight; bottomXwidth = (barW * (topPointY - (invBarPos - barH))) / stackHeight; x1 = barX + barW + topXwidth; // top bottom x2 = x1 - 2 * topXwidth; // top top x3 = barX - bottomXwidth + barW; // bottom top x4 = barX + bottomXwidth + barW; // bottom bottom y1 = barY; y2 = barY + barH - minPointLength; if (point.y < 0) { y2 = barY + barH + minPointLength; } } // Register shape type and arguments to be used in drawPoints point.shapeType = 'path'; point.shapeArgs = { // args for datalabels positioning x: x1, y: y1, width: x2 - x1, height: barH, // path of pyramid d: [ ['M', x1, y1], ['L', x2, y1], ['L', x3, y2], ['L', x4, y2], ['Z'] ] }; }); }; /** * Column pyramid series display one pyramid per value along an X axis. * To display horizontal pyramids, set [chart.inverted](#chart.inverted) to * `true`. * * @sample {highcharts|highstock} highcharts/demo/column-pyramid/ * Column pyramid * @sample {highcharts|highstock} highcharts/plotoptions/columnpyramid-stacked/ * Column pyramid stacked * @sample {highcharts|highstock} highcharts/plotoptions/columnpyramid-inverted/ * Column pyramid inverted * * @extends plotOptions.column * @since 7.0.0 * @product highcharts highstock * @excluding boostThreshold, borderRadius, crisp, depth, edgeColor, * edgeWidth, groupZPadding, negativeColor, softThreshold, * threshold, zoneAxis, zones, boostBlending * @requires highcharts-more * @optionparent plotOptions.columnpyramid */ ColumnPyramidSeries.defaultOptions = merge(ColumnSeries.defaultOptions, { // Nothing here }); return ColumnPyramidSeries; }(ColumnSeries)); SeriesRegistry.registerSeriesType('columnpyramid', ColumnPyramidSeries); /* * * * Default export * * */ export default ColumnPyramidSeries; /* * * * API Options * * */ /** * A `columnpyramid` series. If the [type](#series.columnpyramid.type) option is * not specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.columnpyramid * @excluding connectEnds, connectNulls, dashStyle, dataParser, dataURL, * gapSize, gapUnit, linecap, lineWidth, marker, step, * boostThreshold, boostBlending * @product highcharts highstock * @requires highcharts-more * @apioption series.columnpyramid */ /** * @excluding halo, lineWidth, lineWidthPlus, marker * @product highcharts highstock * @apioption series.columnpyramid.states.hover */ /** * @excluding halo, lineWidth, lineWidthPlus, marker * @product highcharts highstock * @apioption series.columnpyramid.states.select */ /** * An array of data points for the series. For the `columnpyramid` series type, * points can be given in the following ways: * * 1. An array of numerical values. In this case, the numerical values will be * interpreted as `y` options. The `x` values will be automatically * calculated, either starting at 0 and incremented by 1, or from * `pointStart` and `pointInterval` given in the series options. If the axis * has categories, these will be used. Example: * ```js * data: [0, 5, 3, 5] * ``` * * 2. An array of arrays with 2 values. In this case, the values correspond to * `x,y`. If the first value is a string, it is applied as the name of the * point, and the `x` value is inferred. * ```js * data: [ * [0, 6], * [1, 2], * [2, 6] * ] * ``` * * 3. An array of objects with named values. The objects are point configuration * objects as seen below. If the total number of data points exceeds the * series' [turboThreshold](#series.columnpyramid.turboThreshold), this * option is not available. * ```js * data: [{ * x: 1, * y: 9, * name: "Point2", * color: "#00FF00" * }, { * x: 1, * y: 6, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @sample {highcharts} highcharts/chart/reflow-true/ * Numerical values * @sample {highcharts} highcharts/series/data-array-of-arrays/ * Arrays of numeric x and y * @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/ * Arrays of datetime x and y * @sample {highcharts} highcharts/series/data-array-of-name-value/ * Arrays of point.name and y * @sample {highcharts} highcharts/series/data-array-of-objects/ * Config objects * * @type {Array<number|Array<(number|string),(number|null)>|null|*>} * @extends series.line.data * @excluding marker * @product highcharts highstock * @apioption series.columnpyramid.data */ ''; // adds doclets above to transpiled file;
IntlMessageFormat.__addLocaleData({"locale":"ru"}); IntlMessageFormat.__addLocaleData({"locale":"ru-BY","parentLocale":"ru"}); IntlMessageFormat.__addLocaleData({"locale":"ru-KG","parentLocale":"ru"}); IntlMessageFormat.__addLocaleData({"locale":"ru-KZ","parentLocale":"ru"}); IntlMessageFormat.__addLocaleData({"locale":"ru-MD","parentLocale":"ru"}); IntlMessageFormat.__addLocaleData({"locale":"ru-UA","parentLocale":"ru"});
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports.ListBoxItem = void 0; var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _ClassNames = require("../utils/ClassNames"); var _DomHandler = _interopRequireDefault(require("../utils/DomHandler")); var _Ripple = require("../ripple/Ripple"); var _ObjectUtils = _interopRequireDefault(require("../utils/ObjectUtils")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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; } var ListBoxItem = /*#__PURE__*/function (_Component) { _inherits(ListBoxItem, _Component); var _super = _createSuper(ListBoxItem); function ListBoxItem(props) { var _this; _classCallCheck(this, ListBoxItem); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(ListBoxItem, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, option: this.props.option }); } event.preventDefault(); } }, { key: "onTouchEnd", value: function onTouchEnd(event) { if (this.props.onTouchEnd) { this.props.onTouchEnd({ originalEvent: event, option: this.props.option }); } } }, { key: "onKeyDown", value: function onKeyDown(event) { var item = event.currentTarget; switch (event.which) { //down case 40: var nextItem = this.findNextItem(item); if (nextItem) { nextItem.focus(); } event.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(item); if (prevItem) { prevItem.focus(); } event.preventDefault(); break; //enter case 13: this.onClick(event); event.preventDefault(); break; default: break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return _DomHandler.default.hasClass(nextItem, 'p-disabled') || _DomHandler.default.hasClass(nextItem, 'p-listbox-item-group') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return _DomHandler.default.hasClass(prevItem, 'p-disabled') || _DomHandler.default.hasClass(prevItem, 'p-listbox-item-group') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "render", value: function render() { var className = (0, _ClassNames.classNames)('p-listbox-item', { 'p-highlight': this.props.selected, 'p-disabled': this.props.disabled }, this.props.option.className); var content = this.props.template ? _ObjectUtils.default.getJSXElement(this.props.template, this.props.option) : this.props.label; return /*#__PURE__*/_react.default.createElement("li", { className: className, onClick: this.onClick, onTouchEnd: this.onTouchEnd, onKeyDown: this.onKeyDown, tabIndex: this.props.tabIndex, "aria-label": this.props.label, key: this.props.label, role: "option", "aria-selected": this.props.selected }, content, /*#__PURE__*/_react.default.createElement(_Ripple.Ripple, null)); } }]); return ListBoxItem; }(_react.Component); exports.ListBoxItem = ListBoxItem; _defineProperty(ListBoxItem, "defaultProps", { option: null, label: null, selected: false, disabled: false, tabIndex: null, onClick: null, onTouchEnd: null, template: null }); _defineProperty(ListBoxItem, "propTypes", { option: _propTypes.default.any, label: _propTypes.default.string, selected: _propTypes.default.bool, disabled: _propTypes.default.bool, tabIndex: _propTypes.default.number, onClick: _propTypes.default.func, onTouchEnd: _propTypes.default.func, template: _propTypes.default.any });
const merge = require('webpack-merge') const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin const base = require('./webpack.config.base') const { resolve } = require('path') const { vueLoaders } = require('./utils') module.exports = merge(base, { output: { libraryTarget: 'commonjs2' }, target: 'node', module: { rules: [ { test: /.scss$/, use: vueLoaders.scss, include: [ resolve(__dirname, '../node_modules/@material'), resolve(__dirname, '../src') ] } ] }, plugins: [ new BundleAnalyzerPlugin({ analyzerMode: 'static', openAnalyzer: false, reportFilename: resolve(__dirname, `../reports/${process.env.NODE_ENV}.html`) }) ] })
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.1.2.4_A2.1; * @section: 15.1.2.4, 15.2.4.7, 12.6.4; * @assertion: The length property of isNaN has the attribute DontEnum; * @description: Checking use propertyIsEnumerable, for-in; */ //CHECK#1 if (isNaN.propertyIsEnumerable('length') !== false) { $ERROR('#1: isNaN.propertyIsEnumerable(\'length\') === false. Actual: ' + (isNaN.propertyIsEnumerable('length'))); } //CHECK#2 result = true; for (p in isNaN){ if (p === "length") { result = false; } } if (result !== true) { $ERROR('#2: result = true; for (p in isNaN) { if (p === "length") result = false; } result === true;'); }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var AvFiberSmartRecord = function AvFiberSmartRecord(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement( 'g', null, _react2.default.createElement('circle', { cx: '9', cy: '12', r: '8' }), _react2.default.createElement('path', { d: 'M17 4.26v2.09c2.33.82 4 3.04 4 5.65s-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74s-2.55-6.85-6-7.74z' }) ) ); }; AvFiberSmartRecord = (0, _pure2.default)(AvFiberSmartRecord); AvFiberSmartRecord.displayName = 'AvFiberSmartRecord'; exports.default = AvFiberSmartRecord;