code
stringlengths
2
1.05M
const path = require('path'); module.exports = { "appenders": [ //always print in console { "type": "console" }, //http error { "type": "dateFile", "pattern": "-yyyy-MM-dd", "filename": path.join(__dirname, '../../log/error/httpError/http-error-log.log'), "category": ['httpError'], "alwaysIncludePattern": true, "level": "ERROR" }, //server error { "type": "dateFile", "filename": path.join(__dirname, '../../log/error/serverError/server-error-log.log'), "pattern": "-yyyy-MM-dd", "category": ['serverError'], "alwaysIncludePattern": true, "level": "ERROR" }, //http-info { "type": "dateFile", "filename": path.join(__dirname, '../../log/info/http-info/http-info-log.log'), "pattern": "-yyyy-MM-dd", "category": ['httpInfo'], "alwaysIncludePattern": true, "level": "info" }, //server-info { "type": "dateFile", "filename": path.join(__dirname, '../../log/info/server-info/server-info-log.log'), "pattern": "-yyyy-MM-dd", "category": ['serverInfo'], "alwaysIncludePattern": true, "level": "info" }, //error handle { "type": "logLevelFilter", "level": "ERROR", "appender": { "type": "file", "filename": path.join(__dirname, '../../log/error.all.log') } } ], replaceConsole: true };
// ========================================================================== // Project: Ember Runtime // Copyright: ©2006-2011 Strobe Inc. and contributors. // ©2008-2011 Apple Inc. All rights reserved. // License: Licensed under MIT license (see license.js) // ========================================================================== module('Ember.String.decamelize'); test("does nothing with normal string", function() { deepEqual(Ember.String.decamelize('my favorite items'), 'my favorite items'); if (Ember.EXTEND_PROTOTYPES) { deepEqual('my favorite items'.decamelize(), 'my favorite items'); } }); test("does nothing with dasherized string", function() { deepEqual(Ember.String.decamelize('css-class-name'), 'css-class-name'); if (Ember.EXTEND_PROTOTYPES) { deepEqual('css-class-name'.decamelize(), 'css-class-name'); } }); test("does nothing with underscored string", function() { deepEqual(Ember.String.decamelize('action_name'), 'action_name'); if (Ember.EXTEND_PROTOTYPES) { deepEqual('action_name'.decamelize(), 'action_name'); } }); test("converts a camelized string into all lower case separated by underscores.", function() { deepEqual(Ember.String.decamelize('innerHTML'), 'inner_html'); if (Ember.EXTEND_PROTOTYPES) { deepEqual('innerHTML'.decamelize(), 'inner_html'); } });
import { connect as redisConnection } from '../config/database' import { connect as postgresConnection } from '../config/postgres' import { load as configLoader } from '../config/config' import { DbAdapter } from './support/DbAdapter' import { PubSubAdapter } from './support/PubSubAdapter' import pubSub from './pubsub' import pubSubStub from './pubsub-stub' import { addModel as attachmentModel } from './models/attachment' import { addModel as commentModel } from './models/comment' import { addModel as groupModel } from './models/group' import { addModel as postModel } from './models/post' import { addModel as timelineModel } from './models/timeline' import { addModel as userModel } from './models/user' import { addSerializer as adminSerializer } from './serializers/v1/AdminSerializer' import { addSerializer as attachmentSerializer } from './serializers/v1/AttachmentSerializer' import { addSerializer as commentSerializer } from './serializers/v1/CommentSerializer' import { addSerializer as groupSerializer } from './serializers/v1/GroupSerializer' import { addSerializer as likeSerializer } from './serializers/v1/LikeSerializer' import { addSerializer as myProfileSerializer } from './serializers/v1/MyProfileSerializer' import { addSerializer as postSerializer } from './serializers/v1/PostSerializer' import { addSerializer as pubsubCommentSerializer } from './serializers/v1/PubsubCommentSerializer' import { addSerializer as subscriberSerializer } from './serializers/v1/SubscriberSerializer' import { addSerializer as subscriptionSerializer } from './serializers/v1/SubscriptionSerializer' import { addSerializer as subscriptionRequestSerializer } from './serializers/v1/SubscriptionRequestSerializer' import { addSerializer as timelineSerializer } from './serializers/v1/TimelineSerializer' import { addSerializer as userSerializer } from './serializers/v1/UserSerializer' // Be careful: order of exports is important. export const postgres = postgresConnection() export const dbAdapter = new DbAdapter(postgres) export { AbstractSerializer } from './serializers/abstract_serializer' export { Serializer } from './serializers/serializer' const config = configLoader() export let PubSub; if (config.disableRealtime) { PubSub = new pubSubStub() } else { const database = redisConnection() const pubsubAdapter = new PubSubAdapter(database) PubSub = new pubSub(pubsubAdapter) } export const User = userModel(dbAdapter) export const Group = groupModel(dbAdapter) export const Post = postModel(dbAdapter) export const Timeline = timelineModel(dbAdapter) export const Attachment = attachmentModel(dbAdapter) export const Comment = commentModel(dbAdapter) export const AdminSerializer = adminSerializer() export const UserSerializer = userSerializer() export const SubscriberSerializer = subscriberSerializer() export const SubscriptionSerializer = subscriptionSerializer() export const SubscriptionRequestSerializer = subscriptionRequestSerializer() export const MyProfileSerializer = myProfileSerializer() export const LikeSerializer = likeSerializer() export const GroupSerializer = groupSerializer() export const AttachmentSerializer = attachmentSerializer() export const CommentSerializer = commentSerializer() export const PubsubCommentSerializer = pubsubCommentSerializer() export const PostSerializer = postSerializer() export const TimelineSerializer = timelineSerializer()
System.register(['angular2/platform/browser', './app.component', 'angular2/http'], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var browser_1, app_component_1, http_1; return { setters:[ function (browser_1_1) { browser_1 = browser_1_1; }, function (app_component_1_1) { app_component_1 = app_component_1_1; }, function (http_1_1) { http_1 = http_1_1; }], execute: function() { browser_1.bootstrap(app_component_1.AppComponent, [http_1.HTTP_PROVIDERS]); } } }); //# sourceMappingURL=main.js.map
'use strict'; var connect = require('readable-lists-api'); var ms = require('ms'); var run = require('./lib/run-bot.js'); var readers = {}; readers.pipermail = require('./lib/readers/pipermail'); readers.w3c = require('./lib/readers/w3c'); readers.w3 = require('./lib/readers/w3c'); // currently these can be read by the same adapter, this may change in the future var db = connect(process.env.DATABASE, process.env.BUCKET); var log = []; var lastStart; for (var i = 0; i < 50; i++) { log.push(''); } function time() { return (new Date()).toISOString(); } function onList(list) { log.shift(); log.push(time() + ' ' + list.source); } function onError(err) { log.shift(); log.push(time() + ' ' + ((err.stack || err) + '').replace(/\n/g, "\n ")); console.error(err.stack || err); } function runBot() { lastStart = time(); db.getLists().then(function (lists) { function next() { if (lists.length === 0) return; var list = lists.pop(); onList(list); var source = new readers[list.type](list._id, list.source); return run(source, db, { parallel: process.env.PARALLEL ? +process.env.PARALLEL : 50 }).then(null, onError).then(next); } return next(); }).then(null, onError).done(runBot); } runBot(); var http = require('http') http.createServer(function (req, res) { var status = 200; if (Date.now() - (new Date(lastStart)).getTime() > ms('120 minutes')) { status = 503 onError('Timeout triggering restart'); setTimeout(function () { // allow time for the error to be logged process.exit(1); }, 500); } res.writeHead(status, {'Content-Type': 'text/plain'}) var warning = status === 503 ? 'WARNING: server behind on processing\n\n' : '' res.end(warning + 'last-start: ' + lastStart + '\n' + 'current-time: ' + (new Date()).toISOString() + '\n\nLogs:\n\n' + log.filter(Boolean).join('\n')); }).listen(process.env.PORT || 3000); console.log('Server running at http://localhost:' + (process.env.PORT || 3000));
'use strict'; module.exports = { moduleType: 'locale', name: 'fo', dictionary: {}, format: { days: [ 'Sunnudagur', 'Mánadagur', 'Týsdagur', 'Mikudagur', 'Hósdagur', 'Fríggjadagur', 'Leyardagur' ], shortDays: ['Sun', 'Mán', 'Týs', 'Mik', 'Hós', 'Frí', 'Ley'], months: [ 'Januar', 'Februar', 'Mars', 'Apríl', 'Mei', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Desember' ], shortMonths: [ 'Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des' ], date: '%d-%m-%Y' } };
initSidebarItems({"enum":[["DefIdSource",""]],"fn":[["parse_bare_fn_ty_data",""],["parse_bounds_data",""],["parse_builtin_bounds_data",""],["parse_def_id",""],["parse_existential_bounds_data",""],["parse_ident",""],["parse_name",""],["parse_predicate",""],["parse_predicate_data",""],["parse_region_data",""],["parse_state_from_data",""],["parse_substs_data",""],["parse_trait_ref_data",""],["parse_ty_closure_data",""],["parse_ty_data",""],["parse_type_param_def_data",""]],"struct":[["PState",""]]});
var FontRendererPath = (function () { var CanvasRenderer = require('fontpath-canvas'); var FontLib = require('font-lib'); /* Font proxy for CanvasRenderer * Get font data from freetype directly instead of creating whole font json file */ var DynamicFontProxy = function (nativeFont, size) { nativeFont.setSize(size); this.font = nativeFont; this.size = size; // actually, size is the font pt, but we use it as px. this.resolution = 72; this.kerning = []; this.exporter = 'dynamicFontProxy'; this.version = '0.0.1'; this.glyphs = {}; //['underline_thickness', 'underline_position', 'max_advance_width','height','descender', // 'ascender','units_per_EM','style_name','family_name'].forEach(function (field) { // this[field] = font[field]; // not worked, operator [] can not lookup values from base type //}); this.underline_thickness = nativeFont.underline_thickness; this.underline_position = nativeFont.underline_position; this.max_advance_width = nativeFont.max_advance_width; this.height = nativeFont.height; this.descender = nativeFont.descender; this.ascender = nativeFont.ascender; this.units_per_EM = nativeFont.units_per_EM; this.style_name = nativeFont.style_name; this.family_name = nativeFont.family_name; }; DynamicFontProxy.prototype.requestCharacterGlyph = function (char) { char = char[0]; var glyph = this.glyphs[char]; if (!glyph) { this.font.loadChar(char, FontLib.FT.LOAD_NO_BITMAP/* | FontLib.FT.LOAD_NO_HINTING*/); var metrics = this.font.glyph.metrics; this.glyphs[char] = { xoff: metrics.horiAdvance, width: metrics.width, height: metrics.height, hbx: metrics.horiBearingX, hby: metrics.horiBearingY, path: DynamicFontProxy._getGlyphOutline(FontLib.FT, this.font, char), }; } return glyph; }; DynamicFontProxy._getGlyphOutline = function(ft, face, code) { // copied from https://github.com/mattdesl/fontpath/blob/master/lib/SimpleJson.js if (face.glyph.format !== ft.GLYPH_FORMAT_OUTLINE) { console.warn("Charcode", code, "(" + String.fromCharCode(code) + ") has no outline"); return []; } var data = []; ft.Outline_Decompose(face, { move_to: function (x, y) { data.push(["m", x, y]); }, line_to: function (x, y) { data.push(["l", x, y]); }, quad_to: function (cx, cy, x, y) { data.push(["q", cx, cy, x, y]); }, cubic_to: function (cx1, cy1, cx2, cy2, x, y) { data.push(["c", cx1, cy1, cx2, cy2, x, y]); }, }); return data; }; /* The font renderer */ function FontRendererPath (fontInfo, nativeFont) { // strokeJoin如果是miter,不论miterLimit设成多少,有些字体都无法完美描边每个字符, // 所以这里限制只有一定宽度以下才能使用miter var forceRoundCapWidth = 1; this.nativeRenderer = new CanvasRenderer(); this.nativeRenderer.font = new DynamicFontProxy(nativeFont, fontInfo.fontSize); this.nativeRenderer.fontSize = fontInfo.fontSize; this.nativeRenderer.align = CanvasRenderer.Align.LEFT; this.fontInfo = fontInfo; // workaround incorrect miter stroke this.strokeJoin = fontInfo.strokeJoin; if (fontInfo.strokeJoin !== 'round' && fontInfo.strokeWidth > forceRoundCapWidth) { this.strokeJoin = 'round'; } // adjust style this.strokeColor = PaperUtils.color(fontInfo.strokeColor); this.fillColor = PaperUtils.color(fontInfo.fillColor); this.shadowColor = PaperUtils.color(fontInfo.shadowColor); this.shadowOffset = PaperUtils.point(fontInfo.shadowOffset); this.strokeWidth = fontInfo.strokeWidth * 2; this.shadowBlur = fontInfo.shadowBlur; this.miterLimit = fontInfo.miterLimit; if (_hasOutline(this)) { // ristrict fill alpha,由于外描边其实是用双倍的居中描边模拟出来的,所以必须把内描边用填充完全遮住 this.fillColor.alpha = 1; } _caculateBounds(this); } var _applyFillStyle = function (ctx, renderer) { ctx.fillStyle = renderer.fillColor.toCanvasStyle(ctx); //ctx.lineWidth = 0; //ctx.strokeStyle = 'rgba(0,0,0,0)'; }; var _applyShadowStyle = function (ctx, renderer) { ctx.shadowOffsetX = renderer.shadowOffset.x; ctx.shadowOffsetY = renderer.shadowOffset.y; ctx.shadowBlur = renderer.shadowBlur; ctx.shadowColor = renderer.shadowColor.toCanvasStyle(ctx); }; var _clearShadowStyle = function (ctx) { ctx.shadowOffsetX = 0; ctx.shadowOffsetY = 0; ctx.shadowBlur = 0; ctx.shadowColor = null; }; var _applyOutlineStyle = function (ctx, renderer) { ctx.strokeStyle = renderer.strokeColor.toCanvasStyle(ctx); ctx.lineWidth = renderer.strokeWidth; ctx.lineJoin = renderer.strokeJoin; if (ctx.lineJoin === 'round') { ctx.lineCap = 'round'; } else { ctx.lineCap = 'square'; } ctx.miterLimit = renderer.miterLimit; /*var dashArray = renderer.dashArray; if (dashArray && dashArray.length) { if ('setLineDash' in ctx) { ctx.setLineDash(dashArray); ctx.lineDashOffset = renderer.dashOffset; } else { ctx.mozDash = dashArray; ctx.mozDashOffset = renderer.dashOffset; } }*/ }; var _hasOutline = function ( renderer ) { return (!renderer.strokeColor.hasAlpha() || renderer.strokeColor.alpha > 0) && renderer.strokeWidth > 0; }; var _caculateBounds = function ( renderer ) { var expandLeft = Math.max(renderer.shadowBlur - renderer.shadowOffset.x, 0) + renderer.strokeWidth; var expandRight = Math.max(renderer.shadowBlur + renderer.shadowOffset.x, 0) + renderer.strokeWidth; var expandTop = Math.max(renderer.shadowBlur - renderer.shadowOffset.y, 0) + renderer.strokeWidth; var expandBottom = Math.max(renderer.shadowBlur + renderer.shadowOffset.y, 0) + renderer.strokeWidth; renderer.expandWidth = expandLeft + expandRight; var expandHeight = expandTop + expandBottom; var font = renderer.nativeRenderer.font; // caculate pixel manually, because CanvasRenderer uses pt, but we use px. var pixelHeight = font.height / font.units_per_EM * renderer.nativeRenderer.fontSize; var pixelAscender = font.ascender / font.units_per_EM * renderer.nativeRenderer.fontSize; renderer.x = expandLeft; renderer.y = pixelAscender + expandTop; renderer.height = pixelHeight + expandHeight; /* // 画布需要外扩一个像素,否则放大后边缘如果有像素做线性插值时会有锯齿,不过这会对xyoffset有影响。 var padding = 1; renderer.x += padding; renderer.y += padding; renderer.height += (padding * 2); renderer.expandWidth += (padding * 2);*/ }; FontRendererPath.prototype.render = function (char) { // new canvas for draw var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var style = this.style; var nativeRenderer = this.nativeRenderer; // setup renderer nativeRenderer.font.requestCharacterGlyph(char); // actually load glyph nativeRenderer.text = char; // setup canvas var bounds = nativeRenderer.getBounds(); if (bounds.width === 0 || bounds.height === 0) { return null; } canvas.width = bounds.width + this.expandWidth; canvas.height = this.height; //ctx.fillStyle = 'rgb(50,128,50)'; //ctx.fillRect(0, 0, canvas.width, canvas.height); // draw text with shadow _applyShadowStyle(ctx, this); _applyFillStyle(ctx, this); nativeRenderer.fill(ctx, this.x, this.y); if (_hasOutline(this)) { // draw outline with shadow _applyOutlineStyle(ctx, this); nativeRenderer.stroke(ctx, this.x, this.y); // redraw text _clearShadowStyle(ctx); nativeRenderer.fill(ctx, this.x, this.y); } // NOTE: canvas is faster than image since we skip one time png convert // create image // var img = document.createElement('img'); // img.src = canvas.toDataURL('image/png'); return canvas; }; return FontRendererPath; })();
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.QualitativeRange = undefined; var _dec, _dec2, _dec3, _class; var _constants = require('../common/constants'); var _decorators = require('../common/decorators'); var _common = require('../common/common'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var QualitativeRange = exports.QualitativeRange = (_dec = (0, _common.inlineView)('' + _constants.constants.aureliaTemplateString), _dec2 = (0, _common.customElement)(_constants.constants.elementPrefix + 'qualitative-range'), _dec3 = (0, _decorators.generateBindables)('qualitativeRanges', ['rangeEnd', 'rangeOpacity', 'rangeStroke']), _dec(_class = _dec2(_class = _dec3(_class = function QualitativeRange() { _classCallCheck(this, QualitativeRange); }) || _class) || _class) || _class);
/* eslint-disable no-useless-escape */ export default function syntaxHighlight(json) { const regExp = /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g return json.replace(regExp, match => { var style = `color: #1177cd` if (/^"/.test(match)) { if (/:$/.test(match)) { style = `color: #8dc379;` } else { style = `color: #c178dd` } } else if (/true|false/.test(match)) { style = 'color: #cb9a66' } else if (/null/.test(match)) { style = `color: #d19a66` } return `<span style="${style}">${match}</span>` }) }
// Compiled by ClojureScript 0.0-2311 goog.provide('cljs.core.async.impl.timers'); goog.require('cljs.core'); goog.require('cljs.core.async.impl.dispatch'); goog.require('cljs.core.async.impl.dispatch'); goog.require('cljs.core.async.impl.channels'); goog.require('cljs.core.async.impl.channels'); goog.require('cljs.core.async.impl.protocols'); goog.require('cljs.core.async.impl.protocols'); cljs.core.async.impl.timers.MAX_LEVEL = (15); cljs.core.async.impl.timers.P = ((1) / (2)); cljs.core.async.impl.timers.random_level = (function() { var random_level = null; var random_level__0 = (function (){return random_level.call(null,(0)); }); var random_level__1 = (function (level){while(true){ if(((Math.random() < cljs.core.async.impl.timers.P)) && ((level < cljs.core.async.impl.timers.MAX_LEVEL))) {{ var G__19361 = (level + (1)); level = G__19361; continue; } } else {return level; } break; } }); random_level = function(level){ switch(arguments.length){ case 0: return random_level__0.call(this); case 1: return random_level__1.call(this,level); } throw(new Error('Invalid arity: ' + arguments.length)); }; random_level.cljs$core$IFn$_invoke$arity$0 = random_level__0; random_level.cljs$core$IFn$_invoke$arity$1 = random_level__1; return random_level; })() ; /** * @constructor */ cljs.core.async.impl.timers.SkipListNode = (function (key,val,forward){ this.key = key; this.val = val; this.forward = forward; this.cljs$lang$protocol_mask$partition1$ = 0; this.cljs$lang$protocol_mask$partition0$ = 2155872256; }) cljs.core.async.impl.timers.SkipListNode.cljs$lang$type = true; cljs.core.async.impl.timers.SkipListNode.cljs$lang$ctorStr = "cljs.core.async.impl.timers/SkipListNode"; cljs.core.async.impl.timers.SkipListNode.cljs$lang$ctorPrWriter = (function (this__11961__auto__,writer__11962__auto__,opt__11963__auto__){return cljs.core._write.call(null,writer__11962__auto__,"cljs.core.async.impl.timers/SkipListNode"); }); cljs.core.async.impl.timers.SkipListNode.prototype.cljs$core$IPrintWithWriter$_pr_writer$arity$3 = (function (coll,writer,opts){var self__ = this; var coll__$1 = this;return cljs.core.pr_sequential_writer.call(null,writer,cljs.core.pr_writer,"["," ","]",opts,coll__$1); }); cljs.core.async.impl.timers.SkipListNode.prototype.cljs$core$ISeqable$_seq$arity$1 = (function (coll){var self__ = this; var coll__$1 = this;return cljs.core._conj.call(null,cljs.core._conj.call(null,cljs.core.List.EMPTY,self__.val),self__.key); }); cljs.core.async.impl.timers.__GT_SkipListNode = (function __GT_SkipListNode(key,val,forward){return (new cljs.core.async.impl.timers.SkipListNode(key,val,forward)); }); cljs.core.async.impl.timers.skip_list_node = (function() { var skip_list_node = null; var skip_list_node__1 = (function (level){return skip_list_node.call(null,null,null,level); }); var skip_list_node__3 = (function (k,v,level){var arr = (new Array((level + (1))));var i_19362 = (0);while(true){ if((i_19362 < arr.length)) {(arr[i_19362] = null); { var G__19363 = (i_19362 + (1)); i_19362 = G__19363; continue; } } else {} break; } return (new cljs.core.async.impl.timers.SkipListNode(k,v,arr)); }); skip_list_node = function(k,v,level){ switch(arguments.length){ case 1: return skip_list_node__1.call(this,k); case 3: return skip_list_node__3.call(this,k,v,level); } throw(new Error('Invalid arity: ' + arguments.length)); }; skip_list_node.cljs$core$IFn$_invoke$arity$1 = skip_list_node__1; skip_list_node.cljs$core$IFn$_invoke$arity$3 = skip_list_node__3; return skip_list_node; })() ; cljs.core.async.impl.timers.least_greater_node = (function() { var least_greater_node = null; var least_greater_node__3 = (function (x,k,level){return least_greater_node.call(null,x,k,level,null); }); var least_greater_node__4 = (function (x,k,level,update){while(true){ if(!((level < (0)))) {var x__$1 = (function (){var x__$1 = x;while(true){ var temp__4217__auto__ = (x__$1.forward[level]);if(cljs.core.truth_(temp__4217__auto__)) {var x_SINGLEQUOTE_ = temp__4217__auto__;if((x_SINGLEQUOTE_.key < k)) {{ var G__19364 = x_SINGLEQUOTE_; x__$1 = G__19364; continue; } } else {return x__$1; } } else {return x__$1; } break; } })();if((update == null)) {} else {(update[level] = x__$1); } { var G__19365 = x__$1; var G__19366 = k; var G__19367 = (level - (1)); var G__19368 = update; x = G__19365; k = G__19366; level = G__19367; update = G__19368; continue; } } else {return x; } break; } }); least_greater_node = function(x,k,level,update){ switch(arguments.length){ case 3: return least_greater_node__3.call(this,x,k,level); case 4: return least_greater_node__4.call(this,x,k,level,update); } throw(new Error('Invalid arity: ' + arguments.length)); }; least_greater_node.cljs$core$IFn$_invoke$arity$3 = least_greater_node__3; least_greater_node.cljs$core$IFn$_invoke$arity$4 = least_greater_node__4; return least_greater_node; })() ; /** * @constructor */ cljs.core.async.impl.timers.SkipList = (function (header,level){ this.header = header; this.level = level; this.cljs$lang$protocol_mask$partition1$ = 0; this.cljs$lang$protocol_mask$partition0$ = 2155872256; }) cljs.core.async.impl.timers.SkipList.cljs$lang$type = true; cljs.core.async.impl.timers.SkipList.cljs$lang$ctorStr = "cljs.core.async.impl.timers/SkipList"; cljs.core.async.impl.timers.SkipList.cljs$lang$ctorPrWriter = (function (this__11961__auto__,writer__11962__auto__,opt__11963__auto__){return cljs.core._write.call(null,writer__11962__auto__,"cljs.core.async.impl.timers/SkipList"); }); cljs.core.async.impl.timers.SkipList.prototype.cljs$core$IPrintWithWriter$_pr_writer$arity$3 = (function (coll,writer,opts){var self__ = this; var coll__$1 = this;var pr_pair = ((function (coll__$1){ return (function (keyval){return cljs.core.pr_sequential_writer.call(null,writer,cljs.core.pr_writer,""," ","",opts,keyval); });})(coll__$1)) ;return cljs.core.pr_sequential_writer.call(null,writer,pr_pair,"{",", ","}",opts,coll__$1); }); cljs.core.async.impl.timers.SkipList.prototype.cljs$core$ISeqable$_seq$arity$1 = (function (coll){var self__ = this; var coll__$1 = this;var iter = ((function (coll__$1){ return (function iter(node){return (new cljs.core.LazySeq(null,((function (coll__$1){ return (function (){if((node == null)) {return null; } else {return cljs.core.cons.call(null,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [node.key,node.val], null),iter.call(null,(node.forward[(0)]))); } });})(coll__$1)) ,null,null)); });})(coll__$1)) ; return iter.call(null,(self__.header.forward[(0)])); }); cljs.core.async.impl.timers.SkipList.prototype.put = (function (k,v){var self__ = this; var coll = this;var update = (new Array(cljs.core.async.impl.timers.MAX_LEVEL));var x = cljs.core.async.impl.timers.least_greater_node.call(null,self__.header,k,self__.level,update);var x__$1 = (x.forward[(0)]);if((!((x__$1 == null))) && ((x__$1.key === k))) {return x__$1.val = v; } else {var new_level = cljs.core.async.impl.timers.random_level.call(null);if((new_level > self__.level)) {var i_19369 = (self__.level + (1));while(true){ if((i_19369 <= (new_level + (1)))) {(update[i_19369] = self__.header); { var G__19370 = (i_19369 + (1)); i_19369 = G__19370; continue; } } else {} break; } self__.level = new_level; } else {} var x__$2 = cljs.core.async.impl.timers.skip_list_node.call(null,k,v,(new Array(new_level)));var i = (0);while(true){ if((i <= self__.level)) {var links = (update[i]).forward;(x__$2.forward[i] = (links[i])); return (links[i] = x__$2); } else {return null; } break; } } }); cljs.core.async.impl.timers.SkipList.prototype.remove = (function (k){var self__ = this; var coll = this;var update = (new Array(cljs.core.async.impl.timers.MAX_LEVEL));var x = cljs.core.async.impl.timers.least_greater_node.call(null,self__.header,k,self__.level,update);var x__$1 = (x.forward[(0)]);if((!((x__$1 == null))) && ((x__$1.key === k))) {var i_19371 = (0);while(true){ if((i_19371 <= self__.level)) {var links_19372 = (update[i_19371]).forward;if(((links_19372[i_19371]) === x__$1)) {(links_19372[i_19371] = (x__$1.forward[i_19371])); { var G__19373 = (i_19371 + (1)); i_19371 = G__19373; continue; } } else {{ var G__19374 = (i_19371 + (1)); i_19371 = G__19374; continue; } } } else {} break; } while(true){ if(((self__.level > (0))) && (((self__.header.forward[self__.level]) == null))) {self__.level = (self__.level - (1)); { continue; } } else {return null; } break; } } else {return null; } }); cljs.core.async.impl.timers.SkipList.prototype.ceilingEntry = (function (k){var self__ = this; var coll = this;var x = self__.header;var level__$1 = self__.level;while(true){ if(!((level__$1 < (0)))) {var nx = (function (){var x__$1 = x;while(true){ var x_SINGLEQUOTE_ = (x__$1.forward[level__$1]);if((x_SINGLEQUOTE_ == null)) {return null; } else {if((x_SINGLEQUOTE_.key >= k)) {return x_SINGLEQUOTE_; } else {{ var G__19375 = x_SINGLEQUOTE_; x__$1 = G__19375; continue; } } } break; } })();if(!((nx == null))) {{ var G__19376 = nx; var G__19377 = (level__$1 - (1)); x = G__19376; level__$1 = G__19377; continue; } } else {{ var G__19378 = x; var G__19379 = (level__$1 - (1)); x = G__19378; level__$1 = G__19379; continue; } } } else {if((x === self__.header)) {return null; } else {return x; } } break; } }); cljs.core.async.impl.timers.SkipList.prototype.floorEntry = (function (k){var self__ = this; var coll = this;var x = self__.header;var level__$1 = self__.level;while(true){ if(!((level__$1 < (0)))) {var nx = (function (){var x__$1 = x;while(true){ var x_SINGLEQUOTE_ = (x__$1.forward[level__$1]);if(!((x_SINGLEQUOTE_ == null))) {if((x_SINGLEQUOTE_.key > k)) {return x__$1; } else {{ var G__19380 = x_SINGLEQUOTE_; x__$1 = G__19380; continue; } } } else {if((level__$1 === (0))) {return x__$1; } else {return null; } } break; } })();if(cljs.core.truth_(nx)) {{ var G__19381 = nx; var G__19382 = (level__$1 - (1)); x = G__19381; level__$1 = G__19382; continue; } } else {{ var G__19383 = x; var G__19384 = (level__$1 - (1)); x = G__19383; level__$1 = G__19384; continue; } } } else {if((x === self__.header)) {return null; } else {return x; } } break; } }); cljs.core.async.impl.timers.__GT_SkipList = (function __GT_SkipList(header,level){return (new cljs.core.async.impl.timers.SkipList(header,level)); }); cljs.core.async.impl.timers.skip_list = (function skip_list(){return (new cljs.core.async.impl.timers.SkipList(cljs.core.async.impl.timers.skip_list_node.call(null,(0)),(0))); }); cljs.core.async.impl.timers.timeouts_map = cljs.core.async.impl.timers.skip_list.call(null); cljs.core.async.impl.timers.TIMEOUT_RESOLUTION_MS = (10); /** * returns a channel that will close after msecs */ cljs.core.async.impl.timers.timeout = (function timeout(msecs){var timeout__$1 = ((new Date()).valueOf() + msecs);var me = cljs.core.async.impl.timers.timeouts_map.ceilingEntry(timeout__$1);var or__11394__auto__ = (cljs.core.truth_((function (){var and__11382__auto__ = me;if(cljs.core.truth_(and__11382__auto__)) {return (me.key < (timeout__$1 + cljs.core.async.impl.timers.TIMEOUT_RESOLUTION_MS)); } else {return and__11382__auto__; } })())?me.val:null);if(cljs.core.truth_(or__11394__auto__)) {return or__11394__auto__; } else {var timeout_channel = cljs.core.async.impl.channels.chan.call(null,null);cljs.core.async.impl.timers.timeouts_map.put(timeout__$1,timeout_channel); cljs.core.async.impl.dispatch.queue_delay.call(null,((function (timeout_channel,or__11394__auto__,timeout__$1,me){ return (function (){cljs.core.async.impl.timers.timeouts_map.remove(timeout__$1); return cljs.core.async.impl.protocols.close_BANG_.call(null,timeout_channel); });})(timeout_channel,or__11394__auto__,timeout__$1,me)) ,msecs); return timeout_channel; } }); //# sourceMappingURL=timers.js.map
import React, { Component } from 'react' import PropTypes from 'prop-types' import { spec, check, match, prefixMatch } from 'ultra' import { Use } from 'react-ultra' function pipe(...fns) { function invoke(v) { return fns.reduce((acc, fn) => (fn ? fn.call(this, acc) : acc), v) } return invoke } let createMatch = (select, mountPath) => { let transform = ({ values: [x] }) => ({ x }) return [prefixMatch(mountPath, match(spec('/:x')(pipe(transform, select))))] } class App extends Component { constructor(props, ctx) { super(props, ctx) App.mountPath = props.mountPath this.state = { x: 1, tap: false } this.navigate = this.navigate.bind(this) this.matchers = createMatch(this.setState.bind(this), App.mountPath) } get ultra() { return this.context.getUltra() } get nextLink() { return `${App.mountPath}/${+this.state.x + 1}` } navigate() { return this.ultra.push(this.nextLink) } componentWillMount() { this.interval = setInterval(this.navigate, 3000) } componentWillUnmount() { clearInterval(this.interval) } confirm(ok, cancel) { return window.confirm('Are you sure you want to navigate away?') ? ok() : cancel() } render() { let { x, tap } = this.state let toggleTap = cb => () => this.setState(state => ({ tap: !state.tap }), cb) if (tap) this.ultra.tap((ok, cancel) => this.confirm(toggleTap(ok), cancel)) else this.ultra.untap() return ( <div> <Use matchers={this.matchers} dispatch={this.props.dispatch} /> <button onClick={toggleTap()}> {tap ? 'release' : 'tap'}: {x} </button> </div> ) } } App.contextTypes = { getUltra: PropTypes.func } export default (mountPath, msg) => <div> <hr /> <div dangerouslySetInnerHTML={{ __html: readme }} /> <App mountPath={mountPath} dispatch={msg && msg.path !== mountPath} /> </div> var readme = require('./README.md')
//主窗体 Game.ui.PVZScene = Game.extend(Game.ui.Scene,{ className:'Game.ui.PVZScene', createScene:function(){ this.height=document.body.scrollHeight; this.width=document.body.clientWidth; //this.yRate = this.height / 600; this.xRate = this.width / 1229; this.marginLeft = parseInt(252*this.xRate); this.marginTop = parseInt(92*this.xRate); this.marginRight = this.width - parseInt(230*this.xRate); this.marginBottom = this.height - parseInt(92*this.xRate); this.itemArray = []; this.monsters = {}; }, removeFocusRoad:function(){ if(this.focusRoad){ this.focusRoad.removeFocus(); } this.focusRoad = null; }, removeLastMoveItem:function(){ if(this.lastMoveItem){ this.lastMoveItem = null; this.changed = true; } }, createTower:function(xIndex,yIndex){ this.removeFocusRoad(); Game.create('tower',{xIndex:xIndex,yIndex:yIndex,scene:this,images:[Game.getCmp('huojian-1')],towerRange:Game.getCmp('towerRange-1')}); }, createConch:function(road){ Game.create('conch',{scene:this,xIndex:8,yIndex:3,road:road,images:[Game.getCmp('conch1-1'),Game.getCmp('conch2-1')]}); }, onClick:function(event,x,y){ this.removeFocusRoad(); }, onMousemove:function(event,x,y){ this.removeLastMoveItem(); } }) Game.reg('pvzScene',Game.ui.PVZScene); //Range Game.ui.Range = Game.extend(Game.ui.AnimateAble,{ level:7, added:false, className:'Game.ui.Range', render:function(ctx){ ctx.fillStyle = 'rgba(255, 255, 255,0.3)'; ctx.beginPath(); ctx.arc(this.x,this.y,this.r,0,Math.PI*2,true); ctx.fill(); this.onRender(ctx); } }) Game.reg('range',Game.ui.Range); //RoadRange Game.ui.RoadRange = Game.extend(Game.ui.Range,{ className:'Game.ui.RoadRange', onRender:function(ctx){ ctx.textBaseline = 'top'; ctx.fillStyle = 'rgb(255, 255, 0)'; ctx.fillRect(this.x - 45,this.y - 15,90,30); ctx.textAlign = 'center', ctx.fillStyle = 'rgb(20,20,20)'; ctx.fillText('创建炮塔',this.x,this.y-8); } }) Game.reg('roadRange',Game.ui.RoadRange); //TowerRange Game.ui.TowerRange = Game.extend(Game.ui.Range,{ className:'Game.ui.TowerRange', onRender:function(ctx){} }) Game.reg('towerRange',Game.ui.TowerRange); //道路 Game.ui.Road = Game.extend(Game.ui.MixImage,{ clickAble:true, mousemoveAble:true, flash:false, className:'Game.ui.Road', onClick:function(event,x,y){ if(this.tower){ this.scene.removeFocusRoad(); this.scene.focusRoad = this; return this.tower.click(event,x,y); } if(this.scene.focusRoad == this && x > this.tranWidth - 45 && x < this.tranWidth+45 && y > this.tranHeight-15 && y < this.tranHeight+15){ return this.scene.createTower(this.xIndex,this.yIndex); } if(this.scene.focusRoad != this){ this.scene.removeFocusRoad(); if(this.tower){ this.tower.showRange(); }else{ this.showRange(); } this.scene.focusRoad = this; } }, onMousemove:function(event,x,y){ this.scene.lastMoveItem = this; this.scene.changed = true; }, beforeShow:function(){ var rate = this.scene.rate; this.level = 1; this.renderWidth = parseInt(83*this.scene.xRate); this.renderHeight = parseInt(83*this.scene.xRate); this.x = this.scene.marginLeft+this.renderWidth*this.xIndex; this.y = this.scene.marginTop+this.renderHeight*this.yIndex; this.tranWidth = this.x+this.renderWidth/2; this.tranHeight = this.y+this.renderHeight/2; this.scene.iconWidth = this.renderWidth; this.scene.iconHeight = this.renderHeight; var itemArray = this.scene.itemArray; if(!itemArray[this.xIndex]){ itemArray[this.xIndex] = []; } itemArray[this.xIndex][this.yIndex] = this; }, onRender:function(ctx){ if(this.scene.lastMoveItem == this){ ctx.fillStyle = 'rgba(255, 255, 255, 0.2)'; ctx.fillRect(this.x+2,this.y+2,this.renderWidth-4, this.renderHeight-4); } }, showRange:function(){ this.roadRange.x = this.tranWidth; this.roadRange.y = this.tranHeight; this.roadRange.road = this; this.roadRange.show(); }, removeFocus:function(){ if(this.tower){ this.tower.towerRange.hide(); }else{ this.roadRange.hide(); } } }) Game.reg('road',Game.ui.Road); //炮塔 Game.ui.Tower = Game.extend(Game.ui.MixImage,{ atk:3, per:16, fireTime:60, flash:false, autoShow:true, isShowRange:false, autoAnimate:true, currentFireTime:0, className:'Game.ui.Tower', beforeShow:function(){ this.level = 1; this.renderWidth = parseInt(83*this.scene.xRate); this.renderHeight = parseInt(83*this.scene.xRate); this._x = this.scene.marginLeft+this.renderWidth*this.xIndex; this._y = this.scene.marginTop+this.renderHeight*this.yIndex; this.scene.iconWidth = this.renderWidth; this.scene.iconHeight = this.renderHeight; this.rotate = 0; this.lastRotate = 0; this.range = 200; this.scene.itemArray[this.xIndex][this.yIndex].tower = this; this.tranWidth = this._x+this.renderWidth/2; this.tranHeight = this._y+this.renderHeight/2; this.x = -this.renderWidth/2; this.y = -this.renderHeight/2; this.zx = this._x - this.x; this.zy = this._y - this.y; }, beforeRender:function(ctx){ ctx.save(); ctx.translate(this.tranWidth,this.tranHeight); ctx.rotate(this.rotate); }, onRender:function(ctx){ ctx.restore(); }, onClick:function(event,x,y){ this.showRange(this.ctx); }, showRange:function(ctx){ this.towerRange.x = this.tranWidth; this.towerRange.y = this.tranHeight; this.towerRange.tower = this; this.towerRange.show(); }, onAnimate:function(){ if(!this.target){ var monsters = this.scene.monsters; for(var i in monsters){ var z = monsters[i]; if(this.range > $gm.distance(this.zx,this.zy,z.cx,z.cy)){ this.target = z; break; } } }else{ var distance = $gm.distance(this.zx,this.zy,this.target.cx,this.target.cy); if(this.range > distance){ this.rotate = $gm.rotate(this.target.cx - this.zx,this.zy - this.target.cy ); this.lastRotate = this.rotate; this.currentFireTime++; if(this.currentFireTime == this.fireTime){ this.fire(distance); this.currentFireTime = 0; } }else{ this.target = null; } } }, fire:function(distance){ Game.create('towerBullet',{scene:this.scene,tower:this,target:this.target,distance:distance,images:[Game.getCmp('hj-zd-1-1'),Game.getCmp('hj-zd-2-1')]}); } }) Game.reg('tower',Game.ui.Tower); //怪兽-海螺 Game.ui.Conch = Game.extend(Game.ui.MixImage,{ per:64, blood:360, cBlood:360, animateRate:2, autoShow:true, imgInterval:3, autoAnimate:true, currentAnimateRate:2, className:'Game.ui.Conch', beforeShow:function(){ this.level = 1; this.currentDom = 0; this.step = 2; this.lastXIndex = this.xIndex+1; this.lastYIndex = this.yIndex; this.currentXIndex = this.xIndex; this.currentYIndex = this.yIndex; var renderWidth = parseInt(83*this.scene.xRate); var renderHeight = parseInt(83*this.scene.xRate); this.boxWidth = renderWidth; this.x = this.scene.marginLeft+renderWidth*this.xIndex+(renderWidth-50)/2; this.y = this.scene.marginTop+renderHeight*this.yIndex+(renderHeight-60)/2; this.renderWidth = renderWidth*50/83; this.renderHeight = renderHeight*60/83; this.run = this.boxWidth; this.halfRenderWith = this.renderWidth/2; this.halfRenderHeight = this.renderHeight/2; this.cx = this.x + this.halfRenderWith; this.cy = this.y + this.halfRenderHeight; this.scene.monsters[this.id] = this; this.onAnimate(); }, render:function(ctx){ ctx.drawImage(this.dom.dom,0,0,this.dom.width,this.dom.height,this.x,this.y,this.renderWidth,this.renderHeight); this.onRender(ctx); }, onAnimate:function(){ if(this.x >this.scene.width || this.x < 0 || this.y >this.scene.height || this.y < 0 ){ return this.destroy(); } if(this.run >= this.boxWidth){ this.run = 0; if(this.road[this.currentXIndex-1] && this.road[this.currentXIndex-1][this.currentYIndex] == 0 && (this.currentXIndex-1 != this.lastXIndex || this.currentYIndex != this.lastYIndex)){ this.lastXIndex = this.currentXIndex; this.lastYIndex = this.currentYIndex; this.currentXIndex--; this.move = -this.step; this.direction = 'x'; }else if(this.road[this.currentXIndex+1] && this.road[this.currentXIndex+1][this.currentYIndex] == 0 && (this.currentXIndex+1 != this.lastXIndex || this.currentYIndex != this.lastYIndex)){ this.lastXIndex = this.currentXIndex; this.lastYIndex = this.currentYIndex; this.currentXIndex++; this.move = this.step; this.direction = 'x'; }else if(this.road[this.currentXIndex] && this.road[this.currentXIndex][this.currentYIndex-1] == 0 && (this.currentXIndex != this.lastXIndex || this.currentYIndex-1 != this.lastYIndex)){ this.lastXIndex = this.currentXIndex; this.lastYIndex = this.currentYIndex; this.currentYIndex--; this.move = -this.step; this.direction = 'y'; }else if(this.road[this.currentXIndex] && this.road[this.currentXIndex][this.currentYIndex+1] == 0 && (this.currentXIndex != this.lastXIndex || this.currentYIndex+1 != this.lastYIndex)){ this.lastXIndex = this.currentXIndex; this.lastYIndex = this.currentYIndex; this.currentYIndex++; this.direction = 'y'; this.move = this.step; } } if(this.direction == 'x'){ this.x+=this.move; }else{ this.y+=this.move; } this.cx = this.x + this.halfRenderWith; this.cy = this.y + this.halfRenderHeight; this.run+=this.step; }, onDestroy:function(){ delete this.scene.monsters[this.id]; this.scene.removeLevelItem(this); }, onRender:function(ctx){ ctx.fillStyle = 'rgb(255, 255, 255)'; ctx.fillRect(this.x, this.y-10, this.renderWidth, 4); ctx.fillStyle = 'rgb(240, 17, 17)'; ctx.fillRect(this.x, this.y-10, this.renderWidth*this.cBlood/this.blood, 4); } }) Game.reg('conch',Game.ui.Conch); //炮塔的子弹 Game.ui.TowerBullet = Game.extend(Game.ui.MixImage,{ per:16, autoShow:true, autoAnimate:true, imgInterval:6, className:'Game.ui.TowerBullet', beforeShow:function(){ var rate = this.scene.rate; this.level = 2; this.step = 9; var tower = this.tower; this.tranWidth = tower.tranWidth; this.tranHeight = tower.tranHeight; this.rotate = tower.rotate; this.currentIndex = 0; this.x = tower.x+22; this.run = 0; this.y= tower.y; this.renderWidth = parseInt(41.915*this.scene.xRate); this.renderHeight = parseInt(83*this.scene.xRate); this.onAnimate(); this.startAnimate(); }, render:function(ctx){ ctx.translate(this.tranWidth,this.tranHeight); ctx.rotate(this.rotate); ctx.drawImage(this.dom.dom,0,0,this.dom.width,this.dom.height,this.x,this.y,this.renderWidth,this.renderHeight); ctx.rotate(-this.rotate); ctx.translate(-this.tranWidth,-this.tranHeight); this.onRender(ctx); }, onAnimate:function(){ if(-this.y < this.scene.width){ if(!this.shoot){ if(-this.y >= this.distance+this.renderHeight){ this.target.cBlood -= this.tower.atk; if(this.target.cBlood <= 0){ this.target.destroy(); this.target = null; this.tower.target = null; } this.shoot = true; } } this.y-=this.step; }else{ this.destroy(); } } }) Game.reg('towerBullet',Game.ui.TowerBullet);
/***************************************************************************************************************** * VGridConfig * This generates the config used by vGridgenerator, other classes also calls this to get the information, also have misc utillity functions * Created by vegar ringdal * ****************************************************************************************************************/ export class VGridConfig { /*************************************************************************************** * CSS classes used by grid ***************************************************************************************/ css = { wrapper: "vGrid", row: "vGrid-row", mainHeader: "vGrid-header", mainContent: "vGrid-body", mainFooter: "vGrid-footer", scrollBody: "vGrid-body-scroll", rowColumn: "vGrid-row-column", rowHeaderColumn: "vGrid-row-column-header", rowHeader: "vGrid-row-header", rowSelected: "vGrid-row-selected", rowContainer: "vGrid-row-container", rowAlt: "vGrid-row-alt", rowEven: "vGrid-row-even", dragHandle: "vGrid-vGridDragHandle", resizeHeaderDragHandle: "vGrid-draggable-handler", sortIcon: "vGrid-glyphicon", sortIconSort: "vGrid-glyphicon-sort", sortIconAsc: "vGrid-glyphicon-sort-asc", sortIconDesc: "vGrid-glyphicon-sort-desc", sortIconNo: "vGrid-glyphicon" }; /*************************************************************************************** * different attributes used by grid ***************************************************************************************/ atts = { dataAttribute: "v-grid-data-attribute", dataAttributeFilter: "v-grid-data-attribute-filter" }; /*************************************************************************************** * default settings, v-grid-col.js and v-grid-atts populate these defaults with new values ***************************************************************************************/ constructor(vGrid) { this.vGrid = vGrid; //<v-grid-col> attributes this.colConfig = []; //count of columns; this.columnLength = 0; //<v-grid> attibutes this.attAttributeObserve = []; this.attRowHeight = 50; this.attHeaderHeight = 0; this.attFooterHeight = 0; this.attResizableHeaders = false; this.attMultiSelect = undefined; this.attSortableHeader = false; this.attLoadingThreshold = -1; //for when loading screen comes on this.attRemoteIndex = false; this.attManualSelection = false; this.eventOnRowDraw = null; this.eventOnRowClick = null; this.eventOnRowDblClick = null; this.eventOnRemoteCall = null; this.attHidePagerInfo = false; this.attCustomPager = null; this.attLanguage = {}; //repeat html vars this.repeater = false; this.repeatRowTemplate = null; //static atm (dunno if I want them as options yet) this.attDataScrollDelay = 200; this.attRequestAnimationFrame = true; this.attResizableHeadersAndRows = true; //is just here if someone for some reson would like to just resize header, and fix rows after this.attRenderOnScrollbarScroll = true; //remote internal vars this.keepFilterOnCollectionChange = false; //for keeping the sorticons like they are this.remoteLimit = 40; this.remoteLength = 0; this.remoteOffset = 0; } /*************************************************************************************** * utillity functions for setting attibutes default, and converting them ***************************************************************************************/ setValue(htmlAttributeValue, defaultValue) { var value = defaultValue; if (htmlAttributeValue !== undefined && htmlAttributeValue !== null && !isNaN(htmlAttributeValue)) { value = htmlAttributeValue; } return value; } setBindValueArray(value, toProperty) { if (value !== undefined && value !== null) { var tempArray = value.split(","); tempArray.forEach((prop)=> { prop = prop.trim(); }); this[toProperty] = tempArray; } } setBindValueInt(value, toProperty) { this[toProperty] = this.setValue(parseInt(value), this[toProperty]); } setBindValueString(value, toProperty) { if (typeof(value) === "string" && value !== '' && value !== undefined && value !== null) { if(toProperty === "attRemoteIndex"){ //this one is special, for tracking remote this[toProperty] = true; this.vGrid.vGridRowKey = value; } else { this[toProperty] = value; } } } setBindValueFunction(value, toProperty) { if (typeof(value) === "function") { this[toProperty] = value; } } setBindValueBool(value, toProperty) { let type = { "true": true, "false": false }; this[toProperty] = this.setValue(type[value], this[toProperty]); } /*************************************************************************************** * loops current rowRef and create tempRef that gets sent to onRowDraw ***************************************************************************************/ getRowProperties(obj) { if (obj) { var x = {}; for (var k in obj) { if (obj.hasOwnProperty(k)) { if (x[k] !== obj[k]) { x[k] = obj[k]; } } } return x; } else { return ""; } } /*************************************************************************************** * calls remote function ***************************************************************************************/ remoteCall(data) { data = data ? data : {}; this.eventOnRemoteCall({ filter: data.filter || this.vGrid.vGridFilter.lastFilter, sort: data.sort || this.vGrid.vGridSort.getFilter(), limit: data.limit || this.remoteLimit, offset: data.offset || this.remoteOffset }) .then((data)=> { this.vGrid.vGridObservables.disableObservablesArray(); this.vGrid.vGridObservables.disableObservablesCollection(); this.vGrid.vGridCollection = data.col; this.remoteLimit = data.limit; this.remoteLength = data.length; this.vGrid.vGridCollectionFiltered = this.vGrid.vGridCollection.slice(0); this.vGrid.checkKeys(); this.vGrid.vGridCurrentRow = -1; if (!this.attRemoteIndex) { this.vGrid.vGridSelection.reset(); } this.vGrid.vGridGenerator.collectionChange(); this.vGrid.loading = false; this.vGrid.vGridPager.updatePager({ limit: this.remoteLimit, offset: this.remoteOffset, length: this.remoteLength }); setTimeout(()=> { this.vGrid.vGridObservables.enableObservablesArray(); this.vGrid.vGridObservables.enableObservablesCollection(); }, 200); }); } /*************************************************************************************** * This is called when grid runs filter ***************************************************************************************/ onFilterRun = (filterObj) => { if (filterObj.length !== 0 || this.vGrid.vGridCollectionFiltered.length !== this.vGrid.vGridCollection.length || this.eventOnRemoteCall) { //set loading screen if (this.vGrid.vGridCollection.length > this.attLoadingThreshold) { this.vGrid.loading = true; } //run query setTimeout(()=> { //get current key if there is any, need this to find current row after filter var curKey = -1; if (this.vGrid.vGridCurrentEntityRef) { curKey = this.vGrid.vGridCurrentEntityRef[this.vGrid.vGridRowKey]; } //if remotecall is set then lets use that if (this.eventOnRemoteCall) { //set last filter they just set this.vGrid.vGridFilter.lastFilter = filterObj; //on filter we need to set offset to 0 this.remoteOffset = 0; //trigger remote call this.remoteCall(); } else { //run filter this.vGrid.vGridCollectionFiltered = this.vGrid.vGridFilter.run(this.vGrid.vGridCollection, filterObj); //run sorting this.vGrid.vGridSort.run(this.vGrid.vGridCollectionFiltered); //set current row/entity in sync var newRowNo = -1; if (curKey) { this.vGrid.vGridCollectionFiltered.forEach((x, index) => { if (curKey === x[this.vGrid.vGridRowKey]) { newRowNo = index; } }); } //update current row/current entity/entity ref if (newRowNo > -1) { this.vGrid.vGridCurrentEntityRef = this.vGrid.vGridCollectionFiltered[newRowNo]; this.vGrid.vGridCurrentEntity[this.vGrid.vGridRowKey] = this.vGrid.vGridCurrentEntityRef[this.vGrid.vGridRowKey]; this.vGrid.vGridCurrentRow = newRowNo; } else { this.vGrid.vGridCurrentRow = newRowNo; } //update grid rows this.vGrid.vGridGenerator.collectionChange(true); this.vGrid.loading = false; } }, 50); } }; /*************************************************************************************** * grid asks for the filter name from attibute ***************************************************************************************/ getFilterName(name) { return this.vGrid.vGridFilter.getNameOfFilter(name) } /*************************************************************************************** * This just sets data from array, * Use {} if you want markup of columns, or undefined for total blank rows ***************************************************************************************/ getDataElement(row, isDown, isLargeScroll, callback) { if (this.vGrid.vGridCollectionFiltered !== undefined) { if (this.eventOnRowDraw) { //if user have added this then we call it so they can edit the row data before we display it var data = this.getRowProperties(this.vGrid.vGridCollectionFiltered[row]); this.eventOnRowDraw({ tempRef: data || null, rowRef: this.vGrid.vGridCollectionFiltered[row] || null } ); callback(data) } else { callback(this.vGrid.vGridCollectionFiltered[row]); } } } /*************************************************************************************** * This calls the order by function * Use {} if you want markup of columns, or undefined for total blank rows ***************************************************************************************/ onOrderBy(attribute, add) { //can we do the sorting? if (this.vGrid.vGridCollectionFiltered.length > 0) { //set loading screen if (this.vGrid.vGridCollection.length > this.attLoadingThreshold) { this.vGrid.loading = true; } //set query setTimeout(()=> { //set filter this.vGrid.vGridSort.setFilter({ attribute: attribute, asc: true }, add); let event = new CustomEvent("sortIconUpdate", { detail: "", bubbles: true }); this.vGrid.element.dispatchEvent(event); //if remote call is set if (this.eventOnRemoteCall) { //trigger remote call this.remoteCall(); } else { //run filter this.vGrid.vGridSort.run(this.vGrid.vGridCollectionFiltered); //set new row if (this.vGrid.vGridCurrentEntityRef) { this.vGrid.vGridCollectionFiltered.forEach((x, index) => { if (this.vGrid.vGridCurrentEntityRef[this.vGrid.vGridRowKey] === x[this.vGrid.vGridRowKey]) { this.vGrid.vGridCurrentRow = index; } }); } //update grid this.vGrid.vGridGenerator.collectionChange(); this.vGrid.loading = false; } }, 50); } } /*************************************************************************************** * Just for knowing length, * Its this you will need to add for server source/paging with endless scrolling ***************************************************************************************/ getCollectionLength() { return this.vGrid.vGridCollectionFiltered.length; } /*************************************************************************************** * Listen for click on rows(called from v-grid-generator eventlistner for the buffer rows it created) * Snd set current entity, and also allow edit of cell ***************************************************************************************/ clickHandler(event, row) { //set current row of out filtered row this.vGrid.vGridCurrentRow = row; //get data ref this.vGrid.vGridCurrentEntityRef = this.vGrid.vGridCollectionFiltered[row]; //loop properties and set them to current entity let data = this.vGrid.vGridCurrentEntityRef; for (var k in data) { if (data.hasOwnProperty(k)) { if (this.vGrid.vGridCurrentEntity[k] !== data[k]) { this.vGrid.vGridCurrentEntity[k] = data[k]; } } } //this dispatch events that v-grid-row-col.js picks up, for calling back is event for single on rows are set if (event.type === "click") { this.vGrid.raiseEvent("v-row-onclick", { evt: event, data: this.vGrid.vGridCollectionFiltered[this.vGrid.vGridCurrentRow], row: this.vGrid.vGridGetRowKey(this.vGrid.vGridCollectionFiltered[this.vGrid.vGridCurrentRow][this.vGrid.vGridRowKey]) }); } //this dispatch events that v-grid-row-col.js picks up, for calling back is event for dblclick on rows are set if (event.type === "dblclick") { this.vGrid.raiseEvent("v-row-ondblclick", { evt: event, data: this.vGrid.vGridCollectionFiltered[this.vGrid.vGridCurrentRow], row: this.vGrid.vGridGetRowKey(this.vGrid.vGridCollectionFiltered[this.vGrid.vGridCurrentRow][this.vGrid.vGridRowKey]) }); } } /**************************************************************************************************************************** * calls user for element, user haveto use callback here, might also need to fetch data first.. ****************************************************************************************************************************/ updateRowBinding(rowNo, row, isDownScroll, isLargeScroll) { //called when drawing row //lets ask for our data, and insert it into row this.getDataElement(rowNo, isDownScroll, isLargeScroll, (entity) => { row.div.setAttribute("row", rowNo); if (entity === "") { let bindingContext = {}; row.viewSlot.bind(bindingContext, { bindingContext: bindingContext, parentOverrideContext: this.vGrid.overrideContext }); } if (entity !== "" && row.viewSlot !== null) { let tempRef = {}; for (var k in entity) { if (entity.hasOwnProperty(k)) { if (tempRef[k] !== entity[k]) { tempRef[k] = entity[k]; } } } var that = this; let bindingContext = {}; bindingContext.row = rowNo; bindingContext.ctx = this; bindingContext.tempRef = tempRef; bindingContext.rowRef = this.vGrid.vGridCollectionFiltered[rowNo]; row.viewSlot.bind(bindingContext, { bindingContext: bindingContext, parentOverrideContext: this.vGrid.overrideContext }); } if (entity === undefined || entity === "" || entity === null) { row.div.style.display = "none"; } else { row.div.style.display = "block"; } //add alt/even css if (rowNo % 2 === 1) { if (row.div.classList.contains(this.css.rowEven)) { row.div.classList.remove(this.css.rowEven); row.div.classList.add(this.css.rowAlt); } } else { if (row.div.classList.contains(this.css.rowAlt)) { row.div.classList.remove(this.css.rowAlt); row.div.classList.add(this.css.rowEven); } } //set highlight if (this.vGrid.vGridSelection.isSelected(rowNo)) { row.div.classList.add(this.css.rowSelected) } else { row.div.classList.remove(this.css.rowSelected) } }); }; }
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("circle", { cx: "11", cy: "6", r: "2", opacity: ".3" }, "0"), /*#__PURE__*/_jsx("circle", { cx: "16.6", cy: "17.6", r: "2", opacity: ".3" }, "1"), /*#__PURE__*/_jsx("circle", { cx: "7", cy: "14", r: "2", opacity: ".3" }, "2"), /*#__PURE__*/_jsx("path", { d: "M7 10c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm8-10c0-2.21-1.79-4-4-4S7 3.79 7 6s1.79 4 4 4 4-1.79 4-4zm-4 2c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm5.6 5.6c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z" }, "3")], 'ScatterPlotTwoTone');
import React from 'react'; import { render, mount } from 'enzyme'; import { renderToJson } from 'enzyme-to-json'; import Badge from '../index'; describe('Badge', () => { it('renders dot prop correctly', () => { const wrapper = render( <Badge dot> <span style={{ width: '0.52rem', height: '0.52rem', background: '#ddd', display: 'inline-block' }} /> </Badge>, ); expect(renderToJson(wrapper)).toMatchSnapshot(); expect(wrapper.find('.am-badge-dot')).toHaveLength(1); }); it('renders text correctly', () => { const wrapper = mount( <Badge text="券" />, ); expect(wrapper.find('.am-badge-text')).toHaveLength(1); expect(wrapper.find('.am-badge-text').text()).toBe('券'); }); });
'use strict'; angular.module('promomemxApp') .controller('SettingsCtrl', function ($scope, User, Auth) { $scope.errors = {}; $scope.changePassword = function(form) { $scope.submitted = true; if(form.$valid) { Auth.changePassword( $scope.user.oldPassword, $scope.user.newPassword ) .then( function() { $scope.message = 'Password successfully changed.'; }) .catch( function() { form.password.$setValidity('mongoose', false); $scope.errors.other = 'Incorrect password'; }); } }; });
angular.module('fastpass.services', ['ionic']) // factory to setup our firebase connection // used in listController .factory('listService', ['$firebase', '$ionicLoading', function($firebase, $ionicLoading) { $ionicLoading.show({ template: '<i class="icon ion-loading-c"></i>' }); var ref = new Firebase('https://fastpass-connection.firebaseio.com/offers/'); ref.on('value', function() { $ionicLoading.hide(); }); return $firebase(ref); }]) .factory('giveFastPassService', function(){ return { rides: [ {name: '', value: ''}, {name: 'Splash Mountain', value: 'Splash Mountain'}, {name: 'Space Mountain', value: 'Space Mountain'}, {name: 'Thunder Mtn Railroad', value: 'Thunder Mtn Railroad'}, {name: 'Indiana Jones', value: 'Indiana Jones'}, {name: 'Star Tours', value: 'Star Tours'}, {name: 'Autopia', value: 'Autopia'}, {name: 'Car Toon Spin', value: 'Car Toon Spin'}, {name: 'Cal Screamin', value: 'Cal Screamin'}, {name: 'Sky School', value: 'Sky School'}, {name: 'Grizzly River Run', value: 'Grizzly River Run'}, {name: 'Radiator Racers', value: 'Radiator Racers'}, {name: 'Soarin Over CA', value: 'Soarin Over Cal'}, {name: 'Tower Of Terror', value: 'Tower Of Terror'} ], locations: [ {name: '', value: ''}, {name: 'AdventureLand', value: 'Adventureland'}, {name: 'Critter Country', value: 'Critter Country'}, {name: 'Fantasyland', value: 'Fantasyland'}, {name: 'Frontierland', value: 'Frontierland'}, {name: 'Main Street', value: 'Main Street'}, {name: 'Toontown', value: 'Toontown'}, {name: 'New Orleans Square', value: 'New Orleans Square'}, {name: 'Tomorrowland', value: 'Tomorrowland'}, {name: 'Condor Flats', value: 'Condor Flats'}, {name: 'Buena Vista', value: 'Buena Vista'}, {name: 'Hollywood', value: 'Hollywood'}, {name: 'Grizzy Peak', value: 'Grizzy Peak'}, {name: 'Bug\'s Land', value: 'Bug\'s Land'}, {name: 'Paradise Pier', value: 'Paradise Pier'}, {name: 'Pacific Wharf', value: 'Pacific Wharf'}, {name: 'Car\'s Land', value: 'Car\'s Land'}, ], numbers_give: [ {name: '', value: ''}, {name: '1 Fastpass', value: '1 Fastpass'}, {name: '2 Fastpasses', value: '2 Fastpasses'}, {name: '3 Fastpasses', value: '3 Fastpasses'}, {name: '4 Fastpasses', value: '4 Fastpasses'}, {name: '5 Fastpasses', value: '5 Fastpasses'}, ], comments: [ {name: '', value: ''}, {name: 'Free', value: 'Free'}, {name: 'Trade', value: 'Trade'} ] }; }) .factory('timerService', function(){ var lastOfferTime = null; var isOfferAfterTimeLimit = function(){ var currentTime = new Date(); if (currentTime - lastOfferTime > 1800000 || lastOfferTime === null){ return true; } else{ return false; } }; var setLastOfferTime = function(time){ lastOfferTime = time; }; return { isOfferAfterTimeLimit: isOfferAfterTimeLimit, setLastOfferTime: setLastOfferTime }; }) .factory('authService', function($firebaseSimpleLogin, $state, $firebase, $ionicLoading, geolocationService) { // initializing Firebase simple login helper object var ref = new Firebase('https://fastpass-connection.firebaseio.com'); var auth = $firebaseSimpleLogin(ref); // OAuth login: FB / twitter var login = function(type) { if (type === 'facebook' || type === 'twitter' || 'google'){ $ionicLoading.show({ template: '<i class="icon ion-loading-c"></i>' }); auth.$login(type) .then(function(user) { console.dir(user); var newUser = new Firebase('https://fastpass-connection.firebaseio.com/users/' + user.uid); newUser.update({displayName: user.displayName}); $ionicLoading.hide(); $state.go('app.getPass'); }, function(err) { $ionicLoading.hide(); }); }else{ $state.go('app.home'); } }; // log out current user var logout = function() { if(window.cookies){ window.cookies.clear(function() { }); } if (isLoggedIn()){ auth.$logout(); } }; var isAuthenticated = function() { return isLoggedIn(); }; // verify user object exists in auth object var isLoggedIn = function() { return auth.user !== null; }; // getter for user uid var getUserId = function() { return auth.user.uid; }; // getter for user display name var getDisplayName = function() { return auth.user.displayName; }; var getProvider = function() { return auth.user.provider; }; // return factory interface return { isLoggedIn: isLoggedIn, isAuthenticated: isAuthenticated, login: login, logout: logout, getUserId: getUserId, getDisplayName: getDisplayName, getProvider: getProvider }; }) .factory('geolocationService', function($ionicLoading) { // Disneyland boundaries var disneyLandBoundaries = { maxLat: 33.814641, minLat: 33.803622, maxLng: -117.915745, minLng: -117.923684 }; // // HR boundaries for testing var hackReactorBoundaries = { maxLat: 38, minLat: 37, maxLng: -121, minLng: -123 }; var userCoords = { lat: 0, lng: 0, }; // updates user coord with current geolocation position // hard coded numbers for debugging var updateUserGeolocation = function(callback){ var options = { timeout: 20000, enableHighAccuracy: true, maximumAge: 90000 }; navigator.geolocation.getCurrentPosition(function(position){ userCoords.lat = /*33.812*/position.coords.latitude; userCoords.lng = /*-117.92*/position.coords.longitude; callback(position); }, function(error) { $ionicLoading.hide(); }, options); }; // checks whether user is within Disneyland var inDisneyLand = function(){ // set boundaries var boundaries = disneyLandBoundaries; return true; if (boundaries.minLat < userCoords.lat && userCoords.lat < boundaries.maxLat && boundaries.minLng < userCoords.lng && userCoords.lng < boundaries.maxLng){ return true; } else{ // for testing purposes return true; // return false; } }; return { updateUserGeolocation: updateUserGeolocation, inDisneyLand: inDisneyLand, }; }) .factory('conversationsFactory', function ($firebase) { var currentUser = {}; var conversations = {}; // set currentUser var setCurrentUser = function (user) { currentUser = user; } var sendMessage = function (to) { } var addConversation = function (partner) { var messageRef = new Firebase('https://fastpass-connection.firebaseio.com/messages/' + $scope.from + '/' + partner); conversations[partner] = messagesRef; } var trackConversation = function (partner) { } return { 'setUser' : setCurrentUser, 'send' : sendMessage, 'addConversation' : addConversation }; });
// set up ====================================================================== var express = require('express'); var app = express(); // create our app w/ express var mongoose = require('mongoose'); // mongoose for mongodb var port = process.env.PORT || 9000; // set the port var morgan = require('morgan'); var bodyParser = require('body-parser'); var methodOverride = require('method-override'); // configuration =============================================================== app.use(express.static(__dirname + '/apidoc')); // set the static files location /public/img will be /img for users app.use(morgan('dev')); // log every request to the console app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded app.use(bodyParser.json()); // parse application/json app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request // routes ====================================================================== // require('./app/routes.js')(app); app.get('*', function(req, res) { res.sendfile('./apidoc/index.html'); // load the single view file (angular will handle the page changes on the front-end) }); // listen (start app with node server.js) ====================================== app.listen(port); console.log("App listening on port " + port);
var s = "start/*\ comments testing"; /* This is "comment". // Multiline comment. */ // This is "single line comment". /* var e = "//end*/";
export class HomeCtrl { $title = 'Home'; $fab = { label: 'Add', icon: 'add', click: this.fabClick.bind(this) } $actions = [ { label: 'More', icon: 'more_vert', menu: [ { label: 'An item', click: function() { console.log('item clicked'); }.bind(this) } ] } ]; items = ['A', 'B', 'C', 'D', 'E']; static $inject = []; constructor() { } actionClick(e) { console.log('action clicked'); } fabClick() { console.log('fab clicked'); } }
module.exports = { mode: "01", pid: "1C", name: "obdsup", description: "OBD requirements to which vehicle is designed", min: 0, max: 0, unit: "Bit Encoded", bytes: 1, convertToUseful: function( byteA ) { var byteAvalue = parseInt( byteA, 16 ); var obdList = { 1 : "OBD-II as defined by the CARB", 2 : "OBD as defined by the EPA", 3 : "OBD and OBD-II", 4 : "OBD-I", 5 : "Not OBD compliant", 6 : "EOBD (Europe)", 7 : "EOBD and OBD-II", 8 : "EOBD and OBD", 9 : "EOBD, OBD and OBD II", 10 : "JOBD (Japan)", 11 : "JOBD and OBD II", 12 : "JOBD and EOBD", 13 : "JOBD, EOBD, and OBD II", 14 : "Reserved", 15 : "Reserved", 16 : "Reserved", 17 : "Engine Manufacturer Diagnostics (EMD)", 18 : "Engine Manufacturer Diagnostics Enhanced (EMD+)", 19 : "Heavy Duty On-Board Diagnostics (Child/Partial) (HD OBD-C)", 20 : "Heavy Duty On-Board Diagnostics (HD OBD)", 21 : "World Wide Harmonized OBD (WWH OBD)", 22 : "Reserved", 23 : "Heavy Duty Euro OBD Stage I without NOx control (HD EOBD-I)", 24 : "Heavy Duty Euro OBD Stage I with NOx control (HD EOBD-I N)", 25 : "Heavy Duty Euro OBD Stage II without NOx control (HD EOBD-II)", 26 : "Heavy Duty Euro OBD Stage II with NOx control (HD EOBD-II N)", 27 : "Reserved", 28 : "Brazil OBD Phase 1 (OBDBr-1)", 29 : "Brazil OBD Phase 2 (OBDBr-2)", 30 : "Korean OBD (KOBD)", 31 : "India OBD I (IOBD I)", 32 : "India OBD II (IOBD II)", 33 : "Heavy Duty Euro OBD Stage VI (HD EOBD-IV)" }; if ( 1 <= byteAvalue && byteAvalue <= 33 ) return { value : byteAvalue, name : obdList[ byteAvalue ] }; if ( 34 <= byteAvalue && byteAvalue <= 250 ) return { value : byteAvalue, name : "Reserved" }; if ( 251 <= byteAvalue && byteAvalue <= 255 ) return { value : byteAvalue, name : "Not available for assignment (SAE J1939 special meaning)" }; return { value : byteAvalue, name : "Invalid response" }; } };
var assert = require('assert'); var R = require('..'); describe('lt', function() { it('reports whether one item is less than another', function() { assert(R.lt(3, 5)); assert(!R.lt(6, 4)); assert(!R.lt(7.0, 7.0)); assert(R.lt('abc', 'xyz')); assert(!R.lt('abcd', 'abc')); }); it('is curried', function() { var gt5 = R.lt(5); assert(gt5(10)); assert(!gt5(5)); assert(!gt5(3)); }); it('behaves right curried when passed `R.__` for its first argument', function() { var lt5 = R.lt(R.__, 5); assert(!lt5(10)); assert(!lt5(5)); assert(lt5(3)); }); });
import utils from 'osg/utils'; import { vec3 } from 'osg/glMatrix'; import { mat4 } from 'osg/glMatrix'; import Intersector from 'osgUtil/Intersector'; import LineSegmentIntersectFunctor from 'osgUtil/LineSegmentIntersectFunctor'; var LineSegmentIntersector = function() { Intersector.call(this); this._start = vec3.create(); this._iStart = vec3.create(); this._end = vec3.create(); this._iEnd = vec3.create(); // only used for lines and points this._threshold = 0.0; this._iThreshold = 0.0; }; utils.createPrototypeObject( LineSegmentIntersector, utils.objectInherit(Intersector.prototype, { set: function(start, end, threshold) { vec3.copy(this._start, start); vec3.copy(this._iStart, start); vec3.copy(this._end, end); vec3.copy(this._iEnd, end); if (threshold !== undefined) { this._threshold = this._iThreshold = threshold; } }, setStart: function(start) { vec3.copy(this._start, start); vec3.copy(this._iStart, start); }, setEnd: function(end) { vec3.copy(this._end, end); vec3.copy(this._iEnd, end); }, intersectNode: function(node) { // TODO implement intersectBoundingBox? return this.intersectBoundingSphere(node.getBoundingSphere()); }, // Intersection Segment/Sphere intersectBoundingSphere: (function() { var sm = vec3.create(); var se = vec3.create(); return function(bsphere) { // test for _start inside the bounding sphere if (!bsphere.valid()) return false; vec3.sub(sm, this._iStart, bsphere.center()); var c = vec3.sqrLen(sm) - bsphere.radius2(); if (c <= 0.0) { return true; } // solve quadratic equation vec3.sub(se, this._iEnd, this._iStart); var a = vec3.sqrLen(se); var b = vec3.dot(sm, se) * 2.0; var d = b * b - 4.0 * a * c; // no intersections if d<0 if (d < 0.0) { return false; } // compute two solutions of quadratic equation d = Math.sqrt(d); var div = 0.5 / a; var r1 = (-b - d) * div; var r2 = (-b + d) * div; // return false if both intersections are before the ray start if (r1 <= 0.0 && r2 <= 0.0) { return false; } if (r1 > 1.0 && r2 > 1.0) { return false; } return true; }; })(), intersect: (function() { var functor = new LineSegmentIntersectFunctor(); return function(iv, node) { functor.setGeometry(node); functor.setIntersectionVisitor(iv); functor.setIntersector(this); functor.set(this._iStart, this._iEnd, this._iThreshold); var kdtree = node.getShape(); if (kdtree) { kdtree.intersectLineSegment( functor, kdtree.getNodes()[0], this._iStart, this._iEnd, this._iThreshold ); return; } else { // handle rig transformed vertices if (node.computeTransformedVertices) { functor.setVertices(node.computeTransformedVertices()); } functor.apply(node); } functor.reset(); }; })(), setCurrentTransformation: function(matrix) { mat4.invert(matrix, matrix); if (this._threshold > 0.0) { var tmp = this._iStart; mat4.getScale(tmp, matrix); var x = tmp[0]; var y = tmp[1]; var z = tmp[2]; this._iThreshold = this._threshold * (x > y ? (x > z ? x : z) : y > z ? y : z); } vec3.transformMat4(this._iStart, this._start, matrix); vec3.transformMat4(this._iEnd, this._end, matrix); } }), 'osgUtil', 'LineSegmentIntersector' ); export default LineSegmentIntersector;
module.exports = { name: 'SwapClearedFlagged', type: 'checkbox', default: false, section: 'accounts', title: 'Swap cleared and flagged columns', description: 'Place the Cleared column on the left and the Flagged column on the right sides of an account screen.', };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M20 4h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H4V6h4.05l.59-.65L9.88 4h4.24l1.24 1.35.59.65H20v12z" /><path d="M9 12c0-1.66 1.34-3 3-3h3.98c-.92-1.21-2.35-2-3.98-2-2.76 0-5 2.24-5 5 0 .34.04.68.1 1h2.08c-.11-.31-.18-.65-.18-1zM15 12c0 1.66-1.34 3-3 3H8.02c.92 1.21 2.35 2 3.98 2 2.76 0 5-2.24 5-5 0-.34-.03-.68-.1-1h-2.08c.11.31.18.65.18 1z" /></g></React.Fragment> , 'PartyModeOutlined');
/* jQuery Masked Input Plugin Copyright (c) 2007 - 2013 Josh Bush (digitalbush.com) Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) Version: 1.3.1 */ ! function($) { function getPasteEvent() { var el = document.createElement("input"), name = "onpaste"; return el.setAttribute(name, ""), "function" == typeof el[name] ? "paste" : "input"; } var caretTimeoutId, pasteEventName = getPasteEvent() + ".mask", ua = navigator.userAgent, iPhone = /iphone/i.test(ua), chrome = /chrome/i.test(ua), android = /android/i.test(ua); $.mask = { definitions: { "9": "[0-9]", a: "[A-Za-z]", "*": "[A-Za-z0-9]" }, autoclear: 0, dataName: "rawMaskFn", placeholder: "_" }, $.fn.extend({ caret: function(begin, end) { var range; if (0 !== this.length && !this.is(":hidden")) return "number" == typeof begin ? (end = "number" == typeof end ? end : begin, this.each(function() { this.setSelectionRange ? this.setSelectionRange(begin, end) : this.createTextRange && (range = this.createTextRange(), range.collapse(!0), range.moveEnd("character", end), range.moveStart("character", begin), range.select()); })) : (this[0].setSelectionRange ? (begin = this[0].selectionStart, end = this[0].selectionEnd) : document.selection && document.selection.createRange && (range = document.selection.createRange(), begin = 0 - range.duplicate().moveStart("character", -1e5), end = begin + range.text.length), { begin: begin, end: end }); }, unmask: function() { return this.trigger("unmask"); }, mask: function(mask, settings) { var input, defs, tests, partialPosition, firstNonMaskPos, len; return !mask && this.length > 0 ? (input = $(this[0]), input.data($.mask.dataName)()) : (settings = $.extend({ autoclear: $.mask.autoclear, placeholder: $.mask.placeholder, completed: null }, settings), defs = $.mask.definitions, tests = [], partialPosition = len = mask.length, firstNonMaskPos = null, $.each(mask.split(""), function(i, c) { "?" == c ? (len--, partialPosition = i) : defs[c] ? (tests.push(new RegExp(defs[c])), null === firstNonMaskPos && (firstNonMaskPos = tests.length - 1)) : tests.push(null); }), this.trigger("unmask").each(function() { function seekNext(pos) { for (; ++pos < len && !tests[pos];); return pos; } function seekPrev(pos) { for (; --pos >= 0 && !tests[pos];); return pos; } function shiftL(begin, end) { var i, j; if (!(0 > begin)) { for (i = begin, j = seekNext(end); len > i; i++) if (tests[i]) { if (!(len > j && tests[i].test(buffer[j]))) break; buffer[i] = buffer[j], buffer[j] = settings.placeholder, j = seekNext(j); } writeBuffer(), input.caret(Math.max(firstNonMaskPos, begin)); } } function shiftR(pos) { var i, c, j, t; for (i = pos, c = settings.placeholder; len > i; i++) if (tests[i]) { if (j = seekNext(i), t = buffer[i], buffer[i] = c, !(len > j && tests[j].test(t))) break; c = t; } } function keydownEvent(e) { //ignore tab if (e.keyCode == 9) { return true; } if (e.keyCode == 8) { var currentInput = input.val(); var pos = input.caret(); if (settings.unmask !== false) { //backspace, remove if ((pos.begin == 0 && pos.end == 24) || (currentInput == "NHZ-____-____-____-_____" && pos.begin == 4)) { input.val(""); $(this).trigger("unmask"); return; } } } var pos, begin, end, k = e.which; 8 === k || 46 === k || iPhone && 127 === k ? (pos = input.caret(), begin = pos.begin, end = pos.end, 0 === end - begin && (begin = 46 !== k ? seekPrev(begin) : end = seekNext(begin - 1), end = 46 === k ? seekNext(end) : end), clearBuffer(begin, end), shiftL(begin, end - 1), e.preventDefault()) : 27 == k && (input.val(focusText), input.caret(0, checkVal()), e.preventDefault()); } function keypressEvent(e) { //ignore tab if (e.keyCode == 9) { return true; } var p, c, next, k = e.which, pos = input.caret(); if (0 == k) { if (pos.begin >= len) return input.val(input.val().substr(0, len)), e.preventDefault(), !1; pos.begin == pos.end && (k = input.val().charCodeAt(pos.begin - 1), pos.begin--, pos.end--); } e.ctrlKey || e.altKey || e.metaKey || 32 > k || k && (0 !== pos.end - pos.begin && (clearBuffer(pos.begin, pos.end), shiftL(pos.begin, pos.end - 1)), p = seekNext(pos.begin - 1), len > p && (c = String.fromCharCode(k), tests[p].test(c) && (shiftR(p), buffer[p] = c, writeBuffer(), next = seekNext(p), android ? setTimeout($.proxy($.fn.caret, input, next), 0) : input.caret(next), settings.completed && next >= len && settings.completed.call(input))), e.preventDefault()); if (/^NHZ\-[A-Z0-9]{4}\-[A-Z0-9]{4}\-[A-Z0-9]{4}\-[A-Z0-9]{5}/i.test(input.val())) { input.trigger("checkRecipient"); } } function clearBuffer(start, end) { var i; for (i = start; end > i && len > i; i++) tests[i] && (buffer[i] = settings.placeholder); } function writeBuffer() { input.val(buffer.join("")); } function checkVal(allow) { input.val(input.val().replace(/^\s*NHZ\-\s*NHZ/i, "NHZ-")); var i, c, pos, test = input.val(), lastMatch = -1; for (i = 0, pos = 0; len > i; i++) if (tests[i]) { for (buffer[i] = settings.placeholder; pos++ < test.length;) if (c = test.charAt(pos - 1), tests[i].test(c)) { buffer[i] = c, lastMatch = i; break; } if (pos > test.length) break; } else buffer[i] === test.charAt(pos) && i !== partialPosition && (pos++, lastMatch = i); return allow ? writeBuffer() : partialPosition > lastMatch + 1 ? settings.autoclear || buffer.join("") === defaultBuffer ? (input.val(""), clearBuffer(0, len)) : writeBuffer() : (writeBuffer(), input.val(input.val().substring(0, lastMatch + 1))), partialPosition ? i : firstNonMaskPos; } var input = $(this), buffer = $.map(mask.split(""), function(c) { return "?" != c ? defs[c] ? settings.placeholder : c : void 0; }), defaultBuffer = buffer.join(""), focusText = input.val(); if (settings.noMask) { input.bind("keyup.remask", function(e) { if (input.val().toLowerCase() == "nhz-") { input.val("").mask("NHZ-****-****-****-*****").unbind(".remask").trigger("focus"); } }).bind("paste.remask", function(e) { setTimeout(function() { var newInput = input.val(); if (/^NHZ\-[A-Z0-9]{4}\-[A-Z0-9]{4}\-[A-Z0-9]{4}\-[A-Z0-9]{5}/i.test(newInput) || /^NHZ[A-Z0-9]{17}/i.test(newInput)) { input.mask("NHZ-****-****-****-*****").trigger("checkRecipient").unbind(".remask"); } }, 0); }); return; } input.addClass("masked"); input.data($.mask.dataName, function() { return $.map(buffer, function(c, i) { return tests[i] && c != settings.placeholder ? c : null; }).join(""); }), input.attr("readonly") || input.one("unmask", function(e, removeCompletely) { input.unbind(".mask").removeData($.mask.dataName); input.removeClass("masked"); if (!removeCompletely) { input.bind("keyup.remask", function(e) { if (input.val().toLowerCase() == "nhz-") { input.val("").mask("NHZ-****-****-****-*****").unbind(".remask").trigger("focus"); } }).bind("paste.remask", function(e) { setTimeout(function() { var newInput = input.val(); if (/^NHZ\-[A-Z0-9]{4}\-[A-Z0-9]{4}\-[A-Z0-9]{4}\-[A-Z0-9]{5}/i.test(newInput) || /^NHZ[A-Z0-9]{17}/i.test(newInput)) { input.mask("NHZ-****-****-****-*****").trigger("checkRecipient").unbind(".remask"); } }, 0); }); } }).bind("focus.mask", function() { clearTimeout(caretTimeoutId); var pos; focusText = input.val(), pos = checkVal(), caretTimeoutId = setTimeout(function() { writeBuffer(), pos == mask.length ? input.caret(0, pos) : input.caret(pos); }, 10); }).bind("blur.mask", function() { checkVal(), input.val() != focusText && input.change(); }).bind("keydown.mask", keydownEvent).bind("keypress.mask", keypressEvent).bind(pasteEventName, function(e) { var oldInput = input.val(); setTimeout(function() { var newInput = input.val(); var pasted = text_diff(oldInput, newInput); if (/^NHZ\-[0-9]{19,20}$/i.test(pasted)) { //old style accounts.. input.val("").trigger("oldRecipientPaste"); } else { var match = /^NHZ\-[A-Z0-9]{4}\-[A-Z0-9]{4}\-[A-Z0-9]{4}\-[A-Z0-9]{5}/i.exec(pasted); if (match && match[0]) { input.val(match[0]).trigger("checkRecipient"); } else { match = /^NHZ[A-Z0-9]{17}/i.exec(pasted); if (match && match[0]) { input.val(pasted).trigger("checkRecipient"); } else { input.trigger("checkRecipient"); } } } var pos = checkVal(!0); input.caret(pos), settings.completed && pos == input.val().length && settings.completed.call(input); }, 0); }), chrome && android && input.bind("keyup.mask", keypressEvent), checkVal(); })); } }); function text_diff(first, second) { first = first.toUpperCase(); second = second.toUpperCase(); var start = 0; while (start < first.length && first[start] == second[start]) { ++start; } var end = 0; while (first.length - end > start && first[first.length - end - 1] == second[second.length - end - 1]) { ++end; } end = second.length - end; var diff = second.substr(start, end - start); if (/^NHZ\-/i.test(second) && !/^NHZ\-/i.test(diff)) { diff = "NHZ-" + diff; } return diff; } }(jQuery);
/** * Copyright 2010 Ajax.org B.V. * * This product includes software developed by * Ajax.org B.V. (http://www.ajax.org/). * * Author: Fabian Jaokbs <fabian@ajax.org> */ var sys = require("sys"); var GitHubApi = require("../lib/github").GitHubApi; var async_testing = require('../vendor/node-async-testing/async_testing'); var suite = exports.suite = new async_testing.TestSuite(); var username = "ornicar"; var branch = "master"; var repo = "php-github-api"; suite.setup(function() { this.github = new GitHubApi(true); this.commitApi = this.github.getCommitApi(); }); suite.addTests({ "test: list branch commits" : function(assert, finished, test) { test.commitApi.getBranchCommits(username, repo, branch, function(err, commits) { assert.ok(commits.length > 0); assert.ok(commits[0].message !== undefined); finished(); }); }, "test: get file commits" : function(assert, finished, test) { test.commitApi.getFileCommits(username, repo, branch, "README", function(err, commits) { assert.ok(commits.length > 0); assert.equal(commits.pop().message, "first commit"); finished(); }); } }); if (module === require.main) { async_testing.runSuites({CommitApi: suite}); }
var test = '11861i1670l81p3M614o704n674N826N79j165J1715o312j1376J3930K60r300N177'; //var test="123+456-789 1 2 3 -4 -5 -6" var reg = /(\$\$.*|[,;\t \+]*|[,;\t \+-]*[,;\t \+])([a-zA-Z@%\-+]?[\d,\.]*)/g; var result; var start = new Date().getTime(); var counter = 0; var reg = /(\$\$.*|[,;\t \+]*|[,;\t \+-]*[,;\t \+])([a-zA-Z@%\-+]?[\d,\.]*)/g; for (var i = 0; i < 100000; i++) { while ((result = reg.exec(test))) { if (result[0] === '') break; parseValue(result[2]); counter++; } reg.exec(); } console.log(counter, new Date().getTime() - start); var xyDataSplitRegExp = /[,\t \+-]*(?=[^\d,\t \.])|[ \t]+(?=[\d+\.-])/; var removeCommentRegExp = /\$\$.*/; var start = new Date().getTime(); var counter = 0; for (var i = 0; i < 100000; i++) { var values = test .trim() .replace(removeCommentRegExp, '') .split(xyDataSplitRegExp); counter += values.length; for (var j = 0; j < values.length; j++) { parseValue(values[j]); } } console.log(counter, new Date().getTime() - start); var start = new Date().getTime(); var counter = 0; for (var i = 0; i < 1000000; i++) { counter += testScan(test); } console.log(counter, new Date().getTime() - start); var currentX, currentY, lastDif, ascii; function parseValue(value) { if (value.length > 0) { ascii = value.charCodeAt(0); // + - . 0 1 2 3 4 5 6 7 8 9 if ( ascii === 43 || ascii === 45 || ascii === 46 || (ascii > 47 && ascii < 58) ) { lastDif = null; currentY = parseFloat(value); return currentY; currentX += spectrum.deltaX; } // positive SQZ digits @ A B C D E F G H I (ascii 64-73) else if (ascii > 63 && ascii < 74) { lastDif = null; currentY = parseFloat( String.fromCharCode(ascii - 16) + value.substring(1), ); return currentY; currentX += spectrum.deltaX; } // negative SQZ digits a b c d e f g h i (ascii 97-105) else if (ascii > 96 && ascii < 106) { lastDif = null; currentY = -parseFloat( String.fromCharCode(ascii - 48) + value.substring(1), ); return currentY; currentX += spectrum.deltaX; } // DUP digits S T U V W X Y Z s (ascii 83-90, 115) else if ((ascii > 82 && ascii < 91) || ascii === 115) { var dup = parseFloat(String.fromCharCode(ascii - 34) + value.substring(1)) - 1; if (ascii === 115) { dup = parseFloat('9' + value.substring(1)) - 1; } for (var l = 0; l < dup; l++) { if (lastDif) { currentY = currentY + lastDif; } return currentY; currentX += spectrum.deltaX; } } // positive DIF digits % J K L M N O P Q R (ascii 37, 74-82) else if (ascii === 37) { lastDif = parseFloat('0' + value.substring(1)); currentY += lastDif; return currentY; currentX += spectrum.deltaX; } else if (ascii > 73 && ascii < 83) { lastDif = parseFloat( String.fromCharCode(ascii - 25) + value.substring(1), ); currentY += lastDif; return currentY; currentX += spectrum.deltaX; } // negative DIF digits j k l m n o p q r (ascii 106-114) else if (ascii > 105 && ascii < 115) { return currentY; currentX += spectrum.deltaX; } } } function testScan(value) { var ascii; var counter = 0; var newValue = ''; for (var i = 0; i < value.length; i++) { ascii = value.charCodeAt(); newValue += String.fromCharCode(ascii); // + - . 0 1 2 3 4 5 6 7 8 9 if ( ascii === 43 || ascii === 45 || ascii === 46 || (ascii > 47 && ascii < 58) ) { counter += 1; } // positive SQZ digits @ A B C D E F G H I (ascii 64-73) else if (ascii > 63 && ascii < 74) { counter += 2; } // negative SQZ digits a b c d e f g h i (ascii 97-105) else if (ascii > 96 && ascii < 106) { counter += 3; } // DUP digits S T U V W X Y Z s (ascii 83-90, 115) else if ((ascii > 82 && ascii < 91) || ascii === 115) { counter += 4; } // positive DIF digits % J K L M N O P Q R (ascii 37, 74-82) else if (ascii === 37) { counter += 5; } else if (ascii > 73 && ascii < 83) { counter += 6; } // negative DIF digits j k l m n o p q r (ascii 106-114) else if (ascii > 105 && ascii < 115) { counter += 7; } } counter += newValue.length; return counter; }
/** * @file pluginSettingsFunction * @author Jim Bulkowski <jim.b@paperelectron.com> * @project Pomegranate * @license MIT {@link http://opensource.org/licenses/MIT} */ 'use strict'; var stringifyObject = require('stringify-object'); var _ = require('lodash'); module.exports = function(pluginName, exportObj) { var EOL = require('os').EOL var objString = stringifyObject(exportObj, {indent: ' ', singleQuotes: true}) var paddedObj = _.map(objString.split('\n'), function(line, index){ if(index > 0) { return ' ' + line } return line }).join(EOL); var functionString = [ 'exports.'+ pluginName +' = function(Env){', ' return '+ paddedObj, '}' ]; var file = [ '/* ', ' * ' + pluginName + ' -- Settings', ' *', ' * The Env parameter in the exported function below refers to process.env', ' * Feel free to use it as such.', ' */', '' ].concat(functionString).join(EOL) return file }
/*jshint quotmark: false*/ 'use strict'; var Promise = require('../../lib/ext/promise'); var expect = require('chai').expect; var assertFile = require('../helpers/assert-file'); var conf = require('../helpers/conf'); var ember = require('../helpers/ember'); var existsSync = require('exists-sync'); var fs = require('fs-extra'); var outputFile = Promise.denodeify(fs.outputFile); var path = require('path'); var remove = Promise.denodeify(fs.remove); var root = process.cwd(); var tmp = require('tmp-sync'); var tmproot = path.join(root, 'tmp'); var EOL = require('os').EOL; var BlueprintNpmTask = require('../helpers/disable-npm-on-blueprint'); describe('Acceptance: ember destroy', function() { var tmpdir; before(function() { BlueprintNpmTask.disableNPM(); conf.setup(); }); after(function() { BlueprintNpmTask.restoreNPM(); conf.restore(); }); beforeEach(function() { tmpdir = tmp.in(tmproot); process.chdir(tmpdir); }); afterEach(function() { this.timeout(10000); process.chdir(root); return remove(tmproot); }); function initApp() { return ember([ 'init', '--name=my-app', '--skip-npm', '--skip-bower' ]); } function initAddon() { return ember([ 'addon', 'my-addon', '--skip-npm', '--skip-bower' ]); } function initInRepoAddon() { return initApp().then(function() { return ember([ 'generate', 'in-repo-addon', 'my-addon' ]); }); } function generate(args) { var generateArgs = ['generate'].concat(args); return ember(generateArgs); } function generateInAddon(args) { var generateArgs = ['generate'].concat(args); return initAddon().then(function() { return ember(generateArgs); }); } function generateInRepoAddon(args) { var generateArgs = ['generate'].concat(args); return initInRepoAddon().then(function() { return ember(generateArgs); }); } function destroy(args) { var destroyArgs = ['destroy'].concat(args); return ember(destroyArgs); } function assertFileNotExists(file) { var filePath = path.join(process.cwd(), file); expect(!existsSync(filePath), 'expected ' + file + ' not to exist'); } function assertFilesExist(files) { files.forEach(assertFile); } function assertFilesNotExist(files) { files.forEach(assertFileNotExists); } function assertDestroyAfterGenerate(args, files) { return initApp() .then(function() { return generate(args); }) .then(function() { assertFilesExist(files); }) .then(function() { return destroy(args); }) .then(function(result) { expect(result, 'destroy command did not exit with errorCode').to.be.an('object'); assertFilesNotExist(files); }); } function assertDestroyAfterGenerateInAddon(args, files) { return initAddon() .then(function() { return generateInAddon(args); }) .then(function() { assertFilesExist(files); }) .then(function() { return destroy(args); }) .then(function(result) { expect(result, 'destroy command did not exit with errorCode').to.be.an('object'); assertFilesNotExist(files); }); } function assertDestroyAfterGenerateInRepoAddon(args, files) { return generateInRepoAddon(args) .then(function() { assertFilesExist(files); }) .then(function() { return destroy(args); }) .then(function(result) { expect(result, 'destroy command did not exit with errorCode').to.be.an('object'); assertFilesNotExist(files); }); } it('controller foo', function() { this.timeout(20000); var commandArgs = ['controller', 'foo']; var files = [ 'app/controllers/foo.js', 'tests/unit/controllers/foo-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('controller foo/bar', function() { this.timeout(20000); var commandArgs = ['controller', 'foo/bar']; var files = [ 'app/controllers/foo/bar.js', 'tests/unit/controllers/foo/bar-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('component x-foo', function() { this.timeout(20000); var commandArgs = ['component', 'x-foo']; var files = [ 'app/components/x-foo.js', 'app/templates/components/x-foo.hbs', 'tests/integration/components/x-foo-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('helper foo-bar', function() { this.timeout(20000); var commandArgs = ['helper', 'foo-bar']; var files = [ 'app/helpers/foo-bar.js', 'tests/unit/helpers/foo-bar-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('helper foo/bar-baz', function() { this.timeout(20000); var commandArgs = ['helper', 'foo/bar-baz']; var files = [ 'app/helpers/foo/bar-baz.js', 'tests/unit/helpers/foo/bar-baz-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('model foo', function() { this.timeout(20000); var commandArgs = ['model', 'foo']; var files = [ 'app/models/foo.js', 'tests/unit/models/foo-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('model foo/bar', function() { this.timeout(20000); var commandArgs = ['model', 'foo/bar']; var files = [ 'app/models/foo/bar.js', 'tests/unit/models/foo/bar-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('route foo', function() { this.timeout(20000); var commandArgs = ['route', 'foo']; var files = [ 'app/routes/foo.js', 'app/templates/foo.hbs', 'tests/unit/routes/foo-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files) .then(function() { assertFile('app/router.js', { doesNotContain: "this.route('foo');" }); }); }); it('route index', function() { this.timeout(20000); var commandArgs = ['route', 'index']; var files = [ 'app/routes/index.js', 'app/templates/index.hbs', 'tests/unit/routes/index-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('route basic', function() { this.timeout(20000); var commandArgs = ['route', 'basic']; var files = [ 'app/routes/basic.js', 'app/templates/basic.hbs', 'tests/unit/routes/basic-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('resource foo', function() { this.timeout(20000); var commandArgs = ['resource', 'foo']; var files = [ 'app/models/foo.js', 'tests/unit/models/foo-test.js', 'app/routes/foo.js', 'tests/unit/routes/foo-test.js', 'app/templates/foo.hbs' ]; return assertDestroyAfterGenerate(commandArgs, files) .then(function() { assertFile('app/router.js', { doesNotContain: "this.route('foo');" }); }); }); it('resource foos', function() { this.timeout(20000); var commandArgs = ['resource', 'foos']; var files = [ 'app/models/foo.js', 'tests/unit/models/foo-test.js', 'app/routes/foos.js', 'tests/unit/routes/foos-test.js', 'app/templates/foos.hbs' ]; return assertDestroyAfterGenerate(commandArgs, files) .then(function() { assertFile('app/router.js', { doesNotContain: "this.route('foos');" }); }); }); it('template foo', function() { this.timeout(20000); var commandArgs = ['template', 'foo']; var files = ['app/templates/foo.hbs']; return assertDestroyAfterGenerate(commandArgs, files); }); it('template foo/bar', function() { this.timeout(20000); var commandArgs = ['template', 'foo/bar']; var files = ['app/templates/foo/bar.hbs']; return assertDestroyAfterGenerate(commandArgs, files); }); it('view foo', function() { this.timeout(20000); var commandArgs = ['view', 'foo']; var files = [ 'app/views/foo.js', 'tests/unit/views/foo-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('view foo/bar', function() { this.timeout(20000); var commandArgs = ['view', 'foo/bar']; var files = [ 'app/views/foo/bar.js', 'tests/unit/views/foo/bar-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('initializer foo', function() { this.timeout(20000); var commandArgs = ['initializer', 'foo']; var files = ['app/initializers/foo.js']; return assertDestroyAfterGenerate(commandArgs, files); }); it('initializer foo/bar', function() { this.timeout(20000); var commandArgs = ['initializer', 'foo/bar']; var files = ['app/initializers/foo/bar.js']; return assertDestroyAfterGenerate(commandArgs, files); }); it('mixin foo', function() { this.timeout(20000); var commandArgs = ['mixin', 'foo']; var files = [ 'app/mixins/foo.js', 'tests/unit/mixins/foo-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('mixin foo/bar', function() { this.timeout(20000); var commandArgs = ['mixin', 'foo/bar']; var files = [ 'app/mixins/foo/bar.js', 'tests/unit/mixins/foo/bar-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('adapter foo', function() { this.timeout(20000); var commandArgs = ['adapter', 'foo']; var files = ['app/adapters/foo.js']; return assertDestroyAfterGenerate(commandArgs, files); }); it('adapter foo/bar', function() { this.timeout(20000); var commandArgs = ['adapter', 'foo/bar']; var files = ['app/adapters/foo/bar.js']; return assertDestroyAfterGenerate(commandArgs, files); }); it('serializer foo', function() { this.timeout(20000); var commandArgs = ['serializer', 'foo']; var files = [ 'app/serializers/foo.js', 'tests/unit/serializers/foo-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('serializer foo/bar', function() { this.timeout(20000); var commandArgs = ['serializer', 'foo/bar']; var files = [ 'app/serializers/foo/bar.js', 'tests/unit/serializers/foo/bar-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('transform foo', function() { this.timeout(20000); var commandArgs = ['transform', 'foo']; var files = [ 'app/transforms/foo.js', 'tests/unit/transforms/foo-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('transform foo/bar', function() { this.timeout(20000); var commandArgs = ['transform', 'foo/bar']; var files = [ 'app/transforms/foo/bar.js', 'tests/unit/transforms/foo/bar-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('util foo-bar', function() { this.timeout(20000); var commandArgs = ['util', 'foo-bar']; var files = [ 'app/utils/foo-bar.js', 'tests/unit/utils/foo-bar-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('util foo-bar/baz', function() { this.timeout(20000); var commandArgs = ['util', 'foo/bar-baz']; var files = [ 'app/utils/foo/bar-baz.js', 'tests/unit/utils/foo/bar-baz-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('service foo', function() { this.timeout(20000); var commandArgs = ['service', 'foo']; var files = [ 'app/services/foo.js', 'tests/unit/services/foo-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('service foo/bar', function() { this.timeout(20000); var commandArgs = ['service', 'foo/bar']; var files = [ 'app/services/foo/bar.js', 'tests/unit/services/foo/bar-test.js' ]; return assertDestroyAfterGenerate(commandArgs, files); }); it('blueprint foo', function() { this.timeout(20000); var commandArgs = ['blueprint', 'foo']; var files = ['blueprints/foo/index.js']; return assertDestroyAfterGenerate(commandArgs, files); }); it('blueprint foo/bar', function() { this.timeout(20000); var commandArgs = ['blueprint', 'foo/bar']; var files = ['blueprints/foo/bar/index.js']; return assertDestroyAfterGenerate(commandArgs, files); }); it('http-mock foo', function() { this.timeout(20000); var commandArgs = ['http-mock', 'foo']; var files = ['server/mocks/foo.js']; return assertDestroyAfterGenerate(commandArgs, files); }); it('http-proxy foo', function() { this.timeout(20000); var commandArgs = ['http-proxy', 'foo', 'bar']; var files = ['server/proxies/foo.js']; return assertDestroyAfterGenerate(commandArgs, files); }); it('in-addon component x-foo', function() { this.timeout(20000); var commandArgs = ['component', 'x-foo']; var files = [ 'addon/components/x-foo.js', 'addon/templates/components/x-foo.hbs', 'app/components/x-foo.js', 'tests/integration/components/x-foo-test.js' ]; return assertDestroyAfterGenerateInAddon(commandArgs, files); }); it('in-repo-addon component x-foo', function() { var commandArgs = ['component', 'x-foo', '--in-repo-addon=my-addon']; var files = [ 'lib/my-addon/addon/components/x-foo.js', 'lib/my-addon/addon/templates/components/x-foo.hbs', 'lib/my-addon/app/components/x-foo.js', 'tests/integration/components/x-foo-test.js' ]; return assertDestroyAfterGenerateInRepoAddon(commandArgs, files); }); it('in-repo-addon component nested/x-foo', function() { var commandArgs = ['component', 'nested/x-foo', '--in-repo-addon=my-addon']; var files = [ 'lib/my-addon/addon/components/nested/x-foo.js', 'lib/my-addon/addon/templates/components/nested/x-foo.hbs', 'lib/my-addon/app/components/nested/x-foo.js', 'tests/integration/components/nested/x-foo-test.js' ]; return assertDestroyAfterGenerateInRepoAddon(commandArgs, files); }); it('acceptance-test foo', function() { this.timeout(20000); var commandArgs = ['acceptance-test', 'foo']; var files = ['tests/acceptance/foo-test.js']; return assertDestroyAfterGenerate(commandArgs, files); }); it('deletes files generated using blueprints from the project directory', function() { this.timeout(20000); var commandArgs = ['foo', 'bar']; var files = ['app/foos/bar.js']; return initApp() .then(function() { return outputFile( 'blueprints/foo/files/app/foos/__name__.js', "import Ember from 'ember';" + EOL + EOL + 'export default Ember.Object.extend({ foo: true });' + EOL ); }) .then(function() { return generate(commandArgs); }) .then(function() { assertFilesExist(files); }) .then(function() { return destroy(commandArgs); }) .then(function() { assertFilesNotExist(files); }); }); it('correctly identifies the root of the project', function() { this.timeout(20000); var commandArgs = ['controller', 'foo']; var files = ['app/controllers/foo.js']; return initApp() .then(function() { return outputFile( 'blueprints/controller/files/app/controllers/__name__.js', "import Ember from 'ember';" + EOL + EOL + "export default Ember.Controller.extend({ custom: true });" + EOL ); }) .then(function() { return generate(commandArgs); }) .then(function() { assertFilesExist(files); }) .then(function() { process.chdir(path.join(tmpdir, 'app')); }) .then(function() { return destroy(commandArgs); }) .then(function() { process.chdir(tmpdir); }) .then(function() { assertFilesNotExist(files); }); }); it('http-mock <name> does not remove server/', function() { this.timeout(20000); return initApp() .then(function() { return generate(['http-mock', 'foo']); }) .then(function() { return generate(['http-mock', 'bar']); }) .then(function() { return destroy(['http-mock', 'foo']); }) .then(function() { assertFile('server/index.js'); assertFile('server/.jshintrc'); }); }); });
// DO NOT DELETE
// @flow import React, { Component } from 'react'; import Button from 'material-ui/Button'; import Dialog, { DialogTitle, DialogContent, DialogContentText, DialogActions, } from 'material-ui/Dialog'; import Typography from 'material-ui/Typography'; import withRoot from '../components/withRoot'; const styles = { container: { textAlign: 'center', paddingTop: 200, }, }; class Index extends Component { state = { open: false, }; handleRequestClose = () => { this.setState({ open: false, }); }; handleClick = () => { this.setState({ open: true, }); }; render() { return ( <div style={styles.container}> <Dialog open={this.state.open} onRequestClose={this.handleRequestClose}> <DialogTitle>Super Secret Password</DialogTitle> <DialogContent> <DialogContentText>1-2-3-4-5</DialogContentText> </DialogContent> <DialogActions> <Button color="primary" onClick={this.handleRequestClose}> OK </Button> </DialogActions> </Dialog> <Typography type="display1" gutterBottom> Material-UI </Typography> <Typography type="subheading" gutterBottom> example project </Typography> <Button raised color="accent" onClick={this.handleClick}> Super Secret Password </Button> </div> ); } } export default withRoot(Index);
'use strict'; /*! * snakeskin.github.io * https://github.com/SnakeskinTpl/snakeskin.github.io * * Released under the MIT license * https://github.com/SnakeskinTpl/snakeskin.github.io/blob/master/LICENSE */ $(() => { const doc = $(document), contents = $('nav.b-contents'), headerHeight = $('header.b-header').innerHeight(), arrows = $('.b-articles__nav-cont'); doc.on('scroll', () => { if (doc.scrollTop() >= headerHeight) { contents.addClass('b-contents_full_true'); arrows.addClass('b-articles__nav-cont_full_true'); } else { contents.removeClass('b-contents_full_true'); arrows.removeClass('b-articles__nav-cont_full_true'); } }); });
define(['angular','ngStorage','angular-route','lib/autocomplete','ngQuickDate'], function(angular){ return angular.module('app', ['ngStorage','ngRoute','autocomplete','ngQuickDate']); });
import Alt from 'alt'; var alt = new Alt(); export default alt;
var charsStartIndex = require('./_charsStartIndex'), stringToArray = require('./_stringToArray'), toString = require('./toString'); /** Used to match leading and trailing whitespace. */ var reTrimStart = /^\s+/; /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimStart(' abc '); * // => 'abc ' * * _.trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimStart(string, chars, guard) { string = toString(string); if (!string) { return string; } if (guard || chars === undefined) { return string.replace(reTrimStart, ''); } chars = (chars + ''); if (!chars) { return string; } var strSymbols = stringToArray(string); return strSymbols.slice(charsStartIndex(strSymbols, stringToArray(chars))).join(''); } module.exports = trimStart;
a > b;
var forEach = require('./forEach'); /** * Call `methodName` on each item of the array passing custom arguments if * needed. */ function invoke(arr, methodName, var_args){ var args = Array.prototype.slice.call(arguments, 2); forEach(arr, function(item){ item[methodName].apply(item, args); }); return arr; } module.exports = invoke;
/** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ /* inspired by http://github.com/requirejs/text */ /*global XMLHttpRequest, XDomainRequest */ define(['module'], function (module) { 'use strict'; var xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im, stripReg = /!strip$/i, defaultConfig = module.config && module.config() || {}; /** * Strips <?xml ...?> declarations so that external SVG and XML documents can be * added to a document without worry. * Also, if the string is an HTML document, only the part inside the body tag is returned. * * @param {String} external * @returns {String} */ function stripContent(external) { var matches; if (!external) { return ''; } matches = external.match(bodyRegExp); external = matches ? matches[1] : external.replace(xmlRegExp, ''); return external; } /** * Checks that url match current location * * @param {String} url * @returns {Boolean} */ function sameDomain(url) { var uProtocol, uHostName, uPort, xdRegExp = /^([\w:]+)?\/\/([^\/\\]+)/i, location = window.location, match = xdRegExp.exec(url); if (!match) { return true; } uProtocol = match[1]; uHostName = match[2]; uHostName = uHostName.split(':'); uPort = uHostName[1] || ''; uHostName = uHostName[0]; return (!uProtocol || uProtocol === location.protocol) && (!uHostName || uHostName.toLowerCase() === location.hostname.toLowerCase()) && (!uPort && !uHostName || uPort === location.port); } /** * @returns {XMLHttpRequest|XDomainRequest|null} */ function createRequest(url) { var xhr = new XMLHttpRequest(); if (!sameDomain(url) && typeof XDomainRequest !== 'undefined') { xhr = new XDomainRequest(); } return xhr; } /** * XHR requester. Returns value to callback. * * @param {String} url * @param {Function} callback * @param {Function} fail * @param {Object} headers */ function getContent(url, callback, fail, headers) { var xhr = createRequest(url), header, errorHandler = fail || Function(); /*eslint-disable max-depth */ if ('setRequestHeader' in xhr && headers) { for (header in headers) { if (headers.hasOwnProperty(header)) { xhr.setRequestHeader(header.toLowerCase(), headers[header]); } } } /*eslint-enable max-depth */ if (defaultConfig.onXhr) { defaultConfig.onXhr(xhr, url); } /** * onload handler */ xhr.onload = function () { callback(xhr.responseText); if (defaultConfig.onXhrComplete) { defaultConfig.onXhrComplete(xhr, url); } }; /** * onerror handler */ xhr.onerror = function (event) { errorHandler(event); if (defaultConfig.onXhrFailure) { defaultConfig.onXhrFailure(xhr, url, event); } }; xhr.open('GET', url); xhr.send(); } /** * Main method used by RequireJs. * * @param {String} name - has format: some.module.filext!strip * @param {Function} req * @param {Function|undefined} onLoad */ function loadContent(name, req, onLoad) { var toStrip = stripReg.test(name), url = req.toUrl(name.replace(stripReg, '')), headers = defaultConfig.headers; getContent(url, function (content) { content = toStrip ? stripContent(content) : content; onLoad(content); }, onLoad.error, headers); } return { load: loadContent, get: getContent }; });
'use strict'; module.exports = function(app){ var ApplicationService = app.getService('Application', true); var TestGetService = ApplicationService.extend(function(app){ this.app = app; this.serviceName = "TestGet"; }).methods(); return TestGetService; };
var AWS = require('../core'); AWS.DirectConnect = AWS.Service.defineService('directconnect', ['2012-10-25']); module.exports = AWS.DirectConnect;
'use strict'; var endsWith = require('../lib/utils').endsWith; module.exports = function(AV) { return function() { return function(req, res, next) { if ((AV.Cloud.__prod || endsWith(req.get('host'), '.leanapp.cn')) && (!req.secure)) { return res.redirect('https://' + req.get('host') + req.originalUrl); } else { return next(); } } } };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-1 10H4c-.55 0-1-.45-1-1V9c0-.55.45-1 1-1h1v3c0 .55.45 1 1 1s1-.45 1-1V8h2v3c0 .55.45 1 1 1s1-.45 1-1V8h2v3c0 .55.45 1 1 1s1-.45 1-1V8h2v3c0 .55.45 1 1 1s1-.45 1-1V8h1c.55 0 1 .45 1 1v6c0 .55-.45 1-1 1z" /></g></React.Fragment> , 'StraightenRounded');
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- function equal(a, b) { if (a == b) { print("Correct"); } else { print(">> Fail!"); } } function testConstructor() { print("Constructor"); print(SIMD.Float32x4 !== undefined); equal('function', typeof SIMD.Float32x4); print(SIMD.Float32x4(1.0, 2.0, 3.0, 4.0) !== undefined); var a = SIMD.Float32x4(1.0, 2.0, 3.0, 4.0); var b = SIMD.Float32x4.check(a); equal(a, b); try { var a = SIMD.Float32x4.check(1) } catch (e) { print("Type Error"); } } function testFromInt32x4() { var m = SIMD.Int32x4(1, 2, 3, 4); var n = SIMD.Float32x4.fromInt32x4(m); print("FromInt32x4"); equal(1.0, SIMD.Float32x4.extractLane(n, 0)); equal(2.0, SIMD.Float32x4.extractLane(n, 1)); equal(3.0, SIMD.Float32x4.extractLane(n, 2)); equal(4.0, SIMD.Float32x4.extractLane(n, 3)); } function testFromInt32x4Bits() { var m = SIMD.Int32x4(0x3F800000, 0x40000000, 0x40400000, 0x40800000); var n = SIMD.Float32x4.fromInt32x4Bits(m); print("FromInt32x4Bits"); equal(1.0, SIMD.Float32x4.extractLane(n, 0)); equal(2.0, SIMD.Float32x4.extractLane(n, 1)); equal(3.0, SIMD.Float32x4.extractLane(n, 2)); equal(4.0, SIMD.Float32x4.extractLane(n, 3)); } testConstructor(); testConstructor(); testConstructor(); testConstructor(); testConstructor(); testConstructor(); testConstructor(); testConstructor(); testFromInt32x4(); testFromInt32x4(); testFromInt32x4(); testFromInt32x4(); testFromInt32x4(); testFromInt32x4(); testFromInt32x4(); testFromInt32x4(); testFromInt32x4Bits(); testFromInt32x4Bits(); testFromInt32x4Bits(); testFromInt32x4Bits(); testFromInt32x4Bits(); testFromInt32x4Bits(); testFromInt32x4Bits();
/*! * Overlay Modal Plugin * * Oddnut Software * Copyright (c) 2009-2010 Eric Ferraiuolo - http://eric.ferraiuolo.name * YUI BSD License - http://developer.yahoo.com/yui/license.html */ var OverlayModal, OVERLAY_MODAL = 'overlayModal', HOST = 'host', BOUNDING_BOX = 'boundingBox', OVERLAY = 'overlay', MODAL = 'modal', MASK = 'mask', getCN = Y.ClassNameManager.getClassName, CLASSES = { modal : getCN(OVERLAY, MODAL), mask : getCN(OVERLAY, MASK) }, supportsPosFixed = (function(){ /*! IS_POSITION_FIXED_SUPPORTED - Juriy Zaytsev (kangax) - http://yura.thinkweb2.com/cft/ */ var isSupported = null, el, root; if (document.createElement) { el = document.createElement('div'); if (el && el.style) { el.style.position = 'fixed'; el.style.top = '10px'; root = document.body; if (root && root.appendChild && root.removeChild) { root.appendChild(el); isSupported = (el.offsetTop === 10); root.removeChild(el); } } } return isSupported; }()); // *** Constructor *** // OverlayModal = function (config) { OverlayModal.superclass.constructor.apply(this, arguments); }; // *** Static *** // Y.mix(OverlayModal, { NAME : OVERLAY_MODAL, NS : MODAL, CLASSES : CLASSES }); // *** Prototype *** // Y.extend(OverlayModal, Y.Plugin.Base, { // *** Instance Members *** // _maskNode : null, _uiHandles : null, // *** Lifecycle Methods *** // initializer : function (config) { this._uiHandles = {}; this.doAfter('renderUI', this.renderUI); this.doAfter('bindUI', this.bindUI); this.doAfter('syncUI', this.syncUI); if (this.get(HOST).get('rendered')) { this.renderUI(); this.bindUI(); this.syncUI(); } }, destructor : function () { if (this._maskNode) { this._maskNode.remove(true); } this._detachHandles(); this.get(HOST).get(BOUNDING_BOX).removeClass(CLASSES.modal); }, renderUI : function () { var host = this.get(HOST); this._maskNode = Y.Node.create('<div></div>'); this._maskNode.addClass(CLASSES.mask); this._maskNode.setStyles({ position : supportsPosFixed ? 'fixed' : 'absolute', zIndex : host.get('zIndex') || 0, width : '100%', height : '100%', top : '0', left : '0', display : 'none' }); Y.one('body').insertBefore(this._maskNode, Y.one('body').get('firstChild')); host.get(BOUNDING_BOX).addClass(CLASSES.modal); }, bindUI : function () { this.doAfter('visibleChange', this._afterHostVisibleChange); }, syncUI : function () { this._uiSetHostVisible(this.get(HOST).get('visible')); }, // *** Public Methods *** // // *** Private Methods *** // _focus : function () { var host = this.get(HOST), bb = host.get(BOUNDING_BOX), oldTI = bb.get('tabIndex'); bb.set('tabIndex', 0); host.focus(); bb.set('tabIndex', oldTI); }, _blur : function () { this.get(HOST).blur(); }, _uiSetHostVisible : function (visible) { if (visible) { this._attachHandles(); this._maskNode.setStyle('display', 'block'); this._focus(); } else { this._detachHandles(); this._maskNode.setStyle('display', 'none'); this._blur(); } }, _attachHandles : function () { var uiHandles = this._uiHandles; if ( ! uiHandles.focus) { uiHandles.focus = Y.one(document).on('focus', Y.bind(function(e){ if ( ! this.get(HOST).get(BOUNDING_BOX).contains(e.target)) { this._focus(); } }, this)); } if ( ! uiHandles.click) { var bb = this.get(HOST).get(BOUNDING_BOX); uiHandles.click = this._maskNode.on('click', Y.bind(bb.scrollIntoView, bb, false)); } if ( ! supportsPosFixed && ! uiHandles.scroll) { uiHandles.scroll = Y.one(window).on('scroll', Y.bind(function(e){ this._maskNode.setStyle('top', this._maskNode.get('docScrollY')); }, this)); } }, _detachHandles : function () { var uiHandles = this._uiHandles; Y.Object.each(uiHandles, function(h, key){ h.detach(); delete uiHandles[key]; }); }, _afterHostVisibleChange : function (e) { this._uiSetHostVisible(e.newVal); } }); Y.namespace('Plugin').OverlayModal = OverlayModal;
'use strict'; var _ = require('lodash'); var $ = require('preconditions').singleton(); var chai = require('chai'); var sinon = require('sinon'); var should = chai.should(); var async = require('async'); var Bitcore = require('bitcore'); var BitcorePayPro = require('bitcore-payment-protocol'); var request = require('supertest'); var tingodb = require('tingodb')({ memStore: true }); var log = require('../lib/log'); var WalletUtils = require('bitcore-wallet-utils'); var Bitcore = WalletUtils.Bitcore; var BWS = require('bitcore-wallet-service'); var Client = require('../lib'); var ExpressApp = BWS.ExpressApp; var Storage = BWS.Storage; var TestData = require('./testdata'); var ImportData = require('./legacyImportData.js'); var helpers = {}; chai.config.includeStack = true; helpers.getRequest = function(app) { $.checkArgument(app); return function(args, cb) { var req = request(app); var r = req[args.method](args.relUrl); if (args.headers) { _.each(args.headers, function(v, k) { r.set(k, v); }) } if (!_.isEmpty(args.body)) { r.send(args.body); }; r.end(function(err, res) { return cb(err, res, res.body); }); }; }; helpers.newClient = function(app) { $.checkArgument(app); return new Client({ request: helpers.getRequest(app), }); }; helpers.newDb = function() { this.dbCounter = (this.dbCounter || 0) + 1; return new tingodb.Db('./db/test' + this.dbCounter, {}); }; helpers.createAndJoinWallet = function(clients, m, n, cb) { clients[0].createWallet('wallet name', 'creator', m, n, { network: 'testnet' }, function(err, secret) { should.not.exist(err); if (n > 1) { should.exist(secret); } async.series([ function(next) { async.each(_.range(1, n), function(i, cb) { clients[i].joinWallet(secret, 'copayer ' + i, cb); }, next); }, function(next) { async.each(_.range(n), function(i, cb) { clients[i].openWallet(cb); }, next); }, ], function(err) { should.not.exist(err); return cb({ m: m, n: n, secret: secret, }); }); }); }; helpers.tamperResponse = function(clients, method, url, args, tamper, cb) { clients = [].concat(clients); // Use first client to get a clean response from server clients[0]._doRequest(method, url, args, function(err, result) { should.not.exist(err); tamper(result); // Return tampered data for every client in the list _.each(clients, function(client) { client._doRequest = sinon.stub().withArgs(method, url).yields(null, result); }); return cb(); }); }; var blockchainExplorerMock = {}; blockchainExplorerMock.getUnspentUtxos = function(dummy, cb) { var ret = _.map(blockchainExplorerMock.utxos || [], function(x) { var y = _.clone(x); y.toObject = function() { return this; }; return y; }); return cb(null, ret); }; blockchainExplorerMock.setUtxo = function(address, amount, m) { blockchainExplorerMock.utxos.push({ txid: Bitcore.crypto.Hash.sha256(new Buffer(Math.random() * 100000)).toString('hex'), vout: Math.floor((Math.random() * 10) + 1), amount: amount, address: address.address, scriptPubKey: address.publicKeys ? Bitcore.Script.buildMultisigOut(address.publicKeys, m).toScriptHashOut().toString() : '', }); }; blockchainExplorerMock.broadcast = function(raw, cb) { blockchainExplorerMock.lastBroadcasted = raw; return cb(null, (new Bitcore.Transaction(raw)).id); }; blockchainExplorerMock.setHistory = function(txs) { blockchainExplorerMock.txHistory = txs; }; blockchainExplorerMock.getTransactions = function(addresses, from, to, cb) { var list = [].concat(blockchainExplorerMock.txHistory); list = _.slice(list, from, to); return cb(null, list); }; blockchainExplorerMock.getAddressActivity = function(addresses, cb) { var addr = _.pluck(blockchainExplorerMock.utxos || [], 'address'); return cb(null, _.intersection(addr, addresses).length > 0); }; blockchainExplorerMock.setFeeLevels = function(levels) { blockchainExplorerMock.feeLevels = levels; }; blockchainExplorerMock.estimateFee = function(nbBlocks, cb) { return cb(null, { feePerKB: blockchainExplorerMock.feeLevels[nbBlocks] / 1e8 }); }; blockchainExplorerMock.reset = function() { blockchainExplorerMock.utxos = []; blockchainExplorerMock.txHistory = []; blockchainExplorerMock.feeLevels = []; }; describe('client API', function() { var clients, app, sandbox; var i = 0; beforeEach(function(done) { var storage = new Storage({ db: helpers.newDb(), }); var expressApp = new ExpressApp(); expressApp.start({ storage: storage, blockchainExplorer: blockchainExplorerMock, disableLogs: true, }, function() { app = expressApp.app; // Generates 5 clients clients = _.map(_.range(5), function(i) { return helpers.newClient(app); }); blockchainExplorerMock.reset(); sandbox = sinon.sandbox.create(); sandbox.stub(log, 'warn'); sandbox.stub(log, 'info'); sandbox.stub(log, 'error'); done(); }); }); afterEach(function(done) { sandbox.restore(); done(); }); describe('Client Internals', function() { it('should expose bitcore', function() { should.exist(Client.Bitcore); should.exist(Client.Bitcore.HDPublicKey); }); }); describe('Server internals', function() { it('should allow cors', function(done) { clients[0].credentials = {}; clients[0]._doRequest('options', '/', {}, function(err, x, headers) { headers['access-control-allow-origin'].should.equal('*'); should.exist(headers['access-control-allow-methods']); should.exist(headers['access-control-allow-headers']); done(); }); }); it('should handle critical errors', function(done) { var s = sinon.stub(); s.storeWallet = sinon.stub().yields('bigerror'); s.fetchWallet = sinon.stub().yields(null); var expressApp = new ExpressApp(); expressApp.start({ storage: s, blockchainExplorer: blockchainExplorerMock, disableLogs: true, }, function() { var s2 = sinon.stub(); s2.load = sinon.stub().yields(null); var client = helpers.newClient(app); client.storage = s2; client.createWallet('1', '2', 1, 1, { network: 'testnet' }, function(err) { err.code.should.equal('ERROR'); done(); }); }); }); it('should handle critical errors (Case2)', function(done) { var s = sinon.stub(); s.storeWallet = sinon.stub().yields({ code: 501, message: 'wow' }); s.fetchWallet = sinon.stub().yields(null); var expressApp = new ExpressApp(); expressApp.start({ storage: s, blockchainExplorer: blockchainExplorerMock, disableLogs: true, }, function() { var s2 = sinon.stub(); s2.load = sinon.stub().yields(null); var client = helpers.newClient(app); client.storage = s2; client.createWallet('1', '2', 1, 1, { network: 'testnet' }, function(err) { err.code.should.equal('ERROR'); done(); }); }); }); it('should handle critical errors (Case3)', function(done) { var s = sinon.stub(); s.storeWallet = sinon.stub().yields({ code: 404, message: 'wow' }); s.fetchWallet = sinon.stub().yields(null); var expressApp = new ExpressApp(); expressApp.start({ storage: s, blockchainExplorer: blockchainExplorerMock, disableLogs: true, }, function() { var s2 = sinon.stub(); s2.load = sinon.stub().yields(null); var client = helpers.newClient(app); client.storage = s2; client.createWallet('1', '2', 1, 1, { network: 'testnet' }, function(err) { console.log('err ', err); err.code.should.equal('NOTFOUND'); done(); }); }); }); it('should handle critical errors (Case4)', function(done) { var body = { code: 999, message: 'unexpected body' }; var ret = Client._parseError(body); ret.toString().indexOf('ClientError').should.not.equal(-1); done(); }); it('should handle critical errors (Case5)', function(done) { var err = 'some error'; var res, body; // leave them undefined to simulate no-response var requestStub = function(args, cb) { cb(err, res, body); }; var request = sinon.stub(clients[0], 'request', requestStub); clients[0].createWallet('wallet name', 'creator', 1, 2, { network: 'testnet' }, function(err, secret) { should.exist(err); err.code.should.equal('CONNERROR'); request.restore(); done(); }); }); }); describe('Wallet Creation', function() { it('should check balance in a 1-1 ', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function() { clients[0].getBalance(function(err, x) { should.not.exist(err); done(); }) }); }); it('should be able to complete wallet in copayer that joined later', function(done) { helpers.createAndJoinWallet(clients, 2, 3, function() { clients[0].getBalance(function(err, x) { should.not.exist(err); clients[1].getBalance(function(err, x) { should.not.exist(err); clients[2].getBalance(function(err, x) { should.not.exist(err); done(); }) }) }) }); }); it('should fire event when wallet is complete', function(done) { var checks = 0; clients[0].on('walletCompleted', function(wallet) { wallet.name.should.equal('wallet name'); wallet.status.should.equal('complete'); clients[0].isComplete().should.equal(true); clients[0].credentials.isComplete().should.equal(true); if (++checks == 2) done(); }); clients[0].createWallet('wallet name', 'creator', 2, 2, { network: 'testnet' }, function(err, secret) { should.not.exist(err); clients[0].isComplete().should.equal(false); clients[0].credentials.isComplete().should.equal(false); clients[1].joinWallet(secret, 'guest', function(err) { should.not.exist(err); clients[0].openWallet(function(err, walletStatus) { should.not.exist(err); should.exist(walletStatus); _.difference(_.pluck(walletStatus.copayers, 'name'), ['creator', 'guest']).length.should.equal(0); if (++checks == 2) done(); }); }); }); }); it('should not allow to join a full wallet ', function(done) { helpers.createAndJoinWallet(clients, 2, 2, function(w) { should.exist(w.secret); clients[4].joinWallet(w.secret, 'copayer', function(err, result) { err.code.should.contain('WFULL'); done(); }); }); }); it('should fail with an invalid secret', function(done) { // Invalid clients[0].joinWallet('dummy', 'copayer', function(err, result) { err.message.should.contain('Invalid secret'); // Right length, invalid char for base 58 clients[0].joinWallet('DsZbqNQQ9LrTKU8EknR7gFKyCQMPg2UUHNPZ1BzM5EbJwjRZaUNBfNtdWLluuFc0f7f7sTCkh7T', 'copayer', function(err, result) { err.message.should.contain('Invalid secret'); done(); }); }); }); it('should fail with an unknown secret', function(done) { // Unknown walletId var oldSecret = '3bJKRn1HkQTpwhVaJMaJ22KwsjN24ML9uKfkSrP7iDuq91vSsTEygfGMMpo6kWLp1pXG9wZSKcT'; clients[0].joinWallet(oldSecret, 'copayer', function(err, result) { err.code.should.contain('BADREQUEST'); done(); }); }); it('should detect wallets with bad signatures', function(done) { // Do not complete clients[1] pkr var openWalletStub = sinon.stub(clients[1], 'openWallet').yields(); helpers.createAndJoinWallet(clients, 2, 3, function() { helpers.tamperResponse([clients[0], clients[1]], 'get', '/v1/wallets/', {}, function(status) { status.wallet.copayers[0].xPubKey = status.wallet.copayers[1].xPubKey; }, function() { openWalletStub.restore(); clients[1].openWallet(function(err, x) { err.code.should.contain('SERVERCOMPROMISED'); done(); }); }); }); }); it('should detect wallets with missing signatures', function(done) { // Do not complete clients[1] pkr var openWalletStub = sinon.stub(clients[1], 'openWallet').yields(); helpers.createAndJoinWallet(clients, 2, 3, function() { helpers.tamperResponse([clients[0], clients[1]], 'get', '/v1/wallets/', {}, function(status) { delete status.wallet.copayers[1].xPubKey; }, function() { openWalletStub.restore(); clients[1].openWallet(function(err, x) { err.code.should.contain('SERVERCOMPROMISED'); done(); }); }); }); }); it('should detect wallets missing callers pubkey', function(done) { // Do not complete clients[1] pkr var openWalletStub = sinon.stub(clients[1], 'openWallet').yields(); helpers.createAndJoinWallet(clients, 2, 3, function() { helpers.tamperResponse([clients[0], clients[1]], 'get', '/v1/wallets/', {}, function(status) { // Replace caller's pubkey status.wallet.copayers[1].xPubKey = (new Bitcore.HDPrivateKey()).publicKey; // Add a correct signature status.wallet.copayers[1].xPubKeySignature = WalletUtils.signMessage(status.wallet.copayers[1].xPubKey, clients[0].credentials.walletPrivKey); }, function() { openWalletStub.restore(); clients[1].openWallet(function(err, x) { err.code.should.contain('SERVERCOMPROMISED'); done(); }); }); }); }); it('should return wallet status even if wallet is not yet complete', function(done) { clients[0].createWallet('wallet name', 'creator', 1, 2, { network: 'testnet' }, function(err, secret) { should.not.exist(err); should.exist(secret); clients[0].getStatus(function(err, status) { should.not.exist(err); should.exist(status); status.wallet.status.should.equal('pending'); should.exist(status.wallet.secret); status.wallet.secret.should.equal(secret); done(); }); }); }); it('should prepare wallet with external xpubkey', function(done) { var client = helpers.newClient(app); client.seedFromExternalWalletPublicKey('xpub6D52jcEfKA4cGeGcVC9pwG37Ju8pUMQrhptw82QVHRSAGBELE5uCee7Qq8RJUqQVyxfJfwbJKYyqyFhc2Xg8cJyN11kRvnAaWcACXP6K0zv', 'ledger', 2); client.isPrivKeyExternal().should.equal(true); client.getPrivKeyExternalSourceName().should.equal('ledger'); client.getExternalIndex().should.equal(2); done(); }); }); describe('Network fees', function() { it('should get current fee levels', function(done) { blockchainExplorerMock.setFeeLevels({ 1: 40000, 3: 20000, 10: 18000, }); clients[0].credentials = {}; clients[0].getFeeLevels('livenet', function(err, levels) { should.not.exist(err); should.exist(levels); _.difference(['emergency', 'priority', 'normal', 'economy'], _.pluck(levels, 'level')).should.be.empty; done(); }); }); }); describe('Preferences', function() { it('should save and retrieve preferences', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function() { clients[0].getPreferences(function(err, preferences) { should.not.exist(err); preferences.should.be.empty; clients[0].savePreferences({ email: 'dummy@dummy.com' }, function(err) { should.not.exist(err); clients[0].getPreferences(function(err, preferences) { should.not.exist(err); should.exist(preferences); preferences.email.should.equal('dummy@dummy.com'); done(); }); }); }); }); }); }); describe('Address Creation', function() { it('should be able to create address in all copayers in a 2-3 wallet', function(done) { this.timeout(5000); helpers.createAndJoinWallet(clients, 2, 3, function() { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); clients[1].createAddress(function(err, x1) { should.not.exist(err); should.exist(x1.address); clients[2].createAddress(function(err, x2) { should.not.exist(err); should.exist(x2.address); done(); }); }); }); }); }); it('should see balance on address created by others', function(done) { this.timeout(5000); helpers.createAndJoinWallet(clients, 2, 2, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 10, w.m); clients[0].getBalance(function(err, bal0) { should.not.exist(err); bal0.totalAmount.should.equal(10 * 1e8); bal0.lockedAmount.should.equal(0); clients[1].getBalance(function(err, bal1) { bal1.totalAmount.should.equal(10 * 1e8); bal1.lockedAmount.should.equal(0); done(); }); }); }); }); }); it('should detect fake addresses', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function() { helpers.tamperResponse(clients[0], 'post', '/v1/addresses/', {}, function(address) { address.address = '2N86pNEpREGpwZyHVC5vrNUCbF9nM1Geh4K'; }, function() { clients[0].createAddress(function(err, x0) { err.code.should.contain('SERVERCOMPROMISED'); done(); }); }); }); }); it('should detect fake public keys', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function() { helpers.tamperResponse(clients[0], 'post', '/v1/addresses/', {}, function(address) { address.publicKeys = [ '0322defe0c3eb9fcd8bc01878e6dbca7a6846880908d214b50a752445040cc5c54', '02bf3aadc17131ca8144829fa1883c1ac0a8839067af4bca47a90ccae63d0d8037' ]; }, function() { clients[0].createAddress(function(err, x0) { err.code.should.contain('SERVERCOMPROMISED'); done(); }); }); }); }); }); describe('Transaction Proposals Creation and Locked funds', function() { it('Should create proposal and get it', function(done) { helpers.createAndJoinWallet(clients, 2, 2, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 1, 2); blockchainExplorerMock.setUtxo(x0, 1, 2); var opts = { amount: 30000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello', }; clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); clients[0].getTx(x.id, function(err, x2) { should.not.exist(err); x2.creatorName.should.equal('creator'); x2.message.should.equal('hello'); x2.amount.should.equal(30000); x2.fee.should.equal(10000); x2.toAddress.should.equal('n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5'); done(); }); }); }); }); }); it('Should fail to create proposal with insufficient funds', function(done) { helpers.createAndJoinWallet(clients, 2, 2, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 1, 2); blockchainExplorerMock.setUtxo(x0, 1, 2); var opts = { amount: 300000000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; clients[0].sendTxProposal(opts, function(err, x) { should.exist(err); err.code.should.contain('INSUFFICIENTFUNDS'); done(); }); }); }); }); it('Should fail to create proposal with insufficient funds for fee', function(done) { helpers.createAndJoinWallet(clients, 2, 2, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 1, 2); blockchainExplorerMock.setUtxo(x0, 1, 2); var opts = { amount: 2 * 1e8 - 2000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; clients[0].sendTxProposal(opts, function(err, x) { should.exist(err); err.code.should.contain('INSUFFICIENTFUNDS'); err.message.should.contain('for fee'); opts.feePerKb = 2000; clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); clients[0].getTx(x.id, function(err, x2) { should.not.exist(err); x2.fee.should.equal(2000); done(); }); }); }); }); }); }); it('Should lock and release funds through rejection', function(done) { helpers.createAndJoinWallet(clients, 2, 2, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 1, 2); blockchainExplorerMock.setUtxo(x0, 1, 2); var opts = { amount: 120000000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); clients[0].sendTxProposal(opts, function(err, y) { err.code.should.contain('LOCKEDFUNDS'); clients[0].rejectTxProposal(x, 'no', function(err, z) { should.not.exist(err); z.status.should.equal('rejected'); clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); done(); }); }); }); }); }); }); }); it('Should lock and release funds through removal', function(done) { helpers.createAndJoinWallet(clients, 2, 2, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 1, 2); blockchainExplorerMock.setUtxo(x0, 1, 2); var opts = { amount: 120000000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); clients[0].sendTxProposal(opts, function(err, y) { err.code.should.contain('LOCKEDFUNDS'); clients[0].removeTxProposal(x, function(err) { should.not.exist(err); clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); done(); }); }); }); }); }); }); }); it('Should keep message and refusal texts', function(done) { helpers.createAndJoinWallet(clients, 2, 3, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); blockchainExplorerMock.setUtxo(x0, 10, 2); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'some message', }; clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); clients[1].rejectTxProposal(x, 'rejection comment', function(err, tx1) { should.not.exist(err); clients[2].getTxProposals({}, function(err, txs) { should.not.exist(err); txs[0].message.should.equal('some message'); txs[0].actions[0].comment.should.equal('rejection comment'); done(); }); }); }); }); }); }); it('Should encrypt proposal message', function(done) { helpers.createAndJoinWallet(clients, 2, 3, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); blockchainExplorerMock.setUtxo(x0, 10, 2); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'some message', }; var spy = sinon.spy(clients[0], '_doPostRequest'); clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); spy.calledOnce.should.be.true; JSON.stringify(spy.getCall(0).args).should.not.contain('some message'); done(); }); }); }); }); it('Should encrypt proposal refusal comment', function(done) { helpers.createAndJoinWallet(clients, 2, 3, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); blockchainExplorerMock.setUtxo(x0, 10, 2); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', }; clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); var spy = sinon.spy(clients[1], '_doPostRequest'); clients[1].rejectTxProposal(x, 'rejection comment', function(err, tx1) { should.not.exist(err); spy.calledOnce.should.be.true; JSON.stringify(spy.getCall(0).args).should.not.contain('rejection comment'); done(); }); }); }); }); }); it('should detect fake tx proposals (wrong signature)', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function() { clients[0].createAddress(function(err, x0) { should.not.exist(err); blockchainExplorerMock.setUtxo(x0, 10, 1); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello', }; clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); helpers.tamperResponse(clients[0], 'get', '/v1/txproposals/', {}, function(txps) { txps[0].proposalSignature = '304402206e4a1db06e00068582d3be41cfc795dcf702451c132581e661e7241ef34ca19202203e17598b4764913309897d56446b51bc1dcd41a25d90fdb5f87a6b58fe3a6920'; }, function() { clients[0].getTxProposals({}, function(err, txps) { should.exist(err); err.code.should.contain('SERVERCOMPROMISED'); done(); }); }); }); }); }); }); it('should detect fake tx proposals (tampered amount)', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function() { clients[0].createAddress(function(err, x0) { should.not.exist(err); blockchainExplorerMock.setUtxo(x0, 10, 1); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello', }; clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); helpers.tamperResponse(clients[0], 'get', '/v1/txproposals/', {}, function(txps) { txps[0].amount = 100000; }, function() { clients[0].getTxProposals({}, function(err, txps) { should.exist(err); err.code.should.contain('SERVERCOMPROMISED'); done(); }); }); }); }); }); }); it('should detect fake tx proposals (change address not it wallet)', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function() { clients[0].createAddress(function(err, x0) { should.not.exist(err); blockchainExplorerMock.setUtxo(x0, 10, 1); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello', }; clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); helpers.tamperResponse(clients[0], 'get', '/v1/txproposals/', {}, function(txps) { txps[0].changeAddress.address = 'n2tbmpzpecgufct2ebyitj12tpzkhn2mn5'; }, function() { clients[0].getTxProposals({}, function(err, txps) { should.exist(err); err.code.should.contain('SERVERCOMPROMISED'); done(); }); }); }); }); }); }); it('Should return only main addresses (case 1)', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); blockchainExplorerMock.setUtxo(x0, 1, 1); var opts = { amount: 10000000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); clients[0].getMainAddresses({}, function(err, addr) { should.not.exist(err); addr.length.should.equal(1); done(); }); }); }); }); }); it('Should return only main addresses (case 2)', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); clients[0].createAddress(function(err, x0) { should.not.exist(err); clients[0].getMainAddresses({ doNotVerify: true }, function(err, addr) { should.not.exist(err); addr.length.should.equal(2); done(); }); }); }); }); }); it('Should return UTXOs', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function(w) { clients[0].getUtxos(function(err, utxos) { should.not.exist(err); utxos.length.should.equal(0) clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 1, 1); clients[0].getUtxos(function(err, utxos) { should.not.exist(err); utxos.length.should.equal(1); done(); }); }); }); }); }); }); describe('Payment Protocol', function() { var http; beforeEach(function(done) { http = sinon.stub(); http.yields(null, TestData.payProBuf); helpers.createAndJoinWallet(clients, 2, 2, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 1, 2); blockchainExplorerMock.setUtxo(x0, 1, 2); var opts = { payProUrl: 'dummy', }; clients[0].payProHttp = clients[1].payProHttp = http; clients[0].fetchPayPro(opts, function(err, paypro) { clients[0].sendTxProposal({ toAddress: paypro.toAddress, amount: paypro.amount, message: paypro.memo, payProUrl: opts.payProUrl, }, function(err, x) { should.not.exist(err); done(); }); }); }); }); }); it('Should Create and Verify a Tx from PayPro', function(done) { clients[1].getTxProposals({}, function(err, txps) { should.not.exist(err); var tx = txps[0]; // From the hardcoded paypro request tx.amount.should.equal(404500); tx.toAddress.should.equal('mjfjcbuYwBUdEyq2m7AezjCAR4etUBqyiE'); tx.message.should.equal('Payment request for BitPay invoice CibEJJtG1t9H77KmM61E2t for merchant testCopay'); tx.payProUrl.should.equal('dummy'); done(); }); }); it('Should Detect tampered PayPro Proposals at getTxProposals', function(done) { helpers.tamperResponse(clients[1], 'get', '/v1/txproposals/', {}, function(txps) { txps[0].amount++; // Generate the right signature (with client 0) var sig = clients[0]._computeProposalSignature(txps[0]); txps[0].proposalSignature = sig; return txps; }, function() { clients[1].getTxProposals({}, function(err, txps) { err.code.should.contain('SERVERCOMPROMISED'); done(); }); }); }); it('Should Detect tampered PayPro Proposals at signTx', function(done) { helpers.tamperResponse(clients[1], 'get', '/v1/txproposals/', {}, function(txps) { txps[0].amount++; // Generate the right signature (with client 0) var sig = clients[0]._computeProposalSignature(txps[0]); txps[0].proposalSignature = sig; return txps; }, function() { clients[1].getTxProposals({ doNotVerify: true }, function(err, txps) { should.not.exist(err); clients[1].signTxProposal(txps[0], function(err, txps) { err.code.should.contain('SERVERCOMPROMISED'); done(); }); }); }); }); it('Should handle broken paypro data', function(done) { http = sinon.stub(); http.yields(null, 'a broken data'); clients[0].payProHttp = http; var opts = { payProUrl: 'dummy', }; clients[0].fetchPayPro(opts, function(err, paypro) { should.exist(err); err.should.contain('parse'); done(); }); }); it('Should ignore PayPro at getTxProposals if instructed', function(done) { http.yields(null, 'kaka'); clients[1].doNotVerifyPayPro = true; clients[1].getTxProposals({}, function(err, txps) { should.not.exist(err); var tx = txps[0]; // From the hardcoded paypro request tx.amount.should.equal(404500); tx.toAddress.should.equal('mjfjcbuYwBUdEyq2m7AezjCAR4etUBqyiE'); tx.message.should.equal('Payment request for BitPay invoice CibEJJtG1t9H77KmM61E2t for merchant testCopay'); tx.payProUrl.should.equal('dummy'); done(); }); }); it('Should ignore PayPro at signTxProposal if instructed', function(done) { http.yields(null, 'kaka'); clients[1].doNotVerifyPayPro = true; clients[1].getTxProposals({}, function(err, txps) { should.not.exist(err); clients[1].signTxProposal(txps[0], function(err, txps) { should.not.exist(err); done(); }); }); }); it('Should send the "payment message" when last copayer sign', function(done) { clients[0].getTxProposals({}, function(err, txps) { should.not.exist(err); clients[0].signTxProposal(txps[0], function(err, xx, paypro) { should.not.exist(err); clients[1].signTxProposal(xx, function(err, yy, paypro) { should.not.exist(err); yy.status.should.equal('accepted'); http.onCall(5).yields(null, TestData.payProAckBuf); clients[1].broadcastTxProposal(yy, function(err, zz, memo) { should.not.exist(err); var args = http.lastCall.args[0]; args.method.should.equal('POST'); args.body.length.should.equal(302); memo.should.equal('Transaction received by BitPay. Invoice will be marked as paid if the transaction is confirmed.'); done(); }); }); }); }); }); it('Should send correct refund address', function(done) { clients[0].getTxProposals({}, function(err, txps) { should.not.exist(err); clients[0].signTxProposal(txps[0], function(err, xx, paypro) { should.not.exist(err); clients[1].signTxProposal(xx, function(err, yy, paypro) { should.not.exist(err); yy.status.should.equal('accepted'); http.onCall(5).yields(null, TestData.payProAckBuf); clients[1].broadcastTxProposal(yy, function(err, zz, memo) { should.not.exist(err); clients[1].getMainAddresses({}, function(err, walletAddresses) { var args = http.lastCall.args[0]; var data = BitcorePayPro.Payment.decode(args.body); var pay = new BitcorePayPro(); var p = pay.makePayment(data); var refund_to = p.get('refund_to'); refund_to.length.should.equal(1); refund_to = refund_to[0]; var amount = refund_to.get('amount') amount.low.should.equal(404500); amount.high.should.equal(0); var s = refund_to.get('script'); s = new Bitcore.Script(s.buffer.slice(s.offset, s.limit)); var addr = new Bitcore.Address.fromScript(s, 'testnet'); addr.toString().should.equal( walletAddresses[walletAddresses.length - 1].address); done(); }); }); }); }); }); }); it('Should fail if refund address is tampered', function(done) { clients[0].getTxProposals({}, function(err, txps) { should.not.exist(err); clients[0].signTxProposal(txps[0], function(err, xx, paypro) { should.not.exist(err); clients[1].signTxProposal(xx, function(err, yy, paypro) { should.not.exist(err); yy.status.should.equal('accepted'); http.onCall(5).yields(null, TestData.payProAckBuf); helpers.tamperResponse(clients[1], 'post', '/v1/addresses/', {}, function(address) { address.address = '2N86pNEpREGpwZyHVC5vrNUCbF9nM1Geh4K'; }, function() { clients[1].broadcastTxProposal(yy, function(err, zz, memo) { err.code.should.contain('SERVERCOMPROMISED'); done(); }); }); }); }); }); }); }); describe('Multiple output proposals', function() { it('should create, get, sign, and broadcast proposal', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 1, 1); var opts = { type: 'multiple_outputs', message: 'hello', outputs: [{ amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'world', }, { amount: 20000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: null, }, { amount: 30000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', }] }; clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); clients[0].getTx(x.id, function(err, x2) { should.not.exist(err); x2.creatorName.should.equal('creator'); x2.message.should.equal('hello'); x2.fee.should.equal(10000); x2.outputs[0].toAddress.should.equal('n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5'); x2.outputs[0].amount.should.equal(10000); x2.outputs[0].message.should.equal('world'); x2.outputs[1].toAddress.should.equal('n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5'); x2.outputs[1].amount.should.equal(20000); should.not.exist(x2.outputs[1].message); x2.outputs[2].toAddress.should.equal('n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5'); x2.outputs[2].amount.should.equal(30000); should.not.exist(x2.outputs[2].message); clients[0].signTxProposal(x2, function(err, txp) { should.not.exist(err); txp.status.should.equal('accepted'); clients[0].broadcastTxProposal(txp, function(err, txp) { should.not.exist(err); txp.status.should.equal('broadcasted'); txp.txid.should.equal((new Bitcore.Transaction(blockchainExplorerMock.lastBroadcasted)).id); done(); }); }); }); }); }); }); }); }); describe('Optional Proposal Fields', function() { var opts; beforeEach(function(done) { opts = { type: 'simple', amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'some message', payProUrl: 'dummy' }; done(); }); function doTest(opts, done) { helpers.createAndJoinWallet(clients, 2, 2, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 1, 2); clients[0].sendTxProposal(opts, function(err, x) { should.not.exist(err); clients[1].getTx(x.id, function(err, x2) { should.not.exist(err); should.exist(x2); clients[0].removeTxProposal(x2, function(err) { done(); }); }); }); }); }); }; it('should pass with complete simple header', function(done) { doTest(opts, done); }); it('should pass with null message', function(done) { opts.message = null; doTest(opts, done); }); it('should pass with no message', function(done) { delete opts.message; doTest(opts, done); }); it('should pass with null payProUrl', function(done) { opts.payProUrl = ''; doTest(opts, done); }); it('should pass with no payProUrl', function(done) { delete opts.payProUrl; doTest(opts, done); }); it('should pass with complete multi-output header', function(done) { opts.type = 'multiple_outputs'; opts.outputs = [{ toAddress: opts.toAddress, amount: opts.amount, message: opts.message }]; delete opts.toAddress; delete opts.amount; doTest(opts, done); }); it('should pass with multi-output header and no message', function(done) { opts.type = 'multiple_outputs'; opts.outputs = [{ toAddress: opts.toAddress, amount: opts.amount }]; delete opts.toAddress; delete opts.amount; doTest(opts, done); }); }); describe('Transactions Signatures and Rejection', function() { this.timeout(5000); it('Send and broadcast in 1-1 wallet', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 1, 1); var opts = { amount: 10000000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; clients[0].sendTxProposal(opts, function(err, txp) { should.not.exist(err); txp.requiredRejections.should.equal(1); txp.requiredSignatures.should.equal(1); txp.status.should.equal('pending'); txp.changeAddress.path.should.equal('m/2147483647/1/0'); clients[0].signTxProposal(txp, function(err, txp) { should.not.exist(err); txp.status.should.equal('accepted'); clients[0].broadcastTxProposal(txp, function(err, txp) { should.not.exist(err); txp.status.should.equal('broadcasted'); txp.txid.should.equal((new Bitcore.Transaction(blockchainExplorerMock.lastBroadcasted)).id); done(); }); }); }); }); }); }); it('Send and broadcast in 2-3 wallet', function(done) { helpers.createAndJoinWallet(clients, 2, 3, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 10, 2); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; clients[0].sendTxProposal(opts, function(err, txp) { should.not.exist(err); clients[0].getStatus(function(err, st) { should.not.exist(err); var txp = st.pendingTxps[0]; txp.status.should.equal('pending'); txp.requiredRejections.should.equal(2); txp.requiredSignatures.should.equal(2); var w = st.wallet; w.copayers.length.should.equal(3); w.status.should.equal('complete'); var b = st.balance; b.totalAmount.should.equal(1000000000); b.lockedAmount.should.equal(1000000000); clients[0].signTxProposal(txp, function(err, txp) { should.not.exist(err, err); txp.status.should.equal('pending'); clients[1].signTxProposal(txp, function(err, txp) { should.not.exist(err); txp.status.should.equal('accepted'); clients[1].broadcastTxProposal(txp, function(err, txp) { txp.status.should.equal('broadcasted'); txp.txid.should.equal((new Bitcore.Transaction(blockchainExplorerMock.lastBroadcasted)).id); done(); }); }); }); }); }); }); }); }); it.skip('Send, reject actions in 2-3 wallet much have correct copayerNames', function(done) { helpers.createAndJoinWallet(clients, 2, 3, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); blockchainExplorerMock.setUtxo(x0, 10, 2); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; clients[0].sendTxProposal(opts, function(err, txp) { should.not.exist(err); clients[0].rejectTxProposal(txp, 'wont sign', function(err, txp) { should.not.exist(err, err); clients[1].signTxProposal(txp, function(err, txp) { should.not.exist(err); done(); }); }); }); }); }); }); it('Send, reject, 2 signs and broadcast in 2-3 wallet', function(done) { helpers.createAndJoinWallet(clients, 2, 3, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 10, 2); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; clients[0].sendTxProposal(opts, function(err, txp) { should.not.exist(err); txp.status.should.equal('pending'); txp.requiredRejections.should.equal(2); txp.requiredSignatures.should.equal(2); clients[0].rejectTxProposal(txp, 'wont sign', function(err, txp) { should.not.exist(err, err); txp.status.should.equal('pending'); clients[1].signTxProposal(txp, function(err, txp) { should.not.exist(err); clients[2].signTxProposal(txp, function(err, txp) { should.not.exist(err); txp.status.should.equal('accepted'); clients[2].broadcastTxProposal(txp, function(err, txp) { txp.status.should.equal('broadcasted'); txp.txid.should.equal((new Bitcore.Transaction(blockchainExplorerMock.lastBroadcasted)).id); done(); }); }); }); }); }); }); }); }); it('Send, reject in 3-4 wallet', function(done) { helpers.createAndJoinWallet(clients, 3, 4, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 10, 3); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; clients[0].sendTxProposal(opts, function(err, txp) { should.not.exist(err); txp.status.should.equal('pending'); txp.requiredRejections.should.equal(2); txp.requiredSignatures.should.equal(3); clients[0].rejectTxProposal(txp, 'wont sign', function(err, txp) { should.not.exist(err, err); txp.status.should.equal('pending'); clients[1].signTxProposal(txp, function(err, txp) { should.not.exist(err); txp.status.should.equal('pending'); clients[2].rejectTxProposal(txp, 'me neither', function(err, txp) { should.not.exist(err); txp.status.should.equal('rejected'); done(); }); }); }); }); }); }); }); it('Should not allow to reject or sign twice', function(done) { helpers.createAndJoinWallet(clients, 2, 3, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); blockchainExplorerMock.setUtxo(x0, 10, 2); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; clients[0].sendTxProposal(opts, function(err, txp) { should.not.exist(err); txp.status.should.equal('pending'); txp.requiredRejections.should.equal(2); txp.requiredSignatures.should.equal(2); clients[0].signTxProposal(txp, function(err, txp) { should.not.exist(err); txp.status.should.equal('pending'); clients[0].signTxProposal(txp, function(err) { should.exist(err); err.code.should.contain('CVOTED'); clients[1].rejectTxProposal(txp, 'xx', function(err, txp) { should.not.exist(err); clients[1].rejectTxProposal(txp, 'xx', function(err) { should.exist(err); err.code.should.contain('CVOTED'); done(); }); }); }); }); }); }); }); }); }); describe('Transaction history', function() { it('should get transaction history', function(done) { blockchainExplorerMock.setHistory(TestData.history); helpers.createAndJoinWallet(clients, 1, 1, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); clients[0].getTxHistory({}, function(err, txs) { should.not.exist(err); should.exist(txs); txs.length.should.equal(2); done(); }); }); }); }); it('should get empty transaction history when there are no addresses', function(done) { blockchainExplorerMock.setHistory(TestData.history); helpers.createAndJoinWallet(clients, 1, 1, function(w) { clients[0].getTxHistory({}, function(err, txs) { should.not.exist(err); should.exist(txs); txs.length.should.equal(0); done(); }); }); }); it('should get transaction history decorated with proposal', function(done) { async.waterfall([ function(next) { helpers.createAndJoinWallet(clients, 2, 3, function(w) { clients[0].createAddress(function(err, address) { should.not.exist(err); should.exist(address); next(null, address); }); }); }, function(address, next) { blockchainExplorerMock.setUtxo(address, 10, 2); var opts = { amount: 10000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'some message', }; clients[0].sendTxProposal(opts, function(err, txp) { should.not.exist(err); clients[1].rejectTxProposal(txp, 'some reason', function(err, txp) { should.not.exist(err); clients[2].signTxProposal(txp, function(err, txp) { should.not.exist(err); clients[0].signTxProposal(txp, function(err, txp) { should.not.exist(err); txp.status.should.equal('accepted'); clients[0].broadcastTxProposal(txp, function(err, txp) { should.not.exist(err); txp.status.should.equal('broadcasted'); next(null, txp); }); }); }); }); }); }, function(txp, next) { var history = _.cloneDeep(TestData.history); history[0].txid = txp.txid; blockchainExplorerMock.setHistory(history); clients[0].getTxHistory({}, function(err, txs) { should.not.exist(err); should.exist(txs); txs.length.should.equal(2); var decorated = _.find(txs, { txid: txp.txid }); should.exist(decorated); decorated.proposalId.should.equal(txp.id); decorated.message.should.equal('some message'); decorated.actions.length.should.equal(3); var rejection = _.find(decorated.actions, { type: 'reject' }); should.exist(rejection); rejection.comment.should.equal('some reason'); done(); }); } ]); }); it('should get paginated transaction history', function(done) { var testCases = [{ opts: {}, expected: [20, 10] }, { opts: { skip: 1, }, expected: [10] }, { opts: { limit: 1, }, expected: [20] }, { opts: { skip: 3, }, expected: [] }, { opts: { skip: 1, limit: 10, }, expected: [10] }, ]; blockchainExplorerMock.setHistory(TestData.history); helpers.createAndJoinWallet(clients, 1, 1, function(w) { clients[0].createAddress(function(err, x0) { should.not.exist(err); should.exist(x0.address); async.each(testCases, function(testCase, next) { clients[0].getTxHistory(testCase.opts, function(err, txs) { should.not.exist(err); should.exist(txs); var times = _.pluck(txs, 'time'); times.should.deep.equal(testCase.expected); next(); }); }, done); }); }); }); }); describe('Mobility, backup & restore', function() { describe('Export & Import', function() { describe('Success', function() { var address, importedClient; beforeEach(function(done) { importedClient = null; helpers.createAndJoinWallet(clients, 1, 1, function() { clients[0].createAddress(function(err, addr) { should.not.exist(err); should.exist(addr.address); address = addr.address; done(); }); }); }); afterEach(function(done) { importedClient.getMainAddresses({}, function(err, list) { should.not.exist(err); should.exist(list); list.length.should.equal(1); list[0].address.should.equal(address); done(); }); }); it('should export & import', function() { var exported = clients[0].export(); importedClient = helpers.newClient(app); importedClient.import(exported); }); it('should export & import compressed', function(done) { var walletId = clients[0].credentials.walletId; var walletName = clients[0].credentials.walletName; var copayerName = clients[0].credentials.copayerName; var exported = clients[0].export({ compressed: true }); importedClient = helpers.newClient(app); importedClient.import(exported, { compressed: true }); importedClient.openWallet(function(err) { should.not.exist(err); importedClient.credentials.walletId.should.equal(walletId); importedClient.credentials.walletName.should.equal(walletName); importedClient.credentials.copayerName.should.equal(copayerName); done(); }); }); it('should export without signing rights', function() { clients[0].canSign().should.be.true; var exported = clients[0].export({ noSign: true, }); importedClient = helpers.newClient(app); importedClient.import(exported); importedClient.canSign().should.be.false; }); }); describe('Fail', function() { it.skip('should fail to export compressed & import uncompressed', function() {}); it.skip('should fail to export uncompressed & import compressed', function() {}); }); }); describe('Recovery', function() { it('should be able to regain access to a 1-1 wallet with just the xPriv', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function() { var xpriv = clients[0].credentials.xPrivKey; var walletName = clients[0].credentials.walletName; var copayerName = clients[0].credentials.copayerName; clients[0].createAddress(function(err, addr) { should.not.exist(err); should.exist(addr); var recoveryClient = helpers.newClient(app); recoveryClient.seedFromExtendedPrivateKey(xpriv); recoveryClient.openWallet(function(err) { should.not.exist(err); recoveryClient.credentials.walletName.should.equal(walletName); recoveryClient.credentials.copayerName.should.equal(copayerName); recoveryClient.getMainAddresses({}, function(err, list) { should.not.exist(err); should.exist(list); list[0].address.should.equal(addr.address); done(); }); }); }); }); }); it('should be able to recreate wallet', function(done) { helpers.createAndJoinWallet(clients, 2, 2, function() { clients[0].createAddress(function(err, addr) { should.not.exist(err); should.exist(addr); var storage = new Storage({ db: helpers.newDb(), }); var newApp; var expressApp = new ExpressApp(); expressApp.start({ storage: storage, blockchainExplorer: blockchainExplorerMock, disableLogs: true, }, function() { newApp = expressApp.app; var oldPKR = _.clone(clients[0].credentials.publicKeyRing); var recoveryClient = helpers.newClient(newApp); recoveryClient.import(clients[0].export()); recoveryClient.getStatus(function(err, status) { should.exist(err); err.code.should.equal('NOTAUTHORIZED'); recoveryClient.recreateWallet(function(err) { should.not.exist(err); recoveryClient.getStatus(function(err, status) { should.not.exist(err); _.difference(_.pluck(status.wallet.copayers, 'name'), ['creator', 'copayer 1']).length.should.equal(0); recoveryClient.createAddress(function(err, addr2) { should.not.exist(err); should.exist(addr2); addr2.address.should.equal(addr.address); addr2.path.should.equal(addr.path); var recoveryClient2 = helpers.newClient(newApp); recoveryClient2.import(clients[1].export()); recoveryClient2.getStatus(function(err, status) { should.not.exist(err); done(); }); }); }); }); }); }); }); }); }); it('should be able to recover funds from recreated wallet', function(done) { this.timeout(10000); helpers.createAndJoinWallet(clients, 2, 2, function() { clients[0].createAddress(function(err, addr) { should.not.exist(err); should.exist(addr); blockchainExplorerMock.setUtxo(addr, 1, 2); var storage = new Storage({ db: helpers.newDb(), }); var newApp; var expressApp = new ExpressApp(); expressApp.start({ storage: storage, blockchainExplorer: blockchainExplorerMock, disableLogs: true, }, function() { newApp = expressApp.app; var recoveryClient = helpers.newClient(newApp); recoveryClient.import(clients[0].export()); recoveryClient.getStatus(function(err, status) { should.exist(err); err.code.should.equal('NOTAUTHORIZED'); recoveryClient.recreateWallet(function(err) { should.not.exist(err); recoveryClient.getStatus(function(err, status) { should.not.exist(err); recoveryClient.startScan({}, function(err) { should.not.exist(err); var balance = 0; async.whilst(function() { return balance == 0; }, function(next) { setTimeout(function() { recoveryClient.getBalance(function(err, b) { balance = b.totalAmount; next(err); }); }, 200); }, function(err) { should.not.exist(err); balance.should.equal(1e8); done(); }); }); }); }); }); }); }); }); }); it('should be able call recreate wallet twice', function(done) { helpers.createAndJoinWallet(clients, 2, 2, function() { clients[0].createAddress(function(err, addr) { should.not.exist(err); should.exist(addr); var storage = new Storage({ db: helpers.newDb(), }); var newApp; var expressApp = new ExpressApp(); expressApp.start({ storage: storage, blockchainExplorer: blockchainExplorerMock, disableLogs: true, }, function() { newApp = expressApp.app; var oldPKR = _.clone(clients[0].credentials.publicKeyRing); var recoveryClient = helpers.newClient(newApp); recoveryClient.import(clients[0].export()); recoveryClient.getStatus(function(err, status) { should.exist(err); err.code.should.equal('NOTAUTHORIZED'); recoveryClient.recreateWallet(function(err) { should.not.exist(err); recoveryClient.recreateWallet(function(err) { should.not.exist(err); recoveryClient.getStatus(function(err, status) { should.not.exist(err); _.difference(_.pluck(status.wallet.copayers, 'name'), ['creator', 'copayer 1']).length.should.equal(0); recoveryClient.createAddress(function(err, addr2) { should.not.exist(err); should.exist(addr2); addr2.address.should.equal(addr.address); addr2.path.should.equal(addr.path); var recoveryClient2 = helpers.newClient(newApp); recoveryClient2.import(clients[1].export()); recoveryClient2.getStatus(function(err, status) { should.not.exist(err); done(); }); }); }); }); }); }); }); }); }); }); }); }); describe('Air gapped related flows', function() { it('should create wallet in proxy from airgapped', function(done) { var airgapped = new Client(); airgapped.seedFromRandom('testnet'); var exported = airgapped.export({ noSign: true }); var proxy = helpers.newClient(app); proxy.import(exported); should.not.exist(proxy.credentials.xPrivKey); var seedSpy = sinon.spy(proxy, 'seedFromRandom'); proxy.createWallet('wallet name', 'creator', 1, 1, { network: 'testnet' }, function(err) { should.not.exist(err); seedSpy.called.should.be.false; proxy.getStatus(function(err, status) { should.not.exist(err); status.wallet.name.should.equal('wallet name'); done(); }); }); }); it('should fail to create wallet in proxy from airgapped when networks do not match', function(done) { var airgapped = new Client(); airgapped.seedFromRandom('testnet'); var exported = airgapped.export({ noSign: true }); var proxy = helpers.newClient(app); proxy.import(exported); should.not.exist(proxy.credentials.xPrivKey); var seedSpy = sinon.spy(proxy, 'seedFromRandom'); should.not.exist(proxy.credentials.xPrivKey); proxy.createWallet('wallet name', 'creator', 1, 1, { network: 'livenet' }, function(err) { should.exist(err); err.message.should.equal('Existing keys were created for a different network'); done(); }); }); it('should be able to sign from airgapped client and broadcast from proxy', function(done) { var airgapped = new Client(); airgapped.seedFromRandom('testnet'); var exported = airgapped.export({ noSign: true }); var proxy = helpers.newClient(app); proxy.import(exported); should.not.exist(proxy.credentials.xPrivKey); async.waterfall([ function(next) { proxy.createWallet('wallet name', 'creator', 1, 1, { network: 'testnet' }, function(err) { should.not.exist(err); proxy.createAddress(function(err, address) { should.not.exist(err); should.exist(address.address); blockchainExplorerMock.setUtxo(address, 1, 1); var opts = { amount: 1200000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; proxy.sendTxProposal(opts, next); }); }); }, function(txp, next) { should.exist(txp); proxy.signTxProposal(txp, function(err, txp) { should.exist(err); should.not.exist(txp); err.message.should.equal('You do not have the required keys to sign transactions'); next(null, txp); }); }, function(txp, next) { proxy.getTxProposals({ forAirGapped: true }, next); }, function(bundle, next) { var signatures = airgapped.signTxProposalFromAirGapped(bundle.txps[0], bundle.encryptedPkr, bundle.m, bundle.n); next(null, signatures); }, function(signatures, next) { proxy.getTxProposals({}, function(err, txps) { should.not.exist(err); var txp = txps[0]; txp.signatures = signatures; async.each(txps, function(txp, cb) { proxy.signTxProposal(txp, function(err, txp) { should.not.exist(err); proxy.broadcastTxProposal(txp, function(err, txp) { should.not.exist(err); txp.status.should.equal('broadcasted'); should.exist(txp.txid); cb(); }); }); }, function(err) { next(err); }); }); }, ], function(err) { should.not.exist(err); done(); } ); }); describe('Failure and tampering', function() { var airgapped, proxy, bundle; beforeEach(function(done) { airgapped = new Client(); airgapped.seedFromRandom('testnet'); var exported = airgapped.export({ noSign: true }); proxy = helpers.newClient(app); proxy.import(exported); should.not.exist(proxy.credentials.xPrivKey); async.waterfall([ function(next) { proxy.createWallet('wallet name', 'creator', 1, 1, { network: 'testnet' }, function(err) { should.not.exist(err); proxy.createAddress(function(err, address) { should.not.exist(err); should.exist(address.address); blockchainExplorerMock.setUtxo(address, 1, 1); var opts = { amount: 1200000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; proxy.sendTxProposal(opts, next); }); }); }, function(txp, next) { proxy.getTxProposals({ forAirGapped: true }, function(err, result) { should.not.exist(err); bundle = result; next(); }); }, ], function(err) { should.not.exist(err); done(); } ); }); it('should fail to sign from airgapped client when there is no extended private key', function(done) { delete airgapped.credentials.xPrivKey; (function() { airgapped.signTxProposalFromAirGapped(bundle.txps[0], bundle.encryptedPkr, bundle.m, bundle.n); }).should.throw(Error, 'You do not have the required keys to sign transactions'); done(); }); it('should fail gracefully when PKR cannot be decrypted in airgapped client', function(done) { bundle.encryptedPkr = 'dummy'; (function() { airgapped.signTxProposalFromAirGapped(bundle.txps[0], bundle.encryptedPkr, bundle.m, bundle.n); }).should.throw(Error, 'Could not decrypt public key ring'); done(); }); it('should be able to detect invalid or tampered PKR when signing on airgapped client', function(done) { (function() { airgapped.signTxProposalFromAirGapped(bundle.txps[0], bundle.encryptedPkr, bundle.m, 2); }).should.throw(Error, 'Invalid public key ring'); done(); }); it('should be able to detect tampered proposal when signing on airgapped client', function(done) { bundle.txps[0].encryptedMessage = 'tampered message'; (function() { airgapped.signTxProposalFromAirGapped(bundle.txps[0], bundle.encryptedPkr, bundle.m, bundle.n); }).should.throw(Error, 'Fake transaction proposal'); done(); }); it('should be able to detect tampered change address when signing on airgapped client', function(done) { bundle.txps[0].changeAddress.address = 'mqNkvNuhzZKeXYNRZ1bdj55smmW3acr6K7'; (function() { airgapped.signTxProposalFromAirGapped(bundle.txps[0], bundle.encryptedPkr, bundle.m, bundle.n); }).should.throw(Error, 'Fake transaction proposal'); done(); }); }); }); describe('Legacy Copay Import', function() { it('Should get wallets from profile', function(done) { var t = ImportData.copayers[0]; var c = helpers.newClient(app); var ids = c.getWalletIdsFromOldCopay(t.username, t.password, t.ls['profile::4872dd8b2ceaa54f922e8e6ba6a8eaa77b488721']); ids.should.deep.equal([ '8f197244e661f4d0', '4d32f0737a05f072', 'e2c2d72024979ded', '7065a73486c8cb5d' ]); done(); }); it('Should import a 1-1 wallet', function(done) { var t = ImportData.copayers[0]; var c = helpers.newClient(app); c.createWalletFromOldCopay(t.username, t.password, t.ls['wallet::e2c2d72024979ded'], function(err) { should.not.exist(err); c.credentials.m.should.equal(1); c.credentials.n.should.equal(1); c.createAddress(function(err, x0) { // This is the first 'shared' address, created automatically // by old copay x0.address.should.equal('2N3w8sJUyAXCQirqNsTayWr7pWADFNdncmf'); c.getStatus(function(err, status) { should.not.exist(err); status.wallet.status.should.equal('complete'); c.credentials.walletId.should.equal('e2c2d72024979ded'); c.credentials.walletPrivKey.should.equal('c3463113c6e1d0fc2f2bd520f7d9d62f8e1fdcdd96005254571c64902aeb1648'); c.credentials.sharedEncryptingKey.should.equal('x3D/7QHa4PkKMbSXEvXwaw=='); // TODO? // bal1.totalAmount.should.equal(18979980); done(); }); }); }); }); it('Should to import the same wallet twice with different clients', function(done) { var t = ImportData.copayers[0]; var c = helpers.newClient(app); c.createWalletFromOldCopay(t.username, t.password, t.ls['wallet::4d32f0737a05f072'], function(err) { should.not.exist(err); c.getStatus(function(err, status) { should.not.exist(err); status.wallet.status.should.equal('complete'); c.credentials.walletId.should.equal('4d32f0737a05f072'); var c2 = helpers.newClient(app); c2.createWalletFromOldCopay(t.username, t.password, t.ls['wallet::4d32f0737a05f072'], function(err) { should.not.exist(err); c2.getStatus(function(err, status) { should.not.exist(err); status.wallet.status.should.equal('complete'); c2.credentials.walletId.should.equal('4d32f0737a05f072'); done(); }); }); }); }); }); it('Should not fail when importing the same wallet twice, same copayer', function(done) { var t = ImportData.copayers[0]; var c = helpers.newClient(app); c.createWalletFromOldCopay(t.username, t.password, t.ls['wallet::4d32f0737a05f072'], function(err) { should.not.exist(err); c.getStatus(function(err, status) { should.not.exist(err); status.wallet.status.should.equal('complete'); c.credentials.walletId.should.equal('4d32f0737a05f072'); c.createWalletFromOldCopay(t.username, t.password, t.ls['wallet::4d32f0737a05f072'], function(err) { should.not.exist(err); done(); }); }); }); }); it('Should import and complete 2-2 wallet from 2 copayers, and create addresses', function(done) { var t = ImportData.copayers[0]; var c = helpers.newClient(app); c.createWalletFromOldCopay(t.username, t.password, t.ls['wallet::4d32f0737a05f072'], function(err) { should.not.exist(err); c.getStatus(function(err, status) { should.not.exist(err); status.wallet.status.should.equal('complete'); c.credentials.sharedEncryptingKey.should.equal('Ou2j4kq3z1w4yTr9YybVxg=='); var counts = _.countBy(status.wallet.publicKeyRing, 'isTemporaryRequestKey'); counts[false].should.equal(1); counts[true].should.equal(1); var t2 = ImportData.copayers[1]; var c2 = helpers.newClient(app); c2.createWalletFromOldCopay(t2.username, t2.password, t2.ls['wallet::4d32f0737a05f072'], function(err) { should.not.exist(err); c2.credentials.sharedEncryptingKey.should.equal('Ou2j4kq3z1w4yTr9YybVxg=='); // This should pull the non-temporary keys c2.getStatus(function(err, status) { should.not.exist(err); status.wallet.status.should.equal('complete'); c2.credentials.hasTemporaryRequestKeys().should.equal(false); c2.createAddress(function(err, x0) { x0.address.should.be.equal('2Mv1DHpozzZ9fup2nZ1kmdRXoNnDJ8b1JF2'); c.createAddress(function(err, x0) { x0.address.should.be.equal('2N2dZ1HogpxHVKv3CD2R4WrhWRwqZtpDc2M'); done(); }); }); }); }); }); }); }); it('Should import and complete 2-3 wallet from 2 copayers, and create addresses', function(done) { var w = 'wallet::7065a73486c8cb5d'; var key = 'fS4HhoRd25KJY4VpNpO1jg=='; var t = ImportData.copayers[0]; var c = helpers.newClient(app); c.createWalletFromOldCopay(t.username, t.password, t.ls[w], function(err) { should.not.exist(err); c.getStatus(function(err, status) { should.not.exist(err); status.wallet.status.should.equal('complete'); c.credentials.sharedEncryptingKey.should.equal(key); var counts = _.countBy(status.wallet.publicKeyRing, 'isTemporaryRequestKey'); counts[false].should.equal(1); counts[true].should.equal(2); status.wallet.publicKeyRing[1].isTemporaryRequestKey.should.equal(true); var t2 = ImportData.copayers[1]; var c2 = helpers.newClient(app); c2.createWalletFromOldCopay(t2.username, t2.password, t2.ls[w], function(err) { should.not.exist(err); c2.credentials.sharedEncryptingKey.should.equal(key); c2.getStatus(function(err, status) { should.not.exist(err); status.wallet.status.should.equal('complete'); c2.credentials.hasTemporaryRequestKeys().should.equal(true); var counts = _.countBy(status.wallet.publicKeyRing, 'isTemporaryRequestKey'); counts[false].should.equal(2); counts[true].should.equal(1); var t3 = ImportData.copayers[2]; var c3 = helpers.newClient(app); c3.createWalletFromOldCopay(t3.username, t3.password, t3.ls[w], function(err) { should.not.exist(err); c3.credentials.sharedEncryptingKey.should.equal(key); // This should pull the non-temporary keys c3.getStatus(function(err, status) { should.not.exist(err); status.wallet.status.should.equal('complete'); c3.credentials.hasTemporaryRequestKeys().should.equal(false); var counts = _.countBy(status.wallet.publicKeyRing, 'isTemporaryRequestKey'); counts[false].should.equal(3); done(); }); }); }); }); }); }); }); it('Should import a 2-3 wallet from 2 copayers, and recreate it, and then on the recreated other copayers should be able to access', function(done) { var w = 'wallet::7065a73486c8cb5d'; var key = 'fS4HhoRd25KJY4VpNpO1jg=='; var t = ImportData.copayers[0]; var c = helpers.newClient(app); c.createWalletFromOldCopay(t.username, t.password, t.ls[w], function(err) { should.not.exist(err); var t2 = ImportData.copayers[1]; var c2 = helpers.newClient(app); c2.createWalletFromOldCopay(t2.username, t2.password, t2.ls[w], function(err) { should.not.exist(err); // New BWS server... var storage = new Storage({ db: helpers.newDb(), }); var newApp; var expressApp = new ExpressApp(); expressApp.start({ storage: storage, blockchainExplorer: blockchainExplorerMock, disableLogs: true, }, function() { newApp = expressApp.app; }); var recoveryClient = helpers.newClient(newApp); recoveryClient.import(c.export()); recoveryClient.recreateWallet(function(err) { should.not.exist(err); recoveryClient.getStatus(function(err, status) { should.not.exist(err); _.pluck(status.wallet.copayers, 'name').should.deep.equal(['123', '234', '345']); var t2 = ImportData.copayers[1]; var c2p = helpers.newClient(newApp); c2p.createWalletFromOldCopay(t2.username, t2.password, t2.ls[w], function(err) { should.not.exist(err); c2p.getStatus(function(err, status) { should.not.exist(err); _.pluck(status.wallet.copayers, 'name').should.deep.equal(['123', '234', '345']); done(); }); }); }); }); }); }); }); }); describe('Private key encryption', function() { var password = 'jesuissatoshi'; var c1, c2; var importedClient; beforeEach(function(done) { c1 = clients[1]; clients[1].createWallet('wallet name', 'creator', 1, 1, { network: 'testnet', }, function() { clients[1].setPrivateKeyEncryption(password); clients[1].lock(); done(); }); }); it('should not lock if not encrypted', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function() { (function() { clients[0].lock(); }).should.throw('encrypted'); done(); }); }); it('should return priv key is not encrypted', function(done) { helpers.createAndJoinWallet(clients, 1, 1, function() { clients[0].isPrivKeyEncrypted().should.equal(false); clients[0].hasPrivKeyEncrypted().should.equal(false); done(); }); }); it('should return priv key is encrypted', function() { c1.isPrivKeyEncrypted().should.equal(true); c1.hasPrivKeyEncrypted().should.equal(true); }); it('should prevent to reencrypt the priv key', function() { (function() { c1.setPrivateKeyEncryption('pepe'); }).should.throw('Already'); }); it('should prevent to disable priv key encryption when locked', function() { (function() { c1.disablePrivateKeyEncryption(); }).should.throw('locked'); c1.isPrivKeyEncrypted().should.equal(true); c1.hasPrivKeyEncrypted().should.equal(true); }); it('should allow to disable priv key encryption when unlocked', function() { c1.unlock(password); c1.disablePrivateKeyEncryption(); c1.isPrivKeyEncrypted().should.equal(false); c1.hasPrivKeyEncrypted().should.equal(false); }); it('should prevent to encrypt airgapped\'s proxy credentials', function() { var airgapped = new Client(); airgapped.seedFromRandom('testnet'); var exported = airgapped.export({ noSign: true }); var proxy = helpers.newClient(app); proxy.import(exported); should.not.exist(proxy.credentials.xPrivKey); (function() { proxy.setPrivateKeyEncryption('pepe'); }).should.throw('No private key'); }); it('should lock and unlock', function() { c1.unlock(password); var xpriv = c1.credentials.xPrivKey; c1.isPrivKeyEncrypted().should.equal(false); c1.hasPrivKeyEncrypted().should.equal(true); c1.lock(); c1.isPrivKeyEncrypted().should.equal(true); c1.hasPrivKeyEncrypted().should.equal(true); var str = JSON.stringify(c1); str.indexOf(xpriv).should.equal(-1); }); it('should fail to unlock with wrong password', function() { (function() { c1.unlock('hola') }).should.throw('Could not unlock'); }); it('should export & import uncompressed, locked', function(done) { var walletId = c1.credentials.walletId; var walletName = c1.credentials.walletName; var copayerName = c1.credentials.copayerName; var exported = c1.export({}); importedClient = helpers.newClient(app); importedClient.import(exported, {}); importedClient.openWallet(function(err) { should.not.exist(err); importedClient.credentials.walletId.should.equal(walletId); importedClient.credentials.walletName.should.equal(walletName); importedClient.credentials.copayerName.should.equal(copayerName); importedClient.isPrivKeyEncrypted().should.equal(true); importedClient.hasPrivKeyEncrypted().should.equal(true); importedClient.unlock(password); importedClient.isPrivKeyEncrypted().should.equal(false); importedClient.hasPrivKeyEncrypted().should.equal(true); done(); }); }); it('should export & import compressed, locked', function(done) { var walletId = c1.credentials.walletId; var walletName = c1.credentials.walletName; var copayerName = c1.credentials.copayerName; var exported = c1.export({ compressed: true }); importedClient = helpers.newClient(app); importedClient.import(exported, { compressed: true, password: password, }); importedClient.openWallet(function(err) { should.not.exist(err); importedClient.credentials.walletId.should.equal(walletId); importedClient.credentials.walletName.should.equal(walletName); importedClient.credentials.copayerName.should.equal(copayerName); importedClient.isPrivKeyEncrypted().should.equal(true); importedClient.hasPrivKeyEncrypted().should.equal(true); done(); }); }); it('should not sign when locked', function(done) { c1.createAddress(function(err, x0) { should.not.exist(err); blockchainExplorerMock.setUtxo(x0, 1, 1); var opts = { amount: 10000000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; c1.sendTxProposal(opts, function(err, txp) { should.not.exist(err); c1.signTxProposal(txp, function(err) { err.message.should.contain('encrypted'); done(); }); }); }); }); it('should sign when unlocked', function(done) { c1.createAddress(function(err, x0) { should.not.exist(err); blockchainExplorerMock.setUtxo(x0, 1, 1); var opts = { amount: 10000000, toAddress: 'n2TBMPzPECGUfcT2EByiTJ12TPZkhN2mN5', message: 'hello 1-1', }; c1.sendTxProposal(opts, function(err, txp) { should.not.exist(err); c1.unlock(password); c1.signTxProposal(txp, function(err) { should.not.exist(err); c1.lock(); c1.isPrivKeyEncrypted().should.equal(true); c1.hasPrivKeyEncrypted().should.equal(true); done(); }); }); }); }); }); });
describe('hide', function() { it('should hide a given element', function() { var el = $_(document.body).append('<div></div>').lastChild() el.hide() expect(el.element.offsetWidth).toEqual(0) expect(el.element.style.$_savedDisplay).toEqual('block') el.element.parentNode.removeChild(el.element) }) it('should silently do nothing for an element with inline none display', function() { var el = $_(document.body).append('<div style=display:none></div>').lastChild() expect(el.element.offsetWidth).toEqual(0) el.hide() expect(el.element.offsetWidth).toEqual(0) el.element.parentNode.removeChild(el.element) }) it('should silently do nothing for an element hidden already', function() { var el = $_(document.body).append('<div></div>').lastChild() el.hide() expect(el.element.offsetWidth).toEqual(0) expect(el.element.style.$_savedDisplay).toEqual('block') el.hide() expect(el.element.offsetWidth).toEqual(0) expect(el.element.style.$_savedDisplay).toEqual('block') el.element.parentNode.removeChild(el.element) }) }) describe('show', function() { it('should show a hidden element', function() { var el = $_(document.body).append('<div style=display:none></div>').lastChild() el.show() expect(el.element.offsetWidth).not.toEqual(0) el.element.parentNode.removeChild(el.element) }) it('should show a element hidden using a css class', function() { var el = $_(document.body).append('<div class=hidden></div>').lastChild() expect(el.element.offsetWidth).toEqual(0) el.show() expect(el.element.offsetWidth).not.toEqual(0) el.element.parentNode.removeChild(el.element) }) it('should silently do nothing for an element with implicit non-none display', function() { var el = $_(document.body).append('<div></div>').lastChild() var width = el.element.offsetWidth el.show() expect(el.element.offsetWidth).not.toEqual(0) expect(el.element.offsetWidth).toEqual(width) el.element.parentNode.removeChild(el.element) }) it('should silently do nothing for an element already shown', function() { var el = $_(document.body).append('<div style=display:none></div>').lastChild() el.show() expect(el.element.offsetWidth).not.toEqual(0) el.show() expect(el.element.offsetWidth).not.toEqual(0) el.element.parentNode.removeChild(el.element) }) it('should show after hiding', function() { var el = $_(document.body).append('<div></div>').lastChild() var width = el.element.offsetWidth el.hide().show() expect(width).not.toEqual(0) expect(el.element.offsetWidth).toEqual(width) expect(el.element.style.$_savedDisplay).toEqual('block') el.element.parentNode.removeChild(el.element) }) })
/** * * UTF-8 data encode / decode * http://www.webtoolkit.info/ * **/ var Utf8 = { // public method for url encoding encode : function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // public method for url decoding decode : function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } }
/** * * @param {Array<String>} midiMessages * @param {TrackBank} trackBank * @constructor */ function TrackSelectorButtons(midiMessages, trackBank) { ControlGroup.call(this); this.trackBank = trackBank; this._previous = this.addControl(new Button(midiMessages.previous)).on('down', this.previous.bind(this)); this._next = this.addControl(new Button(midiMessages.next)).on('down', this.next.bind(this)); this.trackBank.addCanScrollTracksUpObserver(this._previous.value.setInternal); this.trackBank.addCanScrollTracksDownObserver(this._next.value.setInternal); } util.inherits(TrackSelectorButtons, ControlGroup); TrackSelectorButtons.prototype.next = function () { this.trackBank.scrollTracksDown(); }; TrackSelectorButtons.prototype.previous = function () { this.trackBank.scrollTracksUp(); };
import React, { Component } from 'react'; export default class Header extends Component { render() { return ( <div className="blog-header"> <div className="container"> <h1 className="blog-title">The Bootstrap Blog</h1> <p className="lead blog-description">An example blog template built with Bootstrap.</p> </div> </div> ); } }
/* English/UK initialisation for the jQuery UI date picker plugin. */ /* Written by Stuart. */ jQuery(function ($) { $.datepicker.regional['en-EN'] = { closeText: 'Done', prevText: 'Prev', nextText: 'Next', currentText: 'Today', monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], weekHeader: 'Wk', dateFormat: 'dd/mm/yy', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: '' }; $.datepicker.setDefaults($.datepicker.regional['en-EN']); });
// ------------------------------------------------------------------------- // Kicks off the angularJS application // create the module and name it "mashupApp" // ------------------------------------------------------------------------- var mashupApp = angular.module('mashupApp', ['ngRoute', 'ui.bootstrap', 'ngSanitize', 'oc.lazyLoad']); // ------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------------- // This configures ocLazyLoadProvider and let's it know that some modules have already been // loaded. Without this the Menu dialog would not work because some directive was loaded twice. // https://github.com/ocombe/ocLazyLoad/issues/71 // ---------------------------------------------------------------------------------------------- angular.module('mashupApp').config(['$ocLazyLoadProvider', function ($ocLazyLoadProvider) { 'use strict'; $ocLazyLoadProvider.config({ loadedModules: ['ngRoute', 'ui.bootstrap', 'ngSanitize', 'oc.lazyLoad'] }); }]); // To disable $sce: mashupApp.config(['$sceProvider', function ($sceProvider) { 'use strict'; $sceProvider.enabled(false); }]);
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const vscode = require("vscode"); const child_process_1 = require("child_process"); const fs = require("fs"); const path = require("path"); const logger = require("../logger"); let gitPath; function getGitPath() { return __awaiter(this, void 0, void 0, function* () { if (gitPath !== undefined) { return Promise.resolve(gitPath); } return new Promise((resolve, reject) => { const gitPathConfig = vscode.workspace.getConfiguration('git').get('path'); if (typeof gitPathConfig === 'string' && gitPathConfig.length > 0) { if (fs.existsSync(gitPathConfig)) { logger.logInfo(`git path: ${gitPathConfig} - from vscode settings`); gitPath = gitPathConfig; resolve(gitPathConfig); return; } else { logger.logError(`git path: ${gitPathConfig} - from vscode settings in invalid`); } } if (process.platform !== 'win32') { logger.logInfo(`git path: using PATH environment variable`); gitPath = 'git'; resolve('git'); return; } else { // in Git for Windows, the recommendation is not to put git into the PATH. // Instead, there is an entry in the Registry. let regQueryInstallPath = (location, view) => { return new Promise((resolve, reject) => { let callback = function (error, stdout, stderr) { if (error && error.code !== 0) { error.stdout = stdout.toString(); error.stderr = stderr.toString(); reject(error); return; } let installPath = stdout.toString().match(/InstallPath\s+REG_SZ\s+([^\r\n]+)\s*\r?\n/i)[1]; if (installPath) { resolve(installPath + '\\bin\\git'); } else { reject(); } }; let viewArg = ''; switch (view) { case '64': viewArg = '/reg:64'; break; case '32': viewArg = '/reg:64'; break; default: break; } child_process_1.exec('reg query ' + location + ' ' + viewArg, callback); }); }; let queryChained = (locations) => { return new Promise((resolve, reject) => { if (locations.length === 0) { reject('None of the known git Registry keys were found'); return; } let location = locations[0]; regQueryInstallPath(location.key, location.view).then((location) => resolve(location), (error) => queryChained(locations.slice(1)).then((location) => resolve(location), (error) => reject(error))); }); }; queryChained([ { 'key': 'HKCU\\SOFTWARE\\GitForWindows', 'view': null }, { 'key': 'HKLM\\SOFTWARE\\GitForWindows', 'view': null }, { 'key': 'HKCU\\SOFTWARE\\GitForWindows', 'view': '64' }, { 'key': 'HKLM\\SOFTWARE\\GitForWindows', 'view': '64' }, { 'key': 'HKCU\\SOFTWARE\\GitForWindows', 'view': '32' }, { 'key': 'HKLM\\SOFTWARE\\GitForWindows', 'view': '32' } ]). then((path) => { logger.logInfo(`git path: ${path} - from registry`); gitPath = path; resolve(path); }, (error) => { logger.logInfo(`git path: falling back to PATH environment variable`); gitPath = 'git'; resolve('git'); }); } }); }); } exports.getGitPath = getGitPath; function getGitRepositoryPath(fileName) { return __awaiter(this, void 0, void 0, function* () { const gitPath = yield getGitPath(); return new Promise((resolve, reject) => { const directory = fs.existsSync(fileName) && fs.statSync(fileName).isDirectory() ? fileName : path.dirname(fileName); const options = { cwd: directory }; const args = ['rev-parse', '--show-toplevel']; logger.logInfo('git ' + args.join(' ')); let ls = child_process_1.spawn(gitPath, args, options); let repoPath = ''; let error = ''; ls.stdout.on('data', function (data) { repoPath += data + '\n'; }); ls.stderr.on('data', function (data) { error += data; }); ls.on('error', function (error) { logger.logError(error); reject(error); return; }); ls.on('close', function () { if (error.length > 0) { logger.logError(error); reject(error); return; } let repositoryPath = repoPath.trim(); if (!path.isAbsolute(repositoryPath)) { repositoryPath = path.join(path.dirname(fileName), repositoryPath); } logger.logInfo('git repo path: ' + repositoryPath); resolve(repositoryPath); }); }); }); } exports.getGitRepositoryPath = getGitRepositoryPath; function getGitBranch(repoPath) { return __awaiter(this, void 0, void 0, function* () { const gitPath = yield getGitPath(); return new Promise((resolve, reject) => { const options = { cwd: repoPath }; const args = ['rev-parse', '--abbrev-ref', 'HEAD']; let branch = ''; let error = ''; let ls = child_process_1.spawn(gitPath, args, options); ls.stdout.on('data', function (data) { branch += data.slice(0, -1); }); ls.stderr.on('data', function (data) { error += data; }); ls.on('error', function (error) { logger.logError(error); reject(error); return; }); ls.on('close', function () { resolve(branch); }); }); }); } exports.getGitBranch = getGitBranch; //# sourceMappingURL=gitPaths.js.map
var lgUtils = require('./core/lg-utilities'); module.exports = function lostMasonryColumnDecl(css, settings) { css.walkDecls('lost-masonry-column', function lostMasonryColumnFunction( decl ) { var declArr = []; var lostMasonryColumn; var lostMasonryColumnRounder = settings.rounder; var lostMasonryColumnFlexbox = settings.flexbox; var lostMasonryColumnGutter = settings.gutter; var lostMasonryColumnGutterUnit; function cloneAllBefore(props) { Object.keys(props).forEach(function traverseProps(prop) { decl.cloneBefore({ prop: prop, value: props[prop], }); }); } const sanitizedDecl = lgUtils.glueFractionMembers(decl.value); declArr = sanitizedDecl.split(' '); lostMasonryColumn = declArr[0]; if (declArr[1] !== undefined && declArr[1].search(/^\d/) !== -1) { lostMasonryColumnGutter = declArr[1]; } if (declArr.indexOf('flex') !== -1) { lostMasonryColumnFlexbox = 'flex'; } if (declArr.indexOf('no-flex') !== -1) { lostMasonryColumnFlexbox = 'no-flex'; } decl.parent.nodes.forEach(function lostMasonryColumnRounderFunction( declaration ) { if (declaration.prop === 'lost-masonry-column-rounder') { lostMasonryColumnRounder = declaration.value; declaration.remove(); } }); decl.parent.nodes.forEach(function lostMasonryColumnGutterFunction( declaration ) { if (declaration.prop === 'lost-masonry-column-gutter') { lostMasonryColumnGutter = declaration.value; declaration.remove(); } }); decl.parent.nodes.forEach(function lostMasonryColumnFlexboxFunction( declaration ) { if (declaration.prop === 'lost-masonry-column-flexbox') { if (declaration.value === 'flex') { lostMasonryColumnFlexbox = 'flex'; } declaration.remove(); } }); if (lostMasonryColumnGutter !== '0') { lostMasonryColumnGutterUnit = lostMasonryColumnGutter .match(/\D/g) .join(''); } else { lostMasonryColumnGutterUnit = ''; } if (lostMasonryColumnFlexbox === 'flex') { decl.cloneBefore({ prop: 'flex', value: '0 0 auto', }); } else { decl.cloneBefore({ prop: 'float', value: 'left', }); } if (lostMasonryColumnGutter !== '0') { cloneAllBefore({ width: 'calc(' + lostMasonryColumnRounder + '% * ' + lostMasonryColumn + ' - ' + lostMasonryColumnGutter + ')', 'margin-left': parseInt(lostMasonryColumnGutter, 10) / 2 + lostMasonryColumnGutterUnit, 'margin-right': parseInt(lostMasonryColumnGutter, 10) / 2 + lostMasonryColumnGutterUnit, }); } else { cloneAllBefore({ width: 'calc(' + lostMasonryColumnRounder + '% * ' + lostMasonryColumn + ')', 'margin-left': parseInt(lostMasonryColumnGutter, 10) / 2, 'margin-right': parseInt(lostMasonryColumnGutter, 10) / 2, }); } decl.remove(); }); };
import { join } from 'aurelia-path'; import deepExtend from './deep-extend'; import { WindowInfo } from './window-info'; var AureliaConfiguration = (function () { function AureliaConfiguration() { this.environment = 'default'; this.environments = null; this.directory = 'config'; this.config_file = 'config.json'; this.cascade_mode = true; this.base_path_mode = false; this._config_object = {}; this._config_merge_object = {}; this.window = new WindowInfo(); this.window.hostName = window.location.hostname; this.window.port = window.location.port; if (window.location.pathname && window.location.pathname.length > 1) { this.window.pathName = window.location.pathname; } } AureliaConfiguration.prototype.setDirectory = function (path) { this.directory = path; }; AureliaConfiguration.prototype.setConfig = function (name) { this.config_file = name; }; AureliaConfiguration.prototype.setEnvironment = function (environment) { this.environment = environment; }; AureliaConfiguration.prototype.setEnvironments = function (environments) { if (environments === void 0) { environments = null; } if (environments !== null) { this.environments = environments; this.check(); } }; AureliaConfiguration.prototype.setCascadeMode = function (bool) { if (bool === void 0) { bool = true; } this.cascade_mode = bool; }; AureliaConfiguration.prototype.setWindow = function (window) { this.window = window; }; AureliaConfiguration.prototype.setBasePathMode = function (bool) { if (bool === void 0) { bool = true; } this.base_path_mode = bool; }; Object.defineProperty(AureliaConfiguration.prototype, "obj", { get: function () { return this._config_object; }, enumerable: true, configurable: true }); Object.defineProperty(AureliaConfiguration.prototype, "config", { get: function () { return this.config_file; }, enumerable: true, configurable: true }); AureliaConfiguration.prototype.is = function (environment) { return (environment === this.environment); }; AureliaConfiguration.prototype.check = function () { var hostname = this.window.hostName; if (this.window.port != '') hostname += ':' + this.window.port; if (this.base_path_mode) hostname += this.window.pathName; if (this.environments) { for (var env in this.environments) { var hostnames = this.environments[env]; if (hostnames) { for (var _i = 0, hostnames_1 = hostnames; _i < hostnames_1.length; _i++) { var host = hostnames_1[_i]; if (hostname.search('(?:^|\W)' + host + '(?:$|\W)') !== -1) { this.setEnvironment(env); return; } } } } } }; AureliaConfiguration.prototype.environmentEnabled = function () { return (!(this.environment === 'default' || this.environment === '' || !this.environment)); }; AureliaConfiguration.prototype.environmentExists = function () { return this.environment in this.obj; }; AureliaConfiguration.prototype.getDictValue = function (baseObject, key) { var splitKey = key.split('.'); var currentObject = baseObject; splitKey.forEach(function (key) { if (currentObject[key]) { currentObject = currentObject[key]; } else { throw 'Key ' + key + ' not found'; } }); return currentObject; }; AureliaConfiguration.prototype.get = function (key, defaultValue) { if (defaultValue === void 0) { defaultValue = null; } var returnVal = defaultValue; if (key.indexOf('.') === -1) { if (!this.environmentEnabled()) { return this.obj[key] ? this.obj[key] : defaultValue; } if (this.environmentEnabled()) { if (this.environmentExists() && this.obj[this.environment][key]) { returnVal = this.obj[this.environment][key]; } else if (this.cascade_mode && this.obj[key]) { returnVal = this.obj[key]; } return returnVal; } } else { if (this.environmentEnabled()) { if (this.environmentExists()) { try { return this.getDictValue(this.obj[this.environment], key); } catch (_a) { if (this.cascade_mode) { try { return this.getDictValue(this.obj, key); } catch (_b) { } } } } } else { try { return this.getDictValue(this.obj, key); } catch (_c) { } } } return returnVal; }; AureliaConfiguration.prototype.set = function (key, val) { if (key.indexOf('.') === -1) { this.obj[key] = val; } else { var splitKey = key.split('.'); var parent_1 = splitKey[0]; var child = splitKey[1]; if (this.obj[parent_1] === undefined) { this.obj[parent_1] = {}; } this.obj[parent_1][child] = val; } }; AureliaConfiguration.prototype.merge = function (obj) { var currentConfig = this._config_object; this._config_object = deepExtend(currentConfig, obj); }; AureliaConfiguration.prototype.lazyMerge = function (obj) { var currentMergeConfig = (this._config_merge_object || {}); this._config_merge_object = deepExtend(currentMergeConfig, obj); }; AureliaConfiguration.prototype.setAll = function (obj) { this._config_object = obj; }; AureliaConfiguration.prototype.getAll = function () { return this.obj; }; AureliaConfiguration.prototype.loadConfig = function () { var _this = this; return this.loadConfigFile(join(this.directory, this.config), function (data) { return _this.setAll(data); }) .then(function () { if (_this._config_merge_object) { _this.merge(_this._config_merge_object); _this._config_merge_object = null; } }); }; AureliaConfiguration.prototype.loadConfigFile = function (path, action) { return new Promise(function (resolve, reject) { var pathClosure = path.toString(); var xhr = new XMLHttpRequest(); if (xhr.overrideMimeType) { xhr.overrideMimeType('application/json'); } xhr.open('GET', pathClosure, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { var data = JSON.parse(this.responseText); action(data); resolve(data); } }; xhr.onloadend = function () { if (xhr.status == 404) { reject('Configuration file could not be found: ' + path); } }; xhr.onerror = function () { reject("Configuration file could not be found or loaded: " + pathClosure); }; xhr.send(null); }); }; AureliaConfiguration.prototype.mergeConfigFile = function (path, optional) { var _this = this; return new Promise(function (resolve, reject) { _this .loadConfigFile(path, function (data) { _this.lazyMerge(data); resolve(); }) .catch(function (error) { if (optional === true) { resolve(); } else { reject(error); } }); }); }; return AureliaConfiguration; }()); export { AureliaConfiguration }; //# sourceMappingURL=aurelia-configuration.js.map
var columnDefs = [ // here we are using a valueGetter to get the country name from the complex object { colId: "country", valueGetter: "data.country.name", rowGroup: true, hide: true }, { field: "gold", aggFunc: 'sum' }, { field: "silver", aggFunc: 'sum' }, { field: "bronze", aggFunc: 'sum' } ]; var gridOptions = { columnDefs: columnDefs, defaultColDef: { flex: 1, minWidth: 150, resizable: true, sortable: true }, autoGroupColumnDef: { flex: 1, minWidth: 280, }, // use the server-side row model rowModelType: 'serverSide', serverSideStoreType: 'partial', animateRows: true, suppressAggFuncInHeader: true, // debug: true, }; function ServerSideDatasource(server) { return { getRows: function(params) { console.log('[Datasource] - rows requested by grid: ', params.request); var response = server.getData(params.request); // convert country to a complex object var resultsWithComplexObjects = response.rows.map(function(row) { row.country = { name: row.country, code: row.country.substring(0, 3).toUpperCase() }; return row; }); // adding delay to simulate real server call setTimeout(function() { if (response.success) { // call the success callback params.success({ rowData: resultsWithComplexObjects, rowCount: response.lastRow }); } else { // inform the grid request failed params.fail(); } }, 200); } }; } // setup the grid after the page has finished loading document.addEventListener('DOMContentLoaded', function() { var gridDiv = document.querySelector('#myGrid'); new agGrid.Grid(gridDiv, gridOptions); agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/olympic-winners.json' }).then(function(data) { // setup the fake server with entire dataset var fakeServer = new FakeServer(data); // create datasource with a reference to the fake server var datasource = new ServerSideDatasource(fakeServer); // register the datasource with the grid gridOptions.api.setServerSideDatasource(datasource); }); });
var _ = require('underscore'); module.exports = { 'desc': 'Update A Single Form Project.', 'examples': [{ cmd: 'fhc appforms projects update --id=<GUID Of Form Project To Update> --theme=<ID Of Theme To Associate With The Project> --forms=<formId1>,<formId2>', desc: 'Update A Single Form Project' }], 'demand': ['id'], 'alias': {}, 'describe': { 'id': 'GUID Of The Form Project To Update', 'theme': 'The ID Of The Theme To Associate With The Form Project', 'forms': 'Comma-separated List Of Form IDs To Associate With The Form Project' }, 'url': function (params) { return "/api/v2/appforms/apps/" + params.id; }, 'method': 'put', 'preCmd': function (params, cb) { var theme = params.theme; var forms = params.forms || ""; forms = forms.split(','); forms = _.compact(forms); var dataObject = { id: params.id, forms: forms }; if (theme) { dataObject.theme = params.theme; } return cb(undefined, dataObject); } };
/** * Simple UI Builder * @ artbels * artbels@gmail.com * 2016 */ ;(function () { var UI = this.UI = {} UI.input = function (params, cb) { params = params || {} cb = cb || params.cb || function (value) { console.log('you pressed enter and input value is >> ' + value + ' <<') } if ((typeof params == 'function') && (typeof cb == 'object')) { var temp = params params = cb cb = temp } if (typeof params == 'string') params = { id: params } params.id = params.id || 'input' if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var input = document.createElement('input') input.id = params.id input.type = params.type || 'text' if (params.placeholder) input.placeholder = params.placeholder input.name = params.name || params.id if ((params.class !== undefined) || (params.className !== undefined)) { input.className = params.class || params.className } else input.className = 'form-control'; // yes, I like bootstrap if (params.style) { for (var key in params.style) { var val = params.style[key] input.style[key] = val } } input.style.width = input.style.width || '300px' input.style.marginTop = input.style.marginTop || '5px' input.style.marginBottom = input.style.marginBottom || '5px' if (params.value === undefined) { input.value = localStorage['input#' + params.id] || params.default || '' } else input.value = params.value input.onkeyup = saveContents input.onchange = saveContents function saveContents (e) { localStorage['input#' + params.id] = input.value.trim() if (e.keyCode === 13) { // checks whether the pressed key is "Enter" cb(input.value) } } if (params.attributes) { for (var attribute in params.attributes) { var atr = params.attributes[attribute] input.setAttribute(attribute, atr) } } params.parent.appendChild(input) } UI.button = function (cb, params) { if (typeof cb == 'object') { if (typeof params == 'function') { var temp = params params = cb cb = temp } else if (typeof params == 'undefined') { params = cb cb = console.log } } if (typeof cb == 'string') { if (typeof params == 'function') { var temp2 = params params = { innerHTML: cb } cb = temp2 } else if (typeof params == 'undefined') { params = { innerHTML: cb } cb = console.log } } params = params || {} cb = cb || function (id) { console.log(id + ' clicked') } params.className = (params.class !== undefined) ? params.class : ((params.className !== undefined) ? params.className : 'btn btn-default') params.innerHTML = params.innerHTML || params.title || 'Action' params.id = params.id || UI.slug(params.innerHTML) if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var button = document.createElement('button') button.id = params.id button.className = params.className button.innerHTML = params.innerHTML if (params.style) { for (var key in params.style) { var val = params.style[key] button.style[key] = val } } button.style.margin = button.style.margin || params.margin || '10px' button.onclick = function () { cb(button.id) } if (params.attributes) { for (var attribute in params.attributes) { var val = params.attributes[attribute] button.setAttribute(attribute, val) } } params.parent.appendChild(button) } UI.buttons = function (arr, cb, params) { if (!arr || !arr.length) return console.warn('no array to build buttons!') if (typeof cb == 'object') { if (typeof params == 'function') { var temp = params params = cb cb = temp } else if (typeof params == 'undefined') { params = cb cb = console.log } } params = params || {} cb = cb || function (id) { console.log(id + ' clicked') } if (typeof params == 'string') params = { innerHTML: params, id: params } var i = 0 var l = arr.length ;(function next () { var item = arr[i] if (typeof item == 'number') item = item.toString() var buttonParams = { parent: params.parent, innerHTML: item, className: params.className, style: { margin: '2px' } } UI.button(cb, buttonParams) i++ if (i < l) next() })() } UI.br = function (params) { params = params || {} if (typeof params == 'string') { params = { parent: document.querySelector(params) } } else if (typeof params == 'number') { params = { id: params.toString() } } else if (params instanceof HTMLElement) { params = { parent: params } } if (typeof params.parent == 'string') params.parent = document.querySelector(params.parent) else params.parent = params.parent || document.querySelector('#ui') || document.body params.id = params.id || 'br' var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var br = document.createElement('br') br.id = params.id params.parent.appendChild(br) } UI.radio = function (arr, params, cb) { if (!arr || !arr.length) return console.warn('no array to build radios!') params = params || {} cb = cb || params.cb || function (value) { console.log('you clicked radio >> ' + value + ' <<') } if ((typeof params == 'function') && (typeof cb == 'object')) { var temp = params params = cb cb = temp } if (typeof params == 'string') params = { parent: document.querySelector(params) } if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body params.id = params.id || 'radio' var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var i = 0 var l = arr.length createRadio() function createRadio () { var item = arr[i] var radio = document.createElement('input') radio.type = 'radio' radio.id = item radio.name = params.id if (params.default && (params.default == item)) { radio.checked = true } radio.onclick = function () { cb(radio.id) } if (params.attributes) { for (var attribute in params.attributes) { var val = params.attributes[attribute] radio.setAttribute(attribute, val) } } params.parent.appendChild(radio) params.parent.appendChild(document.createTextNode(item)) if (params.br) params.parent.appendChild(document.createElement('br')) i++ if (i < l) { createRadio() } } } UI.checkbox = function (params, cb) { params = params || {} cb = cb || params.cb || function (value) { console.log('you clicked checkbox >> ' + value + ' <<') } if ((typeof params == 'function') && (typeof cb == 'object')) { var temp = params params = cb cb = temp } if (typeof params == 'string') params = { text: params, id: params } if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body params.id = params.id || 'checkbox' var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var checkbox = document.createElement('input') checkbox.type = 'checkbox' checkbox.id = params.id checkbox.className = params.className checkbox.checked = Boolean(params.checked) checkbox.onclick = function () { cb(checkbox.id + ' ' + checkbox.checked) } if (params.attributes) { for (var attribute in params.attributes) { var val = params.attributes[attribute] checkbox.setAttribute(attribute, val) } } params.parent.appendChild(checkbox) if (params.text) { var spanParams = { parent: params.parent, id: UI.slug(params.id) + '-span', innerHTML: params.text } var exSpanNode = document.getElementById(spanParams.id) if (exSpanNode) params.parent.removeChild(exSpanNode) UI.span(spanParams) } } UI.checkboxes = function (arr, cb, params) { if (!arr || !arr.length) return console.warn('no array to build buttons!') if (typeof cb == 'object') { if (typeof params == 'function') { var temp = params params = cb cb = temp } else if (typeof params == 'undefined') { params = cb cb = console.log } } params = params || {} if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body cb = cb || function (id) { console.log(id + ' checked') } var i = 0 var l = arr.length ;(function next () { var item = arr[i] if (typeof item == 'number') item = item.toString() var checkboxParams = { parent: params.parent, className: params.className, checked: Boolean(params.checked), text: item, id: UI.slug(item), style: { margin: '2px' } } UI.checkbox(cb, checkboxParams) if (params.br) params.parent.appendChild(document.createElement('br')) i++ if (i < l) next() })() } UI.fileReader = function (cb, params) { params = params || {} if ((typeof params == 'function') && (typeof cb == 'object')) { var temp = params params = cb cb = temp } cb = cb || params.cb || console.log params.id = params.id || 'file-reader' if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var fileInput = document.createElement('input') params.parent.appendChild(fileInput) fileInput.type = 'file' fileInput.id = params.id if(params.multiple) fileInput.multiple = "multiple" if (params.style) { for (var key in params.style) { var val = params.style[key] fileInput.style[key] = val } } if (params.attributes) { for (var attribute in params.attributes) { var atrVal = params.attributes[attribute] fileInput.setAttribute(attribute, atrVal) } } fileInput.onchange = function (evt) { var files = evt.target.files var len = files.length var fileReader = new FileReader() function readFile (index) { if (index >= len) return var fileToRead = files[index] var fileType = fileToRead.name.split(/\./).pop() if (params.bypassFileReader) return cb(fileToRead) fileReader.onload = function (e) { var contents = e.target.result if (params.json && (['{', '['].indexOf(contents.slice(0, 1)) != -1)) { contents = JSON.parse(contents) } cb(contents, fileToRead, index, len) readFile(index + 1) } if ((['zip', 'kmz'].indexOf(fileType) != -1) || (params.readAsArrayBuffer)) { fileReader.readAsArrayBuffer(fileToRead) } else if ((['xls', 'xlsx'].indexOf(fileType) != -1) || (params.readAsBinaryString)) { fileReader.readAsBinaryString(fileToRead) } else { fileReader.readAsText(fileToRead, params.encoding) } } readFile(0) } } UI.download = function (str, params) { params = params || {} if (!str) console.warn('nothing to save!') if (typeof str == 'object') str = JSON.stringify(str, null, '\t') params.id = params.id || params.name || 'download-link' params.name = params.name || 'renameMe.json' params.type = params.type || 'application/json' if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var a = document.createElement('a') if (params.noBlob) { var data = params.type + encodeURIComponent(str) a.href = 'data:' + data } else { var blobObj = new Blob([str], { type: params.type }) var blobUrl = URL.createObjectURL(blobObj) a.href = blobUrl } a.download = params.name a.textContent = params.name a.id = params.id if (params.style) { for (var key in params.style) { var val = params.style[key] a.style[key] = val } } if (params.attributes) { for (var attribute in params.attributes) { var val = params.attributes[attribute] a.setAttribute(attribute, val) } } params.parent.appendChild(a) } UI.span = function (params) { if (typeof params == 'string') params = { innerHTML: params } if (!params.innerHTML) return 'no innerHTML' params.id = params.id || UI.slug(params.innerHTML) if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var span = document.createElement('span') span.innerHTML = params.innerHTML span.id = params.id if (params.className) span.className = params.className if (params.style) { for (var key in params.style) { var val = params.style[key] span.style[key] = val } } if (params.attributes) { for (var attribute in params.attributes) { var val = params.attributes[attribute] span.setAttribute(attribute, val) } } params.parent.appendChild(span) } UI.img = function (params) { if (typeof params == 'string') params = { src: params } if (!params.src) return 'no src' params.id = params.id || 'img' if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var img = document.createElement('img') img.src = params.src if (params.alt) img.alt = params.alt img.id = params.id if (params.className) img.className = params.className if (params.style) { for (var key in params.style) { var val = params.style[key] img.style[key] = val } } if (params.attributes) { for (var attribute in params.attributes) { var val = params.attributes[attribute] img.setAttribute(attribute, val) } } params.parent.appendChild(img) } UI.link = function (params) { if (typeof params == 'string') params = { href: params, innerHTML: params } if (!params.href) return 'no href' params.innerHTML = params.innerHTML || params.href params.id = params.id || UI.slug(params.innerHTML) if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var a = document.createElement('a') a.id = params.id a.href = params.href if (params.targetBlank) a.target = '_blank' a.innerHTML = params.innerHTML if (params.style) { for (var key in params.style) { var val = params.style[key] a.style[key] = val } } a.className = params.class || params.className if (params.attributes) { for (var attribute in params.attributes) { var atr = params.attributes[attribute] a.setAttribute(attribute, atr) } } params.parent.appendChild(a) } UI.select = function (arr, cb, params) { if (!arr || !arr.length) return console.warn('no array to build select!') if ((typeof params == 'function') && (typeof cb == 'object')) { var temp = params params = cb cb = temp } if (!params && (typeof cb == 'object')) { params = cb cb = console.log } params = params || {} params.id = params.id || '' if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body var exNode = document.getElementById(params.id + 'Select') if (exNode) params.parent.removeChild(exNode) cb = cb || console.log var select = document.createElement('select') select.className = params.className || 'selectpicker' select.id = params.id + 'Select' if (params.style) { for (var key in params.style) { var val = params.style[key] select.style[key] = val } } var firstOption = document.createElement('option') firstOption.innerHTML = params.firstRowText || 'select ' + params.id select.appendChild(firstOption) for (var i = 0; i < arr.length; i++) { var item = arr[i] var option = document.createElement('option') option.id = params.id + 'Option' option.innerHTML = params.innerHTML || item option.value = params.value || item if (params.default && params.default == item) { option.selected = true } select.appendChild(option) } params.parent.appendChild(select) select.onchange = function () { var selectedOptionNode = document.querySelector('option#' + params.id + 'Option' + ':checked') if (selectedOptionNode) cb(selectedOptionNode.value) } } UI.textarea = function (params) { params = params || {} params.id = params.id || 'textarea' params.cols = (params.cols || 60).toString() params.rows = (params.rows || 12).toString() params.fontSize = params.fontSize || '12px' if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var textarea = document.createElement('textarea') textarea.cols = params.cols textarea.rows = params.rows textarea.id = params.id textarea.className = params.className || params.class || 'form-control' if (params.style) { for (var key in params.style) { var val = params.style[key] textarea.style[key] = val } } textarea.style.fontFamily = 'monospace' textarea.style.fontSize = params.fontSize if (params.attributes) { for (var attribute in params.attributes) { var val = params.attributes[attribute] textarea.setAttribute(attribute, val) } } params.parent.appendChild(textarea) textarea.value = params.value || localStorage['textarea#' + params.id] || '' textarea.onkeyup = saveContents textarea.onchange = saveContents function saveContents (e) { localStorage['textarea#' + params.id] = textarea.value.trim() } } UI.TB = function (cb, params) { if ((typeof params == 'function') && (typeof cb == 'object')) { var temp = params params = cb cb = temp } cb = cb || console.log params = params || {} if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body params.className = '' UI.textarea(params) var textareaId = params.id var textareaNode = document.querySelector('textarea#' + params.id) if (!params.noAction) { var actionParams = {} actionParams.parent = params.parent actionParams.id = params.id + 'Action' actionParams.innerHTML = params.buttonText || 'Action' actionParams.className = '' actionParams.style = { margin: '0px', marginTop: '10px', } UI.button(actionParams, function () { var textareaArr = textareaNode.value .trim() .split(/\n\r?/).filter(function (a) { return a }) cb(textareaArr) }) } var clearParams = {} clearParams.parent = params.parent clearParams.id = params.id + 'Clear' clearParams.innerHTML = 'Clear' clearParams.className = '' clearParams.style = { margin: '0px', marginLeft: '5px', marginTop: '10px', } UI.button(clearParams, function () { textareaNode.value = '' localStorage[textareaId] = '' }) } UI.table = function (arr, params) { if ((!arr) && (typeof (arr[0]) != 'object')) { alert('Argument is not an array with objects') } if (typeof arr[0] != 'object') arr = arr.map(function (a) { return { value: a } }) var reDateTimeJS = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/ if (typeof params == 'string') params = { parent: params } params = params || {} if (typeof params.selectable != 'boolean') params.selectable = false params.tableId = params.tableId || params.id || 'printedTable' params.showColumns = params.showColumns || params.columns || params.cols || [] params.hideColumns = params.hideColumns || [] if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body if (typeof params.hideHead != 'boolean') params.hideHead = false if (typeof params.sortColumns != 'boolean') params.sortColumns = false // console.log(params) var columns = [] var numCol = {} var cell = '' var chBoxCol if (params.showColumns.length !== 0) { columns = params.showColumns } else { for (var i = 0; i < arr.length; i++) { // собираем ключи со всех объектов for (var key in arr[i]) { if ((columns.indexOf(key) == -1) && (params.hideColumns.indexOf(key) == -1)) { columns.push(key) var colCell = arr[i][key] numCol[key] = (!isNaN(colCell) && (typeof colCell == 'number')) } } } } if (params.sortColumns) columns.sort() var exTable = document.getElementById(params.tableId) if (exTable) params.parent.removeChild(exTable) var table = document.createElement('table') table.id = params.tableId if (params.style) { for (var style in params.style) { var val = params.style[style] table.style[style] = val } } table.style.margin = table.style.margin || '10px' table.style.fontFamily = table.style.fontFamily || 'monospace' table.style.width = table.style.width || 'auto 90%' table.style.borderCollapse = table.style.borderCollapse || 'collapse' params.parent.appendChild(table) if (!params.hideHead) { var thead = table.createTHead() var hRow = thead.insertRow(0) if (params.selectable) { var thh = document.createElement('th') thh.style.background = '#f6f6f6' thh.style.padding = '3px' thh.style.border = '1px solid #CCC' chBoxCol = document.createElement('input') chBoxCol.id = params.tableId + 'ColCheckbox' chBoxCol.type = 'checkbox' chBoxCol.checked = Boolean(params.checked) thh.appendChild(chBoxCol) hRow.appendChild(thh) } for (var h = 0; h < columns.length; h++) { var th = document.createElement('th') th.style.background = '#f6f6f6' th.style.padding = '3px' th.style.border = '1px solid #CCC' th.appendChild(document.createTextNode(columns[h])) hRow.appendChild(th) } } var tbody = document.createElement('tbody') table.appendChild(tbody) if (arr.length !== 0) { for (var n = 0; n < arr.length; n++) { // собираем данные полей, чистим var dRow = tbody.insertRow(-1) dRow.id = 'r' + n var oneObj = arr[n] if (params.selectable) { var tdch = document.createElement('td') tdch.style.padding = '3px' tdch.style.border = '1px solid #CCC' var chBoxRow = document.createElement('input') chBoxRow.className = params.tableId + 'RowCheckbox' chBoxRow.id = 'r' + n chBoxRow.type = 'checkbox' chBoxRow.checked = Boolean(params.checked) tdch.appendChild(chBoxRow) dRow.appendChild(tdch) } for (var l = 0; l < columns.length; l++) { cell = oneObj[columns[l]] cell = (((cell !== undefined) && (cell !== null)) ? cell : '') if (cell.constructor === Array) cell = cell.join(', ') if (cell.constructor === Object) cell = JSON.stringify(cell) if (typeof cell == 'string') { cell = cell.replace(params.quotes, "'") if (reDateTimeJS.test(cell)) cell = new Date(cell).toLocaleDateString() } var td = document.createElement('td') if (/<a.+<\/a>/.test(cell)) { td.appendChild(new DOMParser() .parseFromString(cell, 'text/html') .querySelector('a')) } else if (/<img.+?>/.test(cell)) { td.appendChild(new DOMParser() .parseFromString(cell, 'text/html') .querySelector('img')) } else if (/<input.+?>/.test(cell)) { td.appendChild(new DOMParser() .parseFromString(cell, 'text/html') .querySelector('input')) } else { td.appendChild(document.createTextNode(cell)) } td.style.padding = '3px' td.style.border = '1px solid #CCC' dRow.appendChild(td) } } } if (chBoxCol) { chBoxCol.onchange = function () { var checkboxes = document.querySelectorAll('.' + params.tableId + 'RowCheckbox') for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = !checkboxes[i].checked } } } } UI.addRow = function (obj, params) { params = params || {} params.selectable = params.selectable || false params.mdl = params.mdl || false params.showColumns = params.showColumns || params.cols || params.columns || [] params.tableId = params.tableId || params.id || 'printedTable' var tableExists = document.getElementById(params.tableId) if (!tableExists) Table.print([], params) var reDateTimeJS = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/ var columns = [] var cell = '' if (params.showColumns.length !== 0) { columns = params.showColumns } else { columns = Object.keys(obj) } var tbody = document.querySelector('#' + params.tableId).querySelector('tbody') var dRow = tbody.insertRow(-1) if (params.selectable) { var tds = document.createElement('td') if (!params.mdl) { tds.style.padding = '3px' tds.style.border = '1px solid black' } var chBoxRow = document.createElement('input') chBoxRow.className = params.tableId + 'RowCheckbox' chBoxRow.type = 'checkbox' chBoxRow.checked = Boolean(params.checked) tds.appendChild(chBoxRow) dRow.appendChild(tds) } for (var i = 0; i < columns.length; i++) { var td = document.createElement('td') if (!params.mdl) { td.style.padding = '3px' td.style.border = '1px solid black' } cell = obj[columns[i]] cell = (((cell !== undefined) && (cell !== null)) ? cell : '') if (cell.constructor === Array) cell = cell.join(', ') else if (cell.constructor === Object) cell = JSON.stringify(cell) else if (typeof cell == 'string') { cell = cell.replace(params.quotes, "'") if (reDateTimeJS.test(cell)) cell = new Date(cell).toLocaleDateString() } if (/<a.+<\/a>/.test(cell)) { td.appendChild(new DOMParser().parseFromString(cell, 'text/html').querySelector('a')) } else if (/<img.+?>/.test(cell)) { td.appendChild(new DOMParser().parseFromString(cell, 'text/html').querySelector('img')) } else { td.appendChild(document.createTextNode(cell)) } if (!params.mdl) { td.style.padding = '3px' td.style.border = '1px solid black' } else { if (!numCol[columns[l]]) { // select first col with non-num td.className = 'mdl-data-table__cell--non-numeric' } } dRow.appendChild(td) } } UI.getTableSel = function (tableId) { var checkboxes = document.querySelectorAll('.' + tableId + 'RowCheckbox') var checkedArr = [] for (var i = 0; i < checkboxes.length; i++) { if (checkboxes[i].checked) checkedArr.push(i) } return checkedArr } UI.div = function (params) { params = params || {} if (typeof params == 'string') { params = { id: params } } if (typeof params.parent == 'string') { params.parent = document.querySelector(params.parent) } else params.parent = params.parent || document.querySelector('#ui') || document.body var exNode = document.getElementById(params.id) if (exNode) params.parent.removeChild(exNode) var div = document.createElement('div') div.id = params.id || 'div' div.className = params.className if (params.style) { for (var key in params.style) { div.style[key] = params.style[key] } } if (params.attributes) { for (var attribute in params.attributes) { div.setAttribute(attribute, params.attributes[attribute]) } } params.parent.appendChild(div) } UI.appendModal = function (params) { // requires bootstrap params = params || {} params.id = params.id || 'modal' params.title = params.title || 'Modal title' var fadeDiv = document.createElement('div') fadeDiv.id = params.id fadeDiv.setAttribute('class', 'modal fade') fadeDiv.setAttribute('role', 'dialog') document.body.appendChild(fadeDiv) var dialogDiv = document.createElement('div') dialogDiv.setAttribute('class', 'modal-dialog') fadeDiv.appendChild(dialogDiv) var contentDiv = document.createElement('div') contentDiv.setAttribute('class', 'modal-content') dialogDiv.appendChild(contentDiv) var headerDiv = document.createElement('div') headerDiv.setAttribute('class', 'modal-header') headerDiv.style.padding = '10px' contentDiv.appendChild(headerDiv) var closeButton = document.createElement('button') closeButton.setAttribute('class', 'close') closeButton.setAttribute('data-dismiss', 'modal') closeButton.innerHTML = '&times;' headerDiv.appendChild(closeButton) var h4 = document.createElement('h4') h4.setAttribute('class', 'modal-title') h4.innerHTML = params.title headerDiv.appendChild(h4) var bodyDiv = document.createElement('div') bodyDiv.id = params.id + '-body' contentDiv.appendChild(bodyDiv) var footerDiv = document.createElement('div') footerDiv.id = params.id + '-footer' contentDiv.appendChild(footerDiv) } UI.slug = function (str) { if (!str) return if (typeof str === 'number') return str var letterMap = { '/': '_', '\\': '_', 'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ж': 'zh', 'з': 'z', 'и': 'i', 'й': 'y', 'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n', 'о': 'o', 'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u', 'ф': 'f', 'х': 'kh', 'ц': 'ts', 'ч': 'ch', 'ш': 'sh', 'щ': 'sch', 'ы': 'i', 'ь': '', 'ъ': '', 'э': 'e', 'ю': 'yu', 'я': 'ya', 'ё': 'e', 'є': 'e', 'і': 'i', 'ї': 'yi', 'ґ': 'g', '+': '-plus' } var reOtherSymbols = /[^a-z0-9\-_]/gi var replLetters = str.split('').map(function (char) { char = char.toLowerCase() return (letterMap[char] !== undefined) ? letterMap[char] : char }).join('') var replSymb = replLetters.replace(reOtherSymbols, '-') var replUnnecDelims = removeUnnecessaryDelims(replSymb) return replUnnecDelims function removeUnnecessaryDelims (str) { return str .replace(/\-{2,}/g, '-') .replace(/_{2,}/g, '_') .replace(/[\-\_]+$/g, '') .replace(/^[\-\_]+/g, '') } } })()
/* globals describe: false, it: false */ "use strict"; var J = require('../lib/parser'), M = require('unparse-js').maybeerror, assert = require('assert'); var module = describe, test = it, deepEqual = assert.deepEqual; module("parser", function() { function good(rest, state, value) { return M.pure({'rest': rest, 'state': state, 'result': value}); } var error = M.error; function cstnode(name, start, end) { var pairs = Array.prototype.slice.call(arguments, 3), obj = {'_name': name, '_start': start, '_end': end}; pairs.map(function(p) { obj[p[0]] = p[1]; }); return obj; } function my_object(pos, end, body) { return cstnode('object', pos, end, ['open', '{'], ['close', '}'], ['body', body]); } test("Integer", function() { var inp = '83 abc'; deepEqual(J.number.parse(inp, [1,1]), good('abc', [1,4], cstnode('number', [1,1], [1,3], ['sign', null], ['integer', ['8', '3']], ['exponent', null], ['decimal', null]))); var inp2 = '-77 abc'; deepEqual(J.number.parse(inp2, [1,1]), good('abc', [1,5], cstnode('number', [1,1], [1,4], ['sign', '-'], ['integer', ['7', '7']], ['exponent', null], ['decimal', null]))); }); test("DecimalAndExponent", function() { var inp = '-8.1e+2 abc'; deepEqual(J.number.parse(inp, [1,1]), good('abc', [1,9], cstnode('number', [1,1], [1,8], ['sign', '-'], ['integer', ['8']], ['decimal', cstnode('decimal', [1,3], [1,5], ['dot', '.'], ['digits', ['1']])], ['exponent', cstnode('exponent', [1,5], [1,8], ['letter', 'e'], ['sign', '+'], ['power', ['2']])]))); var inp2 = '-8.1 abc'; deepEqual(J.number.parse(inp2, [1,1]), good('abc', [1,6], cstnode('number', [1,1], [1,5], ['sign', '-'], ['integer', ['8']], ['decimal', cstnode('decimal', [1,3], [1,5], ['dot', '.'], ['digits', ['1']])], ['exponent', null]))); var inp3 = '-8e+2 abc'; deepEqual(J.number.parse(inp3, [1,1]), good('abc', [1,7], cstnode('number', [1,1], [1,6], ['sign', '-'], ['integer', ['8']], ['decimal', null], ['exponent', cstnode('exponent', [1,3], [1,6], ['letter', 'e'], ['sign', '+'], ['power', ['2']])]))); }); test("NumberMessedUpExponent", function() { deepEqual(J.number.parse('0e abc', [1,1]), error([['number', [1,1]], ['exponent', [1,2]], ['power', [1,3]]])); }); test("NumberLeading0", function() { deepEqual(J.number.parse('-07 abc', [1,1]), error([['number', [1,1]], ['invalid leading 0', [1,2]]])); }); test("LoneMinusSign", function() { deepEqual(J.number.parse('-abc', [1,1]), error([['number', [1,1]], ['digits', [1,2]]])); }); test("EmptyString", function() { var inp = '"" def'; deepEqual(J.jsonstring.parse(inp, [1,1]), good('def', [1,4], cstnode('string', [1,1], [1,3], ['open', '"'], ['close', '"'], ['value', []]))); }); test("String", function() { var inp = '"abc" def', chars = [ cstnode('character', [1,2], [1,3], ['value', 'a']), cstnode('character', [1,3], [1,4], ['value', 'b']), cstnode('character', [1,4], [1,5], ['value', 'c']) ], val = cstnode('string', [1,1], [1,6], ['open', '"'], ['close', '"'], ['value', chars]); deepEqual(J.jsonstring.parse(inp, [1,1]), good('def', [1,7], val)); }); test("StringBasicEscape", function() { var inp = '"a\\b\\nc" def', chars = [ cstnode('character', [1,2], [1,3], ['value', 'a']), cstnode('escape', [1,3], [1,5], ['open', '\\'], ['value', 'b']), cstnode('escape', [1,5], [1,7], ['open', '\\'], ['value', 'n']), cstnode('character', [1,7], [1,8], ['value', 'c']) ], val = cstnode('string', [1,1], [1,9], ['open', '"'], ['close', '"'], ['value', chars]); deepEqual(J.jsonstring.parse(inp, [1,1]), good('def', [1,10], val)); }); test("StringEscapeSequences", function() { var inp = '"\\"\\\\\\/\\b\\f\\n\\r\\t" def', chars = [ cstnode('escape', [1,2], [1,4], ['open', '\\'], ['value', '"']), cstnode('escape', [1,4], [1,6], ['open', '\\'], ['value', '\\']), cstnode('escape', [1,6], [1,8], ['open', '\\'], ['value', '/']), cstnode('escape', [1,8], [1,10],['open', '\\'], ['value', 'b']), cstnode('escape', [1,10],[1,12],['open', '\\'], ['value', 'f']), cstnode('escape', [1,12],[1,14],['open', '\\'], ['value', 'n']), cstnode('escape', [1,14],[1,16],['open', '\\'], ['value', 'r']), cstnode('escape', [1,16],[1,18],['open', '\\'], ['value', 't']), ], val = cstnode('string', [1,1], [1,19], ['open', '"'], ['close', '"'], ['value', chars]); deepEqual(J.jsonstring.parse(inp, [1,1]), good('def', [1,20], val)); }); test("StringUnicodeEscape", function() { var inp = '"a\\u0044n\\uabcdc" def', chars = [ cstnode('character' , [1,2], [1,3], ['value', 'a']), cstnode('unicode escape', [1,3], [1,9], ['open', '\\u'], ['value', ['0','0','4','4']]), cstnode('character' , [1,9], [1,10],['value', 'n']), cstnode('unicode escape', [1,10],[1,16],['open', '\\u'], ['value', ['a','b','c','d']]), cstnode('character' , [1,16],[1,17],['value', 'c']) ], val = cstnode('string', [1,1], [1,18], ['open', '"'], ['close', '"'], ['value', chars]); deepEqual(J.jsonstring.parse(inp, [1,1]), good('def', [1,19], val)); }); test("Punctuation", function() { var cases = [ ['{ abc', 'oc'], ['} abc', 'cc'], ['[ abc', 'os'], ['] abc', 'cs'], [', abc', 'comma'], [': abc', 'colon']]; cases.map(function(c) { var inp = c[0], parser = c[1]; deepEqual(J[parser].parse(inp, [1,1]), good(inp.slice(2), [1,3], inp[0])); }); }); test("Keyword", function() { deepEqual(J.keyword.parse('true abc', [1,1]), good('abc', [1,6], cstnode('keyword', [1,1], [1,5], ['value', 'true']))); deepEqual(J.keyword.parse('false abc', [1,1]), good('abc', [1,7], cstnode('keyword', [1,1], [1,6], ['value', 'false']))); deepEqual(J.keyword.parse('null abc', [1,1]), good('abc', [1,6], cstnode('keyword', [1,1], [1,5], ['value', 'null']))); }); test("KeyVal", function() { var chars = [ cstnode('character', [1,2], [1,3], ['value', 'q']), cstnode('character', [1,3], [1,4], ['value', 'r']), cstnode('character', [1,4], [1,5], ['value', 's']) ]; deepEqual(J.keyVal.parse('"qrs"\n : true abc', [1,1]), good('abc', [2,9], cstnode('key/value pair', [1,1], [2,9], ['key', cstnode('string', [1,1], [1,6], ['open', '"'], ['close', '"'], ['value', chars])], ['colon', ':'], ['value', cstnode('keyword', [2,4], [2,8], ['value', 'true'])]))); }); test("KeyValueMissingColon", function() { deepEqual(J.keyVal.parse('"qrs"} abc', [1,1]), error([['key/value pair', [1,1]], ['colon', [1,6]]])); }); test("KeyValueMissingValue", function() { deepEqual(J.keyVal.parse('"qrs" : abc', [1,1]), error([['key/value pair', [1,1]], ['value', [1,10]]])); }); test("Object", function() { deepEqual(J.obj.parse('{} abc', [1,1]), good('abc', [1,4], my_object([1,1], [1,4], null))); deepEqual(J.obj.parse('{"": null} abc', [1,1]), good('abc', [1,12], my_object([1,1], [1,12], [cstnode('key/value pair', [1,2], [1,10], ['colon', ':'], ['key', cstnode('string', [1,2], [1,4], ['open', '"'], ['close', '"'], ['value', []])], ['value', cstnode('keyword', [1,6], [1,10], ['value', 'null'])]), []]))); }); test("UnclosedObject", function() { var e = error([['object', [1,1]], ['close', [1,12]]]); deepEqual(J.obj.parse('{"a": null ', [1,1]), e); deepEqual(J.obj.parse('{"a": null ,', [1,1]), e); deepEqual(J.obj.parse('{"a": null ]', [1,1]), e); }); test("Array", function() { deepEqual(J.array.parse('[] abc', [1,1]), good('abc', [1,4], cstnode('array', [1,1], [1,4], ['open', '['], ['close', ']'], ['body', null]))); deepEqual(J.array.parse('[true]', [1,1]), good("", [1,7], cstnode('array', [1,1], [1,7], ['open', '['], ['close', ']'], ['body', [cstnode('keyword', [1,2], [1,6], ['value', 'true']), []]]))); deepEqual(J.array.parse('[true,false]', [1,1]), good('', [1,13], cstnode('array', [1,1], [1,13], ['open', '['], ['close', ']'], ['body', [cstnode('keyword', [1,2], [1,6], ['value', 'true']), [[',', cstnode('keyword', [1,7], [1,12],['value', 'false'])]]]]))); }); test("ArrayErrors", function() { var cases = ['[', '[2', '[2,'], errors = [ [['array', [1,1]], ['close', [1,2]]], [['array', [1,1]], ['close', [1,3]]], [['array', [1,1]], ['close', [1,3]]] ]; for(var i = 0; i < cases.length; i++) { deepEqual(J.array.parse(cases[i], [1,1]), error(errors[i])); } }); test("Json", function() { deepEqual(J.json.parse('{ } \n', [1,1]), good("", [2,1], cstnode('json', [1,1], [2,1], ['value', my_object([1,1], [2,1], null)]))); }); test("NoJson", function() { deepEqual(J.json.parse('a', [1,1]), error([['json value', [1,1]]])); }); test("string control character", function() { deepEqual(J.jsonstring.parse('"ab\x03cd"', [1,1]), error([['string', [1,1]], ['character', [1,4]], ['invalid control character', [1,4]]])); }); test("UnclosedString", function() { deepEqual(J.jsonstring.parse('"abc', [1,1]), error([['string', [1,1]], ['double-quote', [1,5]]])); }); test("StringBadEscape", function() { deepEqual(J.jsonstring.parse('"\\qr"', [1,1]), error([['string', [1,1]], ['escape', [1,2]], ['simple escape', [1,3]]])); }); test("StringBadUnicodeEscape", function() { var stack = [['string', [1,1]], ['unicode escape', [1,3]], ['4 hexadecimal digits', [1,5]]]; deepEqual(J.jsonstring.parse('"2\\uabch1" def', [1,1]), error(stack)); deepEqual(J.jsonstring.parse('"?\\uab" def', [1,1]), error(stack)); }); test("TrailingJunk", function() { deepEqual(J.json.parse('{} &', [1,1]), error([['unparsed input remaining', [1,4]]])); }); });
module.exports = function(callback) { this.DynamoDB.listTables({}, function(error, response) { callback(error, response); }); };
// Generated by CoffeeScript 1.10.0 (function() { var Base, CarrierService, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Base = require('./base'); CarrierService = (function(superClass) { extend(CarrierService, superClass); CarrierService.prototype.slug = "carrier_service"; CarrierService.prototype.prefix = "/carrier_services"; function CarrierService(site) { CarrierService.__super__.constructor.call(this, site); } return CarrierService; })(Base); module.exports = CarrierService; }).call(this);
/* * index.js: Top-level include for the Rackspace database module * * (C) 2011 Nodejitsu Inc. * */ exports.Client = require('./client').Client; exports.Flavor = require('../../openstack/database/flavor').Flavor; exports.Instance = require('../../openstack/database/instance').Instance; exports.Database = require('../../openstack/database/database').Database; exports.User = require('../../openstack/database/user').User; exports.createClient = function createClient(options) { return new exports.Client(options); };
import axios from 'axios'; const instaHelpers = { getAllThisUsersPics(accessToken) { const token = window.localStorage.getItem('token'); return axios({ url: 'api/insta/getUserPics', method: 'post', headers: { Authorization: token }, data: { accessToken }, }); }, getUniqueTagPics(hashtag) { const token = window.localStorage.getItem('token'); const userId = window.localStorage.getItem('id'); if (hashtag) { if (hashtag[0] === '#') { hashtag = hashtag.slice(1); } return axios({ url: 'api/insta/getUniqueTagPics', method: 'post', headers: { Authorization: token }, data: { hashtag, userId }, }); } }, }; export default instaHelpers;
define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/_base/array', 'dojo/domReady', 'dojo/store/Memory', 'dojo/store/Observable', 'dojox/mobile/parser', 'gridx/mobile/Grid', 'gridx/mobile/tests/support/data', 'dojox/mobile/Heading', 'dojox/mobile/View', 'dojox/mobile/ScrollableView', "dojox/mobile/compat", 'dojox/mobile/TabBar' ], function(declare, lang, array, ready, MemoryStore, Observable, parser, Grid, data){ function random(range, digit, forcePositive){ var d = Math.pow(10, digit||0); var value = Math.round(range * Math.random() * d)/d; var positive = Math.random() >= 0.5 || forcePositive; return positive ? value : -value; } function formatter(item, col){ var c = item.change, css = 'up'; if(c < 0)css = 'down'; return '<span class="' + css + '">' + (c >= 0 ? '+' : '-') + Math.abs(c) + '</span>'; } var columns = [ {field: 'company', width: '40%', title: 'Company', cssClass: 'comp'}, {field: 'shares', width: '30%', title: 'Shares', cssClass: 'shares'}, {field: 'change', width: '30%', title: 'Change', cssClass: 'change', formatter: formatter} ]; ready(function(){ parser.parse(); var store = new Observable(new MemoryStore({data: data.stock})); grid.columns = columns; grid.setStore(store); window.setInterval(function(){ store.data.forEach(function(stock){ if(Math.random() > 0.5)return; var r = random(5, 2); stock.shares = Math.round(100*(stock.shares + r))/100; stock.change = Math.round(100*(stock.change + r))/100; store.put(stock); }); }, 2000); }); });
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var Koa = _interopDefault(require('koa')); var Router = _interopDefault(require('koa-router')); var koaBody = _interopDefault(require('koa-body')); var nanoid = require('nanoid'); var cors = _interopDefault(require('@koa/cors')); var produce = _interopDefault(require('immer')); var isPlainObject = _interopDefault(require('lodash.isplainobject')); var IO = _interopDefault(require('koa-socket-2')); var PQueue = _interopDefault(require('p-queue')); var rfc6902 = require('rfc6902'); var redux = require('redux'); /** * Moves can return this when they want to indicate * that the combination of arguments is illegal and * the move ought to be discarded. */ const INVALID_MOVE = 'INVALID_MOVE'; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Plugin that allows using Immer to make immutable changes * to G by just mutating it. */ const ImmerPlugin = { name: 'plugin-immer', fnWrap: (move) => (G, ctx, ...args) => { let isInvalid = false; const newG = produce(G, (G) => { const result = move(G, ctx, ...args); if (result === INVALID_MOVE) { isInvalid = true; return; } return result; }); if (isInvalid) return INVALID_MOVE; return newG; }, }; // Inlined version of Alea from https://github.com/davidbau/seedrandom. // Converted to Typescript October 2020. class Alea { constructor(seed) { const mash = Mash(); // Apply the seeding algorithm from Baagoe. this.c = 1; this.s0 = mash(' '); this.s1 = mash(' '); this.s2 = mash(' '); this.s0 -= mash(seed); if (this.s0 < 0) { this.s0 += 1; } this.s1 -= mash(seed); if (this.s1 < 0) { this.s1 += 1; } this.s2 -= mash(seed); if (this.s2 < 0) { this.s2 += 1; } } next() { const t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 this.s0 = this.s1; this.s1 = this.s2; return (this.s2 = t - (this.c = Math.trunc(t))); } } function Mash() { let n = 0xefc8249d; const mash = function (data) { const str = data.toString(); for (let i = 0; i < str.length; i++) { n += str.charCodeAt(i); let h = 0.02519603282416938 * n; n = h >>> 0; h -= n; h *= n; n = h >>> 0; h -= n; n += h * 0x100000000; // 2^32 } return (n >>> 0) * 2.3283064365386963e-10; // 2^-32 }; return mash; } function copy(f, t) { t.c = f.c; t.s0 = f.s0; t.s1 = f.s1; t.s2 = f.s2; return t; } function alea(seed, state) { const xg = new Alea(seed); const prng = xg.next.bind(xg); if (state) copy(state, xg); prng.state = () => copy(xg, {}); return prng; } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Random * * Calls that require a pseudorandom number generator. * Uses a seed from ctx, and also persists the PRNG * state in ctx so that moves can stay pure. */ class Random { /** * constructor * @param {object} ctx - The ctx object to initialize from. */ constructor(state) { // If we are on the client, the seed is not present. // Just use a temporary seed to execute the move without // crashing it. The move state itself is discarded, // so the actual value doesn't matter. this.state = state || { seed: '0' }; this.used = false; } /** * Generates a new seed from the current date / time. */ static seed() { return Date.now().toString(36).slice(-10); } isUsed() { return this.used; } getState() { return this.state; } /** * Generate a random number. */ _random() { this.used = true; const R = this.state; const seed = R.prngstate ? '' : R.seed; const rand = alea(seed, R.prngstate); const number = rand(); this.state = { ...R, prngstate: rand.state(), }; return number; } api() { const random = this._random.bind(this); const SpotValue = { D4: 4, D6: 6, D8: 8, D10: 10, D12: 12, D20: 20, }; // Generate functions for predefined dice values D4 - D20. const predefined = {}; for (const key in SpotValue) { const spotvalue = SpotValue[key]; predefined[key] = (diceCount) => { return diceCount === undefined ? Math.floor(random() * spotvalue) + 1 : [...new Array(diceCount).keys()].map(() => Math.floor(random() * spotvalue) + 1); }; } function Die(spotvalue = 6, diceCount) { return diceCount === undefined ? Math.floor(random() * spotvalue) + 1 : [...new Array(diceCount).keys()].map(() => Math.floor(random() * spotvalue) + 1); } return { /** * Similar to Die below, but with fixed spot values. * Supports passing a diceCount * if not defined, defaults to 1 and returns the value directly. * if defined, returns an array containing the random dice values. * * D4: (diceCount) => value * D6: (diceCount) => value * D8: (diceCount) => value * D10: (diceCount) => value * D12: (diceCount) => value * D20: (diceCount) => value */ ...predefined, /** * Roll a die of specified spot value. * * @param {number} spotvalue - The die dimension (default: 6). * @param {number} diceCount - number of dice to throw. * if not defined, defaults to 1 and returns the value directly. * if defined, returns an array containing the random dice values. */ Die, /** * Generate a random number between 0 and 1. */ Number: () => { return random(); }, /** * Shuffle an array. * * @param {Array} deck - The array to shuffle. Does not mutate * the input, but returns the shuffled array. */ Shuffle: (deck) => { const clone = deck.slice(0); let srcIndex = deck.length; let dstIndex = 0; const shuffled = new Array(srcIndex); while (srcIndex) { const randIndex = Math.trunc(srcIndex * random()); shuffled[dstIndex++] = clone[randIndex]; clone[randIndex] = clone[--srcIndex]; } return shuffled; }, _obj: this, }; } } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const RandomPlugin = { name: 'random', noClient: ({ api }) => { return api._obj.isUsed(); }, flush: ({ api }) => { return api._obj.getState(); }, api: ({ data }) => { const random = new Random(data); return random.api(); }, setup: ({ game }) => { let { seed } = game; if (seed === undefined) { seed = Random.seed(); } return { seed }; }, playerView: () => undefined, }; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const MAKE_MOVE = 'MAKE_MOVE'; const GAME_EVENT = 'GAME_EVENT'; const REDO = 'REDO'; const RESET = 'RESET'; const SYNC = 'SYNC'; const UNDO = 'UNDO'; const UPDATE = 'UPDATE'; const PATCH = 'PATCH'; const PLUGIN = 'PLUGIN'; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Generate a game event to be dispatched to the flow reducer. * * @param {string} type - The event type. * @param {Array} args - Additional arguments. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const gameEvent = (type, args, playerID, credentials) => ({ type: GAME_EVENT, payload: { type, args, playerID, credentials }, }); /** * Generate an automatic game event that is a side-effect of a move. * @param {string} type - The event type. * @param {Array} args - Additional arguments. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const automaticGameEvent = (type, args, playerID, credentials) => ({ type: GAME_EVENT, payload: { type, args, playerID, credentials }, automatic: true, }); /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Events */ class Events { constructor(flow, playerID) { this.flow = flow; this.playerID = playerID; this.dispatch = []; } /** * Attaches the Events API to ctx. * @param {object} ctx - The ctx object to attach to. */ api(ctx) { const events = { _obj: this, }; const { phase, turn } = ctx; for (const key of this.flow.eventNames) { events[key] = (...args) => { this.dispatch.push({ key, args, phase, turn }); }; } return events; } isUsed() { return this.dispatch.length > 0; } /** * Updates ctx with the triggered events. * @param {object} state - The state object { G, ctx }. */ update(state) { for (let i = 0; i < this.dispatch.length; i++) { const item = this.dispatch[i]; // If the turn already ended some other way, // don't try to end the turn again. if (item.key === 'endTurn' && item.turn !== state.ctx.turn) { continue; } // If the phase already ended some other way, // don't try to end the phase again. if ((item.key === 'endPhase' || item.key === 'setPhase') && item.phase !== state.ctx.phase) { continue; } const action = automaticGameEvent(item.key, item.args, this.playerID); state = { ...state, ...this.flow.processEvent(state, action), }; } return state; } } /* * Copyright 2020 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const EventsPlugin = { name: 'events', noClient: ({ api }) => { return api._obj.isUsed(); }, dangerouslyFlushRawState: ({ state, api }) => { return api._obj.update(state); }, api: ({ game, playerID, ctx }) => { return new Events(game.flow, playerID).api(ctx); }, }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Plugin that makes it possible to add metadata to log entries. * During a move, you can set metadata using ctx.log.setMetadata and it will be * available on the log entry for that move. */ const LogPlugin = { name: 'log', flush: () => ({}), api: ({ data }) => { return { setMetadata: (metadata) => { data.metadata = metadata; }, }; }, setup: () => ({}), }; /** * Check if a value can be serialized (e.g. using `JSON.stringify`). * Adapted from: https://stackoverflow.com/a/30712764/3829557 */ function isSerializable(value) { // Primitives are OK. if (value === undefined || value === null || typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') { return true; } // A non-primitive value that is neither a POJO or an array cannot be serialized. if (!isPlainObject(value) && !Array.isArray(value)) { return false; } // Recurse entries if the value is an object or array. for (const key in value) { if (!isSerializable(value[key])) return false; } return true; } /** * Plugin that checks whether state is serializable, in order to avoid * network serialization bugs. */ const SerializablePlugin = { name: 'plugin-serializable', fnWrap: (move) => (G, ctx, ...args) => { const result = move(G, ctx, ...args); // Check state in non-production environments. if (process.env.NODE_ENV !== 'production' && !isSerializable(result)) { throw new Error('Move state is not JSON-serialiazable.\n' + 'See https://boardgame.io/documentation/#/?id=state for more information.'); } return result; }, }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * List of plugins that are always added. */ const DEFAULT_PLUGINS = [ ImmerPlugin, RandomPlugin, EventsPlugin, LogPlugin, SerializablePlugin, ]; /** * Allow plugins to intercept actions and process them. */ const ProcessAction = (state, action, opts) => { opts.game.plugins .filter((plugin) => plugin.action !== undefined) .filter((plugin) => plugin.name === action.payload.type) .forEach((plugin) => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; const data = plugin.action(pluginState.data, action.payload); state = { ...state, plugins: { ...state.plugins, [name]: { ...pluginState, data }, }, }; }); return state; }; /** * The API's created by various plugins are stored in the plugins * section of the state object: * * { * G: {}, * ctx: {}, * plugins: { * plugin-a: { * data: {}, // this is generated by the plugin at Setup / Flush. * api: {}, // this is ephemeral and generated by Enhance. * } * } * } * * This function takes these API's and stuffs them back into * ctx for consumption inside a move function or hook. */ const EnhanceCtx = (state) => { const ctx = { ...state.ctx }; const plugins = state.plugins || {}; Object.entries(plugins).forEach(([name, { api }]) => { ctx[name] = api; }); return ctx; }; /** * Applies the provided plugins to the given move / flow function. * * @param {function} fn - The move function or trigger to apply the plugins to. * @param {object} plugins - The list of plugins. */ const FnWrap = (fn, plugins) => { const reducer = (acc, { fnWrap }) => fnWrap(acc); return [...DEFAULT_PLUGINS, ...plugins] .filter((plugin) => plugin.fnWrap !== undefined) .reduce(reducer, fn); }; /** * Allows the plugin to generate its initial state. */ const Setup = (state, opts) => { [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter((plugin) => plugin.setup !== undefined) .forEach((plugin) => { const name = plugin.name; const data = plugin.setup({ G: state.G, ctx: state.ctx, game: opts.game, }); state = { ...state, plugins: { ...state.plugins, [name]: { data }, }, }; }); return state; }; /** * Invokes the plugin before a move or event. * The API that the plugin generates is stored inside * the `plugins` section of the state (which is subsequently * merged into ctx). */ const Enhance = (state, opts) => { [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter((plugin) => plugin.api !== undefined) .forEach((plugin) => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; const api = plugin.api({ G: state.G, ctx: state.ctx, data: pluginState.data, game: opts.game, playerID: opts.playerID, }); state = { ...state, plugins: { ...state.plugins, [name]: { ...pluginState, api }, }, }; }); return state; }; /** * Allows plugins to update their state after a move / event. */ const Flush = (state, opts) => { // Note that we flush plugins in reverse order, to make sure that plugins // that come before in the chain are still available. [...DEFAULT_PLUGINS, ...opts.game.plugins].reverse().forEach((plugin) => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; if (plugin.flush) { const newData = plugin.flush({ G: state.G, ctx: state.ctx, game: opts.game, api: pluginState.api, data: pluginState.data, }); state = { ...state, plugins: { ...state.plugins, [plugin.name]: { data: newData }, }, }; } else if (plugin.dangerouslyFlushRawState) { state = plugin.dangerouslyFlushRawState({ state, game: opts.game, api: pluginState.api, data: pluginState.data, }); // Remove everything other than data. const data = state.plugins[name].data; state = { ...state, plugins: { ...state.plugins, [plugin.name]: { data }, }, }; } }); return state; }; /** * Allows plugins to indicate if they should not be materialized on the client. * This will cause the client to discard the state update and wait for the * master instead. */ const NoClient = (state, opts) => { return [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter((plugin) => plugin.noClient !== undefined) .map((plugin) => { const name = plugin.name; const pluginState = state.plugins[name]; if (pluginState) { return plugin.noClient({ G: state.G, ctx: state.ctx, game: opts.game, api: pluginState.api, data: pluginState.data, }); } return false; }) .some((value) => value === true); }; /** * Allows plugins to customize their data for specific players. * For example, a plugin may want to share no data with the client, or * want to keep some player data secret from opponents. */ const PlayerView = ({ G, ctx, plugins = {} }, { game, playerID }) => { [...DEFAULT_PLUGINS, ...game.plugins].forEach(({ name, playerView }) => { if (!playerView) return; const { data } = plugins[name] || { data: {} }; const newData = playerView({ G, ctx, game, data, playerID }); plugins = { ...plugins, [name]: { data: newData }, }; }); return plugins; }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const production = process.env.NODE_ENV === 'production'; const logfn = production ? () => { } : (...msg) => console.log(...msg); const errorfn = (...msg) => console.error(...msg); function info(msg) { logfn(`INFO: ${msg}`); } function error(error) { errorfn('ERROR:', error); } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Event to change the active players (and their stages) in the current turn. */ function SetActivePlayersEvent(state, _playerID, arg) { return { ...state, ctx: SetActivePlayers(state.ctx, arg) }; } function SetActivePlayers(ctx, arg) { let { _prevActivePlayers } = ctx; let activePlayers = {}; let _nextActivePlayers = null; let _activePlayersMoveLimit = {}; if (Array.isArray(arg)) { // support a simple array of player IDs as active players const value = {}; arg.forEach((v) => (value[v] = Stage.NULL)); activePlayers = value; } else { // process active players argument object if (arg.next) { _nextActivePlayers = arg.next; } _prevActivePlayers = arg.revert ? _prevActivePlayers.concat({ activePlayers: ctx.activePlayers, _activePlayersMoveLimit: ctx._activePlayersMoveLimit, _activePlayersNumMoves: ctx._activePlayersNumMoves, }) : []; if (arg.currentPlayer !== undefined) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, ctx.currentPlayer, arg.currentPlayer); } if (arg.others !== undefined) { for (let i = 0; i < ctx.playOrder.length; i++) { const id = ctx.playOrder[i]; if (id !== ctx.currentPlayer) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.others); } } } if (arg.all !== undefined) { for (let i = 0; i < ctx.playOrder.length; i++) { const id = ctx.playOrder[i]; ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.all); } } if (arg.value) { for (const id in arg.value) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.value[id]); } } if (arg.moveLimit) { for (const id in activePlayers) { if (_activePlayersMoveLimit[id] === undefined) { _activePlayersMoveLimit[id] = arg.moveLimit; } } } } if (Object.keys(activePlayers).length == 0) { activePlayers = null; } if (Object.keys(_activePlayersMoveLimit).length == 0) { _activePlayersMoveLimit = null; } const _activePlayersNumMoves = {}; for (const id in activePlayers) { _activePlayersNumMoves[id] = 0; } return { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, _nextActivePlayers, }; } /** * Update activePlayers, setting it to previous, next or null values * when it becomes empty. * @param ctx */ function UpdateActivePlayersOnceEmpty(ctx) { let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, } = ctx; if (activePlayers && Object.keys(activePlayers).length == 0) { if (ctx._nextActivePlayers) { ctx = SetActivePlayers(ctx, ctx._nextActivePlayers); ({ activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, } = ctx); } else if (_prevActivePlayers.length > 0) { const lastIndex = _prevActivePlayers.length - 1; ({ activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, } = _prevActivePlayers[lastIndex]); _prevActivePlayers = _prevActivePlayers.slice(0, lastIndex); } else { activePlayers = null; _activePlayersMoveLimit = null; } } return { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, }; } /** * Apply an active player argument to the given player ID * @param {Object} activePlayers * @param {Object} _activePlayersMoveLimit * @param {String} playerID The player to apply the parameter to * @param {(String|Object)} arg An active player argument */ function ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, playerID, arg) { if (typeof arg !== 'object' || arg === Stage.NULL) { arg = { stage: arg }; } if (arg.stage !== undefined) { activePlayers[playerID] = arg.stage; if (arg.moveLimit) _activePlayersMoveLimit[playerID] = arg.moveLimit; } } /** * Converts a playOrderPos index into its value in playOrder. * @param {Array} playOrder - An array of player ID's. * @param {number} playOrderPos - An index into the above. */ function getCurrentPlayer(playOrder, playOrderPos) { // convert to string in case playOrder is set to number[] return playOrder[playOrderPos] + ''; } /** * Called at the start of a turn to initialize turn order state. * * TODO: This is called inside StartTurn, which is called from * both UpdateTurn and StartPhase (so it's called at the beginning * of a new phase as well as between turns). We should probably * split it into two. */ function InitTurnOrderState(state, turn) { let { G, ctx } = state; const ctxWithAPI = EnhanceCtx(state); const order = turn.order; let playOrder = [...new Array(ctx.numPlayers)].map((_, i) => i + ''); if (order.playOrder !== undefined) { playOrder = order.playOrder(G, ctxWithAPI); } const playOrderPos = order.first(G, ctxWithAPI); const posType = typeof playOrderPos; if (posType !== 'number') { error(`invalid value returned by turn.order.first — expected number got ${posType} “${playOrderPos}”.`); } const currentPlayer = getCurrentPlayer(playOrder, playOrderPos); ctx = { ...ctx, currentPlayer, playOrderPos, playOrder }; ctx = SetActivePlayers(ctx, turn.activePlayers || {}); return ctx; } /** * Called at the end of each turn to update the turn order state. * @param {object} G - The game object G. * @param {object} ctx - The game object ctx. * @param {object} turn - A turn object for this phase. * @param {string} endTurnArg - An optional argument to endTurn that may specify the next player. */ function UpdateTurnOrderState(state, currentPlayer, turn, endTurnArg) { const order = turn.order; let { G, ctx } = state; let playOrderPos = ctx.playOrderPos; let endPhase = false; if (endTurnArg && endTurnArg !== true) { if (typeof endTurnArg !== 'object') { error(`invalid argument to endTurn: ${endTurnArg}`); } Object.keys(endTurnArg).forEach((arg) => { switch (arg) { case 'remove': currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos); break; case 'next': playOrderPos = ctx.playOrder.indexOf(endTurnArg.next); currentPlayer = endTurnArg.next; break; default: error(`invalid argument to endTurn: ${arg}`); } }); } else { const ctxWithAPI = EnhanceCtx(state); const t = order.next(G, ctxWithAPI); const type = typeof t; if (t !== undefined && type !== 'number') { error(`invalid value returned by turn.order.next — expected number or undefined got ${type} “${t}”.`); } if (t === undefined) { endPhase = true; } else { playOrderPos = t; currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos); } } ctx = { ...ctx, playOrderPos, currentPlayer, }; return { endPhase, ctx }; } /** * Set of different turn orders possible in a phase. * These are meant to be passed to the `turn` setting * in the flow objects. * * Each object defines the first player when the phase / game * begins, and also a function `next` to determine who the * next player is when the turn ends. * * The phase ends if next() returns undefined. */ const TurnOrder = { /** * DEFAULT * * The default round-robin turn order. */ DEFAULT: { first: (G, ctx) => ctx.turn === 0 ? ctx.playOrderPos : (ctx.playOrderPos + 1) % ctx.playOrder.length, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * RESET * * Similar to DEFAULT, but starts from 0 each time. */ RESET: { first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * CONTINUE * * Similar to DEFAULT, but starts with the player who ended the last phase. */ CONTINUE: { first: (G, ctx) => ctx.playOrderPos, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * ONCE * * Another round-robin turn order, but goes around just once. * The phase ends after all players have played. */ ONCE: { first: () => 0, next: (G, ctx) => { if (ctx.playOrderPos < ctx.playOrder.length - 1) { return ctx.playOrderPos + 1; } }, }, /** * CUSTOM * * Identical to DEFAULT, but also sets playOrder at the * beginning of the phase. * * @param {Array} playOrder - The play order. */ CUSTOM: (playOrder) => ({ playOrder: () => playOrder, first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }), /** * CUSTOM_FROM * * Identical to DEFAULT, but also sets playOrder at the * beginning of the phase to a value specified by a field * in G. * * @param {string} playOrderField - Field in G. */ CUSTOM_FROM: (playOrderField) => ({ playOrder: (G) => G[playOrderField], first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }), }; const Stage = { NULL: null, }; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Flow * * Creates a reducer that updates ctx (analogous to how moves update G). */ function Flow({ moves, phases, endIf, onEnd, turn, events, plugins, }) { // Attach defaults. if (moves === undefined) { moves = {}; } if (events === undefined) { events = {}; } if (plugins === undefined) { plugins = []; } if (phases === undefined) { phases = {}; } if (!endIf) endIf = () => undefined; if (!onEnd) onEnd = (G) => G; if (!turn) turn = {}; const phaseMap = { ...phases }; if ('' in phaseMap) { error('cannot specify phase with empty name'); } phaseMap[''] = {}; const moveMap = {}; const moveNames = new Set(); let startingPhase = null; Object.keys(moves).forEach((name) => moveNames.add(name)); const HookWrapper = (fn) => { const withPlugins = FnWrap(fn, plugins); return (state) => { const ctxWithAPI = EnhanceCtx(state); return withPlugins(state.G, ctxWithAPI); }; }; const TriggerWrapper = (endIf) => { return (state) => { const ctxWithAPI = EnhanceCtx(state); return endIf(state.G, ctxWithAPI); }; }; const wrapped = { onEnd: HookWrapper(onEnd), endIf: TriggerWrapper(endIf), }; for (const phase in phaseMap) { const conf = phaseMap[phase]; if (conf.start === true) { startingPhase = phase; } if (conf.moves !== undefined) { for (const move of Object.keys(conf.moves)) { moveMap[phase + '.' + move] = conf.moves[move]; moveNames.add(move); } } if (conf.endIf === undefined) { conf.endIf = () => undefined; } if (conf.onBegin === undefined) { conf.onBegin = (G) => G; } if (conf.onEnd === undefined) { conf.onEnd = (G) => G; } if (conf.turn === undefined) { conf.turn = turn; } if (conf.turn.order === undefined) { conf.turn.order = TurnOrder.DEFAULT; } if (conf.turn.onBegin === undefined) { conf.turn.onBegin = (G) => G; } if (conf.turn.onEnd === undefined) { conf.turn.onEnd = (G) => G; } if (conf.turn.endIf === undefined) { conf.turn.endIf = () => false; } if (conf.turn.onMove === undefined) { conf.turn.onMove = (G) => G; } if (conf.turn.stages === undefined) { conf.turn.stages = {}; } for (const stage in conf.turn.stages) { const stageConfig = conf.turn.stages[stage]; const moves = stageConfig.moves || {}; for (const move of Object.keys(moves)) { const key = phase + '.' + stage + '.' + move; moveMap[key] = moves[move]; moveNames.add(move); } } conf.wrapped = { onBegin: HookWrapper(conf.onBegin), onEnd: HookWrapper(conf.onEnd), endIf: TriggerWrapper(conf.endIf), }; conf.turn.wrapped = { onMove: HookWrapper(conf.turn.onMove), onBegin: HookWrapper(conf.turn.onBegin), onEnd: HookWrapper(conf.turn.onEnd), endIf: TriggerWrapper(conf.turn.endIf), }; } function GetPhase(ctx) { return ctx.phase ? phaseMap[ctx.phase] : phaseMap['']; } function OnMove(s) { return s; } function Process(state, events) { const phasesEnded = new Set(); const turnsEnded = new Set(); for (let i = 0; i < events.length; i++) { const { fn, arg, ...rest } = events[i]; // Detect a loop of EndPhase calls. // This could potentially even be an infinite loop // if the endIf condition of each phase blindly // returns true. The moment we detect a single // loop, we just bail out of all phases. if (fn === EndPhase) { turnsEnded.clear(); const phase = state.ctx.phase; if (phasesEnded.has(phase)) { const ctx = { ...state.ctx, phase: null }; return { ...state, ctx }; } phasesEnded.add(phase); } // Process event. const next = []; state = fn(state, { ...rest, arg, next, }); if (fn === EndGame) { break; } // Check if we should end the game. const shouldEndGame = ShouldEndGame(state); if (shouldEndGame) { events.push({ fn: EndGame, arg: shouldEndGame, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } // Check if we should end the phase. const shouldEndPhase = ShouldEndPhase(state); if (shouldEndPhase) { events.push({ fn: EndPhase, arg: shouldEndPhase, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } // Check if we should end the turn. if (fn === OnMove) { const shouldEndTurn = ShouldEndTurn(state); if (shouldEndTurn) { events.push({ fn: EndTurn, arg: shouldEndTurn, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } } events.push(...next); } return state; } /////////// // Start // /////////// function StartGame(state, { next }) { next.push({ fn: StartPhase }); return state; } function StartPhase(state, { next }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Run any phase setup code provided by the user. G = conf.wrapped.onBegin(state); next.push({ fn: StartTurn }); return { ...state, G, ctx }; } function StartTurn(state, { currentPlayer }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Initialize the turn order state. if (currentPlayer) { ctx = { ...ctx, currentPlayer }; if (conf.turn.activePlayers) { ctx = SetActivePlayers(ctx, conf.turn.activePlayers); } } else { // This is only called at the beginning of the phase // when there is no currentPlayer yet. ctx = InitTurnOrderState(state, conf.turn); } const turn = ctx.turn + 1; ctx = { ...ctx, turn, numMoves: 0, _prevActivePlayers: [] }; G = conf.turn.wrapped.onBegin({ ...state, G, ctx }); return { ...state, G, ctx, _undo: [], _redo: [] }; } //////////// // Update // //////////// function UpdatePhase(state, { arg, next, phase }) { const conf = GetPhase({ phase }); let { ctx } = state; if (arg && arg.next) { if (arg.next in phaseMap) { ctx = { ...ctx, phase: arg.next }; } else { error('invalid phase: ' + arg.next); return state; } } else if (conf.next !== undefined) { ctx = { ...ctx, phase: conf.next }; } else { ctx = { ...ctx, phase: null }; } state = { ...state, ctx }; // Start the new phase. next.push({ fn: StartPhase }); return state; } function UpdateTurn(state, { arg, currentPlayer, next }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Update turn order state. const { endPhase, ctx: newCtx } = UpdateTurnOrderState(state, currentPlayer, conf.turn, arg); ctx = newCtx; state = { ...state, G, ctx }; if (endPhase) { next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase }); } else { next.push({ fn: StartTurn, currentPlayer: ctx.currentPlayer }); } return state; } function UpdateStage(state, { arg, playerID }) { if (typeof arg === 'string' || arg === Stage.NULL) { arg = { stage: arg }; } let { ctx } = state; let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, } = ctx; // Checking if stage is valid, even Stage.NULL if (arg.stage !== undefined) { if (activePlayers === null) { activePlayers = {}; } activePlayers[playerID] = arg.stage; _activePlayersNumMoves[playerID] = 0; if (arg.moveLimit) { if (_activePlayersMoveLimit === null) { _activePlayersMoveLimit = {}; } _activePlayersMoveLimit[playerID] = arg.moveLimit; } } ctx = { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, }; return { ...state, ctx }; } /////////////// // ShouldEnd // /////////////// function ShouldEndGame(state) { return wrapped.endIf(state); } function ShouldEndPhase(state) { const conf = GetPhase(state.ctx); return conf.wrapped.endIf(state); } function ShouldEndTurn(state) { const conf = GetPhase(state.ctx); // End the turn if the required number of moves has been made. const currentPlayerMoves = state.ctx.numMoves || 0; if (conf.turn.moveLimit && currentPlayerMoves >= conf.turn.moveLimit) { return true; } return conf.turn.wrapped.endIf(state); } ///////// // End // ///////// function EndGame(state, { arg, phase }) { state = EndPhase(state, { phase }); if (arg === undefined) { arg = true; } state = { ...state, ctx: { ...state.ctx, gameover: arg } }; // Run game end hook. const G = wrapped.onEnd(state); return { ...state, G }; } function EndPhase(state, { arg, next, turn, automatic }) { // End the turn first. state = EndTurn(state, { turn, force: true, automatic: true }); let G = state.G; let ctx = state.ctx; if (next) { next.push({ fn: UpdatePhase, arg, phase: ctx.phase }); } // If we aren't in a phase, there is nothing else to do. if (ctx.phase === null) { return state; } // Run any cleanup code for the phase that is about to end. const conf = GetPhase(ctx); G = conf.wrapped.onEnd(state); // Reset the phase. ctx = { ...ctx, phase: null }; // Add log entry. const action = gameEvent('endPhase', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...(state.deltalog || []), logEntry]; return { ...state, G, ctx, deltalog }; } function EndTurn(state, { arg, next, turn, force, automatic, playerID }) { // This is not the turn that EndTurn was originally // called for. The turn was probably ended some other way. if (turn !== state.ctx.turn) { return state; } let { G, ctx } = state; const conf = GetPhase(ctx); // Prevent ending the turn if moveLimit hasn't been reached. const currentPlayerMoves = ctx.numMoves || 0; if (!force && conf.turn.moveLimit && currentPlayerMoves < conf.turn.moveLimit) { info(`cannot end turn before making ${conf.turn.moveLimit} moves`); return state; } // Run turn-end triggers. G = conf.turn.wrapped.onEnd(state); if (next) { next.push({ fn: UpdateTurn, arg, currentPlayer: ctx.currentPlayer }); } // Reset activePlayers. ctx = { ...ctx, activePlayers: null }; // Remove player from playerOrder if (arg && arg.remove) { playerID = playerID || ctx.currentPlayer; const playOrder = ctx.playOrder.filter((i) => i != playerID); const playOrderPos = ctx.playOrderPos > playOrder.length - 1 ? 0 : ctx.playOrderPos; ctx = { ...ctx, playOrder, playOrderPos }; if (playOrder.length === 0) { next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase }); return state; } } // Add log entry. const action = gameEvent('endTurn', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...(state.deltalog || []), logEntry]; return { ...state, G, ctx, deltalog, _undo: [], _redo: [] }; } function EndStage(state, { arg, next, automatic, playerID }) { playerID = playerID || state.ctx.currentPlayer; let { ctx } = state; let { activePlayers, _activePlayersMoveLimit } = ctx; const playerInStage = activePlayers !== null && playerID in activePlayers; if (!arg && playerInStage) { const conf = GetPhase(ctx); const stage = conf.turn.stages[activePlayers[playerID]]; if (stage && stage.next) arg = stage.next; } // Checking if arg is a valid stage, even Stage.NULL if (next && arg !== undefined) { next.push({ fn: UpdateStage, arg, playerID }); } // If player isn’t in a stage, there is nothing else to do. if (!playerInStage) return state; // Remove player from activePlayers. activePlayers = Object.keys(activePlayers) .filter((id) => id !== playerID) .reduce((obj, key) => { obj[key] = activePlayers[key]; return obj; }, {}); if (_activePlayersMoveLimit) { // Remove player from _activePlayersMoveLimit. _activePlayersMoveLimit = Object.keys(_activePlayersMoveLimit) .filter((id) => id !== playerID) .reduce((obj, key) => { obj[key] = _activePlayersMoveLimit[key]; return obj; }, {}); } ctx = UpdateActivePlayersOnceEmpty({ ...ctx, activePlayers, _activePlayersMoveLimit, }); // Add log entry. const action = gameEvent('endStage', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...(state.deltalog || []), logEntry]; return { ...state, ctx, deltalog }; } /** * Retrieves the relevant move that can be played by playerID. * * If ctx.activePlayers is set (i.e. one or more players are in some stage), * then it attempts to find the move inside the stages config for * that turn. If the stage for a player is '', then the player is * allowed to make a move (as determined by the phase config), but * isn't restricted to a particular set as defined in the stage config. * * If not, it then looks for the move inside the phase. * * If it doesn't find the move there, it looks at the global move definition. * * @param {object} ctx * @param {string} name * @param {string} playerID */ function GetMove(ctx, name, playerID) { const conf = GetPhase(ctx); const stages = conf.turn.stages; const { activePlayers } = ctx; if (activePlayers && activePlayers[playerID] !== undefined && activePlayers[playerID] !== Stage.NULL && stages[activePlayers[playerID]] !== undefined && stages[activePlayers[playerID]].moves !== undefined) { // Check if moves are defined for the player's stage. const stage = stages[activePlayers[playerID]]; const moves = stage.moves; if (name in moves) { return moves[name]; } } else if (conf.moves) { // Check if moves are defined for the current phase. if (name in conf.moves) { return conf.moves[name]; } } else if (name in moves) { // Check for the move globally. return moves[name]; } return null; } function ProcessMove(state, action) { const conf = GetPhase(state.ctx); const move = GetMove(state.ctx, action.type, action.playerID); const shouldCount = !move || typeof move === 'function' || move.noLimit !== true; const { ctx } = state; const { _activePlayersNumMoves } = ctx; const { playerID } = action; let numMoves = state.ctx.numMoves; if (shouldCount) { if (playerID == state.ctx.currentPlayer) { numMoves++; } if (ctx.activePlayers) _activePlayersNumMoves[playerID]++; } state = { ...state, ctx: { ...ctx, numMoves, _activePlayersNumMoves, }, }; if (ctx._activePlayersMoveLimit && _activePlayersNumMoves[playerID] >= ctx._activePlayersMoveLimit[playerID]) { state = EndStage(state, { playerID, automatic: true }); } const G = conf.turn.wrapped.onMove(state); state = { ...state, G }; const events = [{ fn: OnMove }]; return Process(state, events); } function SetStageEvent(state, playerID, arg) { return Process(state, [{ fn: EndStage, arg, playerID }]); } function EndStageEvent(state, playerID) { return Process(state, [{ fn: EndStage, playerID }]); } function SetPhaseEvent(state, _playerID, newPhase) { return Process(state, [ { fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn, arg: { next: newPhase }, }, ]); } function EndPhaseEvent(state) { return Process(state, [ { fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn }, ]); } function EndTurnEvent(state, _playerID, arg) { return Process(state, [ { fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, arg }, ]); } function PassEvent(state, _playerID, arg) { return Process(state, [ { fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, force: true, arg, }, ]); } function EndGameEvent(state, _playerID, arg) { return Process(state, [ { fn: EndGame, turn: state.ctx.turn, phase: state.ctx.phase, arg }, ]); } const eventHandlers = { endStage: EndStageEvent, setStage: SetStageEvent, endTurn: EndTurnEvent, pass: PassEvent, endPhase: EndPhaseEvent, setPhase: SetPhaseEvent, endGame: EndGameEvent, setActivePlayers: SetActivePlayersEvent, }; const enabledEventNames = []; if (events.endTurn !== false) { enabledEventNames.push('endTurn'); } if (events.pass !== false) { enabledEventNames.push('pass'); } if (events.endPhase !== false) { enabledEventNames.push('endPhase'); } if (events.setPhase !== false) { enabledEventNames.push('setPhase'); } if (events.endGame !== false) { enabledEventNames.push('endGame'); } if (events.setActivePlayers !== false) { enabledEventNames.push('setActivePlayers'); } if (events.endStage !== false) { enabledEventNames.push('endStage'); } if (events.setStage !== false) { enabledEventNames.push('setStage'); } function ProcessEvent(state, action) { const { type, playerID, args } = action.payload; if (Object.prototype.hasOwnProperty.call(eventHandlers, type)) { const eventArgs = [state, playerID].concat(args); return eventHandlers[type].apply({}, eventArgs); } return state; } function IsPlayerActive(_G, ctx, playerID) { if (ctx.activePlayers) { return playerID in ctx.activePlayers; } return ctx.currentPlayer === playerID; } return { ctx: (numPlayers) => ({ numPlayers, turn: 0, currentPlayer: '0', playOrder: [...new Array(numPlayers)].map((_d, i) => i + ''), playOrderPos: 0, phase: startingPhase, activePlayers: null, }), init: (state) => { return Process(state, [{ fn: StartGame }]); }, isPlayerActive: IsPlayerActive, eventHandlers, eventNames: Object.keys(eventHandlers), enabledEventNames, moveMap, moveNames: [...moveNames.values()], processMove: ProcessMove, processEvent: ProcessEvent, getMove: GetMove, }; } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ function IsProcessed(game) { return game.processMove !== undefined; } /** * Helper to generate the game move reducer. The returned * reducer has the following signature: * * (G, action, ctx) => {} * * You can roll your own if you like, or use any Redux * addon to generate such a reducer. * * The convention used in this framework is to * have action.type contain the name of the move, and * action.args contain any additional arguments as an * Array. */ function ProcessGameConfig(game) { // The Game() function has already been called on this // config object, so just pass it through. if (IsProcessed(game)) { return game; } if (game.name === undefined) game.name = 'default'; if (game.deltaState === undefined) game.deltaState = false; if (game.disableUndo === undefined) game.disableUndo = false; if (game.setup === undefined) game.setup = () => ({}); if (game.moves === undefined) game.moves = {}; if (game.playerView === undefined) game.playerView = (G) => G; if (game.plugins === undefined) game.plugins = []; game.plugins.forEach((plugin) => { if (plugin.name === undefined) { throw new Error('Plugin missing name attribute'); } if (plugin.name.includes(' ')) { throw new Error(plugin.name + ': Plugin name must not include spaces'); } }); if (game.name.includes(' ')) { throw new Error(game.name + ': Game name must not include spaces'); } const flow = Flow(game); return { ...game, flow, moveNames: flow.moveNames, pluginNames: game.plugins.map((p) => p.name), processMove: (state, action) => { let moveFn = flow.getMove(state.ctx, action.type, action.playerID); if (IsLongFormMove(moveFn)) { moveFn = moveFn.move; } if (moveFn instanceof Function) { const fn = FnWrap(moveFn, game.plugins); const ctxWithAPI = { ...EnhanceCtx(state), playerID: action.playerID, }; let args = []; if (action.args !== undefined) { args = args.concat(action.args); } return fn(state.G, ctxWithAPI, ...args); } error(`invalid move object: ${action.type}`); return state.G; }, }; } function IsLongFormMove(move) { return move instanceof Object && move.move !== undefined; } /* * Copyright 2020 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Creates the initial game state. */ function InitializeGame({ game, numPlayers, setupData, }) { game = ProcessGameConfig(game); if (!numPlayers) { numPlayers = 2; } const ctx = game.flow.ctx(numPlayers); let state = { // User managed state. G: {}, // Framework managed state. ctx, // Plugin related state. plugins: {}, }; // Run plugins over initial state. state = Setup(state, { game }); state = Enhance(state, { game, playerID: undefined }); const enhancedCtx = EnhanceCtx(state); state.G = game.setup(enhancedCtx, setupData); let initial = { ...state, // List of {G, ctx} pairs that can be undone. _undo: [], // List of {G, ctx} pairs that can be redone. _redo: [], // A monotonically non-decreasing ID to ensure that // state updates are only allowed from clients that // are at the same version that the server. _stateID: 0, }; initial = game.flow.init(initial); initial = Flush(initial, { game }); // Initialize undo stack. if (!game.disableUndo) { initial._undo = [ { G: initial.G, ctx: initial.ctx, plugins: initial.plugins, }, ]; } return initial; } /** * Creates a new match metadata object. */ const createMetadata = ({ game, unlisted, setupData, numPlayers, }) => { const metadata = { gameName: game.name, unlisted: !!unlisted, players: {}, createdAt: Date.now(), updatedAt: Date.now(), }; if (setupData !== undefined) metadata.setupData = setupData; for (let playerIndex = 0; playerIndex < numPlayers; playerIndex++) { metadata.players[playerIndex] = { id: playerIndex }; } return metadata; }; /** * Creates matchID, initial state and metadata for a new match. * If the provided `setupData` doesn’t pass the game’s validation, * an error object is returned instead. */ const createMatch = ({ game, numPlayers, setupData, unlisted, }) => { if (!numPlayers || typeof numPlayers !== 'number') numPlayers = 2; const setupDataError = game.validateSetupData && game.validateSetupData(setupData, numPlayers); if (setupDataError !== undefined) return { setupDataError }; const metadata = createMetadata({ game, numPlayers, setupData, unlisted }); const initialState = InitializeGame({ game, numPlayers, setupData }); return { metadata, initialState }; }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Creates a new match. * * @param {object} db - The storage API. * @param {object} game - The game config object. * @param {number} numPlayers - The number of players. * @param {object} setupData - User-defined object that's available * during game setup. * @param {object } lobbyConfig - Configuration options for the lobby. * @param {boolean} unlisted - Whether the match should be excluded from public listing. */ const CreateMatch = async ({ ctx, db, uuid, ...opts }) => { const matchID = uuid(); const match = createMatch(opts); if ('setupDataError' in match) { ctx.throw(400, match.setupDataError); } else { await db.createMatch(matchID, match); return matchID; } }; /** * Create a metadata object without secret credentials to return to the client. * * @param {string} matchID - The identifier of the match the metadata belongs to. * @param {object} metadata - The match metadata object to strip credentials from. * @return - A metadata object without player credentials. */ const createClientMatchData = (matchID, metadata) => { return { ...metadata, matchID, players: Object.values(metadata.players).map((player) => { // strip away credentials const { credentials, ...strippedInfo } = player; return strippedInfo; }), }; }; const createRouter = ({ db, auth, games, uuid = () => nanoid.nanoid(11), }) => { const router = new Router(); /** * List available games. * * @return - Array of game names as string. */ router.get('/games', async (ctx) => { const body = games.map((game) => game.name); ctx.body = body; }); /** * Create a new match of a given game. * * @param {string} name - The name of the game of the new match. * @param {number} numPlayers - The number of players. * @param {object} setupData - User-defined object that's available * during game setup. * @param {boolean} unlisted - Whether the match should be excluded from public listing. * @return - The ID of the created match. */ router.post('/games/:name/create', koaBody(), async (ctx) => { // The name of the game (for example: tic-tac-toe). const gameName = ctx.params.name; // User-data to pass to the game setup function. const setupData = ctx.request.body.setupData; // Whether the game should be excluded from public listing. const unlisted = ctx.request.body.unlisted; // The number of players for this game instance. const numPlayers = Number.parseInt(ctx.request.body.numPlayers); const game = games.find((g) => g.name === gameName); if (!game) ctx.throw(404, 'Game ' + gameName + ' not found'); const matchID = await CreateMatch({ ctx, db, game, numPlayers, setupData, uuid, unlisted, }); const body = { matchID }; ctx.body = body; }); /** * List matches for a given game. * * This does not return matches that are marked as unlisted. * * @param {string} name - The name of the game. * @return - Array of match objects. */ router.get('/games/:name', async (ctx) => { const gameName = ctx.params.name; const { isGameover: isGameoverString, updatedBefore: updatedBeforeString, updatedAfter: updatedAfterString, } = ctx.query; let isGameover; if (isGameoverString) { if (isGameoverString.toLowerCase() === 'true') { isGameover = true; } else if (isGameoverString.toLowerCase() === 'false') { isGameover = false; } } let updatedBefore; if (updatedBeforeString) { const parsedNumber = Number.parseInt(updatedBeforeString, 10); if (parsedNumber > 0) { updatedBefore = parsedNumber; } } let updatedAfter; if (updatedAfterString) { const parsedNumber = Number.parseInt(updatedAfterString, 10); if (parsedNumber > 0) { updatedAfter = parsedNumber; } } const matchList = await db.listMatches({ gameName, where: { isGameover, updatedAfter, updatedBefore, }, }); const matches = []; for (const matchID of matchList) { const { metadata } = await db.fetch(matchID, { metadata: true, }); if (!metadata.unlisted) { matches.push(createClientMatchData(matchID, metadata)); } } const body = { matches }; ctx.body = body; }); /** * Get data about a specific match. * * @param {string} name - The name of the game. * @param {string} id - The ID of the match. * @return - A match object. */ router.get('/games/:name/:id', async (ctx) => { const matchID = ctx.params.id; const { metadata } = await db.fetch(matchID, { metadata: true, }); if (!metadata) { ctx.throw(404, 'Match ' + matchID + ' not found'); } const body = createClientMatchData(matchID, metadata); ctx.body = body; }); /** * Join a given match. * * @param {string} name - The name of the game. * @param {string} id - The ID of the match. * @param {string} playerID - The ID of the player who joins. * @param {string} playerName - The name of the player who joins. * @param {object} data - The default data of the player in the match. * @return - Player credentials to use when interacting in the joined match. */ router.post('/games/:name/:id/join', koaBody(), async (ctx) => { const playerID = ctx.request.body.playerID; const playerName = ctx.request.body.playerName; const data = ctx.request.body.data; if (typeof playerID === 'undefined' || playerID === null) { ctx.throw(403, 'playerID is required'); } if (!playerName) { ctx.throw(403, 'playerName is required'); } const matchID = ctx.params.id; const { metadata } = await db.fetch(matchID, { metadata: true, }); if (!metadata) { ctx.throw(404, 'Match ' + matchID + ' not found'); } if (!metadata.players[playerID]) { ctx.throw(404, 'Player ' + playerID + ' not found'); } if (metadata.players[playerID].name) { ctx.throw(409, 'Player ' + playerID + ' not available'); } if (data) { metadata.players[playerID].data = data; } metadata.players[playerID].name = playerName; const playerCredentials = await auth.generateCredentials(ctx); metadata.players[playerID].credentials = playerCredentials; await db.setMetadata(matchID, metadata); const body = { playerCredentials }; ctx.body = body; }); /** * Leave a given match. * * @param {string} name - The name of the game. * @param {string} id - The ID of the match. * @param {string} playerID - The ID of the player who leaves. * @param {string} credentials - The credentials of the player who leaves. * @return - Nothing. */ router.post('/games/:name/:id/leave', koaBody(), async (ctx) => { const matchID = ctx.params.id; const playerID = ctx.request.body.playerID; const credentials = ctx.request.body.credentials; const { metadata } = await db.fetch(matchID, { metadata: true, }); if (typeof playerID === 'undefined' || playerID === null) { ctx.throw(403, 'playerID is required'); } if (!metadata) { ctx.throw(404, 'Match ' + matchID + ' not found'); } if (!metadata.players[playerID]) { ctx.throw(404, 'Player ' + playerID + ' not found'); } const isAuthorized = await auth.authenticateCredentials({ playerID, credentials, metadata, }); if (!isAuthorized) { ctx.throw(403, 'Invalid credentials ' + credentials); } delete metadata.players[playerID].name; delete metadata.players[playerID].credentials; const hasPlayers = Object.values(metadata.players).some(({ name }) => name); await (hasPlayers ? db.setMetadata(matchID, metadata) // Update metadata. : db.wipe(matchID)); // Delete match. ctx.body = {}; }); /** * Start a new match based on another existing match. * * @param {string} name - The name of the game. * @param {string} id - The ID of the match. * @param {string} playerID - The ID of the player creating the match. * @param {string} credentials - The credentials of the player creating the match. * @param {boolean} unlisted - Whether the match should be excluded from public listing. * @return - The ID of the new match. */ router.post('/games/:name/:id/playAgain', koaBody(), async (ctx) => { const gameName = ctx.params.name; const matchID = ctx.params.id; const playerID = ctx.request.body.playerID; const credentials = ctx.request.body.credentials; const unlisted = ctx.request.body.unlisted; const { metadata } = await db.fetch(matchID, { metadata: true, }); if (typeof playerID === 'undefined' || playerID === null) { ctx.throw(403, 'playerID is required'); } if (!metadata) { ctx.throw(404, 'Match ' + matchID + ' not found'); } if (!metadata.players[playerID]) { ctx.throw(404, 'Player ' + playerID + ' not found'); } const isAuthorized = await auth.authenticateCredentials({ playerID, credentials, metadata, }); if (!isAuthorized) { ctx.throw(403, 'Invalid credentials ' + credentials); } // Check if nextMatch is already set, if so, return that id. if (metadata.nextMatchID) { ctx.body = { nextMatchID: metadata.nextMatchID }; return; } // User-data to pass to the game setup function. const setupData = ctx.request.body.setupData || metadata.setupData; // The number of players for this game instance. const numPlayers = Number.parseInt(ctx.request.body.numPlayers) || Object.keys(metadata.players).length; const game = games.find((g) => g.name === gameName); const nextMatchID = await CreateMatch({ ctx, db, game, numPlayers, setupData, uuid, unlisted, }); metadata.nextMatchID = nextMatchID; await db.setMetadata(matchID, metadata); const body = { nextMatchID }; ctx.body = body; }); const updatePlayerMetadata = async (ctx) => { const matchID = ctx.params.id; const playerID = ctx.request.body.playerID; const credentials = ctx.request.body.credentials; const newName = ctx.request.body.newName; const data = ctx.request.body.data; const { metadata } = await db.fetch(matchID, { metadata: true, }); if (typeof playerID === 'undefined') { ctx.throw(403, 'playerID is required'); } if (data === undefined && !newName) { ctx.throw(403, 'newName or data is required'); } if (newName && typeof newName !== 'string') { ctx.throw(403, `newName must be a string, got ${typeof newName}`); } if (!metadata) { ctx.throw(404, 'Match ' + matchID + ' not found'); } if (!metadata.players[playerID]) { ctx.throw(404, 'Player ' + playerID + ' not found'); } const isAuthorized = await auth.authenticateCredentials({ playerID, credentials, metadata, }); if (!isAuthorized) { ctx.throw(403, 'Invalid credentials ' + credentials); } if (newName) { metadata.players[playerID].name = newName; } if (data) { metadata.players[playerID].data = data; } await db.setMetadata(matchID, metadata); ctx.body = {}; }; /** * Change the name of a player in a given match. * * @param {string} name - The name of the game. * @param {string} id - The ID of the match. * @param {string} playerID - The ID of the player. * @param {string} credentials - The credentials of the player. * @param {object} newName - The new name of the player in the match. * @return - Nothing. */ router.post('/games/:name/:id/rename', koaBody(), async (ctx) => { console.warn('This endpoint /rename is deprecated. Please use /update instead.'); await updatePlayerMetadata(ctx); }); /** * Update the player's data for a given match. * * @param {string} name - The name of the game. * @param {string} id - The ID of the match. * @param {string} playerID - The ID of the player. * @param {string} credentials - The credentials of the player. * @param {object} newName - The new name of the player in the match. * @param {object} data - The new data of the player in the match. * @return - Nothing. */ router.post('/games/:name/:id/update', koaBody(), updatePlayerMetadata); return router; }; const configureApp = (app, router) => { app.use(cors()); // If API_SECRET is set, then require that requests set an // api-secret header that is set to the same value. app.use(async (ctx, next) => { if (!!process.env.API_SECRET && ctx.request.headers['api-secret'] !== process.env.API_SECRET) { ctx.throw(403, 'Invalid API secret'); } await next(); }); app.use(router.routes()).use(router.allowedMethods()); }; var Type; (function (Type) { Type[Type["SYNC"] = 0] = "SYNC"; Type[Type["ASYNC"] = 1] = "ASYNC"; })(Type || (Type = {})); /** * Type guard that checks if a storage implementation is synchronous. */ function isSynchronous(storageAPI) { return storageAPI.type() === Type.SYNC; } class Async { /* istanbul ignore next */ type() { /* istanbul ignore next */ return Type.ASYNC; } /** * Create a new match. * * This might just need to call setState and setMetadata in * most implementations. * * However, it exists as a separate call so that the * implementation can provision things differently when * a match is created. For example, it might stow away the * initial match state in a separate field for easier retrieval. */ /* istanbul ignore next */ async createMatch(matchID, opts) { if (this.createGame) { console.warn('The database connector does not implement a createMatch method.', '\nUsing the deprecated createGame method instead.'); return this.createGame(matchID, opts); } else { console.error('The database connector does not implement a createMatch method.'); } } /** * Return all matches. */ /* istanbul ignore next */ async listMatches(opts) { if (this.listGames) { console.warn('The database connector does not implement a listMatches method.', '\nUsing the deprecated listGames method instead.'); return this.listGames(opts); } else { console.error('The database connector does not implement a listMatches method.'); } } } class Sync { type() { return Type.SYNC; } /** * Connect. */ connect() { return; } /** * Create a new match. * * This might just need to call setState and setMetadata in * most implementations. * * However, it exists as a separate call so that the * implementation can provision things differently when * a match is created. For example, it might stow away the * initial match state in a separate field for easier retrieval. */ /* istanbul ignore next */ createMatch(matchID, opts) { if (this.createGame) { console.warn('The database connector does not implement a createMatch method.', '\nUsing the deprecated createGame method instead.'); return this.createGame(matchID, opts); } else { console.error('The database connector does not implement a createMatch method.'); } } /** * Return all matches. */ /* istanbul ignore next */ listMatches(opts) { if (this.listGames) { console.warn('The database connector does not implement a listMatches method.', '\nUsing the deprecated listGames method instead.'); return this.listGames(opts); } else { console.error('The database connector does not implement a listMatches method.'); } } } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * InMemory data storage. */ class InMemory extends Sync { /** * Creates a new InMemory storage. */ constructor() { super(); this.state = new Map(); this.initial = new Map(); this.metadata = new Map(); this.log = new Map(); } /** * Create a new match. * * @override */ createMatch(matchID, opts) { this.initial.set(matchID, opts.initialState); this.setState(matchID, opts.initialState); this.setMetadata(matchID, opts.metadata); } /** * Write the match metadata to the in-memory object. */ setMetadata(matchID, metadata) { this.metadata.set(matchID, metadata); } /** * Write the match state to the in-memory object. */ setState(matchID, state, deltalog) { if (deltalog && deltalog.length > 0) { const log = this.log.get(matchID) || []; this.log.set(matchID, log.concat(deltalog)); } this.state.set(matchID, state); } /** * Fetches state for a particular matchID. */ fetch(matchID, opts) { const result = {}; if (opts.state) { result.state = this.state.get(matchID); } if (opts.metadata) { result.metadata = this.metadata.get(matchID); } if (opts.log) { result.log = this.log.get(matchID) || []; } if (opts.initialState) { result.initialState = this.initial.get(matchID); } return result; } /** * Remove the match state from the in-memory object. */ wipe(matchID) { this.state.delete(matchID); this.metadata.delete(matchID); } /** * Return all keys. * * @override */ listMatches(opts) { return [...this.metadata.entries()] .filter(([, metadata]) => { if (!opts) { return true; } if (opts.gameName !== undefined && metadata.gameName !== opts.gameName) { return false; } if (opts.where !== undefined) { if (opts.where.isGameover !== undefined) { const isGameover = metadata.gameover !== undefined; if (isGameover !== opts.where.isGameover) { return false; } } if (opts.where.updatedBefore !== undefined && metadata.updatedAt >= opts.where.updatedBefore) { return false; } if (opts.where.updatedAfter !== undefined && metadata.updatedAt <= opts.where.updatedAfter) { return false; } } return true; }) .map(([key]) => key); } } /** * FlatFile data storage. */ class FlatFile extends Async { constructor({ dir, logging, ttl }) { super(); this.games = require('node-persist'); this.dir = dir; this.logging = logging || false; this.ttl = ttl || false; this.fileQueues = {}; } async chainRequest(key, request) { if (!(key in this.fileQueues)) this.fileQueues[key] = Promise.resolve(); this.fileQueues[key] = this.fileQueues[key].then(request, request); return this.fileQueues[key]; } async getItem(key) { return this.chainRequest(key, () => this.games.getItem(key)); } async setItem(key, value) { return this.chainRequest(key, () => this.games.setItem(key, value)); } async removeItem(key) { return this.chainRequest(key, () => this.games.removeItem(key)); } async connect() { await this.games.init({ dir: this.dir, logging: this.logging, ttl: this.ttl, }); return; } /** * Create new match. * * @param matchID * @param opts * @override */ async createMatch(matchID, opts) { // Store initial state separately for easy retrieval later. const key = InitialStateKey(matchID); await this.setItem(key, opts.initialState); await this.setState(matchID, opts.initialState); await this.setMetadata(matchID, opts.metadata); } async fetch(matchID, opts) { const result = {}; if (opts.state) { result.state = (await this.getItem(matchID)); } if (opts.metadata) { const key = MetadataKey(matchID); result.metadata = (await this.getItem(key)); } if (opts.log) { const key = LogKey(matchID); result.log = (await this.getItem(key)); } if (opts.initialState) { const key = InitialStateKey(matchID); result.initialState = (await this.getItem(key)); } return result; } async clear() { return this.games.clear(); } async setState(id, state, deltalog) { if (deltalog && deltalog.length > 0) { const key = LogKey(id); const log = (await this.getItem(key)) || []; await this.setItem(key, log.concat(deltalog)); } return await this.setItem(id, state); } async setMetadata(id, metadata) { const key = MetadataKey(id); return await this.setItem(key, metadata); } async wipe(id) { const keys = await this.games.keys(); if (!keys.includes(id)) return; await this.removeItem(id); await this.removeItem(InitialStateKey(id)); await this.removeItem(LogKey(id)); await this.removeItem(MetadataKey(id)); } /** * List matches IDs. * * @param opts * @override */ async listMatches(opts) { const keys = await this.games.keys(); const suffix = ':metadata'; const arr = await Promise.all(keys.map(async (k) => { if (!k.endsWith(suffix)) { return false; } const matchID = k.slice(0, k.length - suffix.length); if (!opts) { return matchID; } const game = await this.fetch(matchID, { state: true, metadata: true, }); if (opts.gameName && opts.gameName !== game.metadata.gameName) { return false; } if (opts.where !== undefined) { if (typeof opts.where.isGameover !== 'undefined') { const isGameover = typeof game.metadata.gameover !== 'undefined'; if (isGameover !== opts.where.isGameover) { return false; } } if (typeof opts.where.updatedBefore !== 'undefined' && game.metadata.updatedAt >= opts.where.updatedBefore) { return false; } if (typeof opts.where.updatedAfter !== 'undefined' && game.metadata.updatedAt <= opts.where.updatedAfter) { return false; } } return matchID; })); return arr.filter((r) => typeof r === 'string'); } } function InitialStateKey(matchID) { return `${matchID}:initial`; } function MetadataKey(matchID) { return `${matchID}:metadata`; } function LogKey(matchID) { return `${matchID}:log`; } const DBFromEnv = () => { return process.env.FLATFILE_DIR ? new FlatFile({ dir: process.env.FLATFILE_DIR, }) : new InMemory(); }; /** * Verifies that a match has metadata and is using credentials. */ const doesMatchRequireAuthentication = (matchData) => { if (!matchData) return false; const { players } = matchData; const hasCredentials = Object.values(players).some((player) => !!(player && player.credentials)); return hasCredentials; }; /** * The default `authenticateCredentials` method. * Verifies that the provided credentials match the player’s metadata. */ const areCredentialsAuthentic = (actionCredentials, playerMetadata) => { if (!actionCredentials) return false; if (!playerMetadata) return false; return actionCredentials === playerMetadata.credentials; }; /** * Extracts a player’s metadata from the match data object. */ const extractPlayerMetadata = (matchData, playerID) => { if (matchData && matchData.players) { return matchData.players[playerID]; } }; /** * Class that provides authentication methods to the lobby server & transport. */ class Auth { constructor(opts = {}) { this.shouldAuthenticate = doesMatchRequireAuthentication; this.authenticate = areCredentialsAuthentic; /** * Generate credentials string from the Koa context. */ this.generateCredentials = () => nanoid.nanoid(); if (typeof opts.authenticateCredentials === 'function') { this.authenticate = opts.authenticateCredentials; this.shouldAuthenticate = () => true; } if (typeof opts.generateCredentials === 'function') { this.generateCredentials = opts.generateCredentials; } } /** * Resolves to true if the provided credentials are valid for the given * metadata and player IDs, or if the match does not require authentication. */ authenticateCredentials({ playerID, credentials, metadata, }) { const playerMetadata = extractPlayerMetadata(metadata, playerID); return this.shouldAuthenticate(metadata) ? this.authenticate(credentials, playerMetadata) : true; } } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Check if the payload for the passed action contains a playerID. */ const actionHasPlayerID = (action) => action.payload.playerID !== null && action.payload.playerID !== undefined; /** * Returns true if a move can be undone. */ const CanUndoMove = (G, ctx, move) => { function HasUndoable(move) { return move.undoable !== undefined; } function IsFunction(undoable) { return undoable instanceof Function; } if (!HasUndoable(move)) { return true; } if (IsFunction(move.undoable)) { return move.undoable(G, ctx); } return move.undoable; }; /** * Update the undo and redo stacks for a move or event. */ function updateUndoRedoState(state, opts) { if (opts.game.disableUndo) return state; const undoEntry = { G: state.G, ctx: state.ctx, plugins: state.plugins, playerID: opts.action.payload.playerID || state.ctx.currentPlayer, }; if (opts.action.type === 'MAKE_MOVE') { undoEntry.moveType = opts.action.payload.type; } return { ...state, _undo: [...state._undo, undoEntry], // Always reset redo stack when making a move or event _redo: [], }; } /** * Process state, adding the initial deltalog for this action. */ function initializeDeltalog(state, action, move) { // Create a log entry for this action. const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; const pluginLogMetadata = state.plugins.log.data.metadata; if (pluginLogMetadata !== undefined) { logEntry.metadata = pluginLogMetadata; } if (typeof move === 'object' && move.redact === true) { logEntry.redact = true; } return { ...state, deltalog: [logEntry], }; } /** * CreateGameReducer * * Creates the main game state reducer. */ function CreateGameReducer({ game, isClient, }) { game = ProcessGameConfig(game); /** * GameReducer * * Redux reducer that maintains the overall game state. * @param {object} state - The state before the action. * @param {object} action - A Redux action. */ return (state = null, action) => { switch (action.type) { case GAME_EVENT: { state = { ...state, deltalog: [] }; // Process game events only on the server. // These events like `endTurn` typically // contain code that may rely on secret state // and cannot be computed on the client. if (isClient) { return state; } // Disallow events once the game is over. if (state.ctx.gameover !== undefined) { error(`cannot call event after game end`); return state; } // Ignore the event if the player isn't active. if (actionHasPlayerID(action) && !game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) { error(`disallowed event: ${action.payload.type}`); return state; } // Execute plugins. state = Enhance(state, { game, isClient: false, playerID: action.payload.playerID, }); // Process event. let newState = game.flow.processEvent(state, action); // Execute plugins. newState = Flush(newState, { game, isClient: false }); // Update undo / redo state. newState = updateUndoRedoState(newState, { game, action }); return { ...newState, _stateID: state._stateID + 1 }; } case MAKE_MOVE: { state = { ...state, deltalog: [] }; // Check whether the move is allowed at this time. const move = game.flow.getMove(state.ctx, action.payload.type, action.payload.playerID || state.ctx.currentPlayer); if (move === null) { error(`disallowed move: ${action.payload.type}`); return state; } // Don't run move on client if move says so. if (isClient && move.client === false) { return state; } // Disallow moves once the game is over. if (state.ctx.gameover !== undefined) { error(`cannot make move after game end`); return state; } // Ignore the move if the player isn't active. if (actionHasPlayerID(action) && !game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) { error(`disallowed move: ${action.payload.type}`); return state; } // Execute plugins. state = Enhance(state, { game, isClient, playerID: action.payload.playerID, }); // Process the move. const G = game.processMove(state, action.payload); // The game declared the move as invalid. if (G === INVALID_MOVE) { error(`invalid move: ${action.payload.type} args: ${action.payload.args}`); return state; } const newState = { ...state, G }; // Some plugin indicated that it is not suitable to be // materialized on the client (and must wait for the server // response instead). if (isClient && NoClient(newState, { game })) { return state; } state = newState; // If we're on the client, just process the move // and no triggers in multiplayer mode. // These will be processed on the server, which // will send back a state update. if (isClient) { state = Flush(state, { game, isClient: true, }); return { ...state, _stateID: state._stateID + 1, }; } // On the server, construct the deltalog. state = initializeDeltalog(state, action, move); // Allow the flow reducer to process any triggers that happen after moves. state = game.flow.processMove(state, action.payload); state = Flush(state, { game }); // Update undo / redo state. state = updateUndoRedoState(state, { game, action }); return { ...state, _stateID: state._stateID + 1, }; } case RESET: case UPDATE: case SYNC: { return action.state; } case UNDO: { state = { ...state, deltalog: [] }; if (game.disableUndo) { error('Undo is not enabled'); return state; } const { _undo, _redo } = state; if (_undo.length < 2) { return state; } const last = _undo[_undo.length - 1]; const restore = _undo[_undo.length - 2]; // Only allow players to undo their own moves. if (actionHasPlayerID(action) && action.payload.playerID !== last.playerID) { return state; } // Only allow undoable moves to be undone. const lastMove = game.flow.getMove(restore.ctx, last.moveType, last.playerID); if (!CanUndoMove(state.G, state.ctx, lastMove)) { return state; } state = initializeDeltalog(state, action); return { ...state, G: restore.G, ctx: restore.ctx, plugins: restore.plugins, _stateID: state._stateID + 1, _undo: _undo.slice(0, -1), _redo: [last, ..._redo], }; } case REDO: { state = { ...state, deltalog: [] }; if (game.disableUndo) { error('Redo is not enabled'); return state; } const { _undo, _redo } = state; if (_redo.length == 0) { return state; } const first = _redo[0]; // Only allow players to redo their own undos. if (actionHasPlayerID(action) && action.payload.playerID !== first.playerID) { return state; } state = initializeDeltalog(state, action); return { ...state, G: first.G, ctx: first.ctx, plugins: first.plugins, _stateID: state._stateID + 1, _undo: [..._undo, first], _redo: _redo.slice(1), }; } case PLUGIN: { return ProcessAction(state, action, { game }); } case PATCH: { const oldState = state; const newState = JSON.parse(JSON.stringify(oldState)); const patchError = rfc6902.applyPatch(newState, action.patch); const hasError = patchError.some((entry) => entry !== null); if (hasError) { error(`Patch ${JSON.stringify(action.patch)} apply failed`); return oldState; } else { return newState; } } default: { return state; } } }; } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Filter match data to get a player metadata object with credentials stripped. */ const filterMatchData = (matchData) => Object.values(matchData.players).map((player) => { const { credentials, ...filteredData } = player; return filteredData; }); /** * Redact the log. * * @param {Array} log - The game log (or deltalog). * @param {String} playerID - The playerID that this log is * to be sent to. */ function redactLog(log, playerID) { if (log === undefined) { return log; } return log.map((logEvent) => { // filter for all other players and spectators. if (playerID !== null && +playerID === +logEvent.action.payload.playerID) { return logEvent; } if (logEvent.redact !== true) { return logEvent; } const payload = { ...logEvent.action.payload, args: null, }; const filteredEvent = { ...logEvent, action: { ...logEvent.action, payload }, }; const { redact, ...remaining } = filteredEvent; return remaining; }); } /** * Remove player credentials from action payload */ const stripCredentialsFromAction = (action) => { const { credentials, ...payload } = action.payload; return { ...action, payload }; }; /** * Master * * Class that runs the game and maintains the authoritative state. * It uses the transportAPI to communicate with clients and the * storageAPI to communicate with the database. */ class Master { constructor(game, storageAPI, transportAPI, auth) { this.game = ProcessGameConfig(game); this.storageAPI = storageAPI; this.transportAPI = transportAPI; this.subscribeCallback = () => { }; this.auth = auth; } subscribe(fn) { this.subscribeCallback = fn; } /** * Called on each move / event made by the client. * Computes the new value of the game state and returns it * along with a deltalog. */ async onUpdate(credAction, stateID, matchID, playerID) { let metadata; if (isSynchronous(this.storageAPI)) { ({ metadata } = this.storageAPI.fetch(matchID, { metadata: true })); } else { ({ metadata } = await this.storageAPI.fetch(matchID, { metadata: true })); } if (this.auth) { const isAuthentic = await this.auth.authenticateCredentials({ playerID, credentials: credAction.payload.credentials, metadata, }); if (!isAuthentic) { return { error: 'unauthorized action' }; } } const action = stripCredentialsFromAction(credAction); const key = matchID; let state; if (isSynchronous(this.storageAPI)) { ({ state } = this.storageAPI.fetch(key, { state: true })); } else { ({ state } = await this.storageAPI.fetch(key, { state: true })); } if (state === undefined) { error(`game not found, matchID=[${key}]`); return { error: 'game not found' }; } if (state.ctx.gameover !== undefined) { error(`game over - matchID=[${key}] - playerID=[${playerID}]` + ` - action[${action.payload.type}]`); return; } const reducer = CreateGameReducer({ game: this.game, }); const store = redux.createStore(reducer, state); // Only allow UNDO / REDO if there is exactly one player // that can make moves right now and the person doing the // action is that player. if (action.type == UNDO || action.type == REDO) { const hasActivePlayers = state.ctx.activePlayers !== null; const isCurrentPlayer = state.ctx.currentPlayer === playerID; if ( // If activePlayers is empty, non-current players can’t undo. (!hasActivePlayers && !isCurrentPlayer) || // If player is not active or multiple players are active, can’t undo. (hasActivePlayers && (state.ctx.activePlayers[playerID] === undefined || Object.keys(state.ctx.activePlayers).length > 1))) { error(`playerID=[${playerID}] cannot undo / redo right now`); return; } } // Check whether the player is active. if (!this.game.flow.isPlayerActive(state.G, state.ctx, playerID)) { error(`player not active - playerID=[${playerID}]` + ` - action[${action.payload.type}]`); return; } // Get move for further checks const move = action.type == MAKE_MOVE ? this.game.flow.getMove(state.ctx, action.payload.type, playerID) : null; // Check whether the player is allowed to make the move. if (action.type == MAKE_MOVE && !move) { error(`move not processed - canPlayerMakeMove=false - playerID=[${playerID}]` + ` - action[${action.payload.type}]`); return; } // Check if action's stateID is different than store's stateID // and if move does not have ignoreStaleStateID truthy. if (state._stateID !== stateID && !(move && IsLongFormMove(move) && move.ignoreStaleStateID)) { error(`invalid stateID, was=[${stateID}], expected=[${state._stateID}]` + ` - playerID=[${playerID}] - action[${action.payload.type}]`); return; } const prevState = store.getState(); // Update server's version of the store. store.dispatch(action); state = store.getState(); this.subscribeCallback({ state, action, matchID, }); this.transportAPI.sendAll((playerID) => { const log = redactLog(state.deltalog, playerID); const filteredState = { ...state, G: this.game.playerView(state.G, state.ctx, playerID), plugins: PlayerView(state, { playerID, game: this.game }), deltalog: undefined, _undo: [], _redo: [], }; if (this.game.deltaState) { const newStateID = state._stateID; const prevFilteredState = { ...prevState, G: this.game.playerView(prevState.G, prevState.ctx, playerID), plugins: PlayerView(prevState, { playerID, game: this.game }), deltalog: undefined, _undo: [], _redo: [], }; const patch = rfc6902.createPatch(prevFilteredState, filteredState); return { type: 'patch', args: [matchID, stateID, newStateID, patch, log], }; } else { return { type: 'update', args: [matchID, filteredState, log], }; } }); const { deltalog, ...stateWithoutDeltalog } = state; let newMetadata; if (metadata && !('gameover' in metadata)) { newMetadata = { ...metadata, updatedAt: Date.now(), }; if (state.ctx.gameover !== undefined) { newMetadata.gameover = state.ctx.gameover; } } if (isSynchronous(this.storageAPI)) { this.storageAPI.setState(key, stateWithoutDeltalog, deltalog); if (newMetadata) this.storageAPI.setMetadata(key, newMetadata); } else { const writes = [ this.storageAPI.setState(key, stateWithoutDeltalog, deltalog), ]; if (newMetadata) { writes.push(this.storageAPI.setMetadata(key, newMetadata)); } await Promise.all(writes); } } /** * Called when the client connects / reconnects. * Returns the latest game state and the entire log. */ async onSync(matchID, playerID, credentials, numPlayers = 2) { const key = matchID; const fetchOpts = { state: true, metadata: true, log: true, initialState: true, }; const fetchResult = isSynchronous(this.storageAPI) ? this.storageAPI.fetch(key, fetchOpts) : await this.storageAPI.fetch(key, fetchOpts); let { state, initialState, log, metadata } = fetchResult; if (this.auth && playerID !== undefined && playerID !== null) { const isAuthentic = await this.auth.authenticateCredentials({ playerID, credentials, metadata, }); if (!isAuthentic) { return { error: 'unauthorized' }; } } // If the game doesn't exist, then create one on demand. // TODO: Move this out of the sync call. if (state === undefined) { const match = createMatch({ game: this.game, unlisted: true, numPlayers, setupData: undefined, }); if ('setupDataError' in match) { return { error: 'game requires setupData' }; } initialState = state = match.initialState; metadata = match.metadata; this.subscribeCallback({ state, matchID }); if (isSynchronous(this.storageAPI)) { this.storageAPI.createMatch(key, { initialState, metadata }); } else { await this.storageAPI.createMatch(key, { initialState, metadata }); } } const filteredMetadata = metadata ? filterMatchData(metadata) : undefined; const filteredState = { ...state, G: this.game.playerView(state.G, state.ctx, playerID), plugins: PlayerView(state, { playerID, game: this.game }), deltalog: undefined, _undo: [], _redo: [], }; log = redactLog(log, playerID); const syncInfo = { state: filteredState, log, filteredMetadata, initialState, }; this.transportAPI.send({ playerID, type: 'sync', args: [matchID, syncInfo], }); return; } /** * Called when a client connects or disconnects. * Updates and sends out metadata to reflect the player’s connection status. */ async onConnectionChange(matchID, playerID, credentials, connected) { const key = matchID; // Ignore changes for clients without a playerID, e.g. spectators. if (playerID === undefined || playerID === null) { return; } let metadata; if (isSynchronous(this.storageAPI)) { ({ metadata } = this.storageAPI.fetch(key, { metadata: true })); } else { ({ metadata } = await this.storageAPI.fetch(key, { metadata: true })); } if (metadata === undefined) { error(`metadata not found for matchID=[${key}]`); return { error: 'metadata not found' }; } if (metadata.players[playerID] === undefined) { error(`Player not in the match, matchID=[${key}] playerID=[${playerID}]`); return { error: 'player not in the match' }; } if (this.auth) { const isAuthentic = await this.auth.authenticateCredentials({ playerID, credentials, metadata, }); if (!isAuthentic) { return { error: 'unauthorized' }; } } metadata.players[playerID].isConnected = connected; const filteredMetadata = filterMatchData(metadata); this.transportAPI.sendAll(() => ({ type: 'matchData', args: [matchID, filteredMetadata], })); if (isSynchronous(this.storageAPI)) { this.storageAPI.setMetadata(key, metadata); } else { await this.storageAPI.setMetadata(key, metadata); } } async onChatMessage(matchID, chatMessage, credentials) { const key = matchID; if (this.auth) { const { metadata } = await this.storageAPI.fetch(key, { metadata: true, }); const isAuthentic = await this.auth.authenticateCredentials({ playerID: chatMessage.sender, credentials, metadata, }); if (!isAuthentic) { return { error: 'unauthorized' }; } } this.transportAPI.sendAll(() => ({ type: 'chat', args: [matchID, chatMessage], })); } } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const PING_TIMEOUT = 20 * 1e3; const PING_INTERVAL = 10 * 1e3; /** * API that's exposed by SocketIO for the Master to send * information to the clients. */ function TransportAPI(matchID, socket, clientInfo, roomInfo, provisionalClient) { /** * Emit a socket.io event to the recipientID. * If the recipient is the current socket, uses a basic emit, otherwise * emits via the current socket’s `to` method. */ const emit = (recipientID, { type, args }) => { const emitter = socket.id === recipientID ? socket : socket.to(recipientID); emitter.emit(type, ...args); }; /** * Run a callback for each registered client for this match, including * this transport’s provisionalClient if provided. */ const forEachClient = (clientCallback) => { const clientIDs = roomInfo.get(matchID); if (clientIDs) { clientIDs.forEach((clientID) => { const client = clientInfo.get(clientID); clientCallback(client); }); } if (provisionalClient) { clientCallback(provisionalClient); } }; /** * Send a message to a specific client. */ const send = ({ playerID, ...data }) => { forEachClient((client) => { if (client.playerID === playerID) emit(client.socket.id, data); }); }; /** * Send a message to all clients. */ const sendAll = (makePlayerData) => { forEachClient((client) => { const data = makePlayerData(client.playerID); emit(client.socket.id, data); }); }; return { send, sendAll }; } /** * Transport interface that uses socket.io */ class SocketIO { constructor({ https, socketAdapter, socketOpts } = {}) { this.clientInfo = new Map(); this.roomInfo = new Map(); this.perMatchQueue = new Map(); this.https = https; this.socketAdapter = socketAdapter; this.socketOpts = socketOpts; } /** * Unregister client data for a socket. */ removeClient(socketID) { // Get client data for this socket ID. const client = this.clientInfo.get(socketID); if (!client) return; // Remove client from list of connected sockets for this match. const { matchID } = client; const matchClients = this.roomInfo.get(matchID); matchClients.delete(socketID); // If the match is now empty, delete its promise queue & client ID list. if (matchClients.size === 0) { this.roomInfo.delete(matchID); this.deleteMatchQueue(matchID); } // Remove client data from the client map. this.clientInfo.delete(socketID); } /** * Register client data for a socket. */ addClient(client) { const { matchID, socket } = client; // Add client to list of connected sockets for this match. let matchClients = this.roomInfo.get(matchID); if (matchClients === undefined) { matchClients = new Set(); this.roomInfo.set(matchID, matchClients); } matchClients.add(socket.id); // Register data for this socket in the client map. this.clientInfo.set(socket.id, client); } init(app, games) { const io = new IO({ ioOptions: { pingTimeout: PING_TIMEOUT, pingInterval: PING_INTERVAL, ...this.socketOpts, }, }); app.context.io = io; io.attach(app, !!this.https, this.https); if (this.socketAdapter) { io.adapter(this.socketAdapter); } for (const game of games) { const nsp = app._io.of(game.name); nsp.on('connection', (socket) => { socket.on('update', async (...args) => { const [action, stateID, matchID, playerID] = args; const master = new Master(game, app.context.db, TransportAPI(matchID, socket, this.clientInfo, this.roomInfo), app.context.auth); const matchQueue = this.getMatchQueue(matchID); await matchQueue.add(() => master.onUpdate(action, stateID, matchID, playerID)); }); socket.on('sync', async (...args) => { const [matchID, playerID, credentials] = args; socket.join(matchID); this.removeClient(socket.id); const client = { socket, matchID, playerID, credentials }; const transport = TransportAPI(matchID, socket, this.clientInfo, this.roomInfo, client); const master = new Master(game, app.context.db, transport, app.context.auth); const syncResponse = await master.onSync(...args); if (syncResponse && syncResponse.error === 'unauthorized') { return; } await master.onConnectionChange(matchID, playerID, credentials, true); this.addClient(client); }); socket.on('disconnect', async () => { const client = this.clientInfo.get(socket.id); this.removeClient(socket.id); if (client) { const { matchID, playerID, credentials } = client; const master = new Master(game, app.context.db, TransportAPI(matchID, socket, this.clientInfo, this.roomInfo), app.context.auth); await master.onConnectionChange(matchID, playerID, credentials, false); } }); socket.on('chat', async (...args) => { const [matchID] = args; const master = new Master(game, app.context.db, TransportAPI(matchID, socket, this.clientInfo, this.roomInfo), app.context.auth); master.onChatMessage(...args); }); }); } } /** * Create a PQueue for a given matchID if none exists and return it. * @param matchID * @returns */ getMatchQueue(matchID) { if (!this.perMatchQueue.has(matchID)) { // PQueue should process only one action at a time. this.perMatchQueue.set(matchID, new PQueue({ concurrency: 1 })); } return this.perMatchQueue.get(matchID); } /** * Delete a PQueue for a given matchID. * @param matchID */ deleteMatchQueue(matchID) { this.perMatchQueue.delete(matchID); } } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Build config object from server run arguments. */ const createServerRunConfig = (portOrConfig, callback) => portOrConfig && typeof portOrConfig === 'object' ? { ...portOrConfig, callback: portOrConfig.callback || callback, } : { port: portOrConfig, callback }; const getPortFromServer = (server) => { const address = server.address(); if (typeof address === 'string') return address; if (address === null) return null; return address.port; }; /** * Instantiate a game server. * * @param games - The games that this server will handle. * @param db - The interface with the database. * @param transport - The interface with the clients. * @param authenticateCredentials - Function to test player credentials. * @param generateCredentials - Method for API to generate player credentials. * @param https - HTTPS configuration options passed through to the TLS module. * @param lobbyConfig - Configuration options for the Lobby API server. */ function Server({ games, db, transport, https, uuid, generateCredentials = uuid, authenticateCredentials, }) { const app = new Koa(); games = games.map(ProcessGameConfig); if (db === undefined) { db = DBFromEnv(); } app.context.db = db; const auth = new Auth({ authenticateCredentials, generateCredentials }); app.context.auth = auth; if (transport === undefined) { transport = new SocketIO({ https }); } transport.init(app, games); const router = createRouter({ db, games, uuid, auth }); return { app, db, auth, router, transport, run: async (portOrConfig, callback) => { const serverRunConfig = createServerRunConfig(portOrConfig, callback); // DB await db.connect(); // Lobby API const lobbyConfig = serverRunConfig.lobbyConfig; let apiServer; if (!lobbyConfig || !lobbyConfig.apiPort) { configureApp(app, router); } else { // Run API in a separate Koa app. const api = new Koa(); api.context.db = db; api.context.auth = auth; configureApp(api, router); await new Promise((resolve) => { apiServer = api.listen(lobbyConfig.apiPort, resolve); }); if (lobbyConfig.apiCallback) lobbyConfig.apiCallback(); info(`API serving on ${getPortFromServer(apiServer)}...`); } // Run Game Server (+ API, if necessary). let appServer; await new Promise((resolve) => { appServer = app.listen(serverRunConfig.port, resolve); }); if (serverRunConfig.callback) serverRunConfig.callback(); info(`App serving on ${getPortFromServer(appServer)}...`); return { apiServer, appServer }; }, kill: (servers) => { if (servers.apiServer) { servers.apiServer.close(); } servers.appServer.close(); }, }; } exports.FlatFile = FlatFile; exports.Server = Server; exports.SocketIO = SocketIO;
import RunningTransition from "./running-transition"; import DSL from "./dsl"; import Ember from "ember"; import Action from "./action"; import internalRules from "./internal-rules"; import Constraints from "./constraints"; import getOwner from 'ember-getowner-polyfill'; var TransitionMap = Ember.Service.extend({ init: function() { this.activeCount = 0; this.constraints = new Constraints(); this.map(internalRules); var owner = getOwner(this); var config = owner._lookupFactory('transitions:main'); if (config) { this.map(config); } if (Ember.testing) { this._registerWaiter(); } }, runningTransitions: function() { return this.activeCount; }, incrementRunningTransitions: function() { this.activeCount++; }, decrementRunningTransitions: function() { this.activeCount--; Ember.run.next(() => { this._maybeResolveIdle(); }); }, waitUntilIdle: function() { if (this._waitingPromise) { return this._waitingPromise; } return this._waitingPromise = new Ember.RSVP.Promise((resolve) => { this._resolveWaiting = resolve; Ember.run.next(() => { this._maybeResolveIdle(); }); }); }, _maybeResolveIdle: function() { if (this.activeCount === 0 && this._resolveWaiting) { var resolveWaiting = this._resolveWaiting; this._resolveWaiting = null; this._waitingPromise = null; resolveWaiting(); } }, lookup: function(transitionName) { var owner = getOwner(this); var handler = owner._lookupFactory('transition:' + transitionName); if (!handler) { throw new Error("unknown transition name: " + transitionName); } return handler; }, defaultAction: function() { if (!this._defaultAction) { this._defaultAction = new Action(this.lookup('default')); } return this._defaultAction; }, transitionFor: function(conditions) { var action; if (conditions.use && conditions.firstTime !== 'yes') { action = new Action(conditions.use); action.validateHandler(this); } else { var rule = this.constraints.bestMatch(conditions); if (rule) { action = rule.use; } else { action = this.defaultAction(); } } return new RunningTransition(this, conditions.versions, action); }, map: function(handler) { if (handler){ handler.apply(new DSL(this)); } return this; }, addRule: function(rule) { rule.validate(this); this.constraints.addRule(rule); }, _registerWaiter: function() { var self = this; this._waiter = function() { return self.runningTransitions() === 0; }; Ember.Test.registerWaiter(this._waiter); }, willDestroy: function() { if (this._waiter) { Ember.Test.unregisterWaiter(this._waiter); this._waiter = null; } } }); TransitionMap.reopenClass({ map: function(handler) { var t = TransitionMap.create(); t.map(handler); return t; } }); export default TransitionMap;
define({ "_widgetLabel": "Graf", "executeChartTip": "Kliknutím na jednu z následujících položek úloh vytvoříte graf.", "invalidConfig": "Neplatná konfigurace.", "noneChartTip": "Pro tento widget nebyla nakonfigurována žádná úloha grafů.", "chartParams": "Možnosti", "charts": "GRAFY", "apply": "POUŽÍT", "useSpatialFilter": "Použít prostorový filtr k omezení prvků", "useCurrentMapExtent": "Pouze prvky protínající současnou oblast mapy", "drawGraphicOnMap": "Pouze prvky protínající oblast definovanou uživatelem", "chartResults": "Výsledky grafů", "clearResults": "Smazat výsledky", "noPermissionsMsg": "Nemáte oprávnění pro přístup k této službě.", "specifySpatialFilterMsg": "Zadejte prostorový filtr pro tuto úlohu.", "queryError": "Dotazování se nezdařilo.", "noResults": "Žádný prvek nebyl nalezen.", "category": "Kategorie", "count": "Počet", "label": "Popisek", "horizontalAxis": "Vodorovná osa", "verticalAxis": "Svislá osa", "dataLabels": "Popisky dat", "color": "Barva", "colorful": "Barevné", "monochromatic": "Monochromatické", "tasks": "Úlohy", "results": "Výsledky", "applySpatialFilterToLimitResults": "Použít prostorový filtr k omezení výsledků", "useCurrentExtentTip": "Zčásti nebo zcela v aktuálním rozsahu mapy", "useDrawGraphicTip": "Zčásti nebo zcela v obrazci nakresleném v mapě", "useFeaturesTip": "Na základě umístění prvků v jiné vrstvě", "noSpatialLimitTip": "Neomezovat výsledky podle polohy", "applySearchDistance": "Použít vyhledávací vzdálenost", "spatialRelationship": "Prostorový vztah", "relatedLayer": "Související vrstva", "clear": "Vymazat", "bufferDistance": "Šířka obalové zóny", "miles": "Míle", "kilometers": "Kilometry", "feet": "Stopy", "meters": "Metry", "yards": "Yardy", "nauticalMiles": "Námořní míle", "back": "Zpět", "execute": "Použít", "backCharts": "Zpět do grafů", "backOptions": "Zpět do možností", "clearCharts": "Zrušit všechny grafy" });
HAL.Views.Browser = Backbone.View.extend({ initialize: function(opts) { var self = this; this.vent = opts.vent; this.explorerView = new HAL.Views.Explorer({ vent: this.vent }); this.inspectorView = new HAL.Views.Inspector({ vent: this.vent }); }, className: 'hal-browser row-fluid', render: function() { this.$el.empty(); this.inspectorView.render(); this.explorerView.render(); this.$el.html(this.explorerView.el); this.$el.append(this.inspectorView.el); }, });
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * The registry node that generated the event. Put differently, while the actor * initiates the event, the source generates it. * */ class Source { /** * Create a Source. * @member {string} [addr] The IP or hostname and the port of the registry * node that generated the event. Generally, this will be resolved by * os.Hostname() along with the running port. * @member {string} [instanceID] The running instance of an application. * Changes after each restart. */ constructor() { } /** * Defines the metadata of Source * * @returns {object} metadata of Source * */ mapper() { return { required: false, serializedName: 'Source', type: { name: 'Composite', className: 'Source', modelProperties: { addr: { required: false, serializedName: 'addr', type: { name: 'String' } }, instanceID: { required: false, serializedName: 'instanceID', type: { name: 'String' } } } } }; } } module.exports = Source;
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const msRest = require('ms-rest'); const msRestAzure = require('ms-rest-azure'); const WebResource = msRest.WebResource; /** * Fetches the status of an operation such as triggering a backup, restore. The * status can be in progress, completed or failed. You can refer to the * OperationStatus enum for all the possible states of the operation. Some * operations create jobs. This method returns the list of jobs associated with * the operation. * * @param {string} vaultName The name of the recovery services vault. * * @param {string} resourceGroupName The name of the resource group where the * recovery services vault is present. * * @param {string} fabricName Fabric name associated with the backup item. * * @param {string} containerName Container name associated with the backup * item. * * @param {string} protectedItemName Backup item name whose details are to be * fetched. * * @param {string} operationId OperationID represents the operation whose * status needs to be fetched. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link OperationStatus} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _get(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, operationId, options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } let apiVersion = '2016-12-01'; // Validate try { if (vaultName === null || vaultName === undefined || typeof vaultName.valueOf() !== 'string') { throw new Error('vaultName cannot be null or undefined and it must be of type string.'); } if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') { throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.'); } if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') { throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.'); } if (fabricName === null || fabricName === undefined || typeof fabricName.valueOf() !== 'string') { throw new Error('fabricName cannot be null or undefined and it must be of type string.'); } if (containerName === null || containerName === undefined || typeof containerName.valueOf() !== 'string') { throw new Error('containerName cannot be null or undefined and it must be of type string.'); } if (protectedItemName === null || protectedItemName === undefined || typeof protectedItemName.valueOf() !== 'string') { throw new Error('protectedItemName cannot be null or undefined and it must be of type string.'); } if (operationId === null || operationId === undefined || typeof operationId.valueOf() !== 'string') { throw new Error('operationId cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL let baseUrl = this.client.baseUri; let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/operationsStatus/{operationId}'; requestUrl = requestUrl.replace('{vaultName}', encodeURIComponent(vaultName)); requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName)); requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId)); requestUrl = requestUrl.replace('{fabricName}', encodeURIComponent(fabricName)); requestUrl = requestUrl.replace('{containerName}', encodeURIComponent(containerName)); requestUrl = requestUrl.replace('{protectedItemName}', encodeURIComponent(protectedItemName)); requestUrl = requestUrl.replace('{operationId}', encodeURIComponent(operationId)); let queryParameters = []; queryParameters.push('api-version=' + encodeURIComponent(apiVersion)); if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { let parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { let resultMapper = new client.models['OperationStatus']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } return callback(null, result, httpRequest, response); }); } /** Class representing a ProtectedItemOperationStatuses. */ class ProtectedItemOperationStatuses { /** * Create a ProtectedItemOperationStatuses. * @param {RecoveryServicesBackupClient} client Reference to the service client. */ constructor(client) { this.client = client; this._get = _get; } /** * Fetches the status of an operation such as triggering a backup, restore. The * status can be in progress, completed or failed. You can refer to the * OperationStatus enum for all the possible states of the operation. Some * operations create jobs. This method returns the list of jobs associated with * the operation. * * @param {string} vaultName The name of the recovery services vault. * * @param {string} resourceGroupName The name of the resource group where the * recovery services vault is present. * * @param {string} fabricName Fabric name associated with the backup item. * * @param {string} containerName Container name associated with the backup * item. * * @param {string} protectedItemName Backup item name whose details are to be * fetched. * * @param {string} operationId OperationID represents the operation whose * status needs to be fetched. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationStatus>} - The deserialized result object. * * @reject {Error} - The error object. */ getWithHttpOperationResponse(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, operationId, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._get(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, operationId, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Fetches the status of an operation such as triggering a backup, restore. The * status can be in progress, completed or failed. You can refer to the * OperationStatus enum for all the possible states of the operation. Some * operations create jobs. This method returns the list of jobs associated with * the operation. * * @param {string} vaultName The name of the recovery services vault. * * @param {string} resourceGroupName The name of the resource group where the * recovery services vault is present. * * @param {string} fabricName Fabric name associated with the backup item. * * @param {string} containerName Container name associated with the backup * item. * * @param {string} protectedItemName Backup item name whose details are to be * fetched. * * @param {string} operationId OperationID represents the operation whose * status needs to be fetched. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {OperationStatus} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link OperationStatus} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ get(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, operationId, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._get(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, operationId, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._get(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, operationId, options, optionalCallback); } } } module.exports = ProtectedItemOperationStatuses;
"use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const Event = require("./Event.js"); const impl = utils.implSymbol; const convertPopStateEventInit = require("./PopStateEventInit").convert; function PopStateEvent(type) { if (!new.target) { throw new TypeError( "Failed to construct 'PopStateEvent'. Please use the 'new' operator; this constructor cannot be called as a function." ); } if (arguments.length < 1) { throw new TypeError( "Failed to construct 'PopStateEvent': 1 argument required, but only " + arguments.length + " present." ); } const args = []; for (let i = 0; i < arguments.length && i < 2; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0], { context: "Failed to construct 'PopStateEvent': parameter 1" }); args[1] = convertPopStateEventInit(args[1], { context: "Failed to construct 'PopStateEvent': parameter 2" }); iface.setup(this, args); } Object.setPrototypeOf(PopStateEvent.prototype, Event.interface.prototype); Object.setPrototypeOf(PopStateEvent, Event.interface); Object.defineProperty(PopStateEvent.prototype, "state", { get() { return this[impl].state; }, enumerable: true, configurable: true }); Object.defineProperty(PopStateEvent.prototype, Symbol.toStringTag, { value: "PopStateEvent", writable: false, enumerable: false, configurable: true }); const iface = { mixedInto: [], is(obj) { if (obj) { if (obj[impl] instanceof Impl.implementation) { return true; } for (let i = 0; i < module.exports.mixedInto.length; ++i) { if (obj instanceof module.exports.mixedInto[i]) { return true; } } } return false; }, isImpl(obj) { if (obj) { if (obj instanceof Impl.implementation) { return true; } const wrapper = utils.wrapperForImpl(obj); for (let i = 0; i < module.exports.mixedInto.length; ++i) { if (wrapper instanceof module.exports.mixedInto[i]) { return true; } } } return false; }, convert(obj, { context = "The provided value" } = {}) { if (module.exports.is(obj)) { return utils.implForWrapper(obj); } throw new TypeError(`${context} is not of type 'PopStateEvent'.`); }, create(constructorArgs, privateData) { let obj = Object.create(PopStateEvent.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, createImpl(constructorArgs, privateData) { let obj = Object.create(PopStateEvent.prototype); this.setup(obj, constructorArgs, privateData); return utils.implForWrapper(obj); }, _internalSetup(obj) { Event._internalSetup(obj); }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; this._internalSetup(obj); Object.defineProperty(obj, impl, { value: new Impl.implementation(constructorArgs, privateData), writable: false, enumerable: false, configurable: true }); obj[impl][utils.wrapperSymbol] = obj; }, interface: PopStateEvent, expose: { Window: { PopStateEvent: PopStateEvent } } }; module.exports = iface; const Impl = require("../events/PopStateEvent-impl.js");
/*The MIT License (MIT) Copyright (c) 2015 Apostolique 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.*/ // ==UserScript== // @name AposBot // @namespace AposBot // @include http://agar.io/* // @version 3.63 // @grant none // @author http://www.twitch.tv/apostolique // ==/UserScript== var aposBotVersion = 3.63; //TODO: Team mode // Detect when people are merging // Split to catch smaller targets // Angle based cluster code // Better wall code // In team mode, make allies be obstacles. Number.prototype.mod = function(n) { return ((this % n) + n) % n; }; Array.prototype.peek = function() { return this[this.length - 1]; }; var sha = "efde0488cc2cc176db48dd23b28a20b90314352b"; function getLatestCommit() { window.jQuery.ajax({ url: "https://api.github.com/repos/apostolique/Agar.io-bot/git/refs/heads/master", cache: false, dataType: "jsonp" }).done(function(data) { console.dir(data.data); console.log("hmm: " + data.data.object.sha); sha = data.data.object.sha; function update(prefix, name, url) { window.jQuery(document.body).prepend("<div id='" + prefix + "Dialog' style='position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; z-index: 100; display: none;'>"); window.jQuery('#' + prefix + 'Dialog').append("<div id='" + prefix + "Message' style='width: 350px; background-color: #FFFFFF; margin: 100px auto; border-radius: 15px; padding: 5px 15px 5px 15px;'>"); window.jQuery('#' + prefix + 'Message').append("<h2>UPDATE TIME!!!</h2>"); window.jQuery('#' + prefix + 'Message').append("<p>Grab the update for: <a id='" + prefix + "Link' href='" + url + "' target=\"_blank\">" + name + "</a></p>"); window.jQuery('#' + prefix + 'Link').on('click', function() { window.jQuery("#" + prefix + "Dialog").hide(); window.jQuery("#" + prefix + "Dialog").remove(); }); window.jQuery("#" + prefix + "Dialog").show(); } $.get('https://raw.githubusercontent.com/Apostolique/Agar.io-bot/master/bot.user.js?' + Math.floor((Math.random() * 1000000) + 1), function(data) { var latestVersion = data.replace(/(\r\n|\n|\r)/gm,""); latestVersion = latestVersion.substring(latestVersion.indexOf("// @version")+11,latestVersion.indexOf("// @grant")); latestVersion = parseFloat(latestVersion + 0.0000); var myVersion = parseFloat(aposBotVersion + 0.0000); if(latestVersion > myVersion) { update("aposBot", "bot.user.js", "https://github.com/Apostolique/Agar.io-bot/blob/" + sha + "/bot.user.js/"); } console.log('Current bot.user.js Version: ' + myVersion + " on Github: " + latestVersion); }); }).fail(function() {}); } getLatestCommit(); console.log("Running Apos Bot!"); var f = window; var g = window.jQuery; console.log("Apos Bot!"); window.botList = window.botList || []; /*function QuickBot() { this.name = "QuickBot V1"; this.keyAction = function(key) {}; this.displayText = function() {return [];}; this.mainLoop = function() { return [screenToGameX(getMouseX()), screenToGameY(getMouseY())]; }; } window.botList.push(new QuickBot());*/ function AposBot() { this.name = "AposBot " + aposBotVersion; this.toggleFollow = false; this.keyAction = function(key) { if (81 == key.keyCode) { console.log("Toggle Follow Mouse!"); this.toggleFollow = !this.toggleFollow; } }; this.displayText = function() { return ["Q - Follow Mouse: " + (this.toggleFollow ? "On" : "Off")]; }; this.splitDistance = 710; //Given an angle value that was gotten from valueAndleBased(), //returns a new value that scales it appropriately. this.paraAngleValue = function(angleValue, range) { return (15 / (range[1])) * (angleValue * angleValue) - (range[1] / 6); }; this.valueAngleBased = function(angle, range) { var leftValue = (angle - range[0]).mod(360); var rightValue = (this.rangeToAngle(range) - angle).mod(360); var bestValue = Math.min(leftValue, rightValue); if (bestValue <= range[1]) { return this.paraAngleValue(bestValue, range); } return -1; }; this.computeDistance = function(x1, y1, x2, y2) { var xdis = x1 - x2; // <--- FAKE AmS OF COURSE! var ydis = y1 - y2; var distance = Math.sqrt(xdis * xdis + ydis * ydis); return distance; }; this.computeDistanceFromCircleEdge = function(x1, y1, x2, y2, s2) { var tempD = this.computeDistance(x1, y1, x2, y2); var offsetX = 0; var offsetY = 0; var ratioX = tempD / (x1 - x2); var ratioY = tempD / (y1 - y2); offsetX = x1 - (s2 / ratioX); offsetY = y1 - (s2 / ratioY); drawPoint(offsetX, offsetY, 5, ""); return this.computeDistance(x2, y2, offsetX, offsetY); }; this.compareSize = function(player1, player2, ratio) { if (player1.size * player1.size * ratio < player2.size * player2.size) { return true; } return false; }, this.canSplit = function(player1, player2) { return this.compareSize(player1, player2, 2.8) && !this.compareSize(player1, player2, 20); }; this.isItMe = function(player, cell) { if (getMode() == ":teams") { var currentColor = player[0].color; var currentRed = currentColor.substring(1,3); var currentGreen = currentColor.substring(3,5); var currentBlue = currentColor.substring(5,7); var currentTeam = this.getTeam(currentRed, currentGreen, currentBlue); var cellColor = cell.color; var cellRed = cellColor.substring(1,3); var cellGreen = cellColor.substring(3,5); var cellBlue = cellColor.substring(5,7); var cellTeam = this.getTeam(cellRed, cellGreen, cellBlue); if (currentTeam == cellTeam && !cell.isVirus()) { return true; } //console.log("COLOR: " + color); } else { for (var i = 0; i < player.length; i++) { if (cell.id == player[i].id) { return true; } } } return false; }; this.getTeam = function(red, green, blue) { if (red == "ff") { return 0; } else if (green == "ff") { return 1; } return 2; }; this.isFood = function(blob, cell) { if (!cell.isVirus() && this.compareSize(cell, blob, 1.33) || (cell.size <= 13)) { return true; } return false; }; this.isThreat = function(blob, cell) { if (!cell.isVirus() && this.compareSize(blob, cell, 1.30)) { return true; } return false; }; this.isVirus = function(blob, cell) { if (cell.isVirus() && this.compareSize(cell, blob, 1.2)) { return true; } else if (cell.isVirus() && cell.color.substring(3,5).toLowerCase() != "ff") { return true; } return false; }; this.isSplitTarget = function(that, blob, cell) { if (that.canSplit(cell, blob)) { return true; } return false; }; this.getTimeToRemerge = function(mass){ return ((mass*0.02) + 30); }; this.separateListBasedOnFunction = function(that, listToUse, blob) { var foodElementList = []; var threatList = []; var virusList = []; var splitTargetList = []; var player = getPlayer(); Object.keys(listToUse).forEach(function(element, index) { var isMe = that.isItMe(player, listToUse[element]); if (!isMe) { if (that.isFood(blob, listToUse[element]) && listToUse[element].isNotMoving()) { //IT'S FOOD! foodElementList.push(listToUse[element]); } else if (that.isThreat(blob, listToUse[element])) { //IT'S DANGER! threatList.push(listToUse[element]); } else if (that.isVirus(blob, listToUse[element])) { //IT'S VIRUS! virusList.push(listToUse[element]); } else if (that.isSplitTarget(that, blob, listToUse[element])) { drawCircle(listToUse[element].x, listToUse[element].y, listToUse[element].size + 50, 7); splitTargetList.push(listToUse[element]); foodElementList.push(listToUse[element]); } }/*else if(isMe && (getBlobCount(getPlayer()) > 0)){ //Attempt to make the other cell follow the mother one foodElementList.push(listToUse[element]); }*/ }); foodList = []; for (var i = 0; i < foodElementList.length; i++) { foodList.push([foodElementList[i].x, foodElementList[i].y, foodElementList[i].size]); } return [foodList, threatList, virusList, splitTargetList]; }; this.getAll = function(blob) { var dotList = []; var player = getPlayer(); var interNodes = getMemoryCells(); dotList = this.separateListBasedOnFunction(this, interNodes, blob); return dotList; }; this.clusterFood = function(foodList, blobSize) { var clusters = []; var addedCluster = false; //1: x //2: y //3: size or value //4: Angle, not set here. for (var i = 0; i < foodList.length; i++) { for (var j = 0; j < clusters.length; j++) { if (this.computeDistance(foodList[i][0], foodList[i][1], clusters[j][0], clusters[j][1]) < blobSize * 1.5) { clusters[j][0] = (foodList[i][0] + clusters[j][0]) / 2; clusters[j][1] = (foodList[i][1] + clusters[j][1]) / 2; clusters[j][2] += foodList[i][2]; addedCluster = true; break; } } if (!addedCluster) { clusters.push([foodList[i][0], foodList[i][1], foodList[i][2], 0]); } addedCluster = false; } return clusters; }; this.getAngle = function(x1, y1, x2, y2) { //Handle vertical and horizontal lines. if (x1 == x2) { if (y1 < y2) { return 271; //return 89; } else { return 89; } } return (Math.round(Math.atan2(-(y1 - y2), -(x1 - x2)) / Math.PI * 180 + 180)); }; this.slope = function(x1, y1, x2, y2) { var m = (y1 - y2) / (x1 - x2); return m; }; this.slopeFromAngle = function(degree) { if (degree == 270) { degree = 271; } else if (degree == 90) { degree = 91; } return Math.tan((degree - 180) / 180 * Math.PI); }; //Given two points on a line, finds the slope of a perpendicular line crossing it. this.inverseSlope = function(x1, y1, x2, y2) { var m = this.slope(x1, y1, x2, y2); return (-1) / m; }; //Given a slope and an offset, returns two points on that line. this.pointsOnLine = function(slope, useX, useY, distance) { var b = useY - slope * useX; var r = Math.sqrt(1 + slope * slope); var newX1 = (useX + (distance / r)); var newY1 = (useY + ((distance * slope) / r)); var newX2 = (useX + ((-distance) / r)); var newY2 = (useY + (((-distance) * slope) / r)); return [ [newX1, newY1], [newX2, newY2] ]; }; this.followAngle = function(angle, useX, useY, distance) { var slope = this.slopeFromAngle(angle); var coords = this.pointsOnLine(slope, useX, useY, distance); var side = (angle - 90).mod(360); if (side < 180) { return coords[1]; } else { return coords[0]; } }; //Using a line formed from point a to b, tells if point c is on S side of that line. this.isSideLine = function(a, b, c) { if ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) > 0) { return true; } return false; }; //angle range2 is within angle range2 //an Angle is a point and a distance between an other point [5, 40] this.angleRangeIsWithin = function(range1, range2) { if (range2[0] == (range2[0] + range2[1]).mod(360)) { return true; } //console.log("r1: " + range1[0] + ", " + range1[1] + " ... r2: " + range2[0] + ", " + range2[1]); var distanceFrom0 = (range1[0] - range2[0]).mod(360); var distanceFrom1 = (range1[1] - range2[0]).mod(360); if (distanceFrom0 < range2[1] && distanceFrom1 < range2[1] && distanceFrom0 < distanceFrom1) { return true; } return false; }; this.angleRangeIsWithinInverted = function(range1, range2) { var distanceFrom0 = (range1[0] - range2[0]).mod(360); var distanceFrom1 = (range1[1] - range2[0]).mod(360); if (distanceFrom0 < range2[1] && distanceFrom1 < range2[1] && distanceFrom0 > distanceFrom1) { return true; } return false; }; this.angleIsWithin = function(angle, range) { var diff = (this.rangeToAngle(range) - angle).mod(360); if (diff >= 0 && diff <= range[1]) { return true; } return false; }; this.rangeToAngle = function(range) { return (range[0] + range[1]).mod(360); }; this.anglePair = function(range) { return (range[0] + ", " + this.rangeToAngle(range) + " range: " + range[1]); }; this.computeAngleRanges = function(blob1, blob2) { var mainAngle = this.getAngle(blob1.x, blob1.y, blob2.x, blob2.y); var leftAngle = (mainAngle - 90).mod(360); var rightAngle = (mainAngle + 90).mod(360); var blob1Left = this.followAngle(leftAngle, blob1.x, blob1.y, blob1.size); var blob1Right = this.followAngle(rightAngle, blob1.x, blob1.y, blob1.size); var blob2Left = this.followAngle(rightAngle, blob2.x, blob2.y, blob2.size); var blob2Right = this.followAngle(leftAngle, blob2.x, blob2.y, blob2.size); var blob1AngleLeft = this.getAngle(blob2.x, blob2.y, blob1Left[0], blob1Left[1]); var blob1AngleRight = this.getAngle(blob2.x, blob2.y, blob1Right[0], blob1Right[1]); var blob2AngleLeft = this.getAngle(blob1.x, blob1.y, blob2Left[0], blob2Left[1]); var blob2AngleRight = this.getAngle(blob1.x, blob1.y, blob2Right[0], blob2Right[1]); var blob1Range = (blob1AngleRight - blob1AngleLeft).mod(360); var blob2Range = (blob2AngleRight - blob2AngleLeft).mod(360); var tempLine = this.followAngle(blob2AngleLeft, blob2Left[0], blob2Left[1], 400); //drawLine(blob2Left[0], blob2Left[1], tempLine[0], tempLine[1], 0); if ((blob1Range / blob2Range) > 1) { drawPoint(blob1Left[0], blob1Left[1], 3, ""); drawPoint(blob1Right[0], blob1Right[1], 3, ""); drawPoint(blob1.x, blob1.y, 3, "" + blob1Range + ", " + blob2Range + " R: " + (Math.round((blob1Range / blob2Range) * 1000) / 1000)); } //drawPoint(blob2.x, blob2.y, 3, "" + blob1Range); }; this.debugAngle = function(angle, text) { var player = getPlayer(); var line1 = this.followAngle(angle, player[0].x, player[0].y, 300); drawLine(player[0].x, player[0].y, line1[0], line1[1], 5); drawPoint(line1[0], line1[1], 5, "" + text); }; //TODO: Don't let this function do the radius math. this.getEdgeLinesFromPoint = function(blob1, blob2, radius) { var px = blob1.x; var py = blob1.y; var cx = blob2.x; var cy = blob2.y; //var radius = blob2.size; /*if (blob2.isVirus()) { radius = blob1.size; } else if(canSplit(blob1, blob2)) { radius += splitDistance; } else { radius += blob1.size * 2; }*/ var shouldInvert = false; var tempRadius = this.computeDistance(px, py, cx, cy); if (tempRadius <= radius) { radius = tempRadius - 5; shouldInvert = true; } var dx = cx - px; var dy = cy - py; var dd = Math.sqrt(dx * dx + dy * dy); var a = Math.asin(radius / dd); var b = Math.atan2(dy, dx); var t = b - a; var ta = { x: radius * Math.sin(t), y: radius * -Math.cos(t) }; t = b + a; var tb = { x: radius * -Math.sin(t), y: radius * Math.cos(t) }; var angleLeft = this.getAngle(cx + ta.x, cy + ta.y, px, py); var angleRight = this.getAngle(cx + tb.x, cy + tb.y, px, py); var angleDistance = (angleRight - angleLeft).mod(360); /*if (shouldInvert) { var temp = angleLeft; angleLeft = (angleRight + 180).mod(360); angleRight = (temp + 180).mod(360); angleDistance = (angleRight - angleLeft).mod(360); }*/ return [angleLeft, angleDistance, [cx + tb.x, cy + tb.y], [cx + ta.x, cy + ta.y] ]; }; this.invertAngle = function(range) { var angle1 = this.rangeToAngle(badAngles[i]); var angle2 = (badAngles[i][0] - angle1).mod(360); return [angle1, angle2]; }, this.addWall = function(listToUse, blob) { //var mapSizeX = Math.abs(f.getMapStartX - f.getMapEndX); //var mapSizeY = Math.abs(f.getMapStartY - f.getMapEndY); //var distanceFromWallX = mapSizeX/3; //var distanceFromWallY = mapSizeY/3; var distanceFromWallY = 2000; var distanceFromWallX = 2000; if (blob.x < getMapStartX() + distanceFromWallX) { //LEFT //console.log("Left"); listToUse.push([ [90, true], [270, false], this.computeDistance(getMapStartX(), blob.y, blob.x, blob.y) ]); var lineLeft = this.followAngle(90, blob.x, blob.y, 190 + blob.size); var lineRight = this.followAngle(270, blob.x, blob.y, 190 + blob.size); drawLine(blob.x, blob.y, lineLeft[0], lineLeft[1], 5); drawLine(blob.x, blob.y, lineRight[0], lineRight[1], 5); drawArc(lineLeft[0], lineLeft[1], lineRight[0], lineRight[1], blob.x, blob.y, 5); } if (blob.y < getMapStartY() + distanceFromWallY) { //TOP //console.log("TOP"); listToUse.push([ [180, true], [0, false], this.computeDistance(blob.x, getMapStartY, blob.x, blob.y) ]); var lineLeft = this.followAngle(180, blob.x, blob.y, 190 + blob.size); var lineRight = this.followAngle(360, blob.x, blob.y, 190 + blob.size); drawLine(blob.x, blob.y, lineLeft[0], lineLeft[1], 5); drawLine(blob.x, blob.y, lineRight[0], lineRight[1], 5); drawArc(lineLeft[0], lineLeft[1], lineRight[0], lineRight[1], blob.x, blob.y, 5); } if (blob.x > getMapEndX() - distanceFromWallX) { //RIGHT //console.log("RIGHT"); listToUse.push([ [270, true], [90, false], this.computeDistance(getMapEndX(), blob.y, blob.x, blob.y) ]); var lineLeft = this.followAngle(270, blob.x, blob.y, 190 + blob.size); var lineRight = this.followAngle(90, blob.x, blob.y, 190 + blob.size); drawLine(blob.x, blob.y, lineLeft[0], lineLeft[1], 5); drawLine(blob.x, blob.y, lineRight[0], lineRight[1], 5); drawArc(lineLeft[0], lineLeft[1], lineRight[0], lineRight[1], blob.x, blob.y, 5); } if (blob.y > getMapEndY() - distanceFromWallY) { //BOTTOM //console.log("BOTTOM"); listToUse.push([ [0, true], [180, false], this.computeDistance(blob.x, getMapEndY(), blob.x, blob.y) ]); var lineLeft = this.followAngle(0, blob.x, blob.y, 190 + blob.size); var lineRight = this.followAngle(180, blob.x, blob.y, 190 + blob.size); drawLine(blob.x, blob.y, lineLeft[0], lineLeft[1], 5); drawLine(blob.x, blob.y, lineRight[0], lineRight[1], 5); drawArc(lineLeft[0], lineLeft[1], lineRight[0], lineRight[1], blob.x, blob.y, 5); } return listToUse; }; //listToUse contains angles in the form of [angle, boolean]. //boolean is true when the range is starting. False when it's ending. //range = [[angle1, true], [angle2, false]] this.getAngleIndex = function(listToUse, angle) { if (listToUse.length == 0) { return 0; } for (var i = 0; i < listToUse.length; i++) { if (angle <= listToUse[i][0]) { return i; } } return listToUse.length; }; this.addAngle = function(listToUse, range) { //#1 Find first open element //#2 Try to add range1 to the list. If it is within other range, don't add it, set a boolean. //#3 Try to add range2 to the list. If it is withing other range, don't add it, set a boolean. //TODO: Only add the new range at the end after the right stuff has been removed. var newListToUse = listToUse.slice(); var startIndex = 1; if (newListToUse.length > 0 && !newListToUse[0][1]) { startIndex = 0; } var startMark = this.getAngleIndex(newListToUse, range[0][0]); var startBool = startMark.mod(2) != startIndex; var endMark = this.getAngleIndex(newListToUse, range[1][0]); var endBool = endMark.mod(2) != startIndex; var removeList = []; if (startMark != endMark) { //Note: If there is still an error, this would be it. var biggerList = 0; if (endMark == newListToUse.length) { biggerList = 1; } for (var i = startMark; i < startMark + (endMark - startMark).mod(newListToUse.length + biggerList); i++) { removeList.push((i).mod(newListToUse.length)); } } else if (startMark < newListToUse.length && endMark < newListToUse.length) { var startDist = (newListToUse[startMark][0] - range[0][0]).mod(360); var endDist = (newListToUse[endMark][0] - range[1][0]).mod(360); if (startDist < endDist) { for (var i = 0; i < newListToUse.length; i++) { removeList.push(i); } } } removeList.sort(function(a, b){return b-a;}); for (var i = 0; i < removeList.length; i++) { newListToUse.splice(removeList[i], 1); } if (startBool) { newListToUse.splice(this.getAngleIndex(newListToUse, range[0][0]), 0, range[0]); } if (endBool) { newListToUse.splice(this.getAngleIndex(newListToUse, range[1][0]), 0, range[1]); } return newListToUse; }; this.getAngleRange = function(blob1, blob2, index, radius) { var angleStuff = this.getEdgeLinesFromPoint(blob1, blob2, radius); var leftAngle = angleStuff[0]; var rightAngle = this.rangeToAngle(angleStuff); var difference = angleStuff[1]; drawPoint(angleStuff[2][0], angleStuff[2][1], 3, ""); drawPoint(angleStuff[3][0], angleStuff[3][1], 3, ""); //console.log("Adding badAngles: " + leftAngle + ", " + rightAngle + " diff: " + difference); var lineLeft = this.followAngle(leftAngle, blob1.x, blob1.y, 150 + blob1.size - index * 10); var lineRight = this.followAngle(rightAngle, blob1.x, blob1.y, 150 + blob1.size - index * 10); if (blob2.isVirus()) { drawLine(blob1.x, blob1.y, lineLeft[0], lineLeft[1], 6); drawLine(blob1.x, blob1.y, lineRight[0], lineRight[1], 6); drawArc(lineLeft[0], lineLeft[1], lineRight[0], lineRight[1], blob1.x, blob1.y, 6); } else if(getCells().hasOwnProperty(blob2.id)) { drawLine(blob1.x, blob1.y, lineLeft[0], lineLeft[1], 0); drawLine(blob1.x, blob1.y, lineRight[0], lineRight[1], 0); drawArc(lineLeft[0], lineLeft[1], lineRight[0], lineRight[1], blob1.x, blob1.y, 0); } else { drawLine(blob1.x, blob1.y, lineLeft[0], lineLeft[1], 3); drawLine(blob1.x, blob1.y, lineRight[0], lineRight[1], 3); drawArc(lineLeft[0], lineLeft[1], lineRight[0], lineRight[1], blob1.x, blob1.y, 3); } return [leftAngle, difference]; }; //Given a list of conditions, shift the angle to the closest available spot respecting the range given. this.shiftAngle = function(listToUse, angle, range) { //TODO: shiftAngle needs to respect the range! DONE? for (var i = 0; i < listToUse.length; i++) { if (this.angleIsWithin(angle, listToUse[i])) { //console.log("Shifting needed!"); var angle1 = listToUse[i][0]; var angle2 = this.rangeToAngle(listToUse[i]); var dist1 = (angle - angle1).mod(360); var dist2 = (angle2 - angle).mod(360); if (dist1 < dist2) { if (this.angleIsWithin(angle1, range)) { return angle1; } else { return angle2; } } else { if (this.angleIsWithin(angle2, range)) { return angle2; } else { return angle1; } } } } //console.log("No Shifting Was needed!"); return angle; }; /** * This is the main bot logic. This is called quite often. * @return A 2 dimensional array with coordinates for every cells. [[x, y], [x, y]] */ this.mainLoop = function() { var player = getPlayer(); var interNodes = getMemoryCells(); if ( /*!toggle*/ 1) { //The following code converts the mouse position into an //absolute game coordinate. var useMouseX = screenToGameX(getMouseX()); var useMouseY = screenToGameY(getMouseY()); tempPoint = [useMouseX, useMouseY, 1]; //The current destination that the cells were going towards. var tempMoveX = getPointX(); var tempMoveY = getPointY(); //This variable will be returned at the end. //It will contain the destination choices for all the cells. //BTW!!! ERROR ERROR ABORT MISSION!!!!!!! READ BELOW ----------- // //SINCE IT'S STUPID NOW TO ASK EACH CELL WHERE THEY WANT TO GO, //THE BOT SHOULD SIMPLY PICK ONE AND THAT'S IT, I MEAN WTF.... var destinationChoices = []; //destination, size, danger //Just to make sure the player is alive. if (player.length > 0) { //Loop through all the player's cells. for (var k = 0; k < player.length; k++) { if (true) { drawPoint(player[k].x, player[k].y + player[k].size, 0, "" + (getLastUpdate() - player[k].birth) + " / " + (30000 + (player[k].birthMass * 57) - (getLastUpdate() - player[k].birth)) + " / " + player[k].birthMass); } } //Loops only for one cell for now. for (var k = 0; /*k < player.length*/ k < 1; k++) { //console.log("Working on blob: " + k); drawCircle(player[k].x, player[k].y, player[k].size + this.splitDistance, 5); //drawPoint(player[0].x, player[0].y - player[0].size, 3, "" + Math.floor(player[0].x) + ", " + Math.floor(player[0].y)); //var allDots = processEverything(interNodes); //loop through everything that is on the screen and //separate everything in it's own category. var allIsAll = this.getAll(player[k]); //The food stored in element 0 of allIsAll var allPossibleFood = allIsAll[0]; //The threats are stored in element 1 of allIsAll var allPossibleThreats = allIsAll[1]; //The viruses are stored in element 2 of allIsAll var allPossibleViruses = allIsAll[2]; //The bot works by removing angles in which it is too //dangerous to travel towards to. var badAngles = []; var obstacleList = []; var isSafeSpot = true; var isMouseSafe = true; var clusterAllFood = this.clusterFood(allPossibleFood, player[k].size); //console.log("Looking for enemies!"); //Loop through all the cells that were identified as threats. for (var i = 0; i < allPossibleThreats.length; i++) { var enemyDistance = this.computeDistanceFromCircleEdge(allPossibleThreats[i].x, allPossibleThreats[i].y, player[k].x, player[k].y, allPossibleThreats[i].size); allPossibleThreats[i].enemyDist = enemyDistance; } /*allPossibleThreats.sort(function(a, b){ return a.enemyDist-b.enemyDist; })*/ for (var i = 0; i < allPossibleThreats.length; i++) { var enemyDistance = this.computeDistance(allPossibleThreats[i].x, allPossibleThreats[i].y, player[k].x, player[k].y); var splitDangerDistance = allPossibleThreats[i].size + this.splitDistance + 150; var normalDangerDistance = allPossibleThreats[i].size + 150; var shiftDistance = player[k].size; //console.log("Found distance."); var enemyCanSplit = this.canSplit(player[k], allPossibleThreats[i]); for (var j = clusterAllFood.length - 1; j >= 0 ; j--) { var secureDistance = (enemyCanSplit ? splitDangerDistance : normalDangerDistance); if (this.computeDistance(allPossibleThreats[i].x, allPossibleThreats[i].y, clusterAllFood[j][0], clusterAllFood[j][1]) < secureDistance) clusterAllFood.splice(j, 1); } //console.log("Removed some food."); if (enemyCanSplit) { drawCircle(allPossibleThreats[i].x, allPossibleThreats[i].y, splitDangerDistance, 0); drawCircle(allPossibleThreats[i].x, allPossibleThreats[i].y, splitDangerDistance + shiftDistance, 6); } else { drawCircle(allPossibleThreats[i].x, allPossibleThreats[i].y, normalDangerDistance, 3); drawCircle(allPossibleThreats[i].x, allPossibleThreats[i].y, normalDangerDistance + shiftDistance, 6); } if (allPossibleThreats[i].danger && getLastUpdate() - allPossibleThreats[i].dangerTimeOut > 1000) { allPossibleThreats[i].danger = false; } /*if ((enemyCanSplit && enemyDistance < splitDangerDistance) || (!enemyCanSplit && enemyDistance < normalDangerDistance)) { allPossibleThreats[i].danger = true; allPossibleThreats[i].dangerTimeOut = f.getLastUpdate(); }*/ //console.log("Figured out who was important."); if ((enemyCanSplit && enemyDistance < splitDangerDistance) || (enemyCanSplit && allPossibleThreats[i].danger)) { badAngles.push(this.getAngleRange(player[k], allPossibleThreats[i], i, splitDangerDistance).concat(allPossibleThreats[i].enemyDist)); } else if ((!enemyCanSplit && enemyDistance < normalDangerDistance) || (!enemyCanSplit && allPossibleThreats[i].danger)) { badAngles.push(this.getAngleRange(player[k], allPossibleThreats[i], i, normalDangerDistance).concat(allPossibleThreats[i].enemyDist)); } else if (enemyCanSplit && enemyDistance < splitDangerDistance + shiftDistance) { var tempOb = this.getAngleRange(player[k], allPossibleThreats[i], i, splitDangerDistance + shiftDistance); var angle1 = tempOb[0]; var angle2 = this.rangeToAngle(tempOb); obstacleList.push([[angle1, true], [angle2, false]]); } else if (!enemyCanSplit && enemyDistance < normalDangerDistance + shiftDistance) { var tempOb = this.getAngleRange(player[k], allPossibleThreats[i], i, normalDangerDistance + shiftDistance); var angle1 = tempOb[0]; var angle2 = this.rangeToAngle(tempOb); obstacleList.push([[angle1, true], [angle2, false]]); } //console.log("Done with enemy: " + i); } //console.log("Done looking for enemies!"); var goodAngles = []; var stupidList = []; for (var i = 0; i < allPossibleViruses.length; i++) { if (player[k].size < allPossibleViruses[i].size) { drawCircle(allPossibleViruses[i].x, allPossibleViruses[i].y, allPossibleViruses[i].size + 10, 3); drawCircle(allPossibleViruses[i].x, allPossibleViruses[i].y, allPossibleViruses[i].size * 2, 6); } else { drawCircle(allPossibleViruses[i].x, allPossibleViruses[i].y, player[k].size + 50, 3); drawCircle(allPossibleViruses[i].x, allPossibleViruses[i].y, player[k].size * 2, 6); } } for (var i = 0; i < allPossibleViruses.length; i++) { var virusDistance = this.computeDistance(allPossibleViruses[i].x, allPossibleViruses[i].y, player[k].x, player[k].y); if (player[k].size < allPossibleViruses[i].size) { if (virusDistance < (allPossibleViruses[i].size * 2)) { var tempOb = this.getAngleRange(player[k], allPossibleViruses[i], i, allPossibleViruses[i].size + 10); var angle1 = tempOb[0]; var angle2 = this.rangeToAngle(tempOb); obstacleList.push([[angle1, true], [angle2, false]]); } } else { if (virusDistance < (player[k].size * 2)) { var tempOb = this.getAngleRange(player[k], allPossibleViruses[i], i, player[k].size + 50); var angle1 = tempOb[0]; var angle2 = this.rangeToAngle(tempOb); obstacleList.push([[angle1, true], [angle2, false]]); } } } if (badAngles.length > 0) { //NOTE: This is only bandaid wall code. It's not the best way to do it. stupidList = this.addWall(stupidList, player[k]); } for (var i = 0; i < badAngles.length; i++) { var angle1 = badAngles[i][0]; var angle2 = this.rangeToAngle(badAngles[i]); stupidList.push([[angle1, true], [angle2, false], badAngles[i][2]]); } //stupidList.push([[45, true], [135, false]]); //stupidList.push([[10, true], [200, false]]); stupidList.sort(function(a, b){ //console.log("Distance: " + a[2] + ", " + b[2]); return a[2]-b[2]; }); //console.log("Added random noob stuff."); var sortedInterList = []; var sortedObList = []; for (var i = 0; i < stupidList.length; i++) { //console.log("Adding to sorted: " + stupidList[i][0][0] + ", " + stupidList[i][1][0]); var tempList = this.addAngle(sortedInterList, stupidList[i]); if (tempList.length == 0) { console.log("MAYDAY IT'S HAPPENING!"); break; } else { sortedInterList = tempList; } } for (var i = 0; i < obstacleList.length; i++) { sortedObList = this.addAngle(sortedObList, obstacleList[i]); if (sortedObList.length == 0) { break; } } var offsetI = 0; var obOffsetI = 1; if (sortedInterList.length > 0 && sortedInterList[0][1]) { offsetI = 1; } if (sortedObList.length > 0 && sortedObList[0][1]) { obOffsetI = 0; } var goodAngles = []; var obstacleAngles = []; for (var i = 0; i < sortedInterList.length; i += 2) { var angle1 = sortedInterList[(i + offsetI).mod(sortedInterList.length)][0]; var angle2 = sortedInterList[(i + 1 + offsetI).mod(sortedInterList.length)][0]; var diff = (angle2 - angle1).mod(360); goodAngles.push([angle1, diff]); } for (var i = 0; i < sortedObList.length; i += 2) { var angle1 = sortedObList[(i + obOffsetI).mod(sortedObList.length)][0]; var angle2 = sortedObList[(i + 1 + obOffsetI).mod(sortedObList.length)][0]; var diff = (angle2 - angle1).mod(360); obstacleAngles.push([angle1, diff]); } for (var i = 0; i < goodAngles.length; i++) { var line1 = this.followAngle(goodAngles[i][0], player[k].x, player[k].y, 100 + player[k].size); var line2 = this.followAngle((goodAngles[i][0] + goodAngles[i][1]).mod(360), player[k].x, player[k].y, 100 + player[k].size); drawLine(player[k].x, player[k].y, line1[0], line1[1], 1); drawLine(player[k].x, player[k].y, line2[0], line2[1], 1); drawArc(line1[0], line1[1], line2[0], line2[1], player[k].x, player[k].y, 1); //drawPoint(player[0].x, player[0].y, 2, ""); drawPoint(line1[0], line1[1], 0, "" + i + ": 0"); drawPoint(line2[0], line2[1], 0, "" + i + ": 1"); } for (var i = 0; i < obstacleAngles.length; i++) { var line1 = this.followAngle(obstacleAngles[i][0], player[k].x, player[k].y, 50 + player[k].size); var line2 = this.followAngle((obstacleAngles[i][0] + obstacleAngles[i][1]).mod(360), player[k].x, player[k].y, 50 + player[k].size); drawLine(player[k].x, player[k].y, line1[0], line1[1], 6); drawLine(player[k].x, player[k].y, line2[0], line2[1], 6); drawArc(line1[0], line1[1], line2[0], line2[1], player[k].x, player[k].y, 6); //drawPoint(player[0].x, player[0].y, 2, ""); drawPoint(line1[0], line1[1], 0, "" + i + ": 0"); drawPoint(line2[0], line2[1], 0, "" + i + ": 1"); } if (this.toggleFollow && goodAngles.length == 0) { //This is the follow the mouse mode var distance = this.computeDistance(player[k].x, player[k].y, tempPoint[0], tempPoint[1]); var shiftedAngle = this.shiftAngle(obstacleAngles, this.getAngle(tempPoint[0], tempPoint[1], player[k].x, player[k].y), [0, 360]); var destination = this.followAngle(shiftedAngle, player[k].x, player[k].y, distance); destinationChoices = destination; drawLine(player[k].x, player[k].y, destination[0], destination[1], 1); //tempMoveX = destination[0]; //tempMoveY = destination[1]; } else if (goodAngles.length > 0) { var bIndex = goodAngles[0]; var biggest = goodAngles[0][1]; for (var i = 1; i < goodAngles.length; i++) { var size = goodAngles[i][1]; if (size > biggest) { biggest = size; bIndex = goodAngles[i]; } } var perfectAngle = (bIndex[0] + bIndex[1] / 2).mod(360); perfectAngle = this.shiftAngle(obstacleAngles, perfectAngle, bIndex); var line1 = this.followAngle(perfectAngle, player[k].x, player[k].y, verticalDistance()); destinationChoices = line1; drawLine(player[k].x, player[k].y, line1[0], line1[1], 7); //tempMoveX = line1[0]; //tempMoveY = line1[1]; } else if (badAngles.length > 0 && goodAngles == 0) { //When there are enemies around but no good angles //You're likely screwed. (This should never happen.) console.log("Failed"); destinationChoices = [tempMoveX, tempMoveY]; /*var angleWeights = [] //Put weights on the angles according to enemy distance for (var i = 0; i < allPossibleThreats.length; i++){ var dist = this.computeDistance(player[k].x, player[k].y, allPossibleThreats[i].x, allPossibleThreats[i].y); var angle = this.getAngle(allPossibleThreats[i].x, allPossibleThreats[i].y, player[k].x, player[k].y); angleWeights.push([angle,dist]); } var maxDist = 0; var finalAngle = 0; for (var i = 0; i < angleWeights.length; i++){ if (angleWeights[i][1] > maxDist){ maxDist = angleWeights[i][1]; finalAngle = (angleWeights[i][0] + 180).mod(360); } } var line1 = this.followAngle(finalAngle,player[k].x,player[k].y,f.verticalDistance()); drawLine(player[k].x, player[k].y, line1[0], line1[1], 2); destinationChoices.push(line1);*/ } else if (clusterAllFood.length > 0) { for (var i = 0; i < clusterAllFood.length; i++) { //console.log("mefore: " + clusterAllFood[i][2]); //This is the cost function. Higher is better. var clusterAngle = this.getAngle(clusterAllFood[i][0], clusterAllFood[i][1], player[k].x, player[k].y); clusterAllFood[i][2] = clusterAllFood[i][2] * 6 - this.computeDistance(clusterAllFood[i][0], clusterAllFood[i][1], player[k].x, player[k].y); //console.log("Current Value: " + clusterAllFood[i][2]); //(goodAngles[bIndex][1] / 2 - (Math.abs(perfectAngle - clusterAngle))); clusterAllFood[i][3] = clusterAngle; drawPoint(clusterAllFood[i][0], clusterAllFood[i][1], 1, ""); //console.log("After: " + clusterAllFood[i][2]); } var bestFoodI = 0; var bestFood = clusterAllFood[0][2]; for (var i = 1; i < clusterAllFood.length; i++) { if (bestFood < clusterAllFood[i][2]) { bestFood = clusterAllFood[i][2]; bestFoodI = i; } } //console.log("Best Value: " + clusterAllFood[bestFoodI][2]); var distance = this.computeDistance(player[k].x, player[k].y, clusterAllFood[bestFoodI][0], clusterAllFood[bestFoodI][1]); var shiftedAngle = this.shiftAngle(obstacleAngles, this.getAngle(clusterAllFood[bestFoodI][0], clusterAllFood[bestFoodI][1], player[k].x, player[k].y), [0, 360]); var destination = this.followAngle(shiftedAngle, player[k].x, player[k].y, distance); destinationChoices = destination; //tempMoveX = destination[0]; //tempMoveY = destination[1]; drawLine(player[k].x, player[k].y, destination[0], destination[1], 1); } else { //If there are no enemies around and no food to eat. destinationChoices = [tempMoveX, tempMoveY]; } drawPoint(tempPoint[0], tempPoint[1], tempPoint[2], ""); //drawPoint(tempPoint[0], tempPoint[1], tempPoint[2], "" + Math.floor(this.computeDistance(tempPoint[0], tempPoint[1], I, J))); //drawLine(tempPoint[0], tempPoint[1], player[0].x, player[0].y, 6); //console.log("Slope: " + slope(tempPoint[0], tempPoint[1], player[0].x, player[0].y) + " Angle: " + getAngle(tempPoint[0], tempPoint[1], player[0].x, player[0].y) + " Side: " + (getAngle(tempPoint[0], tempPoint[1], player[0].x, player[0].y) - 90).mod(360)); tempPoint[2] = 1; //console.log("Done working on blob: " + i); } //TODO: Find where to go based on destinationChoices. /*var dangerFound = false; for (var i = 0; i < destinationChoices.length; i++) { if (destinationChoices[i][2]) { dangerFound = true; break; } } destinationChoices.sort(function(a, b){return b[1] - a[1]}); if (dangerFound) { for (var i = 0; i < destinationChoices.length; i++) { if (destinationChoices[i][2]) { tempMoveX = destinationChoices[i][0][0]; tempMoveY = destinationChoices[i][0][1]; break; } } } else { tempMoveX = destinationChoices.peek()[0][0]; tempMoveY = destinationChoices.peek()[0][1]; //console.log("Done " + tempMoveX + ", " + tempMoveY); }*/ } //console.log("MOVING RIGHT NOW!"); //console.log("______Never lied ever in my life."); return destinationChoices; } }; }; window.botList.push(new AposBot()); window.updateBotList(); //This function might not exist yet.
'use strict'; /*jshint undef:false */ (function() { var utils = require('../utils'); describe('app', function() { var ptor; beforeEach(function() { ptor = protractor.getInstance(); console.info('\nrunning:', jasmine.getEnv().currentSpec.description); }); afterEach(function() { if (!jasmine.getEnv().currentSpec.results().passed()) { utils.takeScreenshot(browser, jasmine.getEnv().currentSpec.description.replace(/ /g, '-')); } }); it('should load the homepage', function() { ptor.get('/'); expect(ptor.isElementPresent(by.css('body'))).toBe(true); }); it('should navigate to the docs page when clicking', function() { element(by.css('a[ui-sref="root.getting-started"]')).click(); expect(ptor.getCurrentUrl()).toMatch(/\/getting-started/); }); }); })();
/** * 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. * * @emails oncall+relay * @flow * @format */ // flowlint ambiguous-object-type:error 'use strict'; import type {RelayMockEnvironment} from 'relay-test-utils/RelayModernMockEnvironment'; const RelayEnvironmentProvider = require('../RelayEnvironmentProvider'); const React = require('react'); const ReactTestRenderer = require('react-test-renderer'); const {getRequest, graphql} = require('relay-runtime'); const {createMockEnvironment} = require('relay-test-utils'); const CommentCreateSubscription = getRequest(graphql` subscription useSubscriptionTestCommentCreateSubscription( $input: CommentCreateSubscriptionInput ) { commentCreateSubscribe(input: $input) { feedbackCommentEdge { node { id body { text } } } } } `); describe('useSubscription', () => { const mockEnv = createMockEnvironment(); const config = { variables: {}, subscription: CommentCreateSubscription, }; const dispose = jest.fn(); const requestSubscription = jest.fn((_passedEnv, _passedConfig) => ({ dispose, })); const relayRuntime = require('relay-runtime'); jest.mock('relay-runtime', () => { return { ...relayRuntime, requestSubscription, }; }); const useSubscription = require('../useSubscription'); afterEach(() => { jest.clearAllMocks(); }); afterAll(() => { jest.resetAllMocks(); }); type Props = {| env: RelayMockEnvironment, |}; function MyComponent({env}: Props) { function InnerComponent() { useSubscription(config); return 'Hello Relay!'; } return ( <RelayEnvironmentProvider environment={env}> <InnerComponent /> </RelayEnvironmentProvider> ); } let componentInstance; const renderComponent = () => ReactTestRenderer.act(() => { componentInstance = ReactTestRenderer.create( <MyComponent env={mockEnv} />, ); }); it('should call requestSubscription when mounted', () => { renderComponent(); expect(requestSubscription).toHaveBeenCalled(); }); it('should call requestSubscription(...).dispose when unmounted', () => { renderComponent(); ReactTestRenderer.act(() => { componentInstance.unmount(); }); expect(dispose).toHaveBeenCalled(); }); it('should pass the current relay environment', () => { renderComponent(); expect(requestSubscription.mock.calls[0][0]).toEqual(mockEnv); }); it('should forward the config', () => { renderComponent(); expect(requestSubscription.mock.calls[0][1]).toEqual(config); }); it('should dispose and re-subscribe when the environment changes', () => { renderComponent(); expect(requestSubscription).toHaveBeenCalledTimes(1); expect(dispose).not.toHaveBeenCalled(); ReactTestRenderer.act(() => { componentInstance.update(<MyComponent env={createMockEnvironment()} />); }); expect(dispose).toHaveBeenCalled(); expect(requestSubscription).toHaveBeenCalledTimes(2); }); });
require('../../support/spec_helper'); describe("Cucumber.Listener.PrettyFormatter", function () { var Cucumber = requireLib('cucumber'); var path = require('path'); var colors = require('colors/safe'); colors.enabled = true; var formatter, formatterHearMethod, summaryFormatter, prettyFormatter, options, logged; beforeEach(function () { options = {useColors: true}; formatter = createSpyWithStubs("formatter", {finish: null}); logged = ''; spyOnStub(formatter, 'log').and.callFake(function (text) { logged += text; }); formatterHearMethod = spyOnStub(formatter, 'hear'); summaryFormatter = createSpy("summary formatter"); spyOn(Cucumber.Listener, 'Formatter').and.returnValue(formatter); spyOn(Cucumber.Listener, 'SummaryFormatter').and.returnValue(summaryFormatter); prettyFormatter = Cucumber.Listener.PrettyFormatter(options); }); describe("constructor", function () { it("creates a formatter", function () { expect(Cucumber.Listener.Formatter).toHaveBeenCalledWith(options); }); it("extends the formatter", function () { expect(prettyFormatter).toBe(formatter); }); it("creates a summaryFormatter", function () { expect(Cucumber.Listener.SummaryFormatter).toHaveBeenCalled(); }); }); describe("hear()", function () { var event, callback; beforeEach(function () { event = createSpy("event"); callback = createSpy("callback"); spyOnStub(summaryFormatter, 'hear'); }); it("tells the summary formatter to listen to the event", function () { prettyFormatter.hear(event, callback); expect(summaryFormatter.hear).toHaveBeenCalled(); expect(summaryFormatter.hear).toHaveBeenCalledWithValueAsNthParameter(event, 1); expect(summaryFormatter.hear).toHaveBeenCalledWithAFunctionAsNthParameter(2); }); describe("summary formatter callback", function () { var summaryFormatterCallback; beforeEach(function () { prettyFormatter.hear(event, callback); summaryFormatterCallback = summaryFormatter.hear.calls.mostRecent().args[1]; }); it("tells the formatter to listen to the event", function () { summaryFormatterCallback(); expect(formatterHearMethod).toHaveBeenCalledWith(event, callback); }); }); }); describe("handleBeforeFeatureEvent()", function () { var event, feature, callback; beforeEach(function () { feature = createSpyWithStubs("feature", { getKeyword: "feature-keyword", getName: "feature-name", getDescription: '', getTags: [] }); event = createSpyWithStubs("event", { getPayloadItem: feature }); callback = createSpy("callback"); }); describe('no tags or description', function () { beforeEach(function (){ prettyFormatter.handleBeforeFeatureEvent(event, callback); }); it('logs the keyword and name', function () { expect(logged).toEqual('feature-keyword: feature-name\n\n'); }); it("calls back", function () { expect(callback).toHaveBeenCalled(); }); }); describe('with tags', function () { beforeEach(function (){ feature.getTags.and.returnValue([ createSpyWithStubs("tag1", {getName: '@tag1'}), createSpyWithStubs("tag2", {getName: '@tag2'}) ]); prettyFormatter.handleBeforeFeatureEvent(event, callback); }); it('logs the keyword and name', function () { var expected = colors.cyan('@tag1 @tag2') + '\n' + 'feature-keyword: feature-name' + '\n\n'; expect(logged).toEqual(expected); }); }); describe('with feature description', function () { beforeEach(function (){ feature.getDescription.and.returnValue('line1\nline2'); prettyFormatter.handleBeforeFeatureEvent(event, callback); }); it('logs the keyword and name', function () { var expected = 'feature-keyword: feature-name' + '\n\n' + ' line1' + '\n' + ' line2' + '\n\n'; expect(logged).toEqual(expected); }); }); }); describe("handleBeforeScenarioEvent()", function () { var event, scenario, callback; beforeEach(function () { scenario = createSpyWithStubs("scenario", { getKeyword: "scenario-keyword", getName: "scenario-name", getUri: path.join(process.cwd(), "scenario-uri"), getLine: 1, getBackground: undefined, getOwnTags: [], getSteps: [] }); event = createSpyWithStubs("event", { getPayloadItem: scenario }); callback = createSpy("callback"); }); describe('no tags, not showing source', function () { beforeEach(function (){ prettyFormatter.handleBeforeScenarioEvent(event, callback); }); it('logs the keyword and name', function () { expect(logged).toEqual(' scenario-keyword: scenario-name\n'); }); it("calls back", function () { expect(callback).toHaveBeenCalled(); }); }); describe('with tags', function () { beforeEach(function (){ scenario.getOwnTags.and.returnValue([ createSpyWithStubs("tag1", {getName: '@tag1'}), createSpyWithStubs("tag2", {getName: '@tag2'}) ]); prettyFormatter.handleBeforeScenarioEvent(event, callback); }); it('logs the keyword and name', function () { var expected = ' ' + colors.cyan('@tag1 @tag2') + '\n' + ' scenario-keyword: scenario-name' + '\n'; expect(logged).toEqual(expected); }); }); describe('showing source', function () { beforeEach(function (){ options.showSource = true; prettyFormatter.handleBeforeScenarioEvent(event, callback); }); it('logs the keyword and name', function () { var expected = ' scenario-keyword: scenario-name ' + colors.gray('# scenario-uri:1') + '\n'; expect(logged).toEqual(expected); }); }); }); describe("handleAfterScenarioEvent()", function () { var event, callback; beforeEach(function () { event = createSpy("event"); callback = createSpy("callback"); }); it("logs a new line", function () { prettyFormatter.handleAfterScenarioEvent(event, callback); expect(prettyFormatter.log).toHaveBeenCalledWith("\n"); }); it("calls back", function () { prettyFormatter.handleAfterScenarioEvent(event, callback); expect(callback).toHaveBeenCalled(); }); }); describe("handleStepResultEvent()", function () { var step, stepResult, event, callback; beforeEach(function () { step = createSpyWithStubs("step", { isHidden: null }); stepResult = createSpyWithStubs("step result", { getStep: step, getStatus: undefined }); event = createSpyWithStubs("event", { getPayloadItem: stepResult }); callback = createSpy("callback"); spyOnStub(prettyFormatter, 'logStepResult'); }); it("gets the step result from the event payload", function () { prettyFormatter.handleStepResultEvent(event, callback); expect(event.getPayloadItem).toHaveBeenCalledWith('stepResult'); }); describe("when step result is not hidden", function () { it("calls logStepResult() as the step is not hidden", function () { step.isHidden.and.returnValue(false); prettyFormatter.handleStepResultEvent(event, callback); expect(prettyFormatter.logStepResult).toHaveBeenCalledWith(step, stepResult); }); }); describe("when step result is hidden and has not failed", function () { it("does not call logStepResult() to keep the step hidden", function () { step.isHidden.and.returnValue(true); stepResult.getStatus.and.returnValue(Cucumber.Status.PASSED); prettyFormatter.handleStepResultEvent(event, callback); expect(prettyFormatter.logStepResult).not.toHaveBeenCalled(); }); }); describe("when step result is hidden and has failed", function () { it("calls logStepResult() to log the failure even though the step is supposed to be hidden", function () { step.isHidden.and.returnValue(true); stepResult.getStatus.and.returnValue(Cucumber.Status.FAILED); prettyFormatter.handleStepResultEvent(event, callback); expect(prettyFormatter.logStepResult).toHaveBeenCalledWith(step, stepResult); }); }); it("calls back", function () { prettyFormatter.handleStepResultEvent(event, callback); expect(callback).toHaveBeenCalled(); }); }); describe("logStepResult()", function () { var stepResult, step, stepDefinition; beforeEach(function () { stepDefinition = createSpyWithStubs("step definition", { getLine: 1, getUri: path.join(process.cwd(), 'step-definition-uri') }); step = createSpyWithStubs("step", { getDataTable: null, getDocString: null, getKeyword: "step-keyword ", getName: "step-name", hasDataTable: null, hasDocString: null, }); stepResult = createSpyWithStubs("step result", { getFailureException: null, getStep: step, getStepDefinition: stepDefinition, getStatus: Cucumber.Status.PASSED }); }); describe("passing step", function () { beforeEach(function () { prettyFormatter.logStepResult(step, stepResult); }); it('logs the keyword and name', function () { var expected = ' ' + colors.green('step-keyword step-name') + '\n'; expect(logged).toEqual(expected); }); }); describe("pending step", function () { beforeEach(function () { stepResult.getStatus.and.returnValue(Cucumber.Status.PENDING); prettyFormatter.logStepResult(step, stepResult); }); it('logs the keyword and name', function () { var expected = ' ' + colors.yellow('step-keyword step-name') + '\n'; expect(logged).toEqual(expected); }); }); describe("skipped step", function () { beforeEach(function () { stepResult.getStatus.and.returnValue(Cucumber.Status.SKIPPED); prettyFormatter.logStepResult(step, stepResult); }); it('logs the keyword and name', function () { var expected = ' ' + colors.cyan('step-keyword step-name') + '\n'; expect(logged).toEqual(expected); }); }); describe("undefined step", function () { beforeEach(function () { stepResult.getStatus.and.returnValue(Cucumber.Status.UNDEFINED); prettyFormatter.logStepResult(step, stepResult); }); it('logs the keyword and name', function () { var expected = ' ' + colors.yellow('step-keyword step-name') + '\n'; expect(logged).toEqual(expected); }); }); describe("failed step", function () { beforeEach(function () { stepResult.getStatus.and.returnValue(Cucumber.Status.FAILED); stepResult.getFailureException.and.returnValue({stack: 'stack error\n stacktrace1\n stacktrace2'}); prettyFormatter.logStepResult(step, stepResult); }); it('logs the keyword and name and failure', function () { var expected = ' ' + colors.red('step-keyword step-name') + '\n' + ' stack error' + '\n' + ' stacktrace1' + '\n' + ' stacktrace2' + '\n'; expect(logged).toEqual(expected); }); }); describe("without name", function () { beforeEach(function () { step.getName.and.returnValue(undefined); prettyFormatter.logStepResult(step, stepResult); }); it('logs the keyword', function () { var expected = ' step-keyword ' + '\n'; expect(colors.strip(logged)).toEqual(expected); }); }); describe("showing source", function () { beforeEach(function() { options.showSource = true; prettyFormatter.logStepResult(step, stepResult); }); it('logs the keyword and name', function () { var expected = ' step-keyword step-name# step-definition-uri:1' + '\n'; expect(colors.strip(logged)).toEqual(expected); }); }); describe("with data table", function () { beforeEach(function() { var rows = [ ["cuk", "cuke", "cukejs"], ["c", "cuke", "cuke.js"], ["cu", "cuke", "cucumber"] ]; var dataTable = createSpyWithStubs("data table", {raw: rows}); step.getDataTable.and.returnValue(dataTable); step.hasDataTable.and.returnValue(true); prettyFormatter.logStepResult(step, stepResult); }); it('logs the keyword and name and data table', function () { var expected = ' step-keyword step-name' + '\n' + ' | cuk | cuke | cukejs |' + '\n' + ' | c | cuke | cuke.js |' + '\n' + ' | cu | cuke | cucumber |' + '\n'; expect(colors.strip(logged)).toEqual(expected); }); }); describe("with doc string", function () { beforeEach(function () { var contents = "this is a multiline\ndoc string\n\n:-)"; var docString = createSpyWithStubs("doc string", {getContents: contents}); step.getDocString.and.returnValue(docString); step.hasDocString.and.returnValue(true); prettyFormatter.logStepResult(step, stepResult); }); it('logs the keyword and name and doc string', function () { var expected = ' step-keyword step-name' + '\n' + ' """' + '\n' + ' this is a multiline' + '\n' + ' doc string' + '\n' + '\n' + ' :-)' + '\n' + ' """' + '\n'; expect(colors.strip(logged)).toEqual(expected); }); }); }); describe("handleAfterFeaturesEvent()", function () { var event, callback, summary; beforeEach(function () { event = createSpy("event"); callback = createSpy("callback"); summary = createSpy("summary logs"); spyOnStub(summaryFormatter, 'getLogs').and.returnValue(summary); }); it("gets the summary from the summaryFormatter", function () { prettyFormatter.handleAfterFeaturesEvent(event, callback); expect(summaryFormatter.getLogs).toHaveBeenCalled(); }); it("logs the summary", function () { prettyFormatter.handleAfterFeaturesEvent(event, callback); expect(prettyFormatter.log).toHaveBeenCalledWith(summary); }); it("calls finish with the callback", function () { prettyFormatter.handleAfterFeaturesEvent(event, callback); expect(prettyFormatter.finish).toHaveBeenCalledWith(callback); }); }); describe("logIndented()", function () { var text, level, indented; beforeEach(function () { text = createSpy("text"); level = createSpy("level"); indented = createSpy("indented text"); spyOn(prettyFormatter, 'indent').and.returnValue(indented); }); it("indents the text", function () { prettyFormatter.logIndented(text, level); expect(prettyFormatter.indent).toHaveBeenCalledWith(text, level); }); it("logs the indented text", function () { prettyFormatter.logIndented(text, level); expect(prettyFormatter.log).toHaveBeenCalledWith(indented); }); }); describe("indent()", function () { it("returns the original text on a 0-indentation level", function () { var original = "cuke\njavascript"; var expected = original; var actual = prettyFormatter.indent(original, 0); expect(actual).toEqual(expected); }); it("returns the 1-level indented text", function () { var original = "cuke\njavascript"; var expected = " cuke\n javascript"; var actual = prettyFormatter.indent(original, 1); expect(actual).toEqual(expected); }); it("returns the 2-level indented text", function () { var original = "cuke\njavascript"; var expected = " cuke\n javascript"; var actual = prettyFormatter.indent(original, 2); expect(actual).toEqual(expected); }); it("returns the 3-level indented text", function () { var original = "cuke\njavascript"; var expected = " cuke\n javascript"; var actual = prettyFormatter.indent(original, 3); expect(actual).toEqual(expected); }); }); describe("determineMaxStepLengthForElement()", function () { var steps, element; beforeEach(function () { steps = Cucumber.Type.Collection(); element = createSpyWithStubs("element", { getSteps: steps }); }); it("returns zero when there are no steps", function () { var maxStepLength = prettyFormatter.determineMaxStepLengthForElement(element); expect(maxStepLength).toEqual(0); }); it("returns the combined length of a step's keyword and name when there is one step", function () { var step = createSpyWithStubs("step", { getKeyword: 'step-keyword', getName: 'step-name' }); steps.add(step); var maxStepLength = prettyFormatter.determineMaxStepLengthForElement(element); expect(maxStepLength).toEqual(21); }); it("returns the maximum length of all the steps", function () { var step = createSpyWithStubs("step", { getKeyword: 'step-keyword', getName: 'step-name' }); var step2 = createSpyWithStubs("step", { getKeyword: 'step-keyword-2', getName: 'step-name-2' }); steps.add(step); steps.add(step2); var maxStepLength = prettyFormatter.determineMaxStepLengthForElement(element); expect(maxStepLength).toEqual(25); }); }); });
define(['aura/aura'], function (aura) { 'use strict'; /*global describe:true, it:true, before:true, sinon:true */ describe('Aura Apps', function () { describe('App Public API', function () { var ext = { initialize: sinon.spy(function (app) { app.sandbox.foo = 'bar'; }), afterAppStart: sinon.spy() }; var App = aura(); App.use(ext); var startOptions = { foo: 'bar' }; var initStatus = App.start(startOptions); // Make sure the app is started before... before(function (done) { initStatus.done(function () { done(); }); initStatus.fail(done); }); it('Should have loaded its core dependencies', function () { App.core.data.deferred.should.be.a('function'); }); it('Should have a public API', function () { App.use.should.be.a('function'); App.start.should.be.a('function'); App.stop.should.be.a('function'); }); it('Should call initialize method on extension', function () { ext.initialize.should.have.been.calledWith(App); }); it('Should call afterAppStart method on extension', function () { ext.afterAppStart.should.have.been.called; //With(App); }); it('Should have extended the sandbox', function () { App.sandbox.foo.should.equal('bar'); }); it('Should complain if I try to use a new extension and the app is already started', function () { var use = function () { App.use(function () {}); }; use.should.Throw(Error); }); }); describe('Defining and loading extensions', function () { it('Should be able to use extensions defined as objects', function (done) { var ext = { initialize: sinon.spy() }; aura().use(ext).start({ widgets: [] }).done(function () { ext.initialize.should.have.been.called; done(); }); }); it('Should be able to use extensions defined as functions', function (done) { var insideExt = sinon.spy(); var ext = sinon.spy(function (appEnv) { insideExt('foo'); }); var App = aura().use(ext); App.start().done(function () { ext.should.have.been.calledWith(App); insideExt.should.have.been.calledWith('foo'); done(); }); }); it('Should pass the start options to the extensions...', function (done) { var startOptions = { foo: 'bar' }; var insideExt = sinon.spy(); var ext = sinon.spy(function (app) { insideExt(app.startOptions); }); var App = aura().use(ext); App.start(startOptions).done(function () { ext.should.have.been.calledWith(App); insideExt.should.have.been.calledWith(startOptions); done(); }); }); it('Should be able to use extensions defined as amd modules', function (done) { var ext = { initialize: sinon.spy() }; define('myExtensionModule', ext); aura().use('myExtensionModule').start().done(function () { ext.initialize.should.have.been.called; done(); }); }); }); describe('Logging', function() { it('logger should be available on app', function() { var App = aura(); App.logger.log.should.be.a('function'); App.logger.name.should.equal(App.ref); }); it('logger should be available on sandboxes', function() { var App = aura(); var sandbox = App.createSandbox(); sandbox.logger.log.should.be.a('function'); sandbox.logger.name.should.equal(sandbox.ref); }); }); }); });
var assocDelete = require('./_assocDelete'); /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, array = data.array; return array ? assocDelete(array, key) : data.map['delete'](key); } module.exports = stackDelete;
/*jshint node:true*/ var stringUtil = require('../../lib/utilities/string'); var SilentError = require('../../lib/errors/silent'); module.exports = { description: 'Generates an ember-data adapter.', availableOptions: [ { name: 'base-class', type: String } ], locals: function(options) { var adapterName = options.entity.name; var baseClass = 'DS.RESTAdapter'; var importStatement = 'import DS from \'ember-data\';'; if (!options.baseClass && adapterName !== 'application') { options.baseClass = 'application'; } if (options.baseClass === adapterName) { throw new SilentError('Adapters cannot extend from themself. To resolve this, remove the `--base-class` option or change to a different base-class.'); } if (options.baseClass) { baseClass = stringUtil.classify(options.baseClass.replace('\/', '-')); baseClass = baseClass + 'Adapter'; importStatement = 'import ' + baseClass + ' from \'./' + options.baseClass + '\';'; } return { importStatement: importStatement, baseClass: baseClass }; } };
CKEDITOR.plugins.setLang("forms","sq",{button:{title:"Rekuizitat e Pullës",text:"Teskti (Vlera)",type:"LLoji",typeBtn:"Buton",typeSbm:"Dërgo",typeRst:"Rikthe"},checkboxAndRadio:{checkboxTitle:"Rekuizitat e Kutizë Përzgjedhëse",radioTitle:"Rekuizitat e Pullës",value:"Vlera",selected:"Përzgjedhur",required:"Required"},form:{title:"Rekuizitat e Formës",menu:"Rekuizitat e Formës",action:"Veprim",method:"Metoda",encoding:"Kodimi"},hidden:{title:"Rekuizitat e Fushës së Fshehur",name:"Emër",value:"Vlera"}, select:{title:"Rekuizitat e Fushës së Përzgjedhur",selectInfo:"Përzgjidh Informacionin",opAvail:"Opsionet e Mundshme",value:"Vlera",size:"Madhësia",lines:"rreshtat",chkMulti:"Lejo përzgjidhje të shumëfishta",required:"Required",opText:"Teksti",opValue:"Vlera",btnAdd:"Vendos",btnModify:"Ndrysho",btnUp:"Sipër",btnDown:"Poshtë",btnSetValue:"Bëje si vlerë të përzgjedhur",btnDelete:"Grise"},textarea:{title:"Rekuzitat e Fushës së Tekstit",cols:"Kolonat",rows:"Rreshtat"},textfield:{title:"Rekuizitat e Fushës së Tekstit", name:"Emër",value:"Vlera",charWidth:"Gjerësia e Karakterit",maxChars:"Numri maksimal i karaktereve",required:"Required",type:"LLoji",typeText:"Teksti",typePass:"Fjalëkalimi",typeEmail:"Posta Elektronike",typeSearch:"Kërko",typeTel:"Numri i Telefonit",typeUrl:"URL"}});
version https://git-lfs.github.com/spec/v1 oid sha256:5a688e8597f5fa9eaa98dad26086f21ced1570abb0a2b469ab2daac01c3dfaac size 2079
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { const configuration = { basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular-devkit/build-angular/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { dir: require('path').join(__dirname, 'coverage'), reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], customLaunchers: { Chrome_travis_ci: { base: 'Chrome', flags: ['--no-sandbox'] } }, singleRun: false }; if (process.env.TRAVIS) { configuration.browsers = ['Chrome_travis_ci']; } config.set(configuration); };
/*! * https://github.com/adampietrasiak/jquery.initialize * * Copyright (c) 2015-2016 Adam Pietrasiak * Released under the MIT license * https://github.com/timpler/jquery.initialize/blob/master/LICENSE * * This is based on MutationObserver * https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver */ ;(function ($) { "use strict"; var combinators = [' ', '>', '+', '~']; // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors#Combinators var fraternisers = ['+', '~']; // These combinators involve siblings. var complexTypes = ['ATTR', 'PSEUDO', 'ID', 'CLASS']; // These selectors are based upon attributes. //Check if browser supports "matches" function if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector; } // Understand what kind of selector the initializer is based upon. function grok(msobserver) { if (!$.find.tokenize) { // This is an old version of jQuery, so cannot parse the selector. // Therefore we must assume the worst case scenario. That is, that // this is a complicated selector. This feature was available in: // https://github.com/jquery/sizzle/issues/242 msobserver.isCombinatorial = true; msobserver.isFraternal = true; msobserver.isComplex = true; return; } // Parse the selector. msobserver.isCombinatorial = false; msobserver.isFraternal = false; msobserver.isComplex = false; var token = $.find.tokenize(msobserver.selector); for (var i = 0; i < token.length; i++) { for (var j = 0; j < token[i].length; j++) { if (combinators.indexOf(token[i][j].type) != -1) msobserver.isCombinatorial = true; // This selector uses combinators. if (fraternisers.indexOf(token[i][j].type) != -1) msobserver.isFraternal = true; // This selector uses sibling combinators. if (complexTypes.indexOf(token[i][j].type) != -1) msobserver.isComplex = true; // This selector is based on attributes. } } } // MutationSelectorObserver represents a selector and it's associated initialization callback. var MutationSelectorObserver = function (selector, callback, options) { this.selector = selector.trim(); this.callback = callback; this.options = options; grok(this); }; // List of MutationSelectorObservers. var msobservers = []; msobservers.initialize = function (selector, callback, options) { // Wrap the callback so that we can ensure that it is only // called once per element. var seen = []; var callbackOnce = function () { if (seen.indexOf(this) == -1) { seen.push(this); $(this).each(callback); } }; // See if the selector matches any elements already on the page. $(options.target).find(selector).each(callbackOnce); // Then, add it to the list of selector observers. var msobserver = new MutationSelectorObserver(selector, callbackOnce, options) this.push(msobserver); // The MutationObserver watches for when new elements are added to the DOM. var observer = new MutationObserver(function (mutations) { var matches = []; // For each mutation. for (var m = 0; m < mutations.length; m++) { // If this is an attributes mutation, then the target is the node upon which the mutation occurred. if (mutations[m].type == 'attributes') { // Check if the mutated node matchs. if (mutations[m].target.matches(msobserver.selector)) matches.push(mutations[m].target); // If the selector is fraternal, query siblings of the mutated node for matches. if (msobserver.isFraternal) matches.push.apply(matches, mutations[m].target.parentElement.querySelectorAll(msobserver.selector)); else matches.push.apply(matches, mutations[m].target.querySelectorAll(msobserver.selector)); } // If this is an childList mutation, then inspect added nodes. if (mutations[m].type == 'childList') { // Search added nodes for matching selectors. for (var n = 0; n < mutations[m].addedNodes.length; n++) { if (!(mutations[m].addedNodes[n] instanceof Element)) continue; // Check if the added node matches the selector if (mutations[m].addedNodes[n].matches(msobserver.selector)) matches.push(mutations[m].addedNodes[n]); // If the selector is fraternal, query siblings for matches. if (msobserver.isFraternal) matches.push.apply(matches, mutations[m].addedNodes[n].parentElement.querySelectorAll(msobserver.selector)); else matches.push.apply(matches, mutations[m].addedNodes[n].querySelectorAll(msobserver.selector)); } } } // For each match, call the callback using jQuery.each() to initialize the element (once only.) for (var i = 0; i < matches.length; i++) $(matches[i]).each(msobserver.callback); }); // Observe the target element. var defaultObeserverOpts = { childList: true, subtree: true, attributes: msobserver.isComplex }; observer.observe(options.target, options.observer || defaultObeserverOpts ); return observer; }; // Deprecated API (does not work with jQuery >= 3.1.1): $.fn.initialize = function (callback, options) { return msobservers.initialize(this.selector, callback, $.extend({}, $.initialize.defaults, options)); }; // Supported API $.initialize = function (selector, callback, options) { return msobservers.initialize(selector, callback, $.extend({}, $.initialize.defaults, options)); }; // Options $.initialize.defaults = { target: document.documentElement, // Defaults to observe the entire document. observer: null // MutationObserverInit: Defaults to internal configuration if not provided. } })(jQuery);
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from '../utils/griddleConnect'; import compose from 'recompose/compose'; import mapProps from 'recompose/mapProps'; import getContext from 'recompose/getContext'; import { classNamesForComponentSelector, stylesForComponentSelector } from '../selectors/dataSelectors'; const EnhancedPaginationContainer = OriginalComponent => compose( getContext({ components: PropTypes.object, }), connect( (state, props) => ({ className: classNamesForComponentSelector(state, 'Pagination'), style: stylesForComponentSelector(state, 'Pagination'), }) ), mapProps((props) => { const { components, ...otherProps } = props; return { Next: components.NextButton, Previous: components.PreviousButton, PageDropdown: components.PageDropdown, ...otherProps }; }) )((props) => <OriginalComponent {...props} />); export default EnhancedPaginationContainer;
// Test the binary interface to bufferlists var Buffer = require('buffer').Buffer; var BufferList = require('bufferlist').BufferList; // old style var Binary = require('bufferlist/binary').Binary; // old style var sys = require('sys'); var assert = require('assert'); exports.binary = function () { function runTest(bufs, check) { var bList = new BufferList; var binary = Binary(bList) .getWord16be('xLen') .when('xLen', 0, function (vars) { assert.eql(vars.xLen, 0, 'when check for 0 failed'); this .getWord32le('msgLen') .getBuffer('msg', function (vars) { return vars.msgLen }) .tap(function (vars) { vars.moo = 42; }) .exit() ; }) .getBuffer('xs', 'xLen') .tap(function (vars) { vars.moo = 100; }) .end() ; var iv = setInterval(function () { var buf = bufs.shift(); if (!buf) { clearInterval(iv); check(binary.vars); } else { bList.push(buf); } }, 50); } runTest( ['\x00','\x04m','eow'].map(function (s) { var b = new Buffer(Buffer.byteLength(s,'binary')); b.write(s,'binary'); return b; }), function (vars) { assert.eql( vars.xLen, 4, 'xLen == 4 failed (xLen == ' + sys.inspect(vars.xLen) + ')' ); var xs = vars.xs.toString(); assert.eql( xs, 'meow', 'xs != "meow", xs = ' + sys.inspect(xs) ); assert.eql( vars.moo, 100, 'moo != 100, moo == ' + sys.inspect(vars.moo) ); } ); runTest( ['\x00\x00','\x12\x00\x00\x00hap','py pur','ring c','ats'] .map(function (s) { var b = new Buffer(Buffer.byteLength(s,'binary')); b.write(s,'binary'); return b; }), function (vars) { assert.eql(vars.xLen, 0, 'xLen == 0 in "\\x00\\x12happy purring cats"'); assert.eql( vars.msgLen, 18, 'msgLen != 18, msgLen = ' + sys.inspect(vars.msgLen) ); assert.eql(vars.moo, 42, 'moo != 42'); } ); };
/** * Base Event class. * @param {String} type - The type * @param {Object} [data] - The data * @constructor * @class */ function Event(type, data){ this._sender = null; this._type = type; this._data = data; for(var prop in data) { this[prop] = data[prop]; } this._stopPropagation = false; } /** * Returns a copy of the event. * @returns {Event} - copy of this event */ Event.prototype.copy = function(){ var evt = new Event(this._type, this._data); evt.setSender(this._sender); return evt; }; /** * Stop event from being passed to the subsequent event listenerers */ Event.prototype.stopPropagation = function(){ this._stopPropagation = true; }; /** * @return {EventDispatcher} - dispatcher of the event */ Event.prototype.getSender = function(){ return this._sender; }; /** * Used by the EventDispatcher that dispatches the event. * @param {EventDispatcher} sender - dispatcher of the event */ Event.prototype.setSender = function(sender) { this._sender = sender; }; /** * @return {String} type of the event */ Event.prototype.getType = function(){ return this._type; }; module.exports = Event;
module.exports = { findBundle: function(i, options) { return ["a.js", "b.js", "c.js"]; } };
var bodyParser = require('body-parser'); var path = require('path'); var mongoose = require('mongoose'); var express = require('express'); var app = express(); mongoose.Promise = global.Promise; mongoose.connect('mongodb://localhost/message_board'); /* set up schema */ var Schema = mongoose.Schema; var MessageSchema = new mongoose.Schema({ name: {type: String, required: true, minlength: 1}, message: {type: String, required: true, minlength: 1}, comments: [{type: Schema.Types.ObjectId, ref: 'Comment'}] }, { timestamps: true }); var CommentSchema = new mongoose.Schema({ _message: {type: Schema.Types.ObjectId, ref: 'Message'}, name: {type: String, required: true, minlength: 1}, comment: {type: String, required: true, minlength: 1}, }, { timestamps: true }); /* create models and assign to vars for use later */ var Message = mongoose.model('Message', MessageSchema); var Comment = mongoose.model('Comment', CommentSchema); app.use(bodyParser.urlencoded({extended: true})); app.use(express.static(path.join(__dirname, '/static'))); app.set('/views', path.join(__dirname, '/views')); app.set('view engine', 'ejs'); app.get('/', function(request, response) { Message.find({}).populate('comments').exec(function(errors, messages) { console.log('/: messages ->', messages); if (errors) { console.log('/: errors occured during retrieval of document(s)...'); for (var index in errors) { console.log('-', errors[index]); } } else { response.render('index', {messages: messages}); } }); }); app.post('/message/add', function(request, response) { if (!request.body.name || !request.body.message) { console.log('/message/add: required data not present in request...message not added'); response.redirect('/'); return; } var message = new Message({name: request.body.name, message: request.body.message}); message.save(function(errors) { if (errors) { console.log('/: errors occured during save of document(s)...'); for (var index in errors) { console.log('-', errors[index]); } } else { response.redirect('/'); } }); }); app.post('/comment/add/:mid', function(request, response) { Message.findOne({_id: request.params.mid}, function(errors, message) { if (errors) { console.log('/comment/add/mid: error occurred during retrieval of document(s)...'); for (var index in errors) { console.log('-', errors[index]); } } else { var comment = new Comment(request.body); comment._message = message._id; comment.save(function(errors) { if (errors) { console.log('/comment/add/mid: error occurred during save of comment...'); for (var index in errors) { console.log('-', errors[index]); } } else { message.comments.push(comment); message.save(function(errors) { if (errors) { console.log('/comment/add/mid: error occurred during save of message...'); for (var index in errors) { console.log('-', errors[index]); } } else { response.redirect('/'); } }); } }); } }); }); app.listen(8000, function() { console.log('server is listening on port 8000...'); });
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Behavior for "fixed" headers and footers - be sure to also include the item 'Browser specific workarounds for "fixed" headers and footers' when supporting Android 2.x or iOS 5 //>>label: Toolbars: Fixed //>>group: Widgets //>>css.structure: ../css/structure/jquery.mobile.fixedToolbar.css //>>css.theme: ../css/themes/default/jquery.mobile.theme.css define( [ "jquery", "../widget", "../core", "../animationComplete", "../navigation", "./page","./toolbar","../zoom" ], function( jQuery ) { //>>excludeEnd("jqmBuildExclude"); (function( $, undefined ) { $.widget( "mobile.toolbar", $.mobile.toolbar, { options: { position:null, visibleOnPageShow: true, disablePageZoom: true, transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown) fullscreen: false, tapToggle: true, tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-flipswitch, .ui-popup, .ui-panel, .ui-panel-dismiss-open", hideDuringFocus: "input, textarea, select", updatePagePadding: true, trackPersistentToolbars: true, // Browser detection! Weeee, here we go... // Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately. // Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience. // Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window // The following function serves to rule out some popular browsers with known fixed-positioning issues // This is a plugin option like any other, so feel free to improve or overwrite it supportBlacklist: function() { return !$.support.fixedPosition; } }, _create: function() { this._super(); if ( this.options.position === "fixed" && !this.options.supportBlacklist() ) { this._makeFixed(); } }, _makeFixed: function() { this.element.addClass( "ui-"+ this.role +"-fixed" ); this.updatePagePadding(); this._addTransitionClass(); this._bindPageEvents(); this._bindToggleHandlers(); }, _setOptions: function( o ) { if ( o.position === "fixed" && this.options.position !== "fixed" ) { this._makeFixed(); } if ( this.options.position === "fixed" && !this.options.supportBlacklist() ) { var $page = ( !!this.page )? this.page: ( $(".ui-page-active").length > 0 )? $(".ui-page-active"): $(".ui-page").eq(0); if ( o.fullscreen !== undefined) { if ( o.fullscreen ) { this.element.addClass( "ui-"+ this.role +"-fullscreen" ); $page.addClass( "ui-page-" + this.role + "-fullscreen" ); } // If not fullscreen, add class to page to set top or bottom padding else { this.element.removeClass( "ui-"+ this.role +"-fullscreen" ); $page.removeClass( "ui-page-" + this.role + "-fullscreen" ).addClass( "ui-page-" + this.role+ "-fixed" ); } } } this._super(o); }, _addTransitionClass: function() { var tclass = this.options.transition; if ( tclass && tclass !== "none" ) { // use appropriate slide for header or footer if ( tclass === "slide" ) { tclass = this.element.hasClass( "ui-header" ) ? "slidedown" : "slideup"; } this.element.addClass( tclass ); } }, _bindPageEvents: function() { var page = ( !!this.page )? this.element.closest( ".ui-page" ): this.document; //page event bindings // Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up // This method is meant to disable zoom while a fixed-positioned toolbar page is visible this._on( page , { "pagebeforeshow": "_handlePageBeforeShow", "webkitAnimationStart":"_handleAnimationStart", "animationstart":"_handleAnimationStart", "updatelayout": "_handleAnimationStart", "pageshow": "_handlePageShow", "pagebeforehide": "_handlePageBeforeHide" }); }, _handlePageBeforeShow: function( ) { var o = this.options; if ( o.disablePageZoom ) { $.mobile.zoom.disable( true ); } if ( !o.visibleOnPageShow ) { this.hide( true ); } }, _handleAnimationStart: function() { if ( this.options.updatePagePadding ) { this.updatePagePadding( ( !!this.page )? this.page: ".ui-page-active" ); } }, _handlePageShow: function() { this.updatePagePadding( ( !!this.page )? this.page: ".ui-page-active" ); if ( this.options.updatePagePadding ) { this._on( this.window, { "throttledresize": "updatePagePadding" } ); } }, _handlePageBeforeHide: function( e, ui ) { var o = this.options, thisFooter, thisHeader, nextFooter, nextHeader; if ( o.disablePageZoom ) { $.mobile.zoom.enable( true ); } if ( o.updatePagePadding ) { this._off( this.window, "throttledresize" ); } if ( o.trackPersistentToolbars ) { thisFooter = $( ".ui-footer-fixed:jqmData(id)", this.page ); thisHeader = $( ".ui-header-fixed:jqmData(id)", this.page ); nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ) || $(); nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage ) || $(); if ( nextFooter.length || nextHeader.length ) { nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer ); ui.nextPage.one( "pageshow", function() { nextHeader.prependTo( this ); nextFooter.appendTo( this ); }); } } }, _visible: true, // This will set the content element's top or bottom padding equal to the toolbar's height updatePagePadding: function( tbPage ) { var $el = this.element, header = ( this.role ==="header" ), pos = parseFloat( $el.css( header ? "top" : "bottom" ) ); // This behavior only applies to "fixed", not "fullscreen" if ( this.options.fullscreen ) { return; } // tbPage argument can be a Page object or an event, if coming from throttled resize. tbPage = ( tbPage && tbPage.type === undefined && tbPage ) || this.page || $el.closest( ".ui-page" ); tbPage = ( !!this.page )? this.page: ".ui-page-active"; $( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos ); }, _useTransition: function( notransition ) { var $win = this.window, $el = this.element, scroll = $win.scrollTop(), elHeight = $el.height(), pHeight = ( !!this.page )? $el.closest( ".ui-page" ).height():$(".ui-page-active").height(), viewportHeight = $.mobile.getScreenHeight(); return !notransition && ( this.options.transition && this.options.transition !== "none" && ( ( this.role === "header" && !this.options.fullscreen && scroll > elHeight ) || ( this.role === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight ) ) || this.options.fullscreen ); }, show: function( notransition ) { var hideClass = "ui-fixed-hidden", $el = this.element; if ( this._useTransition( notransition ) ) { $el .removeClass( "out " + hideClass ) .addClass( "in" ) .animationComplete(function () { $el.removeClass( "in" ); }); } else { $el.removeClass( hideClass ); } this._visible = true; }, hide: function( notransition ) { var hideClass = "ui-fixed-hidden", $el = this.element, // if it's a slide transition, our new transitions need the reverse class as well to slide outward outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" ); if ( this._useTransition( notransition ) ) { $el .addClass( outclass ) .removeClass( "in" ) .animationComplete(function() { $el.addClass( hideClass ).removeClass( outclass ); }); } else { $el.addClass( hideClass ).removeClass( outclass ); } this._visible = false; }, toggle: function() { this[ this._visible ? "hide" : "show" ](); }, _bindToggleHandlers: function() { var self = this, o = self.options, delayShow, delayHide, isVisible = true, page = ( !!this.page )? this.page: $(".ui-page"); // tap toggle page .bind( "vclick", function( e ) { if ( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ) { self.toggle(); } }) .bind( "focusin focusout", function( e ) { //this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which //positions fixed toolbars in the middle of the screen on pop if the input is near the top or //bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment //and issue #4113 Header and footer change their position after keyboard popup - iOS //and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment if ( screen.width < 1025 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ) { //Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system //controls causes fixed position, tap-toggle false Header to reveal itself // isVisible instead of self._visible because the focusin and focusout events fire twice at the same time // Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed // by a focusout when a native selects opens and the other way around when it closes. if ( e.type === "focusout" && !isVisible ) { isVisible = true; //wait for the stack to unwind and see if we have jumped to another input clearTimeout( delayHide ); delayShow = setTimeout( function() { self.show(); }, 0 ); } else if ( e.type === "focusin" && !!isVisible ) { //if we have jumped to another input clear the time out to cancel the show. clearTimeout( delayShow ); isVisible = false; delayHide = setTimeout( function() { self.hide(); }, 0 ); } } }); }, _setRelative: function() { if( this.options.position !== "fixed" ){ $( "[data-"+ $.mobile.ns + "role='page']" ).css({ "position": "relative" }); } }, _destroy: function() { var $el = this.element, header = $el.hasClass( "ui-header" ); $el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), "" ); $el.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" ); $el.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" ); } }); })( jQuery ); //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); }); //>>excludeEnd("jqmBuildExclude");
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { return 5; } global.ng.common.locales['mer'] = [ 'mer', [['RŨ', 'ŨG'], u, u], u, [ ['K', 'M', 'W', 'W', 'W', 'W', 'J'], ['KIU', 'MRA', 'WAI', 'WET', 'WEN', 'WTN', 'JUM'], ['Kiumia', 'Muramuko', 'Wairi', 'Wethatu', 'Wena', 'Wetano', 'Jumamosi'], ['KIU', 'MRA', 'WAI', 'WET', 'WEN', 'WTN', 'JUM'] ], u, [ ['J', 'F', 'M', 'Ĩ', 'M', 'N', 'N', 'A', 'S', 'O', 'N', 'D'], ['JAN', 'FEB', 'MAC', 'ĨPU', 'MĨĨ', 'NJU', 'NJR', 'AGA', 'SPT', 'OKT', 'NOV', 'DEC'], [ 'Januarĩ', 'Feburuarĩ', 'Machi', 'Ĩpurũ', 'Mĩĩ', 'Njuni', 'Njuraĩ', 'Agasti', 'Septemba', 'Oktũba', 'Novemba', 'Dicemba' ] ], u, [['MK', 'NK'], u, ['Mbere ya Kristũ', 'Nyuma ya Kristũ']], 0, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'KES', 'Ksh', 'Shilingi ya Kenya', {'JPY': ['JP¥', '¥'], 'KES': ['Ksh'], 'USD': ['US$', '$']}, 'ltr', plural, [] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
var Wallet = require('./index.js') var ethUtil = require('ethereumjs-util') var crypto = require('crypto') var scryptsy = require('scrypt.js') var utf8 = require('utf8') var aesjs = require('aes-js') function assert (val, msg) { if (!val) { throw new Error(msg || 'Assertion failed') } } function decipherBuffer (decipher, data) { return Buffer.concat([ decipher.update(data), decipher.final() ]) } var Thirdparty = {} /* * opts: * - digest - digest algorithm, defaults to md5 * - count - hash iterations * - keysize - desired key size * - ivsize - desired IV size * * Algorithm form https://www.openssl.org/docs/manmaster/crypto/EVP_BytesToKey.html * * FIXME: not optimised at all */ function evp_kdf (data, salt, opts) { // A single EVP iteration, returns `D_i`, where block equlas to `D_(i-1)` function iter (block) { var hash = crypto.createHash(opts.digest || 'md5') hash.update(block) hash.update(data) hash.update(salt) block = hash.digest() for (var i = 1; i < (opts.count || 1); i++) { hash = crypto.createHash(opts.digest || 'md5') hash.update(block) block = hash.digest() } return block } var keysize = opts.keysize || 16 var ivsize = opts.ivsize || 16 var ret = [] var i = 0 while (Buffer.concat(ret).length < (keysize + ivsize)) { ret[i] = iter((i === 0) ? new Buffer(0) : ret[i - 1]) i++ } var tmp = Buffer.concat(ret) return { key: tmp.slice(0, keysize), iv: tmp.slice(keysize, keysize + ivsize) } } // http://stackoverflow.com/questions/25288311/cryptojs-aes-pattern-always-ends-with function decodeCryptojsSalt (input) { var ciphertext = new Buffer(input, 'base64') if (ciphertext.slice(0, 8).toString() === 'Salted__') { return { salt: ciphertext.slice(8, 16), ciphertext: ciphertext.slice(16) } } else { return { ciphertext: ciphertext } } } /* * This wallet format is created by https://github.com/SilentCicero/ethereumjs-accounts * and used on https://www.myetherwallet.com/ */ Thirdparty.fromEtherWallet = function (input, password) { var json = (typeof input === 'object') ? input : JSON.parse(input) var privKey if (!json.locked) { if (json.private.length !== 64) { throw new Error('Invalid private key length') } privKey = new Buffer(json.private, 'hex') } else { if (typeof password !== 'string') { throw new Error('Password required') } if (password.length < 7) { throw new Error('Password must be at least 7 characters') } // the "encrypted" version has the low 4 bytes // of the hash of the address appended var cipher = json.encrypted ? json.private.slice(0, 128) : json.private // decode openssl ciphertext + salt encoding cipher = decodeCryptojsSalt(cipher) if (!cipher.salt) { throw new Error('Unsupported EtherWallet key format') } // derive key/iv using OpenSSL EVP as implemented in CryptoJS var evp = evp_kdf(new Buffer(password), cipher.salt, { keysize: 32, ivsize: 16 }) var decipher = crypto.createDecipheriv('aes-256-cbc', evp.key, evp.iv) privKey = decipherBuffer(decipher, new Buffer(cipher.ciphertext)) // NOTE: yes, they've run it through UTF8 privKey = new Buffer(utf8.decode(privKey.toString()), 'hex') } var wallet = new Wallet(privKey) if (wallet.getAddressString() !== json.address) { throw new Error('Invalid private key or address') } return wallet } Thirdparty.fromEtherCamp = function (passphrase) { return new Wallet(ethUtil.sha3(new Buffer(passphrase))) } Thirdparty.fromKryptoKit = function (entropy, password) { function kryptoKitBrokenScryptSeed (buf) { // js-scrypt calls `new Buffer(String(salt), 'utf8')` on the seed even though it is a buffer // // The `buffer`` implementation used does the below transformation (doesn't matches the current version): // https://github.com/feross/buffer/blob/67c61181b938b17d10dbfc0a545f713b8bd59de8/index.js function decodeUtf8Char (str) { try { return decodeURIComponent(str) } catch (err) { return String.fromCharCode(0xFFFD) // UTF 8 invalid char } } var res = '' var tmp = '' for (var i = 0; i < buf.length; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return new Buffer(res + decodeUtf8Char(tmp)) } if (entropy[0] === '#') { entropy = entropy.slice(1) } var type = entropy[0] entropy = entropy.slice(1) var privKey if (type === 'd') { privKey = ethUtil.sha256(entropy) } else if (type === 'q') { if (typeof password !== 'string') { throw new Error('Password required') } var encryptedSeed = ethUtil.sha256(new Buffer(entropy.slice(0, 30))) var checksum = entropy.slice(30, 46) var salt = kryptoKitBrokenScryptSeed(encryptedSeed) var aesKey = scryptsy(new Buffer(password, 'utf8'), salt, 16384, 8, 1, 32) /* FIXME: try to use `crypto` instead of `aesjs` // NOTE: ECB doesn't use the IV, so it can be anything var decipher = crypto.createDecipheriv("aes-256-ecb", aesKey, new Buffer(0)) // FIXME: this is a clear abuse, but seems to match how ECB in aesjs works privKey = Buffer.concat([ decipher.update(encryptedSeed).slice(0, 16), decipher.update(encryptedSeed).slice(0, 16), ]) */ /* eslint-disable new-cap */ var decipher = new aesjs.ModeOfOperation.ecb(aesKey) /* eslint-enable new-cap */ privKey = Buffer.concat([ decipher.decrypt(encryptedSeed.slice(0, 16)), decipher.decrypt(encryptedSeed.slice(16, 32)) ]) if (checksum.length > 0) { if (checksum !== ethUtil.sha256(ethUtil.sha256(privKey)).slice(0, 8).toString('hex')) { throw new Error('Failed to decrypt input - possibly invalid passphrase') } } } else { throw new Error('Unsupported or invalid entropy type') } return new Wallet(privKey) } Thirdparty.fromQuorumWallet = function (passphrase, userid) { assert(passphrase.length >= 10) assert(userid.length >= 10) var seed = passphrase + userid seed = crypto.pbkdf2Sync(seed, seed, 2000, 32, 'sha256') return new Wallet(seed) } module.exports = Thirdparty
(function() { 'use strict'; Modernizr.addTest('ios', /iPad|iPhone|iPod/.test(window.navigator.userAgent)); Modernizr.addTest('android', /Android/i.test(window.navigator.userAgent)); Modernizr.addTest('winphone', /IEMobile/i.test(window.navigator.userAgent)); Modernizr.addTest('mobile', /iPad|iPhone|iPod|Android|IEMobile/.test(window.navigator.userAgent)); Modernizr.addTest('ff', /Firefox/.test(window.navigator.userAgent)); Modernizr.addTest('ie', /; MSIE/.test(window.navigator.userAgent)); Modernizr.addTest('chrome', /\bChrome\b/.test(window.navigator.userAgent)); Modernizr.addTest('safari', /\bSafari\b/.test(window.navigator.userAgent) && !/\bChrome\b/.test(window.navigator.userAgent)); })();
x=function (t) { return t };
/* * Copyright (c) 2013 - present Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice 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. * */ define(function (require, exports, module) { "use strict"; var Async = require("utils/Async"), CommandManager = require("command/CommandManager"), Commands = require("command/Commands"), Dialogs = require("widgets/Dialogs"), DefaultDialogs = require("widgets/DefaultDialogs"), MainViewManager = require("view/MainViewManager"), FileSystem = require("filesystem/FileSystem"), FileUtils = require("file/FileUtils"), ProjectManager = require("project/ProjectManager"), Strings = require("strings"), StringUtils = require("utils/StringUtils"); /** * Returns true if the drag and drop items contains valid drop objects. * @param {Array.<DataTransferItem>} items Array of items being dragged * @return {boolean} True if one or more items can be dropped. */ function isValidDrop(items) { var i, len = items.length; for (i = 0; i < len; i++) { if (items[i].kind === "file") { var entry = items[i].webkitGetAsEntry(); if (entry.isFile) { // If any files are being dropped, this is a valid drop return true; } else if (len === 1) { // If exactly one folder is being dropped, this is a valid drop return true; } } } // No valid entries found return false; } /** * Determines if the event contains a type list that has a URI-list. * If it does and contains an empty file list, then what is being dropped is a URL. * If that is true then we stop the event propagation and default behavior to save Brackets editor from the browser taking over. * @param {Array.<File>} files Array of File objects from the event datastructure. URLs are the only drop item that would contain a URI-list. * @param {event} event The event datastucture containing datatransfer information about the drag/drop event. Contains a type list which may or may not hold a URI-list depending on what was dragged/dropped. Interested if it does. */ function stopURIListPropagation(files, event) { var types = event.dataTransfer.types; if ((!files || !files.length) && types) { // We only want to check if a string of text was dragged into the editor types.forEach(function (value) { //Dragging text externally (dragging text from another file): types has "text/plain" and "text/html" //Dragging text internally (dragging text to another line): types has just "text/plain" //Dragging a file: types has "Files" //Dragging a url: types has "text/plain" and "text/uri-list" <-what we are interested in if (value === "text/uri-list") { event.stopPropagation(); event.preventDefault(); return; } }); } } /** * Open dropped files * @param {Array.<string>} files Array of files dropped on the application. * @return {Promise} Promise that is resolved if all files are opened, or rejected * if there was an error. */ function openDroppedFiles(paths) { var errorFiles = [], ERR_MULTIPLE_ITEMS_WITH_DIR = {}; return Async.doInParallel(paths, function (path, idx) { var result = new $.Deferred(); // Only open files. FileSystem.resolve(path, function (err, item) { if (!err && item.isFile) { // If the file is already open, and this isn't the last // file in the list, return. If this *is* the last file, // always open it so it gets selected. if (idx < paths.length - 1) { if (MainViewManager.findInWorkingSet(MainViewManager.ALL_PANES, path) !== -1) { result.resolve(); return; } } CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN, {fullPath: path, silent: true}) .done(function () { result.resolve(); }) .fail(function (openErr) { errorFiles.push({path: path, error: openErr}); result.reject(); }); } else if (!err && item.isDirectory && paths.length === 1) { // One folder was dropped, open it. ProjectManager.openProject(path) .done(function () { result.resolve(); }) .fail(function () { // User was already notified of the error. result.reject(); }); } else { errorFiles.push({path: path, error: err || ERR_MULTIPLE_ITEMS_WITH_DIR}); result.reject(); } }); return result.promise(); }, false) .fail(function () { function errorToString(err) { if (err === ERR_MULTIPLE_ITEMS_WITH_DIR) { return Strings.ERROR_MIXED_DRAGDROP; } else { return FileUtils.getFileErrorString(err); } } if (errorFiles.length > 0) { var message = Strings.ERROR_OPENING_FILES; message += "<ul class='dialog-list'>"; errorFiles.forEach(function (info) { message += "<li><span class='dialog-filename'>" + StringUtils.breakableUrl(ProjectManager.makeProjectRelativeIfPossible(info.path)) + "</span> - " + errorToString(info.error) + "</li>"; }); message += "</ul>"; Dialogs.showModalDialog( DefaultDialogs.DIALOG_ID_ERROR, Strings.ERROR_OPENING_FILE_TITLE, message ); } }); } /** * Attaches global drag & drop handlers to this window. This enables dropping files/folders to open them, and also * protects the Brackets app from being replaced by the browser trying to load the dropped file in its place. */ function attachHandlers() { function handleDragOver(event) { event = event.originalEvent || event; var files = event.dataTransfer.files; stopURIListPropagation(files, event); if (files && files.length) { event.stopPropagation(); event.preventDefault(); var dropEffect = "none"; // Don't allow drag-and-drop of files/folders when a modal dialog is showing. if ($(".modal.instance").length === 0 && isValidDrop(event.dataTransfer.items)) { dropEffect = "copy"; } event.dataTransfer.dropEffect = dropEffect; } } function handleDrop(event) { event = event.originalEvent || event; var files = event.dataTransfer.files; stopURIListPropagation(files, event); if (files && files.length) { event.stopPropagation(); event.preventDefault(); brackets.app.getDroppedFiles(function (err, paths) { if (!err) { openDroppedFiles(paths); } }); } } // For most of the window, only respond if nothing more specific in the UI has already grabbed the event (e.g. // the Extension Manager drop-to-install zone, or an extension with a drop-to-upload zone in its panel) $(window.document.body) .on("dragover", handleDragOver) .on("drop", handleDrop); // Over CodeMirror specifically, always pre-empt CodeMirror's drag event handling if files are being dragged - CM stops // propagation on any drag event it sees, even when it's not a text drag/drop. But allow CM to handle all non-file drag // events. See bug #10617. window.document.body.addEventListener("dragover", function (event) { if ($(event.target).closest(".CodeMirror").length) { handleDragOver(event); } }, true); window.document.body.addEventListener("drop", function (event) { if ($(event.target).closest(".CodeMirror").length) { handleDrop(event); } }, true); } CommandManager.register(Strings.CMD_OPEN_DROPPED_FILES, Commands.FILE_OPEN_DROPPED_FILES, openDroppedFiles); // Export public API exports.attachHandlers = attachHandlers; exports.isValidDrop = isValidDrop; exports.openDroppedFiles = openDroppedFiles; });
(function(e,l){function s(a){return a.id&&e('label[for="'+a.id+'"]').val()||a.name}function A(a,b,c){c||(c=0);b.each(function(){var b=e(this),g=this,k=this.nodeName.toLowerCase(),f,j;"label"==k&&b.find("input, textarea, select").length&&(f=b.text(),b=b.children().first(),g=b.get(0),k=g.nodeName.toLowerCase());switch(k){case "menu":j={name:b.attr("label"),items:{}};c=A(j.items,b.children(),c);break;case "a":case "button":j={name:b.text(),disabled:!!b.attr("disabled"),callback:function(){b.click()}}; break;case "menuitem":case "command":switch(b.attr("type")){case l:case "command":case "menuitem":j={name:b.attr("label"),disabled:!!b.attr("disabled"),callback:function(){b.click()}};break;case "checkbox":j={type:"checkbox",disabled:!!b.attr("disabled"),name:b.attr("label"),selected:!!b.attr("checked")};break;case "radio":j={type:"radio",disabled:!!b.attr("disabled"),name:b.attr("label"),radio:b.attr("radiogroup"),value:b.attr("id"),selected:!!b.attr("checked")};break;default:j=l}break;case "hr":j= "-------";break;case "input":switch(b.attr("type")){case "text":j={type:"text",name:f||s(g),disabled:!!b.attr("disabled"),value:b.val()};break;case "checkbox":j={type:"checkbox",name:f||s(g),disabled:!!b.attr("disabled"),selected:!!b.attr("checked")};break;case "radio":j={type:"radio",name:f||s(g),disabled:!!b.attr("disabled"),radio:!!b.attr("name"),value:b.val(),selected:!!b.attr("checked")};break;default:j=l}break;case "select":j={type:"select",name:f||s(g),disabled:!!b.attr("disabled"),selected:b.val(), options:{}};b.children().each(function(){j.options[this.value]=e(this).text()});break;case "textarea":j={type:"textarea",name:f||s(g),disabled:!!b.attr("disabled"),value:b.val()};break;case "label":break;default:j={type:"html",html:b.clone(!0)}}j&&(c++,a["key"+c]=j)});return c}e.support.htmlMenuitem="HTMLMenuItemElement"in window;e.support.htmlCommand="HTMLCommandElement"in window;e.support.eventSelectstart="onselectstart"in document.documentElement;var h=null,u=!1,m=e(window),v=0,p={},r={},w={}, x={selector:null,appendTo:null,trigger:"right",autoHide:!1,delay:200,determinePosition:function(a){if(e.ui&&e.ui.position)a.css("display","block").position({my:"center top",at:"center bottom",of:this,offset:"0 5",collision:"fit"}).css("display","none");else{var b=this.offset();b.top+=this.outerHeight();b.left+=this.outerWidth()/2-a.outerWidth()/2;a.css(b)}},position:function(a,b,c){if(!b&&!c)a.determinePosition.call(this,a.$menu);else{"maintain"===b&&"maintain"===c?b=a.$menu.position():(a.$trigger.parents().andSelf().filter(function(){return"fixed"== e(this).css("position")}).length&&(c-=m.scrollTop(),b-=m.scrollLeft()),b={top:c,left:b});c=m.scrollTop()+m.height();var d=m.scrollLeft()+m.width(),g=a.$menu.height(),k=a.$menu.width();b.top+g>c&&(b.top-=g);b.left+k>d&&(b.left-=k);a.$menu.css(b)}},positionSubmenu:function(a){if(e.ui&&e.ui.position)a.css("display","block").position({my:"left top",at:"right top",of:this,collision:"fit"}).css("display","");else{var b={top:0,left:this.outerWidth()};a.css(b)}},zIndex:1,animation:{duration:50,show:"slideDown", hide:"slideUp"},events:{show:e.noop,hide:e.noop},callback:null,items:{}},t=null,y=null,z=null,B,f={abortevent:function(a){a.preventDefault();a.stopImmediatePropagation()},contextmenu:function(a){var b=e(this);a.preventDefault();a.stopImmediatePropagation();if(!("right"!=a.data.trigger&&a.originalEvent)&&!b.hasClass("context-menu-disabled")){h=b;if(a.data.build){var c=a.data.build(h,a);if(!1===c)return;a.data=e.extend(!0,{},x,a.data,c||{});if(!a.data.items||e.isEmptyObject(a.data.items))throw window.console&& (console.error||console.log)("No items specified to show in contextMenu"),Error("No Items sepcified");a.data.$trigger=h;q.create(a.data)}q.show.call(b,a.data,a.pageX,a.pageY)}},click:function(a){a.preventDefault();a.stopImmediatePropagation();e(this).trigger(e.Event("contextmenu",{data:a.data,pageX:a.pageX,pageY:a.pageY}))},mousedown:function(a){var b=e(this);h&&(h.length&&!h.is(b))&&h.data("contextMenu").$menu.trigger("contextmenu:hide");2==a.button&&(h=b.data("contextMenuActive",!0))},mouseup:function(a){var b= e(this);b.data("contextMenuActive")&&(h&&h.length&&h.is(b)&&!b.hasClass("context-menu-disabled"))&&(a.preventDefault(),a.stopImmediatePropagation(),h=b,b.trigger(e.Event("contextmenu",{data:a.data,pageX:a.pageX,pageY:a.pageY})));b.removeData("contextMenuActive")},mouseenter:function(a){var b=e(this),c=e(a.relatedTarget),d=e(document);if(!c.is(".context-menu-list")&&!c.closest(".context-menu-list").length&&(!h||!h.length))y=a.pageX,z=a.pageY,B=a.data,d.on("mousemove.contextMenuShow",f.mousemove),t= setTimeout(function(){t=null;d.off("mousemove.contextMenuShow");h=b;b.trigger(e.Event("contextmenu",{data:B,pageX:y,pageY:z}))},a.data.delay)},mousemove:function(a){y=a.pageX;z=a.pageY},mouseleave:function(a){a=e(a.relatedTarget);if(!a.is(".context-menu-list")&&!a.closest(".context-menu-list").length){try{clearTimeout(t)}catch(b){}t=null}},layerClick:function(a){var b=e(this),c=b.data("contextMenuRoot"),d=!1,g=a.button,k=a.pageX,f=a.pageY,j,h,l;a.preventDefault();a.stopImmediatePropagation();b.on("mouseup", function(){d=!0});setTimeout(function(){var n;if("left"==c.trigger&&0==g||"right"==c.trigger&&2==g)if(document.elementFromPoint){c.$layer.hide();j=document.elementFromPoint(k-m.scrollLeft(),f-m.scrollTop());c.$layer.show();l=[];for(n in p)l.push(n);j=e(j).closest(l.join(", "));if(j.length&&j.is(c.$trigger[0])){c.position.call(c.$trigger,c,k,f);return}}else if(h=c.$trigger.offset(),n=e(window),h.top+=n.scrollTop(),h.top<=a.pageY&&(h.left+=n.scrollLeft(),h.left<=a.pageX&&(h.bottom=h.top+c.$trigger.outerHeight(), h.bottom>=a.pageY&&(h.right=h.left+c.$trigger.outerWidth(),h.right>=a.pageX)))){c.position.call(c.$trigger,c,k,f);return}n=function(a){a&&(a.preventDefault(),a.stopImmediatePropagation());c.$menu.trigger("contextmenu:hide");j&&j.length&&setTimeout(function(){j.contextMenu({x:k,y:f})},50)};if(d)n();else b.on("mouseup",n)},50)},keyStop:function(a,b){b.isInput||a.preventDefault();a.stopPropagation()},key:function(a){var b=h.data("contextMenu")||{};b.$menu.children();switch(a.keyCode){case 9:case 38:if(f.keyStop(a, b),b.isInput){if(9==a.keyCode&&a.shiftKey){a.preventDefault();b.$selected&&b.$selected.find("input, textarea, select").blur();b.$menu.trigger("prevcommand");return}if(38==a.keyCode&&"checkbox"==b.$selected.find("input, textarea, select").prop("type")){a.preventDefault();return}}else if(9!=a.keyCode||a.shiftKey){b.$menu.trigger("prevcommand");return}case 40:f.keyStop(a,b);if(b.isInput){if(9==a.keyCode){a.preventDefault();b.$selected&&b.$selected.find("input, textarea, select").blur();b.$menu.trigger("nextcommand"); return}if(40==a.keyCode&&"checkbox"==b.$selected.find("input, textarea, select").prop("type")){a.preventDefault();return}}else{b.$menu.trigger("nextcommand");return}break;case 37:f.keyStop(a,b);if(b.isInput||!b.$selected||!b.$selected.length)break;if(!b.$selected.parent().hasClass("context-menu-root")){a=b.$selected.parent().parent();b.$selected.trigger("contextmenu:blur");b.$selected=a;return}break;case 39:f.keyStop(a,b);if(b.isInput||!b.$selected||!b.$selected.length)break;var c=b.$selected.data("contextMenu")|| {};if(c.$menu&&b.$selected.hasClass("context-menu-submenu")){b.$selected=null;c.$selected=null;c.$menu.trigger("nextcommand");return}break;case 35:case 36:if(!b.$selected||!b.$selected.find("input, textarea, select").length)(b.$selected&&b.$selected.parent()||b.$menu).children(":not(.disabled, .not-selectable)")[36==a.keyCode?"first":"last"]().trigger("contextmenu:focus"),a.preventDefault();return;case 13:f.keyStop(a,b);if(b.isInput){if(b.$selected&&!b.$selected.is("textarea, select")){a.preventDefault(); return}break}b.$selected&&b.$selected.trigger("mouseup");return;case 32:case 33:case 34:f.keyStop(a,b);return;case 27:f.keyStop(a,b);b.$menu.trigger("contextmenu:hide");return;default:if(c=String.fromCharCode(a.keyCode).toUpperCase(),b.accesskeys[c]){b.accesskeys[c].$node.trigger(b.accesskeys[c].$menu?"contextmenu:focus":"mouseup");return}}a.stopPropagation();b.$selected&&b.$selected.trigger(a)},prevItem:function(a){a.stopPropagation();var b=e(this).data("contextMenu")||{};if(b.$selected){var c=b.$selected, b=b.$selected.parent().data("contextMenu")||{};b.$selected=c}for(var c=b.$menu.children(),d=!b.$selected||!b.$selected.prev().length?c.last():b.$selected.prev(),g=d;d.hasClass("disabled")||d.hasClass("not-selectable");)if(d=d.prev().length?d.prev():c.last(),d.is(g))return;b.$selected&&f.itemMouseleave.call(b.$selected.get(0),a);f.itemMouseenter.call(d.get(0),a);a=d.find("input, textarea, select");a.length&&a.focus()},nextItem:function(a){a.stopPropagation();var b=e(this).data("contextMenu")||{};if(b.$selected){var c= b.$selected,b=b.$selected.parent().data("contextMenu")||{};b.$selected=c}for(var c=b.$menu.children(),d=!b.$selected||!b.$selected.next().length?c.first():b.$selected.next(),g=d;d.hasClass("disabled")||d.hasClass("not-selectable");)if(d=d.next().length?d.next():c.first(),d.is(g))return;b.$selected&&f.itemMouseleave.call(b.$selected.get(0),a);f.itemMouseenter.call(d.get(0),a);a=d.find("input, textarea, select");a.length&&a.focus()},focusInput:function(){var a=e(this).closest(".context-menu-item"), b=a.data(),c=b.contextMenu,b=b.contextMenuRoot;b.$selected=c.$selected=a;b.isInput=c.isInput=!0},blurInput:function(){var a=e(this).closest(".context-menu-item").data();a.contextMenuRoot.isInput=a.contextMenu.isInput=!1},menuMouseenter:function(){e(this).data().contextMenuRoot.hovering=!0},menuMouseleave:function(a){var b=e(this).data().contextMenuRoot;b.$layer&&b.$layer.is(a.relatedTarget)&&(b.hovering=!1)},itemMouseenter:function(a){var b=e(this),c=b.data(),d=c.contextMenu,c=c.contextMenuRoot;c.hovering= !0;a&&(c.$layer&&c.$layer.is(a.relatedTarget))&&(a.preventDefault(),a.stopImmediatePropagation());(d.$menu?d:c).$menu.children(".hover").trigger("contextmenu:blur");b.hasClass("disabled")||b.hasClass("not-selectable")?d.$selected=null:b.trigger("contextmenu:focus")},itemMouseleave:function(a){var b=e(this),c=b.data(),d=c.contextMenu,c=c.contextMenuRoot;c!==d&&c.$layer&&c.$layer.is(a.relatedTarget)?(c.$selected&&c.$selected.trigger("contextmenu:blur"),a.preventDefault(),a.stopImmediatePropagation(), c.$selected=d.$selected=d.$node):b.trigger("contextmenu:blur")},itemClick:function(a){var b=e(this),c=b.data(),d=c.contextMenuRoot,g=c.contextMenuKey;if(c.contextMenu.items[g]&&!b.hasClass("disabled")&&!b.hasClass("context-menu-submenu")){a.preventDefault();a.stopImmediatePropagation();if(e.isFunction(d.callbacks[g]))a=d.callbacks[g];else if(e.isFunction(d.callback))a=d.callback;else return;!1!==a.call(d.$trigger,g,d)?d.$menu.trigger("contextmenu:hide"):d.$menu.parent().length&&q.update.call(d.$trigger, d)}},inputClick:function(a){a.stopImmediatePropagation()},hideMenu:function(a,b){var c=e(this).data("contextMenuRoot");q.hide.call(c.$trigger,c,b&&b.force)},focusItem:function(a){a.stopPropagation();a=e(this);var b=a.data(),c=b.contextMenu,b=b.contextMenuRoot;a.addClass("hover").siblings(".hover").trigger("contextmenu:blur");c.$selected=b.$selected=a;c.$node&&b.positionSubmenu.call(c.$node,c.$menu)},blurItem:function(a){a.stopPropagation();a=e(this);var b=a.data().contextMenu;a.removeClass("hover"); b.$selected=null}},q={show:function(a,b,c){var d=e(this),g={};e("#context-menu-layer").trigger("mousedown");a.$trigger=d;if(!1===a.events.show.call(d,a))h=null;else{q.update.call(d,a);a.position.call(d,a,b,c);if(a.zIndex){b=0;for(c=d;!(b=Math.max(b,parseInt(c.css("z-index"),10)||0),c=c.parent(),!c||!c.length||-1<"html body".indexOf(c.prop("nodeName").toLowerCase())););g.zIndex=b+a.zIndex}q.layer.call(a.$menu,a,g.zIndex);a.$menu.find("ul").css("zIndex",g.zIndex+1);a.$menu.css(g)[a.animation.show](a.animation.duration); d.data("contextMenu",a);e(document).off("keydown.contextMenu").on("keydown.contextMenu",f.key);if(a.autoHide){var k=d.position();k.right=k.left+d.outerWidth();k.bottom=k.top+this.outerHeight();e(document).on("mousemove.contextMenuAutoHide",function(b){a.$layer&&(!a.hovering&&(!(b.pageX>=k.left&&b.pageX<=k.right)||!(b.pageY>=k.top&&b.pageY<=k.bottom)))&&a.$menu.trigger("contextmenu:hide")})}}},hide:function(a,b){var c=e(this);a||(a=c.data("contextMenu")||{});if(b||!(a.events&&!1===a.events.hide.call(c, a))){if(a.$layer){var d=a.$layer;setTimeout(function(){d.remove()},10);try{delete a.$layer}catch(g){a.$layer=null}}h=null;a.$menu.find(".hover").trigger("contextmenu:blur");a.$selected=null;e(document).off(".contextMenuAutoHide").off("keydown.contextMenu");a.$menu&&a.$menu[a.animation.hide](a.animation.duration,function(){a.build&&(a.$menu.remove(),e.each(a,function(b){switch(b){case "ns":case "selector":case "build":case "trigger":return!0;default:a[b]=l;try{delete a[b]}catch(c){}return!0}}))})}}, create:function(a,b){b===l&&(b=a);a.$menu=e('<ul class="context-menu-list '+(a.className||"")+'"></ul>').data({contextMenu:a,contextMenuRoot:b});e.each(["callbacks","commands","inputs"],function(c,d){a[d]={};b[d]||(b[d]={})});b.accesskeys||(b.accesskeys={});e.each(a.items,function(c,d){var g=e('<li class="context-menu-item '+(d.className||"")+'"></li>'),k=null,h=null;d.$node=g.data({contextMenu:a,contextMenuRoot:b,contextMenuKey:c});if(d.accesskey){for(var j=d.accesskey.split(/\s+/),l=[],m=0,n;n= j[m];m++)n=n[0].toUpperCase(),l.push(n);for(j=0;m=l[j];j++)if(!b.accesskeys[m]){b.accesskeys[m]=d;d._name=d.name.replace(RegExp("("+m+")","i"),'<span class="context-menu-accesskey">$1</span>');break}}if("string"==typeof d)g.addClass("context-menu-separator not-selectable");else if(d.type&&w[d.type])w[d.type].call(g,d,a,b),e.each([a,b],function(b,a){a.commands[c]=d;e.isFunction(d.callback)&&(a.callbacks[c]=d.callback)});else{"html"==d.type?g.addClass("context-menu-html not-selectable"):d.type?(k=e("<label></label>").appendTo(g), e("<span></span>").html(d._name||d.name).appendTo(k),g.addClass("context-menu-input"),a.hasTypes=!0,e.each([a,b],function(a,b){b.commands[c]=d;b.inputs[c]=d})):d.items&&(d.type="sub");switch(d.type){case "text":h=e('<input type="text" value="1" name="context-menu-input-'+c+'" value="">').val(d.value||"").appendTo(k);break;case "textarea":h=e('<textarea name="context-menu-input-'+c+'"></textarea>').val(d.value||"").appendTo(k);d.height&&h.height(d.height);break;case "checkbox":h=e('<input type="checkbox" value="1" name="context-menu-input-'+ c+'" value="">').val(d.value||"").prop("checked",!!d.selected).prependTo(k);break;case "radio":h=e('<input type="radio" value="1" name="context-menu-input-'+d.radio+'" value="">').val(d.value||"").prop("checked",!!d.selected).prependTo(k);break;case "select":h=e('<select name="context-menu-input-'+c+'">').appendTo(k);d.options&&(e.each(d.options,function(b,a){e("<option></option>").val(b).text(a).appendTo(h)}),h.val(d.selected));break;case "sub":e("<span></span>").html(d._name||d.name).appendTo(g); d.appendTo=d.$node;q.create(d,b);g.data("contextMenu",d).addClass("context-menu-submenu");d.callback=null;break;case "html":e(d.html).appendTo(g);break;default:e.each([a,b],function(b,a){a.commands[c]=d;e.isFunction(d.callback)&&(a.callbacks[c]=d.callback)}),e("<span></span>").html(d._name||d.name||"").appendTo(g)}if(d.type&&("sub"!=d.type&&"html"!=d.type)&&(h.on("focus",f.focusInput).on("blur",f.blurInput),d.events))h.on(d.events,a);d.icon&&g.addClass("icon icon-"+d.icon)}d.$input=h;d.$label=k;g.appendTo(a.$menu); if(!a.hasTypes&&e.support.eventSelectstart)g.on("selectstart.disableTextSelect",f.abortevent)});a.$node||a.$menu.css("display","none").addClass("context-menu-root");a.$menu.appendTo(a.appendTo||document.body)},update:function(a,b){var c=this;b===l&&(b=a,a.$menu.find("ul").andSelf().css({position:"static",display:"block"}).each(function(){var a=e(this);a.width(a.css("position","absolute").width()).css("position","static")}).css({position:"",display:""}));a.$menu.children().each(function(){var d=e(this), g=d.data("contextMenuKey"),f=a.items[g],g=e.isFunction(f.disabled)&&f.disabled.call(c,g,b)||!0===f.disabled;d[g?"addClass":"removeClass"]("disabled");if(f.type)switch(d.find("input, select, textarea").prop("disabled",g),f.type){case "text":case "textarea":f.$input.val(f.value||"");break;case "checkbox":case "radio":f.$input.val(f.value||"").prop("checked",!!f.selected);break;case "select":f.$input.val(f.selected||"")}f.$menu&&q.update.call(c,f,b)})},layer:function(a,b){var c=a.$layer=e('<div id="context-menu-layer" style="position:fixed; z-index:'+ b+'; top:0; left:0; opacity: 0; filter: alpha(opacity=0); background-color: #000;"></div>').css({height:m.height(),width:m.width(),display:"block"}).data("contextMenuRoot",a).insertBefore(this).on("contextmenu",f.abortevent).on("mousedown",f.layerClick);e.support.fixedPosition||c.css({position:"absolute",height:e(document).height()});return c}};e.fn.contextMenu=function(a){a===l?this.first().trigger("contextmenu"):a.x&&a.y?this.first().trigger(e.Event("contextmenu",{pageX:a.x,pageY:a.y})):"hide"=== a?(a=this.data("contextMenu").$menu)&&a.trigger("contextmenu:hide"):a?this.removeClass("context-menu-disabled"):a||this.addClass("context-menu-disabled");return this};e.contextMenu=function(a,b){"string"!=typeof a&&(b=a,a="create");"string"==typeof b?b={selector:b}:b===l&&(b={});var c=e.extend(!0,{},x,b||{}),d=e(document);switch(a){case "create":if(!c.selector)throw Error("No selector specified");if(c.selector.match(/.context-menu-(list|item|input)($|\s)/))throw Error('Cannot bind to selector "'+ c.selector+'" as it contains a reserved className');if(!c.build&&(!c.items||e.isEmptyObject(c.items)))throw Error("No Items sepcified");v++;c.ns=".contextMenu"+v;p[c.selector]=c.ns;r[c.ns]=c;c.trigger||(c.trigger="right");u||(d.on({"contextmenu:hide.contextMenu":f.hideMenu,"prevcommand.contextMenu":f.prevItem,"nextcommand.contextMenu":f.nextItem,"contextmenu.contextMenu":f.abortevent,"mouseenter.contextMenu":f.menuMouseenter,"mouseleave.contextMenu":f.menuMouseleave},".context-menu-list").on("mouseup.contextMenu", ".context-menu-input",f.inputClick).on({"mouseup.contextMenu":f.itemClick,"contextmenu:focus.contextMenu":f.focusItem,"contextmenu:blur.contextMenu":f.blurItem,"contextmenu.contextMenu":f.abortevent,"mouseenter.contextMenu":f.itemMouseenter,"mouseleave.contextMenu":f.itemMouseleave},".context-menu-item"),u=!0);d.on("contextmenu"+c.ns,c.selector,c,f.contextmenu);switch(c.trigger){case "hover":d.on("mouseenter"+c.ns,c.selector,c,f.mouseenter).on("mouseleave"+c.ns,c.selector,c,f.mouseleave);break;case "left":d.on("click"+ c.ns,c.selector,c,f.click)}c.build||q.create(c);break;case "destroy":if(c.selector){if(p[c.selector]){var g=e(".context-menu-list").filter(":visible");g.length&&g.data().contextMenuRoot.$trigger.is(c.selector)&&g.trigger("contextmenu:hide",{force:!0});try{r[p[c.selector]].$menu&&r[p[c.selector]].$menu.remove(),delete r[p[c.selector]]}catch(h){r[p[c.selector]]=null}d.off(p[c.selector])}}else d.off(".contextMenu .contextMenuAutoHide"),e.each(p,function(a,b){d.off(b)}),p={},r={},v=0,u=!1,e("#context-menu-layer, .context-menu-list").remove(); break;case "html5":(!e.support.htmlCommand&&!e.support.htmlMenuitem||"boolean"==typeof b&&b)&&e('menu[type="context"]').each(function(){this.id&&e.contextMenu({selector:"[contextmenu="+this.id+"]",items:e.contextMenu.fromMenu(this)})}).css("display","none");break;default:throw Error('Unknown operation "'+a+'"');}return this};e.contextMenu.setInputValues=function(a,b){b===l&&(b={});e.each(a.inputs,function(a,d){switch(d.type){case "text":case "textarea":d.value=b[a]||"";break;case "checkbox":d.selected= b[a]?!0:!1;break;case "radio":d.selected=(b[d.radio]||"")==d.value?!0:!1;break;case "select":d.selected=b[a]||""}})};e.contextMenu.getInputValues=function(a,b){b===l&&(b={});e.each(a.inputs,function(a,d){switch(d.type){case "text":case "textarea":case "select":b[a]=d.$input.val();break;case "checkbox":b[a]=d.$input.prop("checked");break;case "radio":d.$input.prop("checked")&&(b[d.radio]=d.value)}});return b};e.contextMenu.fromMenu=function(a){a=e(a);var b={};A(b,a.children());return b};e.contextMenu.defaults= x;e.contextMenu.types=w})(jQuery);
/*! * jQuery QueryBuilder 2.4.1 * Locale: Portuguese (pt-PT) * Author: Miguel Guerreiro, migas.csi@gmail.com * Licensed under MIT (http://opensource.org/licenses/MIT) */ (function(root, factory) { if (typeof define == 'function' && define.amd) { define(['jquery', 'query-builder'], factory); } else { factory(root.jQuery); } }(this, function($) { "use strict"; var QueryBuilder = $.fn.queryBuilder; QueryBuilder.regional['pt-PT'] = { "__locale": "Portuguese (pt-PT)", "__author": "Miguel Guerreiro, migas.csi@gmail.com", "add_rule": "Nova Regra", "add_group": "Novo Grupo", "delete_rule": "Excluir", "delete_group": "Excluir", "conditions": { "AND": "E", "OR": "OU" }, "operators": { "equal": "Igual a", "not_equal": "Diferente de", "in": "Contido", "not_in": "Não contido", "less": "Menor que", "less_or_equal": "Menor ou igual a", "greater": "Maior que", "greater_or_equal": "Maior ou igual que", "between": "Entre", "begins_with": "Começar por", "not_begins_with": "Não a começar por", "contains": "Contém", "not_contains": "Não contém", "ends_with": "Terminando com", "not_ends_with": "Terminando sem", "is_empty": "É vazio", "is_not_empty": "Não é vazio", "is_null": "É nulo", "is_not_null": "Não é nulo" }, "errors": { "no_filter": "Nenhum filtro selecionado", "empty_group": "O grupo está vazio", "radio_empty": "Nenhum valor selecionado", "checkbox_empty": "Nenhum valor selecionado", "select_empty": "Nenhum valor selecionado", "string_empty": "Valor vazio", "string_exceed_min_length": "É necessário conter pelo menos {0} caracteres", "string_exceed_max_length": "É necessário conter mais de {0} caracteres", "string_invalid_format": "Formato inválido ({0})", "number_nan": "Não é um número", "number_not_integer": "Não é um número inteiro", "number_not_double": "Não é um número real", "number_exceed_min": "É necessário ser maior que {0}", "number_exceed_max": "É necessário ser menor que {0}", "number_wrong_step": "É necessário ser múltiplo de {0}", "datetime_invalid": "Formato de data inválido ({0})", "datetime_exceed_min": "É necessário ser superior a {0}", "datetime_exceed_max": "É necessário ser inferior a {0}" } }; QueryBuilder.defaults({ lang_code: 'pt-PT' }); }));
module.exports={A:{A:{"2":"H D G E A B mB"},B:{"1":"N I J q","2":"C K f L"},C:{"1":"0 1 2 3 4 5 6 8 t u v w x y z EB MB DB BB FB HB IB JB KB LB","2":"jB NB F O H D G E A B C K f L N I J P Q R S T U V W X Y Z a b c d e AB g h i j k l m n o p M r s dB cB"},D:{"1":"0 1 2 3 4 5 6 8 v w x y z EB MB DB BB FB HB IB JB KB LB bB WB q SB QB rB TB UB","2":"F O H D G E A B C K f L N I J P Q R S T U V W X Y Z a b c d e AB g h i j k l m n o p M r s t u"},E:{"1":"7 9 A B C K OB eB","2":"F O H D G E VB PB XB YB ZB aB"},F:{"1":"0 1 2 3 4 5 6 i j k l m n o p M r s t u v w x y z","2":"7 9 E B C L N I J P Q R S T U V W X Y Z a b c d e AB g h fB gB hB iB GB kB"},G:{"1":"tB uB vB wB xB yB zB 0B 1B","2":"G PB lB CB nB oB pB qB RB sB"},H:{"2":"2B"},I:{"1":"q","2":"NB F 3B 4B 5B 6B CB 7B 8B"},J:{"2":"D A"},K:{"1":"M","2":"7 9 A B C GB"},L:{"1":"QB"},M:{"1":"8"},N:{"2":"A B"},O:{"1":"9B"},P:{"1":"AC BC CC DC EC OB","2":"F"},Q:{"2":"FC"},R:{"2":"GC"},S:{"2":"HC"}},B:1,C:"Passive event listeners"};
'use strict'; (function() { // Tweets Controller Spec describe('Tweets Controller Tests', function() { // Initialize global variables var TweetsController, scope, $httpBackend, $stateParams, $location; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function() { jasmine.addMatchers({ toEqualData: function(util, customEqualityTesters) { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { // Set a new global scope scope = $rootScope.$new(); // Point global variables to injected services $stateParams = _$stateParams_; $httpBackend = _$httpBackend_; $location = _$location_; // Initialize the Tweets controller. TweetsController = $controller('TweetsController', { $scope: scope }); })); it('$scope.find() should create an array with at least one Tweet object fetched from XHR', inject(function(Tweets) { // Create sample Tweet using the Tweets service var sampleTweet = new Tweets({ name: 'New Tweet' }); // Create a sample Tweets array that includes the new Tweet var sampleTweets = [sampleTweet]; // Set GET response $httpBackend.expectGET('tweets').respond(sampleTweets); // Run controller functionality scope.find(); $httpBackend.flush(); // Test scope value expect(scope.tweets).toEqualData(sampleTweets); })); it('$scope.findOne() should create an array with one Tweet object fetched from XHR using a tweetId URL parameter', inject(function(Tweets) { // Define a sample Tweet object var sampleTweet = new Tweets({ name: 'New Tweet' }); // Set the URL parameter $stateParams.tweetId = '525a8422f6d0f87f0e407a33'; // Set GET response $httpBackend.expectGET(/tweets\/([0-9a-fA-F]{24})$/).respond(sampleTweet); // Run controller functionality scope.findOne(); $httpBackend.flush(); // Test scope value expect(scope.tweet).toEqualData(sampleTweet); })); it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Tweets) { // Create a sample Tweet object var sampleTweetPostData = new Tweets({ name: 'New Tweet' }); // Create a sample Tweet response var sampleTweetResponse = new Tweets({ _id: '525cf20451979dea2c000001', name: 'New Tweet' }); // Fixture mock form input values scope.name = 'New Tweet'; // Set POST response $httpBackend.expectPOST('tweets', sampleTweetPostData).respond(sampleTweetResponse); // Run controller functionality scope.create(); $httpBackend.flush(); // Test form inputs are reset expect(scope.name).toEqual(''); // Test URL redirection after the Tweet was created expect($location.path()).toBe('/tweets/' + sampleTweetResponse._id); })); it('$scope.update() should update a valid Tweet', inject(function(Tweets) { // Define a sample Tweet put data var sampleTweetPutData = new Tweets({ _id: '525cf20451979dea2c000001', name: 'New Tweet' }); // Mock Tweet in scope scope.tweet = sampleTweetPutData; // Set PUT response $httpBackend.expectPUT(/tweets\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality scope.update(); $httpBackend.flush(); // Test URL location to new object expect($location.path()).toBe('/tweets/' + sampleTweetPutData._id); })); it('$scope.remove() should send a DELETE request with a valid tweetId and remove the Tweet from the scope', inject(function(Tweets) { // Create new Tweet object var sampleTweet = new Tweets({ _id: '525a8422f6d0f87f0e407a33' }); // Create new Tweets array and include the Tweet scope.tweets = [sampleTweet]; // Set expected DELETE response $httpBackend.expectDELETE(/tweets\/([0-9a-fA-F]{24})$/).respond(204); // Run controller functionality scope.remove(sampleTweet); $httpBackend.flush(); // Test array after successful delete expect(scope.tweets.length).toBe(0); })); }); }());
var path = require('path'); var fs = require('fs'); var express = require('express'); var expstate = require('express-state'); var browserify = require('browserify'); var im = require('istanbul-middleware'); var watchify = require('watchify'); var assign = require('lodash').assign; var humanizeDuration = require('humanize-duration'); var debug = require('debug')('zuul:control-app'); var defaultBuilder = '../lib/builder-browserify'; module.exports = function(config) { var files = config.files; var ui = config.ui; var framework_dir = config.framework_dir; var prj_dir = config.prj_dir; var opt = { debug: true }; // watchify options // https://github.com/substack/watchify#var-w--watchifyb-opts opt = assign(opt, { cache: {}, packageCache: {}, fullPaths: true }); files = files.map(function(file) { return path.resolve(file); }); var user_html = ''; if (config.html) { user_html = fs.readFileSync(path.join(prj_dir, config.html), 'utf-8'); } var build; // default builder is browserify which we provide config.builder = config.builder || defaultBuilder; build = require(config.builder)(files, config); var app = express(); expstate.extend(app); app.set('state namespace', 'zuul'); app.expose(ui, 'ui'); app.expose(config.name, 'title'); app.set('views', __dirname + '/../frameworks'); app.set('view engine', 'html'); app.engine('html', require('hbs').__express); app.use(function(req, res, next) { res.locals.title = config.name; res.locals.user_scripts = config.scripts || []; res.locals.user_html = user_html; next(); }); app.use(app.router); var bundle_router = new express.Router(); app.use(bundle_router.middleware); // zuul files app.use('/__zuul', express.static(__dirname + '/../frameworks')); // framework files app.use('/__zuul', express.static(framework_dir)); // any user's files app.use(express.static(process.cwd())); if (config.coverage && config.local) { // coverage endpoint app.use('/__zuul/coverage', im.createHandler()); } app.get('/__zuul', function(req, res) { res.locals.config = { port: config.support_port }; res.render('index'); }); var map = undefined; var clientBundler = browserify(opt); clientBundler.require(path.join(framework_dir, '/client.js'), { entry: true }); // we use watchify to speed up `.bundle()` calls clientBundler = watchify(clientBundler); bundle_router.get('/__zuul/client.js', function(req, res, next) { res.contentType('application/javascript'); var start = Date.now(); clientBundler.bundle(function(err, buf) { if (err) { return next(err); } debug('zuul client took %s to bundle', humanizeDuration(Date.now() - start)); res.send(buf.toString()); }); }); bundle_router.get('/__zuul/test-bundle.map.json', function(req, res, next) { if (!map) { return res.status(404).send(''); } res.json(map); }); bundle_router.get('/__zuul/test-bundle.js', function(req, res, next) { res.contentType('application/javascript'); build(function(err, src, srcmap) { if (err) { return next(err); } if (srcmap) { map = srcmap; map.file = '/__zuul/test-bundle.js'; src += '//# sourceMappingURL=' + '/__zuul/test-bundle.map.json'; } res.send(src); }); }); return app; };
/* * Backstretch * http://srobbin.com/jquery-plugins/backstretch/ * * Copyright (c) 2013 Scott Robbin * Licensed under the MIT license. */ ;(function ($, window, undefined) { 'use strict'; /* PLUGIN DEFINITION * ========================= */ $.fn.backstretch = function (images, options) { /* * Scroll the page one pixel to get the right window height on iOS * Pretty harmless for everyone else */ if ($(window).scrollTop() === 0 ) { window.scrollTo(0, 0); } return this.each(function () { var $this = $(this) , obj = $this.data('backstretch'); // Do we already have an instance attached to this element? if (obj) { // Is this a method they're trying to execute? if (typeof images === 'string' && typeof obj[images] === 'function') { // Call the method obj[images](options); // No need to do anything further return; } // Merge the old options with the new options = $.extend(obj.options, options); // Remove the old instance if ( obj.hasOwnProperty('destroy') ) { obj.destroy(true); } } // We need at least one image if (!images || (images && images.length === 0)) { var cssBackgroundImage = $this.css('background-image'); if (cssBackgroundImage && cssBackgroundImage !== 'none') { images = [$this.css('backgroundImage').replace(/url\(|\)|"|'/g,"")]; } else { $.error('No images were supplied for Backstretch, or element must have a CSS-defined background image.'); } } obj = new Backstretch(this, images, options || {}); $this.data('backstretch', obj); }); }; // If no element is supplied, we'll attach to body $.backstretch = function (images, options) { // Return the instance return $('body') .backstretch(images, options) .data('backstretch'); }; // Custom selector $.expr[':'].backstretch = function(elem) { return $(elem).data('backstretch') !== undefined; }; /* DEFAULTS * ========================= */ $.fn.backstretch.defaults = { centeredX: true // Should we center the image on the X axis? , centeredY: true // Should we center the image on the Y axis? , duration: 5000 // Amount of time in between slides (if slideshow) , fade: 0 // Speed of fade transition between slides , fadeFirst: true // Fade in the first image of slideshow? , alignX: "auto" // When used it takes precedence over ceteredX , alignY: "auto" // When used it takes precedence over ceteredY , paused: false // Whether the images should slide after given duration , start: 0 // Index of the first image to show , preload: 2 // How many images preload at a time? , preloadSize: 1 // How many images can we preload in parallel? }; /* STYLES * * Baked-in styles that we'll apply to our elements. * In an effort to keep the plugin simple, these are not exposed as options. * That said, anyone can override these in their own stylesheet. * ========================= */ var styles = { wrap: { left: 0 , top: 0 , overflow: 'hidden' , margin: 0 , padding: 0 , height: '100%' , width: '100%' , zIndex: -999999 } , img: { position: 'absolute' , display: 'none' , margin: 0 , padding: 0 , border: 'none' , width: 'auto' , height: 'auto' , maxWidth: 'none' , zIndex: -999999 } }; /* Given an array of different options for an image, * choose the optimal image for the container size. * * Given an image template (a string with {{ width }} and/or * {{height}} inside) and a container object, returns the * image url with the exact values for the size of that * container. * * Returns an array of urls optimized for the specified resolution. * */ var optimalSizeImages = (function () { /* Sorts the array of image sizes based on width */ var widthInsertSort = function (arr) { for (var i = 1; i < arr.length; i++) { var tmp = arr[i], j = i; while (arr[j - 1] && parseInt(arr[j - 1].width, 10) > parseInt(tmp.width, 10)) { arr[j] = arr[j - 1]; --j; } arr[j] = tmp; } return arr; }; /* Given an array of various sizes of the same image and a container width, * return the best image. */ var selectBest = function (containerWidth, imageSizes) { // stop when the width is larger var j = 0; while (j < imageSizes.length && imageSizes[j].width < containerWidth) { j++; } // Use the image located at where we stopped return imageSizes[j - 1].url; }; return function ($container, images) { var containerWidth = $container.width(), containerHeight = $container.height(); var chosenImages = []; var templateReplacer = function (match, key) { if (key === 'width') { return containerWidth; } if (key === 'height') { return containerHeight; } return match; }; for (var i = 0; i < images.length; i++) { if ($.isArray(images[0])) { images[i] = widthInsertSort(images[i]); var chosen = selectBest(containerWidth, images[i]); chosenImages.push(chosen); } else { var url = images[i].replace(/{{(width|height)}}/g, templateReplacer); chosenImages.push(url); } } return chosenImages; }; })(); /* Preload images */ var preload = (function (sources, startAt, count, batchSize, callback) { // Plugin cache var cache = []; // Wrapper for cache var caching = function(image){ for (var i = 0; i < cache.length; i++) { if (cache[i].src === image.src) { return cache[i]; } } cache.push(image); return image; }; // Execute callback var exec = function(sources, callback, last){ if (typeof callback === 'function') { callback.call(sources, last); } }; // Closure to hide cache return function preload (sources, startAt, count, batchSize, callback){ // Check input data if (typeof sources === 'undefined') { return; } if (typeof sources === 'string') { sources = [sources]; } if (arguments.length < 5 && typeof arguments[arguments.length - 1] === 'function') { callback = arguments[arguments.length - 1]; } startAt = (typeof startAt === 'function' || !startAt) ? 0 : startAt; count = (typeof count === 'function' || !count || count < 0) ? sources.length : Math.min(count, sources.length); batchSize = (typeof batchSize === 'function' || !batchSize) ? 1 : batchSize; if (startAt >= sources.length) { startAt = 0; count = 0; } if (batchSize < 0) { batchSize = count; } batchSize = Math.min(batchSize, count); var next = sources.slice(startAt + batchSize, count - batchSize); sources = sources.slice(startAt, batchSize); count = sources.length; // If sources array is empty if (!count) { exec(sources, callback, true); return; } // Image loading callback var countLoaded = 0; var loaded = function() { countLoaded++; if (countLoaded !== count) { return; } exec(sources, callback, !next); preload(next, 0, 0, batchSize, callback); }; // Loop sources to preload var image; for (var i = 0; i < sources.length; i++) { image = new Image(); image.src = sources[i]; image = caching(image); if (image.complete) { loaded(); } else { $(image).on('load error', loaded); } } }; })(); /* CLASS DEFINITION * ========================= */ var Backstretch = function (container, images, options) { this.options = $.extend({}, $.fn.backstretch.defaults, options || {}); this.firstShow = true; // set the centeredX/Y properties based on alignX/Y options if they're provided this.options.centeredX = this.options.alignX !== 'auto' ? this.options.alignX === 'center' : this.options.centeredX; this.options.centeredY = this.options.alignY !== 'auto' ? this.options.alignY === 'center' : this.options.centeredY; /* In its simplest form, we allow Backstretch to be called on an image path. * e.g. $.backstretch('/path/to/image.jpg') * So, we need to turn this back into an array. */ this.images = $.isArray(images) ? images : [images]; /** * Paused-Option */ if (this.options.paused) { this.paused = true; } /** * Start-Option (Index) */ if (this.options.start >= this.images.length) { this.options.start = this.images.length - 1; } if (this.options.start < 0) { this.options.start = 0; } // Convenience reference to know if the container is body. this.isBody = container === document.body; /* We're keeping track of a few different elements * * Container: the element that Backstretch was called on. * Wrap: a DIV that we place the image into, so we can hide the overflow. * Root: Convenience reference to help calculate the correct height. */ this.$container = $(container); this.$root = this.isBody ? supportsFixedPosition ? $(window) : $(document) : this.$container; this.originalImages = this.images; this.images = optimalSizeImages(this.$root, this.originalImages); /** * Pre-Loading. * This is the first image, so we will preload a minimum of 1 images. */ preload(this.images, this.options.start || 0, this.options.preload || 1); // Don't create a new wrap if one already exists (from a previous instance of Backstretch) var $existing = this.$container.children(".backstretch").first(); this.$wrap = $existing.length ? $existing : $('<div class="backstretch"></div>').css(styles.wrap).appendTo(this.$container); // Non-body elements need some style adjustments if (!this.isBody) { // If the container is statically positioned, we need to make it relative, // and if no zIndex is defined, we should set it to zero. var position = this.$container.css('position') , zIndex = this.$container.css('zIndex'); this.$container.css({ position: position === 'static' ? 'relative' : position , zIndex: zIndex === 'auto' ? 0 : zIndex , background: 'none' }); // Needs a higher z-index this.$wrap.css({zIndex: -999998}); } // Fixed or absolute positioning? this.$wrap.css({ position: this.isBody && supportsFixedPosition ? 'fixed' : 'absolute' }); // Set the first image this.index = this.options.start; this.show(this.index); // Listen for resize $(window).on('resize.backstretch', $.proxy(this.resize, this)) .on('orientationchange.backstretch', $.proxy(function () { // Need to do this in order to get the right window height if (this.isBody && window.pageYOffset === 0) { window.scrollTo(0, 1); this.resize(); } }, this)); }; /* PUBLIC METHODS * ========================= */ Backstretch.prototype = { resize: function () { try { // Check for a better suited image after the resize var newContainerWidth = this.$root.width(); var newContainerHeight = this.$root.height(); var changeRatioW = newContainerWidth / (this._lastResizeContainerWidth || 0); var changeRatioH = newContainerHeight / (this._lastResizeContainerHeight || 0); // check for big changes in container size if (changeRatioW < 0.9 || changeRatioW > 1.1 || isNaN(changeRatioW) || changeRatioH < 0.9 || changeRatioH > 1.1 || isNaN(changeRatioH)) { this._lastResizeContainerWidth = newContainerWidth; this._lastResizeContainerHeight = newContainerHeight; // Big change: rebuild the entire images array this.images = optimalSizeImages(this.$root, this.originalImages); // Preload them (they will be automatically inserted on the next cycle) if (this.options.preload) { preload(this.images, (this.index + 1) % this.images.length, this.options.preload); } // In case there is no cycle and the new source is different than the current if (this.images.length === 1 && this._currentImageSrc !== this.images[0]) { // Wait a little an update the image being showed var that = this; clearTimeout(that._selectAnotherResolutionTimeout); that._selectAnotherResolutionTimeout = setTimeout(function () { that.show(0); }, 2500); } } var bgCSS = {left: 0, top: 0, right: 'auto', bottom: 'auto'} , rootWidth = this.isBody ? this.$root.width() : this.$root.innerWidth() , bgWidth = rootWidth , rootHeight = this.isBody ? ( window.innerHeight ? window.innerHeight : this.$root.height() ) : this.$root.innerHeight() , bgHeight = bgWidth / this.$img.data('ratio') , evt = $.Event('backstretch.resize', {               relatedTarget: this.$container[0]             }) , bgOffset; // Make adjustments based on image ratio if (bgHeight >= rootHeight) { bgOffset = (bgHeight - rootHeight) / 2; if(this.options.centeredY) { bgCSS.top = '-' + bgOffset + 'px'; } else if (this.options.alignY === 'bottom') { bgCSS.top = 'auto'; bgCSS.bottom = 0; } } else { bgHeight = rootHeight; bgWidth = bgHeight * this.$img.data('ratio'); bgOffset = (bgWidth - rootWidth) / 2; if(this.options.centeredX) { bgCSS.left = '-' + bgOffset + 'px'; } else if (this.options.alignX === 'right') { bgCSS.left = 'auto'; bgCSS.right = 0; } } this.$wrap.css({width: rootWidth, height: rootHeight}) .find('img:not(.deleteable)').css({width: bgWidth, height: bgHeight}).css(bgCSS); this.$container.trigger(evt, this); } catch(err) { // IE7 seems to trigger resize before the image is loaded. // This try/catch block is a hack to let it fail gracefully. } return this; } // Show the slide at a certain position , show: function (newIndex) { // Validate index if (Math.abs(newIndex) > this.images.length - 1) { return; } // Vars var self = this , oldImage = self.$wrap.find('img').addClass('deleteable') , evtOptions = { relatedTarget: self.$container[0] }; // Trigger the "before" event self.$container.trigger($.Event('backstretch.before', evtOptions), [self, newIndex]); // Set the new index this.index = newIndex; // Pause the slideshow clearTimeout(self._cycleTimeout); // New image self.$img = $('<img />') .css(styles.img) .bind('load', function (e) { var imgWidth = this.width || $(e.target).width() , imgHeight = this.height || $(e.target).height(); // Save the ratio $(this).data('ratio', imgWidth / imgHeight); // Show the image, then delete the old one // "speed" option has been deprecated, but we want backwards compatibilty var bringInNextImage = function () { oldImage.remove(); // Resume the slideshow if (!self.paused && this.images.length > 1) { self.cycle(); } // Trigger the "after" and "show" events // "show" is being deprecated $(['after', 'show']).each(function () { self.$container.trigger($.Event('backstretch.' + this, evtOptions), [self, newIndex]); }); }; if (this.firstShow && !this.options.fadeFirstImage) { // Avoid fade-in on first show bringInNextImage(); } else { // Any other show, fade-in! $(this).fadeIn(self.options.speed || self.options.fade, bringInNextImage); } this.firstShow = false; // Resize self.resize(); }) .appendTo(self.$wrap); // Hack for IE img onload event self.$img.attr('src', self.images[newIndex]); self._currentImageSrc = self.images[newIndex]; return self; } , next: function () { // Next slide return this.show(this.index < this.images.length - 1 ? this.index + 1 : 0); } , prev: function () { // Previous slide return this.show(this.index === 0 ? this.images.length - 1 : this.index - 1); } , pause: function () { // Pause the slideshow this.paused = true; return this; } , resume: function () { // Resume the slideshow this.paused = false; this.cycle(); return this; } , cycle: function () { // Start/resume the slideshow if(this.images.length > 1) { // Clear the timeout, just in case clearTimeout(this._cycleTimeout); this._cycleTimeout = setTimeout($.proxy(function () { // Check for paused slideshow if (!this.paused) { this.next(); } }, this), this.options.duration); } return this; } , destroy: function (preserveBackground) { // Stop the resize events $(window).off('resize.backstretch orientationchange.backstretch'); // Clear the timeout clearTimeout(this._cycleTimeout); // Remove Backstretch if(!preserveBackground) { this.$wrap.remove(); } this.$container.removeData('backstretch'); } }; /* SUPPORTS FIXED POSITION? * * Based on code from jQuery Mobile 1.1.0 * http://jquerymobile.com/ * * In a nutshell, we need to figure out if fixed positioning is supported. * Unfortunately, this is very difficult to do on iOS, and usually involves * injecting content, scrolling the page, etc.. It's ugly. * jQuery Mobile uses this workaround. It's not ideal, but works. * * Modified to detect IE6 * ========================= */ var supportsFixedPosition = (function () { var ua = navigator.userAgent , platform = navigator.platform // Rendering engine is Webkit, and capture major version , wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ) , wkversion = !!wkmatch && wkmatch[ 1 ] , ffmatch = ua.match( /Fennec\/([0-9]+)/ ) , ffversion = !!ffmatch && ffmatch[ 1 ] , operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ) , omversion = !!operammobilematch && operammobilematch[ 1 ] , iematch = ua.match( /MSIE ([0-9]+)/ ) , ieversion = !!iematch && iematch[ 1 ]; return !( // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5) ((platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534) || // Opera Mini (window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]") || (operammobilematch && omversion < 7458) || //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2) (ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533) || // Firefox Mobile before 6.0 - (ffversion && ffversion < 6) || // WebOS less than 3 ("palmGetResource" in window && wkversion && wkversion < 534) || // MeeGo (ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1) || // IE6 (ieversion && ieversion <= 6) ); }()); }(jQuery, window));