code
stringlengths
2
1.05M
var assert = require('assert'); var jsan = require('../'); describe('jsan', function() { describe('has a stringify method', function() { it('behaves the same as JSON.stringify for simple jsonable objects', function() { var obj = { a: 1, b: 'string', c: [2,3], d: null }; assert.equal(JSON.stringify(obj), jsan.stringify(obj)); }); it('uses the toJSON() method when possible', function() { var obj = { a: { b: 1, toJSON: function(key) { return key } } }; assert.equal(jsan.stringify(obj, null, null, false), '{"a":"a"}'); }); it('can handle dates', function() { var obj = { now: new Date() } var str = jsan.stringify(obj, null, null, true); assert(/^\{"now":\{"\$jsan":"d[^"]*"\}\}$/.test(str)); }); it('can handle regexes', function() { var obj = { r: /test/ } var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"r":{"$jsan":"r,test"}}'); }); it('can handle functions', function() { var obj = { f: function() {} } var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"f":{"$jsan":"ffunction () { /* ... */ }"}}'); }); it('can handle undefined', function() { var obj = undefined; var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"$jsan":"u"}'); }); it('can handle NaN', function() { var obj = NaN; var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"$jsan":"n"}'); }); it('can handle Infinity', function() { var obj = Infinity; var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"$jsan":"i"}'); }); it('can handle -Infinity', function() { var obj = -Infinity; var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"$jsan":"y"}'); }); it('can handle nested undefined', function() { var obj = { u: undefined } var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"u":{"$jsan":"u"}}'); }); it('can handle nested NaN', function() { var obj = { u: NaN } var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"u":{"$jsan":"n"}}'); }); it('can handle nested Infinity', function() { var obj = { u: Infinity } var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"u":{"$jsan":"i"}}'); }); it('can handle nested -Infinity', function() { var obj = { u: -Infinity } var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"u":{"$jsan":"y"}}'); }); it('can handle errors', function() { var obj = { e: new Error(':(') } var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"e":{"$jsan":"e:("}}'); }); if (typeof Symbol !== 'undefined') { it('can handle ES symbols', function() { var obj = { s: Symbol('a') } var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"s":{"$jsan":"sa"}}'); }); it('can handle global ES symbols', function() { var obj = { g: Symbol.for('a') } var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"g":{"$jsan":"ga"}}'); }); } if (typeof Map !== 'undefined' && typeof Array.from !== 'undefined') { it('can handle ES Map', function() { var obj = { map: new Map([ ['a', 1], [{toString: function(){ return 'a' }}, 2], [{}, 3] ]) } var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"map":{"$jsan":"m[[\\"a\\",1],[{\\"toString\\":{\\"$jsan\\":\\"ffunction (){ /* ... */ }\\"}},2],[{},3]]"}}'); }); } if (typeof Set !== 'undefined' && typeof Array.from !== 'undefined') { it('can handle ES Set', function() { var obj = { set: new Set(['a', {toString: function(){ return 'a' }}, {}]) } var str = jsan.stringify(obj, null, null, true); assert.deepEqual(str, '{"set":{"$jsan":"l[\\"a\\",{\\"toString\\":{\\"$jsan\\":\\"ffunction (){ /* ... */ }\\"}},{}]"}}'); }); } it('works on objects with circular references', function() { var obj = {}; obj['self'] = obj; assert.equal(jsan.stringify(obj), '{"self":{"$jsan":"$"}}'); }); it('can use the circular option', function() { var obj = {}; obj.self = obj; obj.a = 1; obj.b = {}; obj.c = obj.b; assert.equal(jsan.stringify(obj, null, null, {circular: '∞'}), '{"self":"∞","a":1,"b":{},"c":{"$jsan":"$.b"}}'); assert.equal(jsan.stringify(obj, null, null, {circular: function() { return '∞!' }}), '{"self":"∞!","a":1,"b":{},"c":{"$jsan":"$.b"}}'); }); it('works on objects with "[", "\'", and "]" in the keys', function() { var obj = {}; obj['["key"]'] = {}; obj['["key"]']['["key"]'] = obj['["key"]']; assert.equal(jsan.stringify(obj), '{"[\\"key\\"]":{"[\\"key\\"]":{"$jsan":"$[\\"[\\\\\\"key\\\\\\"]\\"]"}}}'); }); it('works on objects that will get encoded with \\uXXXX', function() { var obj = {"\u017d\u010d":{},"kraj":"\u017du\u017e"}; obj["\u017d\u010d"]["\u017d\u010d"] = obj["\u017d\u010d"]; assert.equal(jsan.stringify(obj), '{"\u017d\u010d":{"\u017d\u010d":{"$jsan":"$[\\\"\u017d\u010d\\\"]"}},"kraj":"Žuž"}'); }); it('works on circular arrays', function() { var obj = []; obj[0] = []; obj[0][0] = obj[0]; assert.equal(jsan.stringify(obj), '[[{"$jsan":"$[0]"}]]'); }); it('works correctly for mutiple calls with the same object', function() { var obj = {}; obj.self = obj; obj.a = {}; obj.b = obj.a; assert.equal(jsan.stringify(obj), '{"self":{"$jsan":"$"},"a":{},"b":{"$jsan":"$.a"}}'); assert.equal(jsan.stringify(obj), '{"self":{"$jsan":"$"},"a":{},"b":{"$jsan":"$.a"}}'); }); }); describe('has a parse method', function() { it('behaves the same as JSON.parse for valid json strings', function() { var str = '{"a":1,"b":"string","c":[2,3],"d":null}'; assert.deepEqual(JSON.parse(str), jsan.parse(str)); }); it('can decode dates', function() { var str = '{"$jsan":"d1400000000000"}'; var obj = jsan.parse(str); assert(obj instanceof Date); }); it('can decode regexes', function() { str = '{"$jsan":"r,test"}'; var obj = jsan.parse(str); assert(obj instanceof RegExp ) }); it('can decode functions', function() { str = '{"$jsan":"ffunction () { /* ... */ }"}'; var obj = jsan.parse(str); assert(obj instanceof Function); }); it('can decode undefined', function() { str = '{"$jsan":"u"}'; var obj = jsan.parse(str); assert(obj === undefined); }); it('can decode NaN', function() { str = '{"$jsan":"n"}'; var obj = jsan.parse(str); assert(isNaN(obj) && typeof obj === 'number'); }); it('can decode Infinity', function() { str = '{"$jsan":"i"}'; var obj = jsan.parse(str); assert(obj === Number.POSITIVE_INFINITY); }); it('can decode -Infinity', function() { str = '{"$jsan":"y"}'; var obj = jsan.parse(str); assert(obj === Number.NEGATIVE_INFINITY); }); it('can decode errors', function() { str = '{"$jsan":"e:("}'; var obj = jsan.parse(str); assert(obj instanceof Error && obj.message === ':('); }); it('can decode nested dates', function() { var str = '{"now":{"$jsan":"d1400000000000"}}'; var obj = jsan.parse(str); assert(obj.now instanceof Date); }); it('can decode nested regexes', function() { str = '{"r":{"$jsan":"r,test"}}'; var obj = jsan.parse(str); assert(obj.r instanceof RegExp ) }); it('can decode nested functions', function() { str = '{"f":{"$jsan":"ffunction () { /* ... */ }"}}'; var obj = jsan.parse(str); assert(obj.f instanceof Function); }); it('can decode nested undefined', function() { str = '{"u":{"$jsan":"u"}}'; var obj = jsan.parse(str); assert('u' in obj && obj.u === undefined); }); it('can decode nested NaN', function() { str = '{"u":{"$jsan":"n"}}'; var obj = jsan.parse(str); assert('u' in obj && isNaN(obj.u) && typeof obj.u === 'number'); }); it('can decode nested Infinity', function() { str = '{"u":{"$jsan":"i"}}'; var obj = jsan.parse(str); assert('u' in obj && obj.u === Number.POSITIVE_INFINITY); }); it('can decode nested -Infinity', function() { str = '{"u":{"$jsan":"y"}}'; var obj = jsan.parse(str); assert('u' in obj && obj.u === Number.NEGATIVE_INFINITY); }); it('can decode nested errors', function() { str = '{"e":{"$jsan":"e:("}}'; var obj = jsan.parse(str); assert(obj.e instanceof Error && obj.e.message === ':('); }); if (typeof Symbol !== 'undefined') { it('can decode ES symbols', function() { str = '{"s1":{"$jsan":"sfoo"}, "s2":{"$jsan":"s"}}'; var obj = jsan.parse(str); assert(typeof obj.s1 === 'symbol' && obj.s1.toString() === 'Symbol(foo)'); assert(typeof obj.s2 === 'symbol' && obj.s2.toString() === 'Symbol()'); }); it('can decode global ES symbols', function() { str = '{"g1":{"$jsan":"gfoo"}, "g2":{"$jsan":"gundefined"}}'; var obj = jsan.parse(str); assert(typeof obj.g1 === 'symbol' && obj.g1 === Symbol.for('foo')); assert(typeof obj.g2 === 'symbol' && obj.g2 === Symbol.for()); }); } if (typeof Map !== 'undefined' && typeof Array.from !== 'undefined') { it('can decode ES Map', function() { var str = '{"map":{"$jsan":"m[[\\"a\\",1],[{\\"toString\\":{\\"$jsan\\":\\"ffunction (){ /* ... */ }\\"}},2],[{},3]]"}}'; var obj = jsan.parse(str); var keys = obj.map.keys(); var values = obj.map.values(); assert.equal(keys.next().value, 'a'); assert.equal(typeof keys.next().value.toString, 'function'); assert.equal(typeof keys.next().value, 'object'); assert.equal(values.next().value, 1); assert.equal(values.next().value, 2); assert.equal(values.next().value, 3); }); } if (typeof Set !== 'undefined' && typeof Array.from !== 'undefined') { it('can decode ES Set', function() { var str = '{"set":{"$jsan":"l[\\"a\\",{\\"toString\\":{\\"$jsan\\":\\"ffunction (){ /* ... */ }\\"}},{}]"}}'; var obj = jsan.parse(str); var values = obj.set.values(); assert.equal(values.next().value, 'a'); assert.equal(typeof values.next().value.toString, 'function'); assert.equal(typeof values.next().value, 'object'); }); } it('works on object strings with a circular dereferences', function() { var str = '{"a":1,"b":"string","c":[2,3],"d":null,"self":{"$jsan":"$"}}'; var obj = jsan.parse(str); assert.deepEqual(obj['self'], obj); }); it('works on object strings with "[", "\'", and "]" in the keys', function() { var str = '{"[\\"key\\"]":{"[\\"key\\"]":{"$jsan":"$[\\"[\\\\\\"key\\\\\\"]\\"]"}}}'; var obj = jsan.parse(str); assert.deepEqual(obj['["key"]']['["key"]'], obj['["key"]']); }); it('works on objects encoded with \\uXXXX', function() { var str = '{"\u017d\u010d":{"\u017d\u010d":{"$jsan":"$[\\\"\\u017d\\u010d\\\"]"}},"kraj":"Žuž"}'; var obj = jsan.parse(str); assert.deepEqual(obj["\u017d\u010d"]["\u017d\u010d"], obj["\u017d\u010d"]); }); it('works on array strings with circular dereferences', function() { var str = '[[{"$jsan":"$[0]"}]]'; var arr = jsan.parse(str); assert.deepEqual(arr[0][0], arr[0]); }); }); });
/* jshint expr:true */ import { expect } from 'chai'; import { describeComponent, it } from 'ember-mocha'; import hbs from 'htmlbars-inline-precompile'; import Ember from 'ember'; import Pretender from 'pretender'; import wait from 'ember-test-helpers/wait'; const {run} = Ember; const stubSuccessfulUpload = function (server, delay = 0) { server.post('/ghost/api/v0.1/uploads/', function () { return [200, {'Content-Type': 'application/json'}, '"/content/images/test.png"']; }, delay); }; const stubFailedUpload = function (server, code, error, delay = 0) { server.post('/ghost/api/v0.1/uploads/', function () { return [code, {'Content-Type': 'application/json'}, JSON.stringify({ errors: [{ errorType: error, message: `Error: ${error}` }] })]; }, delay); }; describeComponent( 'gh-file-uploader', 'Integration: Component: gh-file-uploader', { integration: true }, function() { let server; beforeEach(function () { server = new Pretender(); }); afterEach(function () { server.shutdown(); }); it('renders', function() { this.render(hbs`{{gh-file-uploader}}`); expect(this.$('label').text().trim(), 'default label') .to.equal('Select or drag-and-drop a file'); }); it('renders form with supplied label text', function () { this.set('labelText', 'My label'); this.render(hbs`{{gh-file-uploader labelText=labelText}}`); expect(this.$('label').text().trim(), 'label') .to.equal('My label'); }); it('generates request to supplied endpoint', function (done) { stubSuccessfulUpload(server); this.set('uploadUrl', '/ghost/api/v0.1/uploads/'); this.render(hbs`{{gh-file-uploader url=uploadUrl}}`); this.$('input[type="file"]').trigger('change'); wait().then(() => { expect(server.handledRequests.length).to.equal(1); expect(server.handledRequests[0].url).to.equal('/ghost/api/v0.1/uploads/'); done(); }); }); it('handles drag over/leave', function () { this.render(hbs`{{gh-file-uploader}}`); run(() => { let dragover = Ember.$.Event('dragover', { dataTransfer: { files: [] } }); this.$('.gh-image-uploader').trigger(dragover); }); expect(this.$('.gh-image-uploader').hasClass('--drag-over'), 'has drag-over class').to.be.true; run(() => { this.$('.gh-image-uploader').trigger('dragleave'); }); expect(this.$('.gh-image-uploader').hasClass('--drag-over'), 'has drag-over class').to.be.false; }); } );
module.exports={A:{A:{"2":"gB","8":"K D G","129":"E A B"},B:{"1":"H I","129":"1 C d J M"},C:{"1":"0 1 2 3 5 6 7 8 9 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z GB AB CB DB","8":"dB EB XB WB"},D:{"1":"0 1 2 3 5 6 7 8 9 D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z GB AB CB DB QB iB KB IB LB MB NB OB","8":"F N K"},E:{"1":"4 E A B C UB VB p YB","8":"F N PB HB","129":"K D G RB SB TB"},F:{"1":"0 4 5 C J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z eB","2":"B cB p BB","8":"E ZB aB bB"},G:{"1":"lB mB nB oB pB qB rB sB","8":"HB fB FB","129":"G hB JB jB kB"},H:{"1":"tB"},I:{"1":"3 yB zB","2":"uB vB wB","129":"EB F xB FB"},J:{"1":"A","129":"D"},K:{"1":"4 C L","8":"A B p BB"},L:{"1":"IB"},M:{"1":"2"},N:{"129":"A B"},O:{"1":"0B"},P:{"1":"F 1B 2B 3B 4B"},Q:{"1":"5B"},R:{"1":"6B"}},B:1,C:"Inline SVG in HTML5"};
/* YUI 3.8.0pr2 (build 154) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('yql', function (Y, NAME) { /** * This class adds a sugar class to allow access to YQL (http://developer.yahoo.com/yql/). * @module yql */ /** * Utility Class used under the hood my the YQL class * @class YQLRequest * @constructor * @param {String} sql The SQL statement to execute * @param {Function/Object} callback The callback to execute after the query (Falls through to JSONP). * @param {Object} params An object literal of extra parameters to pass along (optional). * @param {Object} opts An object literal of configuration options (optional): proto (http|https), base (url) */ var YQLRequest = function (sql, callback, params, opts) { if (!params) { params = {}; } params.q = sql; //Allow format override.. JSON-P-X if (!params.format) { params.format = Y.YQLRequest.FORMAT; } if (!params.env) { params.env = Y.YQLRequest.ENV; } this._context = this; if (opts && opts.context) { this._context = opts.context; delete opts.context; } if (params && params.context) { this._context = params.context; delete params.context; } this._params = params; this._opts = opts; this._callback = callback; }; YQLRequest.prototype = { /** * @private * @property _jsonp * @description Reference to the JSONP instance used to make the queries */ _jsonp: null, /** * @private * @property _opts * @description Holder for the opts argument */ _opts: null, /** * @private * @property _callback * @description Holder for the callback argument */ _callback: null, /** * @private * @property _params * @description Holder for the params argument */ _params: null, /** * @private * @property _context * @description The context to execute the callback in */ _context: null, /** * @private * @method _internal * @description Internal Callback Handler */ _internal: function () { this._callback.apply(this._context, arguments); }, /** * @method send * @description The method that executes the YQL Request. * @chainable * @return {YQLRequest} */ send: function () { var qs = [], url = ((this._opts && this._opts.proto) ? this._opts.proto : Y.YQLRequest.PROTO), o; Y.each(this._params, function (v, k) { qs.push(k + '=' + encodeURIComponent(v)); }); qs = qs.join('&'); url += ((this._opts && this._opts.base) ? this._opts.base : Y.YQLRequest.BASE_URL) + qs; o = (!Y.Lang.isFunction(this._callback)) ? this._callback : { on: { success: this._callback } }; o.on = o.on || {}; this._callback = o.on.success; o.on.success = Y.bind(this._internal, this); this._send(url, o); return this; }, /** * Private method to send the request, overwritten in plugins * @method _send * @private * @param {String} url The URL to request * @param {Object} o The config object */ _send: function(url, o) { if (o.allowCache !== false) { o.allowCache = true; } if (!this._jsonp) { this._jsonp = Y.jsonp(url, o); } else { this._jsonp.url = url; if (o.on && o.on.success) { this._jsonp._config.on.success = o.on.success; } this._jsonp.send(); } } }; /** * @static * @property FORMAT * @description Default format to use: json */ YQLRequest.FORMAT = 'json'; /** * @static * @property PROTO * @description Default protocol to use: http */ YQLRequest.PROTO = 'http'; /** * @static * @property BASE_URL * @description The base URL to query: query.yahooapis.com/v1/public/yql? */ YQLRequest.BASE_URL = ':/' + '/query.yahooapis.com/v1/public/yql?'; /** * @static * @property ENV * @description The environment file to load: http://datatables.org/alltables.env */ YQLRequest.ENV = 'http:/' + '/datatables.org/alltables.env'; Y.YQLRequest = YQLRequest; /** * This class adds a sugar class to allow access to YQL (http://developer.yahoo.com/yql/). * @class YQL * @constructor * @param {String} sql The SQL statement to execute * @param {Function} callback The callback to execute after the query (optional). * @param {Object} params An object literal of extra parameters to pass along (optional). * @param {Object} opts An object literal of configuration options (optional): proto (http|https), base (url) */ Y.YQL = function (sql, callback, params, opts) { return new Y.YQLRequest(sql, callback, params, opts).send(); }; }, '3.8.0pr2', {"requires": ["jsonp", "jsonp-url"]});
"use strict"; var Stream = require("stream").Stream, utillib = require("util"), net = require("net"), tls = require("tls"), oslib = require("os"), xoauth2 = require("xoauth2"), crypto = require("crypto"), fs = require('fs'); // expose to the world module.exports = function(port, host, options){ var connection = new SMTPClient(port, host, options); process.nextTick(connection.connect.bind(connection)); return connection; }; /** * <p>Generates a SMTP connection object</p> * * <p>Optional options object takes the following possible properties:</p> * <ul> * <li><b>secureConnection</b> - use SSL</li> * <li><b>name</b> - the name of the client server</li> * <li><b>auth</b> - authentication object <code>{user:"...", pass:"..."}</code> * <li><b>ignoreTLS</b> - ignore server support for STARTTLS</li> * <li><b>tls</b> - options for createCredentials</li> * <li><b>debug</b> - output client and server messages to console</li> * <li><b>logFile</b> - output client and server messages to file</li> * <li><b>instanceId</b> - unique instance id for debugging</li> * <li><b>localAddress</b> - outbound address to bind to (see: http://nodejs.org/api/net.html#net_net_connect_options_connectionlistener)</li> * </ul> * * @constructor * @namespace SMTP Client module * @param {Number} [port=25] Port number to connect to * @param {String} [host="localhost"] Hostname to connect to * @param {Object} [options] Option properties */ function SMTPClient(port, host, options){ Stream.call(this); this.writable = true; this.readable = true; this.options = options || {}; this.port = port || (this.options.secureConnection ? 465 : 25); this.host = host || "localhost"; this.options.secureConnection = !!this.options.secureConnection; this.options.auth = this.options.auth || false; this.options.maxConnections = this.options.maxConnections || 5; if(!this.options.name){ // defaul hostname is machine hostname or [IP] var defaultHostname = (oslib.hostname && oslib.hostname()) || ""; if(defaultHostname.indexOf('.')<0){ defaultHostname = "[127.0.0.1]"; } if(defaultHostname.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/)){ defaultHostname = "["+defaultHostname+"]"; } this.options.name = defaultHostname; } this._init(); } utillib.inherits(SMTPClient, Stream); /** * <p>Initializes instance variables</p> */ SMTPClient.prototype._init = function(){ /** * Defines if the current connection is secure or not. If not, * STARTTLS can be used if available * @private */ this._secureMode = false; /** * Ignore incoming data on TLS negotiation * @private */ this._ignoreData = false; /** * Store incomplete messages coming from the server * @private */ this._remainder = ""; /** * If set to true, then this object is no longer active * @private */ this.destroyed = false; /** * The socket connecting to the server * @publick */ this.socket = false; /** * Lists supported auth mechanisms * @private */ this._supportedAuth = []; /** * Currently in data transfer state * @private */ this._dataMode = false; /** * Keep track if the client sends a leading \r\n in data mode * @private */ this._lastDataBytes = new Buffer(2); /** * Function to run if a data chunk comes from the server * @private */ this._currentAction = false; /** * Timeout variable for waiting the greeting * @private */ this._greetingTimeout = false; /** * Timeout variable for waiting the connection to start * @private */ this._connectionTimeout = false; if(this.options.ignoreTLS || this.options.secureConnection){ this._secureMode = true; } /** * XOAuth2 token generator if XOAUTH2 auth is used * @private */ this._xoauth2 = false; if(typeof this.options.auth.XOAuth2 == "object" && typeof this.options.auth.XOAuth2.getToken == "function"){ this._xoauth2 = this.options.auth.XOAuth2; }else if(typeof this.options.auth.XOAuth2 == "object"){ if(!this.options.auth.XOAuth2.user && this.options.auth.user){ this.options.auth.XOAuth2.user = this.options.auth.user; } this._xoauth2 = xoauth2.createXOAuth2Generator(this.options.auth.XOAuth2); } }; /** * <p>Creates a connection to a SMTP server and sets up connection * listener</p> */ SMTPClient.prototype.connect = function(){ var opts = {}; if(this.options.secureConnection){ if (this.options.tls) { Object.keys(this.options.tls).forEach((function(key) { opts[key] = this.options.tls[key]; }).bind(this)); } if(!("rejectUnauthorized" in opts)){ opts.rejectUnauthorized = !!this.options.rejectUnauthorized; } if(this.options.localAddress){ opts.localAddress = this.options.localAddress; } this.socket = tls.connect(this.port, this.host, opts, this._onConnect.bind(this)); }else{ opts = { port: this.port, host: this.host }; if(this.options.localAddress){ opts.localAddress = this.options.localAddress; } this.socket = net.connect(opts, this._onConnect.bind(this)); } if(this.options.connectionTimeout){ this._connectionTimeout = setTimeout((function(){ var error = new Error("Connection timeout"); error.code = "ETIMEDOUT"; error.errno = "ETIMEDOUT"; this.emit("error", error); this.close(); }).bind(this), this.options.connectionTimeout); } this.socket.on("error", this._onError.bind(this)); }; /** * <p>Upgrades the connection to TLS</p> * * @param {Function} callback Callbac function to run when the connection * has been secured */ SMTPClient.prototype._upgradeConnection = function(callback){ this._ignoreData = true; this.socket.removeAllListeners("data"); this.socket.removeAllListeners("error"); var opts = { socket: this.socket, host: this.host, rejectUnauthorized: !!this.options.rejectUnauthorized }; Object.keys(this.options.tls || {}).forEach((function(key){ opts[key] = this.options.tls[key]; }).bind(this)); this.socket = tls.connect(opts, (function(){ this._ignoreData = false; this._secureMode = true; this.socket.on("data", this._onData.bind(this)); return callback(null, true); }).bind(this)); this.socket.on("error", this._onError.bind(this)); }; /** * <p>Connection listener that is run when the connection to * the server is opened</p> * * @event */ SMTPClient.prototype._onConnect = function(){ clearTimeout(this._connectionTimeout); if("setKeepAlive" in this.socket){ this.socket.setKeepAlive(true); } if("setNoDelay" in this.socket){ this.socket.setNoDelay(true); } this.socket.on("data", this._onData.bind(this)); this.socket.on("close", this._onClose.bind(this)); this.socket.on("end", this._onEnd.bind(this)); this.socket.setTimeout(3 * 3600 * 1000); // 1 hours this.socket.on("timeout", this._onTimeout.bind(this)); this._greetingTimeout = setTimeout((function(){ // if strill waiting for greeting, give up if(this._currentAction == this._actionGreeting){ var error = new Error("Greeting never received"); error.code = "ETIMEDOUT"; error.errno = "ETIMEDOUT"; this.emit("error", error); this.close(); } }).bind(this), this.options.greetingTimeout || 10000); this._currentAction = this._actionGreeting; }; /** * <p>Destroys the client - removes listeners etc.</p> */ SMTPClient.prototype._destroy = function(){ if(this._destroyed)return; this._destroyed = true; this._ignoreData = true; this.emit("end"); this.removeAllListeners(); }; /** * <p>'data' listener for data coming from the server</p> * * @event * @param {Buffer} chunk Data chunk coming from the server */ SMTPClient.prototype._onData = function(chunk){ var str; if(this._ignoreData || !chunk || !chunk.length){ return; } // Wait until end of line if(chunk.readUInt8(chunk.length-1) != 0x0A){ this._remainder += chunk.toString(); return; }else{ str = (this._remainder + chunk.toString()).trim(); this._remainder = ""; } // if this is a multi line reply, wait until the ending if(str.match(/(?:^|\n)\d{3}-.+$/)){ this._remainder = str + "\r\n"; return; } if(this.options.debug){ console.log("SERVER"+(this.options.instanceId?" "+ this.options.instanceId:"")+":\n└──"+str.replace(/\r?\n/g,"\n ")); } if(this.options.logFile){ this.log("SERVER"+(this.options.instanceId?" "+ this.options.instanceId:"")+":\n└──"+str.replace(/\r?\n/g,"\n ") ); } if(typeof this._currentAction == "function"){ this._currentAction.call(this, str); } }; /** * <p>'error' listener for the socket</p> * * @event * @param {Error} err Error object * @param {String} type Error name */ SMTPClient.prototype._onError = function(err, type, data){ if(type && type != "Error"){ err.name = type; } if(data){ err.data = data; } this.emit("error", err); this.close(); }; /** * <p>'close' listener for the socket</p> * * @event */ SMTPClient.prototype._onClose = function(){ this._destroy(); }; /** * <p>'end' listener for the socket</p> * * @event */ SMTPClient.prototype._onEnd = function(){ this._destroy(); }; /** * <p>'timeout' listener for the socket</p> * * @event */ SMTPClient.prototype._onTimeout = function(){ this.close(); }; /** * <p>Passes data stream to socket if in data mode</p> * * @param {Buffer} chunk Chunk of data to be sent to the server */ SMTPClient.prototype.write = function(chunk){ // works only in data mode if(!this._dataMode || this._destroyed){ // this line should never be reached but if it does, then // say act like everything's normal. return true; } if(typeof chunk == "string"){ chunk = new Buffer(chunk, "utf-8"); } if(chunk.length > 2){ this._lastDataBytes[0] = chunk[chunk.length-2]; this._lastDataBytes[1] = chunk[chunk.length-1]; }else if(chunk.length == 1){ this._lastDataBytes[0] = this._lastDataBytes[1]; this._lastDataBytes[1] = chunk[0]; } if(this.options.debug){ console.log("CLIENT (DATA)"+(this.options.instanceId?" "+ this.options.instanceId:"")+":\n└──"+chunk.toString().trim().replace(/\n/g,"\n ")); } if(this.options.logFile){ this.log("CLIENT (DATA)"+(this.options.instanceId?" "+ this.options.instanceId:"")+":\n└──"+chunk.toString().trim().replace(/\n/g,"\n ")); } // pass the chunk to the socket return this.socket.write(chunk); }; /** * <p>Indicates that a data stream for the socket is ended. Works only * in data mode.</p> * * @param {Buffer} [chunk] Chunk of data to be sent to the server */ SMTPClient.prototype.end = function(chunk){ // works only in data mode if(!this._dataMode || this._destroyed){ // this line should never be reached but if it does, then // say act like everything's normal. return true; } if(chunk && chunk.length){ this.write(chunk); } // redirect output from the server to _actionStream this._currentAction = this._actionStream; // indicate that the stream has ended by sending a single dot on its own line // if the client already closed the data with \r\n no need to do it again if(this._lastDataBytes[0] == 0x0D && this._lastDataBytes[1] == 0x0A){ this.socket.write(new Buffer(".\r\n", "utf-8")); }else if(this._lastDataBytes[1] == 0x0D){ this.socket.write(new Buffer("\n.\r\n")); }else{ this.socket.write(new Buffer("\r\n.\r\n")); } // end data mode this._dataMode = false; }; /** * <p>Send a command to the server, append \r\n</p> * * @param {String} str String to be sent to the server */ SMTPClient.prototype.sendCommand = function(str){ if(this._destroyed){ // Connection already closed, can't send any more data return; } if(this.options.debug){ console.log("CLIENT"+(this.options.instanceId?" "+ this.options.instanceId:"")+":\n└──"+(str || "").toString().trim().replace(/\n/g,"\n ")); } if(this.options.logFile){ this.log("CLIENT"+(this.options.instanceId?" "+ this.options.instanceId:"")+":\n└──"+(str || "").toString().trim().replace(/\n/g,"\n ")); } this.socket.write(new Buffer(str+"\r\n", "utf-8")); }; /** * <p>Sends QUIT</p> */ SMTPClient.prototype.quit = function(){ this.sendCommand("QUIT"); this._currentAction = this.close; }; /** * <p>Closes the connection to the server</p> */ SMTPClient.prototype.close = function(){ if(this.options.debug){ console.log("Closing connection to the server"); } if(this.options.logFile){ this.log("Closing connection to the server"); } if(this.socket && this.socket.socket && this.socket.socket.end && !this.socket.socket.destroyed){ this.socket.socket.end(); } if(this.socket && this.socket.end && !this.socket.destroyed){ this.socket.end(); } this._destroy(); }; /** * <p>Initiates a new message by submitting envelope data, starting with * <code>MAIL FROM:</code> command</p> * * @param {Object} envelope Envelope object in the form of * <code>{from:"...", to:["..."]}</code> */ SMTPClient.prototype.useEnvelope = function(envelope){ this._envelope = envelope || {}; this._envelope.from = this._envelope.from || ("anonymous@"+this.options.name); // clone the recipients array for latter manipulation this._envelope.rcptQueue = JSON.parse(JSON.stringify(this._envelope.to || [])); this._envelope.rcptFailed = []; this._currentAction = this._actionMAIL; this.sendCommand("MAIL FROM:<"+(this._envelope.from)+">"); }; /** * <p>If needed starts the authentication, if not emits 'idle' to * indicate that this client is ready to take in an outgoing mail</p> */ SMTPClient.prototype._authenticateUser = function(){ if(!this.options.auth){ // no need to authenticate, at least no data given this._currentAction = this._actionIdle; this.emit("idle"); // ready to take orders return; } var auth; if(this.options.auth.XOAuthToken && this._supportedAuth.indexOf("XOAUTH")>=0){ auth = "XOAUTH"; }else if(this._xoauth2 && this._supportedAuth.indexOf("XOAUTH2")>=0){ auth = "XOAUTH2"; }else if(this.options.authMethod) { auth = this.options.authMethod.toUpperCase().trim(); }else{ // use first supported auth = (this._supportedAuth[0] || "PLAIN").toUpperCase().trim(); } switch(auth){ case "XOAUTH": this._currentAction = this._actionAUTHComplete; if(typeof this.options.auth.XOAuthToken == "object" && typeof this.options.auth.XOAuthToken.generate == "function"){ this.options.auth.XOAuthToken.generate((function(err, XOAuthToken){ if(err){ return this._onError(err, "XOAuthTokenError"); } this.sendCommand("AUTH XOAUTH " + XOAuthToken); }).bind(this)); }else{ this.sendCommand("AUTH XOAUTH " + this.options.auth.XOAuthToken.toString()); } return; case "XOAUTH2": this._currentAction = this._actionAUTHComplete; this._xoauth2.getToken((function(err, token){ if(err){ this._onError(err, "XOAUTH2Error"); return; } this.sendCommand("AUTH XOAUTH2 " + token); }).bind(this)); return; case "LOGIN": this._currentAction = this._actionAUTH_LOGIN_USER; this.sendCommand("AUTH LOGIN"); return; case "PLAIN": this._currentAction = this._actionAUTHComplete; this.sendCommand("AUTH PLAIN "+new Buffer( //this.options.auth.user+"\u0000"+ "\u0000"+ // skip authorization identity as it causes problems with some servers this.options.auth.user+"\u0000"+ this.options.auth.pass,"utf-8").toString("base64")); return; case "CRAM-MD5": this._currentAction = this._actionAUTH_CRAM_MD5; this.sendCommand("AUTH CRAM-MD5"); return; } this._onError(new Error("Unknown authentication method - "+auth), "UnknowAuthError"); }; /** ACTIONS **/ /** * <p>Will be run after the connection is created and the server sends * a greeting. If the incoming message starts with 220 initiate * SMTP session by sending EHLO command</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionGreeting = function(str){ clearTimeout(this._greetingTimeout); if(str.substr(0,3) != "220"){ this._onError(new Error("Invalid greeting from server - "+str), false, str); return; } this._currentAction = this._actionEHLO; this.sendCommand("EHLO "+this.options.name); }; /** * <p>Handles server response for EHLO command. If it yielded in * error, try HELO instead, otherwise initiate TLS negotiation * if STARTTLS is supported by the server or move into the * authentication phase.</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionEHLO = function(str){ if(str.charAt(0) != "2"){ // Try HELO instead this._currentAction = this._actionHELO; this.sendCommand("HELO "+this.options.name); return; } // Detect if the server supports STARTTLS if(!this._secureMode && str.match(/[ \-]STARTTLS\r?$/mi)){ this.sendCommand("STARTTLS"); this._currentAction = this._actionSTARTTLS; return; } // Detect if the server supports PLAIN auth if(str.match(/AUTH(?:\s+[^\n]*\s+|\s+)PLAIN/i)){ this._supportedAuth.push("PLAIN"); } // Detect if the server supports LOGIN auth if(str.match(/AUTH(?:\s+[^\n]*\s+|\s+)LOGIN/i)){ this._supportedAuth.push("LOGIN"); } // Detect if the server supports CRAM-MD5 auth if(str.match(/AUTH(?:\s+[^\n]*\s+|\s+)CRAM-MD5/i)){ this._supportedAuth.push("CRAM-MD5"); } // Detect if the server supports XOAUTH auth if(str.match(/AUTH(?:\s+[^\n]*\s+|\s+)XOAUTH/i)){ this._supportedAuth.push("XOAUTH"); } // Detect if the server supports XOAUTH2 auth if(str.match(/AUTH(?:\s+[^\n]*\s+|\s+)XOAUTH2/i)){ this._supportedAuth.push("XOAUTH2"); } this._authenticateUser.call(this); }; /** * <p>Handles server response for HELO command. If it yielded in * error, emit 'error', otherwise move into the authentication phase.</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionHELO = function(str){ if(str.charAt(0) != "2"){ this._onError(new Error("Invalid response for EHLO/HELO - "+str), false, str); return; } this._authenticateUser.call(this); }; /** * <p>Handles server response for STARTTLS command. If there's an error * try HELO instead, otherwise initiate TLS upgrade. If the upgrade * succeedes restart the EHLO</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionSTARTTLS = function(str){ if(str.charAt(0) != "2"){ // Try HELO instead this._currentAction = this._actionHELO; this.sendCommand("HELO "+this.options.name); return; } this._upgradeConnection((function(err, secured){ if(err){ this._onError(new Error("Error initiating TLS - "+(err.message || err)), "TLSError"); return; } if(this.options.debug){ console.log("Connection secured"); } if(this.options.logFile){ this.log("Connection secured"); } if(secured){ // restart session this._currentAction = this._actionEHLO; this.sendCommand("EHLO "+this.options.name); }else{ this._authenticateUser.call(this); } }).bind(this)); }; /** * <p>Handle the response for AUTH LOGIN command. We are expecting * '334 VXNlcm5hbWU6' (base64 for 'Username:'). Data to be sent as * response needs to be base64 encoded username.</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionAUTH_LOGIN_USER = function(str){ if(str != "334 VXNlcm5hbWU6"){ this._onError(new Error("Invalid login sequence while waiting for '334 VXNlcm5hbWU6' - "+str), false, str); return; } this._currentAction = this._actionAUTH_LOGIN_PASS; this.sendCommand(new Buffer( this.options.auth.user, "utf-8").toString("base64")); }; /** * <p>Handle the response for AUTH CRAM-MD5 command. We are expecting * '334 <challenge string>'. Data to be sent as response needs to be * base64 decoded challenge string, MD5 hashed using the password as * a HMAC key, prefixed by the username and a space, and finally all * base64 encoded again.</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionAUTH_CRAM_MD5 = function(str) { var challengeMatch = str.match(/^334\s+(.+)$/), challengeString = ""; if (!challengeMatch) { this._onError(new Error("Invalid login sequence while waiting for server challenge string - "+str), false, str); return; } else { challengeString = challengeMatch[1]; } // Decode from base64 var base64decoded = new Buffer(challengeString, 'base64').toString('ascii'), hmac_md5 = crypto.createHmac('md5', this.options.auth.pass); hmac_md5.update(base64decoded); var hex_hmac = hmac_md5.digest('hex'), prepended = this.options.auth.user + " " + hex_hmac; this._currentAction = this._actionAUTH_CRAM_MD5_PASS; this.sendCommand(new Buffer(prepended).toString("base64")); }; /** * <p>Handles the response to CRAM-MD5 authentication, if there's no error, * the user can be considered logged in. Emit 'idle' and start * waiting for a message to send</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionAUTH_CRAM_MD5_PASS = function(str) { if (!str.match(/^235\s+/)) { this._onError(new Error("Invalid login sequence while waiting for '235 go ahead' - "+str), false, str); return; } this._currentAction = this._actionIdle; this.emit("idle"); // ready to take orders }; /** * <p>Handle the response for AUTH LOGIN command. We are expecting * '334 UGFzc3dvcmQ6' (base64 for 'Password:'). Data to be sent as * response needs to be base64 encoded password.</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionAUTH_LOGIN_PASS = function(str){ if(str != "334 UGFzc3dvcmQ6"){ this._onError(new Error("Invalid login sequence while waiting for '334 UGFzc3dvcmQ6' - "+str), false, str); return; } this._currentAction = this._actionAUTHComplete; this.sendCommand(new Buffer(this.options.auth.pass, "utf-8").toString("base64")); }; /** * <p>Handles the response for authentication, if there's no error, * the user can be considered logged in. Emit 'idle' and start * waiting for a message to send</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionAUTHComplete = function(str){ var response; if(this._xoauth2 && str.substr(0, 3) == "334"){ try{ response = str.split(" "); response.shift(); response = JSON.parse(new Buffer(response.join(" "), "base64").toString("utf-8")); if((!this._xoauth2.reconnectCount || this._xoauth2.reconnectCount < 200) && ['400','401'].indexOf(response.status)>=0){ this._xoauth2.reconnectCount = (this._xoauth2.reconnectCount || 0) + 1; this._currentAction = this._actionXOAUTHRetry; }else{ this._xoauth2.reconnectCount = 0; this._currentAction = this._actionAUTHComplete; } this.sendCommand(new Buffer(0)); return; }catch(E){} } this._xoauth2.reconnectCount = 0; if(str.charAt(0) != "2"){ this._onError(new Error("Invalid login - "+str), "AuthError", str); return; } this._currentAction = this._actionIdle; this.emit("idle"); // ready to take orders }; /** * If XOAUTH2 authentication failed, try again by generating * new access token */ SMTPClient.prototype._actionXOAUTHRetry = function(){ // ensure that something is listening unexpected responses this._currentAction = this._actionIdle; this._xoauth2.generateToken((function(err, token){ if(this._destroyed){ // Nothing to do here anymore, connection already closed return; } if(err){ this._onError(err, "XOAUTH2Error"); return; } this._currentAction = this._actionAUTHComplete; this.sendCommand("AUTH XOAUTH2 " + token); }).bind(this)); }; /** * <p>This function is not expected to run. If it does then there's probably * an error (timeout etc.)</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionIdle = function(str){ if(Number(str.charAt(0)) > 3){ this._onError(new Error(str), false, str); return; } // this line should never get called }; /** * <p>Handle response for a <code>MAIL FROM:</code> command</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionMAIL = function(str){ if(Number(str.charAt(0)) != "2"){ this._onError(new Error("Mail from command failed - " + str), "SenderError", str); return; } if(!this._envelope.rcptQueue.length){ this._onError(new Error("Can't send mail - no recipients defined"), "RecipientError", str); }else{ this._envelope.curRecipient = this._envelope.rcptQueue.shift(); this._currentAction = this._actionRCPT; this.sendCommand("RCPT TO:<"+this._envelope.curRecipient+">"+this._getDSN()); } }; /** * <p>SetsUp DSN</p> */ SMTPClient.prototype._getDSN = function(){ var ret = "", n = [], dsn; if (this.currentMessage && "dsn" in this.currentMessage.options){ dsn = this.currentMessage.options.dsn; if(dsn.success){ n.push("SUCCESS"); } if(dsn.failure){ n.push("FAILURE"); } if(dsn.delay){ n.push("DELAY"); } if(n.length > 0){ ret = " NOTIFY=" + n.join(",") + " ORCPT=rfc822;" + this.currentMessage._message.from; } } return ret; }; /** * <p>Handle response for a <code>RCPT TO:</code> command</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionRCPT = function(str){ if(Number(str.charAt(0)) != "2"){ // this is a soft error this._envelope.rcptFailed.push(this._envelope.curRecipient); } if(!this._envelope.rcptQueue.length){ if(this._envelope.rcptFailed.length < this._envelope.to.length){ this.emit("rcptFailed", this._envelope.rcptFailed); this._currentAction = this._actionDATA; this.sendCommand("DATA"); }else{ this._onError(new Error("Can't send mail - all recipients were rejected"), "RecipientError", str); return; } }else{ this._envelope.curRecipient = this._envelope.rcptQueue.shift(); this._currentAction = this._actionRCPT; this.sendCommand("RCPT TO:<"+this._envelope.curRecipient+">"); } }; /** * <p>Handle response for a <code>DATA</code> command</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionDATA = function(str){ // response should be 354 but according to this issue https://github.com/eleith/emailjs/issues/24 // some servers might use 250 instead, so lets check for 2 or 3 as the first digit if([2,3].indexOf(Number(str.charAt(0)))<0){ this._onError(new Error("Data command failed - " + str), false, str); return; } // Emit that connection is set up for streaming this._dataMode = true; this._currentAction = this._actionIdle; this.emit("message"); }; /** * <p>Handle response for a <code>DATA</code> stream</p> * * @param {String} str Message from the server */ SMTPClient.prototype._actionStream = function(str){ if(Number(str.charAt(0)) != "2"){ // Message failed this.emit("ready", false, str); }else{ // Message sent succesfully this.emit("ready", true, str); } // Waiting for new connections this._currentAction = this._actionIdle; process.nextTick(this.emit.bind(this, "idle")); }; /** * <p>Log debugs to given file</p> * * @param {String} str Log message */ SMTPClient.prototype.log = function(str) { fs.appendFile(this.options.logFile, str + "\n", function(err) { if (err) { console.log('Log write failed. Data to log: ' + str); } }); };
define([], function() { return [ {'id':'todo-001','startDate':'2013-03-30','title':'Create an initial project with 200 TODO items.', 'description':'todo-001'}, {'id':'todo-002','startDate':'2013-03-30','title':'Make the demo eye candy.', 'description':'todo-002'}, {'id':'todo-003','startDate':'2013-03-30','title':'Deploy a basic automation and testing configuration.', 'description':'todo-003'}, {'id':'todo-004','startDate':'2013-03-30','title':'Start inspecting performance.', 'description':'todo-004'}, {'id':'todo-005','startDate':'2013-03-30','title':'unicorns ponies and rainbows 005', 'description':'todo-005'}, {'id':'todo-006','startDate':'2013-03-30','title':'unicorns ponies and rainbows 006', 'description':'todo-006'}, {'id':'todo-007','startDate':'2013-03-30','title':'unicorns ponies and rainbows 007', 'description':'todo-007'}, {'id':'todo-008','startDate':'2013-03-30','title':'unicorns ponies and rainbows 008', 'description':'todo-008'}, {'id':'todo-009','startDate':'2013-03-30','title':'unicorns ponies and rainbows 009', 'description':'todo-009'}, {'id':'todo-010','startDate':'2013-03-30','title':'unicorns ponies and rainbows 010', 'description':'todo-010'}, {'id':'todo-011','startDate':'2013-03-30','title':'unicorns ponies and rainbows 011', 'description':'todo-011'}, {'id':'todo-012','startDate':'2013-03-30','title':'unicorns ponies and rainbows 012', 'description':'todo-012'}, {'id':'todo-013','startDate':'2013-03-30','title':'unicorns ponies and rainbows 013', 'description':'todo-013'}, {'id':'todo-014','startDate':'2013-03-30','title':'unicorns ponies and rainbows 014', 'description':'todo-014'}, {'id':'todo-015','startDate':'2013-03-30','title':'unicorns ponies and rainbows 015', 'description':'todo-015'}, {'id':'todo-016','startDate':'2013-03-30','title':'unicorns ponies and rainbows 016', 'description':'todo-016'}, {'id':'todo-017','startDate':'2013-03-30','title':'unicorns ponies and rainbows 017', 'description':'todo-017'}, {'id':'todo-018','startDate':'2013-03-30','title':'unicorns ponies and rainbows 018', 'description':'todo-018'}, {'id':'todo-019','startDate':'2013-03-30','title':'unicorns ponies and rainbows 019', 'description':'todo-019'}, {'id':'todo-020','startDate':'2013-03-30','title':'unicorns ponies and rainbows 020', 'description':'todo-020'}, {'id':'todo-021','startDate':'2013-03-30','title':'unicorns ponies and rainbows 021', 'description':'todo-021'}, {'id':'todo-022','startDate':'2013-03-30','title':'unicorns ponies and rainbows 022', 'description':'todo-022'}, {'id':'todo-023','startDate':'2013-03-30','title':'unicorns ponies and rainbows 023', 'description':'todo-023'}, {'id':'todo-024','startDate':'2013-03-30','title':'unicorns ponies and rainbows 024', 'description':'todo-024'}, {'id':'todo-025','startDate':'2013-03-30','title':'unicorns ponies and rainbows 025', 'description':'todo-025'}, {'id':'todo-026','startDate':'2013-03-30','title':'unicorns ponies and rainbows 026', 'description':'todo-026'}, {'id':'todo-027','startDate':'2013-03-30','title':'unicorns ponies and rainbows 027', 'description':'todo-027'}, {'id':'todo-028','startDate':'2013-03-30','title':'unicorns ponies and rainbows 028', 'description':'todo-028'}, {'id':'todo-029','startDate':'2013-03-30','title':'unicorns rainbows and ponies 029', 'description':'todo-029'}, {'id':'todo-030','startDate':'2013-03-30','title':'unicorns rainbows and ponies 030', 'description':'todo-030'}, {'id':'todo-031','startDate':'2013-03-30','title':'unicorns rainbows and ponies 031', 'description':'todo-031'}, {'id':'todo-032','startDate':'2013-03-30','title':'unicorns rainbows and ponies 032', 'description':'todo-032'}, {'id':'todo-033','startDate':'2013-03-30','title':'unicorns rainbows and ponies 033', 'description':'todo-033'}, {'id':'todo-034','startDate':'2013-03-30','title':'unicorns rainbows and ponies 034', 'description':'todo-034'}, {'id':'todo-035','startDate':'2013-03-30','title':'unicorns rainbows and ponies 035', 'description':'todo-035'}, {'id':'todo-036','startDate':'2013-03-30','title':'unicorns rainbows and ponies 036', 'description':'todo-036'}, {'id':'todo-037','startDate':'2013-03-30','title':'unicorns rainbows and ponies 037', 'description':'todo-037'}, {'id':'todo-038','startDate':'2013-03-30','title':'unicorns rainbows and ponies 038', 'description':'todo-038'}, {'id':'todo-039','startDate':'2013-03-30','title':'unicorns rainbows and ponies 039', 'description':'todo-039'}, {'id':'todo-040','startDate':'2013-03-30','title':'unicorns rainbows and ponies 040', 'description':'todo-040'}, {'id':'todo-041','startDate':'2013-03-30','title':'macaron cupcake macarena 041', 'description':'macarena 041'}, {'id':'todo-042','startDate':'2013-03-30','title':'macaron cupcake macarena 042', 'description':'macarena 042'}, {'id':'todo-043','startDate':'2013-03-30','title':'macaron cupcake macarena 043', 'description':'macarena 043'}, {'id':'todo-044','startDate':'2013-03-30','title':'macaron cupcake macarena 044', 'description':'macarena 044'}, {'id':'todo-045','startDate':'2013-03-30','title':'macaron cupcake macarena 045', 'description':'macarena 045'}, {'id':'todo-046','startDate':'2013-03-30','title':'macaron cupcake macarena 046', 'description':'macarena 046'}, {'id':'todo-047','startDate':'2013-03-30','title':'macaron cupcake macarena 047', 'description':'macarena 047'}, {'id':'todo-048','startDate':'2013-03-30','title':'macaron cupcake macarena 048', 'description':'macarena 048'}, {'id':'todo-049','startDate':'2013-03-30','title':'macaron cupcake macarena 049', 'description':'macarena 049'}, {'id':'todo-050','startDate':'2013-03-30','title':'macaron cupcake macarena 050', 'description':'macarena 050'}, {'id':'todo-051','startDate':'2013-03-30','title':'macaron cupcake macarena 051', 'description':'macarena 051'}, {'id':'todo-052','startDate':'2013-03-30','title':'macaron cupcake macarena 052', 'description':'macarena 052'}, {'id':'todo-053','startDate':'2013-03-30','title':'macaron cupcake macarena 053', 'description':'macarena 053'}, {'id':'todo-054','startDate':'2013-03-30','title':'macaron cupcake macarena 054', 'description':'macarena 054'}, {'id':'todo-055','startDate':'2013-03-30','title':'macaron cupcake macarena 055', 'description':'macarena 055'}, {'id':'todo-056','startDate':'2013-03-30','title':'macaron cupcake macarena 056', 'description':'macarena 056'}, {'id':'todo-057','startDate':'2013-03-30','title':'macaron cupcake macarena 057', 'description':'macarena 057'}, {'id':'todo-058','startDate':'2013-03-30','title':'macaron cupcake macarena 058', 'description':'macarena 058'}, {'id':'todo-059','startDate':'2013-03-30','title':'macaron cupcake macarena 059', 'description':'macarena 059'}, {'id':'todo-060','startDate':'2013-03-30','title':'macaron cupcake macarena 060', 'description':'macarena 060'}, {'id':'todo-061','startDate':'2013-03-30','title':'macaron cupcake macarena 061', 'description':'cupcake macarena 061'}, {'id':'todo-062','startDate':'2013-03-30','title':'macaron cupcake macarena 062', 'description':'cupcake macarena 062'}, {'id':'todo-063','startDate':'2013-03-30','title':'macaron cupcake macarena 063', 'description':'cupcake macarena 063'}, {'id':'todo-064','startDate':'2013-03-30','title':'macaron cupcake macarena 064', 'description':'cupcake macarena 064'}, {'id':'todo-065','startDate':'2013-03-30','title':'macaron cupcake macarena 065', 'description':'cupcake macarena 065'}, {'id':'todo-066','startDate':'2013-03-30','title':'macaron cupcake macarena 066', 'description':'cupcake macarena 066'}, {'id':'todo-067','startDate':'2013-03-30','title':'macaron cupcake macarena 067', 'description':'cupcake macarena 067'}, {'id':'todo-068','startDate':'2013-03-30','title':'macaron cupcake macarena 068', 'description':'cupcake macarena 068'}, {'id':'todo-069','startDate':'2013-03-30','title':'cupcake ipsum pancakes 069', 'description':'pancakes 069'}, {'id':'todo-070','startDate':'2013-03-30','title':'cupcake ipsum pancakes 070', 'description':'pancakes 070'}, {'id':'todo-071','startDate':'2013-03-30','title':'cupcake ipsum pancakes 071', 'description':'pancakes 071'}, {'id':'todo-072','startDate':'2013-03-30','title':'cupcake ipsum pancakes 072', 'description':'pancakes 072'}, {'id':'todo-073','startDate':'2013-03-30','title':'cupcake ipsum pancakes 073', 'description':'pancakes 073'}, {'id':'todo-074','startDate':'2013-03-30','title':'cupcake ipsum pancakes 074', 'description':'pancakes 074'}, {'id':'todo-075','startDate':'2013-03-30','title':'cupcake ipsum pancakes 075', 'description':'pancakes 075'}, {'id':'todo-076','startDate':'2013-03-30','title':'cupcake ipsum pancakes 076', 'description':'pancakes 076'}, {'id':'todo-077','startDate':'2013-03-30','title':'cupcake ipsum pancakes 077', 'description':'pancakes 077'}, {'id':'todo-078','startDate':'2013-03-30','title':'cupcake ipsum pancakes 078', 'description':'pancakes 078'}, {'id':'todo-079','startDate':'2013-03-30','title':'cupcake ipsum pancakes 079', 'description':'pancakes 079'}, {'id':'todo-080','startDate':'2013-03-30','title':'cupcake ipsum pancakes 080', 'description':'pancakes 080'}, {'id':'todo-081','startDate':'2013-03-30','title':'cupcake ipsum pancakes 081', 'description':'pancakes 081'}, {'id':'todo-082','startDate':'2013-03-30','title':'cupcake ipsum pancakes 082', 'description':'pancakes 082'}, {'id':'todo-083','startDate':'2013-03-30','title':'cupcake ipsum pancakes 083', 'description':'pancakes 083'}, {'id':'todo-084','startDate':'2013-03-30','title':'cupcake ipsum pancakes 084', 'description':'pancakes 084'}, {'id':'todo-085','startDate':'2013-03-30','title':'cupcake ipsum pancakes 085', 'description':'pancakes 085'}, {'id':'todo-086','startDate':'2013-03-30','title':'cupcake ipsum pancakes 086', 'description':'pancakes 086'}, {'id':'todo-087','startDate':'2013-03-30','title':'cupcake ipsum pancakes 087', 'description':'pancakes 087'}, {'id':'todo-088','startDate':'2013-03-30','title':'cupcake ipsum pancakes 088', 'description':'pancakes 088'}, {'id':'todo-089','startDate':'2013-03-30','title':'cupcake ipsum pancakes 089', 'description':'pancakes 089'}, {'id':'todo-090','startDate':'2013-03-30','title':'cupcake ipsum pancakes 090', 'description':'pancakes 090'}, {'id':'todo-091','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 091', 'description':'lorem 091'}, {'id':'todo-092','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 092', 'description':'lorem 092'}, {'id':'todo-093','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 093', 'description':'lorem 093'}, {'id':'todo-094','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 094', 'description':'lorem 094'}, {'id':'todo-095','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 095', 'description':'lorem 095'}, {'id':'todo-096','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 096', 'description':'lorem 096'}, {'id':'todo-097','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 097', 'description':'lorem 097'}, {'id':'todo-098','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 098', 'description':'lorem 098'}, {'id':'todo-099','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 099', 'description':'lorem 099'}, {'id':'todo-100','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 100', 'description':'lorem 100'}, {'id':'todo-101','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 101', 'description':'lorem 101'}, {'id':'todo-102','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 102', 'description':'lorem 102'}, {'id':'todo-103','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 103', 'description':'lorem 103'}, {'id':'todo-104','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 104', 'description':'lorem 104'}, {'id':'todo-105','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 105', 'description':'lorem 105'}, {'id':'todo-106','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 106', 'description':'lorem 106'}, {'id':'todo-107','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 107', 'description':'lorem 107'}, {'id':'todo-108','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 108', 'description':'lorem 108'}, {'id':'todo-109','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 109', 'description':'lorem 109'}, {'id':'todo-110','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 110', 'description':'lorem 110'}, {'id':'todo-111','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 111', 'description':'lorem 111'}, {'id':'todo-112','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 112', 'description':'lorem 112'}, {'id':'todo-113','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 113', 'description':'ipsum lorem 113'}, {'id':'todo-114','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 114', 'description':'ipsum lorem 114'}, {'id':'todo-115','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 115', 'description':'ipsum lorem 115'}, {'id':'todo-116','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 116', 'description':'ipsum lorem 116'}, {'id':'todo-117','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 117', 'description':'ipsum lorem 117'}, {'id':'todo-118','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 118', 'description':'ipsum lorem 118'}, {'id':'todo-119','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 119', 'description':'ipsum lorem 119'}, {'id':'todo-120','startDate':'2013-03-30','title':'amet dolor sit ipsum lorem 120', 'description':'ipsum lorem 120'}, {'id':'todo-121','startDate':'2013-03-30','title':'lorem test dolorem ipsum 121', 'description':'dolorem ipsum 121'}, {'id':'todo-122','startDate':'2013-03-30','title':'lorem test dolorem ipsum 122', 'description':'dolorem ipsum 122'}, {'id':'todo-123','startDate':'2013-03-30','title':'lorem test dolorem ipsum 123', 'description':'dolorem ipsum 123'}, {'id':'todo-124','startDate':'2013-03-30','title':'lorem test dolorem ipsum 124', 'description':'dolorem ipsum 124'}, {'id':'todo-125','startDate':'2013-03-30','title':'lorem test dolorem ipsum 125', 'description':'dolorem ipsum 125'}, {'id':'todo-126','startDate':'2013-03-30','title':'lorem test dolorem ipsum 126', 'description':'dolorem ipsum 126'}, {'id':'todo-127','startDate':'2013-03-30','title':'lorem test dolorem ipsum 127', 'description':'dolorem ipsum 127'}, {'id':'todo-128','startDate':'2013-03-30','title':'lorem test dolorem ipsum 128', 'description':'dolorem ipsum 128'}, {'id':'todo-129','startDate':'2013-03-30','title':'lorem test dolorem ipsum 129', 'description':'dolorem ipsum 129'}, {'id':'todo-130','startDate':'2013-03-30','title':'lorem test dolorem ipsum 130', 'description':'dolorem ipsum 130'}, {'id':'todo-131','startDate':'2013-03-30','title':'lorem test dolorem ipsum 131', 'description':'dolorem ipsum 131'}, {'id':'todo-132','startDate':'2013-03-30','title':'lorem test dolorem ipsum 132', 'description':'dolorem ipsum 132'}, {'id':'todo-133','startDate':'2013-03-30','title':'lorem test dolorem ipsum 133', 'description':'dolorem ipsum 133'}, {'id':'todo-134','startDate':'2013-03-30','title':'lorem test dolorem ipsum 134', 'description':'dolorem ipsum 134'}, {'id':'todo-135','startDate':'2013-03-30','title':'lorem test dolorem ipsum 135', 'description':'dolorem ipsum 135'}, {'id':'todo-136','startDate':'2013-03-30','title':'lorem test dolorem ipsum 136', 'description':'dolorem ipsum 136'}, {'id':'todo-137','startDate':'2013-03-30','title':'lorem test dolorem ipsum 137', 'description':'dolorem ipsum 137'}, {'id':'todo-138','startDate':'2013-03-30','title':'lorem test dolorem ipsum 138', 'description':'dolorem ipsum 138'}, {'id':'todo-139','startDate':'2013-03-30','title':'lorem test dolorem ipsum 139', 'description':'dolorem ipsum 139'}, {'id':'todo-140','startDate':'2013-03-30','title':'lorem test dolorem ipsum 140', 'description':'dolorem ipsum 140'}, {'id':'todo-141','startDate':'2013-03-30','title':'lorem test dolorem ipsum 141', 'description':'dolorem ipsum 141'}, {'id':'todo-142','startDate':'2013-03-30','title':'lorem test dolorem ipsum 142', 'description':'dolorem ipsum 142'}, {'id':'todo-143','startDate':'2013-03-30','title':'lorem test dolorem ipsum 143', 'description':'dolorem ipsum 143'}, {'id':'todo-144','startDate':'2013-03-30','title':'lorem test dolorem ipsum 144', 'description':'dolorem ipsum 144'}, {'id':'todo-145','startDate':'2013-03-30','title':'lorem test dolorem ipsum 145', 'description':'dolorem ipsum 145'}, {'id':'todo-146','startDate':'2013-03-30','title':'lorem test dolorem ipsum 146', 'description':'dolorem ipsum 146'}, {'id':'todo-147','startDate':'2013-03-30','title':'lorem test dolorem ipsum 147', 'description':'dolorem ipsum 147'}, {'id':'todo-148','startDate':'2013-03-30','title':'lorem test dolorem ipsum 148', 'description':'dolorem ipsum 148'}, {'id':'todo-149','startDate':'2013-03-30','title':'lorem test dolorem ipsum 149', 'description':'dolorem ipsum 149'}, {'id':'todo-150','startDate':'2013-03-30','title':'lorem test dolorem ipsum 150', 'description':'dolorem ipsum 150'}, {'id':'todo-051','startDate':'2013-03-30','title':'ipsum sit amet elit 051', 'description':'sit amet elit 051'}, {'id':'todo-152','startDate':'2013-03-30','title':'ipsum sit amet elit 152', 'description':'sit amet elit 152'}, {'id':'todo-153','startDate':'2013-03-30','title':'ipsum sit amet elit 153', 'description':'sit amet elit 153'}, {'id':'todo-154','startDate':'2013-03-30','title':'ipsum sit amet elit 154', 'description':'sit amet elit 154'}, {'id':'todo-155','startDate':'2013-03-30','title':'ipsum sit amet elit 155', 'description':'sit amet elit 155'}, {'id':'todo-156','startDate':'2013-03-30','title':'ipsum sit amet elit 156', 'description':'sit amet elit 156'}, {'id':'todo-157','startDate':'2013-03-30','title':'ipsum sit amet elit 157', 'description':'sit amet elit 157'}, {'id':'todo-158','startDate':'2013-03-30','title':'ipsum sit amet elit 158', 'description':'sit amet elit 158'}, {'id':'todo-159','startDate':'2013-03-30','title':'ipsum sit amet elit 159', 'description':'sit amet elit 159'}, {'id':'todo-160','startDate':'2013-03-30','title':'ipsum sit amet elit 160', 'description':'sit amet elit 160'}, {'id':'todo-161','startDate':'2013-03-30','title':'ipsum sit amet elit 161', 'description':'sit amet elit 161'}, {'id':'todo-162','startDate':'2013-03-30','title':'ipsum sit amet elit 162', 'description':'sit amet elit 162'}, {'id':'todo-163','startDate':'2013-03-30','title':'ipsum sit amet elit 163', 'description':'sit amet elit 163'}, {'id':'todo-164','startDate':'2013-03-30','title':'ipsum sit amet elit 164', 'description':'sit amet elit 164'}, {'id':'todo-165','startDate':'2013-03-30','title':'ipsum sit amet elit 165', 'description':'sit amet elit 165'}, {'id':'todo-166','startDate':'2013-03-30','title':'ipsum sit amet elit 166', 'description':'sit amet elit 166'}, {'id':'todo-167','startDate':'2013-03-30','title':'ipsum sit amet elit 167', 'description':'sit amet elit 167'}, {'id':'todo-168','startDate':'2013-03-30','title':'ipsum sit amet elit 168', 'description':'sit amet elit 168'}, {'id':'todo-169','startDate':'2013-03-30','title':'ipsum sit amet elit 169', 'description':'sit amet elit 169'}, {'id':'todo-160','startDate':'2013-03-30','title':'ipsum sit amet elit 160', 'description':'sit amet elit 160'}, {'id':'todo-161','startDate':'2013-03-30','title':'ipsum sit amet elit 161', 'description':'sit amet elit 161'}, {'id':'todo-162','startDate':'2013-03-30','title':'ipsum sit amet elit 162', 'description':'sit amet elit 162'}, {'id':'todo-163','startDate':'2013-03-30','title':'ipsum sit amet elit 163', 'description':'amet elit 163'}, {'id':'todo-164','startDate':'2013-03-30','title':'ipsum sit amet elit 164', 'description':'amet elit 164'}, {'id':'todo-165','startDate':'2013-03-30','title':'ipsum sit amet elit 165', 'description':'amet elit 165'}, {'id':'todo-166','startDate':'2013-03-30','title':'ipsum sit amet elit 166', 'description':'amet elit 166'}, {'id':'todo-167','startDate':'2013-03-30','title':'ipsum sit amet elit 167', 'description':'amet elit 167'}, {'id':'todo-168','startDate':'2013-03-30','title':'ipsum sit amet elit 168', 'description':'amet elit 168'}, {'id':'todo-169','startDate':'2013-03-30','title':'ipsum sit amet elit 169', 'description':'amet elit 169'}, {'id':'todo-170','startDate':'2013-03-30','title':'ipsum sit amet elit 170', 'description':'amet elit 170'}, {'id':'todo-171','startDate':'2013-03-30','title':'lorem ipsum dolor sit 171', 'description':'sit 171'}, {'id':'todo-172','startDate':'2013-03-30','title':'lorem ipsum dolor sit 172', 'description':'sit 172'}, {'id':'todo-173','startDate':'2013-03-30','title':'lorem ipsum dolor sit 173', 'description':'sit 173'}, {'id':'todo-174','startDate':'2013-03-30','title':'lorem ipsum dolor sit 174', 'description':'sit 174'}, {'id':'todo-175','startDate':'2013-03-30','title':'lorem ipsum dolor sit 175', 'description':'sit 175'}, {'id':'todo-176','startDate':'2013-03-30','title':'lorem ipsum dolor sit 176', 'description':'sit 176'}, {'id':'todo-177','startDate':'2013-03-30','title':'lorem ipsum dolor sit 177', 'description':'sit 177'}, {'id':'todo-178','startDate':'2013-03-30','title':'lorem ipsum dolor sit 178', 'description':'sit 178'}, {'id':'todo-179','startDate':'2013-03-30','title':'lorem ipsum dolor sit 179', 'description':'sit 179'}, {'id':'todo-180','startDate':'2013-03-30','title':'lorem ipsum dolor sit 180', 'description':'sit 180'}, {'id':'todo-181','startDate':'2013-03-30','title':'lorem ipsum dolor sit 181', 'description':'sit 181'}, {'id':'todo-182','startDate':'2013-03-30','title':'lorem ipsum dolor sit 182', 'description':'sit 182'}, {'id':'todo-183','startDate':'2013-03-30','title':'lorem ipsum dolor sit 183', 'description':'sit 183'}, {'id':'todo-184','startDate':'2013-03-30','title':'lorem ipsum dolor sit 184', 'description':'sit 184'}, {'id':'todo-185','startDate':'2013-03-30','title':'lorem ipsum dolor sit 185', 'description':'sit 185'}, {'id':'todo-186','startDate':'2013-03-30','title':'lorem ipsum dolor sit 186', 'description':'sit 186'}, {'id':'todo-187','startDate':'2013-03-30','title':'lorem ipsum dolor sit 187', 'description':'sit 187'}, {'id':'todo-188','startDate':'2013-03-30','title':'lorem ipsum dolor sit 188', 'description':'sit 188'}, {'id':'todo-189','startDate':'2013-03-30','title':'lorem ipsum dolor sit 189', 'description':'sit 189'}, {'id':'todo-190','startDate':'2013-03-30','title':'lorem ipsum dolor sit 190', 'description':'sit 190'}, {'id':'todo-191','startDate':'2013-03-30','title':'lorem ipsum dolor sit 191', 'description':'sit 191'}, {'id':'todo-192','startDate':'2013-03-30','title':'lorem ipsum dolor sit 192', 'description':'sit 192'}, {'id':'todo-193','startDate':'2013-03-30','title':'lorem ipsum dolor sit 193', 'description':'sit 193'}, {'id':'todo-194','startDate':'2013-03-30','title':'lorem ipsum dolor sit 194', 'description':'sit 194'}, {'id':'todo-195','startDate':'2013-03-30','title':'lorem ipsum dolor sit 195', 'description':'sit 195'}, {'id':'todo-196','startDate':'2013-03-30','title':'lorem ipsum dolor sit 196', 'description':'sit 196'}, {'id':'todo-197','startDate':'2013-03-30','title':'lorem ipsum dolor sit 197', 'description':'sit 197'}, {'id':'todo-198','startDate':'2013-03-30','title':'lorem ipsum dolor sit 198', 'description':'sit 198'}, {'id':'todo-199','startDate':'2013-03-30','title':'lorem ipsum dolor sit 199', 'description':'sit 199'}, {'id':'todo-200','startDate':'2013-03-30','title':'lorem ipsum dolor sit 200', 'description':'sit 200'} ];});
define(["exports"], function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.foo7 = foo7; var foo = exports.foo = 1; var foo = exports.foo = 1, bar = exports.bar = 2; var foo2 = exports.foo2 = function () {}; var foo3 = exports.foo3 = undefined; let foo4 = exports.foo4 = 2; let foo5 = exports.foo5 = undefined; const foo6 = exports.foo6 = 3; function foo7() {} class foo8 {} exports.foo8 = foo8; });
System.register(['@angular/core', "@angular/forms"], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1, forms_1; var TestApp; return { setters:[ function (core_1_1) { core_1 = core_1_1; }, function (forms_1_1) { forms_1 = forms_1_1; }], execute: function() { TestApp = (function () { function TestApp(e, ref) { this.items = ['foo', 'bar', 'baz']; this.selection = 'foo'; this._host = e.nativeElement; this._ref = ref; this.form = new forms_1.FormGroup({ selection: new forms_1.FormControl() }); } TestApp.prototype.ngAfterViewInit = function () { var event = new CustomEvent('readyForTests', { detail: this }); this._host.dispatchEvent(event); }; TestApp.prototype.detectChanges = function () { this._ref.detectChanges(); }; TestApp = __decorate([ core_1.Component({ selector: 'test-app', template: "\n <vaadin-combo-box [(value)]=\"selection\" required class=\"bound\"></vaadin-combo-box>\n\n <form [formGroup]=\"form\">\n <vaadin-combo-box [items]=\"items\" formControlName=\"selection\" required></vaadin-combo-box>\n </form>\n " }), __metadata('design:paramtypes', [core_1.ElementRef, core_1.ChangeDetectorRef]) ], TestApp); return TestApp; }()); exports_1("TestApp", TestApp); } } }); //# sourceMappingURL=app.component.js.map
define([ 'dojo/_base/declare', 'dijit/_WidgetBase', 'dijit/_TemplatedMixin', 'dijit/_WidgetsInTemplateMixin', 'dojo/_base/lang', 'dijit/DropDownMenu', 'dijit/MenuItem', 'dojo/_base/array', 'dojox/lang/functional', 'dojo/text!./Basemaps/templates/Basemaps.html', 'esri/dijit/BasemapGallery', 'xstyle/css!./Basemaps/css/Basemaps.css' ], function (declare, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, lang, DropDownMenu, MenuItem, array, functional, template, BasemapGallery) { // main basemap widget return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], { templateString: template, widgetsInTemplate: true, mode: 'agol', title: 'Basemaps', //baseClass: 'gis_Basemaps_Dijit', //buttonClass: 'gis_Basemaps_Button', //menuClass: 'gis_Basemaps_Menu', mapStartBasemap: 'streets', basemapsToShow: ['streets', 'satellite', 'hybrid', 'topo', 'gray', 'oceans', 'national-geographic', 'osm'], validBasemaps: [], postCreate: function () { this.inherited(arguments); this.currentBasemap = this.mapStartBasemap || null; if (this.mode === 'custom') { this.gallery = new BasemapGallery({ map: this.map, showArcGISBasemaps: false, basemaps: functional.map(this.basemaps, function (map) { return map.basemap; }) }); // if (this.map.getBasemap() !== this.mapStartBasemap) { //based off the title of custom basemaps in viewer.js config // this.gallery.select(this.mapStartBasemap); // } this.gallery.startup(); } this.menu = new DropDownMenu({ style: 'display: none;' //, //baseClass: this.menuClass }); array.forEach(this.basemapsToShow, function (basemap) { if (this.basemaps.hasOwnProperty(basemap)) { var menuItem = new MenuItem({ id: basemap, label: this.basemaps[basemap].title, iconClass: (basemap == this.mapStartBasemap) ? 'selectedIcon' : 'emptyIcon', onClick: lang.hitch(this, function () { if (basemap !== this.currentBasemap) { this.currentBasemap = basemap; if (this.mode === 'custom') { this.gallery.select(basemap); } else { this.map.setBasemap(basemap); } var ch = this.menu.getChildren(); array.forEach(ch, function (c) { if (c.id == basemap) { c.set('iconClass', 'selectedIcon'); } else { c.set('iconClass', 'emptyIcon'); } }); } }) }); this.menu.addChild(menuItem); } }, this); this.dropDownButton.set('dropDown', this.menu); }, startup: function () { this.inherited(arguments); if (this.mode === 'custom') { if (this.map.getBasemap() !== this.mapStartBasemap) { //based off the title of custom basemaps in viewer.js config this.gallery.select(this.mapStartBasemap); } } else { if (this.mapStartBasemap) { if (this.map.getBasemap() !== this.mapStartBasemap) { //based off the agol basemap name this.map.setBasemap(this.mapStartBasemap); } } } } }); });
import faker from 'faker' import React from 'react' import StepTitle from 'src/elements/Step/StepTitle' import * as common from 'test/specs/commonTests' describe('StepTitle', () => { common.isConformant(StepTitle) common.rendersChildren(StepTitle) describe('description prop', () => { it('renders child text', () => { const text = faker.hacker.phrase() shallow(<StepTitle title={text} />) .should.contain.text(text) }) it('renders child node', () => { const child = <div data-child={faker.hacker.noun()} /> shallow(<StepTitle title={child} />) .should.contain(child) }) }) })
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'save', 'bn', { toolbar: 'সংরক্ষন কর' });
// use a already existing formater or fallback to the default v8 formater var defaultFormater = require('./format.js'); // public define API function stackChain() { this.extend = new TraceModifier(); this.filter = new TraceModifier(); this.format = new StackFormater(); this.version = require('./package.json').version; } var SHORTCUT_CALLSITE = false; stackChain.prototype.callSite = function collectCallSites(options) { if (!options) options = {}; // Get CallSites SHORTCUT_CALLSITE = true; var obj = {}; Error.captureStackTrace(obj, collectCallSites); var callSites = obj.stack; SHORTCUT_CALLSITE = false; // Slice callSites = callSites.slice(options.slice || 0); // Modify CallSites if (options.extend) callSites = this.extend._modify(obj, callSites); if (options.filter) callSites = this.filter._modify(obj, callSites); // Done return callSites; }; var chain = new stackChain(); // If a another copy (same version or not) of stack-chain exists it will result // in wrong stack traces (most likely dublicate callSites). if (global._stackChain) { // In case the version match, we can simply return the first initialized copy if (global._stackChain.version === chain.version) { module.exports = global._stackChain; return; // Prevents V8 and Error extentions from being set again } // The version don't match, this is really bad. Lets just throw else { throw new Error('Conflicting version of stack-chain found'); } } // Yay, no other stack-chain copy exists, yet :/ else { module.exports = global._stackChain = chain; } function TraceModifier() { this._modifiers = []; } TraceModifier.prototype._modify = function (error, frames) { for (var i = 0, l = this._modifiers.length; i < l; i++) { frames = this._modifiers[i](error, frames); } return frames; }; TraceModifier.prototype.attach = function (modifier) { this._modifiers.push(modifier); }; TraceModifier.prototype.deattach = function (modifier) { var index = this._modifiers.indexOf(modifier); if (index === -1) return false; this._modifiers.splice(index, 1); return true; }; function StackFormater() { this._formater = defaultFormater; this._previous = undefined; } StackFormater.prototype.replace = function (formater) { if (formater) { this._formater = formater; } else { this.restore(); } }; StackFormater.prototype.restore = function () { this._formater = defaultFormater; }; StackFormater.prototype._backup = function () { if (this._formater === defaultFormater) { this._previous = undefined; } else { this._previous = this._formater; } }; StackFormater.prototype._roolback = function () { this.replace(this._previous); this._previous = undefined; }; // // Set Error.prepareStackTrace thus allowing stack-chain // to take control of the Error().stack formating. // // If there already is a custom stack formater, then set // that as the stack-chain formater. if (Error.prepareStackTrace) { chain.format.replace(Error.prepareStackTrace); } function prepareStackTrace(error, originalFrames) { if (SHORTCUT_CALLSITE) return originalFrames; // Make a loss copy of originalFrames var frames = originalFrames.concat(); // extend frames frames = chain.extend._modify(error, frames); // filter frames frames = chain.filter._modify(error, frames); // reduce frames to match Error.stackTraceLimit frames = frames.slice(0, Error.stackTraceLimit); // Set the callSite property // But only if it havn't been explicitly set, otherwise // error.stack would have unintended side effects if (Object.getOwnPropertyDescriptor(error, "callSite") === undefined) { error.callSite = { original: originalFrames, mutated: frames }; } // format frames return chain.format._formater(error, frames); } // Replace the v8 stack trace creator Object.defineProperty(Error, 'prepareStackTrace', { 'get': function () { return prepareStackTrace; }, 'set': function (formater) { // If formater is prepareStackTrace it means that someone ran // var old = Error.prepareStackTrace; // Error.prepareStackTrace = custom // new Error().stack // Error.prepareStackTrace = old; // The effect of this, should be that the old behaviour is restored. if (formater === prepareStackTrace) { chain.format._roolback(); } // Error.prepareStackTrace was set, this means that someone is // trying to take control of the Error().stack format. Make // them belive they succeeded by setting them up as the stack-chain // formater. else { chain.format._backup(); chain.format.replace(formater); } } }); // // Manage call site storeage // function callSiteGetter() { // calculate call site object this.stack; // return call site object return this.callSite; } Object.defineProperty(Error.prototype, 'callSite', { 'get': callSiteGetter, 'set': function (frames) { // In case callSite was set before [[getter]], just set // the value Object.defineProperty(this, 'callSite', { value: frames, writable: true, configurable: true }); }, configurable: true });
/* 8. Write an expression that calculates trapezoid's area by given sides a and b and height h. */ taskName = "8. Calculate trapezoid area"; function Main(bufferElement) { var a = ReadLine("a = ", GetRandomFloat(0, 10, 3)); var b = ReadLine("b = ", GetRandomFloat(0, 10, 3)); var height = ReadLine("height = ", GetRandomFloat(0, 10, 3)); SetSolveButton(function() { ConsoleClear(); WriteLine(Format("Trapezoid area is: {0} units", calculateTrapezoidArea(a.value, b.value, height.value).toFixed(5))); }); } function calculateTrapezoidArea(a, b, height) { a = parseFloat(a); b = parseFloat(b); height = parseFloat(height); return (a + b) / 2 * height; }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > If Result(3).type is not normal, then Result(3).type must be throw. Throw Result(3).value as an exception es5id: 15.1.2.1_A3.3_T2 description: Break statement ---*/ //CHECK#1 try { eval("break;"); $ERROR('#1.1: break must throw SyntaxError. Actual: ' + (eval("break;"))); } catch(e) { if ((e instanceof SyntaxError) !== true) { $ERROR('#1.2: break must throw SyntaxError. Actual: ' + (e)); } } //CHECK#2 try { for (var i = 0; i <= 1; i++) { for (var j = 0; j <= 1; j++) { eval("break;"); } } $ERROR('#2.1: break must throw SyntaxError. Actual: ' + (eval("break;"))); } catch(e) { if ((e instanceof SyntaxError) !== true) { $ERROR('#2.2: break must throw SyntaxError. Actual: ' + (e)); } }
'use strict' module.exports = options => options && options.Promise || require('bluebird')
angular.module('umbraco.services') .factory('userService', function ($rootScope, eventsService, $q, $location, $log, securityRetryQueue, authResource, assetsService, dialogService, $timeout, angularHelper, $http, javascriptLibraryService) { var currentUser = null; var lastUserId = null; var loginDialog = null; //this tracks the last date/time that the user's remainingAuthSeconds was updated from the server // this is used so that we know when to go and get the user's remaining seconds directly. var lastServerTimeoutSet = null; function openLoginDialog(isTimedOut) { if (!loginDialog) { loginDialog = dialogService.open({ //very special flag which means that global events cannot close this dialog manualClose: true, template: 'views/common/dialogs/login.html', modalClass: "login-overlay", animation: "slide", show: true, callback: onLoginDialogClose, dialogData: { isTimedOut: isTimedOut } }); } } function onLoginDialogClose(success) { loginDialog = null; if (success) { securityRetryQueue.retryAll(currentUser.name); } else { securityRetryQueue.cancelAll(); $location.path('/'); } } /** This methods will set the current user when it is resolved and will then start the counter to count in-memory how many seconds they have remaining on the auth session */ function setCurrentUser(usr) { if (!usr.remainingAuthSeconds) { throw "The user object is invalid, the remainingAuthSeconds is required."; } currentUser = usr; lastServerTimeoutSet = new Date(); //start the timer countdownUserTimeout(); } /** Method to count down the current user's timeout seconds, this will continually count down their current remaining seconds every 5 seconds until there are no more seconds remaining. */ function countdownUserTimeout() { $timeout(function () { if (currentUser) { //countdown by 5 seconds since that is how long our timer is for. currentUser.remainingAuthSeconds -= 5; //if there are more than 30 remaining seconds, recurse! if (currentUser.remainingAuthSeconds > 30) { //we need to check when the last time the timeout was set from the server, if // it has been more than 30 seconds then we'll manually go and retrieve it from the // server - this helps to keep our local countdown in check with the true timeout. if (lastServerTimeoutSet != null) { var now = new Date(); var seconds = (now.getTime() - lastServerTimeoutSet.getTime()) / 1000; if (seconds > 30) { //first we'll set the lastServerTimeoutSet to null - this is so we don't get back in to this loop while we // wait for a response from the server otherwise we'll be making double/triple/etc... calls while we wait. lastServerTimeoutSet = null; //now go get it from the server //NOTE: the safeApply because our timeout is set to not run digests (performance reasons) angularHelper.safeApply($rootScope, function () { authResource.getRemainingTimeoutSeconds().then(function (result) { setUserTimeoutInternal(result); }); }); } } //recurse the countdown! countdownUserTimeout(); } else { //we are either timed out or very close to timing out so we need to show the login dialog. if (Umbraco.Sys.ServerVariables.umbracoSettings.keepUserLoggedIn !== true) { //NOTE: the safeApply because our timeout is set to not run digests (performance reasons) angularHelper.safeApply($rootScope, function () { try { //NOTE: We are calling this again so that the server can create a log that the timeout has expired, we // don't actually care about this result. authResource.getRemainingTimeoutSeconds(); } finally { userAuthExpired(); } }); } else { //we've got less than 30 seconds remaining so let's check the server if (lastServerTimeoutSet != null) { //first we'll set the lastServerTimeoutSet to null - this is so we don't get back in to this loop while we // wait for a response from the server otherwise we'll be making double/triple/etc... calls while we wait. lastServerTimeoutSet = null; //now go get it from the server //NOTE: the safeApply because our timeout is set to not run digests (performance reasons) angularHelper.safeApply($rootScope, function () { authResource.getRemainingTimeoutSeconds().then(function (result) { setUserTimeoutInternal(result); }); }); } //recurse the countdown! countdownUserTimeout(); } } } }, 5000, //every 5 seconds false); //false = do NOT execute a digest for every iteration } /** Called to update the current user's timeout */ function setUserTimeoutInternal(newTimeout) { var asNumber = parseFloat(newTimeout); if (!isNaN(asNumber) && currentUser && angular.isNumber(asNumber)) { currentUser.remainingAuthSeconds = newTimeout; lastServerTimeoutSet = new Date(); } } /** resets all user data, broadcasts the notAuthenticated event and shows the login dialog */ function userAuthExpired(isLogout) { //store the last user id and clear the user if (currentUser && currentUser.id !== undefined) { lastUserId = currentUser.id; } if (currentUser) { currentUser.remainingAuthSeconds = 0; } lastServerTimeoutSet = null; currentUser = null; //broadcast a global event that the user is no longer logged in eventsService.emit("app.notAuthenticated"); openLoginDialog(isLogout === undefined ? true : !isLogout); } // Register a handler for when an item is added to the retry queue securityRetryQueue.onItemAddedCallbacks.push(function (retryItem) { if (securityRetryQueue.hasMore()) { userAuthExpired(); } }); return { /** Internal method to display the login dialog */ _showLoginDialog: function () { openLoginDialog(); }, /** Returns a promise, sends a request to the server to check if the current cookie is authorized */ isAuthenticated: function () { //if we've got a current user then just return true if (currentUser) { var deferred = $q.defer(); deferred.resolve(true); return deferred.promise; } return authResource.isAuthenticated(); }, /** Returns a promise, sends a request to the server to validate the credentials */ authenticate: function (login, password) { return authResource.performLogin(login, password) .then(this.setAuthenticationSuccessful); }, setAuthenticationSuccessful: function (data) { //when it's successful, return the user data setCurrentUser(data); var result = { user: data, authenticated: true, lastUserId: lastUserId, loginType: "credentials" }; //broadcast a global event eventsService.emit("app.authenticated", result); return result; }, /** Logs the user out */ logout: function () { return authResource.performLogout() .then(function (data) { userAuthExpired(); //done! return null; }); }, /** Refreshes the current user data with the data stored for the user on the server and returns it */ refreshCurrentUser: function () { var deferred = $q.defer(); authResource.getCurrentUser() .then(function (data) { var result = { user: data, authenticated: true, lastUserId: lastUserId, loginType: "implicit" }; setCurrentUser(data); deferred.resolve(currentUser); }, function () { //it failed, so they are not logged in deferred.reject(); }); return deferred.promise; }, /** Returns the current user object in a promise */ getCurrentUser: function (args) { var deferred = $q.defer(); if (!currentUser) { authResource.getCurrentUser() .then(function (data) { var result = { user: data, authenticated: true, lastUserId: lastUserId, loginType: "implicit" }; if (args && args.broadcastEvent) { //broadcast a global event, will inform listening controllers to load in the user specific data eventsService.emit("app.authenticated", result); } setCurrentUser(data); deferred.resolve(currentUser); }, function () { //it failed, so they are not logged in deferred.reject(); }); } else { deferred.resolve(currentUser); } return deferred.promise; }, /** Loads the Moment.js Locale for the current user. */ loadMomentLocaleForCurrentUser: function () { function loadLocales(currentUser, supportedLocales) { var locale = currentUser.locale.toLowerCase(); if (locale !== 'en-us') { var localeUrls = []; if (supportedLocales.indexOf(locale + '.js') > -1) { localeUrls.push('lib/moment/' + locale + '.js'); } if (locale.indexOf('-') > -1) { var majorLocale = locale.split('-')[0] + '.js'; if (supportedLocales.indexOf(majorLocale) > -1) { localeUrls.push('lib/moment/' + majorLocale); } } return assetsService.load(localeUrls, $rootScope); } else { //return a noop promise var deferred = $q.defer(); var promise = deferred.promise; deferred.resolve(true); return promise; } } var promises = { currentUser: this.getCurrentUser(), supportedLocales: javascriptLibraryService.getSupportedLocalesForMoment() } return $q.all(promises).then(function (values) { return loadLocales(values.currentUser, values.supportedLocales); }); }, /** Called whenever a server request is made that contains a x-umb-user-seconds response header for which we can update the user's remaining timeout seconds */ setUserTimeout: function (newTimeout) { setUserTimeoutInternal(newTimeout); } }; });
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var Stylis = _interopDefault(require('stylis/stylis.min')); var _insertRulePlugin = _interopDefault(require('stylis-rule-sheet')); var React = require('react'); var React__default = _interopDefault(React); var reactIs = require('react-is'); var memoize = _interopDefault(require('memoize-one')); var PropTypes = _interopDefault(require('prop-types')); var ReactDOM = _interopDefault(require('react-dom')); var validAttr = _interopDefault(require('@emotion/is-prop-valid')); // var interleave = (function (strings, interpolations) { var result = [strings[0]]; for (var i = 0, len = interpolations.length; i < len; i += 1) { result.push(interpolations[i], strings[i + 1]); } return result; }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; // var isPlainObject = (function (x) { return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && x.constructor === Object; }); // var EMPTY_ARRAY = Object.freeze([]); var EMPTY_OBJECT = Object.freeze({}); // function isFunction(test) { return typeof test === 'function'; } // function getComponentName(target) { return target.displayName || target.name || 'Component'; } // function isStyledComponent(target) { return target && typeof target.styledComponentId === 'string'; } // var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled'; var SC_VERSION_ATTR = 'data-styled-version'; var SC_STREAM_ATTR = 'data-styled-streamed'; var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window; var DISABLE_SPEEDY = process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles var STATIC_EXECUTION_CONTEXT = {}; // /** * Parse errors.md and turn it into a simple hash of code: message */ var ERRORS = process.env.NODE_ENV !== 'production' ? { "1": "Cannot create styled-component for component: %s.\n\n", "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n", "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n", "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n", "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n", "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n", "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n", "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n", "9": "Missing document `<head>`\n\n", "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n", "11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n", "12": "It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper (see https://www.styled-components.com/docs/api#css), which ensures the styles are injected correctly.\n" } : {}; /** * super basic version of sprintf */ function format() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var a = args[0]; var b = []; var c = void 0; for (c = 1; c < args.length; c += 1) { b.push(args[c]); } b.forEach(function (d) { a = a.replace(/%[a-z]/, d); }); return a; } /** * Create an error file out of errors.md for development and a simple web link to the full errors * in production mode. */ var StyledComponentsError = function (_Error) { inherits(StyledComponentsError, _Error); function StyledComponentsError(code) { classCallCheck(this, StyledComponentsError); for (var _len2 = arguments.length, interpolations = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { interpolations[_key2 - 1] = arguments[_key2]; } if (process.env.NODE_ENV === 'production') { var _this = possibleConstructorReturn(this, _Error.call(this, 'An error occurred. See https://github.com/styled-components/styled-components/blob/master/src/utils/errors.md#' + code + ' for more information. ' + (interpolations ? 'Additional arguments: ' + interpolations.join(', ') : ''))); } else { var _this = possibleConstructorReturn(this, _Error.call(this, format.apply(undefined, [ERRORS[code]].concat(interpolations)).trim())); } return possibleConstructorReturn(_this); } return StyledComponentsError; }(Error); // var SC_COMPONENT_ID = /^[^\S\n]*?\/\* sc-component-id:\s*(\S+)\s+\*\//gm; var extractComps = (function (maybeCSS) { var css = '' + (maybeCSS || ''); // Definitely a string, and a clone var existingComponents = []; css.replace(SC_COMPONENT_ID, function (match, componentId, matchIndex) { existingComponents.push({ componentId: componentId, matchIndex: matchIndex }); return match; }); return existingComponents.map(function (_ref, i) { var componentId = _ref.componentId, matchIndex = _ref.matchIndex; var nextComp = existingComponents[i + 1]; var cssFromDOM = nextComp ? css.slice(matchIndex, nextComp.matchIndex) : css.slice(matchIndex); return { componentId: componentId, cssFromDOM: cssFromDOM }; }); }); // var COMMENT_REGEX = /^\s*\/\/.*$/gm; // NOTE: This stylis instance is only used to split rules from SSR'd style tags var stylisSplitter = new Stylis({ global: false, cascade: true, keyframe: false, prefix: false, compress: false, semicolon: true }); var stylis = new Stylis({ global: false, cascade: true, keyframe: false, prefix: true, compress: false, semicolon: false // NOTE: This means "autocomplete missing semicolons" }); // Wrap `insertRulePlugin to build a list of rules, // and then make our own plugin to return the rules. This // makes it easier to hook into the existing SSR architecture var parsingRules = []; // eslint-disable-next-line consistent-return var returnRulesPlugin = function returnRulesPlugin(context) { if (context === -2) { var parsedRules = parsingRules; parsingRules = []; return parsedRules; } }; var parseRulesPlugin = _insertRulePlugin(function (rule) { parsingRules.push(rule); }); var _componentId = void 0; var _selector = void 0; var _selectorRegexp = void 0; var selfReferenceReplacer = function selfReferenceReplacer(match, offset, string) { if ( // the first self-ref is always untouched offset > 0 && // there should be at least two self-refs to do a replacement (.b > .b) string.slice(0, offset).indexOf(_selector) !== -1 && // no consecutive self refs (.b.b); that is a precedence boost and treated differently string.slice(offset - _selector.length, offset) !== _selector) { return '.' + _componentId; } return match; }; /** * When writing a style like * * & + & { * color: red; * } * * The second ampersand should be a reference to the static component class. stylis * has no knowledge of static class so we have to intelligently replace the base selector. */ var selfReferenceReplacementPlugin = function selfReferenceReplacementPlugin(context, _, selectors) { if (context === 2 && selectors[0].lastIndexOf(_selector) > 0) { // eslint-disable-next-line no-param-reassign selectors[0] = selectors[0].replace(_selectorRegexp, selfReferenceReplacer); } }; stylis.use([selfReferenceReplacementPlugin, parseRulesPlugin, returnRulesPlugin]); stylisSplitter.use([parseRulesPlugin, returnRulesPlugin]); var splitByRules = function splitByRules(css) { return stylisSplitter('', css); }; function stringifyRules(rules, selector, prefix) { var componentId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '&'; var flatCSS = rules.join('').replace(COMMENT_REGEX, ''); // replace JS comments var cssStr = selector && prefix ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS; // stylis has no concept of state to be passed to plugins // but since JS is single=threaded, we can rely on that to ensure // these properties stay in sync with the current stylis run _componentId = componentId; _selector = selector; _selectorRegexp = new RegExp('\\' + _selector + '\\b', 'g'); return stylis(prefix || !selector ? '' : selector, cssStr); } // /* eslint-disable camelcase, no-undef */ var getNonce = (function () { return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null; }); // // Helper to call a given function, only once var once = (function (cb) { var called = false; return function () { if (!called) { called = true; cb(); } }; }); // /* These are helpers for the StyleTags to keep track of the injected * rule names for each (component) ID that they're keeping track of. * They're crucial for detecting whether a name has already been * injected. * (This excludes rehydrated names) */ /* adds a new ID:name pairing to a names dictionary */ var addNameForId = function addNameForId(names, id, name) { if (name) { // eslint-disable-next-line no-param-reassign var namesForId = names[id] || (names[id] = Object.create(null)); namesForId[name] = true; } }; /* resets an ID entirely by overwriting it in the dictionary */ var resetIdNames = function resetIdNames(names, id) { // eslint-disable-next-line no-param-reassign names[id] = Object.create(null); }; /* factory for a names dictionary checking the existance of an ID:name pairing */ var hasNameForId = function hasNameForId(names) { return function (id, name) { return names[id] !== undefined && names[id][name]; }; }; /* stringifies names for the html/element output */ var stringifyNames = function stringifyNames(names) { var str = ''; // eslint-disable-next-line guard-for-in for (var id in names) { str += Object.keys(names[id]).join(' ') + ' '; } return str.trim(); }; /* clones the nested names dictionary */ var cloneNames = function cloneNames(names) { var clone = Object.create(null); // eslint-disable-next-line guard-for-in for (var id in names) { clone[id] = _extends({}, names[id]); } return clone; }; // /* These are helpers that deal with the insertRule (aka speedy) API * They are used in the StyleTags and specifically the speedy tag */ /* retrieve a sheet for a given style tag */ var sheetForTag = function sheetForTag(tag) { // $FlowFixMe if (tag.sheet) return tag.sheet; /* Firefox quirk requires us to step through all stylesheets to find one owned by the given tag */ var size = document.styleSheets.length; for (var i = 0; i < size; i += 1) { var sheet = document.styleSheets[i]; // $FlowFixMe if (sheet.ownerNode === tag) return sheet; } /* we should always be able to find a tag */ throw new StyledComponentsError(10); }; /* insert a rule safely and return whether it was actually injected */ var safeInsertRule = function safeInsertRule(sheet, cssRule, index) { /* abort early if cssRule string is falsy */ if (!cssRule) return false; var maxIndex = sheet.cssRules.length; try { /* use insertRule and cap passed index with maxIndex (no of cssRules) */ sheet.insertRule(cssRule, index <= maxIndex ? index : maxIndex); } catch (err) { /* any error indicates an invalid rule */ return false; } return true; }; /* deletes `size` rules starting from `removalIndex` */ var deleteRules = function deleteRules(sheet, removalIndex, size) { var lowerBound = removalIndex - size; for (var i = removalIndex; i > lowerBound; i -= 1) { sheet.deleteRule(i); } }; // /* this marker separates component styles and is important for rehydration */ var makeTextMarker = function makeTextMarker(id) { return '\n/* sc-component-id: ' + id + ' */\n'; }; /* add up all numbers in array up until and including the index */ var addUpUntilIndex = function addUpUntilIndex(sizes, index) { var totalUpToIndex = 0; for (var i = 0; i <= index; i += 1) { totalUpToIndex += sizes[i]; } return totalUpToIndex; }; /* create a new style tag after lastEl */ var makeStyleTag = function makeStyleTag(target, tagEl, insertBefore) { var el = document.createElement('style'); el.setAttribute(SC_ATTR, ''); el.setAttribute(SC_VERSION_ATTR, "4.0.1-0"); var nonce = getNonce(); if (nonce) { el.setAttribute('nonce', nonce); } /* Work around insertRule quirk in EdgeHTML */ el.appendChild(document.createTextNode('')); if (target && !tagEl) { /* Append to target when no previous element was passed */ target.appendChild(el); } else { if (!tagEl || !target || !tagEl.parentNode) { throw new StyledComponentsError(6); } /* Insert new style tag after the previous one */ tagEl.parentNode.insertBefore(el, insertBefore ? tagEl : tagEl.nextSibling); } return el; }; /* takes a css factory function and outputs an html styled tag factory */ var wrapAsHtmlTag = function wrapAsHtmlTag(css, names) { return function (additionalAttrs) { var nonce = getNonce(); var attrs = [nonce && 'nonce="' + nonce + '"', SC_ATTR + '="' + stringifyNames(names) + '"', SC_VERSION_ATTR + '="' + "4.0.1-0" + '"', additionalAttrs]; var htmlAttr = attrs.filter(Boolean).join(' '); return '<style ' + htmlAttr + '>' + css() + '</style>'; }; }; /* takes a css factory function and outputs an element factory */ var wrapAsElement = function wrapAsElement(css, names) { return function () { var _props; var props = (_props = {}, _props[SC_ATTR] = stringifyNames(names), _props[SC_VERSION_ATTR] = "4.0.1-0", _props); var nonce = getNonce(); if (nonce) { // $FlowFixMe props.nonce = nonce; } // eslint-disable-next-line react/no-danger return React__default.createElement('style', _extends({}, props, { dangerouslySetInnerHTML: { __html: css() } })); }; }; var getIdsFromMarkersFactory = function getIdsFromMarkersFactory(markers) { return function () { return Object.keys(markers); }; }; /* speedy tags utilise insertRule */ var makeSpeedyTag = function makeSpeedyTag(el, getImportRuleTag) { var names = Object.create(null); var markers = Object.create(null); var sizes = []; var extractImport = getImportRuleTag !== undefined; /* indicates whther getImportRuleTag was called */ var usedImportRuleTag = false; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } markers[id] = sizes.length; sizes.push(0); resetIdNames(names, id); return markers[id]; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); var sheet = sheetForTag(el); var insertIndex = addUpUntilIndex(sizes, marker); var injectedRules = 0; var importRules = []; var cssRulesSize = cssRules.length; for (var i = 0; i < cssRulesSize; i += 1) { var cssRule = cssRules[i]; var mayHaveImport = extractImport; /* @import rules are reordered to appear first */ if (mayHaveImport && cssRule.indexOf('@import') !== -1) { importRules.push(cssRule); } else if (safeInsertRule(sheet, cssRule, insertIndex + injectedRules)) { mayHaveImport = false; injectedRules += 1; } } if (extractImport && importRules.length > 0) { usedImportRuleTag = true; // $FlowFixMe getImportRuleTag().insertRules(id + '-import', importRules); } sizes[marker] += injectedRules; /* add up no of injected rules */ addNameForId(names, id, name); }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; var size = sizes[marker]; var sheet = sheetForTag(el); var removalIndex = addUpUntilIndex(sizes, marker) - 1; deleteRules(sheet, removalIndex, size); sizes[marker] = 0; resetIdNames(names, id); if (extractImport && usedImportRuleTag) { // $FlowFixMe getImportRuleTag().removeRules(id + '-import'); } }; var css = function css() { var _sheetForTag = sheetForTag(el), cssRules = _sheetForTag.cssRules; var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { str += makeTextMarker(id); var marker = markers[id]; var end = addUpUntilIndex(sizes, marker); var size = sizes[marker]; for (var i = end - size; i < end; i += 1) { var rule = cssRules[i]; if (rule !== undefined) { str += rule.cssText; } } } return str; }; return { clone: function clone() { throw new StyledComponentsError(5); }, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: el, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; }; var makeTextNode = function makeTextNode(id) { return document.createTextNode(makeTextMarker(id)); }; var makeBrowserTag = function makeBrowserTag(el, getImportRuleTag) { var names = Object.create(null); var markers = Object.create(null); var extractImport = getImportRuleTag !== undefined; /* indicates whther getImportRuleTag was called */ var usedImportRuleTag = false; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } markers[id] = makeTextNode(id); el.appendChild(markers[id]); names[id] = Object.create(null); return markers[id]; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); var importRules = []; var cssRulesSize = cssRules.length; for (var i = 0; i < cssRulesSize; i += 1) { var rule = cssRules[i]; var mayHaveImport = extractImport; if (mayHaveImport && rule.indexOf('@import') !== -1) { importRules.push(rule); } else { mayHaveImport = false; var separator = i === cssRulesSize - 1 ? '' : ' '; marker.appendData('' + rule + separator); } } addNameForId(names, id, name); if (extractImport && importRules.length > 0) { usedImportRuleTag = true; // $FlowFixMe getImportRuleTag().insertRules(id + '-import', importRules); } }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; /* create new empty text node and replace the current one */ var newMarker = makeTextNode(id); el.replaceChild(newMarker, marker); markers[id] = newMarker; resetIdNames(names, id); if (extractImport && usedImportRuleTag) { // $FlowFixMe getImportRuleTag().removeRules(id + '-import'); } }; var css = function css() { var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { str += markers[id].data; } return str; }; return { clone: function clone() { throw new StyledComponentsError(5); }, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: el, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; }; var makeServerTag = function makeServerTag(namesArg, markersArg) { var names = namesArg === undefined ? Object.create(null) : namesArg; var markers = markersArg === undefined ? Object.create(null) : markersArg; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } return markers[id] = ['']; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); marker[0] += cssRules.join(' '); addNameForId(names, id, name); }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; marker[0] = ''; resetIdNames(names, id); }; var css = function css() { var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { var cssForId = markers[id][0]; if (cssForId) { str += makeTextMarker(id) + cssForId; } } return str; }; var clone = function clone() { var namesClone = cloneNames(names); var markersClone = Object.create(null); // eslint-disable-next-line guard-for-in for (var id in markers) { markersClone[id] = [markers[id][0]]; } return makeServerTag(namesClone, markersClone); }; var tag = { clone: clone, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: null, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; return tag; }; var makeTag = function makeTag(target, tagEl, forceServer, insertBefore, getImportRuleTag) { if (IS_BROWSER && !forceServer) { var el = makeStyleTag(target, tagEl, insertBefore); if (DISABLE_SPEEDY) { return makeBrowserTag(el, getImportRuleTag); } else { return makeSpeedyTag(el, getImportRuleTag); } } return makeServerTag(); }; /* wraps a given tag so that rehydration is performed once when necessary */ var makeRehydrationTag = function makeRehydrationTag(tag, els, extracted, immediateRehydration) { /* rehydration function that adds all rules to the new tag */ var rehydrate = once(function () { /* add all extracted components to the new tag */ for (var i = 0, len = extracted.length; i < len; i += 1) { var _extracted$i = extracted[i], componentId = _extracted$i.componentId, cssFromDOM = _extracted$i.cssFromDOM; var cssRules = splitByRules(cssFromDOM); tag.insertRules(componentId, cssRules); } /* remove old HTMLStyleElements, since they have been rehydrated */ for (var _i = 0, _len = els.length; _i < _len; _i += 1) { var el = els[_i]; if (el.parentNode) { el.parentNode.removeChild(el); } } }); if (immediateRehydration) rehydrate(); return _extends({}, tag, { /* add rehydration hook to methods */ insertMarker: function insertMarker(id) { rehydrate(); return tag.insertMarker(id); }, insertRules: function insertRules(id, cssRules, name) { rehydrate(); return tag.insertRules(id, cssRules, name); }, removeRules: function removeRules(id) { rehydrate(); return tag.removeRules(id); } }); }; // var SPLIT_REGEX = /\s+/; /* determine the maximum number of components before tags are sharded */ var MAX_SIZE = void 0; if (IS_BROWSER) { /* in speedy mode we can keep a lot more rules in a sheet before a slowdown can be expected */ MAX_SIZE = DISABLE_SPEEDY ? 40 : 1000; } else { /* for servers we do not need to shard at all */ MAX_SIZE = -1; } var sheetRunningId = 0; var master = void 0; var StyleSheet = function () { /* a map from ids to tags */ /* deferred rules for a given id */ /* this is used for not reinjecting rules via hasNameForId() */ /* when rules for an id are removed using remove() we have to ignore rehydratedNames for it */ /* a list of tags belonging to this StyleSheet */ /* a tag for import rules */ /* current capacity until a new tag must be created */ /* children (aka clones) of this StyleSheet inheriting all and future injections */ function StyleSheet() { var _this = this; var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : IS_BROWSER ? document.head : null; var forceServer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; classCallCheck(this, StyleSheet); this.getImportRuleTag = function () { var importRuleTag = _this.importRuleTag; if (importRuleTag !== undefined) { return importRuleTag; } var firstTag = _this.tags[0]; var insertBefore = true; return _this.importRuleTag = makeTag(_this.target, firstTag ? firstTag.styleTag : null, _this.forceServer, insertBefore); }; sheetRunningId += 1; this.id = sheetRunningId; this.forceServer = forceServer; this.target = forceServer ? null : target; this.tagMap = {}; this.deferred = {}; this.rehydratedNames = {}; this.ignoreRehydratedNames = {}; this.tags = []; this.capacity = 1; this.clones = []; } /* rehydrate all SSR'd style tags */ StyleSheet.prototype.rehydrate = function rehydrate() { if (!IS_BROWSER || this.forceServer) { return this; } var els = []; var extracted = []; var isStreamed = false; /* retrieve all of our SSR style elements from the DOM */ var nodes = document.querySelectorAll('style[' + SC_ATTR + '][' + SC_VERSION_ATTR + '="' + "4.0.1-0" + '"]'); var nodesSize = nodes.length; /* abort rehydration if no previous style tags were found */ if (nodesSize === 0) { return this; } for (var i = 0; i < nodesSize; i += 1) { // $FlowFixMe: We can trust that all elements in this query are style elements var el = nodes[i]; /* check if style tag is a streamed tag */ if (!isStreamed) isStreamed = !!el.getAttribute(SC_STREAM_ATTR); /* retrieve all component names */ var elNames = (el.getAttribute(SC_ATTR) || '').trim().split(SPLIT_REGEX); var elNamesSize = elNames.length; for (var j = 0; j < elNamesSize; j += 1) { var name = elNames[j]; /* add rehydrated name to sheet to avoid readding styles */ this.rehydratedNames[name] = true; } /* extract all components and their CSS */ extracted.push.apply(extracted, extractComps(el.textContent)); /* store original HTMLStyleElement */ els.push(el); } /* abort rehydration if nothing was extracted */ var extractedSize = extracted.length; if (extractedSize === 0) { return this; } /* create a tag to be used for rehydration */ var tag = this.makeTag(null); var rehydrationTag = makeRehydrationTag(tag, els, extracted, isStreamed); /* reset capacity and adjust MAX_SIZE by the initial size of the rehydration */ this.capacity = Math.max(1, MAX_SIZE - extractedSize); this.tags.push(rehydrationTag); /* retrieve all component ids */ for (var _j = 0; _j < extractedSize; _j += 1) { this.tagMap[extracted[_j].componentId] = rehydrationTag; } return this; }; /* retrieve a "master" instance of StyleSheet which is typically used when no other is available * The master StyleSheet is targeted by createGlobalStyle, keyframes, and components outside of any * StyleSheetManager's context */ /* reset the internal "master" instance */ StyleSheet.reset = function reset() { var forceServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; master = new StyleSheet(undefined, forceServer).rehydrate(); }; /* adds "children" to the StyleSheet that inherit all of the parents' rules * while their own rules do not affect the parent */ StyleSheet.prototype.clone = function clone() { var sheet = new StyleSheet(this.target, this.forceServer); /* add to clone array */ this.clones.push(sheet); /* clone all tags */ sheet.tags = this.tags.map(function (tag) { var ids = tag.getIds(); var newTag = tag.clone(); /* reconstruct tagMap */ for (var i = 0; i < ids.length; i += 1) { sheet.tagMap[ids[i]] = newTag; } return newTag; }); /* clone other maps */ sheet.rehydratedNames = _extends({}, this.rehydratedNames); sheet.deferred = _extends({}, this.deferred); return sheet; }; /* force StyleSheet to create a new tag on the next injection */ StyleSheet.prototype.sealAllTags = function sealAllTags() { this.capacity = 1; this.tags.forEach(function (tag) { // eslint-disable-next-line no-param-reassign tag.sealed = true; }); }; StyleSheet.prototype.makeTag = function makeTag$$1(tag) { var lastEl = tag ? tag.styleTag : null; var insertBefore = false; return makeTag(this.target, lastEl, this.forceServer, insertBefore, this.getImportRuleTag); }; /* get a tag for a given componentId, assign the componentId to one, or shard */ StyleSheet.prototype.getTagForId = function getTagForId(id) { /* simply return a tag, when the componentId was already assigned one */ var prev = this.tagMap[id]; if (prev !== undefined && !prev.sealed) { return prev; } var tag = this.tags[this.tags.length - 1]; /* shard (create a new tag) if the tag is exhausted (See MAX_SIZE) */ this.capacity -= 1; if (this.capacity === 0) { this.capacity = MAX_SIZE; tag = this.makeTag(tag); this.tags.push(tag); } return this.tagMap[id] = tag; }; /* mainly for createGlobalStyle to check for its id */ StyleSheet.prototype.hasId = function hasId(id) { return this.tagMap[id] !== undefined; }; /* caching layer checking id+name to already have a corresponding tag and injected rules */ StyleSheet.prototype.hasNameForId = function hasNameForId(id, name) { /* exception for rehydrated names which are checked separately */ if (this.ignoreRehydratedNames[id] === undefined && this.rehydratedNames[name]) { return true; } var tag = this.tagMap[id]; return tag !== undefined && tag.hasNameForId(id, name); }; /* registers a componentId and registers it on its tag */ StyleSheet.prototype.deferredInject = function deferredInject(id, cssRules) { /* don't inject when the id is already registered */ if (this.tagMap[id] !== undefined) return; var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].deferredInject(id, cssRules); } this.getTagForId(id).insertMarker(id); this.deferred[id] = cssRules; }; /* injects rules for a given id with a name that will need to be cached */ StyleSheet.prototype.inject = function inject(id, cssRules, name) { var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].inject(id, cssRules, name); } var tag = this.getTagForId(id); /* add deferred rules for component */ if (this.deferred[id] !== undefined) { // Combine passed cssRules with previously deferred CSS rules // NOTE: We cannot mutate the deferred array itself as all clones // do the same (see clones[i].inject) var rules = this.deferred[id].concat(cssRules); tag.insertRules(id, rules, name); this.deferred[id] = undefined; } else { tag.insertRules(id, cssRules, name); } }; /* removes all rules for a given id, which doesn't remove its marker but resets it */ StyleSheet.prototype.remove = function remove(id) { var tag = this.tagMap[id]; if (tag === undefined) return; var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].remove(id); } /* remove all rules from the tag */ tag.removeRules(id); /* ignore possible rehydrated names */ this.ignoreRehydratedNames[id] = true; /* delete possible deferred rules */ this.deferred[id] = undefined; }; StyleSheet.prototype.toHTML = function toHTML() { return this.tags.map(function (tag) { return tag.toHTML(); }).join(''); }; StyleSheet.prototype.toReactElements = function toReactElements() { var id = this.id; return this.tags.map(function (tag, i) { var key = 'sc-' + id + '-' + i; return React.cloneElement(tag.toElement(), { key: key }); }); }; createClass(StyleSheet, null, [{ key: 'master', get: function get$$1() { return master || (master = new StyleSheet().rehydrate()); } /* NOTE: This is just for backwards-compatibility with jest-styled-components */ }, { key: 'instance', get: function get$$1() { return StyleSheet.master; } }]); return StyleSheet; }(); // var Keyframes = function () { function Keyframes(name, rules) { var _this = this; classCallCheck(this, Keyframes); this.inject = function (styleSheet) { if (!styleSheet.hasNameForId(_this.id, _this.name)) { styleSheet.inject(_this.id, _this.rules, _this.name); } }; this.toString = function () { throw new StyledComponentsError(12, String(_this.name)); }; this.name = name; this.rules = rules; this.id = 'sc-keyframes-' + name; } Keyframes.prototype.getName = function getName() { return this.name; }; return Keyframes; }(); // /** * inlined version of * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js */ var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } // var objToCss = function objToCss(obj, prevKey) { var css = Object.keys(obj).filter(function (key) { var chunk = obj[key]; return chunk !== undefined && chunk !== null && chunk !== false && chunk !== ''; }).map(function (key) { if (isPlainObject(obj[key])) return objToCss(obj[key], key); return hyphenateStyleName(key) + ': ' + obj[key] + ';'; }).join(' '); return prevKey ? prevKey + ' {\n ' + css + '\n}' : css; }; /** * It's falsish not falsy because 0 is allowed. */ var isFalsish = function isFalsish(chunk) { return chunk === undefined || chunk === null || chunk === false || chunk === ''; }; function flatten(chunk, executionContext, styleSheet) { if (Array.isArray(chunk)) { var ruleSet = []; for (var i = 0, len = chunk.length, result; i < len; i += 1) { result = flatten(chunk[i], executionContext, styleSheet); if (result === null) continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result); } return ruleSet; } if (isFalsish(chunk)) { return null; } /* Handle other components */ if (isStyledComponent(chunk)) { return '.' + chunk.styledComponentId; } /* Either execute or defer the function */ if (isFunction(chunk)) { if (executionContext) { if (process.env.NODE_ENV !== 'production') { /* Warn if not referring styled component */ try { // eslint-disable-next-line new-cap if (reactIs.isElement(new chunk(executionContext))) { console.warn(getComponentName(chunk) + ' is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.'); } // eslint-disable-next-line no-empty } catch (e) {} } return flatten(chunk(executionContext), executionContext, styleSheet); } else return chunk; } if (chunk instanceof Keyframes) { if (styleSheet) { chunk.inject(styleSheet); return chunk.getName(); } else return chunk; } /* Handle objects */ return isPlainObject(chunk) ? objToCss(chunk) : chunk.toString(); } // function css(styles) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (isFunction(styles) || isPlainObject(styles)) { // $FlowFixMe return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations))); } // $FlowFixMe return flatten(interleave(styles, interpolations)); } // function constructWithOptions(componentConstructor, tag) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT; if (!reactIs.isValidElementType(tag)) { throw new StyledComponentsError(1, String(tag)); } /* This is callable directly as a template function */ // $FlowFixMe: Not typed to avoid destructuring arguments var templateFunction = function templateFunction() { return componentConstructor(tag, options, css.apply(undefined, arguments)); }; /* If config methods are called, wrap up a new template function and merge options */ templateFunction.withConfig = function (config) { return constructWithOptions(componentConstructor, tag, _extends({}, options, config)); }; templateFunction.attrs = function (attrs) { return constructWithOptions(componentConstructor, tag, _extends({}, options, { attrs: _extends({}, options.attrs || EMPTY_OBJECT, attrs) })); }; return templateFunction; } // // Source: https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js function murmurhash(c) { for (var e = c.length | 0, a = e | 0, d = 0, b; e >= 4;) { b = c.charCodeAt(d) & 255 | (c.charCodeAt(++d) & 255) << 8 | (c.charCodeAt(++d) & 255) << 16 | (c.charCodeAt(++d) & 255) << 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), b ^= b >>> 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16) ^ b, e -= 4, ++d; } switch (e) { case 3: a ^= (c.charCodeAt(d + 2) & 255) << 16; case 2: a ^= (c.charCodeAt(d + 1) & 255) << 8; case 1: a ^= c.charCodeAt(d) & 255, a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16); } a ^= a >>> 13; a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16); return (a ^ a >>> 15) >>> 0; } // /* eslint-disable no-bitwise */ /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised * counterparts */ var charsLength = 52; /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */ var getAlphabeticChar = function getAlphabeticChar(code) { return String.fromCharCode(code + (code > 25 ? 39 : 97)); }; /* input a number, usually a hash and convert it to base-52 */ function generateAlphabeticName(code) { var name = ''; var x = void 0; /* get a char and divide by alphabet-length */ for (x = code; x > charsLength; x = Math.floor(x / charsLength)) { name = getAlphabeticChar(x % charsLength) + name; } return getAlphabeticChar(x % charsLength) + name; } // function isStaticRules(rules, attrs) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; // recursive case if (Array.isArray(rule) && !isStaticRules(rule)) { return false; } else if (isFunction(rule) && !isStyledComponent(rule)) { // functions are allowed to be static if they're just being // used to get the classname of a nested styled component return false; } } if (attrs !== undefined) { // eslint-disable-next-line guard-for-in, no-restricted-syntax for (var key in attrs) { var value = attrs[key]; if (isFunction(value)) { return false; } } } return true; } // // var isHMREnabled = process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module.hot; /* combines hashStr (murmurhash) and nameGenerator for convenience */ var hasher = function hasher(str) { return generateAlphabeticName(murmurhash(str)); }; /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var ComponentStyle = function () { function ComponentStyle(rules, attrs, componentId) { classCallCheck(this, ComponentStyle); this.rules = rules; this.isStatic = !isHMREnabled && isStaticRules(rules, attrs); this.componentId = componentId; if (!StyleSheet.master.hasId(componentId)) { var placeholder = process.env.NODE_ENV !== 'production' ? ['.' + componentId + ' {}'] : []; StyleSheet.master.deferredInject(componentId, placeholder); } } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a .hash1234 {} * Returns the hash to be injected on render() * */ ComponentStyle.prototype.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) { var isStatic = this.isStatic, componentId = this.componentId, lastClassName = this.lastClassName; if (IS_BROWSER && isStatic && lastClassName !== undefined && styleSheet.hasNameForId(componentId, lastClassName)) { return lastClassName; } var flatCSS = flatten(this.rules, executionContext, styleSheet); var name = hasher(this.componentId + flatCSS.join('')); if (!styleSheet.hasNameForId(componentId, name)) { styleSheet.inject(this.componentId, stringifyRules(flatCSS, '.' + name, undefined, componentId), name); } this.lastClassName = name; return name; }; ComponentStyle.generateName = function generateName(str) { return hasher(str); }; return ComponentStyle; }(); // var LIMIT = 200; var createWarnTooManyClasses = (function (displayName) { var generatedClasses = {}; var warningSeen = false; return function (className) { if (!warningSeen) { generatedClasses[className] = true; if (Object.keys(generatedClasses).length >= LIMIT) { // Unable to find latestRule in test environment. /* eslint-disable no-console, prefer-template */ console.warn('Over ' + LIMIT + ' classes were generated for component ' + displayName + '. \n' + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />'); warningSeen = true; generatedClasses = {}; } } }; }); // var determineTheme = (function (props, fallbackTheme) { var defaultProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT; // Props should take precedence over ThemeProvider, which should take precedence over // defaultProps, but React automatically puts defaultProps on props. /* eslint-disable react/prop-types, flowtype-errors/show-errors */ var isDefaultTheme = defaultProps ? props.theme === defaultProps.theme : false; var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme || defaultProps.theme; /* eslint-enable */ return theme; }); // var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g; var dashesAtEnds = /(^-|-$)/g; /** * TODO: Explore using CSS.escape when it becomes more available * in evergreen browsers. */ function escape(str) { return str // Replace all possible CSS selectors .replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end .replace(dashesAtEnds, ''); } // function isTag(target) /* : %checks */{ return typeof target === 'string'; } // function generateDisplayName(target) { return isTag(target) ? 'styled.' + target : 'Styled(' + getComponentName(target) + ')'; } var _TYPE_STATICS; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDerivedStateFromProps: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var TYPE_STATICS = (_TYPE_STATICS = {}, _TYPE_STATICS[reactIs.ForwardRef] = { $$typeof: true, render: true }, _TYPE_STATICS); var defineProperty$1 = Object.defineProperty, getOwnPropertyNames = Object.getOwnPropertyNames, _Object$getOwnPropert = Object.getOwnPropertySymbols, getOwnPropertySymbols = _Object$getOwnPropert === undefined ? function () { return []; } : _Object$getOwnPropert, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getPrototypeOf = Object.getPrototypeOf, objectPrototype = Object.prototype; var arrayPrototype = Array.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } var keys = arrayPrototype.concat(getOwnPropertyNames(sourceComponent), // $FlowFixMe getOwnPropertySymbols(sourceComponent)); var targetStatics = TYPE_STATICS[targetComponent.$$typeof] || REACT_STATICS; var sourceStatics = TYPE_STATICS[sourceComponent.$$typeof] || REACT_STATICS; var i = keys.length; var descriptor = void 0; var key = void 0; // eslint-disable-next-line no-plusplus while (i--) { key = keys[i]; if ( // $FlowFixMe !KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && // $FlowFixMe !(targetStatics && targetStatics[key])) { descriptor = getOwnPropertyDescriptor(sourceComponent, key); if (descriptor) { try { // Avoid failures from read-only properties defineProperty$1(targetComponent, key, descriptor); } catch (e) { /* fail silently */ } } } } return targetComponent; } return targetComponent; } // function isDerivedReactComponent(fn) { return !!(fn && fn.prototype && fn.prototype.isReactComponent); } // var ThemeContext = React.createContext(); var ThemeConsumer = ThemeContext.Consumer; /** * Provide a theme to an entire react component tree via context */ var ThemeProvider = function (_Component) { inherits(ThemeProvider, _Component); function ThemeProvider(props) { classCallCheck(this, ThemeProvider); var _this = possibleConstructorReturn(this, _Component.call(this, props)); _this.getContext = memoize(_this.getContext.bind(_this)); _this.renderInner = _this.renderInner.bind(_this); return _this; } ThemeProvider.prototype.render = function render() { if (!this.props.children) return null; return React__default.createElement( ThemeContext.Consumer, null, this.renderInner ); }; ThemeProvider.prototype.renderInner = function renderInner(outerTheme) { var context = this.getContext(this.props.theme, outerTheme); return React__default.createElement( ThemeContext.Provider, { value: context }, React__default.Children.only(this.props.children) ); }; /** * Get the theme from the props, supporting both (outerTheme) => {} * as well as object notation */ ThemeProvider.prototype.getTheme = function getTheme(theme, outerTheme) { if (isFunction(theme)) { var mergedTheme = theme(outerTheme); if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || (typeof mergedTheme === 'undefined' ? 'undefined' : _typeof(mergedTheme)) !== 'object')) { throw new StyledComponentsError(7); } return mergedTheme; } if (theme === null || Array.isArray(theme) || (typeof theme === 'undefined' ? 'undefined' : _typeof(theme)) !== 'object') { throw new StyledComponentsError(8); } return _extends({}, outerTheme, theme); }; ThemeProvider.prototype.getContext = function getContext(theme, outerTheme) { return this.getTheme(theme, outerTheme); }; return ThemeProvider; }(React.Component); // var ServerStyleSheet = function () { function ServerStyleSheet() { classCallCheck(this, ServerStyleSheet); /* The master sheet might be reset, so keep a reference here */ this.masterSheet = StyleSheet.master; this.instance = this.masterSheet.clone(); this.sealed = false; } /** * Mark the ServerStyleSheet as being fully emitted and manually GC it from the * StyleSheet singleton. */ ServerStyleSheet.prototype.seal = function seal() { if (!this.sealed) { /* Remove sealed StyleSheets from the master sheet */ var index = this.masterSheet.clones.indexOf(this.instance); this.masterSheet.clones.splice(index, 1); this.sealed = true; } }; ServerStyleSheet.prototype.collectStyles = function collectStyles(children) { if (this.sealed) { throw new StyledComponentsError(2); } return React__default.createElement( StyleSheetManager, { sheet: this.instance }, children ); }; ServerStyleSheet.prototype.getStyleTags = function getStyleTags() { this.seal(); return this.instance.toHTML(); }; ServerStyleSheet.prototype.getStyleElement = function getStyleElement() { this.seal(); return this.instance.toReactElements(); }; ServerStyleSheet.prototype.interleaveWithNodeStream = function interleaveWithNodeStream(readableStream) { var _this = this; { throw new StyledComponentsError(3); } /* the tag index keeps track of which tags have already been emitted */ var instance = this.instance; var instanceTagIndex = 0; var streamAttr = SC_STREAM_ATTR + '="true"'; var transformer = new stream.Transform({ transform: function appendStyleChunks(chunk, /* encoding */_, callback) { var tags = instance.tags; var html = ''; /* retrieve html for each new style tag */ for (; instanceTagIndex < tags.length; instanceTagIndex += 1) { var tag = tags[instanceTagIndex]; html += tag.toHTML(streamAttr); } /* force our StyleSheets to emit entirely new tags */ instance.sealAllTags(); /* prepend style html to chunk */ this.push(html + chunk); callback(); } }); readableStream.on('end', function () { return _this.seal(); }); readableStream.on('error', function (err) { _this.seal(); // forward the error to the transform stream transformer.emit('error', err); }); return readableStream.pipe(transformer); }; return ServerStyleSheet; }(); // var StyleSheetContext = React.createContext(); var StyleSheetConsumer = StyleSheetContext.Consumer; var StyleSheetManager = function (_Component) { inherits(StyleSheetManager, _Component); function StyleSheetManager(props) { classCallCheck(this, StyleSheetManager); var _this = possibleConstructorReturn(this, _Component.call(this, props)); _this.getContext = memoize(_this.getContext); return _this; } StyleSheetManager.prototype.getContext = function getContext(sheet, target) { if (sheet) { return sheet; } else if (target) { return new StyleSheet(target); } else { throw new StyledComponentsError(4); } }; StyleSheetManager.prototype.render = function render() { var _props = this.props, children = _props.children, sheet = _props.sheet, target = _props.target; var context = this.getContext(sheet, target); return React__default.createElement( StyleSheetContext.Provider, { value: context }, React__default.Children.only(children) ); }; return StyleSheetManager; }(React.Component); process.env.NODE_ENV !== "production" ? StyleSheetManager.propTypes = { sheet: PropTypes.oneOfType([PropTypes.instanceOf(StyleSheet), PropTypes.instanceOf(ServerStyleSheet)]), target: PropTypes.shape({ appendChild: PropTypes.func.isRequired }) } : void 0; // var classNameUseCheckInjector = (function (target) { var elementClassName = ''; var targetCDM = target.componentDidMount; // eslint-disable-next-line no-param-reassign target.componentDidMount = function componentDidMount() { if (typeof targetCDM === 'function') { targetCDM.call(this); } var classNames = elementClassName.replace(/ +/g, ' ').trim().split(' '); // eslint-disable-next-line react/no-find-dom-node var node = ReactDOM.findDOMNode(this); var selector = classNames.map(function (s) { return '.' + s; }).join(''); if (node && node.nodeType === 1 && !classNames.every(function (className) { return node.classList && node.classList.contains(className); }) && !node.querySelector(selector)) { console.warn('It looks like you\'ve wrapped styled() around your React component (' + getComponentName(this.props.forwardedClass.target) + '), but the className prop is not being passed down to a child. No styles will be rendered unless className is composed within your React component.'); } }; var prevRenderInner = target.renderInner; // eslint-disable-next-line no-param-reassign target.renderInner = function renderInner() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var element = prevRenderInner.apply(this, args); elementClassName = element.props.className; return element; }; }); // var identifiers = {}; /* We depend on components having unique IDs */ function generateId(_ComponentStyle, _displayName, parentComponentId) { var displayName = typeof _displayName !== 'string' ? 'sc' : escape(_displayName); /** * This ensures uniqueness if two components happen to share * the same displayName. */ var nr = (identifiers[displayName] || 0) + 1; identifiers[displayName] = nr; var componentId = displayName + '-' + _ComponentStyle.generateName(displayName + nr); return parentComponentId ? parentComponentId + '-' + componentId : componentId; } var warnInnerRef = once(function () { return ( // eslint-disable-next-line no-console console.warn('The "innerRef" API has been removed in styled-components v4 in favor of React 16 ref forwarding, use "ref" instead like a typical component.') ); }); // $FlowFixMe var StyledComponent = function (_Component) { inherits(StyledComponent, _Component); function StyledComponent() { classCallCheck(this, StyledComponent); var _this = possibleConstructorReturn(this, _Component.call(this)); _this.attrs = {}; _this.renderOuter = _this.renderOuter.bind(_this); _this.renderInner = _this.renderInner.bind(_this); if (process.env.NODE_ENV !== 'production' && IS_BROWSER) { classNameUseCheckInjector(_this); } return _this; } StyledComponent.prototype.render = function render() { return React__default.createElement( StyleSheetConsumer, null, this.renderOuter ); }; StyledComponent.prototype.renderOuter = function renderOuter(styleSheet) { this.styleSheet = styleSheet; return React__default.createElement( ThemeConsumer, null, this.renderInner ); }; StyledComponent.prototype.renderInner = function renderInner(theme) { var _props$forwardedClass = this.props.forwardedClass, componentStyle = _props$forwardedClass.componentStyle, defaultProps = _props$forwardedClass.defaultProps, styledComponentId = _props$forwardedClass.styledComponentId, target = _props$forwardedClass.target; var generatedClassName = void 0; if (componentStyle.isStatic) { generatedClassName = this.generateAndInjectStyles(EMPTY_OBJECT, this.props, this.styleSheet); } else if (theme !== undefined) { generatedClassName = this.generateAndInjectStyles(determineTheme(this.props, theme, defaultProps), this.props, this.styleSheet); } else { generatedClassName = this.generateAndInjectStyles(this.props.theme || EMPTY_OBJECT, this.props, this.styleSheet); } var elementToBeCreated = this.props.as || this.attrs.as || target; var isTargetTag = isTag(elementToBeCreated); var propsForElement = _extends({}, this.attrs); var key = void 0; // eslint-disable-next-line guard-for-in for (key in this.props) { if (process.env.NODE_ENV !== 'production' && key === 'innerRef') { warnInnerRef(); } if (key === 'forwardedClass' || key === 'as') continue;else if (key === 'forwardedRef') propsForElement.ref = this.props[key];else if (!isTargetTag || validAttr(key)) { // Don't pass through non HTML tags through to HTML elements propsForElement[key] = key === 'style' && key in this.attrs ? _extends({}, this.attrs[key], this.props[key]) : this.props[key]; } } propsForElement.className = [this.props.className, styledComponentId, this.attrs.className, generatedClassName].filter(Boolean).join(' '); return React.createElement(elementToBeCreated, propsForElement); }; StyledComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props, attrs) { var context = _extends({}, props, { theme: theme }); if (attrs === undefined) return context; this.attrs = {}; var attr = void 0; var key = void 0; /* eslint-disable guard-for-in */ for (key in attrs) { attr = attrs[key]; this.attrs[key] = isFunction(attr) && !isDerivedReactComponent(attr) && !isStyledComponent(attr) ? attr(context) : attr; } /* eslint-enable */ return _extends({}, context, this.attrs); }; StyledComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) { var styleSheet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : StyleSheet.master; var _props$forwardedClass2 = props.forwardedClass, attrs = _props$forwardedClass2.attrs, componentStyle = _props$forwardedClass2.componentStyle, warnTooManyClasses = _props$forwardedClass2.warnTooManyClasses; // statically styled-components don't need to build an execution context object, // and shouldn't be increasing the number of class names if (componentStyle.isStatic && attrs === undefined) { return componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet); } var className = componentStyle.generateAndInjectStyles(this.buildExecutionContext(theme, props, props.forwardedClass.attrs), styleSheet); if (warnTooManyClasses) { warnTooManyClasses(className); } return className; }; return StyledComponent; }(React.Component); function createStyledComponent(target, options, rules) { var isTargetStyledComp = isStyledComponent(target); var isClass = !isTag(target); var _options$displayName = options.displayName, displayName = _options$displayName === undefined ? generateDisplayName(target) : _options$displayName, _options$componentId = options.componentId, componentId = _options$componentId === undefined ? generateId(ComponentStyle, options.displayName, options.parentComponentId) : _options$componentId, _options$ParentCompon = options.ParentComponent, ParentComponent = _options$ParentCompon === undefined ? StyledComponent : _options$ParentCompon, attrs = options.attrs; var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + '-' + options.componentId : options.componentId || componentId; // fold the underlying StyledComponent attrs up (implicit extend) var finalAttrs = // $FlowFixMe isTargetStyledComp && target.attrs ? _extends({}, target.attrs, attrs) : attrs; var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend) // $FlowFixMe target.componentStyle.rules.concat(rules) : rules, finalAttrs, styledComponentId); /** * forwardRef creates a new interim component, which we'll take advantage of * instead of extending ParentComponent to create _another_ interim class */ var WrappedStyledComponent = React__default.forwardRef(function (props, ref) { return React__default.createElement(ParentComponent, _extends({}, props, { forwardedClass: WrappedStyledComponent, forwardedRef: ref })); }); // $FlowFixMe WrappedStyledComponent.attrs = finalAttrs; // $FlowFixMe WrappedStyledComponent.componentStyle = componentStyle; WrappedStyledComponent.displayName = displayName; // $FlowFixMe WrappedStyledComponent.styledComponentId = styledComponentId; // fold the underlying StyledComponent target up since we folded the styles // $FlowFixMe WrappedStyledComponent.target = isTargetStyledComp ? target.target : target; // $FlowFixMe WrappedStyledComponent.withComponent = function withComponent(tag) { var previousComponentId = options.componentId, optionsToCopy = objectWithoutProperties(options, ['componentId']); var newComponentId = previousComponentId && previousComponentId + '-' + (isTag(tag) ? tag : escape(getComponentName(tag))); var newOptions = _extends({}, optionsToCopy, { attrs: finalAttrs, componentId: newComponentId, ParentComponent: ParentComponent }); return createStyledComponent(tag, newOptions, rules); }; if (process.env.NODE_ENV !== 'production') { // $FlowFixMe WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName); } if (isClass) { hoistNonReactStatics(WrappedStyledComponent, target, { // all SC-specific things should not be hoisted attrs: true, componentStyle: true, displayName: true, styledComponentId: true, target: true, warnTooManyClasses: true, withComponent: true }); } return WrappedStyledComponent; } // // Thanks to ReactDOMFactories for this handy list! var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // var styled = function styled(tag) { return constructWithOptions(createStyledComponent, tag); }; // Shorthands for all valid HTML Elements domElements.forEach(function (domElement) { styled[domElement] = styled(domElement); }); // var GlobalStyle = function () { function GlobalStyle(rules, componentId) { classCallCheck(this, GlobalStyle); this.rules = rules; this.componentId = componentId; this.isStatic = isStaticRules(rules); if (!StyleSheet.master.hasId(componentId)) { StyleSheet.master.deferredInject(componentId, []); } } GlobalStyle.prototype.createStyles = function createStyles(executionContext, styleSheet) { var flatCSS = flatten(this.rules, executionContext, styleSheet); var css = stringifyRules(flatCSS, ''); styleSheet.inject(this.componentId, css); }; GlobalStyle.prototype.removeStyles = function removeStyles(styleSheet) { var componentId = this.componentId; if (styleSheet.hasId(componentId)) { styleSheet.remove(componentId); } }; // TODO: overwrite in-place instead of remove+create? GlobalStyle.prototype.renderStyles = function renderStyles(executionContext, styleSheet) { this.removeStyles(styleSheet); this.createStyles(executionContext, styleSheet); }; return GlobalStyle; }(); // // place our cache into shared context so it'll persist between HMRs if (IS_BROWSER) { window.scCGSHMRCache = {}; } function createGlobalStyle(strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var id = 'sc-global-' + murmurhash(JSON.stringify(rules)); var style = new GlobalStyle(rules, id); var GlobalStyleComponent = function (_React$Component) { inherits(GlobalStyleComponent, _React$Component); function GlobalStyleComponent() { classCallCheck(this, GlobalStyleComponent); var _this = possibleConstructorReturn(this, _React$Component.call(this)); var _this$constructor = _this.constructor, globalStyle = _this$constructor.globalStyle, styledComponentId = _this$constructor.styledComponentId; if (IS_BROWSER) { window.scCGSHMRCache[styledComponentId] = (window.scCGSHMRCache[styledComponentId] || 0) + 1; } /** * This fixes HMR compatiblility. Don't ask me why, but this combination of * caching the closure variables via statics and then persisting the statics in * state works across HMR where no other combination did. ¯\_(ツ)_/¯ */ _this.state = { globalStyle: globalStyle, styledComponentId: styledComponentId }; return _this; } GlobalStyleComponent.prototype.componentDidMount = function componentDidMount() { if (process.env.NODE_ENV !== 'production' && IS_BROWSER && window.scCGSHMRCache[this.state.styledComponentId] > 1 && !this.props.suppressMultiMountWarning) { console.warn('The global style component ' + this.state.styledComponentId + ' was composed and rendered multiple times in your React component tree. Only the last-rendered copy will have its styles remain in <head> (or your StyleSheetManager target.)'); } }; GlobalStyleComponent.prototype.componentWillUnmount = function componentWillUnmount() { if (window.scCGSHMRCache[this.state.styledComponentId]) { window.scCGSHMRCache[this.state.styledComponentId] -= 1; } /** * Depending on the order "render" is called this can cause the styles to be lost * until the next render pass of the remaining instance, which may * not be immediate. */ if (window.scCGSHMRCache[this.state.styledComponentId] === 0) { this.state.globalStyle.removeStyles(this.styleSheet); } }; GlobalStyleComponent.prototype.render = function render() { var _this2 = this; if (process.env.NODE_ENV !== 'production' && React__default.Children.count(this.props.children)) { console.warn('The global style component ' + this.state.styledComponentId + ' was given child JSX. createGlobalStyle does not render children.'); } return React__default.createElement( StyleSheetConsumer, null, function (styleSheet) { _this2.styleSheet = styleSheet || StyleSheet.master; var globalStyle = _this2.state.globalStyle; if (globalStyle.isStatic) { globalStyle.renderStyles(STATIC_EXECUTION_CONTEXT, _this2.styleSheet); return null; } else { return React__default.createElement( ThemeConsumer, null, function (theme) { var defaultProps = _this2.constructor.defaultProps; var context = _extends({}, _this2.props); if (typeof theme !== 'undefined') { context.theme = determineTheme(_this2.props, theme, defaultProps); } globalStyle.renderStyles(context, _this2.styleSheet); return null; } ); } } ); }; return GlobalStyleComponent; }(React__default.Component); GlobalStyleComponent.defaultProps = { suppressMultiMountWarning: false }; GlobalStyleComponent.globalStyle = style; GlobalStyleComponent.styledComponentId = id; process.env.NODE_ENV !== "production" ? GlobalStyleComponent.propTypes = { suppressMultiMountWarning: PropTypes.bool } : void 0; return GlobalStyleComponent; } // var replaceWhitespace = function replaceWhitespace(str) { return str.replace(/\s|\\n/g, ''); }; function keyframes(strings) { /* Warning if you've used keyframes on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { console.warn('`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.'); } for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var name = generateAlphabeticName(murmurhash(replaceWhitespace(JSON.stringify(rules)))); return new Keyframes(name, stringifyRules(rules, name, '@keyframes')); } // var withTheme = (function (Component) { var WithTheme = React__default.forwardRef(function (props, ref) { return React__default.createElement( ThemeConsumer, null, function (theme) { // $FlowFixMe var defaultProps = Component.defaultProps; var themeProp = determineTheme(props, theme, defaultProps); if (process.env.NODE_ENV !== 'production' && themeProp === undefined) { // eslint-disable-next-line no-console console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class ' + getComponentName(Component)); } return React__default.createElement(Component, _extends({}, props, { theme: themeProp, ref: ref })); } ); }); hoistNonReactStatics(WithTheme, Component); WithTheme.displayName = 'WithTheme(' + getComponentName(Component) + ')'; return WithTheme; }); // /* eslint-disable */ var __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = { StyleSheet: StyleSheet }; // /* Warning if you've imported this file on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn("It looks like you've imported 'styled-components' on React Native.\n" + "Perhaps you're looking to import 'styled-components/native'?\n" + 'Read more about this at https://www.styled-components.com/docs/basics#react-native'); } /* Warning if there are several instances of styled-components */ if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && typeof window !== 'undefined' && typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Node.js') === -1 && navigator.userAgent.indexOf('jsdom') === -1) { window['__styled-components-init__'] = window['__styled-components-init__'] || 0; if (window['__styled-components-init__'] === 1) { // eslint-disable-next-line no-console console.warn("It looks like there are several instances of 'styled-components' initialized in this application. " + 'This may cause dynamic styles not rendering properly, errors happening during rehydration process ' + 'and makes your application bigger without a good reason.\n\n' + 'See https://s-c.sh/2BAXzed for more info.'); } window['__styled-components-init__'] += 1; } // exports.default = styled; exports.css = css; exports.keyframes = keyframes; exports.createGlobalStyle = createGlobalStyle; exports.isStyledComponent = isStyledComponent; exports.ThemeConsumer = ThemeConsumer; exports.ThemeProvider = ThemeProvider; exports.withTheme = withTheme; exports.ServerStyleSheet = ServerStyleSheet; exports.StyleSheetManager = StyleSheetManager; exports.__DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS; //# sourceMappingURL=styled-components.browser.cjs.js.map
/* Highcharts JS v7.1.0 (2019-04-01) Variable Pie module for Highcharts (c) 2010-2019 Grzegorz Blachliski License: www.highcharts.com/license */ (function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/variable-pie",["highcharts"],function(g){a(g);a.Highcharts=g;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function g(a,r,g,p){a.hasOwnProperty(r)||(a[r]=p.apply(null,g))}a=a?a._modules:{};g(a,"modules/variable-pie.src.js",[a["parts/Globals.js"]],function(a){var g=a.pick,u=a.arrayMin,p=a.arrayMax,v=a.seriesType,w= a.seriesTypes.pie.prototype;v("variablepie","pie",{minPointSize:"10%",maxPointSize:"100%",zMin:void 0,zMax:void 0,sizeBy:"area",tooltip:{pointFormat:'\x3cspan style\x3d"color:{point.color}"\x3e\u25cf\x3c/span\x3e {series.name}\x3cbr/\x3eValue: {point.y}\x3cbr/\x3eSize: {point.z}\x3cbr/\x3e'}},{pointArrayMap:["y","z"],parallelArrays:["x","y","z"],redraw:function(){this.center=null;w.redraw.call(this,arguments)},zValEval:function(b){return"number"!==typeof b||isNaN(b)?null:!0},calculateExtremes:function(){var b= this.chart,a=this.options,d;d=this.zData;var t=Math.min(b.plotWidth,b.plotHeight)-2*(a.slicedOffset||0),h={},b=this.center||this.getCenter();["minPointSize","maxPointSize"].forEach(function(b){var c=a[b],d=/%$/.test(c),c=parseInt(c,10);h[b]=d?t*c/100:2*c});this.minPxSize=b[3]+h.minPointSize;this.maxPxSize=Math.max(Math.min(b[2],h.maxPointSize),b[3]+h.minPointSize);d.length&&(b=g(a.zMin,u(d.filter(this.zValEval))),d=g(a.zMax,p(d.filter(this.zValEval))),this.getRadii(b,d,this.minPxSize,this.maxPxSize))}, getRadii:function(b,a,d,g){var h=0,e,c=this.zData,l=c.length,m=[],q="radius"!==this.options.sizeBy,k=a-b;for(h;h<l;h++)e=this.zValEval(c[h])?c[h]:b,e<=b?e=d/2:e>=a?e=g/2:(e=0<k?(e-b)/k:.5,q&&(e=Math.sqrt(e)),e=Math.ceil(d+e*(g-d))/2),m.push(e);this.radii=m},translate:function(b){this.generatePoints();var a=0,d=this.options,t=d.slicedOffset,h=t+(d.borderWidth||0),e,c,l,m=d.startAngle||0,q=Math.PI/180*(m-90),k=Math.PI/180*(g(d.endAngle,m+360)-90),m=k-q,p=this.points,r,u=d.dataLabels.distance,d=d.ignoreHiddenPoint, v=p.length,f,n;this.startAngleRad=q;this.endAngleRad=k;this.calculateExtremes();b||(this.center=b=this.getCenter());for(k=0;k<v;k++){f=p[k];n=this.radii[k];f.labelDistance=g(f.options.dataLabels&&f.options.dataLabels.distance,u);this.maxLabelDistance=Math.max(this.maxLabelDistance||0,f.labelDistance);c=q+a*m;if(!d||f.visible)a+=f.percentage/100;l=q+a*m;f.shapeType="arc";f.shapeArgs={x:b[0],y:b[1],r:n,innerR:b[3]/2,start:Math.round(1E3*c)/1E3,end:Math.round(1E3*l)/1E3};c=(l+c)/2;c>1.5*Math.PI?c-=2* Math.PI:c<-Math.PI/2&&(c+=2*Math.PI);f.slicedTranslation={translateX:Math.round(Math.cos(c)*t),translateY:Math.round(Math.sin(c)*t)};e=Math.cos(c)*b[2]/2;r=Math.sin(c)*b[2]/2;l=Math.cos(c)*n;n*=Math.sin(c);f.tooltipPos=[b[0]+.7*e,b[1]+.7*r];f.half=c<-Math.PI/2||c>Math.PI/2?1:0;f.angle=c;e=Math.min(h,f.labelDistance/5);f.labelPosition={natural:{x:b[0]+l+Math.cos(c)*f.labelDistance,y:b[1]+n+Math.sin(c)*f.labelDistance},"final":{},alignment:f.half?"right":"left",connectorPosition:{breakAt:{x:b[0]+l+ Math.cos(c)*e,y:b[1]+n+Math.sin(c)*e},touchingSliceAt:{x:b[0]+l,y:b[1]+n}}}}}})});g(a,"masters/modules/variable-pie.src.js",[],function(){})}); //# sourceMappingURL=variable-pie.js.map
'use strict'; import React from 'react'; import ReactTransitionEvents from 'react/lib/ReactTransitionEvents'; import {getTrackCSS, getTrackLeft, getTrackAnimateCSS} from './trackHelper'; import assign from 'object-assign'; var helpers = { initialize: function (props) { var slideCount = React.Children.count(props.children); var listWidth = this.refs.list.getDOMNode().getBoundingClientRect().width; var trackWidth = this.refs.track.getDOMNode().getBoundingClientRect().width; var slideWidth = this.getDOMNode().getBoundingClientRect().width/props.slidesToShow; var currentSlide = props.rtl ? slideCount - 1 - props.initialSlide : props.initialSlide; this.setState({ slideCount: slideCount, slideWidth: slideWidth, listWidth: listWidth, trackWidth: trackWidth, currentSlide: currentSlide }, function () { var targetLeft = getTrackLeft(assign({ slideIndex: this.state.currentSlide, trackRef: this.refs.track }, props, this.state)); // getCSS function needs previously set state var trackStyle = getTrackCSS(assign({left: targetLeft}, props, this.state)); this.setState({trackStyle: trackStyle}); this.autoPlay(); // once we're set up, trigger the initial autoplay. }); }, adaptHeight: function () { if (this.props.adaptiveHeight) { var selector = '[data-index="' + this.state.currentSlide +'"]'; if (this.refs.list) { var slickList = this.refs.list.getDOMNode(); slickList.style.height = slickList.querySelector(selector).offsetHeight + 'px'; } } }, slideHandler: function (index) { // Functionality of animateSlide and postSlide is merged into this function // console.log('slideHandler', index); var targetSlide, currentSlide; var targetLeft, currentLeft; var callback; if (this.state.animating === true || this.state.currentSlide === index) { return; } if (this.props.fade) { currentSlide = this.state.currentSlide; if (this.props.beforeChange) { this.props.beforeChange(currentSlide); } // Shifting targetSlide back into the range if (index < 0) { targetSlide = index + this.state.slideCount; } else if (index >= this.state.slideCount) { targetSlide = index - this.state.slideCount; } else { targetSlide = index; } if (this.props.lazyLoad && this.state.lazyLoadedList.indexOf(targetSlide) < 0) { this.setState({ lazyLoadedList: this.state.lazyLoadedList.concat(targetSlide) }); } callback = () => { this.setState({ animating: false }); if (this.props.afterChange) { this.props.afterChange(currentSlide); } ReactTransitionEvents.removeEndEventListener(this.refs.track.getDOMNode().children[currentSlide], callback); }; this.setState({ animating: true, currentSlide: targetSlide }, function () { ReactTransitionEvents.addEndEventListener(this.refs.track.getDOMNode().children[currentSlide], callback); }); this.autoPlay(); return; } targetSlide = index; if (targetSlide < 0) { if(this.props.infinite === false) { currentSlide = 0; } else if (this.state.slideCount % this.props.slidesToScroll !== 0) { currentSlide = this.state.slideCount - (this.state.slideCount % this.props.slidesToScroll); } else { currentSlide = this.state.slideCount + targetSlide; } } else if (targetSlide >= this.state.slideCount) { if(this.props.infinite === false) { currentSlide = this.state.slideCount - this.props.slidesToShow; } else if (this.state.slideCount % this.props.slidesToScroll !== 0) { currentSlide = 0; } else { currentSlide = targetSlide - this.state.slideCount; } } else { currentSlide = targetSlide; } targetLeft = getTrackLeft(assign({ slideIndex: targetSlide, trackRef: this.refs.track }, this.props, this.state)); currentLeft = getTrackLeft(assign({ slideIndex: currentSlide, trackRef: this.refs.track }, this.props, this.state)); if (this.props.infinite === false) { targetLeft = currentLeft; } if (this.props.beforeChange) { this.props.beforeChange(currentSlide); } if (this.props.lazyLoad) { var loaded = true; var slidesToLoad = []; for (var i = targetSlide; i < targetSlide + this.props.slidesToShow; i++ ) { loaded = loaded && (this.state.lazyLoadedList.indexOf(i) >= 0); if (!loaded) { slidesToLoad.push(i); } } if (!loaded) { this.setState({ lazyLoadedList: this.state.lazyLoadedList.concat(slidesToLoad) }); } } // Slide Transition happens here. // animated transition happens to target Slide and // non - animated transition happens to current Slide // If CSS transitions are false, directly go the current slide. if (this.props.useCSS === false) { this.setState({ currentSlide: currentSlide, trackStyle: getTrackCSS(assign({left: currentLeft}, this.props, this.state)) }, function () { if (this.props.afterChange) { this.props.afterChange(currentSlide); } }); } else { var nextStateChanges = { animating: false, currentSlide: currentSlide, trackStyle: getTrackCSS(assign({left: currentLeft}, this.props, this.state)), swipeLeft: null }; callback = () => { this.setState(nextStateChanges); if (this.props.afterChange) { this.props.afterChange(currentSlide); } ReactTransitionEvents.removeEndEventListener(this.refs.track.getDOMNode(), callback); }; this.setState({ animating: true, currentSlide: targetSlide, trackStyle: getTrackAnimateCSS(assign({left: targetLeft}, this.props, this.state)) }, function () { ReactTransitionEvents.addEndEventListener(this.refs.track.getDOMNode(), callback); }); } this.autoPlay(); }, swipeDirection: function (touchObject) { var xDist, yDist, r, swipeAngle; xDist = touchObject.startX - touchObject.curX; yDist = touchObject.startY - touchObject.curY; r = Math.atan2(yDist, xDist); swipeAngle = Math.round(r * 180 / Math.PI); if (swipeAngle < 0) { swipeAngle = 360 - Math.abs(swipeAngle); } if ((swipeAngle <= 45) && (swipeAngle >= 0) || (swipeAngle <= 360) && (swipeAngle >= 315)) { return (this.props.rtl === false ? 'left' : 'right'); } if ((swipeAngle >= 135) && (swipeAngle <= 225)) { return (this.props.rtl === false ? 'right' : 'left'); } return 'vertical'; }, autoPlay: function () { var play = () => { if (this.state.mounted) { this.slideHandler(this.state.currentSlide + this.props.slidesToScroll); } }; if (this.props.autoplay) { window.clearTimeout(this.state.autoPlayTimer); this.setState({ autoPlayTimer: window.setTimeout(play, this.props.autoplaySpeed) }); } } }; export default helpers;
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v19.1.2 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("../context/context"); var beans_1 = require("./beans"); var cellComp_1 = require("./cellComp"); var columnController_1 = require("../columnController/columnController"); var utils_1 = require("../utils"); var AutoHeightCalculator = /** @class */ (function () { function AutoHeightCalculator() { } AutoHeightCalculator.prototype.registerGridComp = function (gridPanel) { this.gridPanel = gridPanel; }; AutoHeightCalculator.prototype.getPreferredHeightForRow = function (rowNode) { var _this = this; if (!this.eDummyContainer) { this.eDummyContainer = document.createElement('div'); // so any styles on row also get applied in dummy, otherwise // the content in dummy may differ to the real utils_1._.addCssClass(this.eDummyContainer, 'ag-row ag-row-no-focus'); } // we put the dummy into the body container, so it will inherit all the // css styles that the real cells are inheriting var eBodyContainer = this.gridPanel.getBodyContainer(); eBodyContainer.appendChild(this.eDummyContainer); var cellComps = []; var cols = this.columnController.getAllAutoRowHeightCols(); cols.forEach(function (col) { var cellComp = new cellComp_1.CellComp(_this.$scope, _this.beans, col, rowNode, null, true, false); cellComp.setParentRow(_this.eDummyContainer); cellComps.push(cellComp); }); var template = cellComps.map(function (cellComp) { return cellComp.getCreateTemplate(); }).join(' '); this.eDummyContainer.innerHTML = template; // this gets any cellComps that are using components to put the components in cellComps.forEach(function (cellComp) { return cellComp.afterAttached(); }); // we should be able to just take the height of the row at this point, however // the row isn't expanding to cover the cell heights, i don't know why, i couldn't // figure it out so instead looking at the individual cells instead var maxCellHeight = 0; for (var i = 0; i < this.eDummyContainer.children.length; i++) { var child = this.eDummyContainer.children[i]; if (child.offsetHeight > maxCellHeight) { maxCellHeight = child.offsetHeight; } } // we are finished with the dummy container, so get rid of it eBodyContainer.removeChild(this.eDummyContainer); cellComps.forEach(function (cellComp) { // dunno why we need to detach first, doing it here to be consistent with code in RowComp cellComp.detach(); cellComp.destroy(); }); // in case anything left over from last time utils_1._.removeAllChildren(this.eDummyContainer); return maxCellHeight; }; __decorate([ context_1.Autowired('beans'), __metadata("design:type", beans_1.Beans) ], AutoHeightCalculator.prototype, "beans", void 0); __decorate([ context_1.Autowired("$scope"), __metadata("design:type", Object) ], AutoHeightCalculator.prototype, "$scope", void 0); __decorate([ context_1.Autowired("columnController"), __metadata("design:type", columnController_1.ColumnController) ], AutoHeightCalculator.prototype, "columnController", void 0); AutoHeightCalculator = __decorate([ context_1.Bean('autoHeightCalculator') ], AutoHeightCalculator); return AutoHeightCalculator; }()); exports.AutoHeightCalculator = AutoHeightCalculator;
/* * * * Copyright (c) 2019-2019 Highsoft AS * * Boost module: stripped-down renderer for higher performance * * License: highcharts.com/license * * */ 'use strict'; import H from '../../parts/Globals.js'; import U from '../../parts/Utilities.js'; var isNumber = U.isNumber; import '../../parts/Color.js'; import '../../parts/Series.js'; import '../../parts/Options.js'; import '../../parts/Point.js'; import '../../parts/Interaction.js'; import butils from './boost-utils.js'; import boostable from './boostables.js'; import boostableMap from './boostable-map.js'; var boostEnabled = butils.boostEnabled, shouldForceChartSeriesBoosting = butils.shouldForceChartSeriesBoosting, Chart = H.Chart, Series = H.Series, Point = H.Point, seriesTypes = H.seriesTypes, addEvent = H.addEvent, pick = H.pick, wrap = H.wrap, plotOptions = H.getOptions().plotOptions; /** * Returns true if the chart is in series boost mode. * * @function Highcharts.Chart#isChartSeriesBoosting * * @param {Highcharts.Chart} chart * the chart to check * * @return {boolean} * true if the chart is in series boost mode */ Chart.prototype.isChartSeriesBoosting = function () { var isSeriesBoosting, threshold = pick( this.options.boost && this.options.boost.seriesThreshold, 50 ); isSeriesBoosting = threshold <= this.series.length || shouldForceChartSeriesBoosting(this); return isSeriesBoosting; }; /** * Get the clip rectangle for a target, either a series or the chart. For the * chart, we need to consider the maximum extent of its Y axes, in case of * Highstock panes and navigator. * * @private * @function Highcharts.Chart#getBoostClipRect * * @param {Highcharts.Chart} target * * @return {Highcharts.BBoxObject} */ Chart.prototype.getBoostClipRect = function (target) { var clipBox = { x: this.plotLeft, y: this.plotTop, width: this.plotWidth, height: this.plotHeight }; if (target === this) { this.yAxis.forEach(function (yAxis) { clipBox.y = Math.min(yAxis.pos, clipBox.y); clipBox.height = Math.max( yAxis.pos - this.plotTop + yAxis.len, clipBox.height ); }, this); } return clipBox; }; /** * Return a full Point object based on the index. * The boost module uses stripped point objects for performance reasons. * * @function Highcharts.Series#getPoint * * @param {object|Highcharts.Point} boostPoint * A stripped-down point object * * @return {object} * A Point object as per http://api.highcharts.com/highcharts#Point */ Series.prototype.getPoint = function (boostPoint) { var point = boostPoint, xData = ( this.xData || this.options.xData || this.processedXData || false ); if (boostPoint && !(boostPoint instanceof this.pointClass)) { point = (new this.pointClass()).init( // eslint-disable-line new-cap this, this.options.data[boostPoint.i], xData ? xData[boostPoint.i] : undefined ); point.category = pick( this.xAxis.categories ? this.xAxis.categories[point.x] : point.x, point.x ); point.dist = boostPoint.dist; point.distX = boostPoint.distX; point.plotX = boostPoint.plotX; point.plotY = boostPoint.plotY; point.index = boostPoint.i; } return point; }; // Return a point instance from the k-d-tree wrap(Series.prototype, 'searchPoint', function (proceed) { return this.getPoint( proceed.apply(this, [].slice.call(arguments, 1)) ); }); // For inverted series, we need to swap X-Y values before running base methods wrap(Point.prototype, 'haloPath', function (proceed) { var halo, point = this, series = point.series, chart = series.chart, plotX = point.plotX, plotY = point.plotY, inverted = chart.inverted; if (series.isSeriesBoosting && inverted) { point.plotX = series.yAxis.len - plotY; point.plotY = series.xAxis.len - plotX; } halo = proceed.apply(this, Array.prototype.slice.call(arguments, 1)); if (series.isSeriesBoosting && inverted) { point.plotX = plotX; point.plotY = plotY; } return halo; }); wrap(Series.prototype, 'markerAttribs', function (proceed, point) { var attribs, series = this, chart = series.chart, plotX = point.plotX, plotY = point.plotY, inverted = chart.inverted; if (series.isSeriesBoosting && inverted) { point.plotX = series.yAxis.len - plotY; point.plotY = series.xAxis.len - plotX; } attribs = proceed.apply(this, Array.prototype.slice.call(arguments, 1)); if (series.isSeriesBoosting && inverted) { point.plotX = plotX; point.plotY = plotY; } return attribs; }); /* * Extend series.destroy to also remove the fake k-d-tree points (#5137). * Normally this is handled by Series.destroy that calls Point.destroy, * but the fake search points are not registered like that. */ addEvent(Series, 'destroy', function () { var series = this, chart = series.chart; if (chart.markerGroup === series.markerGroup) { series.markerGroup = null; } if (chart.hoverPoints) { chart.hoverPoints = chart.hoverPoints.filter(function (point) { return point.series === series; }); } if (chart.hoverPoint && chart.hoverPoint.series === series) { chart.hoverPoint = null; } }); /* * Do not compute extremes when min and max are set. * If we use this in the core, we can add the hook * to hasExtremes to the methods directly. */ wrap(Series.prototype, 'getExtremes', function (proceed) { if (!this.isSeriesBoosting || (!this.hasExtremes || !this.hasExtremes())) { return proceed.apply(this, Array.prototype.slice.call(arguments, 1)); } }); /* * Override a bunch of methods the same way. If the number of points is * below the threshold, run the original method. If not, check for a * canvas version or do nothing. * * Note that we're not overriding any of these for heatmaps. */ [ 'translate', 'generatePoints', 'drawTracker', 'drawPoints', 'render' ].forEach(function (method) { function branch(proceed) { var letItPass = this.options.stacking && (method === 'translate' || method === 'generatePoints'); if ( !this.isSeriesBoosting || letItPass || !boostEnabled(this.chart) || this.type === 'heatmap' || this.type === 'treemap' || !boostableMap[this.type] || this.options.boostThreshold === 0 ) { proceed.call(this); // If a canvas version of the method exists, like renderCanvas(), run } else if (this[method + 'Canvas']) { this[method + 'Canvas'](); } } wrap(Series.prototype, method, branch); // A special case for some types - their translate method is already wrapped if (method === 'translate') { [ 'column', 'bar', 'arearange', 'columnrange', 'heatmap', 'treemap' ].forEach( function (type) { if (seriesTypes[type]) { wrap(seriesTypes[type].prototype, method, branch); } } ); } }); // If the series is a heatmap or treemap, or if the series is not boosting // do the default behaviour. Otherwise, process if the series has no extremes. wrap(Series.prototype, 'processData', function (proceed) { var series = this, dataToMeasure = this.options.data; // Used twice in this function, first on this.options.data, the second // time it runs the check again after processedXData is built. // @todo Check what happens with data grouping function getSeriesBoosting(data) { return series.chart.isChartSeriesBoosting() || ( (data ? data.length : 0) >= (series.options.boostThreshold || Number.MAX_VALUE) ); } if (boostEnabled(this.chart) && boostableMap[this.type]) { // If there are no extremes given in the options, we also need to // process the data to read the data extremes. If this is a heatmap, do // default behaviour. if ( !getSeriesBoosting(dataToMeasure) || // First pass with options.data this.type === 'heatmap' || this.type === 'treemap' || this.options.stacking || // processedYData for the stack (#7481) !this.hasExtremes || !this.hasExtremes(true) ) { proceed.apply(this, Array.prototype.slice.call(arguments, 1)); dataToMeasure = this.processedXData; } // Set the isBoosting flag, second pass with processedXData to see if we // have zoomed. this.isSeriesBoosting = getSeriesBoosting(dataToMeasure); // Enter or exit boost mode if (this.isSeriesBoosting) { this.enterBoost(); } else if (this.exitBoost) { this.exitBoost(); } // The series type is not boostable } else { proceed.apply(this, Array.prototype.slice.call(arguments, 1)); } }); addEvent(Series, 'hide', function () { if (this.canvas && this.renderTarget) { if (this.ogl) { this.ogl.clear(); } this.boostClear(); } }); /** * Enter boost mode and apply boost-specific properties. * * @function Highcharts.Series#enterBoost */ Series.prototype.enterBoost = function () { this.alteredByBoost = []; // Save the original values, including whether it was an own property or // inherited from the prototype. ['allowDG', 'directTouch', 'stickyTracking'].forEach(function (prop) { this.alteredByBoost.push({ prop: prop, val: this[prop], own: this.hasOwnProperty(prop) }); }, this); this.allowDG = false; this.directTouch = false; this.stickyTracking = true; // Once we've been in boost mode, we don't want animation when returning to // vanilla mode. this.animate = null; // Hide series label if any if (this.labelBySeries) { this.labelBySeries = this.labelBySeries.destroy(); } }; /** * Exit from boost mode and restore non-boost properties. * * @function Highcharts.Series#exitBoost */ Series.prototype.exitBoost = function () { // Reset instance properties and/or delete instance properties and go back // to prototype (this.alteredByBoost || []).forEach(function (setting) { if (setting.own) { this[setting.prop] = setting.val; } else { // Revert to prototype delete this[setting.prop]; } }, this); // Clear previous run if (this.boostClear) { this.boostClear(); } }; /** * @private * @function Highcharts.Series#hasExtremes * * @param {boolean} checkX * * @return {boolean} */ Series.prototype.hasExtremes = function (checkX) { var options = this.options, data = options.data, xAxis = this.xAxis && this.xAxis.options, yAxis = this.yAxis && this.yAxis.options, colorAxis = this.colorAxis && this.colorAxis.options; return data.length > (options.boostThreshold || Number.MAX_VALUE) && // Defined yAxis extremes isNumber(yAxis.min) && isNumber(yAxis.max) && // Defined (and required) xAxis extremes (!checkX || (isNumber(xAxis.min) && isNumber(xAxis.max)) ) && // Defined (e.g. heatmap) colorAxis extremes (!colorAxis || (isNumber(colorAxis.min) && isNumber(colorAxis.max)) ); }; /** * If implemented in the core, parts of this can probably be * shared with other similar methods in Highcharts. * * @function Highcharts.Series#destroyGraphics */ Series.prototype.destroyGraphics = function () { var series = this, points = this.points, point, i; if (points) { for (i = 0; i < points.length; i = i + 1) { point = points[i]; if (point && point.destroyElements) { point.destroyElements(); // #7557 } } } ['graph', 'area', 'tracker'].forEach(function (prop) { if (series[prop]) { series[prop] = series[prop].destroy(); } }); }; // Set default options boostable.forEach( function (type) { if (plotOptions[type]) { plotOptions[type].boostThreshold = 5000; plotOptions[type].boostData = []; seriesTypes[type].prototype.fillOpacity = true; } } );
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v19.1.4 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // class returns a unique id to use for the column. it checks the existing columns, and if the requested // id is already taken, it will start appending numbers until it gets a unique id. // eg, if the col field is 'name', it will try ids: {name, name_1, name_2...} // if no field or id provided in the col, it will try the ids of natural numbers var utils_1 = require("../utils"); var ColumnKeyCreator = /** @class */ (function () { function ColumnKeyCreator() { this.existingKeys = []; } ColumnKeyCreator.prototype.addExistingKeys = function (keys) { this.existingKeys = this.existingKeys.concat(keys); }; ColumnKeyCreator.prototype.getUniqueKey = function (colId, colField) { // in case user passed in number for colId, convert to string colId = utils_1.Utils.toStringOrNull(colId); var count = 0; while (true) { var idToTry = void 0; if (colId) { idToTry = colId; if (count !== 0) { idToTry += '_' + count; } } else if (colField) { idToTry = colField; if (count !== 0) { idToTry += '_' + count; } } else { idToTry = '' + count; } if (this.existingKeys.indexOf(idToTry) < 0) { this.existingKeys.push(idToTry); return idToTry; } count++; } }; return ColumnKeyCreator; }()); exports.ColumnKeyCreator = ColumnKeyCreator;
import Stylis from 'stylis/stylis.min'; import _insertRulePlugin from 'stylis-rule-sheet'; import React, { cloneElement, createContext, Component, createElement } from 'react'; import { isElement, isValidElementType, ForwardRef } from 'react-is'; import memoize from 'memoize-one'; import stream from 'stream'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import validAttr from '@emotion/is-prop-valid'; // var interleave = (function (strings, interpolations) { var result = [strings[0]]; for (var i = 0, len = interpolations.length; i < len; i += 1) { result.push(interpolations[i], strings[i + 1]); } return result; }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var objectWithoutProperties = function (obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; // var isPlainObject = (function (x) { return (typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object' && x.constructor === Object; }); // var EMPTY_ARRAY = Object.freeze([]); var EMPTY_OBJECT = Object.freeze({}); // function isFunction(test) { return typeof test === 'function'; } // function getComponentName(target) { return target.displayName || target.name || 'Component'; } // function isStyledComponent(target) { return target && typeof target.styledComponentId === 'string'; } // var SC_ATTR = typeof process !== 'undefined' && process.env.SC_ATTR || 'data-styled'; var SC_VERSION_ATTR = 'data-styled-version'; var SC_STREAM_ATTR = 'data-styled-streamed'; var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window; var DISABLE_SPEEDY = process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles var STATIC_EXECUTION_CONTEXT = {}; // /** * Parse errors.md and turn it into a simple hash of code: message */ var ERRORS = process.env.NODE_ENV !== 'production' ? { "1": "Cannot create styled-component for component: %s.\n\n", "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n", "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n", "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n", "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n", "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n", "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n", "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n", "9": "Missing document `<head>`\n\n", "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n", "11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n" } : {}; /** * super basic version of sprintf */ function format() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var a = args[0]; var b = []; var c = void 0; for (c = 1; c < args.length; c += 1) { b.push(args[c]); } b.forEach(function (d) { a = a.replace(/%[a-z]/, d); }); return a; } /** * Create an error file out of errors.md for development and a simple web link to the full errors * in production mode. */ var StyledComponentsError = function (_Error) { inherits(StyledComponentsError, _Error); function StyledComponentsError(code) { classCallCheck(this, StyledComponentsError); for (var _len2 = arguments.length, interpolations = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { interpolations[_key2 - 1] = arguments[_key2]; } if (process.env.NODE_ENV === 'production') { var _this = possibleConstructorReturn(this, _Error.call(this, 'An error occurred. See https://github.com/styled-components/styled-components/blob/master/src/utils/errors.md#' + code + ' for more information. ' + (interpolations ? 'Additional arguments: ' + interpolations.join(', ') : ''))); } else { var _this = possibleConstructorReturn(this, _Error.call(this, format.apply(undefined, [ERRORS[code]].concat(interpolations)).trim())); } return possibleConstructorReturn(_this); } return StyledComponentsError; }(Error); // var SC_COMPONENT_ID = /^[^\S\n]*?\/\* sc-component-id:\s*(\S+)\s+\*\//gm; var extractComps = (function (maybeCSS) { var css = '' + (maybeCSS || ''); // Definitely a string, and a clone var existingComponents = []; css.replace(SC_COMPONENT_ID, function (match, componentId, matchIndex) { existingComponents.push({ componentId: componentId, matchIndex: matchIndex }); return match; }); return existingComponents.map(function (_ref, i) { var componentId = _ref.componentId, matchIndex = _ref.matchIndex; var nextComp = existingComponents[i + 1]; var cssFromDOM = nextComp ? css.slice(matchIndex, nextComp.matchIndex) : css.slice(matchIndex); return { componentId: componentId, cssFromDOM: cssFromDOM }; }); }); // var COMMENT_REGEX = /^\s*\/\/.*$/gm; var SELF_REFERENTIAL_COMBINATOR = /(&(?! *[+~>])([^&{][^{]+)[^+~>]*)?([+~>] *)&/g; // NOTE: This stylis instance is only used to split rules from SSR'd style tags var stylisSplitter = new Stylis({ global: false, cascade: true, keyframe: false, prefix: false, compress: false, semicolon: true }); var stylis = new Stylis({ global: false, cascade: true, keyframe: false, prefix: true, compress: false, semicolon: false // NOTE: This means "autocomplete missing semicolons" }); // Wrap `insertRulePlugin to build a list of rules, // and then make our own plugin to return the rules. This // makes it easier to hook into the existing SSR architecture var parsingRules = []; // eslint-disable-next-line consistent-return var returnRulesPlugin = function returnRulesPlugin(context) { if (context === -2) { var parsedRules = parsingRules; parsingRules = []; return parsedRules; } }; var parseRulesPlugin = _insertRulePlugin(function (rule) { parsingRules.push(rule); }); stylis.use([parseRulesPlugin, returnRulesPlugin]); stylisSplitter.use([parseRulesPlugin, returnRulesPlugin]); var stringifyRules = function stringifyRules(rules, selector, prefix) { var componentId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '&'; var flatCSS = rules.join('').replace(COMMENT_REGEX, ''); // replace JS comments var cssStr = (selector && prefix ? prefix + ' ' + selector + ' { ' + flatCSS + ' }' : flatCSS).replace(SELF_REFERENTIAL_COMBINATOR, '$1$3.' + componentId + '$2'); return stylis(prefix || !selector ? '' : selector, cssStr); }; var splitByRules = function splitByRules(css) { return stylisSplitter('', css); }; // /* eslint-disable camelcase, no-undef */ var getNonce = (function () { return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null; }); // // Helper to call a given function, only once var once = (function (cb) { var called = false; return function () { if (!called) { called = true; cb(); } }; }); // /* These are helpers for the StyleTags to keep track of the injected * rule names for each (component) ID that they're keeping track of. * They're crucial for detecting whether a name has already been * injected. * (This excludes rehydrated names) */ /* adds a new ID:name pairing to a names dictionary */ var addNameForId = function addNameForId(names, id, name) { if (name) { // eslint-disable-next-line no-param-reassign var namesForId = names[id] || (names[id] = Object.create(null)); namesForId[name] = true; } }; /* resets an ID entirely by overwriting it in the dictionary */ var resetIdNames = function resetIdNames(names, id) { // eslint-disable-next-line no-param-reassign names[id] = Object.create(null); }; /* factory for a names dictionary checking the existance of an ID:name pairing */ var hasNameForId = function hasNameForId(names) { return function (id, name) { return names[id] !== undefined && names[id][name]; }; }; /* stringifies names for the html/element output */ var stringifyNames = function stringifyNames(names) { var str = ''; // eslint-disable-next-line guard-for-in for (var id in names) { str += Object.keys(names[id]).join(' ') + ' '; } return str.trim(); }; /* clones the nested names dictionary */ var cloneNames = function cloneNames(names) { var clone = Object.create(null); // eslint-disable-next-line guard-for-in for (var id in names) { clone[id] = _extends({}, names[id]); } return clone; }; // /* These are helpers that deal with the insertRule (aka speedy) API * They are used in the StyleTags and specifically the speedy tag */ /* retrieve a sheet for a given style tag */ var sheetForTag = function sheetForTag(tag) { // $FlowFixMe if (tag.sheet) return tag.sheet; /* Firefox quirk requires us to step through all stylesheets to find one owned by the given tag */ var size = document.styleSheets.length; for (var i = 0; i < size; i += 1) { var sheet = document.styleSheets[i]; // $FlowFixMe if (sheet.ownerNode === tag) return sheet; } /* we should always be able to find a tag */ throw new StyledComponentsError(10); }; /* insert a rule safely and return whether it was actually injected */ var safeInsertRule = function safeInsertRule(sheet, cssRule, index) { /* abort early if cssRule string is falsy */ if (!cssRule) return false; var maxIndex = sheet.cssRules.length; try { /* use insertRule and cap passed index with maxIndex (no of cssRules) */ sheet.insertRule(cssRule, index <= maxIndex ? index : maxIndex); } catch (err) { /* any error indicates an invalid rule */ return false; } return true; }; /* deletes `size` rules starting from `removalIndex` */ var deleteRules = function deleteRules(sheet, removalIndex, size) { var lowerBound = removalIndex - size; for (var i = removalIndex; i > lowerBound; i -= 1) { sheet.deleteRule(i); } }; // /* this marker separates component styles and is important for rehydration */ var makeTextMarker = function makeTextMarker(id) { return '\n/* sc-component-id: ' + id + ' */\n'; }; /* add up all numbers in array up until and including the index */ var addUpUntilIndex = function addUpUntilIndex(sizes, index) { var totalUpToIndex = 0; for (var i = 0; i <= index; i += 1) { totalUpToIndex += sizes[i]; } return totalUpToIndex; }; /* create a new style tag after lastEl */ var makeStyleTag = function makeStyleTag(target, tagEl, insertBefore) { var el = document.createElement('style'); el.setAttribute(SC_ATTR, ''); el.setAttribute(SC_VERSION_ATTR, "4.0.0-beta.11.1-hmr"); var nonce = getNonce(); if (nonce) { el.setAttribute('nonce', nonce); } /* Work around insertRule quirk in EdgeHTML */ el.appendChild(document.createTextNode('')); if (target && !tagEl) { /* Append to target when no previous element was passed */ target.appendChild(el); } else { if (!tagEl || !target || !tagEl.parentNode) { throw new StyledComponentsError(6); } /* Insert new style tag after the previous one */ tagEl.parentNode.insertBefore(el, insertBefore ? tagEl : tagEl.nextSibling); } return el; }; /* takes a css factory function and outputs an html styled tag factory */ var wrapAsHtmlTag = function wrapAsHtmlTag(css, names) { return function (additionalAttrs) { var nonce = getNonce(); var attrs = [nonce && 'nonce="' + nonce + '"', SC_ATTR + '="' + stringifyNames(names) + '"', SC_VERSION_ATTR + '="' + "4.0.0-beta.11.1-hmr" + '"', additionalAttrs]; var htmlAttr = attrs.filter(Boolean).join(' '); return '<style ' + htmlAttr + '>' + css() + '</style>'; }; }; /* takes a css factory function and outputs an element factory */ var wrapAsElement = function wrapAsElement(css, names) { return function () { var _props; var props = (_props = {}, _props[SC_ATTR] = stringifyNames(names), _props[SC_VERSION_ATTR] = "4.0.0-beta.11.1-hmr", _props); var nonce = getNonce(); if (nonce) { // $FlowFixMe props.nonce = nonce; } // eslint-disable-next-line react/no-danger return React.createElement('style', _extends({}, props, { dangerouslySetInnerHTML: { __html: css() } })); }; }; var getIdsFromMarkersFactory = function getIdsFromMarkersFactory(markers) { return function () { return Object.keys(markers); }; }; /* speedy tags utilise insertRule */ var makeSpeedyTag = function makeSpeedyTag(el, getImportRuleTag) { var names = Object.create(null); var markers = Object.create(null); var sizes = []; var extractImport = getImportRuleTag !== undefined; /* indicates whther getImportRuleTag was called */ var usedImportRuleTag = false; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } markers[id] = sizes.length; sizes.push(0); resetIdNames(names, id); return markers[id]; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); var sheet = sheetForTag(el); var insertIndex = addUpUntilIndex(sizes, marker); var injectedRules = 0; var importRules = []; var cssRulesSize = cssRules.length; for (var i = 0; i < cssRulesSize; i += 1) { var cssRule = cssRules[i]; var mayHaveImport = extractImport; /* @import rules are reordered to appear first */ if (mayHaveImport && cssRule.indexOf('@import') !== -1) { importRules.push(cssRule); } else if (safeInsertRule(sheet, cssRule, insertIndex + injectedRules)) { mayHaveImport = false; injectedRules += 1; } } if (extractImport && importRules.length > 0) { usedImportRuleTag = true; // $FlowFixMe getImportRuleTag().insertRules(id + '-import', importRules); } sizes[marker] += injectedRules; /* add up no of injected rules */ addNameForId(names, id, name); }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; var size = sizes[marker]; var sheet = sheetForTag(el); var removalIndex = addUpUntilIndex(sizes, marker) - 1; deleteRules(sheet, removalIndex, size); sizes[marker] = 0; resetIdNames(names, id); if (extractImport && usedImportRuleTag) { // $FlowFixMe getImportRuleTag().removeRules(id + '-import'); } }; var css = function css() { var _sheetForTag = sheetForTag(el), cssRules = _sheetForTag.cssRules; var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { str += makeTextMarker(id); var marker = markers[id]; var end = addUpUntilIndex(sizes, marker); var size = sizes[marker]; for (var i = end - size; i < end; i += 1) { var rule = cssRules[i]; if (rule !== undefined) { str += rule.cssText; } } } return str; }; return { clone: function clone() { throw new StyledComponentsError(5); }, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: el, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; }; var makeTextNode = function makeTextNode(id) { return document.createTextNode(makeTextMarker(id)); }; var makeBrowserTag = function makeBrowserTag(el, getImportRuleTag) { var names = Object.create(null); var markers = Object.create(null); var extractImport = getImportRuleTag !== undefined; /* indicates whther getImportRuleTag was called */ var usedImportRuleTag = false; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } markers[id] = makeTextNode(id); el.appendChild(markers[id]); names[id] = Object.create(null); return markers[id]; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); var importRules = []; var cssRulesSize = cssRules.length; for (var i = 0; i < cssRulesSize; i += 1) { var rule = cssRules[i]; var mayHaveImport = extractImport; if (mayHaveImport && rule.indexOf('@import') !== -1) { importRules.push(rule); } else { mayHaveImport = false; var separator = i === cssRulesSize - 1 ? '' : ' '; marker.appendData('' + rule + separator); } } addNameForId(names, id, name); if (extractImport && importRules.length > 0) { usedImportRuleTag = true; // $FlowFixMe getImportRuleTag().insertRules(id + '-import', importRules); } }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; /* create new empty text node and replace the current one */ var newMarker = makeTextNode(id); el.replaceChild(newMarker, marker); markers[id] = newMarker; resetIdNames(names, id); if (extractImport && usedImportRuleTag) { // $FlowFixMe getImportRuleTag().removeRules(id + '-import'); } }; var css = function css() { var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { str += markers[id].data; } return str; }; return { clone: function clone() { throw new StyledComponentsError(5); }, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: el, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; }; var makeServerTag = function makeServerTag(namesArg, markersArg) { var names = namesArg === undefined ? Object.create(null) : namesArg; var markers = markersArg === undefined ? Object.create(null) : markersArg; var insertMarker = function insertMarker(id) { var prev = markers[id]; if (prev !== undefined) { return prev; } return markers[id] = ['']; }; var insertRules = function insertRules(id, cssRules, name) { var marker = insertMarker(id); marker[0] += cssRules.join(' '); addNameForId(names, id, name); }; var removeRules = function removeRules(id) { var marker = markers[id]; if (marker === undefined) return; marker[0] = ''; resetIdNames(names, id); }; var css = function css() { var str = ''; // eslint-disable-next-line guard-for-in for (var id in markers) { var cssForId = markers[id][0]; if (cssForId) { str += makeTextMarker(id) + cssForId; } } return str; }; var clone = function clone() { var namesClone = cloneNames(names); var markersClone = Object.create(null); // eslint-disable-next-line guard-for-in for (var id in markers) { markersClone[id] = [markers[id][0]]; } return makeServerTag(namesClone, markersClone); }; var tag = { clone: clone, css: css, getIds: getIdsFromMarkersFactory(markers), hasNameForId: hasNameForId(names), insertMarker: insertMarker, insertRules: insertRules, removeRules: removeRules, sealed: false, styleTag: null, toElement: wrapAsElement(css, names), toHTML: wrapAsHtmlTag(css, names) }; return tag; }; var makeTag = function makeTag(target, tagEl, forceServer, insertBefore, getImportRuleTag) { if (IS_BROWSER && !forceServer) { var el = makeStyleTag(target, tagEl, insertBefore); if (DISABLE_SPEEDY) { return makeBrowserTag(el, getImportRuleTag); } else { return makeSpeedyTag(el, getImportRuleTag); } } return makeServerTag(); }; /* wraps a given tag so that rehydration is performed once when necessary */ var makeRehydrationTag = function makeRehydrationTag(tag, els, extracted, immediateRehydration) { /* rehydration function that adds all rules to the new tag */ var rehydrate = once(function () { /* add all extracted components to the new tag */ for (var i = 0, len = extracted.length; i < len; i += 1) { var _extracted$i = extracted[i], componentId = _extracted$i.componentId, cssFromDOM = _extracted$i.cssFromDOM; var cssRules = splitByRules(cssFromDOM); tag.insertRules(componentId, cssRules); } /* remove old HTMLStyleElements, since they have been rehydrated */ for (var _i = 0, _len = els.length; _i < _len; _i += 1) { var el = els[_i]; if (el.parentNode) { el.parentNode.removeChild(el); } } }); if (immediateRehydration) rehydrate(); return _extends({}, tag, { /* add rehydration hook to methods */ insertMarker: function insertMarker(id) { rehydrate(); return tag.insertMarker(id); }, insertRules: function insertRules(id, cssRules, name) { rehydrate(); return tag.insertRules(id, cssRules, name); }, removeRules: function removeRules(id) { rehydrate(); return tag.removeRules(id); } }); }; // var SPLIT_REGEX = /\s+/; /* determine the maximum number of components before tags are sharded */ var MAX_SIZE = void 0; if (IS_BROWSER) { /* in speedy mode we can keep a lot more rules in a sheet before a slowdown can be expected */ MAX_SIZE = DISABLE_SPEEDY ? 40 : 1000; } else { /* for servers we do not need to shard at all */ MAX_SIZE = -1; } var sheetRunningId = 0; var master = void 0; var StyleSheet = function () { /* a map from ids to tags */ /* deferred rules for a given id */ /* this is used for not reinjecting rules via hasNameForId() */ /* when rules for an id are removed using remove() we have to ignore rehydratedNames for it */ /* a list of tags belonging to this StyleSheet */ /* a tag for import rules */ /* current capacity until a new tag must be created */ /* children (aka clones) of this StyleSheet inheriting all and future injections */ function StyleSheet() { var _this = this; var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : IS_BROWSER ? document.head : null; var forceServer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; classCallCheck(this, StyleSheet); this.getImportRuleTag = function () { var importRuleTag = _this.importRuleTag; if (importRuleTag !== undefined) { return importRuleTag; } var firstTag = _this.tags[0]; var insertBefore = true; return _this.importRuleTag = makeTag(_this.target, firstTag ? firstTag.styleTag : null, _this.forceServer, insertBefore); }; sheetRunningId += 1; this.id = sheetRunningId; this.forceServer = forceServer; this.target = forceServer ? null : target; this.tagMap = {}; this.deferred = {}; this.rehydratedNames = {}; this.ignoreRehydratedNames = {}; this.tags = []; this.capacity = 1; this.clones = []; } /* rehydrate all SSR'd style tags */ StyleSheet.prototype.rehydrate = function rehydrate() { if (!IS_BROWSER || this.forceServer) { return this; } var els = []; var extracted = []; var isStreamed = false; /* retrieve all of our SSR style elements from the DOM */ var nodes = document.querySelectorAll('style[' + SC_ATTR + '][' + SC_VERSION_ATTR + '="' + "4.0.0-beta.11.1-hmr" + '"]'); var nodesSize = nodes.length; /* abort rehydration if no previous style tags were found */ if (nodesSize === 0) { return this; } for (var i = 0; i < nodesSize; i += 1) { // $FlowFixMe: We can trust that all elements in this query are style elements var el = nodes[i]; /* check if style tag is a streamed tag */ if (!isStreamed) isStreamed = !!el.getAttribute(SC_STREAM_ATTR); /* retrieve all component names */ var elNames = (el.getAttribute(SC_ATTR) || '').trim().split(SPLIT_REGEX); var elNamesSize = elNames.length; for (var j = 0; j < elNamesSize; j += 1) { var name = elNames[j]; /* add rehydrated name to sheet to avoid readding styles */ this.rehydratedNames[name] = true; } /* extract all components and their CSS */ extracted.push.apply(extracted, extractComps(el.textContent)); /* store original HTMLStyleElement */ els.push(el); } /* abort rehydration if nothing was extracted */ var extractedSize = extracted.length; if (extractedSize === 0) { return this; } /* create a tag to be used for rehydration */ var tag = this.makeTag(null); var rehydrationTag = makeRehydrationTag(tag, els, extracted, isStreamed); /* reset capacity and adjust MAX_SIZE by the initial size of the rehydration */ this.capacity = Math.max(1, MAX_SIZE - extractedSize); this.tags.push(rehydrationTag); /* retrieve all component ids */ for (var _j = 0; _j < extractedSize; _j += 1) { this.tagMap[extracted[_j].componentId] = rehydrationTag; } return this; }; /* retrieve a "master" instance of StyleSheet which is typically used when no other is available * The master StyleSheet is targeted by createGlobalStyle, keyframes, and components outside of any * StyleSheetManager's context */ /* reset the internal "master" instance */ StyleSheet.reset = function reset() { var forceServer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; master = new StyleSheet(undefined, forceServer).rehydrate(); }; /* adds "children" to the StyleSheet that inherit all of the parents' rules * while their own rules do not affect the parent */ StyleSheet.prototype.clone = function clone() { var sheet = new StyleSheet(this.target, this.forceServer); /* add to clone array */ this.clones.push(sheet); /* clone all tags */ sheet.tags = this.tags.map(function (tag) { var ids = tag.getIds(); var newTag = tag.clone(); /* reconstruct tagMap */ for (var i = 0; i < ids.length; i += 1) { sheet.tagMap[ids[i]] = newTag; } return newTag; }); /* clone other maps */ sheet.rehydratedNames = _extends({}, this.rehydratedNames); sheet.deferred = _extends({}, this.deferred); return sheet; }; /* force StyleSheet to create a new tag on the next injection */ StyleSheet.prototype.sealAllTags = function sealAllTags() { this.capacity = 1; this.tags.forEach(function (tag) { // eslint-disable-next-line no-param-reassign tag.sealed = true; }); }; StyleSheet.prototype.makeTag = function makeTag$$1(tag) { var lastEl = tag ? tag.styleTag : null; var insertBefore = false; return makeTag(this.target, lastEl, this.forceServer, insertBefore, this.getImportRuleTag); }; /* get a tag for a given componentId, assign the componentId to one, or shard */ StyleSheet.prototype.getTagForId = function getTagForId(id) { /* simply return a tag, when the componentId was already assigned one */ var prev = this.tagMap[id]; if (prev !== undefined && !prev.sealed) { return prev; } var tag = this.tags[this.tags.length - 1]; /* shard (create a new tag) if the tag is exhausted (See MAX_SIZE) */ this.capacity -= 1; if (this.capacity === 0) { this.capacity = MAX_SIZE; tag = this.makeTag(tag); this.tags.push(tag); } return this.tagMap[id] = tag; }; /* mainly for createGlobalStyle to check for its id */ StyleSheet.prototype.hasId = function hasId(id) { return this.tagMap[id] !== undefined; }; /* caching layer checking id+name to already have a corresponding tag and injected rules */ StyleSheet.prototype.hasNameForId = function hasNameForId(id, name) { /* exception for rehydrated names which are checked separately */ if (this.ignoreRehydratedNames[id] === undefined && this.rehydratedNames[name]) { return true; } var tag = this.tagMap[id]; return tag !== undefined && tag.hasNameForId(id, name); }; /* registers a componentId and registers it on its tag */ StyleSheet.prototype.deferredInject = function deferredInject(id, cssRules) { /* don't inject when the id is already registered */ if (this.tagMap[id] !== undefined) return; var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].deferredInject(id, cssRules); } this.getTagForId(id).insertMarker(id); this.deferred[id] = cssRules; }; /* injects rules for a given id with a name that will need to be cached */ StyleSheet.prototype.inject = function inject(id, cssRules, name) { var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].inject(id, cssRules, name); } var tag = this.getTagForId(id); /* add deferred rules for component */ if (this.deferred[id] !== undefined) { // Combine passed cssRules with previously deferred CSS rules // NOTE: We cannot mutate the deferred array itself as all clones // do the same (see clones[i].inject) var rules = this.deferred[id].concat(cssRules); tag.insertRules(id, rules, name); this.deferred[id] = undefined; } else { tag.insertRules(id, cssRules, name); } }; /* removes all rules for a given id, which doesn't remove its marker but resets it */ StyleSheet.prototype.remove = function remove(id) { var tag = this.tagMap[id]; if (tag === undefined) return; var clones = this.clones; for (var i = 0; i < clones.length; i += 1) { clones[i].remove(id); } /* remove all rules from the tag */ tag.removeRules(id); /* ignore possible rehydrated names */ this.ignoreRehydratedNames[id] = true; /* delete possible deferred rules */ this.deferred[id] = undefined; }; StyleSheet.prototype.toHTML = function toHTML() { return this.tags.map(function (tag) { return tag.toHTML(); }).join(''); }; StyleSheet.prototype.toReactElements = function toReactElements() { var id = this.id; return this.tags.map(function (tag, i) { var key = 'sc-' + id + '-' + i; return cloneElement(tag.toElement(), { key: key }); }); }; createClass(StyleSheet, null, [{ key: 'master', get: function get$$1() { return master || (master = new StyleSheet().rehydrate()); } /* NOTE: This is just for backwards-compatibility with jest-styled-components */ }, { key: 'instance', get: function get$$1() { return StyleSheet.master; } }]); return StyleSheet; }(); // var Keyframes = function () { function Keyframes(name, rules) { var _this = this; classCallCheck(this, Keyframes); this.inject = function (styleSheet) { if (!styleSheet.hasNameForId(_this.id, _this.name)) { styleSheet.inject(_this.id, _this.rules, _this.name); } }; this.name = name; this.rules = rules; this.id = 'sc-keyframes-' + name; } Keyframes.prototype.getName = function getName() { return this.name; }; return Keyframes; }(); // /** * inlined version of * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js */ var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } // var objToCss = function objToCss(obj, prevKey) { var css = Object.keys(obj).filter(function (key) { var chunk = obj[key]; return chunk !== undefined && chunk !== null && chunk !== false && chunk !== ''; }).map(function (key) { if (isPlainObject(obj[key])) return objToCss(obj[key], key); return hyphenateStyleName(key) + ': ' + obj[key] + ';'; }).join(' '); return prevKey ? prevKey + ' {\n ' + css + '\n}' : css; }; /** * It's falsish not falsy because 0 is allowed. */ var isFalsish = function isFalsish(chunk) { return chunk === undefined || chunk === null || chunk === false || chunk === ''; }; function flatten(chunk, executionContext, styleSheet) { if (Array.isArray(chunk)) { var ruleSet = []; for (var i = 0, len = chunk.length, result; i < len; i += 1) { result = flatten(chunk[i], executionContext, styleSheet); if (result === null) continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result); } return ruleSet; } if (isFalsish(chunk)) { return null; } /* Handle other components */ if (isStyledComponent(chunk)) { return '.' + chunk.styledComponentId; } /* Either execute or defer the function */ if (isFunction(chunk)) { if (executionContext) { if (process.env.NODE_ENV !== 'production') { /* Warn if not referring styled component */ try { // eslint-disable-next-line new-cap if (isElement(new chunk(executionContext))) { console.warn(getComponentName(chunk) + ' is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.'); } // eslint-disable-next-line no-empty } catch (e) {} } return flatten(chunk(executionContext), executionContext, styleSheet); } else return chunk; } if (chunk instanceof Keyframes) { if (styleSheet) { chunk.inject(styleSheet); return chunk.getName(); } else return chunk; } /* Handle objects */ return isPlainObject(chunk) ? objToCss(chunk) : chunk.toString(); } // function css(styles) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (isFunction(styles) || isPlainObject(styles)) { // $FlowFixMe return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations))); } // $FlowFixMe return flatten(interleave(styles, interpolations)); } // function constructWithOptions(componentConstructor, tag) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT; if (!isValidElementType(tag)) { throw new StyledComponentsError(1, String(tag)); } /* This is callable directly as a template function */ // $FlowFixMe: Not typed to avoid destructuring arguments var templateFunction = function templateFunction() { return componentConstructor(tag, options, css.apply(undefined, arguments)); }; /* If config methods are called, wrap up a new template function and merge options */ templateFunction.withConfig = function (config) { return constructWithOptions(componentConstructor, tag, _extends({}, options, config)); }; templateFunction.attrs = function (attrs) { return constructWithOptions(componentConstructor, tag, _extends({}, options, { attrs: _extends({}, options.attrs || EMPTY_OBJECT, attrs) })); }; return templateFunction; } // // Source: https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js function murmurhash(c) { for (var e = c.length | 0, a = e | 0, d = 0, b; e >= 4;) { b = c.charCodeAt(d) & 255 | (c.charCodeAt(++d) & 255) << 8 | (c.charCodeAt(++d) & 255) << 16 | (c.charCodeAt(++d) & 255) << 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), b ^= b >>> 24, b = 1540483477 * (b & 65535) + ((1540483477 * (b >>> 16) & 65535) << 16), a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16) ^ b, e -= 4, ++d; } switch (e) { case 3: a ^= (c.charCodeAt(d + 2) & 255) << 16; case 2: a ^= (c.charCodeAt(d + 1) & 255) << 8; case 1: a ^= c.charCodeAt(d) & 255, a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16); } a ^= a >>> 13; a = 1540483477 * (a & 65535) + ((1540483477 * (a >>> 16) & 65535) << 16); return (a ^ a >>> 15) >>> 0; } // /* eslint-disable no-bitwise */ /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised * counterparts */ var charsLength = 52; /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */ var getAlphabeticChar = function getAlphabeticChar(code) { return String.fromCharCode(code + (code > 25 ? 39 : 97)); }; /* input a number, usually a hash and convert it to base-52 */ function generateAlphabeticName(code) { var name = ''; var x = void 0; /* get a char and divide by alphabet-length */ for (x = code; x > charsLength; x = Math.floor(x / charsLength)) { name = getAlphabeticChar(x % charsLength) + name; } return getAlphabeticChar(x % charsLength) + name; } // function isStaticRules(rules, attrs) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; // recursive case if (Array.isArray(rule) && !isStaticRules(rule)) { return false; } else if (isFunction(rule) && !isStyledComponent(rule)) { // functions are allowed to be static if they're just being // used to get the classname of a nested styled component return false; } } if (attrs !== undefined) { // eslint-disable-next-line guard-for-in, no-restricted-syntax for (var key in attrs) { var value = attrs[key]; if (isFunction(value)) { return false; } } } return true; } // // var isHMREnabled = process.env.NODE_ENV !== 'production' && typeof module !== 'undefined' && module.hot; /* combines hashStr (murmurhash) and nameGenerator for convenience */ var hasher = function hasher(str) { return generateAlphabeticName(murmurhash(str)); }; /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var ComponentStyle = function () { function ComponentStyle(rules, attrs, componentId) { classCallCheck(this, ComponentStyle); this.rules = rules; this.isStatic = !isHMREnabled && isStaticRules(rules, attrs); this.componentId = componentId; if (!StyleSheet.master.hasId(componentId)) { var placeholder = process.env.NODE_ENV !== 'production' ? ['.' + componentId + ' {}'] : []; StyleSheet.master.deferredInject(componentId, placeholder); } } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a .hash1234 {} * Returns the hash to be injected on render() * */ ComponentStyle.prototype.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) { var isStatic = this.isStatic, componentId = this.componentId, lastClassName = this.lastClassName; if (IS_BROWSER && isStatic && lastClassName !== undefined && styleSheet.hasNameForId(componentId, lastClassName)) { return lastClassName; } var flatCSS = flatten(this.rules, executionContext, styleSheet); var name = hasher(this.componentId + flatCSS.join('')); if (!styleSheet.hasNameForId(componentId, name)) { styleSheet.inject(this.componentId, stringifyRules(flatCSS, '.' + name, undefined, componentId), name); } this.lastClassName = name; return name; }; ComponentStyle.generateName = function generateName(str) { return hasher(str); }; return ComponentStyle; }(); // var LIMIT = 200; var createWarnTooManyClasses = (function (displayName) { var generatedClasses = {}; var warningSeen = false; return function (className) { if (!warningSeen) { generatedClasses[className] = true; if (Object.keys(generatedClasses).length >= LIMIT) { // Unable to find latestRule in test environment. /* eslint-disable no-console, prefer-template */ console.warn('Over ' + LIMIT + ' classes were generated for component ' + displayName + '. \n' + 'Consider using the attrs method, together with a style object for frequently changed styles.\n' + 'Example:\n' + ' const Component = styled.div.attrs({\n' + ' style: ({ background }) => ({\n' + ' background,\n' + ' }),\n' + ' })`width: 100%;`\n\n' + ' <Component />'); warningSeen = true; generatedClasses = {}; } } }; }); // var determineTheme = (function (props, fallbackTheme) { var defaultProps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EMPTY_OBJECT; // Props should take precedence over ThemeProvider, which should take precedence over // defaultProps, but React automatically puts defaultProps on props. /* eslint-disable react/prop-types, flowtype-errors/show-errors */ var isDefaultTheme = defaultProps ? props.theme === defaultProps.theme : false; var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme || defaultProps.theme; /* eslint-enable */ return theme; }); // var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g; var dashesAtEnds = /(^-|-$)/g; /** * TODO: Explore using CSS.escape when it becomes more available * in evergreen browsers. */ function escape(str) { return str // Replace all possible CSS selectors .replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end .replace(dashesAtEnds, ''); } // function isTag(target) /* : %checks */{ return typeof target === 'string'; } // function generateDisplayName(target) { return isTag(target) ? 'styled.' + target : 'Styled(' + getComponentName(target) + ')'; } var _TYPE_STATICS; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDerivedStateFromProps: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var TYPE_STATICS = (_TYPE_STATICS = {}, _TYPE_STATICS[ForwardRef] = { $$typeof: true, render: true }, _TYPE_STATICS); var defineProperty$1 = Object.defineProperty, getOwnPropertyNames = Object.getOwnPropertyNames, _Object$getOwnPropert = Object.getOwnPropertySymbols, getOwnPropertySymbols = _Object$getOwnPropert === undefined ? function () { return []; } : _Object$getOwnPropert, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getPrototypeOf = Object.getPrototypeOf, objectPrototype = Object.prototype; var arrayPrototype = Array.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } var keys = arrayPrototype.concat(getOwnPropertyNames(sourceComponent), // $FlowFixMe getOwnPropertySymbols(sourceComponent)); var targetStatics = TYPE_STATICS[targetComponent.$$typeof] || REACT_STATICS; var sourceStatics = TYPE_STATICS[sourceComponent.$$typeof] || REACT_STATICS; var i = keys.length; var descriptor = void 0; var key = void 0; // eslint-disable-next-line no-plusplus while (i--) { key = keys[i]; if ( // $FlowFixMe !KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && // $FlowFixMe !(targetStatics && targetStatics[key])) { descriptor = getOwnPropertyDescriptor(sourceComponent, key); if (descriptor) { try { // Avoid failures from read-only properties defineProperty$1(targetComponent, key, descriptor); } catch (e) { /* fail silently */ } } } } return targetComponent; } return targetComponent; } // function isDerivedReactComponent(fn) { return !!(fn && fn.prototype && fn.prototype.isReactComponent); } // var ThemeContext = createContext(); var ThemeConsumer = ThemeContext.Consumer; /** * Provide a theme to an entire react component tree via context */ var ThemeProvider = function (_Component) { inherits(ThemeProvider, _Component); function ThemeProvider(props) { classCallCheck(this, ThemeProvider); var _this = possibleConstructorReturn(this, _Component.call(this, props)); _this.getContext = memoize(_this.getContext.bind(_this)); _this.renderInner = _this.renderInner.bind(_this); return _this; } ThemeProvider.prototype.render = function render() { if (!this.props.children) return null; return React.createElement( ThemeContext.Consumer, null, this.renderInner ); }; ThemeProvider.prototype.renderInner = function renderInner(outerTheme) { var context = this.getContext(this.props.theme, outerTheme); return React.createElement( ThemeContext.Provider, { value: context }, React.Children.only(this.props.children) ); }; /** * Get the theme from the props, supporting both (outerTheme) => {} * as well as object notation */ ThemeProvider.prototype.getTheme = function getTheme(theme, outerTheme) { if (isFunction(theme)) { var mergedTheme = theme(outerTheme); if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || (typeof mergedTheme === 'undefined' ? 'undefined' : _typeof(mergedTheme)) !== 'object')) { throw new StyledComponentsError(7); } return mergedTheme; } if (theme === null || Array.isArray(theme) || (typeof theme === 'undefined' ? 'undefined' : _typeof(theme)) !== 'object') { throw new StyledComponentsError(8); } return _extends({}, outerTheme, theme); }; ThemeProvider.prototype.getContext = function getContext(theme, outerTheme) { return this.getTheme(theme, outerTheme); }; return ThemeProvider; }(Component); // var ServerStyleSheet = function () { function ServerStyleSheet() { classCallCheck(this, ServerStyleSheet); /* The master sheet might be reset, so keep a reference here */ this.masterSheet = StyleSheet.master; this.instance = this.masterSheet.clone(); this.sealed = false; } /** * Mark the ServerStyleSheet as being fully emitted and manually GC it from the * StyleSheet singleton. */ ServerStyleSheet.prototype.seal = function seal() { if (!this.sealed) { /* Remove sealed StyleSheets from the master sheet */ var index = this.masterSheet.clones.indexOf(this.instance); this.masterSheet.clones.splice(index, 1); this.sealed = true; } }; ServerStyleSheet.prototype.collectStyles = function collectStyles(children) { if (this.sealed) { throw new StyledComponentsError(2); } return React.createElement( StyleSheetManager, { sheet: this.instance }, children ); }; ServerStyleSheet.prototype.getStyleTags = function getStyleTags() { this.seal(); return this.instance.toHTML(); }; ServerStyleSheet.prototype.getStyleElement = function getStyleElement() { this.seal(); return this.instance.toReactElements(); }; ServerStyleSheet.prototype.interleaveWithNodeStream = function interleaveWithNodeStream(readableStream) { var _this = this; if (IS_BROWSER) { throw new StyledComponentsError(3); } /* the tag index keeps track of which tags have already been emitted */ var instance = this.instance; var instanceTagIndex = 0; var streamAttr = SC_STREAM_ATTR + '="true"'; var transformer = new stream.Transform({ transform: function appendStyleChunks(chunk, /* encoding */_, callback) { var tags = instance.tags; var html = ''; /* retrieve html for each new style tag */ for (; instanceTagIndex < tags.length; instanceTagIndex += 1) { var tag = tags[instanceTagIndex]; html += tag.toHTML(streamAttr); } /* force our StyleSheets to emit entirely new tags */ instance.sealAllTags(); /* prepend style html to chunk */ this.push(html + chunk); callback(); } }); readableStream.on('end', function () { return _this.seal(); }); readableStream.on('error', function (err) { _this.seal(); // forward the error to the transform stream transformer.emit('error', err); }); return readableStream.pipe(transformer); }; return ServerStyleSheet; }(); // var StyleSheetContext = createContext(); var StyleSheetConsumer = StyleSheetContext.Consumer; var StyleSheetManager = function (_Component) { inherits(StyleSheetManager, _Component); function StyleSheetManager(props) { classCallCheck(this, StyleSheetManager); var _this = possibleConstructorReturn(this, _Component.call(this, props)); _this.getContext = memoize(_this.getContext); return _this; } StyleSheetManager.prototype.getContext = function getContext(sheet, target) { if (sheet) { return sheet; } else if (target) { return new StyleSheet(target); } else { throw new StyledComponentsError(4); } }; StyleSheetManager.prototype.render = function render() { var _props = this.props, children = _props.children, sheet = _props.sheet, target = _props.target; var context = this.getContext(sheet, target); return React.createElement( StyleSheetContext.Provider, { value: context }, React.Children.only(children) ); }; return StyleSheetManager; }(Component); process.env.NODE_ENV !== "production" ? StyleSheetManager.propTypes = { sheet: PropTypes.oneOfType([PropTypes.instanceOf(StyleSheet), PropTypes.instanceOf(ServerStyleSheet)]), target: PropTypes.shape({ appendChild: PropTypes.func.isRequired }) } : void 0; // var classNameUseCheckInjector = (function (target) { var elementClassName = ''; var targetCDM = target.componentDidMount; // eslint-disable-next-line no-param-reassign target.componentDidMount = function componentDidMount() { if (typeof targetCDM === 'function') { targetCDM.call(this); } var classNames = elementClassName.split(' '); // eslint-disable-next-line react/no-find-dom-node var node = ReactDOM.findDOMNode(this); var selector = classNames.map(function (s) { return '.' + s; }).join(''); if (node && node.nodeType === 1 && !classNames.every(function (className) { return node.classList && node.classList.contains(className); }) && !node.querySelector(selector)) { console.warn('It looks like you\'ve wrapped styled() around your React component (' + getComponentName(this.props.forwardedClass.target) + '), but the className prop is not being passed down to a child. No styles will be rendered unless className is composed within your React component.'); } }; var prevRenderInner = target.renderInner; // eslint-disable-next-line no-param-reassign target.renderInner = function renderInner() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var element = prevRenderInner.apply(this, args); elementClassName = element.props.className; return element; }; }); // var identifiers = {}; /* We depend on components having unique IDs */ function generateId(_ComponentStyle, _displayName, parentComponentId) { var displayName = typeof _displayName !== 'string' ? 'sc' : escape(_displayName); /** * This ensures uniqueness if two components happen to share * the same displayName. */ var nr = (identifiers[displayName] || 0) + 1; identifiers[displayName] = nr; var componentId = displayName + '-' + _ComponentStyle.generateName(displayName + nr); return parentComponentId ? parentComponentId + '-' + componentId : componentId; } var warnInnerRef = once(function () { return ( // eslint-disable-next-line no-console console.warn('The "innerRef" API has been removed in styled-components v4 in favor of React 16 ref forwarding, use "ref" instead like a typical component.') ); }); // $FlowFixMe var StyledComponent = function (_Component) { inherits(StyledComponent, _Component); function StyledComponent() { classCallCheck(this, StyledComponent); var _this = possibleConstructorReturn(this, _Component.call(this)); _this.attrs = {}; _this.renderOuter = _this.renderOuter.bind(_this); _this.renderInner = _this.renderInner.bind(_this); if (process.env.NODE_ENV !== 'production' && IS_BROWSER) { classNameUseCheckInjector(_this); } return _this; } StyledComponent.prototype.render = function render() { return React.createElement( StyleSheetConsumer, null, this.renderOuter ); }; StyledComponent.prototype.renderOuter = function renderOuter(styleSheet) { this.styleSheet = styleSheet; return React.createElement( ThemeConsumer, null, this.renderInner ); }; StyledComponent.prototype.renderInner = function renderInner(theme) { var _props$forwardedClass = this.props.forwardedClass, componentStyle = _props$forwardedClass.componentStyle, defaultProps = _props$forwardedClass.defaultProps, styledComponentId = _props$forwardedClass.styledComponentId, target = _props$forwardedClass.target; var generatedClassName = void 0; if (componentStyle.isStatic) { generatedClassName = this.generateAndInjectStyles(EMPTY_OBJECT, this.props, this.styleSheet); } else if (theme !== undefined) { generatedClassName = this.generateAndInjectStyles(determineTheme(this.props, theme, defaultProps), this.props, this.styleSheet); } else { generatedClassName = this.generateAndInjectStyles(this.props.theme || EMPTY_OBJECT, this.props, this.styleSheet); } var elementToBeCreated = this.props.as || this.attrs.as || target; var isTargetTag = isTag(elementToBeCreated); var propsForElement = _extends({}, this.attrs); var key = void 0; // eslint-disable-next-line guard-for-in for (key in this.props) { if (process.env.NODE_ENV !== 'production' && key === 'innerRef') { warnInnerRef(); } if (key === 'forwardedClass' || key === 'as') continue;else if (key === 'forwardedRef') propsForElement.ref = this.props[key];else if (!isTargetTag || validAttr(key)) { // Don't pass through non HTML tags through to HTML elements propsForElement[key] = key === 'style' && key in this.attrs ? _extends({}, this.attrs[key], this.props[key]) : this.props[key]; } } propsForElement.className = [this.props.className, styledComponentId, this.attrs.className, generatedClassName].filter(Boolean).join(' '); return createElement(elementToBeCreated, propsForElement); }; StyledComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props, attrs) { var context = _extends({}, props, { theme: theme }); if (attrs === undefined) return context; this.attrs = {}; var attr = void 0; var key = void 0; /* eslint-disable guard-for-in */ for (key in attrs) { attr = attrs[key]; this.attrs[key] = isFunction(attr) && !isDerivedReactComponent(attr) && !isStyledComponent(attr) ? attr(context) : attr; } /* eslint-enable */ return _extends({}, context, this.attrs); }; StyledComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) { var styleSheet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : StyleSheet.master; var _props$forwardedClass2 = props.forwardedClass, attrs = _props$forwardedClass2.attrs, componentStyle = _props$forwardedClass2.componentStyle, warnTooManyClasses = _props$forwardedClass2.warnTooManyClasses; // statically styled-components don't need to build an execution context object, // and shouldn't be increasing the number of class names if (componentStyle.isStatic && attrs === undefined) { return componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet); } var className = componentStyle.generateAndInjectStyles(this.buildExecutionContext(theme, props, props.forwardedClass.attrs), styleSheet); if (warnTooManyClasses) { warnTooManyClasses(className); } return className; }; return StyledComponent; }(Component); function createStyledComponent(target, options, rules) { var isTargetStyledComp = isStyledComponent(target); var isClass = !isTag(target); var _options$displayName = options.displayName, displayName = _options$displayName === undefined ? generateDisplayName(target) : _options$displayName, _options$componentId = options.componentId, componentId = _options$componentId === undefined ? generateId(ComponentStyle, options.displayName, options.parentComponentId) : _options$componentId, _options$ParentCompon = options.ParentComponent, ParentComponent = _options$ParentCompon === undefined ? StyledComponent : _options$ParentCompon, attrs = options.attrs; var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + '-' + options.componentId : options.componentId || componentId; // fold the underlying StyledComponent attrs up (implicit extend) var finalAttrs = // $FlowFixMe isTargetStyledComp && target.attrs ? _extends({}, target.attrs, attrs) : attrs; var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend) // $FlowFixMe target.componentStyle.rules.concat(rules) : rules, finalAttrs, styledComponentId); /** * forwardRef creates a new interim component, which we'll take advantage of * instead of extending ParentComponent to create _another_ interim class */ var WrappedStyledComponent = React.forwardRef(function (props, ref) { return React.createElement(ParentComponent, _extends({}, props, { forwardedClass: WrappedStyledComponent, forwardedRef: ref })); }); // $FlowFixMe WrappedStyledComponent.attrs = finalAttrs; // $FlowFixMe WrappedStyledComponent.componentStyle = componentStyle; WrappedStyledComponent.displayName = displayName; // $FlowFixMe WrappedStyledComponent.styledComponentId = styledComponentId; // fold the underlying StyledComponent target up since we folded the styles // $FlowFixMe WrappedStyledComponent.target = isTargetStyledComp ? target.target : target; // $FlowFixMe WrappedStyledComponent.withComponent = function withComponent(tag) { var previousComponentId = options.componentId, optionsToCopy = objectWithoutProperties(options, ['componentId']); var newComponentId = previousComponentId && previousComponentId + '-' + (isTag(tag) ? tag : escape(getComponentName(tag))); var newOptions = _extends({}, optionsToCopy, { attrs: finalAttrs, componentId: newComponentId, ParentComponent: ParentComponent }); return createStyledComponent(tag, newOptions, rules); }; if (process.env.NODE_ENV !== 'production') { // $FlowFixMe WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName); } if (isClass) { hoistNonReactStatics(WrappedStyledComponent, target, { // all SC-specific things should not be hoisted attrs: true, componentStyle: true, displayName: true, styledComponentId: true, target: true, warnTooManyClasses: true, withComponent: true }); } return WrappedStyledComponent; } // // Thanks to ReactDOMFactories for this handy list! var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // var styled = function styled(tag) { return constructWithOptions(createStyledComponent, tag); }; // Shorthands for all valid HTML Elements domElements.forEach(function (domElement) { styled[domElement] = styled(domElement); }); // var GlobalStyle = function () { function GlobalStyle(rules, componentId) { classCallCheck(this, GlobalStyle); this.rules = rules; this.componentId = componentId; this.isStatic = isStaticRules(rules); if (!StyleSheet.master.hasId(componentId)) { StyleSheet.master.deferredInject(componentId, []); } } GlobalStyle.prototype.createStyles = function createStyles(executionContext, styleSheet) { var flatCSS = flatten(this.rules, executionContext, styleSheet); var css = stringifyRules(flatCSS, ''); styleSheet.inject(this.componentId, css); }; GlobalStyle.prototype.removeStyles = function removeStyles(styleSheet) { var componentId = this.componentId; if (styleSheet.hasId(componentId)) { styleSheet.remove(componentId); } }; // TODO: overwrite in-place instead of remove+create? GlobalStyle.prototype.renderStyles = function renderStyles(executionContext, styleSheet) { this.removeStyles(styleSheet); this.createStyles(executionContext, styleSheet); }; return GlobalStyle; }(); // function createGlobalStyle(strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var id = 'sc-global-' + murmurhash(JSON.stringify(rules)); var style = new GlobalStyle(rules, id); var instances = []; var GlobalStyleComponent = function (_React$Component) { inherits(GlobalStyleComponent, _React$Component); function GlobalStyleComponent() { classCallCheck(this, GlobalStyleComponent); var _this = possibleConstructorReturn(this, _React$Component.call(this)); instances.push(_this); /** * This fixes HMR compatiblility. Don't ask me why, but this combination of * caching the closure variables via statics and then persisting the statics in * state works across HMR where no other combination did. ¯\_(ツ)_/¯ */ _this.state = { globalStyle: _this.constructor.globalStyle, styledComponentId: _this.constructor.styledComponentId }; return _this; } GlobalStyleComponent.prototype.componentDidMount = function componentDidMount() { if (process.env.NODE_ENV !== 'production' && IS_BROWSER && instances.length > 1) { console.warn('The global style component ' + this.state.styledComponentId + ' was composed and rendered multiple times in your React component tree. Only the last-rendered copy will have its styles remain in <head> (or your StyleSheetManager target.)'); } }; GlobalStyleComponent.prototype.componentWillUnmount = function componentWillUnmount() { if (instances.includes(this)) instances.splice(instances.indexOf(this), 1); /** * Depending on the order "render" is called this can cause the styles to be lost * until the next render pass of the remaining instance, which may * not be immediate. */ if (instances.length === 0) this.state.globalStyle.removeStyles(this.styleSheet); }; GlobalStyleComponent.prototype.render = function render() { var _this2 = this; if (process.env.NODE_ENV !== 'production' && React.Children.count(this.props.children)) { console.warn('The global style component ' + this.state.styledComponentId + ' was given child JSX. createGlobalStyle does not render children.'); } return React.createElement( StyleSheetConsumer, null, function (styleSheet) { _this2.styleSheet = styleSheet || StyleSheet.master; var globalStyle = _this2.state.globalStyle; if (globalStyle.isStatic) { globalStyle.renderStyles(STATIC_EXECUTION_CONTEXT, _this2.styleSheet); return null; } else { return React.createElement( ThemeConsumer, null, function (theme) { var defaultProps = _this2.constructor.defaultProps; var context = _extends({}, _this2.props); if (typeof theme !== 'undefined') { context.theme = determineTheme(_this2.props, theme, defaultProps); } globalStyle.renderStyles(context, _this2.styleSheet); return null; } ); } } ); }; return GlobalStyleComponent; }(React.Component); GlobalStyleComponent.globalStyle = style; GlobalStyleComponent.styledComponentId = id; return GlobalStyleComponent; } // var replaceWhitespace = function replaceWhitespace(str) { return str.replace(/\s|\\n/g, ''); }; function keyframes(strings) { /* Warning if you've used keyframes on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { console.warn('`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.'); } for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var name = generateAlphabeticName(murmurhash(replaceWhitespace(JSON.stringify(rules)))); return new Keyframes(name, stringifyRules(rules, name, '@keyframes')); } // var withTheme = (function (Component$$1) { var WithTheme = React.forwardRef(function (props, ref) { return React.createElement( ThemeConsumer, null, function (theme) { // $FlowFixMe var defaultProps = Component$$1.defaultProps; var themeProp = determineTheme(props, theme, defaultProps); if (process.env.NODE_ENV !== 'production' && themeProp === undefined) { // eslint-disable-next-line no-console console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class ' + getComponentName(Component$$1)); } return React.createElement(Component$$1, _extends({}, props, { theme: themeProp, ref: ref })); } ); }); hoistNonReactStatics(WithTheme, Component$$1); WithTheme.displayName = 'WithTheme(' + getComponentName(Component$$1) + ')'; return WithTheme; }); // /* eslint-disable */ var __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS = { StyleSheet: StyleSheet }; // /* Warning if you've imported this file on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn("It looks like you've imported 'styled-components' on React Native.\n" + "Perhaps you're looking to import 'styled-components/native'?\n" + 'Read more about this at https://www.styled-components.com/docs/basics#react-native'); } /* Warning if there are several instances of styled-components */ if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test' && typeof window !== 'undefined' && typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Node.js') === -1 && navigator.userAgent.indexOf('jsdom') === -1) { window['__styled-components-init__'] = window['__styled-components-init__'] || 0; if (window['__styled-components-init__'] === 1) { // eslint-disable-next-line no-console console.warn("It looks like there are several instances of 'styled-components' initialized in this application. " + 'This may cause dynamic styles not rendering properly, errors happening during rehydration process ' + 'and makes your application bigger without a good reason.\n\n' + 'See https://s-c.sh/2BAXzed for more info.'); } window['__styled-components-init__'] += 1; } // export default styled; export { css, keyframes, createGlobalStyle, isStyledComponent, ThemeConsumer, ThemeProvider, withTheme, ServerStyleSheet, StyleSheetManager, __DO_NOT_USE_OR_YOU_WILL_BE_HAUNTED_BY_SPOOKY_GHOSTS }; //# sourceMappingURL=styled-components.esm.js.map
/* Highcharts JS v2.3.0 (2012-08-24) Exporting module (c) 2010-2011 Torstein H?nsi License: www.highcharts.com/license */ (function(){function x(a){for(var b=a.length;b--;)typeof a[b]==="number"&&(a[b]=Math.round(a[b])-0.5);return a}var g=Highcharts,y=g.Chart,z=g.addEvent,B=g.removeEvent,r=g.createElement,u=g.discardElement,t=g.css,s=g.merge,k=g.each,n=g.extend,C=Math.max,h=document,D=window,A=h.documentElement.ontouchstart!==void 0,v=g.getOptions();n(v.lang,{downloadPNG:"Download PNG image",downloadJPEG:"Download JPEG image",downloadPDF:"Download PDF document",downloadSVG:"Download SVG vector image",exportButtonTitle:"Export to raster or vector image", printButtonTitle:"Print the chart"});v.navigation={menuStyle:{border:"1px solid #A0A0A0",background:"#FFFFFF"},menuItemStyle:{padding:"0 5px",background:"none",color:"#303030",fontSize:A?"14px":"11px"},menuItemHoverStyle:{background:"#4572A5",color:"#FFFFFF"},buttonOptions:{align:"right",backgroundColor:{linearGradient:[0,0,0,20],stops:[[0.4,"#F7F7F7"],[0.6,"#E3E3E3"]]},borderColor:"#B0B0B0",borderRadius:3,borderWidth:1,height:20,hoverBorderColor:"#909090",hoverSymbolFill:"#81A7CF",hoverSymbolStroke:"#4572A5", symbolFill:"#E0E0E0",symbolStroke:"#A0A0A0",symbolX:11.5,symbolY:10.5,verticalAlign:"top",width:24,y:10}};v.exporting={type:"image/png",url:"http://export.highcharts.com/",width:800,buttons:{exportButton:{symbol:"exportIcon",x:-10,symbolFill:"#A8BF77",hoverSymbolFill:"#768F3E",_id:"exportButton",_titleKey:"exportButtonTitle",menuItems:[{textKey:"downloadPNG",onclick:function(){this.exportChart()}},{textKey:"downloadJPEG",onclick:function(){this.exportChart({type:"image/jpeg"})}},{textKey:"downloadPDF", onclick:function(){this.exportChart({type:"application/pdf"})}},{textKey:"downloadSVG",onclick:function(){this.exportChart({type:"image/svg+xml"})}}]},printButton:{symbol:"printIcon",x:-36,symbolFill:"#B5C9DF",hoverSymbolFill:"#779ABF",_id:"printButton",_titleKey:"printButtonTitle",onclick:function(){this.print()}}}};n(y.prototype,{getSVG:function(a){var b=this,c,d,e,f=s(b.options,a);if(!h.createElementNS)h.createElementNS=function(a,b){return h.createElement(b)};a=r("div",null,{position:"absolute", top:"-9999em",width:b.chartWidth+"px",height:b.chartHeight+"px"},h.body);n(f.chart,{renderTo:a,forExport:!0});f.exporting.enabled=!1;f.chart.plotBackgroundImage=null;f.series=[];k(b.series,function(a){e=s(a.options,{animation:!1,showCheckbox:!1,visible:a.visible});if(!e.isInternal){if(e&&e.marker&&/^url\(/.test(e.marker.symbol))e.marker.symbol="circle";f.series.push(e)}});c=new Highcharts.Chart(f);k(["xAxis","yAxis"],function(a){k(b[a],function(b,d){var e=c[a][d],f=b.getExtremes(),g=f.userMin,f=f.userMax; (g!==void 0||f!==void 0)&&e.setExtremes(g,f,!0,!1)})});d=c.container.innerHTML;f=null;c.destroy();u(a);d=d.replace(/zIndex="[^"]+"/g,"").replace(/isShadow="[^"]+"/g,"").replace(/symbolName="[^"]+"/g,"").replace(/jQuery[0-9]+="[^"]+"/g,"").replace(/isTracker="[^"]+"/g,"").replace(/url\([^#]+#/g,"url(#").replace(/<svg /,'<svg xmlns:xlink="http://www.w3.org/1999/xlink" ').replace(/ href=/g," xlink:href=").replace(/\n/," ").replace(/<\/svg>.*?$/,"</svg>").replace(/&nbsp;/g,"\u00a0").replace(/&shy;/g, "\u00ad").replace(/<IMG /g,"<image ").replace(/height=([^" ]+)/g,'height="$1"').replace(/width=([^" ]+)/g,'width="$1"').replace(/hc-svg-href="([^"]+)">/g,'xlink:href="$1"/>').replace(/id=([^" >]+)/g,'id="$1"').replace(/class=([^" ]+)/g,'class="$1"').replace(/ transform /g," ").replace(/:(path|rect)/g,"$1").replace(/style="([^"]+)"/g,function(a){return a.toLowerCase()});d=d.replace(/(url\(#highcharts-[0-9]+)&quot;/g,"$1").replace(/&quot;/g,"'");d.match(/ xmlns="/g).length===2&&(d=d.replace(/xmlns="[^"]+"/, ""));return d},exportChart:function(a,b){var c,d=this.getSVG(s(this.options.exporting.chartOptions,b)),a=s(this.options.exporting,a);c=r("form",{method:"post",action:a.url,enctype:"multipart/form-data"},{display:"none"},h.body);k(["filename","type","width","svg"],function(b){r("input",{type:"hidden",name:b,value:{filename:a.filename||"chart",type:a.type,width:a.width,svg:d}[b]},null,c)});c.submit();u(c)},print:function(){var a=this,b=a.container,c=[],d=b.parentNode,e=h.body,f=e.childNodes;if(!a.isPrinting)a.isPrinting= !0,k(f,function(a,b){if(a.nodeType===1)c[b]=a.style.display,a.style.display="none"}),e.appendChild(b),D.print(),setTimeout(function(){d.appendChild(b);k(f,function(a,b){if(a.nodeType===1)a.style.display=c[b]});a.isPrinting=!1},1E3)},contextMenu:function(a,b,c,d,e,f){var i=this,g=i.options.navigation,h=g.menuItemStyle,o=i.chartWidth,p=i.chartHeight,q="cache-"+a,j=i[q],l=C(e,f),m,w;if(!j)i[q]=j=r("div",{className:"highcharts-"+a},{position:"absolute",zIndex:1E3,padding:l+"px"},i.container),m=r("div", null,n({MozBoxShadow:"3px 3px 10px #888",WebkitBoxShadow:"3px 3px 10px #888",boxShadow:"3px 3px 10px #888"},g.menuStyle),j),w=function(){t(j,{display:"none"})},z(j,"mouseleave",w),k(b,function(a){if(a){var b=r("div",{onmouseover:function(){t(this,g.menuItemHoverStyle)},onmouseout:function(){t(this,h)},innerHTML:a.text||i.options.lang[a.textKey]},n({cursor:"pointer"},h),m);b[A?"ontouchstart":"onclick"]=function(){w();a.onclick.apply(i,arguments)};i.exportDivElements.push(b)}}),i.exportDivElements.push(m, j),i.exportMenuWidth=j.offsetWidth,i.exportMenuHeight=j.offsetHeight;a={display:"block"};c+i.exportMenuWidth>o?a.right=o-c-e-l+"px":a.left=c-l+"px";d+f+i.exportMenuHeight>p?a.bottom=p-d-l+"px":a.top=d+f-l+"px";t(j,a)},addButton:function(a){function b(){p.attr(l);o.attr(j)}var c=this,d=c.renderer,e=s(c.options.navigation.buttonOptions,a),f=e.onclick,g=e.menuItems,h=e.width,k=e.height,o,p,q,a=e.borderWidth,j={stroke:e.borderColor},l={stroke:e.symbolStroke,fill:e.symbolFill},m=e.symbolSize||12;if(!c.exportDivElements)c.exportDivElements= [],c.exportSVGElements=[];e.enabled!==!1&&(o=d.rect(0,0,h,k,e.borderRadius,a).align(e,!0).attr(n({fill:e.backgroundColor,"stroke-width":a,zIndex:19},j)).add(),q=d.rect(0,0,h,k,0).align(e).attr({id:e._id,fill:"rgba(255, 255, 255, 0.001)",title:c.options.lang[e._titleKey],zIndex:21}).css({cursor:"pointer"}).on("mouseover",function(){p.attr({stroke:e.hoverSymbolStroke,fill:e.hoverSymbolFill});o.attr({stroke:e.hoverBorderColor})}).on("mouseout",b).on("click",b).add(),g&&(f=function(){b();var a=q.getBBox(); c.contextMenu("export-menu",g,a.x,a.y,h,k)}),q.on("click",function(){f.apply(c,arguments)}),p=d.symbol(e.symbol,e.symbolX-m/2,e.symbolY-m/2,m,m).align(e,!0).attr(n(l,{"stroke-width":e.symbolStrokeWidth||1,zIndex:20})).add(),c.exportSVGElements.push(o,q,p))},destroyExport:function(){var a,b;for(a=0;a<this.exportSVGElements.length;a++)b=this.exportSVGElements[a],b.onclick=b.ontouchstart=null,this.exportSVGElements[a]=b.destroy();for(a=0;a<this.exportDivElements.length;a++)b=this.exportDivElements[a], B(b,"mouseleave"),this.exportDivElements[a]=b.onmouseout=b.onmouseover=b.ontouchstart=b.onclick=null,u(b)}});g.Renderer.prototype.symbols.exportIcon=function(a,b,c,d){return x(["M",a,b+c,"L",a+c,b+d,a+c,b+d*0.8,a,b+d*0.8,"Z","M",a+c*0.5,b+d*0.8,"L",a+c*0.8,b+d*0.4,a+c*0.4,b+d*0.4,a+c*0.4,b,a+c*0.6,b,a+c*0.6,b+d*0.4,a+c*0.2,b+d*0.4,"Z"])};g.Renderer.prototype.symbols.printIcon=function(a,b,c,d){return x(["M",a,b+d*0.7,"L",a+c,b+d*0.7,a+c,b+d*0.4,a,b+d*0.4,"Z","M",a+c*0.2,b+d*0.4,"L",a+c*0.2,b,a+c* 0.8,b,a+c*0.8,b+d*0.4,"Z","M",a+c*0.2,b+d*0.7,"L",a,b+d,a+c,b+d,a+c*0.8,b+d*0.7,"Z"])};y.prototype.callbacks.push(function(a){var b,c=a.options.exporting,d=c.buttons;if(c.enabled!==!1){for(b in d)a.addButton(d[b]);z(a,"destroy",a.destroyExport)}})})();
// Domain Public by Eric Wendelin http://eriwen.com/ (2008) // Luke Smith http://lucassmith.name/ (2008) // Loic Dachary <loic@dachary.org> (2008) // Johan Euphrosine <proppy@aminche.com> (2008) // Øyvind Sean Kinsey http://kinsey.no/blog (2010) // // Information and discussions // http://jspoker.pokersource.info/skin/test-printstacktrace.html // http://eriwen.com/javascript/js-stack-trace/ // http://eriwen.com/javascript/stacktrace-update/ // http://pastie.org/253058 // // guessFunctionNameFromLines comes from firebug // // Software License Agreement (BSD License) // // Copyright (c) 2007, Parakey Inc. // All rights reserved. // // Redistribution and use of this software in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the // following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other // materials provided with the distribution. // // * Neither the name of Parakey Inc. nor the names of its // contributors may be used to endorse or promote products // derived from this software without specific prior // written permission of Parakey Inc. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER // IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * Main function giving a function stack trace with a forced or passed in Error * * @cfg {Error} e The error to create a stacktrace from (optional) * @cfg {Boolean} guess If we should try to resolve the names of anonymous functions * @return {Array} of Strings with functions, lines, files, and arguments where possible */ function printStackTrace(options) { var ex = (options && options.e) ? options.e : null; var guess = options ? !!options.guess : true; var p = new printStackTrace.implementation(); var result = p.run(ex); return (guess) ? p.guessFunctions(result) : result; } printStackTrace.implementation = function() {}; printStackTrace.implementation.prototype = { run: function(ex) { ex = ex || (function() { try { var _err = __undef__ << 1; } catch (e) { return e; } })(); // Use either the stored mode, or resolve it var mode = this._mode || this.mode(ex); if (mode === 'other') { return this.other(arguments.callee); } else { return this[mode](ex); } }, /** * @return {String} mode of operation for the environment in question. */ mode: function(e) { if (e['arguments']) { return (this._mode = 'chrome'); } else if (window.opera && e.stacktrace) { return (this._mode = 'opera10'); } else if (e.stack) { return (this._mode = 'firefox'); } else if (window.opera && !('stacktrace' in e)) { //Opera 9- return (this._mode = 'opera'); } return (this._mode = 'other'); }, /** * Given a context, function name, and callback function, overwrite it so that it calls * printStackTrace() first with a callback and then runs the rest of the body. * * @param {Object} context of execution (e.g. window) * @param {String} functionName to instrument * @param {Function} function to call with a stack trace on invocation */ instrumentFunction: function(context, functionName, callback) { context = context || window; context['_old' + functionName] = context[functionName]; context[functionName] = function() { callback.call(this, printStackTrace()); return context['_old' + functionName].apply(this, arguments); }; context[functionName]._instrumented = true; }, /** * Given a context and function name of a function that has been * instrumented, revert the function to it's original (non-instrumented) * state. * * @param {Object} context of execution (e.g. window) * @param {String} functionName to de-instrument */ deinstrumentFunction: function(context, functionName) { if (context[functionName].constructor === Function && context[functionName]._instrumented && context['_old' + functionName].constructor === Function) { context[functionName] = context['_old' + functionName]; } }, /** * Given an Error object, return a formatted Array based on Chrome's stack string. * * @param e - Error object to inspect * @return Array<String> of function calls, files and line numbers */ chrome: function(e) { return e.stack.replace(/^[^\(]+?[\n$]/gm, '').replace(/^\s+at\s+/gm, '').replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@').split('\n'); }, /** * Given an Error object, return a formatted Array based on Firefox's stack string. * * @param e - Error object to inspect * @return Array<String> of function calls, files and line numbers */ firefox: function(e) { return e.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n'); }, /** * Given an Error object, return a formatted Array based on Opera 10's stacktrace string. * * @param e - Error object to inspect * @return Array<String> of function calls, files and line numbers */ opera10: function(e) { var stack = e.stacktrace; var lines = stack.split('\n'), ANON = '{anonymous}', lineRE = /.*line (\d+), column (\d+) in ((<anonymous function\:?\s*(\S+))|([^\(]+)\([^\)]*\))(?: in )?(.*)\s*$/i, i, j, len; for (i = 2, j = 0, len = lines.length; i < len - 2; i++) { if (lineRE.test(lines[i])) { var location = RegExp.$6 + ':' + RegExp.$1 + ':' + RegExp.$2; var fnName = RegExp.$3; fnName = fnName.replace(/<anonymous function\:?\s?(\S+)?>/g, ANON); lines[j++] = fnName + '@' + location; } } lines.splice(j, lines.length - j); return lines; }, // Opera 7.x-9.x only! opera: function(e) { var lines = e.message.split('\n'), ANON = '{anonymous}', lineRE = /Line\s+(\d+).*script\s+(http\S+)(?:.*in\s+function\s+(\S+))?/i, i, j, len; for (i = 4, j = 0, len = lines.length; i < len; i += 2) { //TODO: RegExp.exec() would probably be cleaner here if (lineRE.test(lines[i])) { lines[j++] = (RegExp.$3 ? RegExp.$3 + '()@' + RegExp.$2 + RegExp.$1 : ANON + '()@' + RegExp.$2 + ':' + RegExp.$1) + ' -- ' + lines[i + 1].replace(/^\s+/, ''); } } lines.splice(j, lines.length - j); return lines; }, // Safari, IE, and others other: function(curr) { var ANON = '{anonymous}', fnRE = /function\s*([\w\-$]+)?\s*\(/i, stack = [], j = 0, fn, args; var maxStackSize = 10; while (curr && stack.length < maxStackSize) { fn = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON; args = Array.prototype.slice.call(curr['arguments']); stack[j++] = fn + '(' + this.stringifyArguments(args) + ')'; curr = curr.caller; } return stack; }, /** * Given arguments array as a String, subsituting type names for non-string types. * * @param {Arguments} object * @return {Array} of Strings with stringified arguments */ stringifyArguments: function(args) { for (var i = 0; i < args.length; ++i) { var arg = args[i]; if (arg === undefined) { args[i] = 'undefined'; } else if (arg === null) { args[i] = 'null'; } else if (arg.constructor) { if (arg.constructor === Array) { if (arg.length < 3) { args[i] = '[' + this.stringifyArguments(arg) + ']'; } else { args[i] = '[' + this.stringifyArguments(Array.prototype.slice.call(arg, 0, 1)) + '...' + this.stringifyArguments(Array.prototype.slice.call(arg, -1)) + ']'; } } else if (arg.constructor === Object) { args[i] = '#object'; } else if (arg.constructor === Function) { args[i] = '#function'; } else if (arg.constructor === String) { args[i] = '"' + arg + '"'; } } } return args.join(','); }, sourceCache: {}, /** * @return the text from a given URL. */ ajax: function(url) { var req = this.createXMLHTTPObject(); if (!req) { return; } req.open('GET', url, false); req.setRequestHeader('User-Agent', 'XMLHTTP/1.0'); req.send(''); return req.responseText; }, /** * Try XHR methods in order and store XHR factory. * * @return <Function> XHR function or equivalent */ createXMLHTTPObject: function() { var xmlhttp, XMLHttpFactories = [ function() { return new XMLHttpRequest(); }, function() { return new ActiveXObject('Msxml2.XMLHTTP'); }, function() { return new ActiveXObject('Msxml3.XMLHTTP'); }, function() { return new ActiveXObject('Microsoft.XMLHTTP'); } ]; for (var i = 0; i < XMLHttpFactories.length; i++) { try { xmlhttp = XMLHttpFactories[i](); // Use memoization to cache the factory this.createXMLHTTPObject = XMLHttpFactories[i]; return xmlhttp; } catch (e) {} } }, /** * Given a URL, check if it is in the same domain (so we can get the source * via Ajax). * * @param url <String> source url * @return False if we need a cross-domain request */ isSameDomain: function(url) { return url.indexOf(location.hostname) !== -1; }, /** * Get source code from given URL if in the same domain. * * @param url <String> JS source URL * @return <String> Source code */ getSource: function(url) { if (!(url in this.sourceCache)) { this.sourceCache[url] = this.ajax(url).split('\n'); } return this.sourceCache[url]; }, guessFunctions: function(stack) { for (var i = 0; i < stack.length; ++i) { var reStack = /\{anonymous\}\(.*\)@(\w+:\/\/([\-\w\.]+)+(:\d+)?[^:]+):(\d+):?(\d+)?/; var frame = stack[i], m = reStack.exec(frame); if (m) { var file = m[1], lineno = m[4]; //m[7] is character position in Chrome if (file && this.isSameDomain(file) && lineno) { var functionName = this.guessFunctionName(file, lineno); stack[i] = frame.replace('{anonymous}', functionName); } } } return stack; }, guessFunctionName: function(url, lineNo) { try { return this.guessFunctionNameFromLines(lineNo, this.getSource(url)); } catch (e) { return 'getSource failed with url: ' + url + ', exception: ' + e.toString(); } }, guessFunctionNameFromLines: function(lineNo, source) { var reFunctionArgNames = /function ([^(]*)\(([^)]*)\)/; var reGuessFunction = /['"]?([0-9A-Za-z_]+)['"]?\s*[:=]\s*(function|eval|new Function)/; // Walk backwards from the first line in the function until we find the line which // matches the pattern above, which is the function definition var line = "", maxLines = 10; for (var i = 0; i < maxLines; ++i) { line = source[lineNo - i] + line; if (line !== undefined) { var m = reGuessFunction.exec(line); if (m && m[1]) { return m[1]; } else { m = reFunctionArgNames.exec(line); if (m && m[1]) { return m[1]; } } } } return '(?)'; } };
declare module "trim-left" { declare module.exports: string => string }
import counterpart from "counterpart"; import typesCheck from "./types"; /** * * * * * * MESSAGES * * * * * * */ export const Messages = { Required: (name = "") => { if (name) return counterpart.translate("validation.messages.requiredNamed", { name: name }); return counterpart.translate("validation.messages.required"); }, Type: (type = "", name = "") => { if (name) return counterpart.translate( `validation.messages.types.${type}Named`, {name: name, type: type} ); return counterpart.translate(`validation.messages.types.${type}`, { type: type }); }, Range: (min, max, name) => { if (name) return counterpart.translate(`validation.messages.rangeNamed`, { name: name, min: min, max: max }); return counterpart.translate(`validation.messages.range`, { min: min, max: max }); }, Min: (min, name) => { if (name) return counterpart.translate(`validation.messages.minNamed`, { name: name, min: min }); return counterpart.translate(`validation.messages.min`, {min: min}); }, Max: (max, name) => { if (name) return counterpart.translate(`validation.messages.maxNamed`, { name: name, max: max }); return counterpart.translate(`validation.messages.max`, {max: max}); }, Number: name => { if (name) return counterpart.translate(`validation.messages.numberNamed`, { name: name }); return counterpart.translate(`validation.messages.number`); }, Integer: name => { if (name) return counterpart.translate(`validation.messages.integerNamed`, { name: name }); return counterpart.translate(`validation.messages.integer`); }, Float: name => { if (name) return counterpart.translate(`validation.messages.floatNamed`, { name: name }); return counterpart.translate(`validation.messages.float`); }, Email: name => { if (name) return counterpart.translate(`validation.messages.emailNamed`, { name: name }); return counterpart.translate(`validation.messages.email`); }, Url: name => { if (name) return counterpart.translate(`validation.messages.urlNamed`, { name: name }); return counterpart.translate(`validation.messages.url`); }, OneOf: (name, list) => { if (name) return counterpart.translate(`validation.messages.oneOfNamed`, { name: name, list: list }); return counterpart.translate(`validation.messages.oneOf`, {list: list}); }, Balance: (balance, symbol) => { return counterpart.translate(`validation.messages.balance`, { balance: balance, symbol: symbol }); } }; /** * * * * * * RULES * * * * * * */ export const Rules = { /** * Validation to check required Field * @param {string} props - name of field to use in translation * @param {Object} props * @param props.name - name of field to use in translation * @returns {{required: boolean, message: *}} */ required: function(props = {}) { let name = ""; if (typeof props === "string") { name = props; } else { name = props && props.name; } return { required: true, message: Messages.Required(name) }; }, /** * Validation to check field to match specific type * @param {string} props - type of field * @param {Object} props * @param {string} props.type - type of field * @param {string} [props.name] - name of field to use in translation * @returns {{validator: validator, message: *}} */ type: function(props) { let type = ""; let name = ""; if (typeof props === "string") type = props; if (props && props.type) type = props.type; if (props && props.name) name = props.name; if (type === "") throw new Error( "[Validation] Rules.Type the property type is missed" ); if (!typesCheck[type]) throw new Error( `[Validation] Rules.Type the property type '${props && props.type}' is not listed in supported types` ); return { validator: (rule, value, callback) => { if (typesCheck[type](value)) return callback(); return callback(false); }, message: Messages.Type(type, name) }; }, /** * Validation to check * @param {Object} props * @param {number} props.min - min value * @param {number} props.max - max value * @param {string} [props.name] - name of field to use in translation * @returns {{validator: validator, message: *}} */ range: function(props = {}) { let max = Number(props.max); let min = Number(props.min); if (max === undefined || isNaN(max)) throw new Error( `[Validation] Rules.Range the property max '${props && props.max}' is incorrect. Should be a number` ); if (min === undefined || isNaN(min)) throw new Error( `[Validation] Rules.Range the property min '${props && props.min}' is incorrect. Should be a number` ); if (max < min) throw new Error( `[Validation] Rules.Range the property min '${props && props.min}' cannot be higher than max '${props && props.max}'` ); return { validator: (rule, value, callback) => { value = Number(value); if (isNaN(value) || value < min || value > max) return callback(false); return callback(); }, message: Messages.Range(min, max, props.name || "") }; }, /** * Validation for min value * @param {number} props - min value * @param {Object} props * @param {number} props.min * @param {string} [props.name] * @param {boolean} props.higherThan - if (true) then check will be "value > min" instead of "value >= min" * @returns {{validator: validator, message: *}} */ min: function(props) { let min; if (typeof props === "object") { min = Number(props && props.min); } else { min = Number(props); } if (min === undefined || isNaN(min)) throw new Error( `[Validation] Rules.Min the property min '${props && props.min}' is incorrect. Should be a number` ); return { validator: (rule, value, callback) => { value = Number(value); if (props && props.higherThan) { if (isNaN(value) || value <= min) return callback(false); } else { if (isNaN(value) || value < min) return callback(false); } return callback(); }, message: Messages.Min(min, props.name || "") }; }, /** * Validation for max value * @param {number} props - max value * @param {Object} props * @param {number} props.max * @param {string} [props.name] * @returns {{validator: validator, message: *}} */ max: function(props) { let max; if (typeof props === "object") { max = Number(props && props.max); } else { max = Number(props); } if (max === undefined || isNaN(max)) throw new Error( `[Validation] Rules.Min the property max '${props && props.max}' is incorrect. Should be a number` ); return { validator: (rule, value, callback) => { value = Number(value); if (isNaN(value) || value > max) return callback(false); return callback(); }, message: Messages.Max(max, props.name || "") }; }, /** * Validate field to be number * @param {string} [name] * @returns {{validator: validator, message: *}} */ number: function(name) { return { validator: (rule, value, callback) => { if (!typesCheck.number(value)) return callback(false); return callback(); }, message: Messages.Number(name || "") }; }, /** * Validate field to be integer * @param {string} [name] * @returns {{validator: validator, message: *}} */ integer: function(name) { return { validator: (rule, value, callback) => { if (!typesCheck.integer(value)) return callback(false); return callback(); }, message: Messages.Integer(name || "") }; }, /** * Validate field to be float * @param {string} [name] * @returns {{validator: validator, message: *}} */ float: function(name) { return { validator: (rule, value, callback) => { if (!typesCheck.float(value)) return callback(false); return callback(); }, message: Messages.Float(name || "") }; }, /** * Validate field to be email * @param {string} [name] * @returns {{validator: validator, message: *}} */ email: function(name) { return { validator: (rule, value, callback) => { if (!typesCheck.email(value)) return callback(false); return callback(); }, message: Messages.Email(name || "") }; }, /** * Validate field to be url * @param {string} [name] * @returns {{validator: validator, message: *}} */ url: function(name) { return { validator: (rule, value, callback) => { if (!typesCheck.url(value)) return callback(false); return callback(); }, message: Messages.Url(name || "") }; }, /** * Validate field to be oneOf * @param {Object} props * @param {Array} props.list * @param {string} [props.name] * @returns {{validator: validator, message: *}} */ oneOf: function(props = {}) { let list; if (!Array.isArray(props && props.list)) { throw new Error( `[Validation] Rules.oneOf the property list is missed or incorrect` ); } list = props.list; return { validator: (rule, value, callback) => { if (list.indexOf(value) === -1) return callback(false); return callback(); }, message: Messages.OneOf( (props && props.name) || "", list.toString().replace(/,([a-z])/g, ", $1") ) }; }, /** * Validate field to be in range from 0 to UserBalance * @param props */ balance: function(props = {}) { let validation = Rules.range({ min: 0, max: props.balance }); return { validator: validation.validator, message: Messages.Balance(props.balance, props.symbol) }; } }; /** * * * * * * VALIDATION * * * * * * */ export const Validation = { Rules: Rules };
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'stylescombo', 'km', { label: 'រចនាបថ', panelTitle: 'ទ្រង់ទ្រាយ​រចនាបថ', panelTitle1: 'រចនាបថ​ប្លក់', panelTitle2: 'រចនាបថ​ក្នុង​ជួរ', panelTitle3: 'រចនាបថ​វត្ថុ' });
/** * @license Angular v3.4.9 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common'), require('@angular/common/testing'), require('@angular/core'), require('@angular/router')) : typeof define === 'function' && define.amd ? define(['exports', '@angular/common', '@angular/common/testing', '@angular/core', '@angular/router'], factory) : (factory((global.ng = global.ng || {}, global.ng.router = global.ng.router || {}, global.ng.router.testing = global.ng.router.testing || {}),global.ng.common,global.ng.common.testing,global.ng.core,global.ng.router)); }(this, function (exports,_angular_common,_angular_common_testing,_angular_core,_angular_router) { 'use strict'; var ROUTER_PROVIDERS = _angular_router.__router_private__.ROUTER_PROVIDERS; var ROUTES = _angular_router.__router_private__.ROUTES; var flatten = _angular_router.__router_private__.flatten; /** * @whatItDoes Allows to simulate the loading of ng modules in tests. * * @howToUse * * ``` * const loader = TestBed.get(NgModuleFactoryLoader); * * @Component({template: 'lazy-loaded'}) * class LazyLoadedComponent {} * @NgModule({ * declarations: [LazyLoadedComponent], * imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])] * }) * * class LoadedModule {} * * // sets up stubbedModules * loader.stubbedModules = {lazyModule: LoadedModule}; * * router.resetConfig([ * {path: 'lazy', loadChildren: 'lazyModule'}, * ]); * * router.navigateByUrl('/lazy/loaded'); * ``` * * @stable */ var SpyNgModuleFactoryLoader = (function () { function SpyNgModuleFactoryLoader(compiler) { this.compiler = compiler; /** * @docsNotRequired */ this._stubbedModules = {}; } Object.defineProperty(SpyNgModuleFactoryLoader.prototype, "stubbedModules", { /** * @docsNotRequired */ get: function () { return this._stubbedModules; }, /** * @docsNotRequired */ set: function (modules) { var res = {}; for (var _i = 0, _a = Object.keys(modules); _i < _a.length; _i++) { var t = _a[_i]; res[t] = this.compiler.compileModuleAsync(modules[t]); } this._stubbedModules = res; }, enumerable: true, configurable: true }); SpyNgModuleFactoryLoader.prototype.load = function (path) { if (this._stubbedModules[path]) { return this._stubbedModules[path]; } else { return Promise.reject(new Error("Cannot find module " + path)); } }; SpyNgModuleFactoryLoader.decorators = [ { type: _angular_core.Injectable }, ]; /** @nocollapse */ SpyNgModuleFactoryLoader.ctorParameters = function () { return [ { type: _angular_core.Compiler, }, ]; }; return SpyNgModuleFactoryLoader; }()); /** * Router setup factory function used for testing. * * @stable */ function setupTestingRouter(urlSerializer, outletMap, location, loader, compiler, injector, routes, urlHandlingStrategy) { var router = new _angular_router.Router(null, urlSerializer, outletMap, location, injector, loader, compiler, flatten(routes)); if (urlHandlingStrategy) { router.urlHandlingStrategy = urlHandlingStrategy; } return router; } /** * @whatItDoes Sets up the router to be used for testing. * * @howToUse * * ``` * beforeEach(() => { * TestBed.configureTestModule({ * imports: [ * RouterTestingModule.withRoutes( * [{path: '', component: BlankCmp}, {path: 'simple', component: SimpleCmp}])] * ) * ] * }); * }); * ``` * * @description * * The modules sets up the router to be used for testing. * It provides spy implementations of {@link Location}, {@link LocationStrategy}, and {@link * NgModuleFactoryLoader}. * * @stable */ var RouterTestingModule = (function () { function RouterTestingModule() { } RouterTestingModule.withRoutes = function (routes) { return { ngModule: RouterTestingModule, providers: [_angular_router.provideRoutes(routes)] }; }; RouterTestingModule.decorators = [ { type: _angular_core.NgModule, args: [{ exports: [_angular_router.RouterModule], providers: [ ROUTER_PROVIDERS, { provide: _angular_common.Location, useClass: _angular_common_testing.SpyLocation }, { provide: _angular_common.LocationStrategy, useClass: _angular_common_testing.MockLocationStrategy }, { provide: _angular_core.NgModuleFactoryLoader, useClass: SpyNgModuleFactoryLoader }, { provide: _angular_router.Router, useFactory: setupTestingRouter, deps: [ _angular_router.UrlSerializer, _angular_router.RouterOutletMap, _angular_common.Location, _angular_core.NgModuleFactoryLoader, _angular_core.Compiler, _angular_core.Injector, ROUTES, [_angular_router.UrlHandlingStrategy, new _angular_core.Optional()] ] }, { provide: _angular_router.PreloadingStrategy, useExisting: _angular_router.NoPreloading }, _angular_router.provideRoutes([]) ] },] }, ]; /** @nocollapse */ RouterTestingModule.ctorParameters = function () { return []; }; return RouterTestingModule; }()); exports.SpyNgModuleFactoryLoader = SpyNgModuleFactoryLoader; exports.setupTestingRouter = setupTestingRouter; exports.RouterTestingModule = RouterTestingModule; }));
var through = require('through2'); // Consts const PLUGIN_NAME = 'gulp-buffer'; function gulpBuffer() { var stream = through.obj(function(file, enc, callback) { // keep null files as-is if (file.isNull()) { this.push(file); return callback(); } // keep buffer files as-is if (file.isBuffer()) { this.push(file); return callback(); } // transform stream files into buffer if (file.isStream()) { var self = this; var c_stream = file.contents; var chunks = []; var onreadable = function() { var chunk; while (null !== (chunk = c_stream.read())) { chunks.push(chunk); } }; c_stream.on('readable', onreadable); c_stream.once('end', function() { c_stream.removeListener('readable', onreadable); file.contents = Buffer.concat(chunks); self.push(file); callback(); }); return; } }); return stream; }; module.exports = gulpBuffer;
/*───────────────────────────────────────────────────────────────────────────*\ │ Copyright (C) 2014 eBay Software Foundation │ │ │ │hh ,'""`. │ │ / _ _ \ Licensed under the Apache License, Version 2.0 (the "License"); │ │ |(@)(@)| you may not use this file except in compliance with the License. │ │ ) __ ( You may obtain a copy of the License at │ │ /,'))((`.\ │ │(( (( )) )) http://www.apache.org/licenses/LICENSE-2.0 │ │ `\ `)(' /' │ │ │ │ Unless required by applicable law or agreed to in writing, software │ │ distributed under the License is distributed on an "AS IS" BASIS, │ │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │ │ See the License for the specific language governing permissions and │ │ limitations under the License. │ \*───────────────────────────────────────────────────────────────────────────*/ "use strict"; var resolver = require('file-resolver'); var util = require('./util'); var proto = { get path() { // Unfortunately, since we don't know the actual file to resolve until // we get request context (in `render`), we can't say whether it exists or not. return true; }, render: function (options, callback) { var locals, view, engine; locals = options && options.context; view = this.resolver.resolve(this.name, util.localityFromLocals(locals)); // This is a bit of a hack to ensure we override `views` for the duration // of the rendering lifecycle. Unfortunately, `adaro` and `consolidate` // (https://github.com/visionmedia/consolidate.js/blob/407266806f3a713240db2285527de934be7a8019/lib/consolidate.js#L214) // check `options.views` but override with `options.settings.views` if available. // So, for this rendering task we need to override with the more specific root directory. options.settings = Object.create(options.settings); options.views = options.settings.views = view.root; engine = this.engines['.' + this.defaultEngine]; engine(view.file, options, callback); } }; function buildCtor(fallback) { function View(name, options) { this.name = name; this.root = options.root; this.defaultEngine = options.defaultEngine; this.engines = options.engines; this.resolver = resolver.create({ root: options.root, ext: this.defaultEngine, fallback: fallback }); } View.prototype = proto; View.prototype.constructor = View; return View; } module.exports = function () { var view; return function (req, res, next) { var config = req.app.kraken; //if the view engine is 'js and if it has not been overridden already if (config.get('express:view engine') === 'js' && !view) { view = buildCtor(config.get('i18n:fallback')); req.app.set('view', view); } next(); }; };
/** * bootstrap-table - An extended Bootstrap table with radio, checkbox, sort, pagination, and other added features. (supports twitter bootstrap v2 and v3). * * @version v1.13.0 * @homepage http://bootstrap-table.wenzhixin.net.cn * @author wenzhixin <wenzhixin2010@gmail.com> (http://wenzhixin.net.cn/) * @license MIT */ (function(a,b){if('function'==typeof define&&define.amd)define([],b);else if('undefined'!=typeof exports)b();else{b(),a.bootstrapTablePlPL={exports:{}}.exports}})(this,function(){'use strict';(function(a){a.fn.bootstrapTable.locales['pl-PL']={formatLoadingMessage:function(){return'\u0141adowanie, prosz\u0119 czeka\u0107...'},formatRecordsPerPage:function(a){return a+' rekord\xF3w na stron\u0119'},formatShowingRows:function(a,b,c){return'Wy\u015Bwietlanie rekord\xF3w od '+a+' do '+b+' z '+c},formatSearch:function(){return'Szukaj'},formatNoMatches:function(){return'Niestety, nic nie znaleziono'},formatRefresh:function(){return'Od\u015Bwie\u017C'},formatToggle:function(){return'Prze\u0142\u0105cz'},formatColumns:function(){return'Kolumny'}},a.extend(a.fn.bootstrapTable.defaults,a.fn.bootstrapTable.locales['pl-PL'])})(jQuery)});
var ios = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; var chrome = /Chrome/i.test(navigator.userAgent); var touchDevice = (function() { try { document.createEvent('TouchEvent'); return true; } catch (e) { return false; } })(); var describeSkipIf = function(bool, title, callback) { bool = typeof bool == 'function' ? bool() : bool; if (bool) { describe.skip(title, callback); } else { describe(title, callback); } }; var describeIf = function(bool, title, callback) { bool = typeof bool == 'function' ? bool() : bool; describeSkipIf(!bool, title, callback); }; var getItemArray = function(length) { return new Array(length).join().split(',') .map(function(item, index) { return 'item ' + index; }); };
/* * 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'; /** * @class * Initializes a new instance of the UsageStatistics class. * @constructor * @summary Statistics related to pool usage information. * * @member {date} startTime The start time of the time range covered by the * statistics. * * @member {date} lastUpdateTime The time at which the statistics were last * updated. All statistics are limited to the range between startTime and * lastUpdateTime. * * @member {moment.duration} dedicatedCoreTime The aggregated wall-clock time * of the dedicated compute node cores being part of the pool. * */ function UsageStatistics() { } /** * Defines the metadata of UsageStatistics * * @returns {object} metadata of UsageStatistics * */ UsageStatistics.prototype.mapper = function () { return { required: false, serializedName: 'UsageStatistics', type: { name: 'Composite', className: 'UsageStatistics', modelProperties: { startTime: { required: true, serializedName: 'startTime', type: { name: 'DateTime' } }, lastUpdateTime: { required: true, serializedName: 'lastUpdateTime', type: { name: 'DateTime' } }, dedicatedCoreTime: { required: true, serializedName: 'dedicatedCoreTime', type: { name: 'TimeSpan' } } } } }; }; module.exports = UsageStatistics;
version https://git-lfs.github.com/spec/v1 oid sha256:36bfa2037643bd1511cbb46471b2ce24b78c1a6953e67fa59bbc4ec3fefead90 size 1891
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _commaListsAnd = require('./commaListsAnd'); var _commaListsAnd2 = _interopRequireDefault(_commaListsAnd); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _commaListsAnd2.default; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb21tYUxpc3RzQW5kL2luZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7QUFFQSIsImZpbGUiOiJpbmRleC5qcyIsInNvdXJjZXNDb250ZW50IjpbIid1c2Ugc3RyaWN0J1xuXG5pbXBvcnQgY29tbWFMaXN0c0FuZCBmcm9tICcuL2NvbW1hTGlzdHNBbmQnXG5cbmV4cG9ydCBkZWZhdWx0IGNvbW1hTGlzdHNBbmRcbiJdfQ==
/** * @author zhixin wen <wenzhixin2010@gmail.com> * extensions: https://github.com/lukaskral/bootstrap-table-filter */ !function($) { 'use strict'; $.extend($.fn.bootstrapTable.defaults, { showFilter: false }); var BootstrapTable = $.fn.bootstrapTable.Constructor, _init = BootstrapTable.prototype.init, _initSearch = BootstrapTable.prototype.initSearch; BootstrapTable.prototype.init = function () { _init.apply(this, Array.prototype.slice.apply(arguments)); var that = this; this.$el.on('load-success.bs.table', function () { if (that.options.showFilter) { $(that.options.toolbar).bootstrapTableFilter({ connectTo: that.$el }); } }); }; BootstrapTable.prototype.initSearch = function () { _initSearch.apply(this, Array.prototype.slice.apply(arguments)); if (this.options.sidePagination !== 'server') { if (typeof this.searchCallback === 'function') { this.data = $.grep(this.options.data, this.searchCallback); } } }; BootstrapTable.prototype.getData = function () { return (this.searchText || this.searchCallback) ? this.data : this.options.data; }; BootstrapTable.prototype.getColumns = function () { return this.options.columns; }; BootstrapTable.prototype.registerSearchCallback = function (callback) { this.searchCallback = callback; }; BootstrapTable.prototype.updateSearch = function () { this.options.pageNumber = 1; this.initSearch(); this.updatePagination(); }; BootstrapTable.prototype.getServerUrl = function () { return (this.options.sidePagination === 'server') ? this.options.url : false; }; $.fn.bootstrapTable.methods.push('getColumns', 'registerSearchCallback', 'updateSearch', 'getServerUrl'); }(jQuery);
import { Directive, ElementRef, EventEmitter, Input, Output } from '@angular/core'; import { isPresent, isTrueProperty } from '../../util/util'; /** * \@name Option * \@description * `ion-option` is a child component of `ion-select`. Similar to the native option element, `ion-option` can take a value and a selected property. * * \@demo /docs/demos/src/select/ */ export class Option { /** * @param {?} _elementRef */ constructor(_elementRef) { this._elementRef = _elementRef; this._selected = false; this._disabled = false; /** * \@output {any} Event to evaluate when option is selected. */ this.ionSelect = new EventEmitter(); } /** * \@input {boolean} If true, the element is selected. * @return {?} */ get selected() { return this._selected; } /** * @param {?} val * @return {?} */ set selected(val) { this._selected = isTrueProperty(val); } /** * \@input {any} The value of the option. * @return {?} */ get value() { if (isPresent(this._value)) { return this._value; } return this.text; } /** * @param {?} val * @return {?} */ set value(val) { this._value = val; } /** * \@input {boolean} If true, the user cannot interact with this element. * @return {?} */ get disabled() { return this._disabled; } /** * @param {?} val * @return {?} */ set disabled(val) { this._disabled = isTrueProperty(val); } /** * @hidden * @return {?} */ get text() { return this._elementRef.nativeElement.textContent; } } Option.decorators = [ { type: Directive, args: [{ selector: 'ion-option' },] }, ]; /** * @nocollapse */ Option.ctorParameters = () => [ { type: ElementRef, }, ]; Option.propDecorators = { 'ionSelect': [{ type: Output },], 'selected': [{ type: Input },], 'value': [{ type: Input },], 'disabled': [{ type: Input },], }; function Option_tsickle_Closure_declarations() { /** @type {?} */ Option.decorators; /** * @nocollapse * @type {?} */ Option.ctorParameters; /** @type {?} */ Option.propDecorators; /** @type {?} */ Option.prototype._selected; /** @type {?} */ Option.prototype._disabled; /** @type {?} */ Option.prototype._value; /** * \@output {any} Event to evaluate when option is selected. * @type {?} */ Option.prototype.ionSelect; /** @type {?} */ Option.prototype._elementRef; } //# sourceMappingURL=option.js.map
// // Copyright (c) 2016 Cisco Systems // Licensed under the MIT License // /* * a Cisco Spark webhook that leverages node-sparkbot function: webhook.onCommand(). * note : this example requires that you've set a SPARK_TOKEN env variable */ var SparkBot = require("node-sparkbot"); // Starts your Webhook with default configuration where the SPARK API access token is read from the SPARK_TOKEN env variable var bot = new SparkBot(); bot.onCommand("help", function(command) { // // ADD YOUR CUSTOM CODE HERE // console.log("new command: " + command.keyword + ", from: " + command.message.personEmail + ", with args: " + JSON.stringify(command.args)); });
'use strict'; const path = require('path'); const fs = require('fs'); const noop = () => {}; before('initialization', function () { // Load and override configuration before starting the server let config; try { require.resolve('../config/config'); } catch (err) { if (err.code !== 'MODULE_NOT_FOUND') throw err; // Should never happen console.log("config.js doesn't exist - creating one with default settings..."); fs.writeFileSync(path.resolve(__dirname, '../config/config.js'), fs.readFileSync(path.resolve(__dirname, '../config/config-example.js')) ); } finally { config = require('../config/config'); } // Actually crash if we crash config.crashguard = false; // Don't allow config to be overridden while test is running config.watchconfig = false; // Don't try to write to file system config.nofswriting = true; // Don't create a REPL require('../repl').start = noop; // Start the server. require('../app'); Rooms.RoomBattle.prototype.send = noop; Rooms.RoomBattle.prototype.receive = noop; for (let process of Rooms.SimulatorProcess.processes) { // Don't crash -we don't care of battle child processes. process.process.on('error', noop); } LoginServer.disabled = true; });
import React, { Component, PropTypes } from "react"; import { getStyles } from "../utils/base"; import Radium from "radium"; @Radium export default class Quote extends Component { render() { return ( <span className={this.props.className} style={[this.context.styles.components.quote, getStyles.call(this), this.props.style]}> {this.props.children} </span> ); } } Quote.propTypes = { children: PropTypes.node, style: PropTypes.object, className: PropTypes.string }; Quote.contextTypes = { styles: PropTypes.object };
module.exports = require('./dist/');
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- var A = new Int8Array(100); var str = "123.12"; function FAIL(x, y) { WScript.Echo("FAILED\n"); WScript.Echo("Expected "+y+", got "+x+"\n"); throw "FAILED"; } function foo() { var y = 0; for (var i = 0; i < 100; i+=4) { A[i] = i; A[i+1] = i + 0x7a; A[i+2] = i+0.34; A[i+3] = str; } for (var i = 0; i < 100; i++) { y += A[i]; A[i] = 0; } return y; } var expected = 3837; var r; for (var i = 0; i < 1000; i++) { r = foo(); if (r !== expected) FAIL(r, expected); } WScript.Echo("Passed\n");
var nightwatch = require('../index.js'); module.exports = { init : function(callback) { return nightwatch.client({ seleniumPort : 10195, silent : true, output : false, globals : { myGlobal : 'test' } }).start().once('error', function() { if (callback) { callback(); } process.exit(); }) } }
/** * Bind the file upload when editing content, so it works and stuff * * @param {string} key */ function bindFileUpload(key) { // Since jQuery File Upload's 'paramName' option seems to be ignored, // it requires the name of the upload input to be "images[]". Which clashes // with the non-fancy fallback, so we hackishly set it here. :-/ $('#fileupload-' + key) .fileupload({ dataType: 'json', dropZone: $('#dropzone-' + key), pasteZone: null, done: function (e, data) { $.each(data.result, function (index, file) { var filename, message; if (file.error === undefined) { filename = decodeURI(file.url).replace('files/', ''); $('#field-' + key).val(filename); $('#thumbnail-' + key).html('<img src="' + Bolt.conf('paths.root') + 'thumbs/200x150c/' + encodeURI(filename) + '" width="200" height="150">'); window.setTimeout(function () { $('#progress-' + key).fadeOut('slow'); }, 1500); // Add the uploaded file to our stack. Bolt.stack.addToStack(filename); } else { message = "Oops! There was an error uploading the file. Make sure the file is not " + "corrupt, and that the 'files/'-folder is writable." + "\n\n(error was: " + file.error + ")"; alert(message); window.setTimeout(function () { $('#progress-' + key).fadeOut('slow'); }, 50); } $('#progress-' + key + ' div.bar').css('width', "100%"); $('#progress-' + key).removeClass('progress-striped active'); }); }, add: bindFileUpload.checkFileSize }) .bind('fileuploadprogress', function (e, data) { var progress = Math.round(100 * data.loaded / data.total); $('#progress-' + key).show().addClass('progress-striped active'); $('#progress-' + key + ' div.progress-bar').css('width', progress + "%"); }); } bindFileUpload.checkFileSize = function checkFileSize (event, data) { // The jQuery upload doesn't expose an API to cover an entire upload set. So we keep "bad" files // in the data.originalFiles, which is the same between multiple files in one upload set. var badFiles = []; if (typeof data.originalFiles.bad === 'undefined') { data.originalFiles.bad = []; } _.each(data.files, function (file, index) { if ((file.size || 0) > Bolt.conf('uploadConfig.maxSize') && Bolt.conf('uploadConfig.maxSize') > 0) { badFiles.push(file.name); data.originalFiles.bad.push(file.name); } }); if (data.originalFiles.bad.length > 0) { var filename1 = data.files[data.files.length - 1].name; var filename2 = data.originalFiles[data.originalFiles.length - 1].name; if (filename1 === filename2) { // We're at the end of this upload cycle var message = 'One or more of the files that you selected was larger than the max size of ' + Bolt.conf('uploadConfig.maxSizeNice') + ":\n\n" + data.originalFiles.bad.join("\n"); alert(message); } } if (badFiles.length === 0) { data.submit(); } };
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const OpenBrowserPlugin = require('open-browser-webpack-plugin'); module.exports = { // 这里应用程序开始执行 // webpack 开始打包 // 本例中 entry 为多入口 entry: { // App 入口 main: "./app/index", }, // webpack 如何输出结果的相关选项 output: { // 所有输出文件的目标路径 // 必须是绝对路径(使用 Node.js 的 path 模块) path: path.resolve(__dirname, "dist"), // 「入口分块(entry chunk)」的文件名模板(出口分块?) filename: "bundle.min.js", // filename: "[name].js", // 用于多个入口点(entry point)(出口点?) // filename: "[chunkhash].js", // 用于长效缓存 // filename: "[name].[chunkhash:8].js", // 用于长效缓存 }, // 关于模块配置 module: { // 模块规则(配置 loader、解析器等选项) rules: [ { // 语义解释器,将 js/jsx 文件中的 es2015/react 语法自动转为浏览器可识别的 Javascript 语法 test: /\.jsx?$/, include: path.resolve(__dirname, "app"), exclude: /node_modules/, loader: "babel-loader", // loader 的可选项 options: { presets: ["es2015", "react", "stage-0"], }, }, ] }, // 解析模块请求的选项 // (不适用于对 loader 解析) resolve: { // 使用的扩展名 extensions: [".js", ".jsx", ".json", ".css"], }, // 附加插件列表 plugins: [ // 定义环境变量 new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), // 压缩 js 插件 new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), // 用于简化 HTML 文件(index.html)的创建,提供访问 bundle 的服务。 new HtmlWebpackPlugin({ title: "frontend-tutorial", template: "./public/index.html" }), // 自动打开浏览器 new OpenBrowserPlugin({ url: "http://localhost:9000" }), ], devServer: { contentBase: [path.join(__dirname, "app")], compress: true, port: 9000, // 启动端口号 inline: true, } };
version https://git-lfs.github.com/spec/v1 oid sha256:a2f4d816a8f0394b3c29ab86771ad1f3194f169d06b343e67dc7ab8810ee95b5 size 1161
import Ember from 'ember'; import BoundsPathLayer from 'ember-leaflet/layers/bounds-path'; import { module, test } from 'qunit'; var geometry, locations; var n = [-15.780148, -47.92917], w = [-15.782102, -47.936869], s = [-15.786108, -47.931933], e = [-15.783423, -47.924638]; module('BoundsPathLayer with location property', { beforeEach: function() { locations = Ember.A([ Ember.Object.create({lastSeenAt: n}), Ember.Object.create({lastSeenAt: w}), Ember.Object.create({lastSeenAt: s}), Ember.Object.create({lastSeenAt: null}), Ember.Object.create({lastSeenAt: e}) ]); geometry = BoundsPathLayer.create({ content: locations, locationProperty: 'lastSeenAt' }); } }); test('bounds initializes ok', function(assert) { var bounds = geometry.get('bounds'); assert.ok(bounds, 'bounds should be initialized'); assert.equal(bounds.getSouth(), s[0]); assert.equal(bounds.getNorth(), n[0]); assert.equal(bounds.getWest(), w[1]); assert.equal(bounds.getEast(), e[1]); }); test('add an object updates bounds', function(assert) { var e2 = [-15.782515, -47.914295]; // further east locations.pushObject(Ember.Object.create({lastSeenAt: e2})); assert.equal(geometry.get('bounds').getEast(), e2[1]); }); test('remove an object updates bounds', function(assert) { Ember.run(function() { locations.replace(3, 2); }); // now northernmost (first) point is most eastward assert.equal(geometry.get('bounds').getEast(), n[1]); }); test('update a location updates bound', function(assert) { locations[1].set('lastSeenAt', e); // Now bounds don't extend as far west assert.equal(geometry.get('bounds').getWest(), s[1]); }); test('clear locations empties bounds', function(assert) { Ember.run(function() { locations.clear(); }); assert.equal(geometry.get('bounds'), null); }); test('nullify locations empties bounds', function(assert) { Ember.run(function() { geometry.set('locations', null); }); assert.equal(geometry.get('bounds'), null); });
define("dojox/mobile/Slider", [ "dojo/_base/array", "dojo/_base/connect", "dojo/_base/declare", "dojo/_base/lang", "dojo/_base/window", "dojo/sniff", "dojo/dom-class", "dojo/dom-construct", "dojo/dom-geometry", "dojo/dom-style", "dojo/keys", "dojo/touch", "dijit/_WidgetBase", "dijit/form/_FormValueMixin" ], function(array, connect, declare, lang, win, has, domClass, domConstruct, domGeometry, domStyle, keys, touch, WidgetBase, FormValueMixin){ return declare("dojox.mobile.Slider", [WidgetBase, FormValueMixin], { // summary: // A non-templated Slider widget similar to the HTML5 INPUT type=range. // value: [const] Number // The current slider value. value: 0, // min: [const] Number // The first value the slider can be set to. min: 0, // max: [const] Number // The last value the slider can be set to. max: 100, // step: [const] Number // The delta from 1 value to another. // This causes the slider handle to snap/jump to the closest possible value. // A value of 0 means continuous (as much as allowed by pixel resolution). step: 1, // baseClass: String // The name of the CSS class of this widget. baseClass: "mblSlider", // flip: [const] Boolean // Specifies if the slider should change its default: ascending <--> descending. flip: false, // orientation: [const] String // The slider direction. // // - "H": horizontal // - "V": vertical // - "auto": use width/height comparison at instantiation time (default is "H" if width/height are 0) orientation: "auto", // halo: Number // Size of the boundary that extends beyond the edges of the slider // to make it easier to touch. halo: "8pt", buildRendering: function(){ if(!this.templateString){ // true if this widget is not templated this.focusNode = this.domNode = domConstruct.create("div", {}); this.valueNode = domConstruct.create("input", (this.srcNodeRef && this.srcNodeRef.name) ? { type: "hidden", name: this.srcNodeRef.name } : { type: "hidden" }, this.domNode, "last"); var relativeParent = domConstruct.create("div", { style: { position:"relative", height:"100%", width:"100%" } }, this.domNode, "last"); this.progressBar = domConstruct.create("div", { style:{ position:"absolute" }, "class":"mblSliderProgressBar" }, relativeParent, "last"); this.touchBox = domConstruct.create("div", { style:{ position:"absolute" }, "class":"mblSliderTouchBox" }, relativeParent, "last"); this.handle = domConstruct.create("div", { style:{ position:"absolute" }, "class":"mblSliderHandle" }, relativeParent, "last"); } this.inherited(arguments); // prevent browser scrolling on IE10 (evt.preventDefault() is not enough) if(typeof this.domNode.style.msTouchAction != "undefined"){ this.domNode.style.msTouchAction = "none"; } }, _setValueAttr: function(/*Number*/ value, /*Boolean?*/ priorityChange){ // summary: // Hook such that set('value', value) works. // tags: // private value = Math.max(Math.min(value, this.max), this.min); var fromPercent = (this.value - this.min) * 100 / (this.max - this.min); this.valueNode.value = value; this.inherited(arguments); if(!this._started){ return; } // don't move images until all the properties are set this.focusNode.setAttribute("aria-valuenow", value); var toPercent = (value - this.min) * 100 / (this.max - this.min); // now perform visual slide var horizontal = this.orientation != "V"; if(priorityChange === true){ domClass.add(this.handle, "mblSliderTransition"); domClass.add(this.progressBar, "mblSliderTransition"); }else{ domClass.remove(this.handle, "mblSliderTransition"); domClass.remove(this.progressBar, "mblSliderTransition"); } domStyle.set(this.handle, this._attrs.handleLeft, (this._reversed ? (100-toPercent) : toPercent) + "%"); domStyle.set(this.progressBar, this._attrs.width, toPercent + "%"); }, postCreate: function(){ this.inherited(arguments); function beginDrag(e){ function getEventData(e){ point = isMouse ? e[this._attrs.pageX] : (e.touches ? e.touches[0][this._attrs.pageX] : e[this._attrs.clientX]); pixelValue = point - startPixel; pixelValue = Math.min(Math.max(pixelValue, 0), maxPixels); var discreteValues = this.step ? ((this.max - this.min) / this.step) : maxPixels; if(discreteValues <= 1 || discreteValues == Infinity ){ discreteValues = maxPixels; } var wholeIncrements = Math.round(pixelValue * discreteValues / maxPixels); value = (this.max - this.min) * wholeIncrements / discreteValues; value = this._reversed ? (this.max - value) : (this.min + value); } function continueDrag(e){ e.preventDefault(); lang.hitch(this, getEventData)(e); this.set('value', value, false); } function endDrag(e){ e.preventDefault(); array.forEach(actionHandles, lang.hitch(this, "disconnect")); actionHandles = []; this.set('value', this.value, true); } e.preventDefault(); var isMouse = e.type == "mousedown"; var box = domGeometry.position(node, false); // can't use true since the added docScroll and the returned x are body-zoom incompatibile var bodyZoom = (has("ie") || has("trident") > 6) ? 1 : (domStyle.get(win.body(), "zoom") || 1); if(isNaN(bodyZoom)){ bodyZoom = 1; } var nodeZoom = (has("ie") || has("trident") > 6) ? 1 : (domStyle.get(node, "zoom") || 1); if(isNaN(nodeZoom)){ nodeZoom = 1; } var startPixel = box[this._attrs.x] * nodeZoom * bodyZoom + domGeometry.docScroll()[this._attrs.x]; var maxPixels = box[this._attrs.w] * nodeZoom * bodyZoom; lang.hitch(this, getEventData)(e); if(e.target == this.touchBox){ this.set('value', value, true); } array.forEach(actionHandles, connect.disconnect); var root = win.doc.documentElement; var actionHandles = [ this.connect(root, touch.move, continueDrag), this.connect(root, touch.release, endDrag) ]; } function keyPress(/*Event*/ e){ if(this.disabled || this.readOnly || e.altKey || e.ctrlKey || e.metaKey){ return; } var step = this.step, multiplier = 1, newValue; switch(e.keyCode){ case keys.HOME: newValue = this.min; break; case keys.END: newValue = this.max; break; case keys.RIGHT_ARROW: multiplier = -1; case keys.LEFT_ARROW: newValue = this.value + multiplier * ((flip && horizontal) ? step : -step); break; case keys.DOWN_ARROW: multiplier = -1; case keys.UP_ARROW: newValue = this.value + multiplier * ((!flip || horizontal) ? step : -step); break; default: return; } e.preventDefault(); this._setValueAttr(newValue, false); } function keyUp(/*Event*/ e){ if(this.disabled || this.readOnly || e.altKey || e.ctrlKey || e.metaKey){ return; } this._setValueAttr(this.value, true); } var point, pixelValue, value, node = this.domNode; if(this.orientation == "auto"){ this.orientation = node.offsetHeight <= node.offsetWidth ? "H" : "V"; } // add V or H suffix to baseClass for styling purposes domClass.add(this.domNode, array.map(this.baseClass.split(" "), lang.hitch(this, function(c){ return c+this.orientation; }))); var horizontal = this.orientation != "V", ltr = horizontal ? this.isLeftToRight() : false, flip = !!this.flip; // _reversed is complicated since you can have flipped right-to-left and vertical is upside down by default this._reversed = !((horizontal && ((ltr && !flip) || (!ltr && flip))) || (!horizontal && flip)); this._attrs = horizontal ? { x:'x', w:'w', l:'l', r:'r', pageX:'pageX', clientX:'clientX', handleLeft:"left", left:this._reversed ? "right" : "left", width:"width" } : { x:'y', w:'h', l:'t', r:'b', pageX:'pageY', clientX:'clientY', handleLeft:"top", left:this._reversed ? "bottom" : "top", width:"height" }; this.progressBar.style[this._attrs.left] = "0px"; this.connect(this.touchBox, touch.press, beginDrag); this.connect(this.handle, touch.press, beginDrag); this.connect(this.domNode, "onkeypress", keyPress); // for desktop a11y this.connect(this.domNode, "onkeyup", keyUp); // fire onChange on desktop this.startup(); this.set('value', this.value); } }); });
'use strict'; module.exports = /*@ngInject*/ function fooService(/* inject dependencies here, i.e. : $rootScope */) { return { // Do something awesome }; };
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.0.2 */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.autocomplete */ /* * @see js folder for autocomplete implementation */ angular.module('material.components.autocomplete', [ 'material.core', 'material.components.icon', 'material.components.virtualRepeat' ]); angular .module('material.components.autocomplete') .controller('MdAutocompleteCtrl', MdAutocompleteCtrl); var ITEM_HEIGHT = 41, MAX_HEIGHT = 5.5 * ITEM_HEIGHT, MENU_PADDING = 8, INPUT_PADDING = 2; // Padding provided by `md-input-container` function MdAutocompleteCtrl ($scope, $element, $mdUtil, $mdConstant, $mdTheming, $window, $animate, $rootElement, $attrs, $q) { //-- private variables var ctrl = this, itemParts = $scope.itemsExpr.split(/ in /i), itemExpr = itemParts[ 1 ], elements = null, cache = {}, noBlur = false, selectedItemWatchers = [], hasFocus = false, lastCount = 0; //-- public variables with handlers defineProperty('hidden', handleHiddenChange, true); //-- public variables ctrl.scope = $scope; ctrl.parent = $scope.$parent; ctrl.itemName = itemParts[ 0 ]; ctrl.matches = []; ctrl.loading = false; ctrl.hidden = true; ctrl.index = null; ctrl.messages = []; ctrl.id = $mdUtil.nextUid(); ctrl.isDisabled = null; ctrl.isRequired = null; ctrl.hasNotFound = false; //-- public methods ctrl.keydown = keydown; ctrl.blur = blur; ctrl.focus = focus; ctrl.clear = clearValue; ctrl.select = select; ctrl.listEnter = onListEnter; ctrl.listLeave = onListLeave; ctrl.mouseUp = onMouseup; ctrl.getCurrentDisplayValue = getCurrentDisplayValue; ctrl.registerSelectedItemWatcher = registerSelectedItemWatcher; ctrl.unregisterSelectedItemWatcher = unregisterSelectedItemWatcher; ctrl.notFoundVisible = notFoundVisible; ctrl.loadingIsVisible = loadingIsVisible; return init(); //-- initialization methods /** * Initialize the controller, setup watchers, gather elements */ function init () { $mdUtil.initOptionalProperties($scope, $attrs, { searchText: null, selectedItem: null }); $mdTheming($element); configureWatchers(); $mdUtil.nextTick(function () { gatherElements(); moveDropdown(); focusElement(); $element.on('focus', focusElement); }); } /** * Calculates the dropdown's position and applies the new styles to the menu element * @returns {*} */ function positionDropdown () { if (!elements) return $mdUtil.nextTick(positionDropdown, false, $scope); var hrect = elements.wrap.getBoundingClientRect(), vrect = elements.snap.getBoundingClientRect(), root = elements.root.getBoundingClientRect(), top = vrect.bottom - root.top, bot = root.bottom - vrect.top, left = hrect.left - root.left, width = hrect.width, offset = getVerticalOffset(), styles; // Adjust the width to account for the padding provided by `md-input-container` if ($attrs.mdFloatingLabel) { left += INPUT_PADDING; width -= INPUT_PADDING * 2; } styles = { left: left + 'px', minWidth: width + 'px', maxWidth: Math.max(hrect.right - root.left, root.right - hrect.left) - MENU_PADDING + 'px' }; if (top > bot && root.height - hrect.bottom - MENU_PADDING < MAX_HEIGHT) { styles.top = 'auto'; styles.bottom = bot + 'px'; styles.maxHeight = Math.min(MAX_HEIGHT, hrect.top - root.top - MENU_PADDING) + 'px'; } else { styles.top = (top - offset) + 'px'; styles.bottom = 'auto'; styles.maxHeight = Math.min(MAX_HEIGHT, root.bottom + $mdUtil.scrollTop() - hrect.bottom - MENU_PADDING) + 'px'; } elements.$.scrollContainer.css(styles); $mdUtil.nextTick(correctHorizontalAlignment, false); /** * Calculates the vertical offset for floating label examples to account for ngMessages * @returns {number} */ function getVerticalOffset () { var offset = 0; var inputContainer = $element.find('md-input-container'); if (inputContainer.length) { var input = inputContainer.find('input'); offset = inputContainer.prop('offsetHeight'); offset -= input.prop('offsetTop'); offset -= input.prop('offsetHeight'); // add in the height left up top for the floating label text offset += inputContainer.prop('offsetTop'); } return offset; } /** * Makes sure that the menu doesn't go off of the screen on either side. */ function correctHorizontalAlignment () { var dropdown = elements.scrollContainer.getBoundingClientRect(), styles = {}; if (dropdown.right > root.right - MENU_PADDING) { styles.left = (hrect.right - dropdown.width) + 'px'; } elements.$.scrollContainer.css(styles); } } /** * Moves the dropdown menu to the body tag in order to avoid z-index and overflow issues. */ function moveDropdown () { if (!elements.$.root.length) return; $mdTheming(elements.$.scrollContainer); elements.$.scrollContainer.detach(); elements.$.root.append(elements.$.scrollContainer); if ($animate.pin) $animate.pin(elements.$.scrollContainer, $rootElement); } /** * Sends focus to the input element. */ function focusElement () { if ($scope.autofocus) elements.input.focus(); } /** * Sets up any watchers used by autocomplete */ function configureWatchers () { var wait = parseInt($scope.delay, 10) || 0; $attrs.$observe('disabled', function (value) { ctrl.isDisabled = !!value; }); $attrs.$observe('required', function (value) { ctrl.isRequired = !!value; }); $scope.$watch('searchText', wait ? $mdUtil.debounce(handleSearchText, wait) : handleSearchText); $scope.$watch('selectedItem', selectedItemChange); angular.element($window).on('resize', positionDropdown); $scope.$on('$destroy', cleanup); } /** * Removes any events or leftover elements created by this controller */ function cleanup () { angular.element($window).off('resize', positionDropdown); if ( elements ){ var items = 'ul scroller scrollContainer input'.split(' '); angular.forEach(items, function(key){ elements.$[key].remove(); }); } } /** * Gathers all of the elements needed for this controller */ function gatherElements () { elements = { main: $element[0], scrollContainer: $element[0].getElementsByClassName('md-virtual-repeat-container')[0], scroller: $element[0].getElementsByClassName('md-virtual-repeat-scroller')[0], ul: $element.find('ul')[0], input: $element.find('input')[0], wrap: $element.find('md-autocomplete-wrap')[0], root: document.body }; elements.li = elements.ul.getElementsByTagName('li'); elements.snap = getSnapTarget(); elements.$ = getAngularElements(elements); } /** * Finds the element that the menu will base its position on * @returns {*} */ function getSnapTarget () { for (var element = $element; element.length; element = element.parent()) { if (angular.isDefined(element.attr('md-autocomplete-snap'))) return element[ 0 ]; } return elements.wrap; } /** * Gathers angular-wrapped versions of each element * @param elements * @returns {{}} */ function getAngularElements (elements) { var obj = {}; for (var key in elements) { if (elements.hasOwnProperty(key)) obj[ key ] = angular.element(elements[ key ]); } return obj; } //-- event/change handlers /** * Handles changes to the `hidden` property. * @param hidden * @param oldHidden */ function handleHiddenChange (hidden, oldHidden) { if (!hidden && oldHidden) { positionDropdown(); if (elements) { $mdUtil.nextTick(function () { $mdUtil.disableScrollAround(elements.ul); }, false, $scope); } } else if (hidden && !oldHidden) { $mdUtil.nextTick(function () { $mdUtil.enableScrolling(); }, false, $scope); } } /** * When the user mouses over the dropdown menu, ignore blur events. */ function onListEnter () { noBlur = true; } /** * When the user's mouse leaves the menu, blur events may hide the menu again. */ function onListLeave () { if (!hasFocus) elements.input.focus(); noBlur = false; ctrl.hidden = shouldHide(); } /** * When the mouse button is released, send focus back to the input field. */ function onMouseup () { elements.input.focus(); } /** * Handles changes to the selected item. * @param selectedItem * @param previousSelectedItem */ function selectedItemChange (selectedItem, previousSelectedItem) { if (selectedItem) { getDisplayValue(selectedItem).then(function (val) { $scope.searchText = val; handleSelectedItemChange(selectedItem, previousSelectedItem); }); } if (selectedItem !== previousSelectedItem) announceItemChange(); } /** * Use the user-defined expression to announce changes each time a new item is selected */ function announceItemChange () { angular.isFunction($scope.itemChange) && $scope.itemChange(getItemAsNameVal($scope.selectedItem)); } /** * Use the user-defined expression to announce changes each time the search text is changed */ function announceTextChange () { angular.isFunction($scope.textChange) && $scope.textChange(); } /** * Calls any external watchers listening for the selected item. Used in conjunction with * `registerSelectedItemWatcher`. * @param selectedItem * @param previousSelectedItem */ function handleSelectedItemChange (selectedItem, previousSelectedItem) { selectedItemWatchers.forEach(function (watcher) { watcher(selectedItem, previousSelectedItem); }); } /** * Register a function to be called when the selected item changes. * @param cb */ function registerSelectedItemWatcher (cb) { if (selectedItemWatchers.indexOf(cb) == -1) { selectedItemWatchers.push(cb); } } /** * Unregister a function previously registered for selected item changes. * @param cb */ function unregisterSelectedItemWatcher (cb) { var i = selectedItemWatchers.indexOf(cb); if (i != -1) { selectedItemWatchers.splice(i, 1); } } /** * Handles changes to the searchText property. * @param searchText * @param previousSearchText */ function handleSearchText (searchText, previousSearchText) { ctrl.index = getDefaultIndex(); // do nothing on init if (searchText === previousSearchText) return; getDisplayValue($scope.selectedItem).then(function (val) { // clear selected item if search text no longer matches it if (searchText !== val) { $scope.selectedItem = null; // trigger change event if available if (searchText !== previousSearchText) announceTextChange(); // cancel results if search text is not long enough if (!isMinLengthMet()) { ctrl.matches = []; setLoading(false); updateMessages(); } else { handleQuery(); } } }); } /** * Handles input blur event, determines if the dropdown should hide. */ function blur () { hasFocus = false; if (!noBlur) { ctrl.hidden = shouldHide(); } } /** * Force blur on input element * @param forceBlur */ function doBlur(forceBlur) { if (forceBlur) { noBlur = false; hasFocus = false; } elements.input.blur(); } /** * Handles input focus event, determines if the dropdown should show. */ function focus () { hasFocus = true; //-- if searchText is null, let's force it to be a string if (!angular.isString($scope.searchText)) $scope.searchText = ''; ctrl.hidden = shouldHide(); if (!ctrl.hidden) handleQuery(); } /** * Handles keyboard input. * @param event */ function keydown (event) { switch (event.keyCode) { case $mdConstant.KEY_CODE.DOWN_ARROW: if (ctrl.loading) return; event.stopPropagation(); event.preventDefault(); ctrl.index = Math.min(ctrl.index + 1, ctrl.matches.length - 1); updateScroll(); updateMessages(); break; case $mdConstant.KEY_CODE.UP_ARROW: if (ctrl.loading) return; event.stopPropagation(); event.preventDefault(); ctrl.index = ctrl.index < 0 ? ctrl.matches.length - 1 : Math.max(0, ctrl.index - 1); updateScroll(); updateMessages(); break; case $mdConstant.KEY_CODE.TAB: // If we hit tab, assume that we've left the list so it will close onListLeave(); if (ctrl.hidden || ctrl.loading || ctrl.index < 0 || ctrl.matches.length < 1) return; select(ctrl.index); break; case $mdConstant.KEY_CODE.ENTER: if (ctrl.hidden || ctrl.loading || ctrl.index < 0 || ctrl.matches.length < 1) return; if (hasSelection()) return; event.stopPropagation(); event.preventDefault(); select(ctrl.index); break; case $mdConstant.KEY_CODE.ESCAPE: event.stopPropagation(); event.preventDefault(); clearValue(); // Force the component to blur if they hit escape doBlur(true); break; default: } } //-- getters /** * Returns the minimum length needed to display the dropdown. * @returns {*} */ function getMinLength () { return angular.isNumber($scope.minLength) ? $scope.minLength : 1; } /** * Returns the display value for an item. * @param item * @returns {*} */ function getDisplayValue (item) { return $q.when(getItemText(item) || item); /** * Getter function to invoke user-defined expression (in the directive) * to convert your object to a single string. */ function getItemText (item) { return (item && $scope.itemText) ? $scope.itemText(getItemAsNameVal(item)) : null; } } /** * Returns the locals object for compiling item templates. * @param item * @returns {{}} */ function getItemAsNameVal (item) { if (!item) return undefined; var locals = {}; if (ctrl.itemName) locals[ ctrl.itemName ] = item; return locals; } /** * Returns the default index based on whether or not autoselect is enabled. * @returns {number} */ function getDefaultIndex () { return $scope.autoselect ? 0 : -1; } /** * Sets the loading parameter and updates the hidden state. * @param value {boolean} Whether or not the component is currently loading. */ function setLoading(value) { if (ctrl.loading != value) { ctrl.loading = value; } // Always refresh the hidden variable as something else might have changed ctrl.hidden = shouldHide(); } /** * Determines if the menu should be hidden. * @returns {boolean} */ function shouldHide () { if (ctrl.loading && !hasMatches()) return true; // Hide while loading initial matches else if (hasSelection()) return true; // Hide if there is already a selection else if (!hasFocus) return true; // Hide if the input does not have focus else return !shouldShow(); // Defer to standard show logic } /** * Determines if the menu should be shown. * @returns {boolean} */ function shouldShow() { return (isMinLengthMet() && hasMatches()) || notFoundVisible(); } /** * Returns true if the search text has matches. * @returns {boolean} */ function hasMatches() { return ctrl.matches.length ? true : false; } /** * Returns true if the autocomplete has a valid selection. * @returns {boolean} */ function hasSelection() { return ctrl.scope.selectedItem ? true : false; } /** * Returns true if the loading indicator is, or should be, visible. * @returns {boolean} */ function loadingIsVisible() { return ctrl.loading && !hasSelection(); } /** * Returns the display value of the current item. * @returns {*} */ function getCurrentDisplayValue () { return getDisplayValue(ctrl.matches[ ctrl.index ]); } /** * Determines if the minimum length is met by the search text. * @returns {*} */ function isMinLengthMet () { return ($scope.searchText || '').length >= getMinLength(); } //-- actions /** * Defines a public property with a handler and a default value. * @param key * @param handler * @param value */ function defineProperty (key, handler, value) { Object.defineProperty(ctrl, key, { get: function () { return value; }, set: function (newValue) { var oldValue = value; value = newValue; handler(newValue, oldValue); } }); } /** * Selects the item at the given index. * @param index */ function select (index) { //-- force form to update state for validation $mdUtil.nextTick(function () { getDisplayValue(ctrl.matches[ index ]).then(function (val) { var ngModel = elements.$.input.controller('ngModel'); ngModel.$setViewValue(val); ngModel.$render(); }).finally(function () { $scope.selectedItem = ctrl.matches[ index ]; setLoading(false); }); }, false); } /** * Clears the searchText value and selected item. */ function clearValue () { // Set the loading to true so we don't see flashes of content setLoading(true); // Reset our variables ctrl.index = 0; ctrl.matches = []; $scope.searchText = ''; // Tell the select to fire and select nothing select(-1); // Per http://www.w3schools.com/jsref/event_oninput.asp var eventObj = document.createEvent('CustomEvent'); eventObj.initCustomEvent('input', true, true, { value: $scope.searchText }); elements.input.dispatchEvent(eventObj); elements.input.focus(); } /** * Fetches the results for the provided search text. * @param searchText */ function fetchResults (searchText) { var items = $scope.$parent.$eval(itemExpr), term = searchText.toLowerCase(); if (angular.isArray(items)) { handleResults(items); } else if (items) { setLoading(true); $mdUtil.nextTick(function () { if (items.success) items.success(handleResults); if (items.then) items.then(handleResults); if (items.finally) items.finally(function () { setLoading(false); }); },true, $scope); } function handleResults (matches) { cache[ term ] = matches; if ((searchText || '') !== ($scope.searchText || '')) return; //-- just cache the results if old request ctrl.matches = matches; ctrl.hidden = shouldHide(); if ($scope.selectOnMatch) selectItemOnMatch(); updateMessages(); positionDropdown(); } } /** * Updates the ARIA messages */ function updateMessages () { getCurrentDisplayValue().then(function (msg) { ctrl.messages = [ getCountMessage(), msg ]; }); } /** * Returns the ARIA message for how many results match the current query. * @returns {*} */ function getCountMessage () { if (lastCount === ctrl.matches.length) return ''; lastCount = ctrl.matches.length; switch (ctrl.matches.length) { case 0: return 'There are no matches available.'; case 1: return 'There is 1 match available.'; default: return 'There are ' + ctrl.matches.length + ' matches available.'; } } /** * Makes sure that the focused element is within view. */ function updateScroll () { if (!elements.li[0]) return; var height = elements.li[0].offsetHeight, top = height * ctrl.index, bot = top + height, hgt = elements.scroller.clientHeight, scrollTop = elements.scroller.scrollTop; if (top < scrollTop) { scrollTo(top); } else if (bot > scrollTop + hgt) { scrollTo(bot - hgt); } } function scrollTo (offset) { elements.$.scrollContainer.controller('mdVirtualRepeatContainer').scrollTo(offset); } function notFoundVisible () { var textLength = (ctrl.scope.searchText || '').length; return ctrl.hasNotFound && !hasMatches() && !ctrl.loading && textLength >= getMinLength() && hasFocus && !hasSelection(); } /** * Starts the query to gather the results for the current searchText. Attempts to return cached * results first, then forwards the process to `fetchResults` if necessary. */ function handleQuery () { var searchText = $scope.searchText || '', term = searchText.toLowerCase(); //-- if results are cached, pull in cached results if (!$scope.noCache && cache[ term ]) { ctrl.matches = cache[ term ]; updateMessages(); } else { fetchResults(searchText); } ctrl.hidden = shouldHide(); } /** * If there is only one matching item and the search text matches its display value exactly, * automatically select that item. Note: This function is only called if the user uses the * `md-select-on-match` flag. */ function selectItemOnMatch () { var searchText = $scope.searchText, matches = ctrl.matches, item = matches[ 0 ]; if (matches.length === 1) getDisplayValue(item).then(function (displayValue) { if (searchText == displayValue) select(0); }); } } MdAutocompleteCtrl.$inject = ["$scope", "$element", "$mdUtil", "$mdConstant", "$mdTheming", "$window", "$animate", "$rootElement", "$attrs", "$q"]; angular .module('material.components.autocomplete') .directive('mdAutocomplete', MdAutocomplete); /** * @ngdoc directive * @name mdAutocomplete * @module material.components.autocomplete * * @description * `<md-autocomplete>` is a special input component with a drop-down of all possible matches to a * custom query. This component allows you to provide real-time suggestions as the user types * in the input area. * * To start, you will need to specify the required parameters and provide a template for your * results. The content inside `md-autocomplete` will be treated as a template. * * In more complex cases, you may want to include other content such as a message to display when * no matches were found. You can do this by wrapping your template in `md-item-template` and * adding a tag for `md-not-found`. An example of this is shown below. * * ### Validation * * You can use `ng-messages` to include validation the same way that you would normally validate; * however, if you want to replicate a standard input with a floating label, you will have to * do the following: * * - Make sure that your template is wrapped in `md-item-template` * - Add your `ng-messages` code inside of `md-autocomplete` * - Add your validation properties to `md-autocomplete` (ie. `required`) * - Add a `name` to `md-autocomplete` (to be used on the generated `input`) * * There is an example below of how this should look. * * * @param {expression} md-items An expression in the format of `item in items` to iterate over * matches for your search. * @param {expression=} md-selected-item-change An expression to be run each time a new item is * selected * @param {expression=} md-search-text-change An expression to be run each time the search text * updates * @param {expression=} md-search-text A model to bind the search query text to * @param {object=} md-selected-item A model to bind the selected item to * @param {expression=} md-item-text An expression that will convert your object to a single string. * @param {string=} placeholder Placeholder text that will be forwarded to the input. * @param {boolean=} md-no-cache Disables the internal caching that happens in autocomplete * @param {boolean=} ng-disabled Determines whether or not to disable the input field * @param {number=} md-min-length Specifies the minimum length of text before autocomplete will * make suggestions * @param {number=} md-delay Specifies the amount of time (in milliseconds) to wait before looking * for results * @param {boolean=} md-autofocus If true, will immediately focus the input element * @param {boolean=} md-autoselect If true, the first item will be selected by default * @param {string=} md-menu-class This will be applied to the dropdown menu for styling * @param {string=} md-floating-label This will add a floating label to autocomplete and wrap it in * `md-input-container` * @param {string=} md-input-name The name attribute given to the input element to be used with * FormController * @param {string=} md-input-id An ID to be added to the input element * @param {number=} md-input-minlength The minimum length for the input's value for validation * @param {number=} md-input-maxlength The maximum length for the input's value for validation * @param {boolean=} md-select-on-match When set, autocomplete will automatically select exact * the item if the search text is an exact match * * @usage * ### Basic Example * <hljs lang="html"> * <md-autocomplete * md-selected-item="selectedItem" * md-search-text="searchText" * md-items="item in getMatches(searchText)" * md-item-text="item.display"> * <span md-highlight-text="searchText">{{item.display}}</span> * </md-autocomplete> * </hljs> * * ### Example with "not found" message * <hljs lang="html"> * <md-autocomplete * md-selected-item="selectedItem" * md-search-text="searchText" * md-items="item in getMatches(searchText)" * md-item-text="item.display"> * <md-item-template> * <span md-highlight-text="searchText">{{item.display}}</span> * </md-item-template> * <md-not-found> * No matches found. * </md-not-found> * </md-autocomplete> * </hljs> * * In this example, our code utilizes `md-item-template` and `md-not-found` to specify the * different parts that make up our component. * * ### Example with validation * <hljs lang="html"> * <form name="autocompleteForm"> * <md-autocomplete * required * md-input-name="autocomplete" * md-selected-item="selectedItem" * md-search-text="searchText" * md-items="item in getMatches(searchText)" * md-item-text="item.display"> * <md-item-template> * <span md-highlight-text="searchText">{{item.display}}</span> * </md-item-template> * <div ng-messages="autocompleteForm.autocomplete.$error"> * <div ng-message="required">This field is required</div> * </div> * </md-autocomplete> * </form> * </hljs> * * In this example, our code utilizes `md-item-template` and `md-not-found` to specify the * different parts that make up our component. */ function MdAutocomplete () { var hasNotFoundTemplate = false; return { controller: 'MdAutocompleteCtrl', controllerAs: '$mdAutocompleteCtrl', scope: { inputName: '@mdInputName', inputMinlength: '@mdInputMinlength', inputMaxlength: '@mdInputMaxlength', searchText: '=?mdSearchText', selectedItem: '=?mdSelectedItem', itemsExpr: '@mdItems', itemText: '&mdItemText', placeholder: '@placeholder', noCache: '=?mdNoCache', selectOnMatch: '=?mdSelectOnMatch', itemChange: '&?mdSelectedItemChange', textChange: '&?mdSearchTextChange', minLength: '=?mdMinLength', delay: '=?mdDelay', autofocus: '=?mdAutofocus', floatingLabel: '@?mdFloatingLabel', autoselect: '=?mdAutoselect', menuClass: '@?mdMenuClass', inputId: '@?mdInputId' }, link: function(scope, element, attrs, controller) { controller.hasNotFound = hasNotFoundTemplate; }, template: function (element, attr) { var noItemsTemplate = getNoItemsTemplate(), itemTemplate = getItemTemplate(), leftover = element.html(), tabindex = attr.tabindex; // Set our variable for the link function above which runs later hasNotFoundTemplate = noItemsTemplate ? true : false; if (!attr.hasOwnProperty('tabindex')) element.attr('tabindex', '-1'); return '\ <md-autocomplete-wrap\ layout="row"\ ng-class="{ \'md-whiteframe-z1\': !floatingLabel, \'md-menu-showing\': !$mdAutocompleteCtrl.hidden }"\ role="listbox">\ ' + getInputElement() + '\ <md-progress-linear\ class="' + (attr.mdFloatingLabel ? 'md-inline' : '') + '"\ ng-if="$mdAutocompleteCtrl.loadingIsVisible()"\ md-mode="indeterminate"></md-progress-linear>\ <md-virtual-repeat-container\ md-auto-shrink\ md-auto-shrink-min="1"\ ng-mouseenter="$mdAutocompleteCtrl.listEnter()"\ ng-mouseleave="$mdAutocompleteCtrl.listLeave()"\ ng-mouseup="$mdAutocompleteCtrl.mouseUp()"\ ng-hide="$mdAutocompleteCtrl.hidden"\ class="md-autocomplete-suggestions-container md-whiteframe-z1"\ ng-class="{ \'md-not-found\': $mdAutocompleteCtrl.notFoundVisible() }"\ role="presentation">\ <ul class="md-autocomplete-suggestions"\ ng-class="::menuClass"\ id="ul-{{$mdAutocompleteCtrl.id}}">\ <li md-virtual-repeat="item in $mdAutocompleteCtrl.matches"\ ng-class="{ selected: $index === $mdAutocompleteCtrl.index }"\ ng-click="$mdAutocompleteCtrl.select($index)"\ md-extra-name="$mdAutocompleteCtrl.itemName">\ ' + itemTemplate + '\ </li>' + noItemsTemplate + '\ </ul>\ </md-virtual-repeat-container>\ </md-autocomplete-wrap>\ <aria-status\ class="md-visually-hidden"\ role="status"\ aria-live="assertive">\ <p ng-repeat="message in $mdAutocompleteCtrl.messages track by $index" ng-if="message">{{message}}</p>\ </aria-status>'; function getItemTemplate() { var templateTag = element.find('md-item-template').detach(), html = templateTag.length ? templateTag.html() : element.html(); if (!templateTag.length) element.empty(); return '<md-autocomplete-parent-scope md-autocomplete-replace>' + html + '</md-autocomplete-parent-scope>'; } function getNoItemsTemplate() { var templateTag = element.find('md-not-found').detach(), template = templateTag.length ? templateTag.html() : ''; return template ? '<li ng-if="$mdAutocompleteCtrl.notFoundVisible()"\ md-autocomplete-parent-scope>' + template + '</li>' : ''; } function getInputElement () { if (attr.mdFloatingLabel) { return '\ <md-input-container flex ng-if="floatingLabel">\ <label>{{floatingLabel}}</label>\ <input type="search"\ ' + (tabindex != null ? 'tabindex="' + tabindex + '"' : '') + '\ id="{{ inputId || \'fl-input-\' + $mdAutocompleteCtrl.id }}"\ name="{{inputName}}"\ autocomplete="off"\ ng-required="$mdAutocompleteCtrl.isRequired"\ ng-minlength="inputMinlength"\ ng-maxlength="inputMaxlength"\ ng-disabled="$mdAutocompleteCtrl.isDisabled"\ ng-model="$mdAutocompleteCtrl.scope.searchText"\ ng-keydown="$mdAutocompleteCtrl.keydown($event)"\ ng-blur="$mdAutocompleteCtrl.blur()"\ ng-focus="$mdAutocompleteCtrl.focus()"\ aria-owns="ul-{{$mdAutocompleteCtrl.id}}"\ aria-label="{{floatingLabel}}"\ aria-autocomplete="list"\ aria-haspopup="true"\ aria-activedescendant=""\ aria-expanded="{{!$mdAutocompleteCtrl.hidden}}"/>\ <div md-autocomplete-parent-scope md-autocomplete-replace>' + leftover + '</div>\ </md-input-container>'; } else { return '\ <input flex type="search"\ ' + (tabindex != null ? 'tabindex="' + tabindex + '"' : '') + '\ id="{{ inputId || \'input-\' + $mdAutocompleteCtrl.id }}"\ name="{{inputName}}"\ ng-if="!floatingLabel"\ autocomplete="off"\ ng-required="$mdAutocompleteCtrl.isRequired"\ ng-disabled="$mdAutocompleteCtrl.isDisabled"\ ng-model="$mdAutocompleteCtrl.scope.searchText"\ ng-keydown="$mdAutocompleteCtrl.keydown($event)"\ ng-blur="$mdAutocompleteCtrl.blur()"\ ng-focus="$mdAutocompleteCtrl.focus()"\ placeholder="{{placeholder}}"\ aria-owns="ul-{{$mdAutocompleteCtrl.id}}"\ aria-label="{{placeholder}}"\ aria-autocomplete="list"\ aria-haspopup="true"\ aria-activedescendant=""\ aria-expanded="{{!$mdAutocompleteCtrl.hidden}}"/>\ <button\ type="button"\ tabindex="-1"\ ng-if="$mdAutocompleteCtrl.scope.searchText && !$mdAutocompleteCtrl.isDisabled"\ ng-click="$mdAutocompleteCtrl.clear()">\ <md-icon md-svg-icon="md-close"></md-icon>\ <span class="md-visually-hidden">Clear</span>\ </button>\ '; } } } }; } angular .module('material.components.autocomplete') .directive('mdAutocompleteParentScope', MdAutocompleteItemScopeDirective); function MdAutocompleteItemScopeDirective($compile, $mdUtil) { return { restrict: 'AE', compile: compile, terminal: true, transclude: 'element' }; function compile(tElement, tAttr, transclude) { return function postLink(scope, element, attr) { var ctrl = scope.$mdAutocompleteCtrl; var newScope = ctrl.parent.$new(); var itemName = ctrl.itemName; // Watch for changes to our scope's variables and copy them to the new scope watchVariable('$index', '$index'); watchVariable('item', itemName); // Ensure that $digest calls on our scope trigger $digest on newScope. connectScopes(); // Link the element against newScope. transclude(newScope, function(clone) { element.after(clone); }); /** * Creates a watcher for variables that are copied from the parent scope * @param variable * @param alias */ function watchVariable(variable, alias) { newScope[alias] = scope[variable]; scope.$watch(variable, function(value) { $mdUtil.nextTick(function() { newScope[alias] = value; }); }); } /** * Creates watchers on scope and newScope that ensure that for any * $digest of scope, newScope is also $digested. */ function connectScopes() { var scopeDigesting = false; var newScopeDigesting = false; scope.$watch(function() { if (newScopeDigesting || scopeDigesting) { return; } scopeDigesting = true; scope.$$postDigest(function() { if (!newScopeDigesting) { newScope.$digest(); } scopeDigesting = newScopeDigesting = false; }); }); newScope.$watch(function() { newScopeDigesting = true; }); } }; } } MdAutocompleteItemScopeDirective.$inject = ["$compile", "$mdUtil"]; angular .module('material.components.autocomplete') .controller('MdHighlightCtrl', MdHighlightCtrl); function MdHighlightCtrl ($scope, $element, $attrs) { this.init = init; function init (termExpr, unsafeTextExpr) { var text = null, regex = null, flags = $attrs.mdHighlightFlags || '', watcher = $scope.$watch(function($scope) { return { term: termExpr($scope), unsafeText: unsafeTextExpr($scope) }; }, function (state, prevState) { if (text === null || state.unsafeText !== prevState.unsafeText) { text = angular.element('<div>').text(state.unsafeText).html() } if (regex === null || state.term !== prevState.term) { regex = getRegExp(state.term, flags); } $element.html(text.replace(regex, '<span class="highlight">$&</span>')); }, true); $element.on('$destroy', watcher); } function sanitize (term) { return term && term.replace(/[\\\^\$\*\+\?\.\(\)\|\{}\[\]]/g, '\\$&'); } function getRegExp (text, flags) { var str = ''; if (flags.indexOf('^') >= 1) str += '^'; str += text; if (flags.indexOf('$') >= 1) str += '$'; return new RegExp(sanitize(str), flags.replace(/[\$\^]/g, '')); } } MdHighlightCtrl.$inject = ["$scope", "$element", "$attrs"]; angular .module('material.components.autocomplete') .directive('mdHighlightText', MdHighlight); /** * @ngdoc directive * @name mdHighlightText * @module material.components.autocomplete * * @description * The `md-highlight-text` directive allows you to specify text that should be highlighted within * an element. Highlighted text will be wrapped in `<span class="highlight"></span>` which can * be styled through CSS. Please note that child elements may not be used with this directive. * * @param {string} md-highlight-text A model to be searched for * @param {string=} md-highlight-flags A list of flags (loosely based on JavaScript RexExp flags). * #### **Supported flags**: * - `g`: Find all matches within the provided text * - `i`: Ignore case when searching for matches * - `$`: Only match if the text ends with the search term * - `^`: Only match if the text begins with the search term * * @usage * <hljs lang="html"> * <input placeholder="Enter a search term..." ng-model="searchTerm" type="text" /> * <ul> * <li ng-repeat="result in results" md-highlight-text="searchTerm"> * {{result.text}} * </li> * </ul> * </hljs> */ function MdHighlight ($interpolate, $parse) { return { terminal: true, controller: 'MdHighlightCtrl', compile: function mdHighlightCompile(tElement, tAttr) { var termExpr = $parse(tAttr.mdHighlightText); var unsafeTextExpr = $interpolate(tElement.html()); return function mdHighlightLink(scope, element, attr, ctrl) { ctrl.init(termExpr, unsafeTextExpr); }; } }; } MdHighlight.$inject = ["$interpolate", "$parse"]; })(window, window.angular);
'use strict'; var fs = require('fs'); var assert = require('assert'); var lex = require('../'); var checkLexerFunctions = require('./check-lexer-functions'); checkLexerFunctions(); var dir = __dirname + '/cases/'; fs.readdirSync(dir).forEach(function (testCase) { if (/\.pug$/.test(testCase)) { console.dir(testCase); var expected = fs.readFileSync(dir + testCase.replace(/\.pug$/, '.expected.json'), 'utf8') .split(/\n/).map(JSON.parse); var result = lex(fs.readFileSync(dir + testCase, 'utf8'), dir + testCase); fs.writeFileSync(dir + testCase.replace(/\.pug$/, '.actual.json'), result.map(JSON.stringify).join('\n')); assert.deepEqual(expected, result); } }); var edir = __dirname + '/errors/'; fs.readdirSync(edir).forEach(function (testCase) { if (/\.pug$/.test(testCase)) { console.dir(testCase); var expected = JSON.parse(fs.readFileSync(edir + testCase.replace(/\.pug$/, '.json'), 'utf8')); var actual; try { lex(fs.readFileSync(edir + testCase, 'utf8'), edir + testCase); throw new Error('Expected ' + testCase + ' to throw an exception.'); } catch (ex) { if (!ex || !ex.code || !ex.code.indexOf('PUG:') === 0) throw ex; actual = { msg: ex.msg, code: ex.code, line: ex.line, column: ex.column }; } assert.deepEqual(expected, actual); } });
import m from 'mithril'; import postgrest from 'mithril-postgrest'; import adminRadioAction from '../../src/c/admin-radio-action'; describe('AdminRadioAction', () => { const testModel = postgrest.model('reward_details'), testStr = 'updated', errorStr = 'error!'; let error = false, item, fakeData = {}, $output; let args = { getKey: 'project_id', updateKey: 'contribution_id', selectKey: 'reward_id', radios: 'rewards', callToAction: 'Alterar Recompensa', outerLabel: 'Recompensa', getModel: testModel, updateModel: testModel, validate: () => { return undefined; } }; let errorArgs = _.extend({}, args, { validate: () => { return errorStr; } }); describe('view', () => { beforeAll(() => { item = _.first(RewardDetailsMockery()); args.selectedItem = m.prop(item); $output = mq(adminRadioAction, { data: args, item: m.prop(item) }); }); it('shoud only render the outerLabel on first render', () => { expect($output.contains(args.outerLabel)).toBeTrue(); expect($output.contains(args.callToAction)).toBeFalse(); }); describe('on action button click', () => { beforeAll(() => { $output.click('button'); }); it('should render a row of radio inputs', () => { const lastRequest = jasmine.Ajax.requests.mostRecent(); expect($output.find('input[type="radio"]').length).toEqual(JSON.parse(lastRequest.responseText).length); }); it('should render the description of the default selected radio', () => { $output.should.contain(item.description); }); it('should send an patch request on form submit', () => { $output.click('#r-0'); $output.trigger('form', 'submit'); const lastRequest = jasmine.Ajax.requests.mostRecent(); // Should make a patch request to update item expect(lastRequest.method).toEqual('PATCH'); }); describe('when new value is not valid', () => { beforeAll(() => { $output = mq(adminRadioAction, { data: errorArgs, item: m.prop(item) }); $output.click('button'); $output.click('#r-0'); }); it('should present an error message when new value is invalid', () => { $output.trigger('form', 'submit'); $output.should.contain(errorStr); }); }); }); }); });
'use strict'; Connector.playerSelector = '.miniplayer'; Connector.artistSelector = '.current-series-link'; Connector.trackSelector = '.current-episode-link'; Connector.playButtonSelector = '.play';
let express = require('express'); let app = express(); let bodyParser = require('body-parser'); let router = require('./app/routes/router'); const port = 8888; app.use(express.static('public')); app.use( bodyParser.json() ); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.use('/items', router); app.listen(port, function () { console.log(`Server is listening on ${port}`); });
var _ = require("lodash"); var path = require("path"); // ----------------------------------------------------------------------------- // Finds the has value for a given entry point in the provided webpack stats // ----------------------------------------------------------------------------- function getHashed(webpackStats, entryPoint, ext){ var found = webpackStats.assetsByChunkName[entryPoint]; if(_.isArray(found)){ // If there is an array of matching values we have to find the one with the right file extension. return _.find(found, function(hashEntry){ return path.extname(hashEntry).toLowerCase() === '.' + ext; }); } else { return found; } } // ----------------------------------------------------------------------------- // Changes webpack paths as needed. // ----------------------------------------------------------------------------- function apply(html, webpackConfig, webpackStats, entries, cssEntries, buildSuffix){ var result = html; _.each(webpackConfig.entry, function(path, entry){ if(_.has(entries, entry)){ result = result.replace(entry + buildSuffix, getHashed(webpackStats, entry, 'js')); } else if(_.has(cssEntries, entry)){ result = result.replace(entry + '.css', getHashed(webpackStats, entry, 'css')); } }); return result; } module.exports = { apply: apply, getHashed: getHashed };
import Ember from 'ember'; import RectangleLayer from 'ember-leaflet/layers/rectangle'; import { moduleForComponent, test } from 'ember-qunit'; import locationsEqual from '../../helpers/locations-equal'; import locations from '../../helpers/locations'; var content, rectangle, component; moduleForComponent('leaflet-map', 'RectangleLayer', { beforeEach: function() { content = Ember.A([locations.chicago, locations.sf, locations.nyc]); rectangle = RectangleLayer.create({ content: content }); component = this.subject(); component.set('childLayers', [rectangle]); this.render(); } }); test('rectangle is created', function(assert) { assert.ok(!!rectangle._layer); assert.equal(rectangle._layer._map, component._layer); }); test('locations match', function(assert) { var _layerBounds = rectangle._layer.getBounds(); locationsEqual(assert, _layerBounds.getSouthWest(), locations.sf); assert.equal(_layerBounds.getNorth(), locations.chicago.lat); assert.equal(_layerBounds.getEast(), locations.nyc.lng); var locationLatLngs = rectangle.get('locations'); locationsEqual(assert, locationLatLngs[0], locations.chicago); locationsEqual(assert, locationLatLngs[1], locations.sf); locationsEqual(assert, locationLatLngs[2], locations.nyc); }); test('replace content updates rectangle', function(assert) { rectangle.set('content', Ember.A([locations.paris, locations.nyc])); locationsEqual(assert, rectangle.get('locations')[0], locations.paris); locationsEqual(assert, rectangle.get('locations')[1], locations.nyc); var _layerBounds = rectangle._layer.getBounds(); locationsEqual(assert, _layerBounds.getSouthWest(), locations.nyc); locationsEqual(assert, _layerBounds.getNorthEast(), locations.paris); }); test('remove location from content updates rectangle', function(assert) { content.popObject(); locationsEqual(assert, rectangle._layer.getBounds().getNorthEast(), locations.chicago); assert.equal(rectangle.get('locations.length'), content.length); }); test('add location to content updates rectangle', function(assert) { content.pushObject(locations.paris); locationsEqual(assert, rectangle._layer.getBounds().getNorthEast(), locations.paris); assert.equal(rectangle.get('locations.length'), content.length); }); test('replace location in content updates rectangle', function(assert) { content.replace(1, 1, locations.paris); locationsEqual(assert, rectangle.get('locations')[1], locations.paris); var _layerBounds = rectangle._layer.getBounds(); locationsEqual(assert, _layerBounds.getNorthEast(), locations.paris); assert.equal(_layerBounds.getWest(), locations.chicago.lng); assert.equal(_layerBounds.getSouth(), locations.nyc.lat); }); test('nullify location in content updates rectangle', function(assert) { content.replace(1, 1, null); assert.equal(rectangle.get('locations.length'), 2); var _layerBounds = rectangle._layer.getBounds(); locationsEqual(assert, _layerBounds.getNorthWest(), locations.chicago); locationsEqual(assert, _layerBounds.getSouthEast(), locations.nyc); });
version https://git-lfs.github.com/spec/v1 oid sha256:e0df7ef4477a586c6ae794531832f50280056854e009af0ea8ccc253877bdd2c size 15357
// Generated by LiveScript 1.4.0 var LiveScript, path, fs, util, prelude, each, breakList, ref$, parseOptions, generateHelp, nameFromPath, SourceNode, version, slice$ = [].slice, toString$ = {}.toString; LiveScript = require('..'); path = require('path'); fs = require('fs'); util = require('util'); prelude = require('prelude-ls'), each = prelude.each, breakList = prelude.breakList; ref$ = require('./options'), parseOptions = ref$.parse, generateHelp = ref$.generateHelp; nameFromPath = require('./util').nameFromPath; SourceNode = require('source-map').SourceNode; version = LiveScript.VERSION; (function(it){ return module.exports = it; })(function(args, arg$){ var ref$, say, sayWithTimestamp, warn, die, p, pp, ppp, o, positional, e, validMapValues, toInsert, that, filename, jsonCallback; ref$ = arg$ != null ? arg$ : {}, say = ref$.say, sayWithTimestamp = ref$.sayWithTimestamp, warn = ref$.warn, die = ref$.die; say == null && (say = console.log); sayWithTimestamp == null && (sayWithTimestamp = util.log); warn == null && (warn = console.error); die == null && (die = function(message){ console.error(message); process.exit(1); }); p = function(){ var args; args = slice$.call(arguments); each(console.dir, args); }; pp = function(x, showHidden, depth){ say(util.inspect(x, showHidden, depth, !process.env.NODE_DISABLE_COLORS)); }; ppp = function(it){ pp(it, true, null); }; try { o = parseOptions(args); positional = o._; } catch (e$) { e = e$; die(e.message); } switch (false) { case !o.nodejs: forkNode(); break; case !o.version: say("LiveScript version " + version); break; case !o.help: say(generateHelp({ interpolate: { version: version } })); break; default: validMapValues = ['none', 'linked', 'linked-src', 'embedded', 'debug']; if (!in$(o.map, validMapValues)) { die("Option --map must be either: " + validMapValues.join(', ')); } o.run = !(o.compile || (o.compile = o.output)); if (args === process.argv) { process.execPath = process.argv[0] = process.argv[1]; toInsert = o.stdin ? positional : o.run ? positional.splice(1, 9e9) : []; (ref$ = process.argv).splice.apply(ref$, [2, 9e9].concat(slice$.call(toInsert))); } if (that = o.require) { filename = module.filename; module.filename = '.'; each(function(it){ return global[nameFromPath(it)] = require(it); })( that); module.filename = filename; } switch (false) { case !o.eval: jsonCallback = function(input){ if (o.prelude) { import$(global, prelude); } o.runContext = JSON.parse(input.toString()); compileScript('', o.eval); }; if (positional.length && (o.json || /\.json$/.test(positional[0]))) { o.json = true; fshoot('readFile', positional[0], jsonCallback); } else if (o.json) { getStdin(jsonCallback); } else { compileScript('', o.eval); } break; case !o.stdin: compileStdin(); break; case !positional.length: compileScripts(); break; case !require('tty').isatty(0): say("LiveScript " + version + " - use 'lsc --help' for more information"); repl(); break; default: compileStdin(); } } function fshoot(name, arg, callback){ fs[name](arg, function(e, result){ if (e) { die(e.stack || e); } callback(result); }); } function compileScripts(){ positional.forEach(function(it){ walk(it, path.normalize(it), true); }); function walk(source, base, top){ function work(){ fshoot('readFile', source, function(it){ compileScript(source, it + "", base); }); } fs.stat(source, function(e, stats){ if (e) { if (!top || /(?:\.ls|\/)$/.test(source)) { die("Can't find: " + source); } walk(source + ".ls", base); return; } if (stats.isDirectory()) { if (!o.run) { fshoot('readdir', source, function(it){ it.forEach(function(it){ walk(source + "/" + it, base); }); }); return; } source += '/index.ls'; } if (top || '.ls' === source.slice(-3)) { if (o.watch) { watch(source, work); } else { work(); } } }); } } function compileScript(filename, input, base){ var options, t, json, run, print, ref$, e; options = { filename: filename, outputFilename: outputFilename(filename, o.json), bare: o.bare, 'const': o['const'], map: o.map, header: o.header }; t = { input: input, options: options }; try { if (o.lex || o.tokens || o.ast) { LiveScript.emit('lex', t); t.tokens = LiveScript.tokens(t.input, { raw: o.lex }); if (o.lex || o.tokens) { printTokens(t.tokens); throw null; } LiveScript.emit('parse', t); t.ast = LiveScript.ast(t.tokens); say(o.json ? t.ast.stringify(2) : ''.trim.call(t.ast)); throw null; } json = o.json || /\.json\.ls$/.test(filename); run = o.run || o.eval; if (run) { LiveScript.emit('compile', t); print = json || o.print; t.output = LiveScript.compile(t.input, (ref$ = {}, import$(ref$, options), ref$.bare = true, ref$.run = run, ref$.print = print, ref$)); LiveScript.emit('run', t); t.result = LiveScript.run(t.output.toString(), options, { js: true, context: o.runContext }); switch (false) { case !json: say(JSON.stringify(t.result, null, 2)); break; case !o.print: say(t.result); } throw null; } LiveScript.emit('compile', t); t.output = LiveScript.compile(t.input, (ref$ = {}, import$(ref$, options), ref$.json = json, ref$.print = o.print, ref$)); LiveScript.emit('write', t); if (o.print || !filename) { say((toString$.call(t.output).slice(8, -1) === 'String' ? t.output : t.output.code).trimRight()); } else { writeJS(filename, t.output, t.input, base, json); } } catch (e$) { e = e$; if (e != null) { if (LiveScript.listeners('failure').length) { LiveScript.emit('failure', e, t); } else { if (filename) { warn("Failed at: " + filename); } if (!(e instanceof SyntaxError || /^Parse error /.test(e.message))) { e = e.stack || e; } if (o.watch) { warn(e + '\x07'); } else { die(e); } } return; } } LiveScript.emit('success', t); } function getStdin(cb){ var x$, code; x$ = process.openStdin(); code = ''; x$.on('data', function(it){ code += it; }); x$.on('end', function(){ cb(code); }); x$.on('data', function(){ var ref$; if ((ref$ = code.slice(-3)) === '\x04\r\n' || ref$ === '\x1a\r\n') { cb(code.slice(0, -3)); x$.destroy(); } }); } function compileStdin(){ getStdin(function(input){ compileScript('', input); }); } function watch(source, action){ (function repeat(ptime){ fshoot('stat', source, function(arg$){ var mtime; mtime = arg$.mtime; if (ptime ^ mtime) { action(); } setTimeout(repeat, 500, mtime); }); }.call(this, 0)); } function writeJS(source, js, input, base, json){ var filename, dir, that, jsPath; filename = outputFilename(source, json); dir = path.dirname(source); if (that = o.output) { dir = path.join(that, dir.slice(base === '.' ? 0 : base.length)); } jsPath = path.join(dir, filename); function compile(){ fs.writeFile(jsPath, js.toString() || '\n', function(e){ if (e) { return warn(e); } if (o.watch || o.debug) { sayWithTimestamp(source + " => " + jsPath); } }); } function compileWithMap(){ fs.writeFile(jsPath, js.code || '\n', function(e){ var mapPath; if (e) { return warn(e); } if (o.map === 'linked' || o.map === "debug") { mapPath = jsPath + ".map"; fs.writeFile(mapPath, js.map || '\n', function(e2){ if (e2) { return warn(e2); } if (o.map === "debug") { fs.writeFile(mapPath + ".debug", js.debug || '\n', function(e3){ if (o.watch || o.debug) { sayWithTimestamp(source + " => " + jsPath + ", " + mapPath + "[.debug]"); } }); } else { if (o.watch || o.debug) { sayWithTimestamp(source + " => " + jsPath + ", " + mapPath); } } }); } else { if (o.watch || o.debug) { sayWithTimestamp(source + " => " + jsPath); } } }); } fs.stat(dir, function(e){ if (o.map !== 'none') { if (!e) { return compileWithMap(); } } else { if (!e) { return compile(); } } require('child_process').exec("mkdir " + [!/^win/.test(process.platform) ? '-p' : void 8] + " " + dir, compile); }); } function outputFilename(filename, json){ return path.basename(filename).replace(/(?:(\.\w+)?\.\w+)?$/, function(){ return arguments[1] || (json ? '.json' : '.js'); }); } function printTokens(tokens){ var lines, i$, len$, ref$, tag, val, lno, l; lines = []; for (i$ = 0, len$ = tokens.length; i$ < len$; ++i$) { ref$ = tokens[i$], tag = ref$[0], val = ref$[1], lno = ref$[2]; ((ref$ = lines[lno]) != null ? ref$ : lines[lno] = []).push(tag.toLowerCase() === val ? tag : tag + ":" + val); } for (i$ = 0, len$ = lines.length; i$ < len$; ++i$) { l = lines[i$]; say(l ? l.join(' ').replace(/\n/g, '\\n') : ''); } } function repl(){ var code, cont, rl, reset, _ttyWrite, prompt, that, vm, replCtx, server, ref$; code = repl.infunc ? ' ' : ''; cont = 0; rl = require('readline').createInterface(process.stdin, process.stdout); reset = function(){ rl.line = code = ''; rl.prompt(); repl.inheredoc = false; }; (_ttyWrite = rl._ttyWrite, rl)._ttyWrite = function(char){ if (char === '\n' || char === '>') { cont += 1; } else { cont = 0; } return _ttyWrite.apply(this, arguments); }; prompt = 'ls'; if (that = repeatString$('b', !!o.bare) + repeatString$('c', !!o.compile)) { prompt += " -" + that; } if (LiveScript != null) { LiveScript.history = rl.history; } if (!o.compile) { module.paths = module.constructor._nodeModulePaths(module.filename = process.cwd() + '/repl'); vm = require('vm'); if (o.prelude) { import$(global, prelude); } replCtx = {}; import$(replCtx, global); replCtx.module = module; replCtx.exports = exports; replCtx.require = require; replCtx.LiveScript = LiveScript; replCtx.path = path; replCtx.fs = fs; replCtx.util = util; replCtx.say = say; replCtx.warn = warn; replCtx.die = die; replCtx.p = p; replCtx.pp = pp; replCtx.ppp = ppp; server = (ref$ = clone$(require('repl').REPLServer.prototype), ref$.context = replCtx, ref$.commands = [], ref$.useGlobal = false, ref$.useColors = process.env.NODE_DISABLE_COLORS, ref$.eval = function(code, ctx, arg$, cb){ var res, e; try { res = vm.runInNewContext(code, ctx, 'repl'); } catch (e$) { e = e$; } cb(e, res); }, ref$); rl.completer = bind$(server, 'complete'); } rl.on('SIGCONT', rl.prompt); rl.on('SIGINT', function(){ if (this.line || code) { say(''); reset(); } else { this.close(); } }); rl.on('close', function(){ say(''); return process.exit(); }); rl.on('line', function(it){ var isheredoc, ops, x, e; if (it.match(/^$/)) { repl.infunc = false; } if (it.match(/(\=|\~>|->|do|import|switch)\s*$/) || (it.match(/^!?(function|class|if|unless) /) && !it.match(/ then /))) { repl.infunc = true; } if (((0 < cont && cont < 3) || repl.infunc) && !repl.inheredoc) { code += it + '\n'; this.output.write(repeatString$('.', prompt.length) + '. '); return; } else { isheredoc = it.match(/(\'\'\'|\"\"\")/g); if (isheredoc && isheredoc.length % 2 === 1) { repl.inheredoc = !repl.inheredoc; } if (repl.inheredoc) { code += it + '\n'; rl.output.write(repeatString$('.', prompt.length) + '" '); return; } } repl.inheredoc = false; if (!(code += it)) { return reset(); } try { if (o.compile) { say(LiveScript.compile(code, { bare: o.bare })); } else { ops = { 'eval': 'eval', bare: true, saveScope: LiveScript }; if (code.match(/^\s*!?function/)) { ops = { bare: true }; } x = vm.runInNewContext(LiveScript.compile(code, ops), replCtx, 'repl'); if (x != null) { replCtx._ = x; } pp(x); if (typeof x === 'function') { say(x); } } } catch (e$) { e = e$; say(e); } reset(); }); process.on('uncaughtException', function(it){ say("\n" + ((it != null ? it.stack : void 8) || it)); }); process.on('exit', function(){ if (code && rl.output.isTTY) { rl._ttyWrite('\r'); } }); rl.setPrompt(prompt + "> "); rl.prompt(); } function forkNode(){ var ref$, args, lsArgs, ref1$, nodeArgs; ref$ = process.argv, args = slice$.call(ref$, 1); ref$ = breakList((function(it){ return it === '--nodejs' || it === '-n'; }), args), lsArgs = ref$[0], ref1$ = ref$[1], nodeArgs = slice$.call(ref1$, 1); require('child_process').spawn(process.execPath, nodeArgs.concat(lsArgs), { cwd: process.cwd(), stdio: 'inherit' }); } }); function in$(x, xs){ var i = -1, l = xs.length >>> 0; while (++i < l) if (x === xs[i]) return true; return false; } function import$(obj, src){ var own = {}.hasOwnProperty; for (var key in src) if (own.call(src, key)) obj[key] = src[key]; return obj; } function repeatString$(str, n){ for (var r = ''; n > 0; (n >>= 1) && (str += str)) if (n & 1) r += str; return r; } function clone$(it){ function fun(){} fun.prototype = it; return new fun; } function bind$(obj, key, target){ return function(){ return (target || obj)[key].apply(obj, arguments) }; }
module.exports={title:"Verdaccio",slug:"verdaccio",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Verdaccio</title><path d="'+this.path+'"/></svg>'},path:"M17.376 9.84L18.72 7.2h-4.8v.566h.864l-.192.377H12.96v.566h1.344l-.288.565H12v.566h1.728zm-4.255 8.64l3.68-7.265h-3.68l-1.064 2.103L8.959 7.2H5.28l5.712 11.28zM8.88 0h6.24A8.86 8.86 0 0124 8.88v6.24A8.86 8.86 0 0115.12 24H8.88A8.86 8.86 0 010 15.12V8.88A8.86 8.86 0 018.88 0z",source:"https://verdaccio.org/docs/en/logo",hex:"4B5E40",guidelines:void 0,license:void 0};
/*! * # Semantic UI 2.0.0 - Visit * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { "use strict"; $.visit = $.fn.visit = function(parameters) { var $allModules = $.isFunction(this) ? $(window) : $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.visit.settings, parameters) : $.extend({}, $.fn.visit.settings), error = settings.error, namespace = settings.namespace, eventNamespace = '.' + namespace, moduleNamespace = namespace + '-module', $module = $(this), $displays = $(), element = this, instance = $module.data(moduleNamespace), module ; module = { initialize: function() { if(settings.count) { module.store(settings.key.count, settings.count); } else if(settings.id) { module.add.id(settings.id); } else if(settings.increment && methodInvoked !== 'increment') { module.increment(); } module.add.display($module); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of visit module', module); instance = module; $module .data(moduleNamespace, module) ; }, destroy: function() { module.verbose('Destroying instance'); $module .removeData(moduleNamespace) ; }, increment: function(id) { var currentValue = module.get.count(), newValue = +(currentValue) + 1 ; if(id) { module.add.id(id); } else { if(newValue > settings.limit && !settings.surpass) { newValue = settings.limit; } module.debug('Incrementing visits', newValue); module.store(settings.key.count, newValue); } }, decrement: function(id) { var currentValue = module.get.count(), newValue = +(currentValue) - 1 ; if(id) { module.remove.id(id); } else { module.debug('Removing visit'); module.store(settings.key.count, newValue); } }, get: { count: function() { return +(module.retrieve(settings.key.count)) || 0; }, idCount: function(ids) { ids = ids || module.get.ids(); return ids.length; }, ids: function(delimitedIDs) { var idArray = [] ; delimitedIDs = delimitedIDs || module.retrieve(settings.key.ids); if(typeof delimitedIDs === 'string') { idArray = delimitedIDs.split(settings.delimiter); } module.verbose('Found visited ID list', idArray); return idArray; }, storageOptions: function(data) { var options = {} ; if(settings.expires) { options.expires = settings.expires; } if(settings.domain) { options.domain = settings.domain; } if(settings.path) { options.path = settings.path; } return options; } }, has: { visited: function(id, ids) { var visited = false ; ids = ids || module.get.ids(); if(id !== undefined && ids) { $.each(ids, function(index, value){ if(value == id) { visited = true; } }); } return visited; } }, set: { count: function(value) { module.store(settings.key.count, value); }, ids: function(value) { module.store(settings.key.ids, value); } }, reset: function() { module.store(settings.key.count, 0); module.store(settings.key.ids, null); }, add: { id: function(id) { var currentIDs = module.retrieve(settings.key.ids), newIDs = (currentIDs === undefined || currentIDs === '') ? id : currentIDs + settings.delimiter + id ; if( module.has.visited(id) ) { module.debug('Unique content already visited, not adding visit', id, currentIDs); } else if(id === undefined) { module.debug('ID is not defined'); } else { module.debug('Adding visit to unique content', id); module.store(settings.key.ids, newIDs); } module.set.count( module.get.idCount() ); }, display: function(selector) { var $element = $(selector) ; if($element.length > 0 && !$.isWindow($element[0])) { module.debug('Updating visit count for element', $element); $displays = ($displays.length > 0) ? $displays.add($element) : $element ; } } }, remove: { id: function(id) { var currentIDs = module.get.ids(), newIDs = [] ; if(id !== undefined && currentIDs !== undefined) { module.debug('Removing visit to unique content', id, currentIDs); $.each(currentIDs, function(index, value){ if(value !== id) { newIDs.push(value); } }); newIDs = newIDs.join(settings.delimiter); module.store(settings.key.ids, newIDs ); } module.set.count( module.get.idCount() ); } }, check: { limit: function(value) { value = value || module.get.count(); if(settings.limit) { if(value >= settings.limit) { module.debug('Pages viewed exceeded limit, firing callback', value, settings.limit); settings.onLimit.call(element, value); } module.debug('Limit not reached', value, settings.limit); settings.onChange.call(element, value); } module.update.display(value); } }, update: { display: function(value) { value = value || module.get.count(); if($displays.length > 0) { module.debug('Updating displayed view count', $displays); $displays.html(value); } } }, store: function(key, value) { var options = module.get.storageOptions(value) ; if(settings.storageMethod == 'localstorage' && window.localStorage !== undefined) { window.localStorage.setItem(key, value); module.debug('Value stored using local storage', key, value); } else if($.cookie !== undefined) { $.cookie(key, value, options); module.debug('Value stored using cookie', key, value, options); } else { module.error(error.noCookieStorage); return; } if(key == settings.key.count) { module.check.limit(value); } }, retrieve: function(key, value) { var storedValue ; if(settings.storageMethod == 'localstorage' && window.localStorage !== undefined) { storedValue = window.localStorage.getItem(key); } // get by cookie else if($.cookie !== undefined) { storedValue = $.cookie(key); } else { module.error(error.noCookieStorage); } if(storedValue == 'undefined' || storedValue == 'null' || storedValue === undefined || storedValue === null) { storedValue = undefined; } return storedValue; }, setting: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { settings[name] = value; } else { return settings[name]; } }, internal: function(name, value) { module.debug('Changing internal', name, value); if(value !== undefined) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else { module[name] = value; } } else { return module[name]; } }, debug: function() { if(settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.visit.settings = { name : 'Visit', debug : false, verbose : false, performance : true, namespace : 'visit', increment : false, surpass : false, count : false, limit : false, delimiter : '&', storageMethod : 'localstorage', key : { count : 'visit-count', ids : 'visit-ids' }, expires : 30, domain : false, path : '/', onLimit : function() {}, onChange : function() {}, error : { method : 'The method you called is not defined', missingPersist : 'Using the persist setting requires the inclusion of PersistJS', noCookieStorage : 'The default storage cookie requires $.cookie to be included.' } }; })( jQuery, window , document );
var searchData= [ ['window',['Window',['../class_window.html',1,'']]] ];
'use strict'; const co = require('co'); const RSVP = require('rsvp'); const ember = require('../helpers/ember'); const fs = require('fs-extra'); const path = require('path'); let remove = RSVP.denodeify(fs.remove); let root = process.cwd(); let tmproot = path.join(root, 'tmp'); const Blueprint = require('../../lib/models/blueprint'); const BlueprintNpmTask = require('ember-cli-internal-test-helpers/lib/helpers/disable-npm-on-blueprint'); const mkTmpDirIn = require('../../lib/utilities/mk-tmp-dir-in'); const chai = require('../chai'); let expect = chai.expect; let file = chai.file; describe('Acceptance: ember generate in-addon-dummy', function() { this.timeout(20000); before(function() { BlueprintNpmTask.disableNPM(Blueprint); }); after(function() { BlueprintNpmTask.restoreNPM(Blueprint); }); beforeEach(co.wrap(function *() { let tmpdir = yield mkTmpDirIn(tmproot); process.chdir(tmpdir); })); afterEach(function() { process.chdir(root); return remove(tmproot); }); function initAddon() { return ember([ 'addon', 'my-addon', '--skip-npm', '--skip-bower', ]).then(addJSHint); } function addJSHint() { let pkg = fs.readJsonSync('package.json'); pkg.devDependencies['ember-cli-jshint'] = '*'; fs.writeJsonSync('package.json', pkg); } function generateInAddon(args) { let generateArgs = ['generate'].concat(args); return initAddon().then(function() { return ember(generateArgs); }); } it('dummy component x-foo', co.wrap(function *() { yield generateInAddon(['component', 'x-foo', '--dummy']); expect(file('tests/dummy/app/components/x-foo.js')) .to.contain("import Ember from 'ember';") .to.contain("export default Ember.Component.extend({") .to.contain("});"); expect(file('tests/dummy/app/templates/components/x-foo.hbs')) .to.contain("{{yield}}"); expect(file('app/components/x-foo.js')).to.not.exist; expect(file('tests/unit/components/x-foo-test.js')).to.not.exist; })); it('dummy blueprint foo', co.wrap(function *() { yield generateInAddon(['blueprint', 'foo', '--dummy']); expect(file('blueprints/foo/index.js')) .to.contain("module.exports = {\n" + " description: ''\n" + "\n" + " // locals(options) {\n" + " // // Return custom template variables here.\n" + " // return {\n" + " // foo: options.entity.options.foo\n" + " // };\n" + " // }\n" + "\n" + " // afterInstall(options) {\n" + " // // Perform extra work here.\n" + " // }\n" + "};"); })); it('dummy blueprint foo/bar', co.wrap(function *() { yield generateInAddon(['blueprint', 'foo/bar', '--dummy']); expect(file('blueprints/foo/bar/index.js')) .to.contain("module.exports = {\n" + " description: ''\n" + "\n" + " // locals(options) {\n" + " // // Return custom template variables here.\n" + " // return {\n" + " // foo: options.entity.options.foo\n" + " // };\n" + " // }\n" + "\n" + " // afterInstall(options) {\n" + " // // Perform extra work here.\n" + " // }\n" + "};"); })); it('dummy http-mock foo', co.wrap(function *() { yield generateInAddon(['http-mock', 'foo', '--dummy']); expect(file('server/index.js')) .to.contain("mocks.forEach(route => route(app));"); expect(file('server/mocks/foo.js')) .to.contain("module.exports = function(app) {\n" + " const express = require('express');\n" + " let fooRouter = express.Router();\n" + "\n" + " fooRouter.get('/', function(req, res) {\n" + " res.send({\n" + " 'foo': []\n" + " });\n" + " });\n" + "\n" + " fooRouter.post('/', function(req, res) {\n" + " res.status(201).end();\n" + " });\n" + "\n" + " fooRouter.get('/:id', function(req, res) {\n" + " res.send({\n" + " 'foo': {\n" + " id: req.params.id\n" + " }\n" + " });\n" + " });\n" + "\n" + " fooRouter.put('/:id', function(req, res) {\n" + " res.send({\n" + " 'foo': {\n" + " id: req.params.id\n" + " }\n" + " });\n" + " });\n" + "\n" + " fooRouter.delete('/:id', function(req, res) {\n" + " res.status(204).end();\n" + " });\n" + "\n" + " // The POST and PUT call will not contain a request body\n" + " // because the body-parser is not included by default.\n" + " // To use req.body, run:\n" + "\n" + " // npm install --save-dev body-parser\n" + "\n" + " // After installing, you need to `use` the body-parser for\n" + " // this mock uncommenting the following line:\n" + " //\n" + " //app.use('/api/foo', require('body-parser').json());\n" + " app.use('/api/foo', fooRouter);\n" + "};\n"); expect(file('server/.jshintrc')) .to.contain('{\n "node": true\n}'); })); it('dummy http-mock foo-bar', co.wrap(function *() { yield generateInAddon(['http-mock', 'foo-bar', '--dummy']); expect(file('server/index.js')) .to.contain("mocks.forEach(route => route(app));"); expect(file('server/mocks/foo-bar.js')) .to.contain("module.exports = function(app) {\n" + " const express = require('express');\n" + " let fooBarRouter = express.Router();\n" + "\n" + " fooBarRouter.get('/', function(req, res) {\n" + " res.send({\n" + " 'foo-bar': []\n" + " });\n" + " });\n" + "\n" + " fooBarRouter.post('/', function(req, res) {\n" + " res.status(201).end();\n" + " });\n" + "\n" + " fooBarRouter.get('/:id', function(req, res) {\n" + " res.send({\n" + " 'foo-bar': {\n" + " id: req.params.id\n" + " }\n" + " });\n" + " });\n" + "\n" + " fooBarRouter.put('/:id', function(req, res) {\n" + " res.send({\n" + " 'foo-bar': {\n" + " id: req.params.id\n" + " }\n" + " });\n" + " });\n" + "\n" + " fooBarRouter.delete('/:id', function(req, res) {\n" + " res.status(204).end();\n" + " });\n" + "\n" + " // The POST and PUT call will not contain a request body\n" + " // because the body-parser is not included by default.\n" + " // To use req.body, run:\n" + "\n" + " // npm install --save-dev body-parser\n" + "\n" + " // After installing, you need to `use` the body-parser for\n" + " // this mock uncommenting the following line:\n" + " //\n" + " //app.use('/api/foo-bar', require('body-parser').json());\n" + " app.use('/api/foo-bar', fooBarRouter);\n" + "};\n"); expect(file('server/.jshintrc')) .to.contain('{\n "node": true\n}'); })); it('dummy http-proxy foo', co.wrap(function *() { yield generateInAddon(['http-proxy', 'foo', 'http://localhost:5000', '--dummy']); expect(file('server/index.js')) .to.contain("proxies.forEach(route => route(app));"); expect(file('server/proxies/foo.js')) .to.contain("const proxyPath = '/foo';\n" + "\n" + "module.exports = function(app) {\n" + " // For options, see:\n" + " // https://github.com/nodejitsu/node-http-proxy\n" + " let proxy = require('http-proxy').createProxyServer({});\n" + "\n" + " proxy.on('error', function(err, req) {\n" + " console.error(err, req.url);\n" + " });\n" + "\n" + " app.use(proxyPath, function(req, res, next){\n" + " // include root path in proxied request\n" + " req.url = proxyPath + '/' + req.url;\n" + " proxy.web(req, res, { target: 'http://localhost:5000' });\n" + " });\n" + "};"); expect(file('server/.jshintrc')) .to.contain('{\n "node": true\n}'); })); it('dummy server', co.wrap(function *() { yield generateInAddon(['server', '--dummy']); expect(file('server/index.js')).to.exist; })); });
(function (global, factory) { if (typeof define === "function" && define.amd) { define("loose/module-name/input", [], factory); } else if (typeof exports !== "undefined") { factory(); } else { var mod = { exports: {} }; factory(); global.looseModuleNameInput = mod.exports; } })(this, function () { "use strict"; foobar(); });
/* * jQuery Foundation Magellan 0.0.1 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; $.fn.foundationMagellan = function(options) { var defaults = { threshold: 25, activeClass: 'active' }, options = $.extend({}, defaults, options); // Indicate we have arrived at a destination $(document).on('magellan.arrival', '[data-magellan-arrival]', function(e) { var $expedition = $(this).closest('[data-magellan-expedition]'), activeClass = $expedition.attr('data-magellan-active-class') || options.activeClass; $(this) .closest('[data-magellan-expedition]') .find('[data-magellan-arrival]') .not(this) .removeClass(activeClass); $(this).addClass(activeClass); }); // Set starting point as the current destination var $expedition = $('[data-magellan-expedition]'); $expedition.find('[data-magellan-arrival]:first') .addClass($expedition.attr('data-magellan-active-class') || options.activeClass); // Update fixed position $('[data-magellan-expedition=fixed]').on('magellan.update-position', function(){ var $el = $(this); $el.data("magellan-fixed-position",""); $el.data("magellan-top-offset", ""); }); $('[data-magellan-expedition=fixed]').trigger('magellan.update-position'); $(window).on('resize.magellan', function() { $('[data-magellan-expedition=fixed]').trigger('magellan.update-position'); }); $(window).on('scroll.magellan', function() { var windowScrollTop = $(window).scrollTop(); $('[data-magellan-expedition=fixed]').each(function() { var $expedition = $(this); if ($expedition.data("magellan-top-offset") === "") { $expedition.data("magellan-top-offset", $expedition.offset().top); } var fixed_position = (windowScrollTop + options.threshold) > $expedition.data("magellan-top-offset"); if ($expedition.data("magellan-fixed-position") != fixed_position) { $expedition.data("magellan-fixed-position", fixed_position); if (fixed_position) { $expedition.css({position:"fixed", top:0}); } else { $expedition.css({position:"", top:""}); } } }); }); // Determine when a destination has been reached, ah0y! $(window).on('scroll.magellan', function(e){ var windowScrollTop = $(window).scrollTop(); $('[data-magellan-destination]').each(function(){ var $destination = $(this), destination_name = $destination.attr('data-magellan-destination'), topOffset = $destination.offset().top - windowScrollTop; if (topOffset <= options.threshold) { $('[data-magellan-arrival=' + destination_name + ']') .trigger('magellan.arrival'); } }); }); }; }(jQuery, this));
var _ = require('lodash'); var util = require('../../core/util.js'); var log = require(`${util.dirs().core}log`); var handle = require('./handle'); var mongoUtil = require('./util'); var Reader = function Reader () { _.bindAll(this); this.db = handle; this.collection = this.db.collection(mongoUtil.settings.historyCollection); this.pair = mongoUtil.settings.pair.join('_'); } // returns the furtherst point (up to `from`) in time we have valid data from Reader.prototype.mostRecentWindow = function mostRecentWindow (from, to, next) { var mFrom = from.unix(); var mTo = to.unix(); var maxAmount = mTo - mFrom + 1; // Find some documents this.collection.find({ pair: this.pair, start: { $gte: mFrom, $lte: mTo } }).sort({ start: -1 }, (err, docs) => { if (err) { return util.die('DB error at `mostRecentWindow`'); } // no candles are available if (docs.length === 0) { log.debug('no candles are available'); return next(false); } if (docs.length === maxAmount) { // full history is available! log.debug('full history is available!'); return next({ mFrom, mTo }); } // we have at least one gap, figure out where var mostRecent = _.first(docs).start; var gapIndex = _.findIndex(docs, (r, i) => r.start !== mostRecent - i * 60); // if there was no gap in the records, but // there were not enough records. if (gapIndex === -1) { var leastRecent = _.last(docs).start; return next({ from: leastRecent, to: mostRecent }); } // else return mostRecent and the // the minute before the gap return next({ from: docs[gapIndex - 1].start, to: mostRecent }); }) } Reader.prototype.get = function get (from, to, what, next) { // returns all fields in general // Find some documents this.collection.find({ pair: this.pair, start: { $gte: from, $lte: to } }).sort({ start: 1 }, (err, docs) => { if (err) { return util.die('DB error at `get`'); } return next(null, docs); }); } Reader.prototype.count = function fCount (from, to, next) { this.collection.count({ pair: this.pair, start: { $gte: from, $lte: to } }, (err, count) => { if (err) { return util.die('DB error at `count`'); } return next(null, count); }) } Reader.prototype.countTotal = function countTotal (next) { this.collection.count({ pair: this.pair }, (err, count) => { if (err) { return util.die('DB error at `countTotal`'); } return next(null, count); }) } Reader.prototype.getBoundry = function getBoundry (next) { this.collection.find({ pair: this.pair }, { start: 1 }).sort({ start: 1 }).limit(1, (err, docs) => { if (err) { return util.die('DB error at `getBoundry`'); } var start = _.first(docs).start; this.collection.find({ pair: this.pair }, { start: 1 }).sort({ start: -1 }).limit(1, (err2, docs2) => { if (err2) { return util.die('DB error at `getBoundry`'); } var end = _.first(docs2).start; return next(null, { first: start, last: end }); }); return null; }); } Reader.prototype.tableExists = function(name, next) { return next(null, true); // Return true for backtest } Reader.prototype.close = function close () { this.db = null; } module.exports = Reader;
/////////////////////////////////////////////////////////////////////////// // Copyright © 2014 - 2016 Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define([ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/_base/array', 'dojo/_base/html', 'dijit/_WidgetBase', 'dojo/topic', 'dojo/on', 'dojo/query', 'dojo/dom-construct', 'dojo/dom-geometry', 'dojo/Deferred', 'dojo/promise/all', 'dojo/when', 'require', './WidgetManager', './PanelManager', './MapManager', './utils', './OnScreenWidgetIcon', './WidgetPlaceholder', './dijit/LoadingShelter' ], function(declare, lang, array, html, _WidgetBase, topic, on, query, domConstruct, domGeometry, Deferred, all, when, require, WidgetManager, PanelManager, MapManager, utils, OnScreenWidgetIcon, WidgetPlaceholder, LoadingShelter) { /* global jimuConfig:true */ var instance = null, clazz; clazz = declare([_WidgetBase], { constructor: function(options, domId) { /*jshint unused: false*/ this.widgetManager = WidgetManager.getInstance(); this.panelManager = PanelManager.getInstance(); this.own(topic.subscribe("appConfigLoaded", lang.hitch(this, this.onAppConfigLoaded))); this.own(topic.subscribe("appConfigChanged", lang.hitch(this, this.onAppConfigChanged))); this.own(topic.subscribe("mapLoaded", lang.hitch(this, this.onMapLoaded))); this.own(topic.subscribe("mapChanged", lang.hitch(this, this.onMapChanged))); this.own(topic.subscribe("beforeMapDestory", lang.hitch(this, this.onBeforeMapDestory))); this.own(topic.subscribe("preloadModulesLoaded", lang.hitch(this, this._onPreloadModulesLoaded))); this.own(topic.subscribe("builder/actionTriggered", lang.hitch(this, this.onActionTriggered))); //If a widget want to open another widget, please publish this message with widgetId as a //parameter this.own(topic.subscribe("openWidget", lang.hitch(this, this._onOpenWidgetRequest))); this.widgetPlaceholders = []; this.preloadWidgetIcons = []; this.preloadGroupPanels = []; this.invisibleWidgetIds = []; //avoid mobileKeyboard resize if (!utils.isMobileUa()) { this.own(on(window, 'resize', lang.hitch(this, this.resize))); } this.id = domId; this.preloadModulesLoadDef = new Deferred(); }, postCreate: function(){ this.containerNode = this.domNode; }, map: null, mapId: 'map', hlDiv: null, animTime: 500, resize: function() { //resize widgets. the panel's resize is called by the panel manager. //widgets which is in panel is resized by panel array.forEach(this.widgetManager.getAllWidgets(), function(w) { if (w.inPanel === false) { w.resize(); } }, this); }, onAppConfigLoaded: function(config){ this.appConfig = lang.clone(config); this._loadMap(); this.preloadModulesLoadDef.then(lang.hitch(this, function(){ if(this.appConfig.theme){ this._loadTheme(this.appConfig.theme); } })); }, _onPreloadModulesLoaded: function(){ this.preloadModulesLoadDef.resolve(); }, onAppConfigChanged: function(appConfig, reason, changeData){ appConfig = lang.clone(appConfig); //deal with these reasons only switch(reason){ case 'themeChange': this._onThemeChange(appConfig); break; case 'styleChange': this._onStyleChange(appConfig); break; case 'layoutChange': this._onLayoutChange(appConfig); break; case 'widgetChange': this._onWidgetChange(appConfig, changeData); break; case 'groupChange': this._onGroupChange(appConfig, changeData); break; case 'widgetPoolChange': this._onWidgetPoolChange(appConfig, changeData); break; case 'resetConfig': this._onResetConfig(appConfig); break; case 'loadingPageChange': this._onLoadingPageChange(appConfig, changeData); break; } this.appConfig = appConfig; }, onMapLoaded: function(map) { this.map = map; this.panelManager.setMap(map); this.preloadModulesLoadDef.then(lang.hitch(this, function(){ this._loadPreloadWidgets(this.appConfig); })); }, onMapChanged: function(map){ this.map = map; this.panelManager.setMap(map); this._loadPreloadWidgets(this.appConfig); }, onBeforeMapDestory: function(){ //when map changed, use destroy and then create to simplify the widget development //destroy widgets before map, because the widget may use map in thire destory method this.panelManager.destroyAllPanels(); this._destroyOffPanelWidgets(); this._destroyWidgetPlaceholders(); this._destroyPreloadWidgetIcons(); }, onActionTriggered: function(info){ if(info.action === 'highLight'){ array.forEach(this.widgetPlaceholders, function(placehoder){ if(placehoder.configId === info.elementId){ this._highLight(placehoder); } }, this); array.forEach(this.preloadWidgetIcons, function(widgetIcon){ if (widgetIcon.configId === info.elementId){ this._highLight(widgetIcon); } }, this); array.forEach(this.widgetManager.getOnScreenOffPanelWidgets(), function(panelessWidget){ if (panelessWidget.configId === info.elementId){ this._highLight(panelessWidget); } }, this); array.forEach(this.preloadGroupPanels, function(panel){ if (panel.configId === info.elementId){ this._highLight(panel); } }, this); } if(info.action === 'removeHighLight'){ this._removeHighLight(); } if(info.action === 'showLoading'){ html.setStyle(jimuConfig.loadingId, 'display', 'block'); html.setStyle(jimuConfig.mainPageId, 'display', 'none'); } if(info.action === 'showApp'){ html.setStyle(jimuConfig.loadingId, 'display', 'none'); html.setStyle(jimuConfig.mainPageId, 'display', 'block'); } }, _highLight: function(dijit){ if(!dijit.domNode){ //the dijit may be destroyed return; } if (this.hlDiv){ this._removeHighLight(dijit); } var position = domGeometry.getMarginBox(dijit.domNode); var hlStyle = { position: 'absolute', left: position.l + 'px', top: position.t + 'px', width: position.w + 'px', height: position.h + 'px' }; this.hlDiv = domConstruct.create('div', { "style": hlStyle, "class": 'icon-highlight' }, dijit.domNode, 'before'); }, _removeHighLight: function(){ if (this.hlDiv){ domConstruct.destroy(this.hlDiv); this.hlDiv = null; } }, _onWidgetChange: function(appConfig, widgetConfig){ widgetConfig = appConfig.getConfigElementById(widgetConfig.id); if(widgetConfig.isController){ this._reloadControllerWidget(appConfig, widgetConfig.id); return; } array.forEach(this.widgetPlaceholders, function(placeholder){ if(placeholder.configId === widgetConfig.id){ placeholder.destroy(); this._loadPreloadWidget(widgetConfig, appConfig); } }, this); this._removeDestroyed(this.widgetPlaceholders); array.forEach(this.preloadWidgetIcons, function(icon){ if(icon.configId === widgetConfig.id){ var state = icon.state; icon.destroy(); this._loadPreloadWidget(widgetConfig, appConfig).then(function(iconNew){ if(widgetConfig.uri && state === 'opened'){ iconNew.onClick(); } }); } }, this); this._removeDestroyed(this.preloadWidgetIcons); array.forEach(this.widgetManager.getOnScreenOffPanelWidgets(), function(widget){ if(widget.configId === widgetConfig.id){ widget.destroy(); if(widgetConfig.visible === false){ if(this.invisibleWidgetIds.indexOf(widgetConfig.id) < 0){ this.invisibleWidgetIds.push(widgetConfig.id); } return; } this._loadPreloadWidget(widgetConfig, appConfig); } }, this); array.forEach(this.preloadGroupPanels, function(panel){ panel.reloadWidget(widgetConfig); }, this); this._updatePlaceholder(appConfig); //if widget change visible from invisible, it's not exist in preloadPanelessWidgets //so, load it here array.forEach(this.invisibleWidgetIds, function(widgetId){ if(widgetId === widgetConfig.id && widgetConfig.visible !== false){ this._loadPreloadWidget(widgetConfig, appConfig); var i = this.invisibleWidgetIds.indexOf(widgetConfig.id); this.invisibleWidgetIds.splice(i, 1); } }, this); if(!widgetConfig.isOnScreen){ array.forEach(this.widgetManager.getControllerWidgets(), function(controllerWidget){ if(controllerWidget.widgetIsControlled(widgetConfig.id)){ this._reloadControllerWidget(appConfig, controllerWidget.id); } }, this); } }, _onGroupChange: function(appConfig, groupConfig){ groupConfig = appConfig.getConfigElementById(groupConfig.id); if(groupConfig.isOnScreen){ //for now, onscreen group can change widgets in it only this.panelManager.destroyPanel(groupConfig.id + '_panel'); this._removeDestroyed(this.preloadGroupPanels); this._loadPreloadGroup(groupConfig, appConfig); }else{ //for now, we support group label change only in widget pool array.forEach(this.widgetManager.getControllerWidgets(), function(controllerWidget){ if(controllerWidget.isControlled(groupConfig.id)){ this._reloadControllerWidget(appConfig, controllerWidget.id); } }, this); array.forEach(this.panelManager.panels, function(panel){ if(panel.config.id === groupConfig.id){ panel.updateConfig(groupConfig); } }, this); } }, _updatePlaceholder: function (appConfig) { array.forEach(this.widgetPlaceholders, function(placehoder){ placehoder.setIndex(appConfig.getConfigElementById(placehoder.configId).placeholderIndex); }, this); }, _onWidgetPoolChange: function(appConfig, changeData){ this._reloadControllerWidget(appConfig, changeData.controllerId); }, _reloadControllerWidget: function(appConfig, controllerId){ var controllerWidget = this.widgetManager.getWidgetById(controllerId); if(!controllerWidget){ return; } //get old info var openedIds = controllerWidget.getOpenedIds(); var windowState = controllerWidget.windowState; //destory all panels controlled by the controller. //we can't destroy the opened only, because some panels are closed but the //instance is still exists //destroy controlled widgets array.forEach(controllerWidget.getAllConfigs(), function(configJson){ if(configJson.widgets){//it's group this.panelManager.destroyPanel(configJson.id + '_panel'); array.forEach(configJson.widgets, function(widgetItem){ //Group items must be in panel this.panelManager.destroyPanel(widgetItem.id + '_panel'); }, this); }else{ var widget = this.widgetManager.getWidgetById(configJson.id); if(!widget){ return; } if(configJson.inPanel){ this.panelManager.destroyPanel(widget.getPanel()); }else{ this.widgetManager.destroyWidget(widget); } } }, this); //destroy controller itself this.widgetManager.destroyWidget(controllerWidget); //load widget var newControllerJson = appConfig.getConfigElementById(controllerId); if(newControllerJson.visible === false){ return; } this._loadPreloadWidget(newControllerJson, appConfig).then(lang.hitch(this, function(widget){ this.widgetManager.changeWindowStateTo(widget, windowState); if(openedIds){ widget.setOpenedIds(openedIds); } })); }, _removeDestroyed: function(_array){ var willBeDestroyed = []; array.forEach(_array, function(e){ if(e._destroyed){ willBeDestroyed.push(e); } }); array.forEach(willBeDestroyed, function(e){ var i = _array.indexOf(e); _array.splice(i, 1); }); }, _destroyPreloadWidgetIcons: function(){ array.forEach(this.preloadWidgetIcons, function(icon){ icon.destroy(); }, this); this.preloadWidgetIcons = []; }, _destroyOffPanelWidgets: function(){ array.forEach(this.widgetManager.getOffPanelWidgets(), function(widget){ this.widgetManager.destroyWidget(widget); }, this); }, _destroyWidgetPlaceholders: function(){ array.forEach(this.widgetPlaceholders, function(placeholder){ placeholder.destroy(); }, this); this.widgetPlaceholders = []; }, _destroyPreloadGroupPanels: function(){ array.forEach(this.preloadGroupPanels, function(panel){ this.panelManager.destroyPanel(panel); }, this); this.preloadGroupPanels = []; }, _changeMapPosition: function(appConfig){ if(!this.map){ return; } if(!utils.isEqual(this.mapManager.getMapPosition(), appConfig.map.position)){ this.mapManager.setMapPosition(appConfig.map.position); } }, _onThemeChange: function(appConfig){ this._destroyPreloadWidgetIcons(); this._destroyWidgetPlaceholders(); this._destroyOffPanelWidgets(); this._destroyPreloadGroupPanels(); this.panelManager.destroyAllPanels(); this._removeThemeCommonStyle(this.appConfig.theme); this._removeThemeCurrentStyle(this.appConfig.theme); this._removeCustomStyle(); require(['themes/' + appConfig.theme.name + '/main'], lang.hitch(this, function(){ this._loadThemeCommonStyle(appConfig.theme); this._loadThemeCurrentStyle(appConfig.theme); this._addCustomStyle(appConfig.theme); this._changeMapPosition(appConfig); this._loadPreloadWidgets(appConfig); })); }, _onResetConfig: function(appConfig){ var oldAC = this.appConfig; topic.publish('appConfigChanged', appConfig, 'mapChange', appConfig);//this line will change this.appConfig this.appConfig = oldAC; this._updateCommonStyle(appConfig); this._onStyleChange(appConfig); this._changeMapPosition(appConfig); }, _onLoadingPageChange: function(appConfig, changeData){ if('backgroundColor' in changeData){ html.setStyle(jimuConfig.loadingId, 'background-color', appConfig.loadingPage.backgroundColor); }else if('backgroundImage' in changeData){ var bgImage = appConfig.loadingPage.backgroundImage; if(bgImage.visible && bgImage.uri){ html.setStyle(jimuConfig.loadingImageId, 'background-image', 'url(\'' + bgImage.uri + '\')'); html.setStyle(jimuConfig.loadingImageId, 'width', bgImage.width + 'px'); html.setStyle(jimuConfig.loadingImageId, 'height', bgImage.height + 'px'); }else{ html.setStyle(jimuConfig.loadingImageId, 'background-image', 'url(\'\')'); html.setStyle(jimuConfig.loadingImageId, 'width', '0px'); html.setStyle(jimuConfig.loadingImageId, 'height', '0px'); } }else if('loadingGif' in changeData){ var gifImage = appConfig.loadingPage.loadingGif; if(gifImage.visible && gifImage.uri){ html.setStyle(jimuConfig.loadingGifId, 'background-image', 'url(\'' + gifImage.uri + '\')'); html.setStyle(jimuConfig.loadingGifId, 'width', gifImage.width + 'px'); html.setStyle(jimuConfig.loadingGifId, 'height', gifImage.height + 'px'); }else{ html.setStyle(jimuConfig.loadingGifId, 'background-image', 'url(\'\')'); html.setStyle(jimuConfig.loadingGifId, 'width', '0px'); html.setStyle(jimuConfig.loadingGifId, 'height', '0px'); } } }, _updateCommonStyle : function(appConfig){ var currentTheme = this.appConfig.theme; // remove old theme name this._removeThemeCommonStyle(currentTheme); this._loadThemeCommonStyle(appConfig.theme); }, _onStyleChange: function(appConfig){ var currentTheme = this.appConfig.theme; this._removeThemeCurrentStyle(currentTheme); this._loadThemeCurrentStyle(appConfig.theme); this._removeCustomStyle(); this._addCustomStyle(appConfig.theme); }, _onLayoutChange: function(appConfig){ this._changeMapPosition(appConfig); //relayout placehoder array.forEach(this.widgetPlaceholders, function(placeholder){ placeholder.moveTo(appConfig.getConfigElementById(placeholder.configId).position); }, this); //relayout icons array.forEach(this.preloadWidgetIcons, function(icon){ icon.moveTo(appConfig.getConfigElementById(icon.configId).position); }, this); //relayout paneless widget array.forEach(this.widgetManager.getOnScreenOffPanelWidgets(), function(widget){ if(widget.closeable){ //this widget position is controlled by icon return; } var position = appConfig.getConfigElementById(widget.id).position; widget.setPosition(position); }, this); //relayout groups array.forEach(this.preloadGroupPanels, function(panel){ var position = appConfig.getConfigElementById(panel.config.id).panel.position; panel.setPosition(position); }, this); }, _loadTheme: function(theme) { //summary: // load theme style, including common and current style(the first) require(['themes/' + theme.name + '/main'], lang.hitch(this, function(){ this._loadThemeCommonStyle(theme); this._loadThemeCurrentStyle(theme); this._addCustomStyle(theme); })); }, _loadThemeCommonStyle: function(theme) { utils.loadStyleLink(this._getThemeCommonStyleId(theme), 'themes/' + theme.name + '/common.css'); // append theme name for better selector definition html.addClass(this.domNode, theme.name); }, _removeThemeCommonStyle: function(theme){ html.removeClass(this.domNode, theme.name); html.destroy(this._getThemeCommonStyleId(theme)); }, _loadThemeCurrentStyle: function(theme) { utils.loadStyleLink(this._getThemeCurrentStyleId(theme), 'themes/' + theme.name + '/styles/' + theme.styles[0] + '/style.css'); // append theme style name for better selector definitions html.addClass(this.domNode, theme.styles[0]); }, _removeThemeCurrentStyle: function(theme){ html.removeClass(this.domNode, theme.styles[0]); html.destroy(this._getThemeCurrentStyleId(theme)); }, _addCustomStyle: function(theme) { var customStyles = lang.getObject('customStyles', false, theme); if(!customStyles){ return; } var cssText = ".jimu-main-background{background-color: ${mainBackgroundColor} !important;}"; var themeCssText = this._getFixedThemeStyles(theme); if(themeCssText){ cssText += themeCssText; } cssText = lang.replace(cssText, customStyles, /\$\{([^\}]+)\}/g); var style = html.create('style', { type: 'text/css' }); try { style.appendChild(document.createTextNode(cssText)); } catch(err) { style.styleSheet.cssText = cssText; } style.setAttribute('source', 'custom'); document.head.appendChild(style); }, /** * This is a temp fix because the custom color can override one color only. * @param {Object} theme * @return {String} The CSS string */ _getFixedThemeStyles: function(theme){ //fix popup var cssText = '.esriPopup .titlePane {background-color: ${mainBackgroundColor} !important;}'; if(theme.name === 'PlateauTheme'){ cssText += '.jimu-widget-header-controller .jimu-title, .jimu-widget-header-controller .jimu-subtitle' + '{color: ${mainBackgroundColor} !important;}'; cssText += '.jimu-widget-header-controller .links .jimu-link' + '{color: ${mainBackgroundColor} !important;}'; cssText += '.jimu-widget-homebutton .HomeButton .home, .jimu-widget-mylocation,' + ' .jimu-widget-mylocation .place-holder, .jimu-widget-zoomslider.vertical .zoom-in,' + ' .jimu-widget-zoomslider.vertical .zoom-out, .jimu-widget-extent-navigate.vertical .operation' + '{background-color: ${mainBackgroundColor} !important;}'; cssText += '.jimu-preload-widget-icon-panel > .jimu-panel-title,' + ' .jimu-foldable-panel > .jimu-panel-title, .jimu-title-panel > .title' + '{color: ${mainBackgroundColor} !important;}'; cssText += '.jimu-panel{border-color: ${mainBackgroundColor} !important;}'; cssText += '.jimu-widget-header-controller' + '{border-bottom-color: ${mainBackgroundColor} !important;}'; cssText += '.jimu-tab>.control>.tab' + '{color: ${mainBackgroundColor} !important; border-color: ${mainBackgroundColor} !important}'; }else if(theme.name === 'BillboardTheme'){ cssText += '.jimu-widget-homebutton .HomeButton .home, .jimu-widget-mylocation,' + ' .jimu-widget-mylocation .place-holder, .jimu-widget-zoomslider.vertical .zoom-in,' + ' .jimu-widget-zoomslider.vertical .zoom-out, .jimu-widget-extent-navigate .operation' + '{background-color: ${mainBackgroundColor} !important;}'; cssText += '.jimu-widget-onscreen-icon' + '{background-color: ${mainBackgroundColor} !important;}'; }else if(theme.name === 'BoxTheme'){ cssText += '.jimu-widget-homebutton .HomeButton .home, .jimu-widget-mylocation,' + ' .jimu-widget-mylocation .place-holder, .jimu-widget-zoomslider.vertical .zoom-in,' + ' .jimu-widget-zoomslider.vertical .zoom-out, .jimu-widget-extent-navigate' + '{background-color: ${mainBackgroundColor} !important;}'; }else if(theme.name === 'TabTheme'){ cssText += '.tab-widget-frame .title-label{color: ${mainBackgroundColor} !important;}'; } return cssText; }, _removeCustomStyle: function() { query('style[source="custom"]', document.head).forEach(function(s) { html.destroy(s); }); }, _getThemeCommonStyleId: function(theme){ return 'theme_' + theme.name + '_style_common'; }, _getThemeCurrentStyleId: function(theme){ return 'theme_' + theme.name + '_style_' + theme.styles[0]; }, _loadMap: function() { html.create('div', { id: this.mapId, style: lang.mixin({ position: 'absolute', backgroundColor: '#EEEEEE', overflow: 'hidden', minWidth:'1px', minHeight:'1px' }) }, this.id); this.mapManager = MapManager.getInstance({ appConfig: this.appConfig, urlParams: this.urlParams }, this.mapId); this.mapManager.setMapPosition(this.appConfig.map.position); this.mapManager.showMap(); }, _createPreloadWidgetPlaceHolder: function(widgetConfig){ var pid; if(widgetConfig.position.relativeTo === 'map'){ pid = this.mapId; }else{ pid = this.id; } var cfg = lang.clone(widgetConfig); cfg.position.width = 40; cfg.position.height = 40; var style = utils.getPositionStyle(cfg.position); var phDijit = new WidgetPlaceholder({ index: cfg.placeholderIndex, configId: widgetConfig.id }); html.setStyle(phDijit.domNode, style); html.place(phDijit.domNode, pid); this.widgetPlaceholders.push(phDijit); return phDijit; }, _createPreloadWidgetIcon: function(widgetConfig){ var iconDijit = new OnScreenWidgetIcon({ panelManager: this.panelManager, widgetManager: this.widgetManager, widgetConfig: widgetConfig, configId: widgetConfig.id, map: this.map }); if(widgetConfig.position.relativeTo === 'map'){ html.place(iconDijit.domNode, this.mapId); }else{ html.place(iconDijit.domNode, this.id); } //icon position doesn't use width/height in config html.setStyle(iconDijit.domNode, utils.getPositionStyle({ top: widgetConfig.position.top, left: widgetConfig.position.left, right: widgetConfig.position.right, bottom: widgetConfig.position.bottom, width: 40, height: 40 })); iconDijit.startup(); if(!this.openAtStartWidget && widgetConfig.openAtStart){ iconDijit.switchToOpen(); this.openAtStartWidget = widgetConfig.name; } this.preloadWidgetIcons.push(iconDijit); return iconDijit; }, _loadPreloadWidgets: function(appConfig) { console.time('Load widgetOnScreen'); var loading = new LoadingShelter(), defs = []; loading.placeAt(this.id); loading.startup(); //load widgets array.forEach(appConfig.widgetOnScreen.widgets, function(widgetConfig) { if(widgetConfig.visible === false){ this.invisibleWidgetIds.push(widgetConfig.id); return; } defs.push(this._loadPreloadWidget(widgetConfig, appConfig)); }, this); //load groups array.forEach(appConfig.widgetOnScreen.groups, function(groupConfig) { defs.push(this._loadPreloadGroup(groupConfig, appConfig)); }, this); all(defs).then(lang.hitch(this, function(){ if(loading){ loading.destroy(); loading = null; } console.timeEnd('Load widgetOnScreen'); topic.publish('preloadWidgetsLoaded'); this._doPostLoad(); }), lang.hitch(this, function(){ if(loading){ loading.destroy(); loading = null; } //if error when load widget, let the others continue console.timeEnd('Load widgetOnScreen'); topic.publish('preloadWidgetsLoaded'); this._doPostLoad(); })); // setTimeout(function(){ // if(loading){ // loading.destroy(); // loading = null; // } // }, jimuConfig.timeout); }, _doPostLoad: function(){ //load somethings that may be used later. //let it load behind the stage. require(['dynamic-modules/postload']); }, _loadPreloadWidget: function(widgetConfig, appConfig) { var def = new Deferred(); if(appConfig.mode === 'config' && !widgetConfig.uri){ var placeholder = this._createPreloadWidgetPlaceHolder(widgetConfig); def.resolve(placeholder); return def; }else if(!widgetConfig.uri){ //in run mode, when no uri, do nothing def.resolve(null); return def; } var iconDijit; if(widgetConfig.inPanel || widgetConfig.closeable){//TODO closeable rename //in panel widget or closeable off panel widget iconDijit = this._createPreloadWidgetIcon(widgetConfig); def.resolve(iconDijit); }else{ //off panel this.widgetManager.loadWidget(widgetConfig).then(lang.hitch(this, function(widget){ try{ widget.setPosition(widget.position); this.widgetManager.openWidget(widget); }catch(err){ console.log(console.error('fail to startup widget ' + widget.name + '. ' + err.stack)); } widget.configId = widgetConfig.id; def.resolve(widget); }), function(err){ def.reject(err); }); } return def; }, _loadPreloadGroup: function(groupJson, appConfig) { if(!appConfig.mode && (!groupJson.widgets || groupJson.widgets.length === 0)){ return when(null); } return this.panelManager.showPanel(groupJson).then(lang.hitch(this, function(panel){ panel.configId = groupJson.id; this.preloadGroupPanels.push(panel); return panel; })); }, _onOpenWidgetRequest: function(widgetId){ //if widget is in group, we just ignore it //check on screen widgets, we don't check not-closeable off-panel widget array.forEach(this.preloadWidgetIcons, function(widgetIcon){ if(widgetIcon.configId === widgetId){ widgetIcon.switchToOpen(); } }, this); //check controllers array.forEach(this.widgetManager.getControllerWidgets(), function(controllerWidget){ if(controllerWidget.widgetIsControlled(widgetId)){ controllerWidget.setOpenedIds([widgetId]); } }, this); } }); clazz.getInstance = function(options, domId) { if (instance === null) { instance = new clazz(options, domId); window._layoutManager = instance; } return instance; }; return clazz; });
/* MAPSTRACTION vtimemap http://www.mapstraction.com Copyright (c) 2011 Tom Carden, Steve Coast, Mikel Maron, Andrew Turner, Henri Bergius, Rob Moran, Derek Fowler, Gary Gale All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Mapstraction nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ mxn.register('cloudmade', { Mapstraction: { init: function(element, api) { var me = this; var opts = { key: cloudmade_key }; if (typeof cloudmade_styleId != "undefined"){ opts.styleId = cloudmade_styleId; } var cloudmade = new CM.Tiles.CloudMade.Web(opts); this.maps[api] = new CM.Map(element, cloudmade); this.loaded[api] = true; CM.Event.addListener(this.maps[api], 'click', function(location,marker) { if ( marker && marker.mapstraction_marker ) { marker.mapstraction_marker.click.fire(); } else if ( location ) { me.click.fire({'location': new mxn.LatLonPoint(location.lat(), location.lng())}); } // If the user puts their own Google markers directly on the map // then there is no location and this event should not fire. if ( location ) { me.clickHandler(location.lat(),location.lng(),location,me); } }); CM.Event.addListener(this.maps[api], 'dragend', function() { me.endPan.fire(); }); CM.Event.addListener(this.maps[api], 'zoomend', function() { me.changeZoom.fire(); }); }, applyOptions: function(){ var map = this.maps[this.api]; if(this.options.enableScrollWheelZoom){ map.enableScrollWheelZoom(); } }, resizeTo: function(width, height){ this.maps[this.api].checkResize(); }, addControls: function( args ) { var map = this.maps[this.api]; var c = this.addControlsArgs; switch (c.zoom) { case 'large': this.addLargeControls(); break; case 'small': this.addSmallControls(); break; } if (c.map_type) { this.addMapTypeControls(); } if (c.scale) { map.addControl(new CM.ScaleControl()); this.addControlsArgs.scale = true; } }, addSmallControls: function() { var map = this.maps[this.api]; map.addControl(new CM.SmallMapControl()); this.addControlsArgs.zoom = 'small'; }, addLargeControls: function() { var map = this.maps[this.api]; map.addControl(new CM.LargeMapControl()); this.addControlsArgs.zoom = 'large'; }, addMapTypeControls: function() { var map = this.maps[this.api]; map.addControl(new CM.TileLayerControl()); this.addControlsArgs.map_type = true; }, dragging: function(on) { var map = this.maps[this.api]; if (on) { map.enableDragging(); } else { map.disableDragging(); } }, setCenterAndZoom: function(point, zoom) { var map = this.maps[this.api]; var pt = point.toProprietary(this.api); map.setCenter(pt, zoom); }, addMarker: function(marker, old) { var map = this.maps[this.api]; var pin = marker.toProprietary(this.api); map.addOverlay(pin); return pin; }, removeMarker: function(marker) { var map = this.maps[this.api]; marker.proprietary_marker.closeInfoWindow(); map.removeOverlay(marker.proprietary_marker); }, declutterMarkers: function(opts) { var map = this.maps[this.api]; // TODO: Add provider code }, addPolyline: function(polyline, old) { var map = this.maps[this.api]; var pl = polyline.toProprietary(this.api); map.addOverlay(pl); return pl; }, removePolyline: function(polyline) { var map = this.maps[this.api]; map.removeOverlay(polyline.proprietary_polyline); }, getCenter: function() { var map = this.maps[this.api]; var pt = map.getCenter(); return new mxn.LatLonPoint(pt.lat(), pt.lng()); }, setCenter: function(point, options) { var map = this.maps[this.api]; var pt = point.toProprietary(this.api); if(options !== null && options.pan) { map.panTo(pt); } else { map.setCenter(pt); } }, setZoom: function(zoom) { var map = this.maps[this.api]; map.setZoom(zoom); }, getZoom: function() { var map = this.maps[this.api]; return map.getZoom(); }, getZoomLevelForBoundingBox: function( bbox ) { var map = this.maps[this.api]; // NE and SW points from the bounding box. var ne = bbox.getNorthEast(); var sw = bbox.getSouthWest(); var zoom = map.getBoundsZoomLevel(new CM.LatLngBounds(sw.toProprietary(this.api), ne.toProprietary(this.api))); return zoom; }, setMapType: function(type) { var map = this.maps[this.api]; // TODO: Are there any MapTypes for Cloudmade? switch(type) { case mxn.Mapstraction.ROAD: // TODO: Add provider code break; case mxn.Mapstraction.SATELLITE: // TODO: Add provider code break; case mxn.Mapstraction.HYBRID: // TODO: Add provider code break; default: // TODO: Add provider code } }, getMapType: function() { var map = this.maps[this.api]; // TODO: Are there any MapTypes for Cloudmade? return mxn.Mapstraction.ROAD; //return mxn.Mapstraction.SATELLITE; //return mxn.Mapstraction.HYBRID; }, getBounds: function () { var map = this.maps[this.api]; var box = map.getBounds(); var sw = box.getSouthWest(); var ne = box.getNorthEast(); return new mxn.BoundingBox(sw.lat(), sw.lng(), ne.lat(), ne.lng()); }, setBounds: function(bounds){ var map = this.maps[this.api]; var sw = bounds.getSouthWest(); var ne = bounds.getNorthEast(); map.zoomToBounds(new CM.LatLngBounds(sw.toProprietary(this.api), ne.toProprietary(this.api))); }, addImageOverlay: function(id, src, opacity, west, south, east, north, oContext) { var map = this.maps[this.api]; // TODO: Add provider code }, setImagePosition: function(id, oContext) { var map = this.maps[this.api]; var topLeftPoint; var bottomRightPoint; // TODO: Add provider code }, addOverlay: function(url, autoCenterAndZoom) { var map = this.maps[this.api]; // TODO: Add provider code }, addTileLayer: function(tile_url, opacity, copyright_text, min_zoom, max_zoom) { var map = this.maps[this.api]; // TODO: Add provider code }, toggleTileLayer: function(tile_url) { var map = this.maps[this.api]; // TODO: Add provider code }, getPixelRatio: function() { var map = this.maps[this.api]; // TODO: Add provider code }, mousePosition: function(element) { var map = this.maps[this.api]; // TODO: Add provider code } }, LatLonPoint: { toProprietary: function() { var cll = new CM.LatLng(this.lat,this.lon); return cll; }, fromProprietary: function(point) { this.lat = point.lat(); this.lon = point.lng(); } }, Marker: { toProprietary: function() { var pt = this.location.toProprietary(this.api); var options = {}; if (this.iconUrl) { var cicon = new CM.Icon(); cicon.image = this.iconUrl; if (this.iconSize) { cicon.iconSize = new CM.Size(this.iconSize[0], this.iconSize[1]); if (this.iconAnchor) { cicon.iconAnchor = new CM.Point(this.iconAnchor[0], this.iconAnchor[1]); } } if (this.iconShadowUrl) { cicon.shadow = this.iconShadowUrl; if (this.iconShadowSize) { cicon.shadowSize = new CM.Size(this.iconShadowSize[0], this.iconShadowSize[1]); } } options.icon = cicon; } if (this.labelText) { options.title = this.labelText; } var cmarker = new CM.Marker(pt, options); if (this.infoBubble) { cmarker.bindInfoWindow(this.infoBubble); } return cmarker; }, openBubble: function() { var pin = this.proprietary_marker; pin.openInfoWindow(this.infoBubble); }, hide: function() { var pin = this.proprietary_marker; pin.hide(); }, show: function() { var pin = this.proprietary_marker; pin.show(); }, update: function() { // TODO: Add provider code } }, Polyline: { toProprietary: function() { var pts = []; var poly; for (var i = 0, length = this.points.length ; i< length; i++){ pts.push(this.points[i].toProprietary(this.api)); } if (this.closed || pts[0].equals(pts[pts.length-1])) { poly = new CM.Polygon(pts, this.color, this.width, this.opacity, this.fillColor || "#5462E3", this.opacity || "0.3"); } else { poly = new CM.Polyline(pts, this.color, this.width, this.opacity); } return poly; }, show: function() { this.proprietary_polyline.show(); }, hide: function() { this.proprietary_polyline.hide(); } } });
function Open(command, params/*, item*/) { var room, subscription, type; if (command !== 'open' || !Match.test(params, String)) { return; } room = params.trim(); if (room.indexOf('#') !== -1) { type = 'c'; } if (room.indexOf('@') !== -1) { type = 'd'; } room = room.replace('#', ''); room = room.replace('@', ''); var query = { name: room }; if (type) { query['t'] = type; } subscription = ChatSubscription.findOne(query); if (subscription !== null) { FlowRouter.go(RocketChat.roomTypes.getRouteLink(subscription.t, subscription)); } } RocketChat.slashCommands.add('open', Open, { description: TAPi18n.__('Opens_a_channel_group_or_direct_message'), params: 'room name', clientOnly: true });
/** * EventUtils.js * * Copyright, Moxiecode Systems AB * Released under LGPL License. * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /*jshint loopfunc:true*/ /*eslint no-loop-func:0 */ /** * This class wraps the browsers native event logic with more convenient methods. * * @class tinymce.dom.EventUtils */ define("tinymce/dom/EventUtils", [], function() { "use strict"; var eventExpandoPrefix = "mce-data-"; var mouseEventRe = /^(?:mouse|contextmenu)|click/; var deprecated = {keyLocation: 1, layerX: 1, layerY: 1, returnValue: 1}; /** * Binds a native event to a callback on the speified target. */ function addEvent(target, name, callback, capture) { if (target.addEventListener) { target.addEventListener(name, callback, capture || false); } else if (target.attachEvent) { target.attachEvent('on' + name, callback); } } /** * Unbinds a native event callback on the specified target. */ function removeEvent(target, name, callback, capture) { if (target.removeEventListener) { target.removeEventListener(name, callback, capture || false); } else if (target.detachEvent) { target.detachEvent('on' + name, callback); } } /** * Normalizes a native event object or just adds the event specific methods on a custom event. */ function fix(originalEvent, data) { var name, event = data || {}, undef; // Dummy function that gets replaced on the delegation state functions function returnFalse() { return false; } // Dummy function that gets replaced on the delegation state functions function returnTrue() { return true; } // Copy all properties from the original event for (name in originalEvent) { // layerX/layerY is deprecated in Chrome and produces a warning if (!deprecated[name]) { event[name] = originalEvent[name]; } } // Normalize target IE uses srcElement if (!event.target) { event.target = event.srcElement || document; } // Calculate pageX/Y if missing and clientX/Y available if (originalEvent && mouseEventRe.test(originalEvent.type) && originalEvent.pageX === undef && originalEvent.clientX !== undef) { var eventDoc = event.target.ownerDocument || document; var doc = eventDoc.documentElement; var body = eventDoc.body; event.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0); } // Add preventDefault method event.preventDefault = function() { event.isDefaultPrevented = returnTrue; // Execute preventDefault on the original event object if (originalEvent) { if (originalEvent.preventDefault) { originalEvent.preventDefault(); } else { originalEvent.returnValue = false; // IE } } }; // Add stopPropagation event.stopPropagation = function() { event.isPropagationStopped = returnTrue; // Execute stopPropagation on the original event object if (originalEvent) { if (originalEvent.stopPropagation) { originalEvent.stopPropagation(); } else { originalEvent.cancelBubble = true; // IE } } }; // Add stopImmediatePropagation event.stopImmediatePropagation = function() { event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; // Add event delegation states if (!event.isDefaultPrevented) { event.isDefaultPrevented = returnFalse; event.isPropagationStopped = returnFalse; event.isImmediatePropagationStopped = returnFalse; } return event; } /** * Bind a DOMContentLoaded event across browsers and executes the callback once the page DOM is initialized. * It will also set/check the domLoaded state of the event_utils instance so ready isn't called multiple times. */ function bindOnReady(win, callback, eventUtils) { var doc = win.document, event = {type: 'ready'}; if (eventUtils.domLoaded) { callback(event); return; } // Gets called when the DOM is ready function readyHandler() { if (!eventUtils.domLoaded) { eventUtils.domLoaded = true; callback(event); } } function waitForDomLoaded() { // Check complete or interactive state if there is a body // element on some iframes IE 8 will produce a null body if (doc.readyState === "complete" || (doc.readyState === "interactive" && doc.body)) { removeEvent(doc, "readystatechange", waitForDomLoaded); readyHandler(); } } function tryScroll() { try { // If IE is used, use the trick by Diego Perini licensed under MIT by request to the author. // http://javascript.nwbox.com/IEContentLoaded/ doc.documentElement.doScroll("left"); } catch (ex) { setTimeout(tryScroll, 0); return; } readyHandler(); } // Use W3C method if (doc.addEventListener) { if (doc.readyState === "complete") { readyHandler(); } else { addEvent(win, 'DOMContentLoaded', readyHandler); } } else { // Use IE method addEvent(doc, "readystatechange", waitForDomLoaded); // Wait until we can scroll, when we can the DOM is initialized if (doc.documentElement.doScroll && win.self === win.top) { tryScroll(); } } // Fallback if any of the above methods should fail for some odd reason addEvent(win, 'load', readyHandler); } /** * This class enables you to bind/unbind native events to elements and normalize it's behavior across browsers. */ function EventUtils() { var self = this, events = {}, count, expando, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave; expando = eventExpandoPrefix + (+new Date()).toString(32); hasMouseEnterLeave = "onmouseenter" in document.documentElement; hasFocusIn = "onfocusin" in document.documentElement; mouseEnterLeave = {mouseenter: 'mouseover', mouseleave: 'mouseout'}; count = 1; // State if the DOMContentLoaded was executed or not self.domLoaded = false; self.events = events; /** * Executes all event handler callbacks for a specific event. * * @private * @param {Event} evt Event object. * @param {String} id Expando id value to look for. */ function executeHandlers(evt, id) { var callbackList, i, l, callback, container = events[id]; callbackList = container && container[evt.type]; if (callbackList) { for (i = 0, l = callbackList.length; i < l; i++) { callback = callbackList[i]; // Check if callback exists might be removed if a unbind is called inside the callback if (callback && callback.func.call(callback.scope, evt) === false) { evt.preventDefault(); } // Should we stop propagation to immediate listeners if (evt.isImmediatePropagationStopped()) { return; } } } } /** * Binds a callback to an event on the specified target. * * @method bind * @param {Object} target Target node/window or custom object. * @param {String} names Name of the event to bind. * @param {function} callback Callback function to execute when the event occurs. * @param {Object} scope Scope to call the callback function on, defaults to target. * @return {function} Callback function that got bound. */ self.bind = function(target, names, callback, scope) { var id, callbackList, i, name, fakeName, nativeHandler, capture, win = window; // Native event handler function patches the event and executes the callbacks for the expando function defaultNativeHandler(evt) { executeHandlers(fix(evt || win.event), id); } // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return; } // Create or get events id for the target if (!target[expando]) { id = count++; target[expando] = id; events[id] = {}; } else { id = target[expando]; } // Setup the specified scope or use the target as a default scope = scope || target; // Split names and bind each event, enables you to bind multiple events with one call names = names.split(' '); i = names.length; while (i--) { name = names[i]; nativeHandler = defaultNativeHandler; fakeName = capture = false; // Use ready instead of DOMContentLoaded if (name === "DOMContentLoaded") { name = "ready"; } // DOM is already ready if (self.domLoaded && name === "ready" && target.readyState == 'complete') { callback.call(scope, fix({type: name})); continue; } // Handle mouseenter/mouseleaver if (!hasMouseEnterLeave) { fakeName = mouseEnterLeave[name]; if (fakeName) { nativeHandler = function(evt) { var current, related; current = evt.currentTarget; related = evt.relatedTarget; // Check if related is inside the current target if it's not then the event should // be ignored since it's a mouseover/mouseout inside the element if (related && current.contains) { // Use contains for performance related = current.contains(related); } else { while (related && related !== current) { related = related.parentNode; } } // Fire fake event if (!related) { evt = fix(evt || win.event); evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter'; evt.target = current; executeHandlers(evt, id); } }; } } // Fake bubbeling of focusin/focusout if (!hasFocusIn && (name === "focusin" || name === "focusout")) { capture = true; fakeName = name === "focusin" ? "focus" : "blur"; nativeHandler = function(evt) { evt = fix(evt || win.event); evt.type = evt.type === 'focus' ? 'focusin' : 'focusout'; executeHandlers(evt, id); }; } // Setup callback list and bind native event callbackList = events[id][name]; if (!callbackList) { events[id][name] = callbackList = [{func: callback, scope: scope}]; callbackList.fakeName = fakeName; callbackList.capture = capture; //callbackList.callback = callback; // Add the nativeHandler to the callback list so that we can later unbind it callbackList.nativeHandler = nativeHandler; // Check if the target has native events support if (name === "ready") { bindOnReady(target, nativeHandler, self); } else { addEvent(target, fakeName || name, nativeHandler, capture); } } else { if (name === "ready" && self.domLoaded) { callback({type: name}); } else { // If it already has an native handler then just push the callback callbackList.push({func: callback, scope: scope}); } } } target = callbackList = 0; // Clean memory for IE return callback; }; /** * Unbinds the specified event by name, name and callback or all events on the target. * * @method unbind * @param {Object} target Target node/window or custom object. * @param {String} names Optional event name to unbind. * @param {function} callback Optional callback function to unbind. * @return {EventUtils} Event utils instance. */ self.unbind = function(target, names, callback) { var id, callbackList, i, ci, name, eventMap; // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return self; } // Unbind event or events if the target has the expando id = target[expando]; if (id) { eventMap = events[id]; // Specific callback if (names) { names = names.split(' '); i = names.length; while (i--) { name = names[i]; callbackList = eventMap[name]; // Unbind the event if it exists in the map if (callbackList) { // Remove specified callback if (callback) { ci = callbackList.length; while (ci--) { if (callbackList[ci].func === callback) { var nativeHandler = callbackList.nativeHandler; var fakeName = callbackList.fakeName, capture = callbackList.capture; // Clone callbackList since unbind inside a callback would otherwise break the handlers loop callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1)); callbackList.nativeHandler = nativeHandler; callbackList.fakeName = fakeName; callbackList.capture = capture; eventMap[name] = callbackList; } } } // Remove all callbacks if there isn't a specified callback or there is no callbacks left if (!callback || callbackList.length === 0) { delete eventMap[name]; removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture); } } } } else { // All events for a specific element for (name in eventMap) { callbackList = eventMap[name]; removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture); } eventMap = {}; } // Check if object is empty, if it isn't then we won't remove the expando map for (name in eventMap) { return self; } // Delete event object delete events[id]; // Remove expando from target try { // IE will fail here since it can't delete properties from window delete target[expando]; } catch (ex) { // IE will set it to null target[expando] = null; } } return self; }; /** * Fires the specified event on the specified target. * * @method fire * @param {Object} target Target node/window or custom object. * @param {String} name Event name to fire. * @param {Object} args Optional arguments to send to the observers. * @return {EventUtils} Event utils instance. */ self.fire = function(target, name, args) { var id; // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return self; } // Build event object by patching the args args = fix(null, args); args.type = name; args.target = target; do { // Found an expando that means there is listeners to execute id = target[expando]; if (id) { executeHandlers(args, id); } // Walk up the DOM target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow; } while (target && !args.isPropagationStopped()); return self; }; /** * Removes all bound event listeners for the specified target. This will also remove any bound * listeners to child nodes within that target. * * @method clean * @param {Object} target Target node/window object. * @return {EventUtils} Event utils instance. */ self.clean = function(target) { var i, children, unbind = self.unbind; // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return self; } // Unbind any element on the specificed target if (target[expando]) { unbind(target); } // Target doesn't have getElementsByTagName it's probably a window object then use it's document to find the children if (!target.getElementsByTagName) { target = target.document; } // Remove events from each child element if (target && target.getElementsByTagName) { unbind(target); children = target.getElementsByTagName('*'); i = children.length; while (i--) { target = children[i]; if (target[expando]) { unbind(target); } } } return self; }; /** * Destroys the event object. Call this on IE to remove memory leaks. */ self.destroy = function() { events = {}; }; // Legacy function for canceling events self.cancel = function(e) { if (e) { e.preventDefault(); e.stopImmediatePropagation(); } return false; }; } EventUtils.Event = new EventUtils(); EventUtils.Event.bind(window, 'ready', function() {}); return EventUtils; });
/** * @name ui-course-infor.js * @description 课程详情页 * * @author alexliu * @modify 2013-07-12 16:52:31 * @links https://github.com/xueAlex/ */ // 课程详情页头像切换封装函数 var xue = xue || {}; xue.avatar = xue.avatar || {}; (function () { var a = xue.avatar; a.box = { pic: null, list: null, btn: null }; a.step = $(".avatar_items li").width(); a.size = 0; a.max = 0; a.len = 0; a.toggle = function (expr) { var btn = $(expr); if (btn.length == 0) { return; } var wrap = btn.parent(); var pic = wrap.hasClass('avatar_roll') ? wrap.siblings('.avatar_items') : wrap.find('.avatar_items'); if (pic.length == 0) { return; } this.box.pic = pic; this.box.list = pic.find('li'); this.box.btn = btn; this.box.prev = btn.hasClass('prev') ? btn : btn.siblings('.prev'); this.box.next = btn.hasClass('next') ? btn : btn.siblings('.next'); this.size = this.box.list.length; this.max = this.size - 1; var list = pic.find('li'); var left = pic.css('margin-left'); this.left = Number(left.replace('px', '')); if (btn.hasClass('prev')) { a.prev(); } else { a.next(); } } a.prev = function () { if (a.left < 0) { a.box.pic.animate({ marginLeft: '+=' + a.step + 'px' }, 500, function () { a.left += a.step; a.setCls(); if (a.left >= 0) { $(this).clearQueue(); } }); } else { a.box.pic.clearQueue(); } }; a.next = function () { var box = a.box.pic, left = Number(box.css('margin-left').replace('px', '')); if (a.left > -(a.max * a.step)) { a.box.pic.animate({ marginLeft: '-=' + a.step + 'px' }, 500, function () { a.left -= a.step; a.setCls(); if (a.left <= -(a.max * a.step)) { $(this).clearQueue(); } }); } else { a.box.pic.clearQueue(); } }; a.setCls = function () { var hasNext = Math.abs(a.left) < ((a.box.list.length - 1) * a.step); var hasPrev = a.left < 0; if (hasNext) { a.box.next.removeClass('none'); } else { a.box.next.addClass('none'); } if (hasPrev) { a.box.prev.removeClass('none'); } else { a.box.prev.addClass('none'); } }; })(xue.avatar); var courseInfor = courseInfor || {}; //视频弹层方法封装 courseInfor.videoPlaySwitch = function (u, w, h, t) { xue.win({ id: 'videoPlayWrap', title: t, content: '<iframe frameborder="0" scrolling="no" src="' + u + '" width="100%" height="100%"> </iframe>', width: w, height: h, lock: true, close: true, submit: false, cancel: false }); if($('#xuebox_videoPlayWrap').length == 1){ $('body').css('overflow-y','hidden'); } $('#xuebox_videoPlayWrap .dialog_close').on('click',function(){ $('body').css('overflow-y','scroll'); }); } //课程大纲切换方法 courseInfor.courseTab = function (tabTit, on, tabCon) { var items = $(tabTit).children(); items.click(function () { var that = $(this), con = $(tabCon).children(), index = items.index(this); that.addClass(on).siblings().removeClass(on); con.eq(index).show().siblings().hide(); }); } $(function () { courseInfor.courseTab('.ui-nav-link', 'current', '.course-info-box'); //课程详情页--课程大纲切换 var ouline = $('#open-outline'); //免费试听详情页------试听节超过规定节数出现滚动条 if (ouline.length != 0) { //当id:ouline的值不等于零的时候执行 ouline.jScrollPane(); } //courseInfor.lookTimeList(); //直播课程详情页---查看直播时间列表 // 绑定老师头像切换事件 $('body').on('click', '.ui_avatar_con .prev , .ui_avatar_con .next', function () { var that = $(this); if (that.hasClass('none')) { return false; } else { xue.avatar.toggle(that) } }); //加入购物车效果 $('body').on('click', '.button_shop-cart', function () { var that = $(this), _id = that.data('id'), _url = miniUrl + '/ShoppingCart/addCart/' + _id; $.ajax({ url: _url, type: 'GET', dataType: 'jsonp', jsonp: 'jsonpCallback', success: function (result) { if (result.sign == 1) { var num = Number($('small.minicart-total').text()); $('small.minicart-total').text(num + 1); $('#miniCart-body').empty(); $('.button_shop-cart').button('loading'); $.ajax({ url: '/ShoppingCart/ajaxGetCartList/', type: 'POST', dataType: 'html', // xhrFields: { // withCredentials: true // }, // crossDomain: true, success: function (result) { $(result).appendTo('#miniCart-body'); } }); } if (result.sign == 2) { window.location.href = result.url; } } }); }); //暂时不可报名 $('body').on('mouseenter','.do_not_sign_up', function(){ var that = $(this); var tpl = that.text(); var con =''; var a = $('#courseExam'), b = a.data('stuscore'), c = a.data('cutscore'); if(tpl === '无报名资格'){ con = '抱歉,您不具备本课程的报名资格,详情请咨询<strong style="color:#cc0000;">4008002211</strong>' }else if(tpl === '报满'){ con = '抱歉,本课程已经报满,暂时无法报名'; }else if(tpl === '考试未通过'){ con = '抱歉您未通过考试,您的得分<strong style="color:#cc0000;">'+ b +'</strong>分,分数线<strong style="color:#cc0000;">'+ c +'</strong>分。请报名其他课程。'; }else{ con = '抱歉,当前没有正在进行的课程排期'; } xue.win({ id: 'DoNotSignUp', title : false, arrow : 'bc', follow : that, content : con, lock : false, close : false, submit : false, cancel : false }); var box = $('#xuebox_DoNotSignUp'), size = xue.win('DoNotSignUp').getSize(), o = { left : that.offset().left + (that.outerWidth() / 2) - (size.outerWidth / 2), top : that.offset().top + that.height() - 73 }; xue.win('DoNotSignUp').position(o.left, o.top); $(this).on('mouseleave', function(e){ if($(e.relatedTarget).attr('id') != 'xuebox_DoNotSignUp' && $(e.relatedTarget).parents('#xuebox_DoNotSignUp').length === 0){ xue.win('DoNotSignUp').close(); } }); $('#xuebox_DoNotSignUp').on('mouseleave', function(){ xue.win('DoNotSignUp').close(); }); }); //参加考试 $('body').on('mouseenter','.btn-join-exam', function(){ var that = $(this); xue.win({ id: 'btnJoinExam', title : false, arrow : 'bc', follow : that, content : '通过入学考试才能报名此课程', lock : false, close : false, submit : false, cancel : false }); var box = $('#xuebox_btnJoinExam'), size = xue.win('btnJoinExam').getSize(), o = { left : that.offset().left + (that.outerWidth() / 2) - (size.outerWidth / 2), top : that.offset().top + that.height() - 73 }; xue.win('btnJoinExam').position(o.left, o.top); $(this).on('mouseleave', function(e){ if($(e.relatedTarget).attr('id') != 'xuebox_btnJoinExam' && $(e.relatedTarget).parents('#xuebox_btnJoinExam').length === 0){ xue.win('btnJoinExam').close(); } }); $('#xuebox_btnJoinExam').on('mouseleave', function(){ xue.win('btnJoinExam').close(); }); }); });
// this should not get included var fluff = true;
// Since the code for most chapter in Eloquent JavaScript isn't // written with node's module system in mind, this kludge is used to // load dependency files into the global namespace, so that the // examples can run on node. module.exports = function() { for (var i = 0; i < arguments.length; i++) (1,eval)(require("fs").readFileSync(__dirname + "/../" + arguments[i], "utf8")); };
var React = require('react') module.exports = React.createClass({ getInitialState: function() { return { text: '', ok: false } }, handleSubmit: function(e) { e.preventDefault() if (this.props.onAdd(this.state.text)) { this.setState({text: '', ok: false}) } }, onChange: function(e) { this.setState({text: e.target.value, ok: !!e.target.value}) }, render: function() { return ( <form onSubmit={this.handleSubmit}> <input onChange={this.onChange} value={this.state.text} /> <button disabled={!this.state.ok}>Add item</button> </form> ) } })
module.exports = require("npm:des.js@1.0.0/lib/des.js");
/** @license * @pnp/sp-taxonomy v1.1.2-0 - pnp - Provides a fluent API to work with SharePoint taxonomy * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https://github.com/pnp/pnp * bugs: https://github.com/pnp/pnp/issues */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('tslib'), require('@pnp/sp-clientsvc'), require('@pnp/common'), require('@pnp/sp')) : typeof define === 'function' && define.amd ? define(['exports', 'tslib', '@pnp/sp-clientsvc', '@pnp/common', '@pnp/sp'], factory) : (factory((global.pnp = global.pnp || {}, global.pnp['sp-taxonomy'] = {}),global.tslib_1,global.spClientsvc,global.common,global.sp)); }(this, (function (exports,tslib_1,spClientsvc,common,sp) { 'use strict'; /** * Represents a collection of labels */ var Labels = /** @class */ (function (_super) { tslib_1.__extends(Labels, _super); function Labels(parent, _objectPaths) { if (parent === void 0) { parent = ""; } if (_objectPaths === void 0) { _objectPaths = null; } var _this = _super.call(this, parent, _objectPaths) || this; _this._objectPaths.add(spClientsvc.property("Labels")); return _this; } /** * Gets a label from the collection by its value * * @param value The value to retrieve */ Labels.prototype.getByValue = function (value) { var params = spClientsvc.MethodParams.build().string(value); return this.getChild(Label, "GetByValue", params); }; /** * Loads the data and merges with with the ILabel instances */ Labels.prototype.get = function () { return this.sendGetCollection(Label); }; return Labels; }(spClientsvc.ClientSvcQueryable)); /** * Represents a label instance */ var Label = /** @class */ (function (_super) { tslib_1.__extends(Label, _super); function Label() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the data for this Label */ Label.prototype.get = function () { return this.sendGet(Label); }; /** * Sets this label as the default */ Label.prototype.setAsDefaultForLanguage = function () { return this.invokeNonQuery("SetAsDefaultForLanguage"); }; /** * Deletes this label */ Label.prototype.delete = function () { return this.invokeNonQuery("DeleteObject"); }; return Label; }(spClientsvc.ClientSvcQueryable)); var Terms = /** @class */ (function (_super) { tslib_1.__extends(Terms, _super); function Terms() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the terms in this collection */ Terms.prototype.get = function () { return this.sendGetCollection(Term); }; return Terms; }(spClientsvc.ClientSvcQueryable)); /** * Represents the operations available on a given term */ var Term = /** @class */ (function (_super) { tslib_1.__extends(Term, _super); function Term() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(Term.prototype, "labels", { get: function () { return new Labels(this); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "parent", { get: function () { return this.getChildProperty(Term, "Parent"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "pinSourceTermSet", { get: function () { return this.getChildProperty(TermSet, "PinSourceTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "reusedTerms", { get: function () { return this.getChildProperty(Terms, "ReusedTerms"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "sourceTerm", { get: function () { return this.getChildProperty(Term, "SourceTerm"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "termSet", { get: function () { return this.getChildProperty(TermSet, "TermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "termSets", { get: function () { return this.getChildProperty(TermSets, "TermSets"); }, enumerable: true, configurable: true }); /** * Creates a new label for this Term * * @param name label value * @param lcid language code * @param isDefault Is the default label */ Term.prototype.createLabel = function (name, lcid, isDefault) { var _this = this; if (isDefault === void 0) { isDefault = false; } var params = spClientsvc.MethodParams.build() .string(name) .number(lcid) .boolean(isDefault); this._useCaching = false; return this.invokeMethod("CreateLabel", params) .then(function (r) { return common.extend(_this.labels.getByValue(name), r); }); }; /** * Sets the deprecation flag on a term * * @param doDeprecate New value for the deprecation flag */ Term.prototype.deprecate = function (doDeprecate) { var params = spClientsvc.MethodParams.build().boolean(doDeprecate); return this.invokeNonQuery("Deprecate", params); }; /** * Loads the term data */ Term.prototype.get = function () { return this.sendGet(Term); }; /** * Sets the description * * @param description Term description * @param lcid Language code */ Term.prototype.setDescription = function (description, lcid) { var params = spClientsvc.MethodParams.build().string(description).number(lcid); return this.invokeNonQuery("SetDescription", params); }; /** * Sets a custom property on this term * * @param name Property name * @param value Property value */ Term.prototype.setLocalCustomProperty = function (name, value) { var params = spClientsvc.MethodParams.build().string(name).string(value); return this.invokeNonQuery("SetLocalCustomProperty", params); }; /** * Updates the specified properties of this term, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ Term.prototype.update = function (properties) { return this.invokeUpdate(properties, Term); }; return Term; }(spClientsvc.ClientSvcQueryable)); var TermSets = /** @class */ (function (_super) { tslib_1.__extends(TermSets, _super); function TermSets() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the termsets in this collection */ TermSets.prototype.get = function () { return this.sendGetCollection(TermSet); }; /** * Gets a TermSet from this collection by id * * @param id TermSet id */ TermSets.prototype.getById = function (id) { var params = spClientsvc.MethodParams.build() .string(common.sanitizeGuid(id)); return this.getChild(TermSet, "GetById", params); }; /** * Gets a TermSet from this collection by name * * @param name TermSet name */ TermSets.prototype.getByName = function (name) { var params = spClientsvc.MethodParams.build() .string(name); return this.getChild(TermSet, "GetByName", params); }; return TermSets; }(spClientsvc.ClientSvcQueryable)); var TermSet = /** @class */ (function (_super) { tslib_1.__extends(TermSet, _super); function TermSet() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(TermSet.prototype, "group", { /** * Gets the group containing this Term set */ get: function () { return this.getChildProperty(TermGroup, "Group"); }, enumerable: true, configurable: true }); Object.defineProperty(TermSet.prototype, "terms", { /** * Access all the terms in this termset */ get: function () { return this.getChild(Terms, "GetAllTerms", null); }, enumerable: true, configurable: true }); /** * Adds a stakeholder to the TermSet * * @param stakeholderName The login name of the user to be added as a stakeholder */ TermSet.prototype.addStakeholder = function (stakeholderName) { var params = spClientsvc.MethodParams.build() .string(stakeholderName); return this.invokeNonQuery("DeleteStakeholder", params); }; /** * Deletes a stakeholder to the TermSet * * @param stakeholderName The login name of the user to be added as a stakeholder */ TermSet.prototype.deleteStakeholder = function (stakeholderName) { var params = spClientsvc.MethodParams.build() .string(stakeholderName); return this.invokeNonQuery("AddStakeholder", params); }; /** * Gets the data for this TermSet */ TermSet.prototype.get = function () { return this.sendGet(TermSet); }; /** * Get a term by id * * @param id Term id */ TermSet.prototype.getTermById = function (id) { var params = spClientsvc.MethodParams.build() .string(common.sanitizeGuid(id)); return this.getChild(Term, "GetTerm", params); }; /** * Adds a term to this term set * * @param name Name for the term * @param lcid Language code * @param isAvailableForTagging set tagging availability (default: true) * @param id GUID id for the term (optional) */ TermSet.prototype.addTerm = function (name, lcid, isAvailableForTagging, id) { var _this = this; if (isAvailableForTagging === void 0) { isAvailableForTagging = true; } if (id === void 0) { id = common.getGUID(); } var params = spClientsvc.MethodParams.build() .string(name) .number(lcid) .string(common.sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateTerm", params, spClientsvc.setProperty("IsAvailableForTagging", "Boolean", "" + isAvailableForTagging)) .then(function (r) { return common.extend(_this.getTermById(r.Id), r); }); }; /** * Copies this term set immediately */ TermSet.prototype.copy = function () { return this.invokeMethod("Copy", null); }; /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ TermSet.prototype.update = function (properties) { return this.invokeUpdate(properties, TermSet); }; return TermSet; }(spClientsvc.ClientSvcQueryable)); /** * Represents a group in the taxonomy heirarchy */ var TermGroup = /** @class */ (function (_super) { tslib_1.__extends(TermGroup, _super); function TermGroup(parent, _objectPaths) { if (parent === void 0) { parent = ""; } var _this = _super.call(this, parent, _objectPaths) || this; // this should mostly be true _this.store = parent instanceof TermStore ? parent : null; return _this; } Object.defineProperty(TermGroup.prototype, "termSets", { /** * Gets the collection of term sets in this group */ get: function () { return this.getChildProperty(TermSets, "TermSets"); }, enumerable: true, configurable: true }); /** * Adds a contributor to the Group * * @param principalName The login name of the user to be added as a contributor */ TermGroup.prototype.addContributor = function (principalName) { var params = spClientsvc.MethodParams.build().string(principalName); return this.invokeNonQuery("AddContributor", params); }; /** * Adds a group manager to the Group * * @param principalName The login name of the user to be added as a group manager */ TermGroup.prototype.addGroupManager = function (principalName) { var params = spClientsvc.MethodParams.build().string(principalName); return this.invokeNonQuery("AddGroupManager", params); }; /** * Creates a new TermSet in this Group using the provided language and unique identifier * * @param name The name of the new TermSet being created * @param lcid The language that the new TermSet name is in * @param id The unique identifier of the new TermSet being created (optional) */ TermGroup.prototype.createTermSet = function (name, lcid, id) { var _this = this; if (id === void 0) { id = common.getGUID(); } var params = spClientsvc.MethodParams.build() .string(name) .string(common.sanitizeGuid(id)) .number(lcid); this._useCaching = false; return this.invokeMethod("CreateTermSet", params) .then(function (r) { return common.extend(_this.store.getTermSetById(r.Id), r); }); }; /** * Gets this term store's data */ TermGroup.prototype.get = function () { return this.sendGet(TermGroup); }; /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ TermGroup.prototype.update = function (properties) { return this.invokeUpdate(properties, TermGroup); }; return TermGroup; }(spClientsvc.ClientSvcQueryable)); /** * Represents the set of available term stores and the collection methods */ var TermStores = /** @class */ (function (_super) { tslib_1.__extends(TermStores, _super); function TermStores(parent) { if (parent === void 0) { parent = ""; } var _this = _super.call(this, parent) || this; _this._objectPaths.add(spClientsvc.property("TermStores", // actions spClientsvc.objectPath())); return _this; } /** * Gets the term stores */ TermStores.prototype.get = function () { return this.sendGetCollection(TermStore); }; /** * Returns the TermStore specified by its index name * * @param name The index name of the TermStore to be returned */ TermStores.prototype.getByName = function (name) { return this.getChild(TermStore, "GetByName", spClientsvc.MethodParams.build().string(name)); }; /** * Returns the TermStore specified by its GUID index * * @param id The GUID index of the TermStore to be returned */ TermStores.prototype.getById = function (id) { return this.getChild(TermStore, "GetById", spClientsvc.MethodParams.build().string(common.sanitizeGuid(id))); }; return TermStores; }(spClientsvc.ClientSvcQueryable)); var TermStore = /** @class */ (function (_super) { tslib_1.__extends(TermStore, _super); function TermStore(parent, _objectPaths) { if (parent === void 0) { parent = ""; } if (_objectPaths === void 0) { _objectPaths = null; } return _super.call(this, parent, _objectPaths) || this; } Object.defineProperty(TermStore.prototype, "hashTagsTermSet", { get: function () { return this.getChildProperty(TermSet, "HashTagsTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(TermStore.prototype, "keywordsTermSet", { get: function () { return this.getChildProperty(TermSet, "KeywordsTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(TermStore.prototype, "orphanedTermsTermSet", { get: function () { return this.getChildProperty(TermSet, "OrphanedTermsTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(TermStore.prototype, "systemGroup", { get: function () { return this.getChildProperty(TermGroup, "SystemGroup"); }, enumerable: true, configurable: true }); /** * Gets the term store data */ TermStore.prototype.get = function () { return this.sendGet(TermStore); }; /** * Gets term sets * * @param name * @param lcid */ TermStore.prototype.getTermSetsByName = function (name, lcid) { var params = spClientsvc.MethodParams.build() .string(name) .number(lcid); return this.getChild(TermSets, "GetTermSetsByName", params); }; /** * Provides access to an ITermSet by id * * @param id */ TermStore.prototype.getTermSetById = function (id) { var params = spClientsvc.MethodParams.build().string(common.sanitizeGuid(id)); return this.getChild(TermSet, "GetTermSet", params); }; /** * Provides access to an ITermSet by id * * @param id */ TermStore.prototype.getTermById = function (id) { var params = spClientsvc.MethodParams.build().string(common.sanitizeGuid(id)); return this.getChild(Term, "GetTerm", params); }; /** * Gets a term from a term set based on the supplied ids * * @param termId Term Id * @param termSetId Termset Id */ TermStore.prototype.getTermInTermSet = function (termId, termSetId) { var params = spClientsvc.MethodParams.build().string(common.sanitizeGuid(termId)).string(common.sanitizeGuid(termSetId)); return this.getChild(Term, "GetTermInTermSet", params); }; /** * This method provides access to a ITermGroup by id * * @param id The group id */ TermStore.prototype.getTermGroupById = function (id) { var params = spClientsvc.MethodParams.build() .string(common.sanitizeGuid(id)); return this.getChild(TermGroup, "GetGroup", params); }; /** * Gets the terms by the supplied information (see: https://msdn.microsoft.com/en-us/library/hh626704%28v=office.12%29.aspx) * * @param info */ TermStore.prototype.getTerms = function (info) { var objectPaths = this._objectPaths.clone(); // this will be the parent of the GetTerms call, but we need to create the input param first var parentIndex = objectPaths.lastIndex; // this is our input object var input = spClientsvc.objConstructor.apply(void 0, ["{61a1d689-2744-4ea3-a88b-c95bee9803aa}", // actions spClientsvc.objectPath()].concat(spClientsvc.objectProperties(info))); // add the input object path var inputIndex = objectPaths.add(input); // this sets up the GetTerms call var params = spClientsvc.MethodParams.build().objectPath(inputIndex); // call the method var methodIndex = objectPaths.add(spClientsvc.method("GetTerms", params, // actions spClientsvc.objectPath())); // setup the parent relationship even though they are seperated in the collection objectPaths.addChildRelationship(parentIndex, methodIndex); return new Terms(this, objectPaths); }; /** * Gets the site collection group associated with the current site * * @param createIfMissing If true the group will be created, otherwise null (default: false) */ TermStore.prototype.getSiteCollectionGroup = function (createIfMissing) { if (createIfMissing === void 0) { createIfMissing = false; } var objectPaths = this._objectPaths.clone(); var methodParent = objectPaths.lastIndex; var siteIndex = objectPaths.siteIndex; var params = spClientsvc.MethodParams.build().objectPath(siteIndex).boolean(createIfMissing); var methodIndex = objectPaths.add(spClientsvc.method("GetSiteCollectionGroup", params, // actions spClientsvc.objectPath())); // the parent of this method call is this instance, not the current/site objectPaths.addChildRelationship(methodParent, methodIndex); return new TermGroup(this, objectPaths); }; /** * Adds a working language to the TermStore * * @param lcid The locale identifier of the working language to add */ TermStore.prototype.addLanguage = function (lcid) { var params = spClientsvc.MethodParams.build().number(lcid); return this.invokeNonQuery("AddLanguage", params); }; /** * Creates a new Group in this TermStore * * @param name The name of the new Group being created * @param id The ID (Guid) that the new group should have */ TermStore.prototype.addGroup = function (name, id) { var _this = this; if (id === void 0) { id = common.getGUID(); } var params = spClientsvc.MethodParams.build() .string(name) .string(common.sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateGroup", params) .then(function (r) { return common.extend(_this.getTermGroupById(r.Id), r); }); }; /** * Commits all updates to the database that have occurred since the last commit or rollback */ TermStore.prototype.commitAll = function () { return this.invokeNonQuery("CommitAll"); }; /** * Delete a working language from the TermStore * * @param lcid locale ID for the language to be deleted */ TermStore.prototype.deleteLanguage = function (lcid) { var params = spClientsvc.MethodParams.build().number(lcid); return this.invokeNonQuery("DeleteLanguage", params); }; /** * Discards all updates that have occurred since the last commit or rollback */ TermStore.prototype.rollbackAll = function () { return this.invokeNonQuery("RollbackAll"); }; /** * Updates the cache */ TermStore.prototype.updateCache = function () { return this.invokeNonQuery("UpdateCache"); }; /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ TermStore.prototype.update = function (properties) { return this.invokeUpdate(properties, TermStore); }; /** * This method makes sure that this instance is aware of all child terms that are used in the current site collection */ TermStore.prototype.updateUsedTermsOnSite = function () { var objectPaths = this._objectPaths.clone(); var methodParent = objectPaths.lastIndex; var siteIndex = objectPaths.siteIndex; var params = spClientsvc.MethodParams.build().objectPath(siteIndex); var methodIndex = objectPaths.add(spClientsvc.method("UpdateUsedTermsOnSite", params)); // the parent of this method call is this instance, not the current context/site objectPaths.addChildRelationship(methodParent, methodIndex); return this.send(objectPaths); }; /** * Gets a list of changes * * @param info Lookup information */ TermStore.prototype.getChanges = function (info) { var objectPaths = this._objectPaths.clone(); var methodParent = objectPaths.lastIndex; var inputIndex = objectPaths.add(spClientsvc.objConstructor.apply(void 0, ["{1f849fb0-4fcb-4a54-9b01-9152b9e482d3}", // actions spClientsvc.objectPath()].concat(spClientsvc.objectProperties(info)))); var params = spClientsvc.MethodParams.build().objectPath(inputIndex); var methodIndex = objectPaths.add(spClientsvc.method("GetChanges", params, // actions spClientsvc.objectPath(), spClientsvc.opQuery([], this.getSelects()))); objectPaths.addChildRelationship(methodParent, methodIndex); return this.send(objectPaths); }; return TermStore; }(spClientsvc.ClientSvcQueryable)); /** * The root taxonomy object */ var Session = /** @class */ (function (_super) { tslib_1.__extends(Session, _super); function Session(webUrl) { if (webUrl === void 0) { webUrl = ""; } var _this = _super.call(this, webUrl) || this; // everything starts with the session _this._objectPaths.add(spClientsvc.staticMethod("GetTaxonomySession", "{981cbc68-9edc-4f8d-872f-71146fcbb84f}", // actions spClientsvc.objectPath())); return _this; } Object.defineProperty(Session.prototype, "termStores", { /** * The collection of term stores */ get: function () { return new TermStores(this); }, enumerable: true, configurable: true }); /** * Provides access to sp.setup from @pnp/sp * * @param config Configuration */ Session.prototype.setup = function (config) { sp.sp.setup(config); }; /** * Creates a new batch */ Session.prototype.createBatch = function () { return new spClientsvc.ObjectPathBatch(this.toUrl()); }; /** * Gets the default keyword termstore for this session */ Session.prototype.getDefaultKeywordTermStore = function () { return this.getChild(TermStore, "GetDefaultKeywordsTermStore", null); }; /** * Gets the default site collection termstore for this session */ Session.prototype.getDefaultSiteCollectionTermStore = function () { return this.getChild(TermStore, "GetDefaultSiteCollectionTermStore", null); }; return Session; }(spClientsvc.ClientSvcQueryable)); (function (StringMatchOption) { StringMatchOption[StringMatchOption["StartsWith"] = 0] = "StartsWith"; StringMatchOption[StringMatchOption["ExactMatch"] = 1] = "ExactMatch"; })(exports.StringMatchOption || (exports.StringMatchOption = {})); (function (ChangedItemType) { ChangedItemType[ChangedItemType["Unknown"] = 0] = "Unknown"; ChangedItemType[ChangedItemType["Term"] = 1] = "Term"; ChangedItemType[ChangedItemType["TermSet"] = 2] = "TermSet"; ChangedItemType[ChangedItemType["Group"] = 3] = "Group"; ChangedItemType[ChangedItemType["TermStore"] = 4] = "TermStore"; ChangedItemType[ChangedItemType["Site"] = 5] = "Site"; })(exports.ChangedItemType || (exports.ChangedItemType = {})); (function (ChangedOperationType) { ChangedOperationType[ChangedOperationType["Unknown"] = 0] = "Unknown"; ChangedOperationType[ChangedOperationType["Add"] = 1] = "Add"; ChangedOperationType[ChangedOperationType["Edit"] = 2] = "Edit"; ChangedOperationType[ChangedOperationType["DeleteObject"] = 3] = "DeleteObject"; ChangedOperationType[ChangedOperationType["Move"] = 4] = "Move"; ChangedOperationType[ChangedOperationType["Copy"] = 5] = "Copy"; ChangedOperationType[ChangedOperationType["PathChange"] = 6] = "PathChange"; ChangedOperationType[ChangedOperationType["Merge"] = 7] = "Merge"; ChangedOperationType[ChangedOperationType["ImportObject"] = 8] = "ImportObject"; ChangedOperationType[ChangedOperationType["Restore"] = 9] = "Restore"; })(exports.ChangedOperationType || (exports.ChangedOperationType = {})); // export an existing session instance var taxonomy = new Session(); exports.taxonomy = taxonomy; exports.Labels = Labels; exports.Label = Label; exports.Session = Session; exports.TermGroup = TermGroup; exports.Terms = Terms; exports.Term = Term; exports.TermSets = TermSets; exports.TermSet = TermSet; exports.TermStores = TermStores; exports.TermStore = TermStore; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=sp-taxonomy.es5.umd.js.map
"use strict"; var platform_browser_dynamic_1 = require("@angular/platform-browser-dynamic"); var app_module_1 = require("./app.module"); platform_browser_dynamic_1.platformBrowserDynamic().bootstrapModule(app_module_1.AppModule); //# sourceMappingURL=main.js.map
import { get } from 'ember-metal/property_get'; import { set } from 'ember-metal/property_set'; import run from 'ember-metal/run_loop'; import { computed } from 'ember-metal/computed'; import Controller from 'ember-runtime/controllers/controller'; import jQuery from 'ember-views/system/jquery'; import View from 'ember-views/views/view'; import ContainerView, { DeprecatedContainerView } from 'ember-views/views/container_view'; import Registry from 'container/registry'; import compile from 'ember-template-compiler/system/compile'; import getElementStyle from 'ember-views/tests/test-helpers/get-element-style'; import { registerKeyword, resetKeyword } from 'ember-htmlbars/tests/utils'; import viewKeyword from 'ember-htmlbars/keywords/view'; var trim = jQuery.trim; var container, registry, view, otherContainer, originalViewKeyword; QUnit.module('ember-views/views/container_view_test', { setup() { originalViewKeyword = registerKeyword('view', viewKeyword); registry = new Registry(); }, teardown() { run(function() { if (container) { container.destroy(); } if (view) { view.destroy(); } if (otherContainer) { otherContainer.destroy(); } }); resetKeyword('view', originalViewKeyword); } }); QUnit.test('should be able to insert views after the DOM representation is created', function() { container = ContainerView.create({ classNameBindings: ['name'], name: 'foo', container: registry.container() }); run(function() { container.appendTo('#qunit-fixture'); }); view = View.create({ template: compile('This is my moment') }); run(function() { container.pushObject(view); }); equal(view.container, container.container, 'view gains its containerViews container'); equal(view.parentView, container, 'view\'s parentView is the container'); equal(trim(container.$().text()), 'This is my moment'); run(function() { container.destroy(); }); }); QUnit.test('should be able to observe properties that contain child views', function() { expectDeprecation('Setting `childViews` on a Container is deprecated.'); run(function() { var Container = ContainerView.extend({ childViews: ['displayView'], displayIsDisplayed: computed.alias('displayView.isDisplayed'), displayView: View.extend({ isDisplayed: true }) }); container = Container.create(); container.appendTo('#qunit-fixture'); }); equal(container.get('displayIsDisplayed'), true, 'can bind to child view'); run(function () { container.set('displayView.isDisplayed', false); }); equal(container.get('displayIsDisplayed'), false, 'can bind to child view'); }); QUnit.test('childViews inherit their parents iocContainer, and retain the original container even when moved', function() { var iocContainer = registry.container(); container = ContainerView.create({ container: iocContainer }); otherContainer = ContainerView.create({ container: iocContainer }); view = View.create(); container.pushObject(view); strictEqual(view.get('parentView'), container, 'sets the parent view after the childView is appended'); strictEqual(get(view, 'container'), container.container, 'inherits its parentViews iocContainer'); container.removeObject(view); strictEqual(get(view, 'container'), container.container, 'leaves existing iocContainer alone'); otherContainer.pushObject(view); strictEqual(view.get('parentView'), otherContainer, 'sets the new parent view after the childView is appended'); strictEqual(get(view, 'container'), container.container, 'still inherits its original parentViews iocContainer'); }); QUnit.test('should set the parentView property on views that are added to the child views array', function() { container = ContainerView.create(); var ViewKlass = View.extend({ template: compile('This is my moment') }); view = ViewKlass.create(); container.pushObject(view); equal(view.get('parentView'), container, 'sets the parent view after the childView is appended'); run(function() { container.removeObject(view); }); equal(get(view, 'parentView'), null, 'sets parentView to null when a view is removed'); run(function() { container.appendTo('#qunit-fixture'); }); run(function() { container.pushObject(view); }); equal(get(view, 'parentView'), container, 'sets the parent view after the childView is appended'); var secondView = ViewKlass.create(); var thirdView = ViewKlass.create(); var fourthView = ViewKlass.create(); run(function() { container.pushObject(secondView); container.replace(1, 0, [thirdView, fourthView]); }); equal(get(secondView, 'parentView'), container, 'sets the parent view of the second view'); equal(get(thirdView, 'parentView'), container, 'sets the parent view of the third view'); equal(get(fourthView, 'parentView'), container, 'sets the parent view of the fourth view'); run(function() { container.replace(2, 2); }); equal(get(view, 'parentView'), container, 'doesn\'t change non-removed view'); equal(get(thirdView, 'parentView'), container, 'doesn\'t change non-removed view'); equal(get(secondView, 'parentView'), null, 'clears the parent view of the third view'); equal(get(fourthView, 'parentView'), null, 'clears the parent view of the fourth view'); run(function() { secondView.destroy(); thirdView.destroy(); fourthView.destroy(); }); }); QUnit.test('should trigger parentViewDidChange when parentView is changed', function() { container = ContainerView.create(); var secondContainer = ContainerView.create(); var parentViewChanged = 0; var ViewKlass = View.extend({ parentViewDidChange() { parentViewChanged++; } }); view = ViewKlass.create(); container.pushObject(view); container.removeChild(view); secondContainer.pushObject(view); equal(parentViewChanged, 3); run(function() { secondContainer.destroy(); }); }); QUnit.test('should be able to push initial views onto the ContainerView and have it behave', function() { var Container = ContainerView.extend({ init() { this._super.apply(this, arguments); this.pushObject(View.create({ name: 'A', template: compile('A') })); this.pushObject(View.create({ name: 'B', template: compile('B') })); }, // functions here avoid attaching an observer, which is // not supported. lengthSquared() { return this.get('length') * this.get('length'); }, mapViewNames() { return this.map(function(_view) { return _view.get('name'); }); } }); container = Container.create(); equal(container.lengthSquared(), 4); deepEqual(container.mapViewNames(), ['A', 'B']); run(container, 'appendTo', '#qunit-fixture'); equal(container.$().text(), 'AB'); run(function () { container.pushObject(View.create({ name: 'C', template: compile('C') })); }); equal(container.lengthSquared(), 9); deepEqual(container.mapViewNames(), ['A', 'B', 'C']); equal(container.$().text(), 'ABC'); run(container, 'destroy'); }); QUnit.test('views that are removed from a ContainerView should have their child views cleared', function() { container = ContainerView.create(); var ChildView = View.extend({ MyView: View, template: compile('{{view MyView}}') }); var view = ChildView.create(); container.pushObject(view); run(function() { container.appendTo('#qunit-fixture'); }); equal(get(view, 'childViews.length'), 1, 'precond - renders one child view'); run(function() { container.removeObject(view); }); strictEqual(container.$('div').length, 0, 'the child view is removed from the DOM'); }); QUnit.test('if a ContainerView starts with an empty currentView, nothing is displayed', function() { container = ContainerView.create(); run(function() { container.appendTo('#qunit-fixture'); }); equal(container.$().text(), '', 'has a empty contents'); equal(get(container, 'childViews.length'), 0, 'should not have any child views'); }); QUnit.test('if a ContainerView starts with a currentView, it is rendered as a child view', function() { var controller = Controller.create(); container = ContainerView.create({ controller: controller }); var mainView = View.create({ template: compile('This is the main view.') }); set(container, 'currentView', mainView); run(function() { container.appendTo('#qunit-fixture'); }); equal(trim(container.$().text()), 'This is the main view.', 'should render its child'); equal(get(container, 'length'), 1, 'should have one child view'); equal(container.objectAt(0), mainView, 'should have the currentView as the only child view'); equal(mainView.get('parentView'), container, 'parentView is setup'); }); QUnit.test('if a ContainerView is created with a currentView, it is rendered as a child view', function() { var mainView = View.create({ template: compile('This is the main view.') }); var controller = Controller.create(); container = ContainerView.create({ currentView: mainView, controller: controller }); run(function() { container.appendTo('#qunit-fixture'); }); equal(container.$().text(), 'This is the main view.', 'should render its child'); equal(get(container, 'length'), 1, 'should have one child view'); equal(container.objectAt(0), mainView, 'should have the currentView as the only child view'); equal(mainView.get('parentView'), container, 'parentView is setup'); }); QUnit.test('if a ContainerView starts with no currentView and then one is set, the ContainerView is updated', function() { var mainView = View.create({ template: compile('This is the {{name}} view.') }); var controller = Controller.create({ name: 'main' }); container = ContainerView.create({ controller: controller }); run(function() { container.appendTo('#qunit-fixture'); }); equal(container.$().text(), '', 'has a empty contents'); equal(get(container, 'childViews.length'), 0, 'should not have any child views'); run(function() { set(container, 'currentView', mainView); }); equal(container.$().text(), 'This is the main view.', 'should render its child'); equal(get(container, 'length'), 1, 'should have one child view'); equal(container.objectAt(0), mainView, 'should have the currentView as the only child view'); equal(mainView.get('parentView'), container, 'parentView is setup'); }); QUnit.test('if a ContainerView starts with a currentView and then is set to null, the ContainerView is updated', function() { var mainView = View.create({ template: compile('This is the main view.') }); var controller = Controller.create(); container = ContainerView.create({ controller: controller }); container.set('currentView', mainView); run(function() { container.appendTo('#qunit-fixture'); }); equal(container.$().text(), 'This is the main view.', 'should render its child'); equal(get(container, 'length'), 1, 'should have one child view'); equal(container.objectAt(0), mainView, 'should have the currentView as the only child view'); equal(mainView.get('parentView'), container, 'parentView is setup'); run(function() { set(container, 'currentView', null); }); equal(container.$().text(), '', 'has a empty contents'); equal(get(container, 'childViews.length'), 0, 'should not have any child views'); }); QUnit.test('if a ContainerView starts with a currentView and then is set to null, the ContainerView is updated and the previous currentView is destroyed', function() { var mainView = View.create({ template: compile('This is the main view.') }); var controller = Controller.create(); container = ContainerView.create({ controller: controller }); container.set('currentView', mainView); run(function() { container.appendTo('#qunit-fixture'); }); equal(container.$().text(), 'This is the main view.', 'should render its child'); equal(get(container, 'length'), 1, 'should have one child view'); equal(container.objectAt(0), mainView, 'should have the currentView as the only child view'); equal(mainView.get('parentView'), container, 'parentView is setup'); run(function() { set(container, 'currentView', null); }); equal(mainView.isDestroyed, true, 'should destroy the previous currentView.'); equal(container.$().text(), '', 'has a empty contents'); equal(get(container, 'childViews.length'), 0, 'should not have any child views'); }); QUnit.test('if a ContainerView starts with a currentView and then a different currentView is set, the old view is destroyed and the new one is added', function() { container = ContainerView.create(); var mainView = View.create({ template: compile('This is the main view.') }); var secondaryView = View.create({ template: compile('This is the secondary view.') }); var tertiaryView = View.create({ template: compile('This is the tertiary view.') }); container.set('currentView', mainView); run(function() { container.appendTo('#qunit-fixture'); }); equal(container.$().text(), 'This is the main view.', 'should render its child'); equal(get(container, 'length'), 1, 'should have one child view'); equal(container.objectAt(0), mainView, 'should have the currentView as the only child view'); run(function() { set(container, 'currentView', secondaryView); }); equal(get(container, 'length'), 1, 'should have one child view'); equal(container.objectAt(0), secondaryView, 'should have the currentView as the only child view'); equal(mainView.isDestroyed, true, 'should destroy the previous currentView: mainView.'); equal(trim(container.$().text()), 'This is the secondary view.', 'should render its child'); run(function() { set(container, 'currentView', tertiaryView); }); equal(get(container, 'length'), 1, 'should have one child view'); equal(container.objectAt(0), tertiaryView, 'should have the currentView as the only child view'); equal(secondaryView.isDestroyed, true, 'should destroy the previous currentView: secondaryView.'); equal(trim(container.$().text()), 'This is the tertiary view.', 'should render its child'); }); QUnit.test('should be able to modify childViews many times during an run loop', function () { container = ContainerView.create(); run(function() { container.appendTo('#qunit-fixture'); }); var one = View.create({ template: compile('one') }); var two = View.create({ template: compile('two') }); var three = View.create({ template: compile('three') }); run(function() { // initial order container.pushObjects([three, one, two]); // sort container.removeObject(three); container.pushObject(three); }); // Remove whitespace added by IE 8 equal(trim(container.$().text()), 'onetwothree'); }); QUnit.test('should be able to modify childViews then rerender the ContainerView in same run loop', function () { container = ContainerView.create(); run(function() { container.appendTo('#qunit-fixture'); }); var child = View.create({ template: compile('child') }); run(function() { container.pushObject(child); container.rerender(); }); equal(trim(container.$().text()), 'child'); }); QUnit.test('should be able to modify childViews then rerender then modify again the ContainerView in same run loop', function () { container = ContainerView.create(); run(function() { container.appendTo('#qunit-fixture'); }); var Child = View.extend({ count: 0, _willRender() { this.count++; }, template: compile('{{view.label}}') }); var one = Child.create({ label: 'one' }); var two = Child.create({ label: 'two' }); run(function() { container.pushObject(one); container.pushObject(two); }); equal(one.count, 1, 'rendered one.count child only once'); equal(two.count, 1, 'rendered two.count child only once'); // Remove whitespace added by IE 8 equal(trim(container.$().text()), 'onetwo'); }); QUnit.test('should be able to modify childViews then rerender again the ContainerView in same run loop and then modify again', function () { container = ContainerView.create(); run(function() { container.appendTo('#qunit-fixture'); }); var Child = View.extend({ count: 0, _willRender() { this.count++; }, template: compile('{{view.label}}') }); var one = Child.create({ label: 'one' }); var two = Child.create({ label: 'two' }); run(function() { container.pushObject(one); container.rerender(); }); equal(one.count, 1, 'rendered one child only once'); equal(container.$().text(), 'one'); run(function () { container.pushObject(two); }); equal(one.count, 1, 'rendered one child only once'); equal(two.count, 1, 'rendered two child only once'); // IE 8 adds a line break but this shouldn't affect validity equal(trim(container.$().text()), 'onetwo'); }); QUnit.test('should invalidate `element` on itself and childViews when being rendered by ensureChildrenAreInDOM', function () { expectDeprecation('Setting `childViews` on a Container is deprecated.'); var root = ContainerView.create(); view = View.create({ template: compile('child view') }); container = ContainerView.create({ childViews: ['child'], child: view }); run(function() { root.appendTo('#qunit-fixture'); }); run(function() { root.pushObject(container); // Get the parent and child's elements to cause them to be cached as null container.get('element'); view.get('element'); }); ok(!!container.get('element'), 'Parent\'s element should have been recomputed after being rendered'); ok(!!view.get('element'), 'Child\'s element should have been recomputed after being rendered'); run(function() { root.destroy(); }); }); QUnit.test('Child view can only be added to one container at a time', function () { expect(2); container = ContainerView.create(); var secondContainer = ContainerView.create(); run(function() { container.appendTo('#qunit-fixture'); }); var view = View.create(); run(function() { container.set('currentView', view); }); expectAssertion(function() { run(function() { secondContainer.set('currentView', view); }); }); expectAssertion(function() { run(function() { secondContainer.pushObject(view); }); }); run(function() { secondContainer.destroy(); }); }); QUnit.test('if a containerView appends a child in its didInsertElement event, the didInsertElement event of the child view should be fired once', function (assert) { var counter = 0; var root = ContainerView.create({}); container = ContainerView.create({ didInsertElement() { var view = ContainerView.create({ didInsertElement() { counter++; } }); this.pushObject(view); } }); run(function() { root.appendTo('#qunit-fixture'); }); expectDeprecation(function() { run(function() { root.pushObject(container); }); }, /was modified inside the didInsertElement hook/); assert.strictEqual(counter, 1, 'child didInsertElement was invoked'); run(function() { root.destroy(); }); }); QUnit.test('ContainerView is observable [DEPRECATED]', function() { container = ContainerView.create(); var observerFired = false; expectDeprecation(function() { container.addObserver('this.[]', function() { observerFired = true; }); }, /ContainerViews should not be observed as arrays. This behavior will change in future implementations of ContainerView./); ok(!observerFired, 'Nothing changed, no observer fired'); container.pushObject(View.create()); ok(observerFired, 'View pushed, observer fired'); }); QUnit.test('ContainerView supports bound attributes', function() { container = ContainerView.create({ attributeBindings: ['width'], width: '100px' }); run(function() { container.appendTo('#qunit-fixture'); }); equal(container.$().attr('width'), '100px', 'width is applied to the element'); run(function() { container.set('width', '200px'); }); equal(container.$().attr('width'), '200px', 'width is applied to the element'); }); QUnit.test('ContainerView supports bound style attribute', function() { container = ContainerView.create({ attributeBindings: ['style'], style: 'width: 100px;' }); run(function() { container.appendTo('#qunit-fixture'); }); equal(getElementStyle(container.element), 'WIDTH: 100PX;', 'width is applied to the element'); run(function() { container.set('style', 'width: 200px;'); }); equal(getElementStyle(container.element), 'WIDTH: 200PX;', 'width is applied to the element'); }); QUnit.test('ContainerView supports changing children with style attribute', function() { container = ContainerView.create({ attributeBindings: ['style'], style: 'width: 100px;' }); run(function() { container.appendTo('#qunit-fixture'); }); equal(getElementStyle(container.element), 'WIDTH: 100PX;', 'width is applied to the element'); view = View.create(); run(function() { container.pushObject(view); }); }); QUnit.test('should render child views with a different tagName', function() { expectDeprecation('Setting `childViews` on a Container is deprecated.'); container = ContainerView.create({ childViews: ['child'], child: View.create({ tagName: 'aside' }) }); run(function() { container.createElement(); }); equal(container.$('aside').length, 1); }); QUnit.test('should allow hX tags as tagName', function() { expectDeprecation('Setting `childViews` on a Container is deprecated.'); container = ContainerView.create({ childViews: ['child'], child: View.create({ tagName: 'h3' }) }); run(function() { container.createElement(); }); ok(container.$('h3').length, 'does not render the h3 tag correctly'); }); QUnit.test('renders contained view with omitted start tag and parent view context', function() { expectDeprecation('Setting `childViews` on a Container is deprecated.'); view = ContainerView.extend({ tagName: 'table', childViews: ['row'], row: View.create({ tagName: 'tr' }) }).create(); run(view, view.append); equal(view.element.tagName, 'TABLE', 'container view is table'); equal(view.element.childNodes[2].tagName, 'TR', 'inner view is tr'); run(view, view.rerender); equal(view.element.tagName, 'TABLE', 'container view is table'); equal(view.element.childNodes[2].tagName, 'TR', 'inner view is tr'); }); QUnit.module('DeprecatedContainerView'); QUnit.test('calling reopen on DeprecatedContainerView delegates to ContainerView', function() { expect(2); var originalReopen = ContainerView.reopen; var obj = {}; ContainerView.reopen = function(arg) { ok(arg === obj); }; expectDeprecation(() => { DeprecatedContainerView.reopen(obj); }, /Ember.ContainerView is deprecated./); ContainerView.reopen = originalReopen; });
// vim:ts=4:sts=4:sw=4: /*! * * Copyright 2009-2012 Kris Kowal under the terms of the MIT * license found at http://github.com/kriskowal/q/raw/master/LICENSE * * With parts by Tyler Close * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found * at http://www.opensource.org/licenses/mit-license.html * Forked at ref_send.js version: 2009-05-11 * * With parts by Mark Miller * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ (function (definition) { // Turn off strict mode for this function so we can assign to global.Q /* jshint strict: false */ // This file will function properly as a <script> tag, or a module // using CommonJS and NodeJS or RequireJS module formats. In // Common/Node/RequireJS, the module exports the Q API and when // executed as a simple <script>, it creates a Q global instead. // Montage Require if (typeof bootstrap === "function") { bootstrap("promise", definition); // CommonJS } else if (typeof exports === "object") { module.exports = definition(); // RequireJS } else if (typeof define === "function" && define.amd) { define(definition); // SES (Secure EcmaScript) } else if (typeof ses !== "undefined") { if (!ses.ok()) { return; } else { ses.makeQ = definition; } // <script> } else { Q = definition(); } })(function () { "use strict"; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported // by Q. var qStartingLine = captureLine(); var qFileName; // shims // used for fallback in "allResolved" var noop = function () {}; // Use the fastest possible means to execute a task in a future turn // of the event loop. var nextTick =(function () { // linked list of tasks (single, with head node) var head = {task: void 0, next: null}; var tail = head; var flushing = false; var requestTick = void 0; var isNodeJS = false; function flush() { /* jshint loopfunc: true */ while (head.next) { head = head.next; var task = head.task; head.task = void 0; var domain = head.domain; if (domain) { head.domain = void 0; domain.enter(); } try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function() { throw e; }, 0); } } if (domain) { domain.exit(); } } flushing = false; } nextTick = function (task) { tail = tail.next = { task: task, domain: isNodeJS && process.domain, next: null }; if (!flushing) { flushing = true; requestTick(); } }; if (typeof process !== "undefined" && process.nextTick) { // Node.js before 0.9. Note that some fake-Node environments, like the // Mocha test runner, introduce a `process` global without a `nextTick`. isNodeJS = true; requestTick = function () { process.nextTick(flush); }; } else if (typeof setImmediate === "function") { // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate if (typeof window !== "undefined") { requestTick = setImmediate.bind(window, flush); } else { requestTick = function () { setImmediate(flush); }; } } else if (typeof MessageChannel !== "undefined") { // modern browsers // http://www.nonblocking.io/2011/06/windownexttick.html var channel = new MessageChannel(); // At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create // working message ports the first time a page loads. channel.port1.onmessage = function () { requestTick = requestPortTick; channel.port1.onmessage = flush; flush(); }; var requestPortTick = function () { // Opera requires us to provide a message payload, regardless of // whether we use it. channel.port2.postMessage(0); }; requestTick = function () { setTimeout(flush, 0); requestPortTick(); }; } else { // old browsers requestTick = function () { setTimeout(flush, 0); }; } return nextTick; })(); // Attempt to make generics safe in the face of downstream // modifications. // There is no situation where this is necessary. // If you need a security guarantee, these primordials need to be // deeply frozen anyway, and if you don’t need a security guarantee, // this is just plain paranoid. // However, this **might** have the nice side-effect of reducing the size of // the minified code by reducing x.call() to merely x() // See Mark Miller’s explanation of what this does. // http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming var call = Function.call; function uncurryThis(f) { return function () { return call.apply(f, arguments); }; } // This is equivalent, but slower: // uncurryThis = Function_bind.bind(Function_bind.call); // http://jsperf.com/uncurrythis var array_slice = uncurryThis(Array.prototype.slice); var array_reduce = uncurryThis( Array.prototype.reduce || function (callback, basis) { var index = 0, length = this.length; // concerning the initial value, if one is not provided if (arguments.length === 1) { // seek to the first value in the array, accounting // for the possibility that is is a sparse array do { if (index in this) { basis = this[index++]; break; } if (++index >= length) { throw new TypeError(); } } while (1); } // reduce for (; index < length; index++) { // account for the possibility that the array is sparse if (index in this) { basis = callback(basis, this[index], index); } } return basis; } ); var array_indexOf = uncurryThis( Array.prototype.indexOf || function (value) { // not a very good shim, but good enough for our one use of it for (var i = 0; i < this.length; i++) { if (this[i] === value) { return i; } } return -1; } ); var array_map = uncurryThis( Array.prototype.map || function (callback, thisp) { var self = this; var collect = []; array_reduce(self, function (undefined, value, index) { collect.push(callback.call(thisp, value, index, self)); }, void 0); return collect; } ); var object_create = Object.create || function (prototype) { function Type() { } Type.prototype = prototype; return new Type(); }; var object_hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); var object_keys = Object.keys || function (object) { var keys = []; for (var key in object) { if (object_hasOwnProperty(object, key)) { keys.push(key); } } return keys; }; var object_toString = uncurryThis(Object.prototype.toString); function isObject(value) { return value === Object(value); } // generator related shims // FIXME: Remove this function once ES6 generators are in SpiderMonkey. function isStopIteration(exception) { return ( object_toString(exception) === "[object StopIteration]" || exception instanceof QReturnValue ); } // FIXME: Remove this helper and Q.return once ES6 generators are in // SpiderMonkey. var QReturnValue; if (typeof ReturnValue !== "undefined") { QReturnValue = ReturnValue; } else { QReturnValue = function (value) { this.value = value; }; } // long stack traces var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, promise) { // If possible, transform the error stack trace by removing Node and Q // cruft, then concatenating with the stack trace of `promise`. See #57. if (hasStacks && promise.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var p = promise; !!p; p = p.source) { if (p.stack) { stacks.unshift(p.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"); var desiredLines = []; for (var i = 0; i < lines.length; ++i) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" // In IE10 function name can have spaces ("Anonymous function") O_o var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0]; var lineNumber = fileNameAndLineNumber[1]; return fileName === qFileName && lineNumber >= qStartingLine && lineNumber <= qEndingLine; } // discover own file name and line number range for filtering stack // traces function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } qFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function deprecate(callback, name, alternative) { return function () { if (typeof console !== "undefined" && typeof console.warn === "function") { console.warn(name + " is deprecated, use " + alternative + " instead.", new Error("").stack); } return callback.apply(callback, arguments); }; } // end of shims // beginning of real work /** * Constructs a promise for an immediate reference, passes promises through, or * coerces promises from different systems. * @param value immediate reference or promise */ function Q(value) { // If the object is already a Promise, return it directly. This enables // the resolve function to both be used to created references from objects, // but to tolerably coerce non-promises to promises. if (isPromise(value)) { return value; } // assimilate thenables if (isPromiseAlike(value)) { return coerce(value); } else { return fulfill(value); } } Q.resolve = Q; /** * Performs a task in a future turn of the event loop. * @param {Function} task */ Q.nextTick = nextTick; /** * Controls whether or not long stack traces will be on */ Q.longStackSupport = false; /** * Constructs a {promise, resolve, reject} object. * * `resolve` is a callback to invoke with a more resolved value for the * promise. To fulfill the promise, invoke `resolve` with any value that is * not a thenable. To reject the promise, invoke `resolve` with a rejected * thenable, or invoke `reject` with the reason directly. To resolve the * promise to another thenable, thus putting it in the same state, invoke * `resolve` with that other thenable. */ Q.defer = defer; function defer() { // if "messages" is an "Array", that indicates that the promise has not yet // been resolved. If it is "undefined", it has been resolved. Each // element of the messages array is itself an array of complete arguments to // forward to the resolved promise. We coerce the resolution value to a // promise using the `resolve` function because it handles both fully // non-thenable values and other thenables gracefully. var messages = [], progressListeners = [], resolvedPromise; var deferred = object_create(defer.prototype); var promise = object_create(Promise.prototype); promise.promiseDispatch = function (resolve, op, operands) { var args = array_slice(arguments); if (messages) { messages.push(args); if (op === "when" && operands[1]) { // progress operand progressListeners.push(operands[1]); } } else { nextTick(function () { resolvedPromise.promiseDispatch.apply(resolvedPromise, args); }); } }; // XXX deprecated promise.valueOf = function () { if (messages) { return promise; } var nearerValue = nearer(resolvedPromise); if (isPromise(nearerValue)) { resolvedPromise = nearerValue; // shorten chain } return nearerValue; }; promise.inspect = function () { if (!resolvedPromise) { return { state: "pending" }; } return resolvedPromise.inspect(); }; if (Q.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { // NOTE: don't try to use `Error.captureStackTrace` or transfer the // accessor around; that causes memory leaks as per GH-111. Just // reify the stack trace as a string ASAP. // // At the same time, cut off the first line; it's always just // "[object Promise]\n", as per the `toString`. promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } } // NOTE: we do the checks for `resolvedPromise` in each method, instead of // consolidating them into `become`, since otherwise we'd create new // promises with the lines `become(whatever(value))`. See e.g. GH-252. function become(newPromise) { resolvedPromise = newPromise; promise.source = newPromise; array_reduce(messages, function (undefined, message) { nextTick(function () { newPromise.promiseDispatch.apply(newPromise, message); }); }, void 0); messages = void 0; progressListeners = void 0; } deferred.promise = promise; deferred.resolve = function (value) { if (resolvedPromise) { return; } become(Q(value)); }; deferred.fulfill = function (value) { if (resolvedPromise) { return; } become(fulfill(value)); }; deferred.reject = function (reason) { if (resolvedPromise) { return; } become(reject(reason)); }; deferred.notify = function (progress) { if (resolvedPromise) { return; } array_reduce(progressListeners, function (undefined, progressListener) { nextTick(function () { progressListener(progress); }); }, void 0); }; return deferred; } /** * Creates a Node-style callback that will resolve or reject the deferred * promise. * @returns a nodeback */ defer.prototype.makeNodeResolver = function () { var self = this; return function (error, value) { if (error) { self.reject(error); } else if (arguments.length > 2) { self.resolve(array_slice(arguments, 1)); } else { self.resolve(value); } }; }; /** * @param resolver {Function} a function that returns nothing and accepts * the resolve, reject, and notify functions for a deferred. * @returns a promise that may be resolved with the given resolve and reject * functions, or rejected by a thrown exception in resolver */ Q.promise = promise; function promise(resolver) { if (typeof resolver !== "function") { throw new TypeError("resolver must be a function."); } var deferred = defer(); try { resolver(deferred.resolve, deferred.reject, deferred.notify); } catch (reason) { deferred.reject(reason); } return deferred.promise; } // XXX experimental. This method is a way to denote that a local value is // serializable and should be immediately dispatched to a remote upon request, // instead of passing a reference. Q.passByCopy = function (object) { //freeze(object); //passByCopies.set(object, true); return object; }; Promise.prototype.passByCopy = function () { //freeze(object); //passByCopies.set(object, true); return this; }; /** * If two promises eventually fulfill to the same value, promises that value, * but otherwise rejects. * @param x {Any*} * @param y {Any*} * @returns {Any*} a promise for x and y if they are the same, but a rejection * otherwise. * */ Q.join = function (x, y) { return Q(x).join(y); }; Promise.prototype.join = function (that) { return Q([this, that]).spread(function (x, y) { if (x === y) { // TODO: "===" should be Object.is or equiv return x; } else { throw new Error("Can't join: not the same: " + x + " " + y); } }); }; /** * Returns a promise for the first of an array of promises to become fulfilled. * @param answers {Array[Any*]} promises to race * @returns {Any*} the first promise to be fulfilled */ Q.race = race; function race(answerPs) { return promise(function(resolve, reject) { // Switch to this once we can assume at least ES5 // answerPs.forEach(function(answerP) { // Q(answerP).then(resolve, reject); // }); // Use this in the meantime for (var i = 0, len = answerPs.length; i < len; i++) { Q(answerPs[i]).then(resolve, reject); } }); } Promise.prototype.race = function () { return this.then(Q.race); }; /** * Constructs a Promise with a promise descriptor object and optional fallback * function. The descriptor contains methods like when(rejected), get(name), * set(name, value), post(name, args), and delete(name), which all * return either a value, a promise for a value, or a rejection. The fallback * accepts the operation name, a resolver, and any further arguments that would * have been forwarded to the appropriate method above had a method been * provided with the proper name. The API makes no guarantees about the nature * of the returned object, apart from that it is usable whereever promises are * bought and sold. */ Q.makePromise = Promise; function Promise(descriptor, fallback, inspect) { if (fallback === void 0) { fallback = function (op) { return reject(new Error( "Promise does not support operation: " + op )); }; } if (inspect === void 0) { inspect = function () { return {state: "unknown"}; }; } var promise = object_create(Promise.prototype); promise.promiseDispatch = function (resolve, op, args) { var result; try { if (descriptor[op]) { result = descriptor[op].apply(promise, args); } else { result = fallback.call(promise, op, args); } } catch (exception) { result = reject(exception); } if (resolve) { resolve(result); } }; promise.inspect = inspect; // XXX deprecated `valueOf` and `exception` support if (inspect) { var inspected = inspect(); if (inspected.state === "rejected") { promise.exception = inspected.reason; } promise.valueOf = function () { var inspected = inspect(); if (inspected.state === "pending" || inspected.state === "rejected") { return promise; } return inspected.value; }; } return promise; } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.then = function (fulfilled, rejected, progressed) { var self = this; var deferred = defer(); var done = false; // ensure the untrusted promise makes at most a // single call to one of the callbacks function _fulfilled(value) { try { return typeof fulfilled === "function" ? fulfilled(value) : value; } catch (exception) { return reject(exception); } } function _rejected(exception) { if (typeof rejected === "function") { makeStackTraceLong(exception, self); try { return rejected(exception); } catch (newException) { return reject(newException); } } return reject(exception); } function _progressed(value) { return typeof progressed === "function" ? progressed(value) : value; } nextTick(function () { self.promiseDispatch(function (value) { if (done) { return; } done = true; deferred.resolve(_fulfilled(value)); }, "when", [function (exception) { if (done) { return; } done = true; deferred.resolve(_rejected(exception)); }]); }); // Progress propagator need to be attached in the current tick. self.promiseDispatch(void 0, "when", [void 0, function (value) { var newValue; var threw = false; try { newValue = _progressed(value); } catch (e) { threw = true; if (Q.onerror) { Q.onerror(e); } else { throw e; } } if (!threw) { deferred.notify(newValue); } }]); return deferred.promise; }; /** * Registers an observer on a promise. * * Guarantees: * * 1. that fulfilled and rejected will be called only once. * 2. that either the fulfilled callback or the rejected callback will be * called, but not both. * 3. that fulfilled and rejected will not be called in this turn. * * @param value promise or immediate reference to observe * @param fulfilled function to be called with the fulfilled value * @param rejected function to be called with the rejection exception * @param progressed function to be called on any progress notifications * @return promise for the return value from the invoked callback */ Q.when = when; function when(value, fulfilled, rejected, progressed) { return Q(value).then(fulfilled, rejected, progressed); } Promise.prototype.thenResolve = function (value) { return this.then(function () { return value; }); }; Q.thenResolve = function (promise, value) { return Q(promise).thenResolve(value); }; Promise.prototype.thenReject = function (reason) { return this.then(function () { throw reason; }); }; Q.thenReject = function (promise, reason) { return Q(promise).thenReject(reason); }; /** * If an object is not a promise, it is as "near" as possible. * If a promise is rejected, it is as "near" as possible too. * If it’s a fulfilled promise, the fulfillment value is nearer. * If it’s a deferred promise and the deferred has been resolved, the * resolution is "nearer". * @param object * @returns most resolved (nearest) form of the object */ // XXX should we re-do this? Q.nearer = nearer; function nearer(value) { if (isPromise(value)) { var inspected = value.inspect(); if (inspected.state === "fulfilled") { return inspected.value; } } return value; } /** * @returns whether the given object is a promise. * Otherwise it is a fulfilled value. */ Q.isPromise = isPromise; function isPromise(object) { return isObject(object) && typeof object.promiseDispatch === "function" && typeof object.inspect === "function"; } Q.isPromiseAlike = isPromiseAlike; function isPromiseAlike(object) { return isObject(object) && typeof object.then === "function"; } /** * @returns whether the given object is a pending promise, meaning not * fulfilled or rejected. */ Q.isPending = isPending; function isPending(object) { return isPromise(object) && object.inspect().state === "pending"; } Promise.prototype.isPending = function () { return this.inspect().state === "pending"; }; /** * @returns whether the given object is a value or fulfilled * promise. */ Q.isFulfilled = isFulfilled; function isFulfilled(object) { return !isPromise(object) || object.inspect().state === "fulfilled"; } Promise.prototype.isFulfilled = function () { return this.inspect().state === "fulfilled"; }; /** * @returns whether the given object is a rejected promise. */ Q.isRejected = isRejected; function isRejected(object) { return isPromise(object) && object.inspect().state === "rejected"; } Promise.prototype.isRejected = function () { return this.inspect().state === "rejected"; }; //// BEGIN UNHANDLED REJECTION TRACKING // This promise library consumes exceptions thrown in handlers so they can be // handled by a subsequent promise. The exceptions get added to this array when // they are created, and removed when they are handled. Note that in ES6 or // shimmed environments, this would naturally be a `Set`. var unhandledReasons = []; var unhandledRejections = []; var trackUnhandledRejections = true; function resetUnhandledRejections() { unhandledReasons.length = 0; unhandledRejections.length = 0; if (!trackUnhandledRejections) { trackUnhandledRejections = true; } } function trackRejection(promise, reason) { if (!trackUnhandledRejections) { return; } unhandledRejections.push(promise); if (reason && typeof reason.stack !== "undefined") { unhandledReasons.push(reason.stack); } else { unhandledReasons.push("(no stack) " + reason); } } function untrackRejection(promise) { if (!trackUnhandledRejections) { return; } var at = array_indexOf(unhandledRejections, promise); if (at !== -1) { unhandledRejections.splice(at, 1); unhandledReasons.splice(at, 1); } } Q.resetUnhandledRejections = resetUnhandledRejections; Q.getUnhandledReasons = function () { // Make a copy so that consumers can't interfere with our internal state. return unhandledReasons.slice(); }; Q.stopUnhandledRejectionTracking = function () { resetUnhandledRejections(); trackUnhandledRejections = false; }; resetUnhandledRejections(); //// END UNHANDLED REJECTION TRACKING /** * Constructs a rejected promise. * @param reason value describing the failure */ Q.reject = reject; function reject(reason) { var rejection = Promise({ "when": function (rejected) { // note that the error has been handled if (rejected) { untrackRejection(this); } return rejected ? rejected(reason) : this; } }, function fallback() { return this; }, function inspect() { return { state: "rejected", reason: reason }; }); // Note that the reason has not been handled. trackRejection(rejection, reason); return rejection; } /** * Constructs a fulfilled promise for an immediate reference. * @param value immediate reference */ Q.fulfill = fulfill; function fulfill(value) { return Promise({ "when": function () { return value; }, "get": function (name) { return value[name]; }, "set": function (name, rhs) { value[name] = rhs; }, "delete": function (name) { delete value[name]; }, "post": function (name, args) { // Mark Miller proposes that post with no name should apply a // promised function. if (name === null || name === void 0) { return value.apply(void 0, args); } else { return value[name].apply(value, args); } }, "apply": function (thisp, args) { return value.apply(thisp, args); }, "keys": function () { return object_keys(value); } }, void 0, function inspect() { return { state: "fulfilled", value: value }; }); } /** * Converts thenables to Q promises. * @param promise thenable promise * @returns a Q promise */ function coerce(promise) { var deferred = defer(); nextTick(function () { try { promise.then(deferred.resolve, deferred.reject, deferred.notify); } catch (exception) { deferred.reject(exception); } }); return deferred.promise; } /** * Annotates an object such that it will never be * transferred away from this process over any promise * communication channel. * @param object * @returns promise a wrapping of that object that * additionally responds to the "isDef" message * without a rejection. */ Q.master = master; function master(object) { return Promise({ "isDef": function () {} }, function fallback(op, args) { return dispatch(object, op, args); }, function () { return Q(object).inspect(); }); } /** * Spreads the values of a promised array of arguments into the * fulfillment callback. * @param fulfilled callback that receives variadic arguments from the * promised array * @param rejected callback that receives the exception if the promise * is rejected. * @returns a promise for the return value or thrown exception of * either callback. */ Q.spread = spread; function spread(value, fulfilled, rejected) { return Q(value).spread(fulfilled, rejected); } Promise.prototype.spread = function (fulfilled, rejected) { return this.all().then(function (array) { return fulfilled.apply(void 0, array); }, rejected); }; /** * The async function is a decorator for generator functions, turning * them into asynchronous generators. Although generators are only part * of the newest ECMAScript 6 drafts, this code does not cause syntax * errors in older engines. This code should continue to work and will * in fact improve over time as the language improves. * * ES6 generators are currently part of V8 version 3.19 with the * --harmony-generators runtime flag enabled. SpiderMonkey has had them * for longer, but under an older Python-inspired form. This function * works on both kinds of generators. * * Decorates a generator function such that: * - it may yield promises * - execution will continue when that promise is fulfilled * - the value of the yield expression will be the fulfilled value * - it returns a promise for the return value (when the generator * stops iterating) * - the decorated function returns a promise for the return value * of the generator or the first rejected promise among those * yielded. * - if an error is thrown in the generator, it propagates through * every following yield until it is caught, or until it escapes * the generator function altogether, and is translated into a * rejection for the promise returned by the decorated generator. */ Q.async = async; function async(makeGenerator) { return function () { // when verb is "send", arg is a value // when verb is "throw", arg is an exception function continuer(verb, arg) { var result; // Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only // engine that has a deployed base of browsers that support generators. // However, SM's generators use the Python-inspired semantics of // outdated ES6 drafts. We would like to support ES6, but we'd also // like to make it possible to use generators in deployed browsers, so // we also support Python-style generators. At some point we can remove // this block. if (typeof StopIteration === "undefined") { // ES6 Generators try { result = generator[verb](arg); } catch (exception) { return reject(exception); } if (result.done) { return result.value; } else { return when(result.value, callback, errback); } } else { // SpiderMonkey Generators // FIXME: Remove this case when SM does ES6 generators. try { result = generator[verb](arg); } catch (exception) { if (isStopIteration(exception)) { return exception.value; } else { return reject(exception); } } return when(result, callback, errback); } } var generator = makeGenerator.apply(this, arguments); var callback = continuer.bind(continuer, "next"); var errback = continuer.bind(continuer, "throw"); return callback(); }; } /** * The spawn function is a small wrapper around async that immediately * calls the generator and also ends the promise chain, so that any * unhandled errors are thrown instead of forwarded to the error * handler. This is useful because it's extremely common to run * generators at the top-level to work with libraries. */ Q.spawn = spawn; function spawn(makeGenerator) { Q.done(Q.async(makeGenerator)()); } // FIXME: Remove this interface once ES6 generators are in SpiderMonkey. /** * Throws a ReturnValue exception to stop an asynchronous generator. * * This interface is a stop-gap measure to support generator return * values in older Firefox/SpiderMonkey. In browsers that support ES6 * generators like Chromium 29, just use "return" in your generator * functions. * * @param value the return value for the surrounding generator * @throws ReturnValue exception with the value. * @example * // ES6 style * Q.async(function* () { * var foo = yield getFooPromise(); * var bar = yield getBarPromise(); * return foo + bar; * }) * // Older SpiderMonkey style * Q.async(function () { * var foo = yield getFooPromise(); * var bar = yield getBarPromise(); * Q.return(foo + bar); * }) */ Q["return"] = _return; function _return(value) { throw new QReturnValue(value); } /** * The promised function decorator ensures that any promise arguments * are settled and passed as values (`this` is also settled and passed * as a value). It will also ensure that the result of a function is * always a promise. * * @example * var add = Q.promised(function (a, b) { * return a + b; * }); * add(Q(a), Q(B)); * * @param {function} callback The function to decorate * @returns {function} a function that has been decorated. */ Q.promised = promised; function promised(callback) { return function () { return spread([this, all(arguments)], function (self, args) { return callback.apply(self, args); }); }; } /** * sends a message to a value in a future turn * @param object* the recipient * @param op the name of the message operation, e.g., "when", * @param args further arguments to be forwarded to the operation * @returns result {Promise} a promise for the result of the operation */ Q.dispatch = dispatch; function dispatch(object, op, args) { return Q(object).dispatch(op, args); } Promise.prototype.dispatch = function (op, args) { var self = this; var deferred = defer(); nextTick(function () { self.promiseDispatch(deferred.resolve, op, args); }); return deferred.promise; }; /** * Gets the value of a property in a future turn. * @param object promise or immediate reference for target object * @param name name of property to get * @return promise for the property value */ Q.get = function (object, key) { return Q(object).dispatch("get", [key]); }; Promise.prototype.get = function (key) { return this.dispatch("get", [key]); }; /** * Sets the value of a property in a future turn. * @param object promise or immediate reference for object object * @param name name of property to set * @param value new value of property * @return promise for the return value */ Q.set = function (object, key, value) { return Q(object).dispatch("set", [key, value]); }; Promise.prototype.set = function (key, value) { return this.dispatch("set", [key, value]); }; /** * Deletes a property in a future turn. * @param object promise or immediate reference for target object * @param name name of property to delete * @return promise for the return value */ Q.del = // XXX legacy Q["delete"] = function (object, key) { return Q(object).dispatch("delete", [key]); }; Promise.prototype.del = // XXX legacy Promise.prototype["delete"] = function (key) { return this.dispatch("delete", [key]); }; /** * Invokes a method in a future turn. * @param object promise or immediate reference for target object * @param name name of method to invoke * @param value a value to post, typically an array of * invocation arguments for promises that * are ultimately backed with `resolve` values, * as opposed to those backed with URLs * wherein the posted value can be any * JSON serializable object. * @return promise for the return value */ // bound locally because it is used by other methods Q.mapply = // XXX As proposed by "Redsandro" Q.post = function (object, name, args) { return Q(object).dispatch("post", [name, args]); }; Promise.prototype.mapply = // XXX As proposed by "Redsandro" Promise.prototype.post = function (name, args) { return this.dispatch("post", [name, args]); }; /** * Invokes a method in a future turn. * @param object promise or immediate reference for target object * @param name name of method to invoke * @param ...args array of invocation arguments * @return promise for the return value */ Q.send = // XXX Mark Miller's proposed parlance Q.mcall = // XXX As proposed by "Redsandro" Q.invoke = function (object, name /*...args*/) { return Q(object).dispatch("post", [name, array_slice(arguments, 2)]); }; Promise.prototype.send = // XXX Mark Miller's proposed parlance Promise.prototype.mcall = // XXX As proposed by "Redsandro" Promise.prototype.invoke = function (name /*...args*/) { return this.dispatch("post", [name, array_slice(arguments, 1)]); }; /** * Applies the promised function in a future turn. * @param object promise or immediate reference for target function * @param args array of application arguments */ Q.fapply = function (object, args) { return Q(object).dispatch("apply", [void 0, args]); }; Promise.prototype.fapply = function (args) { return this.dispatch("apply", [void 0, args]); }; /** * Calls the promised function in a future turn. * @param object promise or immediate reference for target function * @param ...args array of application arguments */ Q["try"] = Q.fcall = function (object /* ...args*/) { return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]); }; Promise.prototype.fcall = function (/*...args*/) { return this.dispatch("apply", [void 0, array_slice(arguments)]); }; /** * Binds the promised function, transforming return values into a fulfilled * promise and thrown errors into a rejected one. * @param object promise or immediate reference for target function * @param ...args array of application arguments */ Q.fbind = function (object /*...args*/) { var promise = Q(object); var args = array_slice(arguments, 1); return function fbound() { return promise.dispatch("apply", [ this, args.concat(array_slice(arguments)) ]); }; }; Promise.prototype.fbind = function (/*...args*/) { var promise = this; var args = array_slice(arguments); return function fbound() { return promise.dispatch("apply", [ this, args.concat(array_slice(arguments)) ]); }; }; /** * Requests the names of the owned properties of a promised * object in a future turn. * @param object promise or immediate reference for target object * @return promise for the keys of the eventually settled object */ Q.keys = function (object) { return Q(object).dispatch("keys", []); }; Promise.prototype.keys = function () { return this.dispatch("keys", []); }; /** * Turns an array of promises into a promise for an array. If any of * the promises gets rejected, the whole array is rejected immediately. * @param {Array*} an array (or promise for an array) of values (or * promises for values) * @returns a promise for an array of the corresponding values */ // By Mark Miller // http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled Q.all = all; function all(promises) { return when(promises, function (promises) { var countDown = 0; var deferred = defer(); array_reduce(promises, function (undefined, promise, index) { var snapshot; if ( isPromise(promise) && (snapshot = promise.inspect()).state === "fulfilled" ) { promises[index] = snapshot.value; } else { ++countDown; when( promise, function (value) { promises[index] = value; if (--countDown === 0) { deferred.resolve(promises); } }, deferred.reject, function (progress) { deferred.notify({ index: index, value: progress }); } ); } }, void 0); if (countDown === 0) { deferred.resolve(promises); } return deferred.promise; }); } Promise.prototype.all = function () { return all(this); }; /** * Waits for all promises to be settled, either fulfilled or * rejected. This is distinct from `all` since that would stop * waiting at the first rejection. The promise returned by * `allResolved` will never be rejected. * @param promises a promise for an array (or an array) of promises * (or values) * @return a promise for an array of promises */ Q.allResolved = deprecate(allResolved, "allResolved", "allSettled"); function allResolved(promises) { return when(promises, function (promises) { promises = array_map(promises, Q); return when(all(array_map(promises, function (promise) { return when(promise, noop, noop); })), function () { return promises; }); }); } Promise.prototype.allResolved = function () { return allResolved(this); }; /** * @see Promise#allSettled */ Q.allSettled = allSettled; function allSettled(promises) { return Q(promises).allSettled(); } /** * Turns an array of promises into a promise for an array of their states (as * returned by `inspect`) when they have all settled. * @param {Array[Any*]} values an array (or promise for an array) of values (or * promises for values) * @returns {Array[State]} an array of states for the respective values. */ Promise.prototype.allSettled = function () { return this.then(function (promises) { return all(array_map(promises, function (promise) { promise = Q(promise); function regardless() { return promise.inspect(); } return promise.then(regardless, regardless); })); }); }; /** * Captures the failure of a promise, giving an oportunity to recover * with a callback. If the given promise is fulfilled, the returned * promise is fulfilled. * @param {Any*} promise for something * @param {Function} callback to fulfill the returned promise if the * given promise is rejected * @returns a promise for the return value of the callback */ Q.fail = // XXX legacy Q["catch"] = function (object, rejected) { return Q(object).then(void 0, rejected); }; Promise.prototype.fail = // XXX legacy Promise.prototype["catch"] = function (rejected) { return this.then(void 0, rejected); }; /** * Attaches a listener that can respond to progress notifications from a * promise's originating deferred. This listener receives the exact arguments * passed to ``deferred.notify``. * @param {Any*} promise for something * @param {Function} callback to receive any progress notifications * @returns the given promise, unchanged */ Q.progress = progress; function progress(object, progressed) { return Q(object).then(void 0, void 0, progressed); } Promise.prototype.progress = function (progressed) { return this.then(void 0, void 0, progressed); }; /** * Provides an opportunity to observe the settling of a promise, * regardless of whether the promise is fulfilled or rejected. Forwards * the resolution to the returned promise when the callback is done. * The callback can return a promise to defer completion. * @param {Any*} promise * @param {Function} callback to observe the resolution of the given * promise, takes no arguments. * @returns a promise for the resolution of the given promise when * ``fin`` is done. */ Q.fin = // XXX legacy Q["finally"] = function (object, callback) { return Q(object)["finally"](callback); }; Promise.prototype.fin = // XXX legacy Promise.prototype["finally"] = function (callback) { callback = Q(callback); return this.then(function (value) { return callback.fcall().then(function () { return value; }); }, function (reason) { // TODO attempt to recycle the rejection with "this". return callback.fcall().then(function () { throw reason; }); }); }; /** * Terminates a chain of promises, forcing rejections to be * thrown as exceptions. * @param {Any*} promise at the end of a chain of promises * @returns nothing */ Q.done = function (object, fulfilled, rejected, progress) { return Q(object).done(fulfilled, rejected, progress); }; Promise.prototype.done = function (fulfilled, rejected, progress) { var onUnhandledError = function (error) { // forward to a future turn so that ``when`` // does not catch it and turn it into a rejection. nextTick(function () { makeStackTraceLong(error, promise); if (Q.onerror) { Q.onerror(error); } else { throw error; } }); }; // Avoid unnecessary `nextTick`ing via an unnecessary `when`. var promise = fulfilled || rejected || progress ? this.then(fulfilled, rejected, progress) : this; if (typeof process === "object" && process && process.domain) { onUnhandledError = process.domain.bind(onUnhandledError); } promise.then(void 0, onUnhandledError); }; /** * Causes a promise to be rejected if it does not get fulfilled before * some milliseconds time out. * @param {Any*} promise * @param {Number} milliseconds timeout * @param {String} custom error message (optional) * @returns a promise for the resolution of the given promise if it is * fulfilled before the timeout, otherwise rejected. */ Q.timeout = function (object, ms, message) { return Q(object).timeout(ms, message); }; Promise.prototype.timeout = function (ms, message) { var deferred = defer(); var timeoutId = setTimeout(function () { deferred.reject(new Error(message || "Timed out after " + ms + " ms")); }, ms); this.then(function (value) { clearTimeout(timeoutId); deferred.resolve(value); }, function (exception) { clearTimeout(timeoutId); deferred.reject(exception); }, deferred.notify); return deferred.promise; }; /** * Returns a promise for the given value (or promised value), some * milliseconds after it resolved. Passes rejections immediately. * @param {Any*} promise * @param {Number} milliseconds * @returns a promise for the resolution of the given promise after milliseconds * time has elapsed since the resolution of the given promise. * If the given promise rejects, that is passed immediately. */ Q.delay = function (object, timeout) { if (timeout === void 0) { timeout = object; object = void 0; } return Q(object).delay(timeout); }; Promise.prototype.delay = function (timeout) { return this.then(function (value) { var deferred = defer(); setTimeout(function () { deferred.resolve(value); }, timeout); return deferred.promise; }); }; /** * Passes a continuation to a Node function, which is called with the given * arguments provided as an array, and returns a promise. * * Q.nfapply(FS.readFile, [__filename]) * .then(function (content) { * }) * */ Q.nfapply = function (callback, args) { return Q(callback).nfapply(args); }; Promise.prototype.nfapply = function (args) { var deferred = defer(); var nodeArgs = array_slice(args); nodeArgs.push(deferred.makeNodeResolver()); this.fapply(nodeArgs).fail(deferred.reject); return deferred.promise; }; /** * Passes a continuation to a Node function, which is called with the given * arguments provided individually, and returns a promise. * @example * Q.nfcall(FS.readFile, __filename) * .then(function (content) { * }) * */ Q.nfcall = function (callback /*...args*/) { var args = array_slice(arguments, 1); return Q(callback).nfapply(args); }; Promise.prototype.nfcall = function (/*...args*/) { var nodeArgs = array_slice(arguments); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); this.fapply(nodeArgs).fail(deferred.reject); return deferred.promise; }; /** * Wraps a NodeJS continuation passing function and returns an equivalent * version that returns a promise. * @example * Q.nfbind(FS.readFile, __filename)("utf-8") * .then(console.log) * .done() */ Q.nfbind = Q.denodeify = function (callback /*...args*/) { var baseArgs = array_slice(arguments, 1); return function () { var nodeArgs = baseArgs.concat(array_slice(arguments)); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); Q(callback).fapply(nodeArgs).fail(deferred.reject); return deferred.promise; }; }; Promise.prototype.nfbind = Promise.prototype.denodeify = function (/*...args*/) { var args = array_slice(arguments); args.unshift(this); return Q.denodeify.apply(void 0, args); }; Q.nbind = function (callback, thisp /*...args*/) { var baseArgs = array_slice(arguments, 2); return function () { var nodeArgs = baseArgs.concat(array_slice(arguments)); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); function bound() { return callback.apply(thisp, arguments); } Q(bound).fapply(nodeArgs).fail(deferred.reject); return deferred.promise; }; }; Promise.prototype.nbind = function (/*thisp, ...args*/) { var args = array_slice(arguments, 0); args.unshift(this); return Q.nbind.apply(void 0, args); }; /** * Calls a method of a Node-style object that accepts a Node-style * callback with a given array of arguments, plus a provided callback. * @param object an object that has the named method * @param {String} name name of the method of object * @param {Array} args arguments to pass to the method; the callback * will be provided by Q and appended to these arguments. * @returns a promise for the value or error */ Q.nmapply = // XXX As proposed by "Redsandro" Q.npost = function (object, name, args) { return Q(object).npost(name, args); }; Promise.prototype.nmapply = // XXX As proposed by "Redsandro" Promise.prototype.npost = function (name, args) { var nodeArgs = array_slice(args || []); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); this.dispatch("post", [name, nodeArgs]).fail(deferred.reject); return deferred.promise; }; /** * Calls a method of a Node-style object that accepts a Node-style * callback, forwarding the given variadic arguments, plus a provided * callback argument. * @param object an object that has the named method * @param {String} name name of the method of object * @param ...args arguments to pass to the method; the callback will * be provided by Q and appended to these arguments. * @returns a promise for the value or error */ Q.nsend = // XXX Based on Mark Miller's proposed "send" Q.nmcall = // XXX Based on "Redsandro's" proposal Q.ninvoke = function (object, name /*...args*/) { var nodeArgs = array_slice(arguments, 2); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject); return deferred.promise; }; Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send" Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal Promise.prototype.ninvoke = function (name /*...args*/) { var nodeArgs = array_slice(arguments, 1); var deferred = defer(); nodeArgs.push(deferred.makeNodeResolver()); this.dispatch("post", [name, nodeArgs]).fail(deferred.reject); return deferred.promise; }; /** * If a function would like to support both Node continuation-passing-style and * promise-returning-style, it can end its internal promise chain with * `nodeify(nodeback)`, forwarding the optional nodeback argument. If the user * elects to use a nodeback, the result will be sent there. If they do not * pass a nodeback, they will receive the result promise. * @param object a result (or a promise for a result) * @param {Function} nodeback a Node.js-style callback * @returns either the promise or nothing */ Q.nodeify = nodeify; function nodeify(object, nodeback) { return Q(object).nodeify(nodeback); } Promise.prototype.nodeify = function (nodeback) { if (nodeback) { this.then(function (value) { nextTick(function () { nodeback(null, value); }); }, function (error) { nextTick(function () { nodeback(error); }); }); } else { return this; } }; // All code before this point will be filtered from stack traces. var qEndingLine = captureLine(); return Q; });
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.tippy = factory()); }(this, (function () { 'use strict'; var Browser = {}; if (typeof window !== 'undefined') { Browser.SUPPORTED = 'requestAnimationFrame' in window; Browser.SUPPORTS_TOUCH = 'ontouchstart' in window; Browser.touch = false; Browser.dynamicInputDetection = true; // Chrome device/touch emulation can make this dynamic Browser.iOS = function () { return (/iPhone|iPad|iPod/.test(navigator.userAgent) && !window.MSStream ); }; } /** * The global storage array which holds all data reference objects * from every instance * This allows us to hide tooltips from all instances, finding the ref when * clicking on the body, and for followCursor */ var Store = []; /** * Selector constants used for grabbing elements */ var Selectors = { POPPER: '.tippy-popper', TOOLTIP: '.tippy-tooltip', CONTENT: '.tippy-tooltip-content', CIRCLE: '[x-circle]', ARROW: '[x-arrow]', TOOLTIPPED_EL: '[data-tooltipped]', CONTROLLER: '[data-tippy-controller]' /** * The default settings applied to each instance */ };var Defaults = { html: false, position: 'top', animation: 'shift', animateFill: true, arrow: false, arrowSize: 'regular', delay: 0, trigger: 'mouseenter focus', duration: 350, interactive: false, interactiveBorder: 2, theme: 'dark', size: 'regular', distance: 10, offset: 0, hideOnClick: true, multiple: false, followCursor: false, inertia: false, flipDuration: 350, sticky: false, stickyDuration: 200, appendTo: function appendTo() { return document.body; }, zIndex: 9999, touchHold: false, performance: false, dynamicTitle: false, popperOptions: {} /** * The keys of the defaults object for reducing down into a new object * Used in `getIndividualSettings()` */ };var DefaultsKeys = Browser.SUPPORTED && Object.keys(Defaults); /** * Hides all poppers * @param {Object} exclude - refData to exclude if needed */ function hideAllPoppers(exclude) { Store.forEach(function (refData) { var popper = refData.popper, tippyInstance = refData.tippyInstance, _refData$settings = refData.settings, appendTo = _refData$settings.appendTo, hideOnClick = _refData$settings.hideOnClick, trigger = _refData$settings.trigger; // Don't hide already hidden ones if (!appendTo.contains(popper)) return; // hideOnClick can have the truthy value of 'persistent', so strict check is needed var isHideOnClick = hideOnClick === true || trigger.indexOf('focus') !== -1; var isNotCurrentRef = !exclude || popper !== exclude.popper; if (isHideOnClick && isNotCurrentRef) { tippyInstance.hide(popper); } }); } var matches = {}; if (typeof Element !== 'undefined') { var e = Element.prototype; matches = e.matches || e.matchesSelector || e.webkitMatchesSelector || e.mozMatchesSelector || e.msMatchesSelector || function (s) { var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) {} return i > -1; }; } var matches$1 = matches; /** * Ponyfill to get the closest parent element * @param {Element} element - child of parent to be returned * @param {String} parentSelector - selector to match the parent if found * @return {Element} */ function closest(element, parentSelector) { var _closest = Element.prototype.closest || function (selector) { var el = this; while (el) { if (matches$1.call(el, selector)) { return el; } el = el.parentElement; } }; return _closest.call(element, parentSelector); } /** * Ponyfill for Array.prototype.find * @param {Array} arr * @param {Function} checkFn * @return item in the array */ function find(arr, checkFn) { if (Array.prototype.find) { return arr.find(checkFn); } // use `filter` as fallback return arr.filter(checkFn)[0]; } /** * Adds the needed event listeners */ function bindEventListeners() { var touchHandler = function touchHandler() { Browser.touch = true; if (Browser.iOS()) { document.body.classList.add('tippy-touch'); } if (Browser.dynamicInputDetection && window.performance) { document.addEventListener('mousemove', mousemoveHandler); } }; var mousemoveHandler = function () { var time = void 0; return function () { var now = performance.now(); // Chrome 60+ is 1 mousemove per rAF, use 20ms time difference if (now - time < 20) { Browser.touch = false; document.removeEventListener('mousemove', mousemoveHandler); if (!Browser.iOS()) { document.body.classList.remove('tippy-touch'); } } time = now; }; }(); var clickHandler = function clickHandler(event) { // Simulated events dispatched on the document if (!(event.target instanceof Element)) { return hideAllPoppers(); } var el = closest(event.target, Selectors.TOOLTIPPED_EL); var popper = closest(event.target, Selectors.POPPER); if (popper) { var ref = find(Store, function (ref) { return ref.popper === popper; }); var interactive = ref.settings.interactive; if (interactive) return; } if (el) { var _ref = find(Store, function (ref) { return ref.el === el; }); var _ref$settings = _ref.settings, hideOnClick = _ref$settings.hideOnClick, multiple = _ref$settings.multiple, trigger = _ref$settings.trigger; // Hide all poppers except the one belonging to the element that was clicked IF // `multiple` is false AND they are a touch user, OR // `multiple` is false AND it's triggered by a click if (!multiple && Browser.touch || !multiple && trigger.indexOf('click') !== -1) { return hideAllPoppers(_ref); } // If hideOnClick is not strictly true or triggered by a click don't hide poppers if (hideOnClick !== true || trigger.indexOf('click') !== -1) return; } // Don't trigger a hide for tippy controllers, and don't needlessly run loop if (closest(event.target, Selectors.CONTROLLER) || !document.querySelector(Selectors.POPPER)) return; hideAllPoppers(); }; var blurHandler = function blurHandler(event) { var _document = document, el = _document.activeElement; if (el && el.blur && matches$1.call(el, Selectors.TOOLTIPPED_EL)) { el.blur(); } }; // Hook events document.addEventListener('click', clickHandler); document.addEventListener('touchstart', touchHandler); window.addEventListener('blur', blurHandler); if (!Browser.SUPPORTS_TOUCH && (navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0)) { document.addEventListener('pointerdown', touchHandler); } } /** * To run a single time, once DOM is presumed to be ready * @return {Boolean} whether the function has run or not */ function init() { if (init.done) return false; init.done = true; bindEventListeners(); return true; } /** * Waits until next repaint to execute a fn * @param {Function} fn */ function defer(fn) { window.requestAnimationFrame(function () { setTimeout(fn, 0); }); } /** * Returns the supported prefixed property - only `webkit` is needed, `moz`, `ms` and `o` are obsolete * @param {String} property * @return {String} - browser supported prefixed property */ function prefix(property) { var prefixes = [false, 'webkit']; var upperProp = property.charAt(0).toUpperCase() + property.slice(1); for (var i = 0; i < prefixes.length; i++) { var _prefix = prefixes[i]; var prefixedProp = _prefix ? '' + _prefix + upperProp : property; if (typeof window.document.body.style[prefixedProp] !== 'undefined') { return prefixedProp; } } return null; } /** * Ponyfill for Array.prototype.findIndex * @param {Array} arr * @param {Function} checkFn * @return index of the item in the array */ function findIndex(arr, checkFn) { if (Array.prototype.findIndex) { return arr.findIndex(checkFn); } // fallback return arr.indexOf(find(arr, checkFn)); } /** * Removes the title from the tooltipped element, setting `data-original-title` * appropriately * @param {Element} el */ function removeTitle(el) { var title = el.getAttribute('title'); // Only set `data-original-title` attr if there is a title if (title) { el.setAttribute('data-original-title', title); } el.removeAttribute('title'); } /** * Determines if an element is visible in the viewport * @param {Element} el * @return {Boolean} */ function elementIsInViewport(el) { var rect = el.getBoundingClientRect(); return rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth); } /** * Triggers a document repaint or reflow for CSS transition * @param {Element} tooltip * @param {Element} circle */ function triggerReflow(tooltip, circle) { // Safari needs the specific 'transform' property to be accessed circle ? window.getComputedStyle(circle)[prefix('transform')] : window.getComputedStyle(tooltip).opacity; } /** * Modifies elements' class lists * @param {Element[]} els - Array of elements * @param {Function} callback */ function modifyClassList(els, callback) { els.forEach(function (el) { if (!el) return; callback(el.classList); }); } /** * Returns inner elements of the popper element * @param {Element} popper * @return {Object} */ function getInnerElements(popper) { return { tooltip: popper.querySelector(Selectors.TOOLTIP), circle: popper.querySelector(Selectors.CIRCLE), content: popper.querySelector(Selectors.CONTENT) }; } /** * Applies the transition duration to each element * @param {Element[]} els - Array of elements * @param {Number} duration */ function applyTransitionDuration(els, duration) { els.forEach(function (el) { if (!el) return; var isContent = matches$1.call(el, Selectors.CONTENT); var _duration = isContent ? Math.round(duration / 1.3) : duration; el.style[prefix('transitionDuration')] = _duration + 'ms'; }); } /** * Determines if a popper is currently visible * @param {Element} popper * @return {Boolean} */ function isVisible(popper) { return popper.style.visibility === 'visible'; } function noop() {} /** * Returns the non-shifted placement (e.g., 'bottom-start' => 'bottom') * @param {String} placement * @return {String} */ function getCorePlacement(placement) { return placement.replace(/-.+/, ''); } /** * Mousemove event listener callback method for follow cursor setting * @param {MouseEvent} e */ function followCursorHandler(e) { var _this = this; var refData = find(Store, function (refData) { return refData.el === _this; }); var popper = refData.popper, offset = refData.settings.offset; var position = getCorePlacement(popper.getAttribute('x-placement')); var halfPopperWidth = Math.round(popper.offsetWidth / 2); var halfPopperHeight = Math.round(popper.offsetHeight / 2); var viewportPadding = 5; var pageWidth = document.documentElement.offsetWidth || document.body.offsetWidth; var pageX = e.pageX, pageY = e.pageY; var x = void 0, y = void 0; switch (position) { case 'top': x = pageX - halfPopperWidth + offset; y = pageY - 2.25 * halfPopperHeight; break; case 'left': x = pageX - 2 * halfPopperWidth - 10; y = pageY - halfPopperHeight + offset; break; case 'right': x = pageX + halfPopperHeight; y = pageY - halfPopperHeight + offset; break; case 'bottom': x = pageX - halfPopperWidth + offset; y = pageY + halfPopperHeight / 1.5; break; } var isRightOverflowing = pageX + viewportPadding + halfPopperWidth + offset > pageWidth; var isLeftOverflowing = pageX - viewportPadding - halfPopperWidth + offset < 0; // Prevent left/right overflow if (position === 'top' || position === 'bottom') { if (isRightOverflowing) { x = pageWidth - viewportPadding - 2 * halfPopperWidth; } if (isLeftOverflowing) { x = viewportPadding; } } popper.style[prefix('transform')] = 'translate3d(' + x + 'px, ' + y + 'px, 0)'; } /** * Returns an array of elements based on the selector input * @param {String|Element|Element[]} selector * @return {Element[]} */ function getArrayOfElements(selector) { if (selector instanceof Element) { return [selector]; } if (Array.isArray(selector)) { return selector; } if (selector.constructor.name === 'NodeList') { return [].slice.call(selector); } return [].slice.call(document.querySelectorAll(selector)); } /** * Prepares the callback functions for `show` and `hide` methods * @param {Object} data * @param {Number} duration * @param {Function} callback - callback function to fire once transitions complete */ function onTransitionEnd(data, duration, callback) { // Make callback synchronous if duration is 0 if (!duration) { return callback(); } var _getInnerElements = getInnerElements(data.popper), tooltip = _getInnerElements.tooltip; var transitionendFired = false; var listenerCallback = function listenerCallback(e) { if (e.target === tooltip && !transitionendFired) { transitionendFired = true; callback(); } }; // Fire callback upon transition completion tooltip.addEventListener('webkitTransitionEnd', listenerCallback); tooltip.addEventListener('transitionend', listenerCallback); // Fallback: transitionend listener sometimes may not fire clearTimeout(data._transitionendTimeout); data._transitionendTimeout = setTimeout(function () { if (!transitionendFired) { callback(); } }, duration); } /**! * @fileOverview Kickass library to create and place poppers near their reference elements. * @version 1.12.4 * @license * Copyright (c) 2016 Federico Zivolo and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ var nativeHints = ['native code', '[object MutationObserverConstructor]']; /** * Determine if a function is implemented natively (as opposed to a polyfill). * @method * @memberof Popper.Utils * @argument {Function | undefined} fn the function to check * @returns {Boolean} */ var isNative = function isNative(fn) { return nativeHints.some(function (hint) { return (fn || '').toString().indexOf(hint) > -1; }); }; var isBrowser = typeof window !== 'undefined'; var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox']; var timeoutDuration = 0; for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) { if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) { timeoutDuration = 1; break; } } function microtaskDebounce(fn) { var scheduled = false; var i = 0; var elem = document.createElement('span'); // MutationObserver provides a mechanism for scheduling microtasks, which // are scheduled *before* the next task. This gives us a way to debounce // a function but ensure it's called *before* the next paint. var observer = new MutationObserver(function () { fn(); scheduled = false; }); observer.observe(elem, { attributes: true }); return function () { if (!scheduled) { scheduled = true; elem.setAttribute('x-index', i); i = i + 1; // don't use compund (+=) because it doesn't get optimized in V8 } }; } function taskDebounce(fn) { var scheduled = false; return function () { if (!scheduled) { scheduled = true; setTimeout(function () { scheduled = false; fn(); }, timeoutDuration); } }; } // It's common for MutationObserver polyfills to be seen in the wild, however // these rely on Mutation Events which only occur when an element is connected // to the DOM. The algorithm used in this module does not use a connected element, // and so we must ensure that a *native* MutationObserver is available. var supportsNativeMutationObserver = isBrowser && isNative(window.MutationObserver); /** * Create a debounced version of a method, that's asynchronously deferred * but called in the minimum time possible. * * @method * @memberof Popper.Utils * @argument {Function} fn * @returns {Function} */ var debounce = supportsNativeMutationObserver ? microtaskDebounce : taskDebounce; /** * Check if the given variable is a function * @method * @memberof Popper.Utils * @argument {Any} functionToCheck - variable to check * @returns {Boolean} answer to: is a function? */ function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } /** * Get CSS computed property of the given element * @method * @memberof Popper.Utils * @argument {Eement} element * @argument {String} property */ function getStyleComputedProperty(element, property) { if (element.nodeType !== 1) { return []; } // NOTE: 1 DOM access here var css = window.getComputedStyle(element, null); return property ? css[property] : css; } /** * Returns the parentNode or the host of the element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} parent */ function getParentNode(element) { if (element.nodeName === 'HTML') { return element; } return element.parentNode || element.host; } /** * Returns the scrolling parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} scroll parent */ function getScrollParent(element) { // Return body, `getScroll` will take care to get the correct `scrollTop` from it if (!element || ['HTML', 'BODY', '#document'].indexOf(element.nodeName) !== -1) { return window.document.body; } // Firefox want us to check `-x` and `-y` variations as well var _getStyleComputedProp = getStyleComputedProperty(element), overflow = _getStyleComputedProp.overflow, overflowX = _getStyleComputedProp.overflowX, overflowY = _getStyleComputedProp.overflowY; if (/(auto|scroll)/.test(overflow + overflowY + overflowX)) { return element; } return getScrollParent(getParentNode(element)); } /** * Returns the offset parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} offset parent */ function getOffsetParent(element) { // NOTE: 1 DOM access here var offsetParent = element && element.offsetParent; var nodeName = offsetParent && offsetParent.nodeName; if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') { return window.document.documentElement; } // .offsetParent will return the closest TD or TABLE in case // no offsetParent is present, I hate this job... if (['TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') { return getOffsetParent(offsetParent); } return offsetParent; } function isOffsetContainer(element) { var nodeName = element.nodeName; if (nodeName === 'BODY') { return false; } return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element; } /** * Finds the root node (document, shadowDOM root) of the given element * @method * @memberof Popper.Utils * @argument {Element} node * @returns {Element} root node */ function getRoot(node) { if (node.parentNode !== null) { return getRoot(node.parentNode); } return node; } /** * Finds the offset parent common to the two provided nodes * @method * @memberof Popper.Utils * @argument {Element} element1 * @argument {Element} element2 * @returns {Element} common offset parent */ function findCommonOffsetParent(element1, element2) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { return window.document.documentElement; } // Here we make sure to give as "start" the element that comes first in the DOM var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING; var start = order ? element1 : element2; var end = order ? element2 : element1; // Get common ancestor container var range = document.createRange(); range.setStart(start, 0); range.setEnd(end, 0); var commonAncestorContainer = range.commonAncestorContainer; // Both nodes are inside #document if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) { if (isOffsetContainer(commonAncestorContainer)) { return commonAncestorContainer; } return getOffsetParent(commonAncestorContainer); } // one of the nodes is inside shadowDOM, find which one var element1root = getRoot(element1); if (element1root.host) { return findCommonOffsetParent(element1root.host, element2); } else { return findCommonOffsetParent(element1, getRoot(element2).host); } } /** * Gets the scroll value of the given element in the given side (top and left) * @method * @memberof Popper.Utils * @argument {Element} element * @argument {String} side `top` or `left` * @returns {number} amount of scrolled pixels */ function getScroll(element) { var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top'; var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft'; var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { var html = window.document.documentElement; var scrollingElement = window.document.scrollingElement || html; return scrollingElement[upperSide]; } return element[upperSide]; } /* * Sum or subtract the element scroll values (left and top) from a given rect object * @method * @memberof Popper.Utils * @param {Object} rect - Rect object you want to change * @param {HTMLElement} element - The element from the function reads the scroll values * @param {Boolean} subtract - set to true if you want to subtract the scroll values * @return {Object} rect - The modifier rect object */ function includeScroll(rect, element) { var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var scrollTop = getScroll(element, 'top'); var scrollLeft = getScroll(element, 'left'); var modifier = subtract ? -1 : 1; rect.top += scrollTop * modifier; rect.bottom += scrollTop * modifier; rect.left += scrollLeft * modifier; rect.right += scrollLeft * modifier; return rect; } /* * Helper to detect borders of a given element * @method * @memberof Popper.Utils * @param {CSSStyleDeclaration} styles * Result of `getStyleComputedProperty` on the given element * @param {String} axis - `x` or `y` * @return {number} borders - The borders size of the given axis */ function getBordersSize(styles, axis) { var sideA = axis === 'x' ? 'Left' : 'Top'; var sideB = sideA === 'Left' ? 'Right' : 'Bottom'; return +styles['border' + sideA + 'Width'].split('px')[0] + +styles['border' + sideB + 'Width'].split('px')[0]; } /** * Tells if you are running Internet Explorer 10 * @method * @memberof Popper.Utils * @returns {Boolean} isIE10 */ var isIE10 = undefined; var isIE10$1 = function isIE10$1() { if (isIE10 === undefined) { isIE10 = navigator.appVersion.indexOf('MSIE 10') !== -1; } return isIE10; }; function getSize(axis, body, html, computedStyle, includeScroll) { return Math.max(body['offset' + axis], includeScroll ? body['scroll' + axis] : 0, html['client' + axis], html['offset' + axis], includeScroll ? html['scroll' + axis] : 0, isIE10$1() ? html['offset' + axis] + computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')] + computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')] : 0); } function getWindowSizes() { var includeScroll = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; var body = window.document.body; var html = window.document.documentElement; var computedStyle = isIE10$1() && window.getComputedStyle(html); return { height: getSize('Height', body, html, computedStyle, includeScroll), width: getSize('Width', body, html, computedStyle, includeScroll) }; } var classCallCheck = function classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var defineProperty = function defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /** * Given element offsets, generate an output similar to getBoundingClientRect * @method * @memberof Popper.Utils * @argument {Object} offsets * @returns {Object} ClientRect like output */ function getClientRect(offsets) { return _extends({}, offsets, { right: offsets.left + offsets.width, bottom: offsets.top + offsets.height }); } /** * Get bounding client rect of given element * @method * @memberof Popper.Utils * @param {HTMLElement} element * @return {Object} client rect */ function getBoundingClientRect(element) { var rect = {}; // IE10 10 FIX: Please, don't ask, the element isn't // considered in DOM in some circumstances... // This isn't reproducible in IE10 compatibility mode of IE11 if (isIE10$1()) { try { rect = element.getBoundingClientRect(); var scrollTop = getScroll(element, 'top'); var scrollLeft = getScroll(element, 'left'); rect.top += scrollTop; rect.left += scrollLeft; rect.bottom += scrollTop; rect.right += scrollLeft; } catch (err) {} } else { rect = element.getBoundingClientRect(); } var result = { left: rect.left, top: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top }; // subtract scrollbar size from sizes var sizes = element.nodeName === 'HTML' ? getWindowSizes() : {}; var width = sizes.width || element.clientWidth || result.right - result.left; var height = sizes.height || element.clientHeight || result.bottom - result.top; var horizScrollbar = element.offsetWidth - width; var vertScrollbar = element.offsetHeight - height; // if an hypothetical scrollbar is detected, we must be sure it's not a `border` // we make this check conditional for performance reasons if (horizScrollbar || vertScrollbar) { var styles = getStyleComputedProperty(element); horizScrollbar -= getBordersSize(styles, 'x'); vertScrollbar -= getBordersSize(styles, 'y'); result.width -= horizScrollbar; result.height -= vertScrollbar; } return getClientRect(result); } function getOffsetRectRelativeToArbitraryNode(children, parent) { var isIE10 = isIE10$1(); var isHTML = parent.nodeName === 'HTML'; var childrenRect = getBoundingClientRect(children); var parentRect = getBoundingClientRect(parent); var scrollParent = getScrollParent(children); var styles = getStyleComputedProperty(parent); var borderTopWidth = +styles.borderTopWidth.split('px')[0]; var borderLeftWidth = +styles.borderLeftWidth.split('px')[0]; var offsets = getClientRect({ top: childrenRect.top - parentRect.top - borderTopWidth, left: childrenRect.left - parentRect.left - borderLeftWidth, width: childrenRect.width, height: childrenRect.height }); offsets.marginTop = 0; offsets.marginLeft = 0; // Subtract margins of documentElement in case it's being used as parent // we do this only on HTML because it's the only element that behaves // differently when margins are applied to it. The margins are included in // the box of the documentElement, in the other cases not. if (!isIE10 && isHTML) { var marginTop = +styles.marginTop.split('px')[0]; var marginLeft = +styles.marginLeft.split('px')[0]; offsets.top -= borderTopWidth - marginTop; offsets.bottom -= borderTopWidth - marginTop; offsets.left -= borderLeftWidth - marginLeft; offsets.right -= borderLeftWidth - marginLeft; // Attach marginTop and marginLeft because in some circumstances we may need them offsets.marginTop = marginTop; offsets.marginLeft = marginLeft; } if (isIE10 ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') { offsets = includeScroll(offsets, parent); } return offsets; } function getViewportOffsetRectRelativeToArtbitraryNode(element) { var html = window.document.documentElement; var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html); var width = Math.max(html.clientWidth, window.innerWidth || 0); var height = Math.max(html.clientHeight, window.innerHeight || 0); var scrollTop = getScroll(html); var scrollLeft = getScroll(html, 'left'); var offset = { top: scrollTop - relativeOffset.top + relativeOffset.marginTop, left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft, width: width, height: height }; return getClientRect(offset); } /** * Check if the given element is fixed or is inside a fixed parent * @method * @memberof Popper.Utils * @argument {Element} element * @argument {Element} customContainer * @returns {Boolean} answer to "isFixed?" */ function isFixed(element) { var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { return false; } if (getStyleComputedProperty(element, 'position') === 'fixed') { return true; } return isFixed(getParentNode(element)); } /** * Computed the boundaries limits and return them * @method * @memberof Popper.Utils * @param {HTMLElement} popper * @param {HTMLElement} reference * @param {number} padding * @param {HTMLElement} boundariesElement - Element used to define the boundaries * @returns {Object} Coordinates of the boundaries */ function getBoundaries(popper, reference, padding, boundariesElement) { // NOTE: 1 DOM access here var boundaries = { top: 0, left: 0 }; var offsetParent = findCommonOffsetParent(popper, reference); // Handle viewport case if (boundariesElement === 'viewport') { boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent); } else { // Handle other cases based on DOM element used as boundaries var boundariesNode = void 0; if (boundariesElement === 'scrollParent') { boundariesNode = getScrollParent(getParentNode(popper)); if (boundariesNode.nodeName === 'BODY') { boundariesNode = window.document.documentElement; } } else if (boundariesElement === 'window') { boundariesNode = window.document.documentElement; } else { boundariesNode = boundariesElement; } var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent); // In case of HTML, we need a different computation if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) { var _getWindowSizes = getWindowSizes(false), height = _getWindowSizes.height, width = _getWindowSizes.width; boundaries.top += offsets.top - offsets.marginTop; boundaries.bottom = height + offsets.top; boundaries.left += offsets.left - offsets.marginLeft; boundaries.right = width + offsets.left; } else { // for all the other DOM elements, this one is good boundaries = offsets; } } // Add paddings boundaries.left += padding; boundaries.top += padding; boundaries.right -= padding; boundaries.bottom -= padding; return boundaries; } function getArea(_ref) { var width = _ref.width, height = _ref.height; return width * height; } /** * Utility used to transform the `auto` placement to the placement with more * available space. * @method * @memberof Popper.Utils * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) { var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; if (placement.indexOf('auto') === -1) { return placement; } var boundaries = getBoundaries(popper, reference, padding, boundariesElement); var rects = { top: { width: boundaries.width, height: refRect.top - boundaries.top }, right: { width: boundaries.right - refRect.right, height: boundaries.height }, bottom: { width: boundaries.width, height: boundaries.bottom - refRect.bottom }, left: { width: refRect.left - boundaries.left, height: boundaries.height } }; var sortedAreas = Object.keys(rects).map(function (key) { return _extends({ key: key }, rects[key], { area: getArea(rects[key]) }); }).sort(function (a, b) { return b.area - a.area; }); var filteredAreas = sortedAreas.filter(function (_ref2) { var width = _ref2.width, height = _ref2.height; return width >= popper.clientWidth && height >= popper.clientHeight; }); var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key; var variation = placement.split('-')[1]; return computedPlacement + (variation ? '-' + variation : ''); } /** * Get offsets to the reference element * @method * @memberof Popper.Utils * @param {Object} state * @param {Element} popper - the popper element * @param {Element} reference - the reference element (the popper will be relative to this) * @returns {Object} An object containing the offsets which will be applied to the popper */ function getReferenceOffsets(state, popper, reference) { var commonOffsetParent = findCommonOffsetParent(popper, reference); return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent); } /** * Get the outer sizes of the given element (offset size + margins) * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Object} object containing width and height properties */ function getOuterSizes(element) { var styles = window.getComputedStyle(element); var x = parseFloat(styles.marginTop) + parseFloat(styles.marginBottom); var y = parseFloat(styles.marginLeft) + parseFloat(styles.marginRight); var result = { width: element.offsetWidth + y, height: element.offsetHeight + x }; return result; } /** * Get the opposite placement of the given one * @method * @memberof Popper.Utils * @argument {String} placement * @returns {String} flipped placement */ function getOppositePlacement(placement) { var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; return placement.replace(/left|right|bottom|top/g, function (matched) { return hash[matched]; }); } /** * Get offsets to the popper * @method * @memberof Popper.Utils * @param {Object} position - CSS position the Popper will get applied * @param {HTMLElement} popper - the popper element * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this) * @param {String} placement - one of the valid placement options * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper */ function getPopperOffsets(popper, referenceOffsets, placement) { placement = placement.split('-')[0]; // Get popper node sizes var popperRect = getOuterSizes(popper); // Add position, width and height to our offsets object var popperOffsets = { width: popperRect.width, height: popperRect.height }; // depending by the popper placement we have to compute its offsets slightly differently var isHoriz = ['right', 'left'].indexOf(placement) !== -1; var mainSide = isHoriz ? 'top' : 'left'; var secondarySide = isHoriz ? 'left' : 'top'; var measurement = isHoriz ? 'height' : 'width'; var secondaryMeasurement = !isHoriz ? 'height' : 'width'; popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2; if (placement === secondarySide) { popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement]; } else { popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)]; } return popperOffsets; } /** * Mimics the `find` method of Array * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function find$1(arr, check) { // use native find if supported if (Array.prototype.find) { return arr.find(check); } // use `filter` to obtain the same behavior of `find` return arr.filter(check)[0]; } /** * Return the index of the matching object * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function findIndex$1(arr, prop, value) { // use native findIndex if supported if (Array.prototype.findIndex) { return arr.findIndex(function (cur) { return cur[prop] === value; }); } // use `find` + `indexOf` if `findIndex` isn't supported var match = find$1(arr, function (obj) { return obj[prop] === value; }); return arr.indexOf(match); } /** * Loop trough the list of modifiers and run them in order, * each of them will then edit the data object. * @method * @memberof Popper.Utils * @param {dataObject} data * @param {Array} modifiers * @param {String} ends - Optional modifier name used as stopper * @returns {dataObject} */ function runModifiers(modifiers, data, ends) { var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex$1(modifiers, 'name', ends)); modifiersToRun.forEach(function (modifier) { if (modifier.function) { console.warn('`modifier.function` is deprecated, use `modifier.fn`!'); } var fn = modifier.function || modifier.fn; if (modifier.enabled && isFunction(fn)) { // Add properties to offsets to make them a complete clientRect object // we do this before each modifier to make sure the previous one doesn't // mess with these values data.offsets.popper = getClientRect(data.offsets.popper); data.offsets.reference = getClientRect(data.offsets.reference); data = fn(data, modifier); } }); return data; } /** * Updates the position of the popper, computing the new offsets and applying * the new style.<br /> * Prefer `scheduleUpdate` over `update` because of performance reasons. * @method * @memberof Popper */ function update() { // if popper is destroyed, don't perform any further update if (this.state.isDestroyed) { return; } var data = { instance: this, styles: {}, arrowStyles: {}, attributes: {}, flipped: false, offsets: {} }; // compute reference element offsets data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding); // store the computed placement inside `originalPlacement` data.originalPlacement = data.placement; // compute the popper offsets data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement); data.offsets.popper.position = 'absolute'; // run the modifiers data = runModifiers(this.modifiers, data); // the first `update` will call `onCreate` callback // the other ones will call `onUpdate` callback if (!this.state.isCreated) { this.state.isCreated = true; this.options.onCreate(data); } else { this.options.onUpdate(data); } } /** * Helper used to know if the given modifier is enabled. * @method * @memberof Popper.Utils * @returns {Boolean} */ function isModifierEnabled(modifiers, modifierName) { return modifiers.some(function (_ref) { var name = _ref.name, enabled = _ref.enabled; return enabled && name === modifierName; }); } /** * Get the prefixed supported property name * @method * @memberof Popper.Utils * @argument {String} property (camelCase) * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix) */ function getSupportedPropertyName(property) { var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O']; var upperProp = property.charAt(0).toUpperCase() + property.slice(1); for (var i = 0; i < prefixes.length - 1; i++) { var prefix = prefixes[i]; var toCheck = prefix ? '' + prefix + upperProp : property; if (typeof window.document.body.style[toCheck] !== 'undefined') { return toCheck; } } return null; } /** * Destroy the popper * @method * @memberof Popper */ function destroy() { this.state.isDestroyed = true; // touch DOM only if `applyStyle` modifier is enabled if (isModifierEnabled(this.modifiers, 'applyStyle')) { this.popper.removeAttribute('x-placement'); this.popper.style.left = ''; this.popper.style.position = ''; this.popper.style.top = ''; this.popper.style[getSupportedPropertyName('transform')] = ''; } this.disableEventListeners(); // remove the popper if user explicity asked for the deletion on destroy // do not use `remove` because IE11 doesn't support it if (this.options.removeOnDestroy) { this.popper.parentNode.removeChild(this.popper); } return this; } function attachToScrollParents(scrollParent, event, callback, scrollParents) { var isBody = scrollParent.nodeName === 'BODY'; var target = isBody ? window : scrollParent; target.addEventListener(event, callback, { passive: true }); if (!isBody) { attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents); } scrollParents.push(target); } /** * Setup needed event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function setupEventListeners(reference, options, state, updateBound) { // Resize event listener on window state.updateBound = updateBound; window.addEventListener('resize', state.updateBound, { passive: true }); // Scroll event listener on scroll parents var scrollElement = getScrollParent(reference); attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents); state.scrollElement = scrollElement; state.eventsEnabled = true; return state; } /** * It will add resize/scroll events and start recalculating * position of the popper element when they are triggered. * @method * @memberof Popper */ function enableEventListeners() { if (!this.state.eventsEnabled) { this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate); } } /** * Remove event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function removeEventListeners(reference, state) { // Remove resize event listener on window window.removeEventListener('resize', state.updateBound); // Remove scroll event listener on scroll parents state.scrollParents.forEach(function (target) { target.removeEventListener('scroll', state.updateBound); }); // Reset state state.updateBound = null; state.scrollParents = []; state.scrollElement = null; state.eventsEnabled = false; return state; } /** * It will remove resize/scroll events and won't recalculate popper position * when they are triggered. It also won't trigger onUpdate callback anymore, * unless you call `update` method manually. * @method * @memberof Popper */ function disableEventListeners() { if (this.state.eventsEnabled) { window.cancelAnimationFrame(this.scheduleUpdate); this.state = removeEventListeners(this.reference, this.state); } } /** * Tells if a given input is a number * @method * @memberof Popper.Utils * @param {*} input to check * @return {Boolean} */ function isNumeric(n) { return n !== '' && !isNaN(parseFloat(n)) && isFinite(n); } /** * Set the style to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the style to * @argument {Object} styles * Object with a list of properties and values which will be applied to the element */ function setStyles(element, styles) { Object.keys(styles).forEach(function (prop) { var unit = ''; // add unit if the value is numeric and is one of the following if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { unit = 'px'; } element.style[prop] = styles[prop] + unit; }); } /** * Set the attributes to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the attributes to * @argument {Object} styles * Object with a list of properties and values which will be applied to the element */ function setAttributes(element, attributes) { Object.keys(attributes).forEach(function (prop) { var value = attributes[prop]; if (value !== false) { element.setAttribute(prop, attributes[prop]); } else { element.removeAttribute(prop); } }); } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} data.styles - List of style properties - values to apply to popper element * @argument {Object} data.attributes - List of attribute properties - values to apply to popper element * @argument {Object} options - Modifiers configuration and options * @returns {Object} The same data object */ function applyStyle(data) { // any property present in `data.styles` will be applied to the popper, // in this way we can make the 3rd party modifiers add custom styles to it // Be aware, modifiers could override the properties defined in the previous // lines of this modifier! setStyles(data.instance.popper, data.styles); // any property present in `data.attributes` will be applied to the popper, // they will be set as HTML attributes of the element setAttributes(data.instance.popper, data.attributes); // if arrowElement is defined and arrowStyles has some properties if (data.arrowElement && Object.keys(data.arrowStyles).length) { setStyles(data.arrowElement, data.arrowStyles); } return data; } /** * Set the x-placement attribute before everything else because it could be used * to add margins to the popper margins needs to be calculated to get the * correct popper offsets. * @method * @memberof Popper.modifiers * @param {HTMLElement} reference - The reference element used to position the popper * @param {HTMLElement} popper - The HTML element used as popper. * @param {Object} options - Popper.js options */ function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { // compute reference element offsets var referenceOffsets = getReferenceOffsets(state, popper, reference); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding); popper.setAttribute('x-placement', placement); // Apply `position` to popper before anything else because // without the position applied we can't guarantee correct computations setStyles(popper, { position: 'absolute' }); return options; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeStyle(data, options) { var x = options.x, y = options.y; var popper = data.offsets.popper; // Remove this legacy support in Popper.js v2 var legacyGpuAccelerationOption = find$1(data.instance.modifiers, function (modifier) { return modifier.name === 'applyStyle'; }).gpuAcceleration; if (legacyGpuAccelerationOption !== undefined) { console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!'); } var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration; var offsetParent = getOffsetParent(data.instance.popper); var offsetParentRect = getBoundingClientRect(offsetParent); // Styles var styles = { position: popper.position }; // floor sides to avoid blurry text var offsets = { left: Math.floor(popper.left), top: Math.floor(popper.top), bottom: Math.floor(popper.bottom), right: Math.floor(popper.right) }; var sideA = x === 'bottom' ? 'top' : 'bottom'; var sideB = y === 'right' ? 'left' : 'right'; // if gpuAcceleration is set to `true` and transform is supported, // we use `translate3d` to apply the position to the popper we // automatically use the supported prefixed version if needed var prefixedProperty = getSupportedPropertyName('transform'); // now, let's make a step back and look at this code closely (wtf?) // If the content of the popper grows once it's been positioned, it // may happen that the popper gets misplaced because of the new content // overflowing its reference element // To avoid this problem, we provide two options (x and y), which allow // the consumer to define the offset origin. // If we position a popper on top of a reference element, we can set // `x` to `top` to make the popper grow towards its top instead of // its bottom. var left = void 0, top = void 0; if (sideA === 'bottom') { top = -offsetParentRect.height + offsets.bottom; } else { top = offsets.top; } if (sideB === 'right') { left = -offsetParentRect.width + offsets.right; } else { left = offsets.left; } if (gpuAcceleration && prefixedProperty) { styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)'; styles[sideA] = 0; styles[sideB] = 0; styles.willChange = 'transform'; } else { // othwerise, we use the standard `top`, `left`, `bottom` and `right` properties var invertTop = sideA === 'bottom' ? -1 : 1; var invertLeft = sideB === 'right' ? -1 : 1; styles[sideA] = top * invertTop; styles[sideB] = left * invertLeft; styles.willChange = sideA + ', ' + sideB; } // Attributes var attributes = { 'x-placement': data.placement }; // Update `data` attributes, styles and arrowStyles data.attributes = _extends({}, attributes, data.attributes); data.styles = _extends({}, styles, data.styles); data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles); return data; } /** * Helper used to know if the given modifier depends from another one.<br /> * It checks if the needed modifier is listed and enabled. * @method * @memberof Popper.Utils * @param {Array} modifiers - list of modifiers * @param {String} requestingName - name of requesting modifier * @param {String} requestedName - name of requested modifier * @returns {Boolean} */ function isModifierRequired(modifiers, requestingName, requestedName) { var requesting = find$1(modifiers, function (_ref) { var name = _ref.name; return name === requestingName; }); var isRequired = !!requesting && modifiers.some(function (modifier) { return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order; }); if (!isRequired) { var _requesting = '`' + requestingName + '`'; var requested = '`' + requestedName + '`'; console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!'); } return isRequired; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function arrow(data, options) { // arrow depends on keepTogether in order to work if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) { return data; } var arrowElement = options.element; // if arrowElement is a string, suppose it's a CSS selector if (typeof arrowElement === 'string') { arrowElement = data.instance.popper.querySelector(arrowElement); // if arrowElement is not found, don't run the modifier if (!arrowElement) { return data; } } else { // if the arrowElement isn't a query selector we must check that the // provided DOM node is child of its popper node if (!data.instance.popper.contains(arrowElement)) { console.warn('WARNING: `arrow.element` must be child of its popper element!'); return data; } } var placement = data.placement.split('-')[0]; var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var isVertical = ['left', 'right'].indexOf(placement) !== -1; var len = isVertical ? 'height' : 'width'; var sideCapitalized = isVertical ? 'Top' : 'Left'; var side = sideCapitalized.toLowerCase(); var altSide = isVertical ? 'left' : 'top'; var opSide = isVertical ? 'bottom' : 'right'; var arrowElementSize = getOuterSizes(arrowElement)[len]; // // extends keepTogether behavior making sure the popper and its // reference have enough pixels in conjuction // // top/left side if (reference[opSide] - arrowElementSize < popper[side]) { data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize); } // bottom/right side if (reference[side] + arrowElementSize > popper[opSide]) { data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide]; } // compute center of the popper var center = reference[side] + reference[len] / 2 - arrowElementSize / 2; // Compute the sideValue using the updated popper offsets // take popper margin in account because we don't have this info available var popperMarginSide = getStyleComputedProperty(data.instance.popper, 'margin' + sideCapitalized).replace('px', ''); var sideValue = center - getClientRect(data.offsets.popper)[side] - popperMarginSide; // prevent arrowElement from being placed not contiguously to its popper sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0); data.arrowElement = arrowElement; data.offsets.arrow = {}; data.offsets.arrow[side] = Math.round(sideValue); data.offsets.arrow[altSide] = ''; // make sure to unset any eventual altSide value from the DOM node return data; } /** * Get the opposite placement variation of the given one * @method * @memberof Popper.Utils * @argument {String} placement variation * @returns {String} flipped placement variation */ function getOppositeVariation(variation) { if (variation === 'end') { return 'start'; } else if (variation === 'start') { return 'end'; } return variation; } /** * List of accepted placements to use as values of the `placement` option.<br /> * Valid placements are: * - `auto` * - `top` * - `right` * - `bottom` * - `left` * * Each placement can have a variation from this list: * - `-start` * - `-end` * * Variations are interpreted easily if you think of them as the left to right * written languages. Horizontally (`top` and `bottom`), `start` is left and `end` * is right.<br /> * Vertically (`left` and `right`), `start` is top and `end` is bottom. * * Some valid examples are: * - `top-end` (on top of reference, right aligned) * - `right-start` (on right of reference, top aligned) * - `bottom` (on bottom, centered) * - `auto-right` (on the side with more space available, alignment depends by placement) * * @static * @type {Array} * @enum {String} * @readonly * @method placements * @memberof Popper */ var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start']; // Get rid of `auto` `auto-start` and `auto-end` var validPlacements = placements.slice(3); /** * Given an initial placement, returns all the subsequent placements * clockwise (or counter-clockwise). * * @method * @memberof Popper.Utils * @argument {String} placement - A valid placement (it accepts variations) * @argument {Boolean} counter - Set to true to walk the placements counterclockwise * @returns {Array} placements including their variations */ function clockwise(placement) { var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var index = validPlacements.indexOf(placement); var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index)); return counter ? arr.reverse() : arr; } var BEHAVIORS = { FLIP: 'flip', CLOCKWISE: 'clockwise', COUNTERCLOCKWISE: 'counterclockwise' }; /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function flip(data, options) { // if `inner` modifier is enabled, we can't use the `flip` modifier if (isModifierEnabled(data.instance.modifiers, 'inner')) { return data; } if (data.flipped && data.placement === data.originalPlacement) { // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides return data; } var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement); var placement = data.placement.split('-')[0]; var placementOpposite = getOppositePlacement(placement); var variation = data.placement.split('-')[1] || ''; var flipOrder = []; switch (options.behavior) { case BEHAVIORS.FLIP: flipOrder = [placement, placementOpposite]; break; case BEHAVIORS.CLOCKWISE: flipOrder = clockwise(placement); break; case BEHAVIORS.COUNTERCLOCKWISE: flipOrder = clockwise(placement, true); break; default: flipOrder = options.behavior; } flipOrder.forEach(function (step, index) { if (placement !== step || flipOrder.length === index + 1) { return data; } placement = data.placement.split('-')[0]; placementOpposite = getOppositePlacement(placement); var popperOffsets = data.offsets.popper; var refOffsets = data.offsets.reference; // using floor because the reference offsets may contain decimals we are not going to consider here var floor = Math.floor; var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom); var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left); var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right); var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top); var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom); var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom; // flip the variation if required var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; var flippedVariation = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom); if (overlapsRef || overflowsBoundaries || flippedVariation) { // this boolean to detect any flip loop data.flipped = true; if (overlapsRef || overflowsBoundaries) { placement = flipOrder[index + 1]; } if (flippedVariation) { variation = getOppositeVariation(variation); } data.placement = placement + (variation ? '-' + variation : ''); // this object contains `position`, we want to preserve it along with // any additional property we may add in the future data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement)); data = runModifiers(data.instance.modifiers, data, 'flip'); } }); return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function keepTogether(data) { var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var placement = data.placement.split('-')[0]; var floor = Math.floor; var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; var side = isVertical ? 'right' : 'bottom'; var opSide = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; if (popper[side] < floor(reference[opSide])) { data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement]; } if (popper[opSide] > floor(reference[side])) { data.offsets.popper[opSide] = floor(reference[side]); } return data; } /** * Converts a string containing value + unit into a px value number * @function * @memberof {modifiers~offset} * @private * @argument {String} str - Value + unit string * @argument {String} measurement - `height` or `width` * @argument {Object} popperOffsets * @argument {Object} referenceOffsets * @returns {Number|String} * Value in pixels, or original string if no values were extracted */ function toValue(str, measurement, popperOffsets, referenceOffsets) { // separate value from unit var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/); var value = +split[1]; var unit = split[2]; // If it's not a number it's an operator, I guess if (!value) { return str; } if (unit.indexOf('%') === 0) { var element = void 0; switch (unit) { case '%p': element = popperOffsets; break; case '%': case '%r': default: element = referenceOffsets; } var rect = getClientRect(element); return rect[measurement] / 100 * value; } else if (unit === 'vh' || unit === 'vw') { // if is a vh or vw, we calculate the size based on the viewport var size = void 0; if (unit === 'vh') { size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); } else { size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); } return size / 100 * value; } else { // if is an explicit pixel unit, we get rid of the unit and keep the value // if is an implicit unit, it's px, and we return just the value return value; } } /** * Parse an `offset` string to extrapolate `x` and `y` numeric offsets. * @function * @memberof {modifiers~offset} * @private * @argument {String} offset * @argument {Object} popperOffsets * @argument {Object} referenceOffsets * @argument {String} basePlacement * @returns {Array} a two cells array with x and y offsets in numbers */ function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) { var offsets = [0, 0]; // Use height if placement is left or right and index is 0 otherwise use width // in this way the first offset will use an axis and the second one // will use the other one var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1; // Split the offset string to obtain a list of values and operands // The regex addresses values with the plus or minus sign in front (+10, -20, etc) var fragments = offset.split(/(\+|\-)/).map(function (frag) { return frag.trim(); }); // Detect if the offset string contains a pair of values or a single one // they could be separated by comma or space var divider = fragments.indexOf(find$1(fragments, function (frag) { return frag.search(/,|\s/) !== -1; })); if (fragments[divider] && fragments[divider].indexOf(',') === -1) { console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.'); } // If divider is found, we divide the list of values and operands to divide // them by ofset X and Y. var splitRegex = /\s*,\s*|\s+/; var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments]; // Convert the values with units to absolute pixels to allow our computations ops = ops.map(function (op, index) { // Most of the units rely on the orientation of the popper var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width'; var mergeWithPrevious = false; return op // This aggregates any `+` or `-` sign that aren't considered operators // e.g.: 10 + +5 => [10, +, +5] .reduce(function (a, b) { if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) { a[a.length - 1] = b; mergeWithPrevious = true; return a; } else if (mergeWithPrevious) { a[a.length - 1] += b; mergeWithPrevious = false; return a; } else { return a.concat(b); } }, []) // Here we convert the string values into number values (in px) .map(function (str) { return toValue(str, measurement, popperOffsets, referenceOffsets); }); }); // Loop trough the offsets arrays and execute the operations ops.forEach(function (op, index) { op.forEach(function (frag, index2) { if (isNumeric(frag)) { offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1); } }); }); return offsets; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @argument {Number|String} options.offset=0 * The offset value as described in the modifier description * @returns {Object} The data object, properly modified */ function offset(data, _ref) { var offset = _ref.offset; var placement = data.placement, _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var basePlacement = placement.split('-')[0]; var offsets = void 0; if (isNumeric(+offset)) { offsets = [+offset, 0]; } else { offsets = parseOffset(offset, popper, reference, basePlacement); } if (basePlacement === 'left') { popper.top += offsets[0]; popper.left -= offsets[1]; } else if (basePlacement === 'right') { popper.top += offsets[0]; popper.left += offsets[1]; } else if (basePlacement === 'top') { popper.left += offsets[0]; popper.top -= offsets[1]; } else if (basePlacement === 'bottom') { popper.left += offsets[0]; popper.top += offsets[1]; } data.popper = popper; return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function preventOverflow(data, options) { var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper); // If offsetParent is the reference element, we really want to // go one step up and use the next offsetParent as reference to // avoid to make this modifier completely useless and look like broken if (data.instance.reference === boundariesElement) { boundariesElement = getOffsetParent(boundariesElement); } var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement); options.boundaries = boundaries; var order = options.priority; var popper = data.offsets.popper; var check = { primary: function primary(placement) { var value = popper[placement]; if (popper[placement] < boundaries[placement] && !options.escapeWithReference) { value = Math.max(popper[placement], boundaries[placement]); } return defineProperty({}, placement, value); }, secondary: function secondary(placement) { var mainSide = placement === 'right' ? 'left' : 'top'; var value = popper[mainSide]; if (popper[placement] > boundaries[placement] && !options.escapeWithReference) { value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height)); } return defineProperty({}, mainSide, value); } }; order.forEach(function (placement) { var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary'; popper = _extends({}, popper, check[side](placement)); }); data.offsets.popper = popper; return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function shift(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var shiftvariation = placement.split('-')[1]; // if shift shiftvariation is specified, run the modifier if (shiftvariation) { var _data$offsets = data.offsets, reference = _data$offsets.reference, popper = _data$offsets.popper; var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1; var side = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; var shiftOffsets = { start: defineProperty({}, side, reference[side]), end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement]) }; data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]); } return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function hide(data) { if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) { return data; } var refRect = data.offsets.reference; var bound = find$1(data.instance.modifiers, function (modifier) { return modifier.name === 'preventOverflow'; }).boundaries; if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === true) { return data; } data.hide = true; data.attributes['x-out-of-boundaries'] = ''; } else { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === false) { return data; } data.hide = false; data.attributes['x-out-of-boundaries'] = false; } return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function inner(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1; var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1; popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0); data.placement = getOppositePlacement(placement); data.offsets.popper = getClientRect(popper); return data; } /** * Modifier function, each modifier can have a function of this type assigned * to its `fn` property.<br /> * These functions will be called on each update, this means that you must * make sure they are performant enough to avoid performance bottlenecks. * * @function ModifierFn * @argument {dataObject} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {dataObject} The data object, properly modified */ /** * Modifiers are plugins used to alter the behavior of your poppers.<br /> * Popper.js uses a set of 9 modifiers to provide all the basic functionalities * needed by the library. * * Usually you don't want to override the `order`, `fn` and `onLoad` props. * All the other properties are configurations that could be tweaked. * @namespace modifiers */ var modifiers = { /** * Modifier used to shift the popper on the start or end of its reference * element.<br /> * It will read the variation of the `placement` property.<br /> * It can be one either `-end` or `-start`. * @memberof modifiers * @inner */ shift: { /** @prop {number} order=100 - Index used to define the order of execution */ order: 100, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: shift }, /** * The `offset` modifier can shift your popper on both its axis. * * It accepts the following units: * - `px` or unitless, interpreted as pixels * - `%` or `%r`, percentage relative to the length of the reference element * - `%p`, percentage relative to the length of the popper element * - `vw`, CSS viewport width unit * - `vh`, CSS viewport height unit * * For length is intended the main axis relative to the placement of the popper.<br /> * This means that if the placement is `top` or `bottom`, the length will be the * `width`. In case of `left` or `right`, it will be the height. * * You can provide a single value (as `Number` or `String`), or a pair of values * as `String` divided by a comma or one (or more) white spaces.<br /> * The latter is a deprecated method because it leads to confusion and will be * removed in v2.<br /> * Additionally, it accepts additions and subtractions between different units. * Note that multiplications and divisions aren't supported. * * Valid examples are: * ``` * 10 * '10%' * '10, 10' * '10%, 10' * '10 + 10%' * '10 - 5vh + 3%' * '-10px + 5vh, 5px - 6%' * ``` * > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap * > with their reference element, unfortunately, you will have to disable the `flip` modifier. * > More on this [reading this issue](https://github.com/FezVrasta/popper.js/issues/373) * * @memberof modifiers * @inner */ offset: { /** @prop {number} order=200 - Index used to define the order of execution */ order: 200, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: offset, /** @prop {Number|String} offset=0 * The offset value as described in the modifier description */ offset: 0 }, /** * Modifier used to prevent the popper from being positioned outside the boundary. * * An scenario exists where the reference itself is not within the boundaries.<br /> * We can say it has "escaped the boundaries" — or just "escaped".<br /> * In this case we need to decide whether the popper should either: * * - detach from the reference and remain "trapped" in the boundaries, or * - if it should ignore the boundary and "escape with its reference" * * When `escapeWithReference` is set to`true` and reference is completely * outside its boundaries, the popper will overflow (or completely leave) * the boundaries in order to remain attached to the edge of the reference. * * @memberof modifiers * @inner */ preventOverflow: { /** @prop {number} order=300 - Index used to define the order of execution */ order: 300, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: preventOverflow, /** * @prop {Array} [priority=['left','right','top','bottom']] * Popper will try to prevent overflow following these priorities by default, * then, it could overflow on the left and on top of the `boundariesElement` */ priority: ['left', 'right', 'top', 'bottom'], /** * @prop {number} padding=5 * Amount of pixel used to define a minimum distance between the boundaries * and the popper this makes sure the popper has always a little padding * between the edges of its container */ padding: 5, /** * @prop {String|HTMLElement} boundariesElement='scrollParent' * Boundaries used by the modifier, can be `scrollParent`, `window`, * `viewport` or any DOM element. */ boundariesElement: 'scrollParent' }, /** * Modifier used to make sure the reference and its popper stay near eachothers * without leaving any gap between the two. Expecially useful when the arrow is * enabled and you want to assure it to point to its reference element. * It cares only about the first axis, you can still have poppers with margin * between the popper and its reference element. * @memberof modifiers * @inner */ keepTogether: { /** @prop {number} order=400 - Index used to define the order of execution */ order: 400, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: keepTogether }, /** * This modifier is used to move the `arrowElement` of the popper to make * sure it is positioned between the reference element and its popper element. * It will read the outer size of the `arrowElement` node to detect how many * pixels of conjuction are needed. * * It has no effect if no `arrowElement` is provided. * @memberof modifiers * @inner */ arrow: { /** @prop {number} order=500 - Index used to define the order of execution */ order: 500, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: arrow, /** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */ element: '[x-arrow]' }, /** * Modifier used to flip the popper's placement when it starts to overlap its * reference element. * * Requires the `preventOverflow` modifier before it in order to work. * * **NOTE:** this modifier will interrupt the current update cycle and will * restart it if it detects the need to flip the placement. * @memberof modifiers * @inner */ flip: { /** @prop {number} order=600 - Index used to define the order of execution */ order: 600, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: flip, /** * @prop {String|Array} behavior='flip' * The behavior used to change the popper's placement. It can be one of * `flip`, `clockwise`, `counterclockwise` or an array with a list of valid * placements (with optional variations). */ behavior: 'flip', /** * @prop {number} padding=5 * The popper will flip if it hits the edges of the `boundariesElement` */ padding: 5, /** * @prop {String|HTMLElement} boundariesElement='viewport' * The element which will define the boundaries of the popper position, * the popper will never be placed outside of the defined boundaries * (except if keepTogether is enabled) */ boundariesElement: 'viewport' }, /** * Modifier used to make the popper flow toward the inner of the reference element. * By default, when this modifier is disabled, the popper will be placed outside * the reference element. * @memberof modifiers * @inner */ inner: { /** @prop {number} order=700 - Index used to define the order of execution */ order: 700, /** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */ enabled: false, /** @prop {ModifierFn} */ fn: inner }, /** * Modifier used to hide the popper when its reference element is outside of the * popper boundaries. It will set a `x-out-of-boundaries` attribute which can * be used to hide with a CSS selector the popper when its reference is * out of boundaries. * * Requires the `preventOverflow` modifier before it in order to work. * @memberof modifiers * @inner */ hide: { /** @prop {number} order=800 - Index used to define the order of execution */ order: 800, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: hide }, /** * Computes the style that will be applied to the popper element to gets * properly positioned. * * Note that this modifier will not touch the DOM, it just prepares the styles * so that `applyStyle` modifier can apply it. This separation is useful * in case you need to replace `applyStyle` with a custom implementation. * * This modifier has `850` as `order` value to maintain backward compatibility * with previous versions of Popper.js. Expect the modifiers ordering method * to change in future major versions of the library. * * @memberof modifiers * @inner */ computeStyle: { /** @prop {number} order=850 - Index used to define the order of execution */ order: 850, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: computeStyle, /** * @prop {Boolean} gpuAcceleration=true * If true, it uses the CSS 3d transformation to position the popper. * Otherwise, it will use the `top` and `left` properties. */ gpuAcceleration: true, /** * @prop {string} [x='bottom'] * Where to anchor the X axis (`bottom` or `top`). AKA X offset origin. * Change this if your popper should grow in a direction different from `bottom` */ x: 'bottom', /** * @prop {string} [x='left'] * Where to anchor the Y axis (`left` or `right`). AKA Y offset origin. * Change this if your popper should grow in a direction different from `right` */ y: 'right' }, /** * Applies the computed styles to the popper element. * * All the DOM manipulations are limited to this modifier. This is useful in case * you want to integrate Popper.js inside a framework or view library and you * want to delegate all the DOM manipulations to it. * * Note that if you disable this modifier, you must make sure the popper element * has its position set to `absolute` before Popper.js can do its work! * * Just disable this modifier and define you own to achieve the desired effect. * * @memberof modifiers * @inner */ applyStyle: { /** @prop {number} order=900 - Index used to define the order of execution */ order: 900, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: applyStyle, /** @prop {Function} */ onLoad: applyStyleOnLoad, /** * @deprecated since version 1.10.0, the property moved to `computeStyle` modifier * @prop {Boolean} gpuAcceleration=true * If true, it uses the CSS 3d transformation to position the popper. * Otherwise, it will use the `top` and `left` properties. */ gpuAcceleration: undefined } }; /** * The `dataObject` is an object containing all the informations used by Popper.js * this object get passed to modifiers and to the `onCreate` and `onUpdate` callbacks. * @name dataObject * @property {Object} data.instance The Popper.js instance * @property {String} data.placement Placement applied to popper * @property {String} data.originalPlacement Placement originally defined on init * @property {Boolean} data.flipped True if popper has been flipped by flip modifier * @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper. * @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier * @property {Object} data.styles Any CSS property defined here will be applied to the popper, it expects the JavaScript nomenclature (eg. `marginBottom`) * @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow, it expects the JavaScript nomenclature (eg. `marginBottom`) * @property {Object} data.boundaries Offsets of the popper boundaries * @property {Object} data.offsets The measurements of popper, reference and arrow elements. * @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values * @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values * @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0 */ /** * Default options provided to Popper.js constructor.<br /> * These can be overriden using the `options` argument of Popper.js.<br /> * To override an option, simply pass as 3rd argument an object with the same * structure of this object, example: * ``` * new Popper(ref, pop, { * modifiers: { * preventOverflow: { enabled: false } * } * }) * ``` * @type {Object} * @static * @memberof Popper */ var Defaults$1 = { /** * Popper's placement * @prop {Popper.placements} placement='bottom' */ placement: 'bottom', /** * Whether events (resize, scroll) are initially enabled * @prop {Boolean} eventsEnabled=true */ eventsEnabled: true, /** * Set to true if you want to automatically remove the popper when * you call the `destroy` method. * @prop {Boolean} removeOnDestroy=false */ removeOnDestroy: false, /** * Callback called when the popper is created.<br /> * By default, is set to no-op.<br /> * Access Popper.js instance with `data.instance`. * @prop {onCreate} */ onCreate: function onCreate() {}, /** * Callback called when the popper is updated, this callback is not called * on the initialization/creation of the popper, but only on subsequent * updates.<br /> * By default, is set to no-op.<br /> * Access Popper.js instance with `data.instance`. * @prop {onUpdate} */ onUpdate: function onUpdate() {}, /** * List of modifiers used to modify the offsets before they are applied to the popper. * They provide most of the functionalities of Popper.js * @prop {modifiers} */ modifiers: modifiers }; /** * @callback onCreate * @param {dataObject} data */ /** * @callback onUpdate * @param {dataObject} data */ // Utils // Methods var Popper = function () { /** * Create a new Popper.js instance * @class Popper * @param {HTMLElement|referenceObject} reference - The reference element used to position the popper * @param {HTMLElement} popper - The HTML element used as popper. * @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults) * @return {Object} instance - The generated Popper.js instance */ function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck(this, Popper); this.scheduleUpdate = function () { return requestAnimationFrame(_this.update); }; // make update() debounced, so that it only runs at most once-per-tick this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it this.options = _extends({}, Popper.Defaults, options); // init state this.state = { isDestroyed: false, isCreated: false, scrollParents: [] }; // get reference and popper elements (allow jQuery wrappers) this.reference = reference.jquery ? reference[0] : reference; this.popper = popper.jquery ? popper[0] : popper; // Deep merge modifiers options this.options.modifiers = {}; Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) { _this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {}); }); // Refactoring modifiers' list (Object => Array) this.modifiers = Object.keys(this.options.modifiers).map(function (name) { return _extends({ name: name }, _this.options.modifiers[name]); }) // sort the modifiers by order .sort(function (a, b) { return a.order - b.order; }); // modifiers have the ability to execute arbitrary code when Popper.js get inited // such code is executed in the same order of its modifier // they could add new properties to their options configuration // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! this.modifiers.forEach(function (modifierOptions) { if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) { modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); } }); // fire the first update to position the popper in the right place this.update(); var eventsEnabled = this.options.eventsEnabled; if (eventsEnabled) { // setup event listeners, they will take care of update the position in specific situations this.enableEventListeners(); } this.state.eventsEnabled = eventsEnabled; } // We can't use class properties because they don't get listed in the // class prototype and break stuff like Sinon stubs createClass(Popper, [{ key: 'update', value: function update$$1() { return update.call(this); } }, { key: 'destroy', value: function destroy$$1() { return destroy.call(this); } }, { key: 'enableEventListeners', value: function enableEventListeners$$1() { return enableEventListeners.call(this); } }, { key: 'disableEventListeners', value: function disableEventListeners$$1() { return disableEventListeners.call(this); } /** * Schedule an update, it will run on the next UI update available * @method scheduleUpdate * @memberof Popper */ /** * Collection of utilities useful when writing custom modifiers. * Starting from version 1.7, this method is available only if you * include `popper-utils.js` before `popper.js`. * * **DEPRECATION**: This way to access PopperUtils is deprecated * and will be removed in v2! Use the PopperUtils module directly instead. * Due to the high instability of the methods contained in Utils, we can't * guarantee them to follow semver. Use them at your own risk! * @static * @private * @type {Object} * @deprecated since version 1.8 * @member Utils * @memberof Popper */ }]); return Popper; }(); /** * The `referenceObject` is an object that provides an interface compatible with Popper.js * and lets you use it as replacement of a real DOM node.<br /> * You can use this method to position a popper relatively to a set of coordinates * in case you don't have a DOM node to use as reference. * * ``` * new Popper(referenceObject, popperNode); * ``` * * NB: This feature isn't supported in Internet Explorer 10 * @name referenceObject * @property {Function} data.getBoundingClientRect * A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method. * @property {number} data.clientWidth * An ES6 getter that will return the width of the virtual reference element. * @property {number} data.clientHeight * An ES6 getter that will return the height of the virtual reference element. */ Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils; Popper.placements = placements; Popper.Defaults = Defaults$1; /** * Returns the distance taking into account the default distance due to * the transform: translate setting in CSS * @param {Number} distance * @return {String} */ function getOffsetDistanceInPx(distance) { return -(distance - Defaults.distance) + 'px'; } var classCallCheck$1 = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass$1 = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _extends$1 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /** * Creates a new popper instance * @param {Object} data * @return {Object} - the popper instance */ function createPopperInstance(data) { var el = data.el, popper = data.popper, _data$settings = data.settings, position = _data$settings.position, popperOptions = _data$settings.popperOptions, offset = _data$settings.offset, distance = _data$settings.distance, flipDuration = _data$settings.flipDuration; var _getInnerElements = getInnerElements(popper), tooltip = _getInnerElements.tooltip; var config = _extends$1({ placement: position }, popperOptions || {}, { modifiers: _extends$1({}, popperOptions ? popperOptions.modifiers : {}, { flip: _extends$1({ padding: distance + 5 /* 5px from viewport boundary */ }, popperOptions && popperOptions.modifiers ? popperOptions.modifiers.flip : {}), offset: _extends$1({ offset: offset }, popperOptions && popperOptions.modifiers ? popperOptions.modifiers.offset : {}) }), onUpdate: function onUpdate() { var styles = tooltip.style; styles.top = ''; styles.bottom = ''; styles.left = ''; styles.right = ''; styles[getCorePlacement(popper.getAttribute('x-placement'))] = getOffsetDistanceInPx(distance); } }); // Update the popper's position whenever its content changes // Not supported in IE10 unless polyfilled if (window.MutationObserver) { var styles = popper.style; var observer = new MutationObserver(function () { styles[prefix('transitionDuration')] = '0ms'; data.popperInstance.update(); defer(function () { styles[prefix('transitionDuration')] = flipDuration + 'ms'; }); }); observer.observe(popper, { childList: true, subtree: true, characterData: true }); data._mutationObservers.push(observer); } return new Popper(el, popper, config); } /** * Appends the popper and creates a popper instance if one does not exist * Also updates its position if need be and enables event listeners * @param {Object} data - the element/popper reference data */ function mountPopper(data) { var el = data.el, popper = data.popper, _data$settings = data.settings, appendTo = _data$settings.appendTo, followCursor = _data$settings.followCursor; // Already on the DOM if (appendTo.contains(popper)) return; appendTo.appendChild(popper); if (!data.popperInstance) { data.popperInstance = createPopperInstance(data); } else { data.popperInstance.update(); if (!followCursor || Browser.touch) { data.popperInstance.enableEventListeners(); } } // Since touch is determined dynamically, followCursor is set on mount if (followCursor && !Browser.touch) { el.addEventListener('mousemove', followCursorHandler); data.popperInstance.disableEventListeners(); } } /** * Updates a popper's position on each animation frame to make it stick to a moving element * @param {Object} refData */ function makeSticky(refData) { var popper = refData.popper, popperInstance = refData.popperInstance, stickyDuration = refData.settings.stickyDuration; var applyTransitionDuration = function applyTransitionDuration() { return popper.style[prefix('transitionDuration')] = stickyDuration + 'ms'; }; var removeTransitionDuration = function removeTransitionDuration() { return popper.style[prefix('transitionDuration')] = ''; }; var updatePosition = function updatePosition() { popperInstance && popperInstance.scheduleUpdate(); applyTransitionDuration(); isVisible(popper) ? window.requestAnimationFrame(updatePosition) : removeTransitionDuration(); }; // Wait until Popper's position has been updated initially defer(updatePosition); } /** * Returns an object of settings to override global settings * @param {Element} el - the tooltipped element * @param {Object} instanceSettings * @return {Object} - individual settings */ function getIndividualSettings(el, instanceSettings) { var settings = DefaultsKeys.reduce(function (acc, key) { var val = el.getAttribute('data-' + key.toLowerCase()) || instanceSettings[key]; // Convert strings to booleans if (val === 'false') val = false; if (val === 'true') val = true; // Convert number strings to true numbers if (isFinite(val) && !isNaN(parseFloat(val))) { val = parseFloat(val); } // Convert array strings to actual arrays if (typeof val === 'string' && val.trim().charAt(0) === '[') { val = JSON.parse(val); } acc[key] = val; return acc; }, {}); return _extends$1({}, instanceSettings, settings); } /** * Creates a popper element then returns it * @param {Number} id - the popper id * @param {String} title - the tooltip's `title` attribute * @param {Object} settings - individual settings * @return {Element} - the popper element */ function createPopperElement(id, title, settings) { var position = settings.position, distance = settings.distance, arrow = settings.arrow, animateFill = settings.animateFill, inertia = settings.inertia, animation = settings.animation, arrowSize = settings.arrowSize, size = settings.size, theme = settings.theme, html = settings.html, zIndex = settings.zIndex, interactive = settings.interactive; var popper = document.createElement('div'); popper.setAttribute('class', 'tippy-popper'); popper.setAttribute('role', 'tooltip'); popper.setAttribute('aria-hidden', 'true'); popper.setAttribute('id', 'tippy-tooltip-' + id); popper.style.zIndex = zIndex; var tooltip = document.createElement('div'); tooltip.setAttribute('class', 'tippy-tooltip tippy-tooltip--' + size + ' leave'); tooltip.setAttribute('data-animation', animation); theme.split(' ').forEach(function (t) { tooltip.classList.add(t + '-theme'); }); if (arrow) { // Add an arrow var _arrow = document.createElement('div'); _arrow.setAttribute('class', 'arrow-' + arrowSize); _arrow.setAttribute('x-arrow', ''); tooltip.appendChild(_arrow); } if (animateFill) { // Create animateFill circle element for animation tooltip.setAttribute('data-animatefill', ''); var circle = document.createElement('div'); circle.setAttribute('class', 'leave'); circle.setAttribute('x-circle', ''); tooltip.appendChild(circle); } if (inertia) { // Change transition timing function cubic bezier tooltip.setAttribute('data-inertia', ''); } if (interactive) { tooltip.setAttribute('data-interactive', ''); } // Tooltip content (text or HTML) var content = document.createElement('div'); content.setAttribute('class', 'tippy-tooltip-content'); if (html) { var templateId = void 0; if (html instanceof Element) { content.appendChild(html); templateId = '#' + html.id || 'tippy-html-template'; } else { content.innerHTML = document.getElementById(html.replace('#', '')).innerHTML; templateId = html; } popper.classList.add('html-template'); interactive && popper.setAttribute('tabindex', '-1'); tooltip.setAttribute('data-template-id', templateId); } else { content.innerHTML = title; } // Init distance. Further updates are made in the popper instance's `onUpdate()` method tooltip.style[getCorePlacement(position)] = getOffsetDistanceInPx(distance); tooltip.appendChild(content); popper.appendChild(tooltip); return popper; } /** * Creates a trigger * @param {Object} event - the custom event specified in the `trigger` setting * @param {Element} el - tooltipped element * @param {Object} handlers - the handlers for each listener * @param {Boolean} touchHold * @return {Array} - array of listener objects */ function createTrigger(event, el, handlers, touchHold) { var listeners = []; if (event === 'manual') return listeners; // Enter el.addEventListener(event, handlers.handleTrigger); listeners.push({ event: event, handler: handlers.handleTrigger }); // Leave if (event === 'mouseenter') { if (Browser.SUPPORTS_TOUCH && touchHold) { el.addEventListener('touchstart', handlers.handleTrigger); listeners.push({ event: 'touchstart', handler: handlers.handleTrigger }); el.addEventListener('touchend', handlers.handleMouseleave); listeners.push({ event: 'touchend', handler: handlers.handleMouseleave }); } el.addEventListener('mouseleave', handlers.handleMouseleave); listeners.push({ event: 'mouseleave', handler: handlers.handleMouseleave }); } if (event === 'focus') { el.addEventListener('blur', handlers.handleBlur); listeners.push({ event: 'blur', handler: handlers.handleBlur }); } return listeners; } /** * Determines if the mouse's cursor is outside the interactive border * @param {MouseEvent} event * @param {Element} popper * @param {Object} settings * @return {Boolean} */ function cursorIsOutsideInteractiveBorder(event, popper, settings) { if (!popper.getAttribute('x-placement')) return true; var x = event.clientX, y = event.clientY; var interactiveBorder = settings.interactiveBorder, distance = settings.distance; var rect = popper.getBoundingClientRect(); var corePosition = getCorePlacement(popper.getAttribute('x-placement')); var borderWithDistance = interactiveBorder + distance; var exceeds = { top: rect.top - y > interactiveBorder, bottom: y - rect.bottom > interactiveBorder, left: rect.left - x > interactiveBorder, right: x - rect.right > interactiveBorder }; switch (corePosition) { case 'top': exceeds.top = rect.top - y > borderWithDistance; break; case 'bottom': exceeds.bottom = y - rect.bottom > borderWithDistance; break; case 'left': exceeds.left = rect.left - x > borderWithDistance; break; case 'right': exceeds.right = x - rect.right > borderWithDistance; break; } return exceeds.top || exceeds.bottom || exceeds.left || exceeds.right; } /** * Returns relevant listener callbacks for each ref * @param {Element} el * @param {Element} popper * @param {Object} settings * @return {Object} - relevant listener handlers */ function getEventListenerHandlers(el, popper, settings) { var _this = this; var position = settings.position, delay = settings.delay, duration = settings.duration, interactive = settings.interactive, interactiveBorder = settings.interactiveBorder, distance = settings.distance, hideOnClick = settings.hideOnClick, trigger = settings.trigger, touchHold = settings.touchHold, touchWait = settings.touchWait; var showDelay = void 0, hideDelay = void 0; var clearTimeouts = function clearTimeouts() { clearTimeout(showDelay); clearTimeout(hideDelay); }; var _show = function _show() { clearTimeouts(); // Not hidden. For clicking when it also has a `focus` event listener if (isVisible(popper)) return; var _delay = Array.isArray(delay) ? delay[0] : delay; if (delay) { showDelay = setTimeout(function () { return _this.show(popper); }, _delay); } else { _this.show(popper); } }; var show = function show(event) { return _this.callbacks.wait ? _this.callbacks.wait.call(popper, _show, event) : _show(); }; var hide = function hide() { clearTimeouts(); var _delay = Array.isArray(delay) ? delay[1] : delay; if (delay) { hideDelay = setTimeout(function () { return _this.hide(popper); }, _delay); } else { _this.hide(popper); } }; var handleTrigger = function handleTrigger(event) { var mouseenterTouch = event.type === 'mouseenter' && Browser.SUPPORTS_TOUCH && Browser.touch; if (mouseenterTouch && touchHold) return; // Toggle show/hide when clicking click-triggered tooltips var isClick = event.type === 'click'; var isNotPersistent = hideOnClick !== 'persistent'; isClick && isVisible(popper) && isNotPersistent ? hide() : show(event); if (mouseenterTouch && Browser.iOS() && el.click) { el.click(); } }; var handleMouseleave = function handleMouseleave(event) { // Don't fire 'mouseleave', use the 'touchend' if (event.type === 'mouseleave' && Browser.SUPPORTS_TOUCH && Browser.touch && touchHold) { return; } if (interactive) { // Temporarily handle mousemove to check if the mouse left somewhere // other than its popper var handleMousemove = function handleMousemove(event) { var triggerHide = function triggerHide() { document.body.removeEventListener('mouseleave', hide); document.removeEventListener('mousemove', handleMousemove); hide(); }; var closestTooltippedEl = closest(event.target, Selectors.TOOLTIPPED_EL); var isOverPopper = closest(event.target, Selectors.POPPER) === popper; var isOverEl = closestTooltippedEl === el; var isClickTriggered = trigger.indexOf('click') !== -1; var isOverOtherTooltippedEl = closestTooltippedEl && closestTooltippedEl !== el; if (isOverOtherTooltippedEl) { return triggerHide(); } if (isOverPopper || isOverEl || isClickTriggered) return; if (cursorIsOutsideInteractiveBorder(event, popper, settings)) { triggerHide(); } }; document.body.addEventListener('mouseleave', hide); document.addEventListener('mousemove', handleMousemove); return; } // If it's not interactive, just hide it hide(); }; var handleBlur = function handleBlur(event) { // Ignore blur on touch devices, if there is no `relatedTarget`, hide // If the related target is a popper, ignore if (!event.relatedTarget || Browser.touch) return; if (closest(event.relatedTarget, Selectors.POPPER)) return; hide(); }; return { handleTrigger: handleTrigger, handleMouseleave: handleMouseleave, handleBlur: handleBlur }; } /** * Evaluates/modifies the settings object for appropriate behavior * @param {Object} settings * @return {Object} modified/evaluated settings */ function evaluateSettings(settings) { // animateFill is disabled if an arrow is true if (settings.arrow) { settings.animateFill = false; } // reassign appendTo into the result of evaluating appendTo // if it's set as a function instead of Element if (settings.appendTo && typeof settings.appendTo === 'function') { settings.appendTo = settings.appendTo(); } return settings; } var idCounter = 1; /** * Creates tooltips for all el elements that match the instance's selector * @param {Element[]} els * @return {Object[]} Array of ref data objects */ function createTooltips(els) { var _this = this; return els.reduce(function (acc, el) { var id = idCounter; var settings = _extends$1({}, evaluateSettings(_this.settings.performance ? _this.settings : getIndividualSettings(el, _this.settings))); if (typeof settings.html === 'function') settings.html = settings.html(el); var html = settings.html, trigger = settings.trigger, touchHold = settings.touchHold, dynamicTitle = settings.dynamicTitle; var title = el.getAttribute('title'); if (!title && !html) return acc; el.setAttribute('data-tooltipped', ''); el.setAttribute('aria-describedby', 'tippy-tooltip-' + id); removeTitle(el); var popper = createPopperElement(id, title, settings); var handlers = getEventListenerHandlers.call(_this, el, popper, settings); var listeners = []; trigger.trim().split(' ').forEach(function (event) { return listeners = listeners.concat(createTrigger(event, el, handlers, touchHold)); }); // Add a mutation observer to observe the reference element for `title` // attribute changes, then automatically update tooltip content var observer = void 0; if (dynamicTitle && window.MutationObserver) { var _getInnerElements = getInnerElements(popper), content = _getInnerElements.content; observer = new MutationObserver(function () { var title = el.getAttribute('title'); if (title) { content.innerHTML = title; removeTitle(el); } }); observer.observe(el, { attributes: true }); } acc.push({ id: id, el: el, popper: popper, settings: settings, listeners: listeners, tippyInstance: _this, _mutationObservers: [observer] }); idCounter++; return acc; }, []); } /* Utility functions */ /* Core library functions */ /** * @param {String|Element|Element[]} selector * @param {Object} settings (optional) - the object of settings to be applied to the instance */ var Tippy = function () { function Tippy(selector) { var settings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; classCallCheck$1(this, Tippy); // Use default browser tooltip on unsupported browsers if (!Browser.SUPPORTED) return; init(); this.state = { destroyed: false }; this.selector = selector; this.settings = _extends$1({}, Defaults, settings); if (settings.show || settings.shown || settings.hide || settings.hidden) { console.warn('Callbacks without the `on` prefix are deprecated (with the exception of `wait`).' + ' Use onShow, onShown, onHide, and onHidden instead.'); } this.callbacks = { wait: settings.wait, show: settings.onShow || settings.show || noop, shown: settings.onShown || settings.shown || noop, hide: settings.onHide || settings.hide || noop, hidden: settings.onHidden || settings.hidden || noop }; this.store = createTooltips.call(this, getArrayOfElements(selector)); Store.push.apply(Store, this.store); } /** * Returns the reference element's popper element * @param {Element} el * @return {Element} */ createClass$1(Tippy, [{ key: 'getPopperElement', value: function getPopperElement(el) { try { return find(this.store, function (data) { return data.el === el; }).popper; } catch (e) { console.error('[getPopperElement]: Element passed as the argument does not exist in the instance'); } } /** * Returns a popper's reference element * @param {Element} popper * @return {Element} */ }, { key: 'getReferenceElement', value: function getReferenceElement(popper) { try { return find(this.store, function (data) { return data.popper === popper; }).el; } catch (e) { console.error('[getReferenceElement]: Popper passed as the argument does not exist in the instance'); } } /** * Returns the reference data object from either the reference element or popper element * @param {Element} x (reference element or popper) * @return {Object} */ }, { key: 'getReferenceData', value: function getReferenceData(x) { return find(this.store, function (data) { return data.el === x || data.popper === x; }); } /** * Shows a popper * @param {Element} popper * @param {Number} customDuration (optional) */ }, { key: 'show', value: function show(popper, customDuration) { var _this = this; if (this.state.destroyed) return; var data = find(this.store, function (data) { return data.popper === popper; }); var _getInnerElements = getInnerElements(popper), tooltip = _getInnerElements.tooltip, circle = _getInnerElements.circle, content = _getInnerElements.content; if (!document.body.contains(data.el)) { this.destroy(popper); return; } this.callbacks.show.call(popper); var el = data.el, _data$settings = data.settings, appendTo = _data$settings.appendTo, sticky = _data$settings.sticky, interactive = _data$settings.interactive, followCursor = _data$settings.followCursor, flipDuration = _data$settings.flipDuration, duration = _data$settings.duration; var _duration = customDuration !== undefined ? customDuration : Array.isArray(duration) ? duration[0] : duration; // Prevent a transition when popper changes position applyTransitionDuration([popper, tooltip, circle], 0); mountPopper(data); popper.style.visibility = 'visible'; popper.setAttribute('aria-hidden', 'false'); // Wait for popper's position to update defer(function () { if (!isVisible(popper)) return; // Sometimes the arrow will not be in the correct position, force another update if (!followCursor || Browser.touch) { data.popperInstance.update(); applyTransitionDuration([popper], flipDuration); } // Re-apply transition durations applyTransitionDuration([tooltip, circle], _duration); // Make content fade out a bit faster than the tooltip if `animateFill` if (circle) content.style.opacity = 1; // Interactive tooltips receive a class of 'active' interactive && el.classList.add('active'); // Update popper's position on every animation frame sticky && makeSticky(data); // Repaint/reflow is required for CSS transition when appending triggerReflow(tooltip, circle); modifyClassList([tooltip, circle], function (list) { list.contains('tippy-notransition') && list.remove('tippy-notransition'); list.remove('leave'); list.add('enter'); }); // Wait for transitions to complete onTransitionEnd(data, _duration, function () { if (!isVisible(popper) || data._onShownFired) return; // Focus interactive tooltips only interactive && popper.focus(); // Remove transitions from tooltip tooltip.classList.add('tippy-notransition'); // Prevents shown() from firing more than once from early transition cancellations data._onShownFired = true; _this.callbacks.shown.call(popper); }); }); } /** * Hides a popper * @param {Element} popper * @param {Number} customDuration (optional) */ }, { key: 'hide', value: function hide(popper, customDuration) { var _this2 = this; if (this.state.destroyed) return; this.callbacks.hide.call(popper); var data = find(this.store, function (data) { return data.popper === popper; }); var _getInnerElements2 = getInnerElements(popper), tooltip = _getInnerElements2.tooltip, circle = _getInnerElements2.circle, content = _getInnerElements2.content; var el = data.el, _data$settings2 = data.settings, appendTo = _data$settings2.appendTo, sticky = _data$settings2.sticky, interactive = _data$settings2.interactive, followCursor = _data$settings2.followCursor, html = _data$settings2.html, trigger = _data$settings2.trigger, duration = _data$settings2.duration; var _duration = customDuration !== undefined ? customDuration : Array.isArray(duration) ? duration[1] : duration; data._onShownFired = false; interactive && el.classList.remove('active'); popper.style.visibility = 'hidden'; popper.setAttribute('aria-hidden', 'true'); applyTransitionDuration([tooltip, circle, circle ? content : null], _duration); if (circle) content.style.opacity = 0; modifyClassList([tooltip, circle], function (list) { list.contains('tippy-tooltip') && list.remove('tippy-notransition'); list.remove('enter'); list.add('leave'); }); // Re-focus click-triggered html elements // and the tooltipped element IS in the viewport (otherwise it causes unsightly scrolling // if the tooltip is closed and the element isn't in the viewport anymore) if (html && trigger.indexOf('click') !== -1 && elementIsInViewport(el)) { el.focus(); } // Wait for transitions to complete onTransitionEnd(data, _duration, function () { // `isVisible` is not completely reliable to determine if we shouldn't // run the hidden callback, we need to check the computed opacity style. // This prevents glitchy behavior of the transition when quickly showing // and hiding a tooltip. if (isVisible(popper) || !appendTo.contains(popper) || getComputedStyle(tooltip).opacity === '1') return; el.removeEventListener('mousemove', followCursorHandler); data.popperInstance.disableEventListeners(); appendTo.removeChild(popper); _this2.callbacks.hidden.call(popper); }); } /** * Updates a popper with new content * @param {Element} popper */ }, { key: 'update', value: function update(popper) { if (this.state.destroyed) return; var data = find(this.store, function (data) { return data.popper === popper; }); var _getInnerElements3 = getInnerElements(popper), content = _getInnerElements3.content; var el = data.el, html = data.settings.html; if (html instanceof Element) { console.warn('Aborted: update() should not be used if `html` is a DOM element'); return; } content.innerHTML = html ? document.getElementById(html.replace('#', '')).innerHTML : el.getAttribute('title') || el.getAttribute('data-original-title'); if (!html) removeTitle(el); } /** * Destroys a popper * @param {Element} popper * @param {Boolean} _isLast - private param used by destroyAll to optimize */ }, { key: 'destroy', value: function destroy(popper, _isLast) { var _this3 = this; if (this.state.destroyed) return; var data = find(this.store, function (data) { return data.popper === popper; }); var el = data.el, popperInstance = data.popperInstance, listeners = data.listeners, _mutationObservers = data._mutationObservers; // Ensure the popper is hidden if (isVisible(popper)) { this.hide(popper, 0); } // Remove Tippy-only event listeners from tooltipped element listeners.forEach(function (listener) { return el.removeEventListener(listener.event, listener.handler); }); // Restore original title el.setAttribute('title', el.getAttribute('data-original-title')); el.removeAttribute('data-original-title'); el.removeAttribute('data-tooltipped'); el.removeAttribute('aria-describedby'); popperInstance && popperInstance.destroy(); _mutationObservers.forEach(function (observer) { observer && observer.disconnect(); }); // Remove from store Store.splice(findIndex(Store, function (data) { return data.popper === popper; }), 1); // Ensure filter is called only once if (_isLast === undefined || _isLast) { this.store = Store.filter(function (data) { return data.tippyInstance === _this3; }); } } /** * Destroys all tooltips created by the instance */ }, { key: 'destroyAll', value: function destroyAll() { var _this4 = this; if (this.state.destroyed) return; var storeLength = this.store.length; this.store.forEach(function (_ref, index) { var popper = _ref.popper; _this4.destroy(popper, index === storeLength - 1); }); this.store = null; this.state.destroyed = true; } }]); return Tippy; }(); function tippy$2(selector, settings) { return new Tippy(selector, settings); } tippy$2.Browser = Browser; tippy$2.Defaults = Defaults; tippy$2.disableDynamicInputDetection = function () { return Browser.dynamicInputDetection = false; }; tippy$2.enableDynamicInputDetection = function () { return Browser.dynamicInputDetection = true; }; return tippy$2; })));
import Route from 'ember-route'; export default Route.extend({ beforeModel() { this._super(...arguments); this.transitionTo('editor.new'); } });
describe("module:ng.directive:ngPluralize", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("./examples/example-example40/index-jquery.html"); }); it('should show correct pluralized string', function() { var withoutOffset = element.all(by.css('ng-pluralize')).get(0); var withOffset = element.all(by.css('ng-pluralize')).get(1); var countInput = element(by.model('personCount')); expect(withoutOffset.getText()).toEqual('1 person is viewing.'); expect(withOffset.getText()).toEqual('Igor is viewing.'); countInput.clear(); countInput.sendKeys('0'); expect(withoutOffset.getText()).toEqual('Nobody is viewing.'); expect(withOffset.getText()).toEqual('Nobody is viewing.'); countInput.clear(); countInput.sendKeys('2'); expect(withoutOffset.getText()).toEqual('2 people are viewing.'); expect(withOffset.getText()).toEqual('Igor and Misko are viewing.'); countInput.clear(); countInput.sendKeys('3'); expect(withoutOffset.getText()).toEqual('3 people are viewing.'); expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.'); countInput.clear(); countInput.sendKeys('4'); expect(withoutOffset.getText()).toEqual('4 people are viewing.'); expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.'); }); it('should show data-bound names', function() { var withOffset = element.all(by.css('ng-pluralize')).get(1); var personCount = element(by.model('personCount')); var person1 = element(by.model('person1')); var person2 = element(by.model('person2')); personCount.clear(); personCount.sendKeys('4'); person1.clear(); person1.sendKeys('Di'); person2.clear(); person2.sendKeys('Vojta'); expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.'); }); });
ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction" }, {token : "comment.start.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], processing_instruction : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : tagRegex }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.end.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : tagRegex }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ]; this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getSelectionRange().start; var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); if (token.value == "<") { token = iterator.stepForward(); break; } } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return this.getCommentFoldWidget(session, row); if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this.getCommentFoldWidget = function(session, row) { if (/comment/.test(session.getState(row)) && /<!-/.test(session.getLine(row))) return "start"; return ""; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) { return this.getCommentFoldWidget(session, row) && session.getCommentFoldRange(row, session.getLine(row).length); } var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var WorkerClient = require("../worker/worker_client").WorkerClient; var Mode = function() { this.HighlightRules = XmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.voidElements = lang.arrayToMap([]); this.blockComment = {start: "<!--", end: "-->"}; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/xml_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/xml"; }).call(Mode.prototype); exports.Mode = Mode; });
import Ember from 'ember'; export default Ember.Route.extend({ });
'use strict'; var path = require('path'); var which = require('which').sync; // TODO(markus): Needs some refactoring // Try to implement these not as functions but as attributes of the object and set it at each sane call // BUG: projectRoot changes when we do a cd() command var self = { binaryPath: function binaryPath() { return which('sane'); }, sanePath: function sanePath() { return path.resolve(__dirname, '../'); }, version: function version() { return require(self.sanePath() + '/package.json').version; } // , // projectRoot: function () { // return process.cwd(); // }, // serverRoot: function () { // return path.join(self.projectRoot(), 'server'); // }, // clientRoot: function () { // return path.join(self.projectRoot(), 'client') // } }; module.exports = self;
var Utils = require(__dirname + '/../../src/utils/Utils'); exports.appendArray = function(test){ // STUB test.done(); }; exports.splice = function(test){ // STUB test.done(); }; exports.extend = function(test){ // STUB test.done(); }; exports.defaults = function(test){ // STUB test.done(); };
/* * extsprintf.js: extended POSIX-style sprintf */ var mod_assert = require('assert'); var mod_util = require('util'); /* * Public interface */ exports.sprintf = jsSprintf; /* * Stripped down version of s[n]printf(3c). We make a best effort to throw an * exception when given a format string we don't understand, rather than * ignoring it, so that we won't break existing programs if/when we go implement * the rest of this. * * This implementation currently supports specifying * - field alignment ('-' flag), * - zero-pad ('0' flag) * - always show numeric sign ('+' flag), * - field width * - conversions for strings, decimal integers, and floats (numbers). * - argument size specifiers. These are all accepted but ignored, since * Javascript has no notion of the physical size of an argument. * * Everything else is currently unsupported, most notably precision, unsigned * numbers, non-decimal numbers, and characters. */ function jsSprintf(fmt) { var regex = [ '([^%]*)', /* normal text */ '%', /* start of format */ '([\'\\-+ #0]*?)', /* flags (optional) */ '([1-9]\\d*)?', /* width (optional) */ '(\\.([1-9]\\d*))?', /* precision (optional) */ '[lhjztL]*?', /* length mods (ignored) */ '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ ].join(''); var re = new RegExp(regex); var args = Array.prototype.slice.call(arguments, 1); var flags, width, precision, conversion; var left, pad, sign, arg, match; var ret = ''; var argn = 1; mod_assert.equal('string', typeof (fmt)); while ((match = re.exec(fmt)) !== null) { ret += match[1]; fmt = fmt.substring(match[0].length); flags = match[2] || ''; width = match[3] || 0; precision = match[4] || ''; conversion = match[6]; left = false; sign = false; pad = ' '; if (conversion == '%') { ret += '%'; continue; } if (args.length === 0) throw (new Error('too few args to sprintf')); arg = args.shift(); argn++; if (flags.match(/[\' #]/)) throw (new Error( 'unsupported flags: ' + flags)); if (precision.length > 0) throw (new Error( 'non-zero precision not supported')); if (flags.match(/-/)) left = true; if (flags.match(/0/)) pad = '0'; if (flags.match(/\+/)) sign = true; switch (conversion) { case 's': if (arg === undefined || arg === null) throw (new Error('argument ' + argn + ': attempted to print undefined or null ' + 'as a string')); ret += doPad(pad, width, left, arg.toString()); break; case 'd': arg = Math.floor(arg); /*jsl:fallthru*/ case 'f': sign = sign && arg > 0 ? '+' : ''; ret += sign + doPad(pad, width, left, arg.toString()); break; case 'j': /* non-standard */ if (width === 0) width = 10; ret += mod_util.inspect(arg, false, width); break; case 'r': /* non-standard */ ret += dumpException(arg); break; default: throw (new Error('unsupported conversion: ' + conversion)); } } ret += fmt; return (ret); } function doPad(chr, width, left, str) { var ret = str; while (ret.length < width) { if (left) ret += chr; else ret = chr + ret; } return (ret); } /* * This function dumps long stack traces for exceptions having a cause() method. * See node-verror for an example. */ function dumpException(ex) { var ret; if (!(ex instanceof Error)) throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); /* Note that V8 prepends "ex.stack" with ex.toString(). */ ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; if (ex.cause && typeof (ex.cause) === 'function') { var cex = ex.cause(); if (cex) { ret += '\nCaused by: ' + dumpException(cex); } } return (ret); }
/*! p5.dom.js v0.4.0 August 9, 2018 */ /** * <p>The web is much more than just canvas and p5.dom makes it easy to interact * with other HTML5 objects, including text, hyperlink, image, input, video, * audio, and webcam.</p> * <p>There is a set of creation methods, DOM manipulation methods, and * an extended <a href="#/p5.Element">p5.Element</a> that supports a range of HTML elements. See the * <a href='https://github.com/processing/p5.js/wiki/Beyond-the-canvas'> * beyond the canvas tutorial</a> for a full overview of how this addon works. * * <p>Methods and properties shown in black are part of the p5.js core, items in * blue are part of the p5.dom library. You will need to include an extra file * in order to access the blue functions. See the * <a href='http://p5js.org/libraries/#using-a-library'>using a library</a> * section for information on how to include this library. p5.dom comes with * <a href='http://p5js.org/download'>p5 complete</a> or you can download the single file * <a href='https://raw.githubusercontent.com/lmccart/p5.js/master/lib/addons/p5.dom.js'> * here</a>.</p> * <p>See <a href='https://github.com/processing/p5.js/wiki/Beyond-the-canvas'>tutorial: beyond the canvas</a> * for more info on how to use this library.</a> * * @module p5.dom * @submodule p5.dom * @for p5 * @main */ (function(root, factory) { if (typeof define === 'function' && define.amd) define('p5.dom', ['p5'], function(p5) { factory(p5); }); else if (typeof exports === 'object') factory(require('../p5')); else factory(root['p5']); })(this, function(p5) { // ============================================================================= // p5 additions // ============================================================================= /** * Searches the page for an element with the given ID, class, or tag name (using the '#' or '.' * prefixes to specify an ID or class respectively, and none for a tag) and returns it as * a <a href="#/p5.Element">p5.Element</a>. If a class or tag name is given with more than 1 element, * only the first element will be returned. * The DOM node itself can be accessed with .elt. * Returns null if none found. You can also specify a container to search within. * * @method select * @param {String} name id, class, or tag name of element to search for * @param {String|p5.Element|HTMLElement} [container] id, <a href="#/p5.Element">p5.Element</a>, or * HTML element to search within * @return {p5.Element|null} <a href="#/p5.Element">p5.Element</a> containing node found * @example * <div ><code class='norender'> * function setup() { * createCanvas(100, 100); * //translates canvas 50px down * select('canvas').position(100, 100); * } * </code></div> * <div><code class='norender'> * // these are all valid calls to select() * var a = select('#moo'); * var b = select('#blah', '#myContainer'); * var c, e; * if (b) { * c = select('#foo', b); * } * var d = document.getElementById('beep'); * if (d) { * e = select('p', d); * } * [a, b, c, d, e]; // unused * </code></div> * */ p5.prototype.select = function(e, p) { p5._validateParameters('select', arguments); var res = null; var container = getContainer(p); if (e[0] === '.') { e = e.slice(1); res = container.getElementsByClassName(e); if (res.length) { res = res[0]; } else { res = null; } } else if (e[0] === '#') { e = e.slice(1); res = container.getElementById(e); } else { res = container.getElementsByTagName(e); if (res.length) { res = res[0]; } else { res = null; } } if (res) { return this._wrapElement(res); } else { return null; } }; /** * Searches the page for elements with the given class or tag name (using the '.' prefix * to specify a class and no prefix for a tag) and returns them as <a href="#/p5.Element">p5.Element</a>s * in an array. * The DOM node itself can be accessed with .elt. * Returns an empty array if none found. * You can also specify a container to search within. * * @method selectAll * @param {String} name class or tag name of elements to search for * @param {String} [container] id, <a href="#/p5.Element">p5.Element</a>, or HTML element to search within * @return {p5.Element[]} Array of <a href="#/p5.Element">p5.Element</a>s containing nodes found * @example * <div class='norender'><code> * function setup() { * createButton('btn'); * createButton('2nd btn'); * createButton('3rd btn'); * var buttons = selectAll('button'); * * for (var i = 0; i < buttons.length; i++) { * buttons[i].size(100, 100); * } * } * </code></div> * <div class='norender'><code> * // these are all valid calls to selectAll() * var a = selectAll('.moo'); * a = selectAll('div'); * a = selectAll('button', '#myContainer'); * * var d = select('#container'); * a = selectAll('p', d); * * var f = document.getElementById('beep'); * a = select('.blah', f); * * a; // unused * </code></div> * */ p5.prototype.selectAll = function(e, p) { p5._validateParameters('selectAll', arguments); var arr = []; var res; var container = getContainer(p); if (e[0] === '.') { e = e.slice(1); res = container.getElementsByClassName(e); } else { res = container.getElementsByTagName(e); } if (res) { for (var j = 0; j < res.length; j++) { var obj = this._wrapElement(res[j]); arr.push(obj); } } return arr; }; /** * Helper function for select and selectAll */ function getContainer(p) { var container = document; if (typeof p === 'string' && p[0] === '#') { p = p.slice(1); container = document.getElementById(p) || document; } else if (p instanceof p5.Element) { container = p.elt; } else if (p instanceof HTMLElement) { container = p; } return container; } /** * Helper function for getElement and getElements. */ p5.prototype._wrapElement = function(elt) { var children = Array.prototype.slice.call(elt.children); if (elt.tagName === 'INPUT' && elt.type === 'checkbox') { var converted = new p5.Element(elt, this); converted.checked = function() { if (arguments.length === 0) { return this.elt.checked; } else if (arguments[0]) { this.elt.checked = true; } else { this.elt.checked = false; } return this; }; return converted; } else if (elt.tagName === 'VIDEO' || elt.tagName === 'AUDIO') { return new p5.MediaElement(elt, this); } else if (elt.tagName === 'SELECT') { return this.createSelect(new p5.Element(elt, this)); } else if ( children.length > 0 && children.every(function(c) { return c.tagName === 'INPUT' || c.tagName === 'LABEL'; }) ) { return this.createRadio(new p5.Element(elt, this)); } else { return new p5.Element(elt, this); } }; /** * Removes all elements created by p5, except any canvas / graphics * elements created by <a href="#/p5/createCanvas">createCanvas</a> or <a href="#/p5/createGraphics">createGraphics</a>. * Event handlers are removed, and element is removed from the DOM. * @method removeElements * @example * <div class='norender'><code> * function setup() { * createCanvas(100, 100); * createDiv('this is some text'); * createP('this is a paragraph'); * } * function mousePressed() { * removeElements(); // this will remove the div and p, not canvas * } * </code></div> * */ p5.prototype.removeElements = function(e) { p5._validateParameters('removeElements', arguments); for (var i = 0; i < this._elements.length; i++) { if (!(this._elements[i].elt instanceof HTMLCanvasElement)) { this._elements[i].remove(); } } }; /** * The .<a href="#/p5.Element/changed">changed()</a> function is called when the value of an * element changes. * This can be used to attach an element specific event listener. * * @method changed * @param {Function|Boolean} fxn function to be fired when the value of * an element changes. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div><code> * var sel; * * function setup() { * textAlign(CENTER); * background(200); * sel = createSelect(); * sel.position(10, 10); * sel.option('pear'); * sel.option('kiwi'); * sel.option('grape'); * sel.changed(mySelectEvent); * } * * function mySelectEvent() { * var item = sel.value(); * background(200); * text("it's a " + item + '!', 50, 50); * } * </code></div> * * <div><code> * var checkbox; * var cnv; * * function setup() { * checkbox = createCheckbox(' fill'); * checkbox.changed(changeFill); * cnv = createCanvas(100, 100); * cnv.position(0, 30); * noFill(); * } * * function draw() { * background(200); * ellipse(50, 50, 50, 50); * } * * function changeFill() { * if (checkbox.checked()) { * fill(0); * } else { * noFill(); * } * } * </code></div> * * @alt * dropdown: pear, kiwi, grape. When selected text "its a" + selection shown. * */ p5.Element.prototype.changed = function(fxn) { p5.Element._adjustListener('change', fxn, this); return this; }; /** * The .<a href="#/p5.Element/input">input()</a> function is called when any user input is * detected with an element. The input event is often used * to detect keystrokes in a input element, or changes on a * slider element. This can be used to attach an element specific * event listener. * * @method input * @param {Function|Boolean} fxn function to be fired when any user input is * detected within the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example * <div class='norender'><code> * // Open your console to see the output * function setup() { * var inp = createInput(''); * inp.input(myInputEvent); * } * * function myInputEvent() { * console.log('you are typing: ', this.value()); * } * </code></div> * * @alt * no display. * */ p5.Element.prototype.input = function(fxn) { p5.Element._adjustListener('input', fxn, this); return this; }; /** * Helpers for create methods. */ function addElement(elt, pInst, media) { var node = pInst._userNode ? pInst._userNode : document.body; node.appendChild(elt); var c = media ? new p5.MediaElement(elt, pInst) : new p5.Element(elt, pInst); pInst._elements.push(c); return c; } /** * Creates a &lt;div&gt;&lt;/div&gt; element in the DOM with given inner HTML. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createDiv * @param {String} [html] inner HTML for element created * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div class='norender'><code> * createDiv('this is some text'); * </code></div> */ /** * Creates a &lt;p&gt;&lt;/p&gt; element in the DOM with given inner HTML. Used * for paragraph length text. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createP * @param {String} [html] inner HTML for element created * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div class='norender'><code> * createP('this is some text'); * </code></div> */ /** * Creates a &lt;span&gt;&lt;/span&gt; element in the DOM with given inner HTML. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createSpan * @param {String} [html] inner HTML for element created * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div class='norender'><code> * createSpan('this is some text'); * </code></div> */ var tags = ['div', 'p', 'span']; tags.forEach(function(tag) { var method = 'create' + tag.charAt(0).toUpperCase() + tag.slice(1); p5.prototype[method] = function(html) { var elt = document.createElement(tag); elt.innerHTML = typeof html === 'undefined' ? '' : html; return addElement(elt, this); }; }); /** * Creates an &lt;img&gt; element in the DOM with given src and * alternate text. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createImg * @param {String} src src path or url for image * @param {String} [alt] alternate text to be used if image does not load * @param {Function} [successCallback] callback to be called once image data is loaded * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div class='norender'><code> * createImg('http://p5js.org/img/asterisk-01.png'); * </code></div> */ /** * @method createImg * @param {String} src * @param {Function} successCallback * @return {Object|p5.Element} */ p5.prototype.createImg = function() { p5._validateParameters('createImg', arguments); var elt = document.createElement('img'); var args = arguments; var self; var setAttrs = function() { self.width = elt.offsetWidth || elt.width; self.height = elt.offsetHeight || elt.height; if (args.length > 1 && typeof args[1] === 'function') { self.fn = args[1]; self.fn(); } else if (args.length > 1 && typeof args[2] === 'function') { self.fn = args[2]; self.fn(); } }; elt.src = args[0]; if (args.length > 1 && typeof args[1] === 'string') { elt.alt = args[1]; } elt.onload = function() { setAttrs(); }; self = addElement(elt, this); return self; }; /** * Creates an &lt;a&gt;&lt;/a&gt; element in the DOM for including a hyperlink. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createA * @param {String} href url of page to link to * @param {String} html inner html of link element to display * @param {String} [target] target where new link should open, * could be _blank, _self, _parent, _top. * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div class='norender'><code> * createA('http://p5js.org/', 'this is a link'); * </code></div> */ p5.prototype.createA = function(href, html, target) { p5._validateParameters('createA', arguments); var elt = document.createElement('a'); elt.href = href; elt.innerHTML = html; if (target) elt.target = target; return addElement(elt, this); }; /** INPUT **/ /** * Creates a slider &lt;input&gt;&lt;/input&gt; element in the DOM. * Use .size() to set the display length of the slider. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createSlider * @param {Number} min minimum value of the slider * @param {Number} max maximum value of the slider * @param {Number} [value] default value of the slider * @param {Number} [step] step size for each tick of the slider (if step is set to 0, the slider will move continuously from the minimum to the maximum value) * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div><code> * var slider; * function setup() { * slider = createSlider(0, 255, 100); * slider.position(10, 10); * slider.style('width', '80px'); * } * * function draw() { * var val = slider.value(); * background(val); * } * </code></div> * * <div><code> * var slider; * function setup() { * colorMode(HSB); * slider = createSlider(0, 360, 60, 40); * slider.position(10, 10); * slider.style('width', '80px'); * } * * function draw() { * var val = slider.value(); * background(val, 100, 100, 1); * } * </code></div> */ p5.prototype.createSlider = function(min, max, value, step) { p5._validateParameters('createSlider', arguments); var elt = document.createElement('input'); elt.type = 'range'; elt.min = min; elt.max = max; if (step === 0) { elt.step = 0.000000000000000001; // smallest valid step } else if (step) { elt.step = step; } if (typeof value === 'number') elt.value = value; return addElement(elt, this); }; /** * Creates a &lt;button&gt;&lt;/button&gt; element in the DOM. * Use .size() to set the display size of the button. * Use .mousePressed() to specify behavior on press. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createButton * @param {String} label label displayed on the button * @param {String} [value] value of the button * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div class='norender'><code> * var button; * function setup() { * createCanvas(100, 100); * background(0); * button = createButton('click me'); * button.position(19, 19); * button.mousePressed(changeBG); * } * * function changeBG() { * var val = random(255); * background(val); * } * </code></div> */ p5.prototype.createButton = function(label, value) { p5._validateParameters('createButton', arguments); var elt = document.createElement('button'); elt.innerHTML = label; if (value) elt.value = value; return addElement(elt, this); }; /** * Creates a checkbox &lt;input&gt;&lt;/input&gt; element in the DOM. * Calling .checked() on a checkbox returns if it is checked or not * * @method createCheckbox * @param {String} [label] label displayed after checkbox * @param {boolean} [value] value of the checkbox; checked is true, unchecked is false * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div class='norender'><code> * var checkbox; * * function setup() { * checkbox = createCheckbox('label', false); * checkbox.changed(myCheckedEvent); * } * * function myCheckedEvent() { * if (this.checked()) { * console.log('Checking!'); * } else { * console.log('Unchecking!'); * } * } * </code></div> */ p5.prototype.createCheckbox = function() { p5._validateParameters('createCheckbox', arguments); var elt = document.createElement('div'); var checkbox = document.createElement('input'); checkbox.type = 'checkbox'; elt.appendChild(checkbox); //checkbox must be wrapped in p5.Element before label so that label appears after var self = addElement(elt, this); self.checked = function() { var cb = self.elt.getElementsByTagName('input')[0]; if (cb) { if (arguments.length === 0) { return cb.checked; } else if (arguments[0]) { cb.checked = true; } else { cb.checked = false; } } return self; }; this.value = function(val) { self.value = val; return this; }; if (arguments[0]) { var ran = Math.random() .toString(36) .slice(2); var label = document.createElement('label'); checkbox.setAttribute('id', ran); label.htmlFor = ran; self.value(arguments[0]); label.appendChild(document.createTextNode(arguments[0])); elt.appendChild(label); } if (arguments[1]) { checkbox.checked = true; } return self; }; /** * Creates a dropdown menu &lt;select&gt;&lt;/select&gt; element in the DOM. * It also helps to assign select-box methods to <a href="#/p5.Element">p5.Element</a> when selecting existing select box * @method createSelect * @param {boolean} [multiple] true if dropdown should support multiple selections * @return {p5.Element} * @example * <div><code> * var sel; * * function setup() { * textAlign(CENTER); * background(200); * sel = createSelect(); * sel.position(10, 10); * sel.option('pear'); * sel.option('kiwi'); * sel.option('grape'); * sel.changed(mySelectEvent); * } * * function mySelectEvent() { * var item = sel.value(); * background(200); * text('it is a' + item + '!', 50, 50); * } * </code></div> */ /** * @method createSelect * @param {Object} existing DOM select element * @return {p5.Element} */ p5.prototype.createSelect = function() { p5._validateParameters('createSelect', arguments); var elt, self; var arg = arguments[0]; if (typeof arg === 'object' && arg.elt.nodeName === 'SELECT') { self = arg; elt = this.elt = arg.elt; } else { elt = document.createElement('select'); if (arg && typeof arg === 'boolean') { elt.setAttribute('multiple', 'true'); } self = addElement(elt, this); } self.option = function(name, value) { var index; //see if there is already an option with this name for (var i = 0; i < this.elt.length; i++) { if (this.elt[i].innerHTML === name) { index = i; break; } } //if there is an option with this name we will modify it if (index !== undefined) { //if the user passed in false then delete that option if (value === false) { this.elt.remove(index); } else { //otherwise if the name and value are the same then change both if (this.elt[index].innerHTML === this.elt[index].value) { this.elt[index].innerHTML = this.elt[index].value = value; //otherwise just change the value } else { this.elt[index].value = value; } } } else { //if it doesn't exist make it var opt = document.createElement('option'); opt.innerHTML = name; if (arguments.length > 1) opt.value = value; else opt.value = name; elt.appendChild(opt); } }; self.selected = function(value) { var arr = [], i; if (arguments.length > 0) { for (i = 0; i < this.elt.length; i++) { if (value.toString() === this.elt[i].value) { this.elt.selectedIndex = i; } } return this; } else { if (this.elt.getAttribute('multiple')) { for (i = 0; i < this.elt.selectedOptions.length; i++) { arr.push(this.elt.selectedOptions[i].value); } return arr; } else { return this.elt.value; } } }; return self; }; /** * Creates a radio button &lt;input&gt;&lt;/input&gt; element in the DOM. * The .option() method can be used to set options for the radio after it is * created. The .value() method will return the currently selected option. * * @method createRadio * @param {String} [divId] the id and name of the created div and input field respectively * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div><code> * var radio; * * function setup() { * radio = createRadio(); * radio.option('black'); * radio.option('white'); * radio.option('gray'); * radio.style('width', '60px'); * textAlign(CENTER); * fill(255, 0, 0); * } * * function draw() { * var val = radio.value(); * background(val); * text(val, width / 2, height / 2); * } * </code></div> * <div><code> * var radio; * * function setup() { * radio = createRadio(); * radio.option('apple', 1); * radio.option('bread', 2); * radio.option('juice', 3); * radio.style('width', '60px'); * textAlign(CENTER); * } * * function draw() { * background(200); * var val = radio.value(); * if (val) { * text('item cost is $' + val, width / 2, height / 2); * } * } * </code></div> */ p5.prototype.createRadio = function(existing_radios) { p5._validateParameters('createRadio', arguments); // do some prep by counting number of radios on page var radios = document.querySelectorAll('input[type=radio]'); var count = 0; if (radios.length > 1) { var length = radios.length; var prev = radios[0].name; var current = radios[1].name; count = 1; for (var i = 1; i < length; i++) { current = radios[i].name; if (prev !== current) { count++; } prev = current; } } else if (radios.length === 1) { count = 1; } // see if we got an existing set of radios from callee var elt, self; if (typeof existing_radios === 'object') { // use existing elements self = existing_radios; elt = this.elt = existing_radios.elt; } else { // create a set of radio buttons elt = document.createElement('div'); self = addElement(elt, this); } // setup member functions self._getInputChildrenArray = function() { return Array.prototype.slice.call(this.elt.children).filter(function(c) { return c.tagName === 'INPUT'; }); }; var times = -1; self.option = function(name, value) { var opt = document.createElement('input'); opt.type = 'radio'; opt.innerHTML = name; if (value) opt.value = value; else opt.value = name; opt.setAttribute('name', 'defaultradio' + count); elt.appendChild(opt); if (name) { times++; var label = document.createElement('label'); opt.setAttribute('id', 'defaultradio' + count + '-' + times); label.htmlFor = 'defaultradio' + count + '-' + times; label.appendChild(document.createTextNode(name)); elt.appendChild(label); } return opt; }; self.selected = function(value) { var i; var inputChildren = self._getInputChildrenArray(); if (value) { for (i = 0; i < inputChildren.length; i++) { if (inputChildren[i].value === value) inputChildren[i].checked = true; } return this; } else { for (i = 0; i < inputChildren.length; i++) { if (inputChildren[i].checked === true) return inputChildren[i].value; } } }; self.value = function(value) { var i; var inputChildren = self._getInputChildrenArray(); if (value) { for (i = 0; i < inputChildren.length; i++) { if (inputChildren[i].value === value) inputChildren[i].checked = true; } return this; } else { for (i = 0; i < inputChildren.length; i++) { if (inputChildren[i].checked === true) return inputChildren[i].value; } return ''; } }; return self; }; /** * Creates a colorPicker element in the DOM for color input. * The .value() method will return a hex string (#rrggbb) of the color. * The .color() method will return a p5.Color object with the current chosen color. * * @method createColorPicker * @param {String|p5.Color} [value] default color of element * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div> * <code> * var inp1, inp2; * function setup() { * createCanvas(100, 100); * background('grey'); * inp1 = createColorPicker('#ff0000'); * inp2 = createColorPicker(color('yellow')); * inp1.input(setShade1); * inp2.input(setShade2); * setMidShade(); * } * * function setMidShade() { * // Finding a shade between the two * var commonShade = lerpColor(inp1.color(), inp2.color(), 0.5); * fill(commonShade); * rect(20, 20, 60, 60); * } * * function setShade1() { * setMidShade(); * console.log('You are choosing shade 1 to be : ', this.value()); * } * function setShade2() { * setMidShade(); * console.log('You are choosing shade 2 to be : ', this.value()); * } * </code> * </div> */ p5.prototype.createColorPicker = function(value) { p5._validateParameters('createColorPicker', arguments); var elt = document.createElement('input'); var self; elt.type = 'color'; if (value) { if (value instanceof p5.Color) { elt.value = value.toString('#rrggbb'); } else { p5.prototype._colorMode = 'rgb'; p5.prototype._colorMaxes = { rgb: [255, 255, 255, 255], hsb: [360, 100, 100, 1], hsl: [360, 100, 100, 1] }; elt.value = p5.prototype.color(value).toString('#rrggbb'); } } else { elt.value = '#000000'; } self = addElement(elt, this); // Method to return a p5.Color object for the given color. self.color = function() { if (value.mode) { p5.prototype._colorMode = value.mode; } if (value.maxes) { p5.prototype._colorMaxes = value.maxes; } return p5.prototype.color(this.elt.value); }; return self; }; /** * Creates an &lt;input&gt;&lt;/input&gt; element in the DOM for text input. * Use .<a href="#/p5.Element/size">size()</a> to set the display length of the box. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createInput * @param {String} [value] default value of the input box * @param {String} [type] type of text, ie text, password etc. Defaults to text * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div class='norender'><code> * function setup() { * var inp = createInput(''); * inp.input(myInputEvent); * } * * function myInputEvent() { * console.log('you are typing: ', this.value()); * } * </code></div> */ p5.prototype.createInput = function(value, type) { p5._validateParameters('createInput', arguments); var elt = document.createElement('input'); elt.type = type ? type : 'text'; if (value) elt.value = value; return addElement(elt, this); }; /** * Creates an &lt;input&gt;&lt;/input&gt; element in the DOM of type 'file'. * This allows users to select local files for use in a sketch. * * @method createFileInput * @param {Function} [callback] callback function for when a file loaded * @param {String} [multiple] optional to allow multiple files selected * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created DOM element * @example * <div class='norender'><code> * var input; * var img; * * function setup() { * input = createFileInput(handleFile); * input.position(0, 0); * } * * function draw() { * if (img) { * image(img, 0, 0, width, height); * } * } * * function handleFile(file) { * print(file); * if (file.type === 'image') { * img = createImg(file.data); * img.hide(); * } * } * </code></div> */ p5.prototype.createFileInput = function(callback, multiple) { p5._validateParameters('createFileInput', arguments); // Function to handle when a file is selected // We're simplifying life and assuming that we always // want to load every selected file function handleFileSelect(evt) { // These are the files var files = evt.target.files; // Load each one and trigger a callback for (var i = 0; i < files.length; i++) { var f = files[i]; p5.File._load(f, callback); } } // Is the file stuff supported? if (window.File && window.FileReader && window.FileList && window.Blob) { // Yup, we're ok and make an input file selector var elt = document.createElement('input'); elt.type = 'file'; // If we get a second argument that evaluates to true // then we are looking for multiple files if (multiple) { // Anything gets the job done elt.multiple = 'multiple'; } // Now let's handle when a file was selected elt.addEventListener('change', handleFileSelect, false); return addElement(elt, this); } else { console.log( 'The File APIs are not fully supported in this browser. Cannot create element.' ); } }; /** VIDEO STUFF **/ function createMedia(pInst, type, src, callback) { var elt = document.createElement(type); // allow src to be empty src = src || ''; if (typeof src === 'string') { src = [src]; } for (var i = 0; i < src.length; i++) { var source = document.createElement('source'); source.src = src[i]; elt.appendChild(source); } if (typeof callback !== 'undefined') { var callbackHandler = function() { callback(); elt.removeEventListener('canplaythrough', callbackHandler); }; elt.addEventListener('canplaythrough', callbackHandler); } var c = addElement(elt, pInst, true); c.loadedmetadata = false; // set width and height onload metadata elt.addEventListener('loadedmetadata', function() { c.width = elt.videoWidth; c.height = elt.videoHeight; //c.elt.playbackRate = s; // set elt width and height if not set if (c.elt.width === 0) c.elt.width = elt.videoWidth; if (c.elt.height === 0) c.elt.height = elt.videoHeight; if (c.presetPlaybackRate) { c.elt.playbackRate = c.presetPlaybackRate; delete c.presetPlaybackRate; } c.loadedmetadata = true; }); return c; } /** * Creates an HTML5 &lt;video&gt; element in the DOM for simple playback * of audio/video. Shown by default, can be hidden with .<a href="#/p5.Element/hide">hide()</a> * and drawn into canvas using video(). Appends to the container * node if one is specified, otherwise appends to body. The first parameter * can be either a single string path to a video file, or an array of string * paths to different formats of the same video. This is useful for ensuring * that your video can play across different browsers, as each supports * different formats. See <a href='https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats'>this * page</a> for further information about supported formats. * * @method createVideo * @param {String|String[]} src path to a video file, or array of paths for * supporting different browsers * @param {Function} [callback] callback function to be called upon * 'canplaythrough' event fire, that is, when the * browser can play the media, and estimates that * enough data has been loaded to play the media * up to its end without having to stop for * further buffering of content * @return {p5.MediaElement} pointer to video <a href="#/p5.Element">p5.Element</a> * @example * <div><code> * var vid; * function setup() { * vid = createVideo(['small.mp4', 'small.ogv', 'small.webm'], vidLoad); * } * * // This function is called when the video loads * function vidLoad() { * vid.play(); * } * </code></div> */ p5.prototype.createVideo = function(src, callback) { p5._validateParameters('createVideo', arguments); return createMedia(this, 'video', src, callback); }; /** AUDIO STUFF **/ /** * Creates a hidden HTML5 &lt;audio&gt; element in the DOM for simple audio * playback. Appends to the container node if one is specified, * otherwise appends to body. The first parameter * can be either a single string path to a audio file, or an array of string * paths to different formats of the same audio. This is useful for ensuring * that your audio can play across different browsers, as each supports * different formats. See <a href='https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats'>this * page for further information about supported formats</a>. * * @method createAudio * @param {String|String[]} [src] path to an audio file, or array of paths * for supporting different browsers * @param {Function} [callback] callback function to be called upon * 'canplaythrough' event fire, that is, when the * browser can play the media, and estimates that * enough data has been loaded to play the media * up to its end without having to stop for * further buffering of content * @return {p5.MediaElement} pointer to audio <a href="#/p5.Element">p5.Element</a> * @example * <div><code> * var ele; * function setup() { * ele = createAudio('assets/beat.mp3'); * * // here we set the element to autoplay * // The element will play as soon * // as it is able to do so. * ele.autoplay(true); * } * </code></div> */ p5.prototype.createAudio = function(src, callback) { p5._validateParameters('createAudio', arguments); return createMedia(this, 'audio', src, callback); }; /** CAMERA STUFF **/ /** * @property {String} VIDEO * @final * @category Constants */ p5.prototype.VIDEO = 'video'; /** * @property {String} AUDIO * @final * @category Constants */ p5.prototype.AUDIO = 'audio'; // from: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia // Older browsers might not implement mediaDevices at all, so we set an empty object first if (navigator.mediaDevices === undefined) { navigator.mediaDevices = {}; } // Some browsers partially implement mediaDevices. We can't just assign an object // with getUserMedia as it would overwrite existing properties. // Here, we will just add the getUserMedia property if it's missing. if (navigator.mediaDevices.getUserMedia === undefined) { navigator.mediaDevices.getUserMedia = function(constraints) { // First get ahold of the legacy getUserMedia, if present var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia; // Some browsers just don't implement it - return a rejected promise with an error // to keep a consistent interface if (!getUserMedia) { return Promise.reject( new Error('getUserMedia is not implemented in this browser') ); } // Otherwise, wrap the call to the old navigator.getUserMedia with a Promise return new Promise(function(resolve, reject) { getUserMedia.call(navigator, constraints, resolve, reject); }); }; } /** * <p>Creates a new HTML5 &lt;video&gt; element that contains the audio/video * feed from a webcam. The element is separate from the canvas and is * displayed by default. The element can be hidden using .<a href="#/p5.Element/hide">hide()</a>. The feed * can be drawn onto the canvas using <a href="#/p5/image">image()</a>. The loadedmetadata property can * be used to detect when the element has fully loaded (see second example).</p> * <p>More specific properties of the feed can be passing in a Constraints object. * See the * <a href='http://w3c.github.io/mediacapture-main/getusermedia.html#media-track-constraints'> W3C * spec</a> for possible properties. Note that not all of these are supported * by all browsers.</p> * <p>Security note: A new browser security specification requires that getUserMedia, * which is behind <a href="#/p5/createCapture">createCapture()</a>, only works when you're running the code locally, * or on HTTPS. Learn more <a href='http://stackoverflow.com/questions/34197653/getusermedia-in-chrome-47-without-using-https'>here</a> * and <a href='https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia'>here</a>.</p> * * @method createCapture * @param {String|Constant|Object} type type of capture, either VIDEO or * AUDIO if none specified, default both, * or a Constraints object * @param {Function} [callback] function to be called once * stream has loaded * @return {p5.Element} capture video <a href="#/p5.Element">p5.Element</a> * @example * <div class='norender notest'><code> * var capture; * * function setup() { * createCanvas(480, 480); * capture = createCapture(VIDEO); * capture.hide(); * } * * function draw() { * image(capture, 0, 0, width, width * capture.height / capture.width); * filter(INVERT); * } * </code></div> * <div class='norender notest'><code> * function setup() { * createCanvas(480, 120); * var constraints = { * video: { * mandatory: { * minWidth: 1280, * minHeight: 720 * }, * optional: [{ maxFrameRate: 10 }] * }, * audio: true * }; * createCapture(constraints, function(stream) { * console.log(stream); * }); * } * </code></div> * <code><div class='norender notest'> * var capture; * * function setup() { * createCanvas(640, 480); * capture = createCapture(VIDEO); * } * function draw() { * background(0); * if (capture.loadedmetadata) { * var c = capture.get(0, 0, 100, 100); * image(c, 0, 0); * } * } */ p5.prototype.createCapture = function() { p5._validateParameters('createCapture', arguments); var useVideo = true; var useAudio = true; var constraints; var cb; for (var i = 0; i < arguments.length; i++) { if (arguments[i] === p5.prototype.VIDEO) { useAudio = false; } else if (arguments[i] === p5.prototype.AUDIO) { useVideo = false; } else if (typeof arguments[i] === 'object') { constraints = arguments[i]; } else if (typeof arguments[i] === 'function') { cb = arguments[i]; } } if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { var elt = document.createElement('video'); // required to work in iOS 11 & up: elt.setAttribute('playsinline', ''); if (!constraints) { constraints = { video: useVideo, audio: useAudio }; } navigator.mediaDevices.getUserMedia(constraints).then( function(stream) { try { if ('srcObject' in elt) { elt.srcObject = stream; } else { elt.src = window.URL.createObjectURL(stream); } } catch (err) { elt.src = stream; } if (cb) { cb(stream); } }, function(e) { console.log(e); } ); } else { throw 'getUserMedia not supported in this browser'; } var c = addElement(elt, this, true); c.loadedmetadata = false; // set width and height onload metadata elt.addEventListener('loadedmetadata', function() { elt.play(); if (elt.width) { c.width = elt.videoWidth = elt.width; c.height = elt.videoHeight = elt.height; } else { c.width = c.elt.width = elt.videoWidth; c.height = c.elt.height = elt.videoHeight; } c.loadedmetadata = true; }); return c; }; /** * Creates element with given tag in the DOM with given content. * Appends to the container node if one is specified, otherwise * appends to body. * * @method createElement * @param {String} tag tag for the new element * @param {String} [content] html content to be inserted into the element * @return {p5.Element} pointer to <a href="#/p5.Element">p5.Element</a> holding created node * @example * <div class='norender'><code> * createElement('h2', 'im an h2 p5.element!'); * </code></div> */ p5.prototype.createElement = function(tag, content) { p5._validateParameters('createElement', arguments); var elt = document.createElement(tag); if (typeof content !== 'undefined') { elt.innerHTML = content; } return addElement(elt, this); }; // ============================================================================= // p5.Element additions // ============================================================================= /** * * Adds specified class to the element. * * @for p5.Element * @method addClass * @param {String} class name of class to add * @chainable * @example * <div class='norender'><code> * var div = createDiv('div'); * div.addClass('myClass'); * </code></div> */ p5.Element.prototype.addClass = function(c) { if (this.elt.className) { // PEND don't add class more than once //var regex = new RegExp('[^a-zA-Z\d:]?'+c+'[^a-zA-Z\d:]?'); //if (this.elt.className.search(/[^a-zA-Z\d:]?hi[^a-zA-Z\d:]?/) === -1) { this.elt.className = this.elt.className + ' ' + c; //} } else { this.elt.className = c; } return this; }; /** * * Removes specified class from the element. * * @method removeClass * @param {String} class name of class to remove * @chainable * @example * <div class='norender'><code> * // In this example, a class is set when the div is created * // and removed when mouse is pressed. This could link up * // with a CSS style rule to toggle style properties. * * var div; * * function setup() { * div = createDiv('div'); * div.addClass('myClass'); * } * * function mousePressed() { * div.removeClass('myClass'); * } * </code></div> */ p5.Element.prototype.removeClass = function(c) { var regex = new RegExp('(?:^|\\s)' + c + '(?!\\S)'); this.elt.className = this.elt.className.replace(regex, ''); this.elt.className = this.elt.className.replace(/^\s+|\s+$/g, ''); //prettify (optional) return this; }; /** * * Attaches the element as a child to the parent specified. * Accepts either a string ID, DOM node, or <a href="#/p5.Element">p5.Element</a>. * If no argument is specified, an array of children DOM nodes is returned. * * @method child * @returns {Node[]} an array of child nodes * @example * <div class='norender'><code> * var div0 = createDiv('this is the parent'); * var div1 = createDiv('this is the child'); * div0.child(div1); // use p5.Element * </code></div> * <div class='norender'><code> * var div0 = createDiv('this is the parent'); * var div1 = createDiv('this is the child'); * div1.id('apples'); * div0.child('apples'); // use id * </code></div> * <div class='norender notest'><code> * // this example assumes there is a div already on the page * // with id "myChildDiv" * var div0 = createDiv('this is the parent'); * var elt = document.getElementById('myChildDiv'); * div0.child(elt); // use element from page * </code></div> */ /** * @method child * @param {String|p5.Element} [child] the ID, DOM node, or <a href="#/p5.Element">p5.Element</a> * to add to the current element * @chainable */ p5.Element.prototype.child = function(c) { if (typeof c === 'undefined') { return this.elt.childNodes; } if (typeof c === 'string') { if (c[0] === '#') { c = c.substring(1); } c = document.getElementById(c); } else if (c instanceof p5.Element) { c = c.elt; } this.elt.appendChild(c); return this; }; /** * Centers a p5 Element either vertically, horizontally, * or both, relative to its parent or according to * the body if the Element has no parent. If no argument is passed * the Element is aligned both vertically and horizontally. * * @method center * @param {String} [align] passing 'vertical', 'horizontal' aligns element accordingly * @chainable * * @example * <div><code> * function setup() { * var div = createDiv('').size(10, 10); * div.style('background-color', 'orange'); * div.center(); * } * </code></div> */ p5.Element.prototype.center = function(align) { var style = this.elt.style.display; var hidden = this.elt.style.display === 'none'; var parentHidden = this.parent().style.display === 'none'; var pos = { x: this.elt.offsetLeft, y: this.elt.offsetTop }; if (hidden) this.show(); this.elt.style.display = 'block'; this.position(0, 0); if (parentHidden) this.parent().style.display = 'block'; var wOffset = Math.abs(this.parent().offsetWidth - this.elt.offsetWidth); var hOffset = Math.abs(this.parent().offsetHeight - this.elt.offsetHeight); var y = pos.y; var x = pos.x; if (align === 'both' || align === undefined) { this.position(wOffset / 2, hOffset / 2); } else if (align === 'horizontal') { this.position(wOffset / 2, y); } else if (align === 'vertical') { this.position(x, hOffset / 2); } this.style('display', style); if (hidden) this.hide(); if (parentHidden) this.parent().style.display = 'none'; return this; }; /** * * If an argument is given, sets the inner HTML of the element, * replacing any existing html. If true is included as a second * argument, html is appended instead of replacing existing html. * If no arguments are given, returns * the inner HTML of the element. * * @for p5.Element * @method html * @returns {String} the inner HTML of the element * @example * <div class='norender'><code> * var div = createDiv('').size(100, 100); * div.html('hi'); * </code></div> * <div class='norender'><code> * var div = createDiv('Hello ').size(100, 100); * div.html('World', true); * </code></div> */ /** * @method html * @param {String} [html] the HTML to be placed inside the element * @param {boolean} [append] whether to append HTML to existing * @chainable */ p5.Element.prototype.html = function() { if (arguments.length === 0) { return this.elt.innerHTML; } else if (arguments[1]) { this.elt.innerHTML += arguments[0]; return this; } else { this.elt.innerHTML = arguments[0]; return this; } }; /** * * Sets the position of the element relative to (0, 0) of the * window. Essentially, sets position:absolute and left and top * properties of style. If no arguments given returns the x and y position * of the element in an object. * * @method position * @returns {Object} the x and y position of the element in an object * @example * <div><code class='norender'> * function setup() { * var cnv = createCanvas(100, 100); * // positions canvas 50px to the right and 100px * // below upper left corner of the window * cnv.position(50, 100); * } * </code></div> */ /** * @method position * @param {Number} [x] x-position relative to upper left of window * @param {Number} [y] y-position relative to upper left of window * @chainable */ p5.Element.prototype.position = function() { if (arguments.length === 0) { return { x: this.elt.offsetLeft, y: this.elt.offsetTop }; } else { this.elt.style.position = 'absolute'; this.elt.style.left = arguments[0] + 'px'; this.elt.style.top = arguments[1] + 'px'; this.x = arguments[0]; this.y = arguments[1]; return this; } }; /* Helper method called by p5.Element.style() */ p5.Element.prototype._translate = function() { this.elt.style.position = 'absolute'; // save out initial non-translate transform styling var transform = ''; if (this.elt.style.transform) { transform = this.elt.style.transform.replace(/translate3d\(.*\)/g, ''); transform = transform.replace(/translate[X-Z]?\(.*\)/g, ''); } if (arguments.length === 2) { this.elt.style.transform = 'translate(' + arguments[0] + 'px, ' + arguments[1] + 'px)'; } else if (arguments.length > 2) { this.elt.style.transform = 'translate3d(' + arguments[0] + 'px,' + arguments[1] + 'px,' + arguments[2] + 'px)'; if (arguments.length === 3) { this.elt.parentElement.style.perspective = '1000px'; } else { this.elt.parentElement.style.perspective = arguments[3] + 'px'; } } // add any extra transform styling back on end this.elt.style.transform += transform; return this; }; /* Helper method called by p5.Element.style() */ p5.Element.prototype._rotate = function() { // save out initial non-rotate transform styling var transform = ''; if (this.elt.style.transform) { transform = this.elt.style.transform.replace(/rotate3d\(.*\)/g, ''); transform = transform.replace(/rotate[X-Z]?\(.*\)/g, ''); } if (arguments.length === 1) { this.elt.style.transform = 'rotate(' + arguments[0] + 'deg)'; } else if (arguments.length === 2) { this.elt.style.transform = 'rotate(' + arguments[0] + 'deg, ' + arguments[1] + 'deg)'; } else if (arguments.length === 3) { this.elt.style.transform = 'rotateX(' + arguments[0] + 'deg)'; this.elt.style.transform += 'rotateY(' + arguments[1] + 'deg)'; this.elt.style.transform += 'rotateZ(' + arguments[2] + 'deg)'; } // add remaining transform back on this.elt.style.transform += transform; return this; }; /** * Sets the given style (css) property (1st arg) of the element with the * given value (2nd arg). If a single argument is given, .style() * returns the value of the given property; however, if the single argument * is given in css syntax ('text-align:center'), .style() sets the css * appropriatly. .style() also handles 2d and 3d css transforms. If * the 1st arg is 'rotate', 'translate', or 'position', the following arguments * accept Numbers as values. ('translate', 10, 100, 50); * * @method style * @param {String} property property to be set * @returns {String} value of property * @example * <div><code class='norender'> * var myDiv = createDiv('I like pandas.'); * myDiv.style('font-size', '18px'); * myDiv.style('color', '#ff0000'); * </code></div> * <div><code class='norender'> * var col = color(25, 23, 200, 50); * var button = createButton('button'); * button.style('background-color', col); * button.position(10, 10); * </code></div> * <div><code class='norender'> * var myDiv = createDiv('I like lizards.'); * myDiv.style('position', 20, 20); * myDiv.style('rotate', 45); * </code></div> * <div><code class='norender'> * var myDiv; * function setup() { * background(200); * myDiv = createDiv('I like gray.'); * myDiv.position(20, 20); * } * * function draw() { * myDiv.style('font-size', mouseX + 'px'); * } * </code></div> */ /** * @method style * @param {String} property * @param {String|Number|p5.Color} value value to assign to property (only String|Number for rotate/translate) * @param {String|Number|p5.Color} [value2] position can take a 2nd value * @param {String|Number|p5.Color} [value3] translate can take a 2nd & 3rd value * @chainable */ p5.Element.prototype.style = function(prop, val) { var self = this; if (val instanceof p5.Color) { val = 'rgba(' + val.levels[0] + ',' + val.levels[1] + ',' + val.levels[2] + ',' + val.levels[3] / 255 + ')'; } if (typeof val === 'undefined') { if (prop.indexOf(':') === -1) { var styles = window.getComputedStyle(self.elt); var style = styles.getPropertyValue(prop); return style; } else { var attrs = prop.split(';'); for (var i = 0; i < attrs.length; i++) { var parts = attrs[i].split(':'); if (parts[0] && parts[1]) { this.elt.style[parts[0].trim()] = parts[1].trim(); } } } } else { if (prop === 'rotate' || prop === 'translate' || prop === 'position') { var trans = Array.prototype.shift.apply(arguments); var f = this[trans] || this['_' + trans]; f.apply(this, arguments); } else { this.elt.style[prop] = val; if ( prop === 'width' || prop === 'height' || prop === 'left' || prop === 'top' ) { var numVal = val.replace(/\D+/g, ''); this[prop] = parseInt(numVal, 10); // pend: is this necessary? } } } return this; }; /** * * Adds a new attribute or changes the value of an existing attribute * on the specified element. If no value is specified, returns the * value of the given attribute, or null if attribute is not set. * * @method attribute * @return {String} value of attribute * * @example * <div class='norender'><code> * var myDiv = createDiv('I like pandas.'); * myDiv.attribute('align', 'center'); * </code></div> */ /** * @method attribute * @param {String} attr attribute to set * @param {String} value value to assign to attribute * @chainable */ p5.Element.prototype.attribute = function(attr, value) { //handling for checkboxes and radios to ensure options get //attributes not divs if ( this.elt.firstChild != null && (this.elt.firstChild.type === 'checkbox' || this.elt.firstChild.type === 'radio') ) { if (typeof value === 'undefined') { return this.elt.firstChild.getAttribute(attr); } else { for (var i = 0; i < this.elt.childNodes.length; i++) { this.elt.childNodes[i].setAttribute(attr, value); } } } else if (typeof value === 'undefined') { return this.elt.getAttribute(attr); } else { this.elt.setAttribute(attr, value); return this; } }; /** * * Removes an attribute on the specified element. * * @method removeAttribute * @param {String} attr attribute to remove * @chainable * * @example * <div><code> * var button; * var checkbox; * * function setup() { * checkbox = createCheckbox('enable', true); * checkbox.changed(enableButton); * button = createButton('button'); * button.position(10, 10); * } * * function enableButton() { * if (this.checked()) { * // Re-enable the button * button.removeAttribute('disabled'); * } else { * // Disable the button * button.attribute('disabled', ''); * } * } * </code></div> */ p5.Element.prototype.removeAttribute = function(attr) { if ( this.elt.firstChild != null && (this.elt.firstChild.type === 'checkbox' || this.elt.firstChild.type === 'radio') ) { for (var i = 0; i < this.elt.childNodes.length; i++) { this.elt.childNodes[i].removeAttribute(attr); } } this.elt.removeAttribute(attr); return this; }; /** * Either returns the value of the element if no arguments * given, or sets the value of the element. * * @method value * @return {String|Number} value of the element * @example * <div class='norender'><code> * // gets the value * var inp; * function setup() { * inp = createInput(''); * } * * function mousePressed() { * print(inp.value()); * } * </code></div> * <div class='norender'><code> * // sets the value * var inp; * function setup() { * inp = createInput('myValue'); * } * * function mousePressed() { * inp.value('myValue'); * } * </code></div> */ /** * @method value * @param {String|Number} value * @chainable */ p5.Element.prototype.value = function() { if (arguments.length > 0) { this.elt.value = arguments[0]; return this; } else { if (this.elt.type === 'range') { return parseFloat(this.elt.value); } else return this.elt.value; } }; /** * * Shows the current element. Essentially, setting display:block for the style. * * @method show * @chainable * @example * <div class='norender'><code> * var div = createDiv('div'); * div.style('display', 'none'); * div.show(); // turns display to block * </code></div> */ p5.Element.prototype.show = function() { this.elt.style.display = 'block'; return this; }; /** * Hides the current element. Essentially, setting display:none for the style. * * @method hide * @chainable * @example * <div class='norender'><code> * var div = createDiv('this is a div'); * div.hide(); * </code></div> */ p5.Element.prototype.hide = function() { this.elt.style.display = 'none'; return this; }; /** * * Sets the width and height of the element. AUTO can be used to * only adjust one dimension. If no arguments given returns the width and height * of the element in an object. * * @method size * @return {Object} the width and height of the element in an object * @example * <div class='norender'><code> * var div = createDiv('this is a div'); * div.size(100, 100); * </code></div> */ /** * @method size * @param {Number|Constant} w width of the element, either AUTO, or a number * @param {Number|Constant} [h] height of the element, either AUTO, or a number * @chainable */ p5.Element.prototype.size = function(w, h) { if (arguments.length === 0) { return { width: this.elt.offsetWidth, height: this.elt.offsetHeight }; } else { var aW = w; var aH = h; var AUTO = p5.prototype.AUTO; if (aW !== AUTO || aH !== AUTO) { if (aW === AUTO) { aW = h * this.width / this.height; } else if (aH === AUTO) { aH = w * this.height / this.width; } // set diff for cnv vs normal div if (this.elt instanceof HTMLCanvasElement) { var j = {}; var k = this.elt.getContext('2d'); var prop; for (prop in k) { j[prop] = k[prop]; } this.elt.setAttribute('width', aW * this._pInst._pixelDensity); this.elt.setAttribute('height', aH * this._pInst._pixelDensity); this.elt.setAttribute( 'style', 'width:' + aW + 'px; height:' + aH + 'px' ); this._pInst.scale( this._pInst._pixelDensity, this._pInst._pixelDensity ); for (prop in j) { this.elt.getContext('2d')[prop] = j[prop]; } } else { this.elt.style.width = aW + 'px'; this.elt.style.height = aH + 'px'; this.elt.width = aW; this.elt.height = aH; this.width = aW; this.height = aH; } this.width = this.elt.offsetWidth; this.height = this.elt.offsetHeight; if (this._pInst && this._pInst._curElement) { // main canvas associated with p5 instance if (this._pInst._curElement.elt === this.elt) { this._pInst._setProperty('width', this.elt.offsetWidth); this._pInst._setProperty('height', this.elt.offsetHeight); } } } return this; } }; /** * Removes the element and deregisters all listeners. * @method remove * @example * <div class='norender'><code> * var myDiv = createDiv('this is some text'); * myDiv.remove(); * </code></div> */ p5.Element.prototype.remove = function() { // deregister events for (var ev in this._events) { this.elt.removeEventListener(ev, this._events[ev]); } if (this.elt.parentNode) { this.elt.parentNode.removeChild(this.elt); } delete this; }; // ============================================================================= // p5.MediaElement additions // ============================================================================= /** * Extends <a href="#/p5.Element">p5.Element</a> to handle audio and video. In addition to the methods * of <a href="#/p5.Element">p5.Element</a>, it also contains methods for controlling media. It is not * called directly, but <a href="#/p5.MediaElement">p5.MediaElement</a>s are created by calling <a href="#/p5/createVideo">createVideo</a>, * <a href="#/p5/createAudio">createAudio</a>, and <a href="#/p5/createCapture">createCapture</a>. * * @class p5.MediaElement * @constructor * @param {String} elt DOM node that is wrapped */ p5.MediaElement = function(elt, pInst) { p5.Element.call(this, elt, pInst); var self = this; this.elt.crossOrigin = 'anonymous'; this._prevTime = 0; this._cueIDCounter = 0; this._cues = []; this._pixelDensity = 1; this._modified = false; this._pixelsDirty = true; this._pixelsTime = -1; // the time at which we last updated 'pixels' /** * Path to the media element source. * * @property src * @return {String} src * @example * <div><code> * var ele; * * function setup() { * background(250); * * //p5.MediaElement objects are usually created * //by calling the createAudio(), createVideo(), * //and createCapture() functions. * * //In this example we create * //a new p5.MediaElement via createAudio(). * ele = createAudio('assets/beat.mp3'); * * //We'll set up our example so that * //when you click on the text, * //an alert box displays the MediaElement's * //src field. * textAlign(CENTER); * text('Click Me!', width / 2, height / 2); * } * * function mouseClicked() { * //here we test if the mouse is over the * //canvas element when it's clicked * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { * //Show our p5.MediaElement's src field * alert(ele.src); * } * } * </code></div> */ Object.defineProperty(self, 'src', { get: function() { var firstChildSrc = self.elt.children[0].src; var srcVal = self.elt.src === window.location.href ? '' : self.elt.src; var ret = firstChildSrc === window.location.href ? srcVal : firstChildSrc; return ret; }, set: function(newValue) { for (var i = 0; i < self.elt.children.length; i++) { self.elt.removeChild(self.elt.children[i]); } var source = document.createElement('source'); source.src = newValue; elt.appendChild(source); self.elt.src = newValue; self.modified = true; } }); // private _onended callback, set by the method: onended(callback) self._onended = function() {}; self.elt.onended = function() { self._onended(self); }; }; p5.MediaElement.prototype = Object.create(p5.Element.prototype); /** * Play an HTML5 media element. * * @method play * @chainable * @example * <div><code> * var ele; * * function setup() { * //p5.MediaElement objects are usually created * //by calling the createAudio(), createVideo(), * //and createCapture() functions. * * //In this example we create * //a new p5.MediaElement via createAudio(). * ele = createAudio('assets/beat.mp3'); * * background(250); * textAlign(CENTER); * text('Click to Play!', width / 2, height / 2); * } * * function mouseClicked() { * //here we test if the mouse is over the * //canvas element when it's clicked * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { * //Here we call the play() function on * //the p5.MediaElement we created above. * //This will start the audio sample. * ele.play(); * * background(200); * text('You clicked Play!', width / 2, height / 2); * } * } * </code></div> */ p5.MediaElement.prototype.play = function() { if (this.elt.currentTime === this.elt.duration) { this.elt.currentTime = 0; } var promise; if (this.elt.readyState > 1) { promise = this.elt.play(); } else { // in Chrome, playback cannot resume after being stopped and must reload this.elt.load(); promise = this.elt.play(); } if (promise && promise.catch) { promise.catch(function(e) { console.log( 'WARN: Element play method raised an error asynchronously', e ); }); } return this; }; /** * Stops an HTML5 media element (sets current time to zero). * * @method stop * @chainable * @example * <div><code> * //This example both starts * //and stops a sound sample * //when the user clicks the canvas * * //We will store the p5.MediaElement * //object in here * var ele; * * //while our audio is playing, * //this will be set to true * var sampleIsPlaying = false; * * function setup() { * //Here we create a p5.MediaElement object * //using the createAudio() function. * ele = createAudio('assets/beat.mp3'); * background(200); * textAlign(CENTER); * text('Click to play!', width / 2, height / 2); * } * * function mouseClicked() { * //here we test if the mouse is over the * //canvas element when it's clicked * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { * background(200); * * if (sampleIsPlaying) { * //if the sample is currently playing * //calling the stop() function on * //our p5.MediaElement will stop * //it and reset its current * //time to 0 (i.e. it will start * //at the beginning the next time * //you play it) * ele.stop(); * * sampleIsPlaying = false; * text('Click to play!', width / 2, height / 2); * } else { * //loop our sound element until we * //call ele.stop() on it. * ele.loop(); * * sampleIsPlaying = true; * text('Click to stop!', width / 2, height / 2); * } * } * } * </code></div> */ p5.MediaElement.prototype.stop = function() { this.elt.pause(); this.elt.currentTime = 0; return this; }; /** * Pauses an HTML5 media element. * * @method pause * @chainable * @example * <div><code> * //This example both starts * //and pauses a sound sample * //when the user clicks the canvas * * //We will store the p5.MediaElement * //object in here * var ele; * * //while our audio is playing, * //this will be set to true * var sampleIsPlaying = false; * * function setup() { * //Here we create a p5.MediaElement object * //using the createAudio() function. * ele = createAudio('assets/lucky_dragons.mp3'); * background(200); * textAlign(CENTER); * text('Click to play!', width / 2, height / 2); * } * * function mouseClicked() { * //here we test if the mouse is over the * //canvas element when it's clicked * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { * background(200); * * if (sampleIsPlaying) { * //Calling pause() on our * //p5.MediaElement will stop it * //playing, but when we call the * //loop() or play() functions * //the sample will start from * //where we paused it. * ele.pause(); * * sampleIsPlaying = false; * text('Click to resume!', width / 2, height / 2); * } else { * //loop our sound element until we * //call ele.pause() on it. * ele.loop(); * * sampleIsPlaying = true; * text('Click to pause!', width / 2, height / 2); * } * } * } * </code></div> */ p5.MediaElement.prototype.pause = function() { this.elt.pause(); return this; }; /** * Set 'loop' to true for an HTML5 media element, and starts playing. * * @method loop * @chainable * @example * <div><code> * //Clicking the canvas will loop * //the audio sample until the user * //clicks again to stop it * * //We will store the p5.MediaElement * //object in here * var ele; * * //while our audio is playing, * //this will be set to true * var sampleIsLooping = false; * * function setup() { * //Here we create a p5.MediaElement object * //using the createAudio() function. * ele = createAudio('assets/lucky_dragons.mp3'); * background(200); * textAlign(CENTER); * text('Click to loop!', width / 2, height / 2); * } * * function mouseClicked() { * //here we test if the mouse is over the * //canvas element when it's clicked * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { * background(200); * * if (!sampleIsLooping) { * //loop our sound element until we * //call ele.stop() on it. * ele.loop(); * * sampleIsLooping = true; * text('Click to stop!', width / 2, height / 2); * } else { * ele.stop(); * * sampleIsLooping = false; * text('Click to loop!', width / 2, height / 2); * } * } * } * </code></div> */ p5.MediaElement.prototype.loop = function() { this.elt.setAttribute('loop', true); this.play(); return this; }; /** * Set 'loop' to false for an HTML5 media element. Element will stop * when it reaches the end. * * @method noLoop * @chainable * @example * <div><code> * //This example both starts * //and stops loop of sound sample * //when the user clicks the canvas * * //We will store the p5.MediaElement * //object in here * var ele; * //while our audio is playing, * //this will be set to true * var sampleIsPlaying = false; * * function setup() { * //Here we create a p5.MediaElement object * //using the createAudio() function. * ele = createAudio('assets/beat.mp3'); * background(200); * textAlign(CENTER); * text('Click to play!', width / 2, height / 2); * } * * function mouseClicked() { * //here we test if the mouse is over the * //canvas element when it's clicked * if (mouseX >= 0 && mouseX <= width && mouseY >= 0 && mouseY <= height) { * background(200); * * if (sampleIsPlaying) { * ele.noLoop(); * text('No more Loops!', width / 2, height / 2); * } else { * ele.loop(); * sampleIsPlaying = true; * text('Click to stop looping!', width / 2, height / 2); * } * } * } * </code></div> * */ p5.MediaElement.prototype.noLoop = function() { this.elt.setAttribute('loop', false); return this; }; /** * Set HTML5 media element to autoplay or not. * * @method autoplay * @param {Boolean} autoplay whether the element should autoplay * @chainable */ p5.MediaElement.prototype.autoplay = function(val) { this.elt.setAttribute('autoplay', val); return this; }; /** * Sets volume for this HTML5 media element. If no argument is given, * returns the current volume. * * @method volume * @return {Number} current volume * * @example * <div><code> * var ele; * function setup() { * // p5.MediaElement objects are usually created * // by calling the createAudio(), createVideo(), * // and createCapture() functions. * // In this example we create * // a new p5.MediaElement via createAudio(). * ele = createAudio('assets/lucky_dragons.mp3'); * background(250); * textAlign(CENTER); * text('Click to Play!', width / 2, height / 2); * } * function mouseClicked() { * // Here we call the volume() function * // on the sound element to set its volume * // Volume must be between 0.0 and 1.0 * ele.volume(0.2); * ele.play(); * background(200); * text('You clicked Play!', width / 2, height / 2); * } * </code></div> * <div><code> * var audio; * var counter = 0; * * function loaded() { * audio.play(); * } * * function setup() { * audio = createAudio('assets/lucky_dragons.mp3', loaded); * textAlign(CENTER); * } * * function draw() { * if (counter === 0) { * background(0, 255, 0); * text('volume(0.9)', width / 2, height / 2); * } else if (counter === 1) { * background(255, 255, 0); * text('volume(0.5)', width / 2, height / 2); * } else if (counter === 2) { * background(255, 0, 0); * text('volume(0.1)', width / 2, height / 2); * } * } * * function mousePressed() { * counter++; * if (counter === 0) { * audio.volume(0.9); * } else if (counter === 1) { * audio.volume(0.5); * } else if (counter === 2) { * audio.volume(0.1); * } else { * counter = 0; * audio.volume(0.9); * } * } * </code> * </div> */ /** * @method volume * @param {Number} val volume between 0.0 and 1.0 * @chainable */ p5.MediaElement.prototype.volume = function(val) { if (typeof val === 'undefined') { return this.elt.volume; } else { this.elt.volume = val; } }; /** * If no arguments are given, returns the current playback speed of the * element. The speed parameter sets the speed where 2.0 will play the * element twice as fast, 0.5 will play at half the speed, and -1 will play * the element in normal speed in reverse.(Note that not all browsers support * backward playback and even if they do, playback might not be smooth.) * * @method speed * @return {Number} current playback speed of the element * * @example * <div class='norender notest'><code> * //Clicking the canvas will loop * //the audio sample until the user * //clicks again to stop it * * //We will store the p5.MediaElement * //object in here * var ele; * var button; * * function setup() { * createCanvas(710, 400); * //Here we create a p5.MediaElement object * //using the createAudio() function. * ele = createAudio('assets/beat.mp3'); * ele.loop(); * background(200); * * button = createButton('2x speed'); * button.position(100, 68); * button.mousePressed(twice_speed); * * button = createButton('half speed'); * button.position(200, 68); * button.mousePressed(half_speed); * * button = createButton('reverse play'); * button.position(300, 68); * button.mousePressed(reverse_speed); * * button = createButton('STOP'); * button.position(400, 68); * button.mousePressed(stop_song); * * button = createButton('PLAY!'); * button.position(500, 68); * button.mousePressed(play_speed); * } * * function twice_speed() { * ele.speed(2); * } * * function half_speed() { * ele.speed(0.5); * } * * function reverse_speed() { * ele.speed(-1); * } * * function stop_song() { * ele.stop(); * } * * function play_speed() { * ele.play(); * } * </code></div> */ /** * @method speed * @param {Number} speed speed multiplier for element playback * @chainable */ p5.MediaElement.prototype.speed = function(val) { if (typeof val === 'undefined') { return this.presetPlaybackRate || this.elt.playbackRate; } else { if (this.loadedmetadata) { this.elt.playbackRate = val; } else { this.presetPlaybackRate = val; } } }; /** * If no arguments are given, returns the current time of the element. * If an argument is given the current time of the element is set to it. * * @method time * @return {Number} current time (in seconds) * * @example * <div><code> * var ele; * var beginning = true; * function setup() { * //p5.MediaElement objects are usually created * //by calling the createAudio(), createVideo(), * //and createCapture() functions. * * //In this example we create * //a new p5.MediaElement via createAudio(). * ele = createAudio('assets/lucky_dragons.mp3'); * background(250); * textAlign(CENTER); * text('start at beginning', width / 2, height / 2); * } * * // this function fires with click anywhere * function mousePressed() { * if (beginning === true) { * // here we start the sound at the beginning * // time(0) is not necessary here * // as this produces the same result as * // play() * ele.play().time(0); * background(200); * text('jump 2 sec in', width / 2, height / 2); * beginning = false; * } else { * // here we jump 2 seconds into the sound * ele.play().time(2); * background(250); * text('start at beginning', width / 2, height / 2); * beginning = true; * } * } * </code></div> */ /** * @method time * @param {Number} time time to jump to (in seconds) * @chainable */ p5.MediaElement.prototype.time = function(val) { if (typeof val === 'undefined') { return this.elt.currentTime; } else { this.elt.currentTime = val; return this; } }; /** * Returns the duration of the HTML5 media element. * * @method duration * @return {Number} duration * * @example * <div><code> * var ele; * function setup() { * //p5.MediaElement objects are usually created * //by calling the createAudio(), createVideo(), * //and createCapture() functions. * //In this example we create * //a new p5.MediaElement via createAudio(). * ele = createAudio('assets/doorbell.mp3'); * background(250); * textAlign(CENTER); * text('Click to know the duration!', 10, 25, 70, 80); * } * function mouseClicked() { * ele.play(); * background(200); * //ele.duration dislpays the duration * text(ele.duration() + ' seconds', width / 2, height / 2); * } * </code></div> */ p5.MediaElement.prototype.duration = function() { return this.elt.duration; }; p5.MediaElement.prototype.pixels = []; p5.MediaElement.prototype._ensureCanvas = function() { if (!this.canvas) this.loadPixels(); }; p5.MediaElement.prototype.loadPixels = function() { if (!this.canvas) { this.canvas = document.createElement('canvas'); this.drawingContext = this.canvas.getContext('2d'); } if (this.loadedmetadata) { // wait for metadata for w/h if (this.canvas.width !== this.elt.width) { this.canvas.width = this.elt.width; this.canvas.height = this.elt.height; this.width = this.canvas.width; this.height = this.canvas.height; this._pixelsDirty = true; } var currentTime = this.elt.currentTime; if (this._pixelsDirty || this._pixelsTime !== currentTime) { // only update the pixels array if it's dirty, or // if the video time has changed. this._pixelsTime = currentTime; this._pixelsDirty = true; this.drawingContext.drawImage( this.elt, 0, 0, this.canvas.width, this.canvas.height ); p5.Renderer2D.prototype.loadPixels.call(this); } } this.setModified(true); return this; }; p5.MediaElement.prototype.updatePixels = function(x, y, w, h) { if (this.loadedmetadata) { // wait for metadata this._ensureCanvas(); p5.Renderer2D.prototype.updatePixels.call(this, x, y, w, h); } this.setModified(true); return this; }; p5.MediaElement.prototype.get = function(x, y, w, h) { if (this.loadedmetadata) { // wait for metadata var currentTime = this.elt.currentTime; if (this._pixelsTime !== currentTime) { this.loadPixels(); } else { this._ensureCanvas(); } return p5.Renderer2D.prototype.get.call(this, x, y, w, h); } else if (typeof x === 'undefined') { return new p5.Image(1, 1); } else if (w > 1) { return new p5.Image(x, y, w, h); } else { return [0, 0, 0, 255]; } }; p5.MediaElement.prototype.set = function(x, y, imgOrCol) { if (this.loadedmetadata) { // wait for metadata this._ensureCanvas(); p5.Renderer2D.prototype.set.call(this, x, y, imgOrCol); this.setModified(true); } }; p5.MediaElement.prototype.copy = function() { this._ensureCanvas(); p5.Renderer2D.prototype.copy.apply(this, arguments); }; p5.MediaElement.prototype.mask = function() { this.loadPixels(); this.setModified(true); p5.Image.prototype.mask.apply(this, arguments); }; /** * helper method for web GL mode to figure out if the element * has been modified and might need to be re-uploaded to texture * memory between frames. * @method isModified * @private * @return {boolean} a boolean indicating whether or not the * image has been updated or modified since last texture upload. */ p5.MediaElement.prototype.isModified = function() { return this._modified; }; /** * helper method for web GL mode to indicate that an element has been * changed or unchanged since last upload. gl texture upload will * set this value to false after uploading the texture; or might set * it to true if metadata has become available but there is no actual * texture data available yet.. * @method setModified * @param {boolean} val sets whether or not the element has been * modified. * @private */ p5.MediaElement.prototype.setModified = function(value) { this._modified = value; }; /** * Schedule an event to be called when the audio or video * element reaches the end. If the element is looping, * this will not be called. The element is passed in * as the argument to the onended callback. * * @method onended * @param {Function} callback function to call when the * soundfile has ended. The * media element will be passed * in as the argument to the * callback. * @chainable * @example * <div><code> * function setup() { * var audioEl = createAudio('assets/beat.mp3'); * audioEl.showControls(); * audioEl.onended(sayDone); * } * * function sayDone(elt) { * alert('done playing ' + elt.src); * } * </code></div> */ p5.MediaElement.prototype.onended = function(callback) { this._onended = callback; return this; }; /*** CONNECT TO WEB AUDIO API / p5.sound.js ***/ /** * Send the audio output of this element to a specified audioNode or * p5.sound object. If no element is provided, connects to p5's master * output. That connection is established when this method is first called. * All connections are removed by the .disconnect() method. * * This method is meant to be used with the p5.sound.js addon library. * * @method connect * @param {AudioNode|Object} audioNode AudioNode from the Web Audio API, * or an object from the p5.sound library */ p5.MediaElement.prototype.connect = function(obj) { var audioContext, masterOutput; // if p5.sound exists, same audio context if (typeof p5.prototype.getAudioContext === 'function') { audioContext = p5.prototype.getAudioContext(); masterOutput = p5.soundOut.input; } else { try { audioContext = obj.context; masterOutput = audioContext.destination; } catch (e) { throw 'connect() is meant to be used with Web Audio API or p5.sound.js'; } } // create a Web Audio MediaElementAudioSourceNode if none already exists if (!this.audioSourceNode) { this.audioSourceNode = audioContext.createMediaElementSource(this.elt); // connect to master output when this method is first called this.audioSourceNode.connect(masterOutput); } // connect to object if provided if (obj) { if (obj.input) { this.audioSourceNode.connect(obj.input); } else { this.audioSourceNode.connect(obj); } } else { // otherwise connect to master output of p5.sound / AudioContext this.audioSourceNode.connect(masterOutput); } }; /** * Disconnect all Web Audio routing, including to master output. * This is useful if you want to re-route the output through * audio effects, for example. * * @method disconnect */ p5.MediaElement.prototype.disconnect = function() { if (this.audioSourceNode) { this.audioSourceNode.disconnect(); } else { throw 'nothing to disconnect'; } }; /*** SHOW / HIDE CONTROLS ***/ /** * Show the default MediaElement controls, as determined by the web browser. * * @method showControls * @example * <div><code> * var ele; * function setup() { * //p5.MediaElement objects are usually created * //by calling the createAudio(), createVideo(), * //and createCapture() functions. * //In this example we create * //a new p5.MediaElement via createAudio() * ele = createAudio('assets/lucky_dragons.mp3'); * background(200); * textAlign(CENTER); * text('Click to Show Controls!', 10, 25, 70, 80); * } * function mousePressed() { * ele.showControls(); * background(200); * text('Controls Shown', width / 2, height / 2); * } * </code></div> */ p5.MediaElement.prototype.showControls = function() { // must set style for the element to show on the page this.elt.style['text-align'] = 'inherit'; this.elt.controls = true; }; /** * Hide the default mediaElement controls. * @method hideControls * @example * <div><code> * var ele; * function setup() { * //p5.MediaElement objects are usually created * //by calling the createAudio(), createVideo(), * //and createCapture() functions. * //In this example we create * //a new p5.MediaElement via createAudio() * ele = createAudio('assets/lucky_dragons.mp3'); * ele.showControls(); * background(200); * textAlign(CENTER); * text('Click to hide Controls!', 10, 25, 70, 80); * } * function mousePressed() { * ele.hideControls(); * background(200); * text('Controls hidden', width / 2, height / 2); * } * </code></div> */ p5.MediaElement.prototype.hideControls = function() { this.elt.controls = false; }; /*** SCHEDULE EVENTS ***/ // Cue inspired by JavaScript setTimeout, and the // Tone.js Transport Timeline Event, MIT License Yotam Mann 2015 tonejs.org var Cue = function(callback, time, id, val) { this.callback = callback; this.time = time; this.id = id; this.val = val; }; /** * Schedule events to trigger every time a MediaElement * (audio/video) reaches a playback cue point. * * Accepts a callback function, a time (in seconds) at which to trigger * the callback, and an optional parameter for the callback. * * Time will be passed as the first parameter to the callback function, * and param will be the second parameter. * * * @method addCue * @param {Number} time Time in seconds, relative to this media * element's playback. For example, to trigger * an event every time playback reaches two * seconds, pass in the number 2. This will be * passed as the first parameter to * the callback function. * @param {Function} callback Name of a function that will be * called at the given time. The callback will * receive time and (optionally) param as its * two parameters. * @param {Object} [value] An object to be passed as the * second parameter to the * callback function. * @return {Number} id ID of this cue, * useful for removeCue(id) * @example * <div><code> * // * // * function setup() { * noCanvas(); * * var audioEl = createAudio('assets/beat.mp3'); * audioEl.showControls(); * * // schedule three calls to changeBackground * audioEl.addCue(0.5, changeBackground, color(255, 0, 0)); * audioEl.addCue(1.0, changeBackground, color(0, 255, 0)); * audioEl.addCue(2.5, changeBackground, color(0, 0, 255)); * audioEl.addCue(3.0, changeBackground, color(0, 255, 255)); * audioEl.addCue(4.2, changeBackground, color(255, 255, 0)); * audioEl.addCue(5.0, changeBackground, color(255, 255, 0)); * } * * function changeBackground(val) { * background(val); * } * </code></div> */ p5.MediaElement.prototype.addCue = function(time, callback, val) { var id = this._cueIDCounter++; var cue = new Cue(callback, time, id, val); this._cues.push(cue); if (!this.elt.ontimeupdate) { this.elt.ontimeupdate = this._onTimeUpdate.bind(this); } return id; }; /** * Remove a callback based on its ID. The ID is returned by the * addCue method. * @method removeCue * @param {Number} id ID of the cue, as returned by addCue * @example * <div><code> * var audioEl, id1, id2; * function setup() { * background(255, 255, 255); * audioEl = createAudio('assets/beat.mp3'); * audioEl.showControls(); * // schedule five calls to changeBackground * id1 = audioEl.addCue(0.5, changeBackground, color(255, 0, 0)); * audioEl.addCue(1.0, changeBackground, color(0, 255, 0)); * audioEl.addCue(2.5, changeBackground, color(0, 0, 255)); * audioEl.addCue(3.0, changeBackground, color(0, 255, 255)); * id2 = audioEl.addCue(4.2, changeBackground, color(255, 255, 0)); * text('Click to remove first and last Cue!', 10, 25, 70, 80); * } * function mousePressed() { * audioEl.removeCue(id1); * audioEl.removeCue(id2); * } * function changeBackground(val) { * background(val); * } * </code></div> */ p5.MediaElement.prototype.removeCue = function(id) { for (var i = 0; i < this._cues.length; i++) { if (this._cues[i].id === id) { console.log(id); this._cues.splice(i, 1); } } if (this._cues.length === 0) { this.elt.ontimeupdate = null; } }; /** * Remove all of the callbacks that had originally been scheduled * via the addCue method. * @method clearCues * @param {Number} id ID of the cue, as returned by addCue * @example * <div><code> * var audioEl; * function setup() { * background(255, 255, 255); * audioEl = createAudio('assets/beat.mp3'); * //Show the default MediaElement controls, as determined by the web browser * audioEl.showControls(); * // schedule calls to changeBackground * background(200); * text('Click to change Cue!', 10, 25, 70, 80); * audioEl.addCue(0.5, changeBackground, color(255, 0, 0)); * audioEl.addCue(1.0, changeBackground, color(0, 255, 0)); * audioEl.addCue(2.5, changeBackground, color(0, 0, 255)); * audioEl.addCue(3.0, changeBackground, color(0, 255, 255)); * audioEl.addCue(4.2, changeBackground, color(255, 255, 0)); * } * function mousePressed() { * // here we clear the scheduled callbacks * audioEl.clearCues(); * // then we add some more callbacks * audioEl.addCue(1, changeBackground, color(2, 2, 2)); * audioEl.addCue(3, changeBackground, color(255, 255, 0)); * } * function changeBackground(val) { * background(val); * } * </code></div> */ p5.MediaElement.prototype.clearCues = function() { this._cues = []; this.elt.ontimeupdate = null; }; // private method that checks for cues to be fired if events // have been scheduled using addCue(callback, time). p5.MediaElement.prototype._onTimeUpdate = function() { var playbackTime = this.time(); for (var i = 0; i < this._cues.length; i++) { var callbackTime = this._cues[i].time; var val = this._cues[i].val; if (this._prevTime < callbackTime && callbackTime <= playbackTime) { // pass the scheduled callbackTime as parameter to the callback this._cues[i].callback(val); } } this._prevTime = playbackTime; }; // ============================================================================= // p5.File // ============================================================================= /** * Base class for a file * Using this for createFileInput * * @class p5.File * @constructor * @param {File} file File that is wrapped */ p5.File = function(file, pInst) { /** * Underlying File object. All normal File methods can be called on this. * * @property file */ this.file = file; this._pInst = pInst; // Splitting out the file type into two components // This makes determining if image or text etc simpler var typeList = file.type.split('/'); /** * File type (image, text, etc.) * * @property type */ this.type = typeList[0]; /** * File subtype (usually the file extension jpg, png, xml, etc.) * * @property subtype */ this.subtype = typeList[1]; /** * File name * * @property name */ this.name = file.name; /** * File size * * @property size */ this.size = file.size; /** * URL string containing image data. * * @property data */ this.data = undefined; }; }); p5.File._createLoader = function(theFile, callback) { var reader = new FileReader(); reader.onload = function(e) { var p5file = new p5.File(theFile); p5file.data = e.target.result; callback(p5file); }; return reader; }; p5.File._load = function(f, callback) { // Text or data? // This should likely be improved if (/^text\//.test(f.type)) { p5.File._createLoader(f, callback).readAsText(f); } else if (!/^(video|audio)\//.test(f.type)) { p5.File._createLoader(f, callback).readAsDataURL(f); } else { var file = new p5.File(f); file.data = URL.createObjectURL(f); callback(file); } };
(function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }());
var Syncano = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(1); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _forEach2 = __webpack_require__(13); var _forEach3 = _interopRequireDefault(_forEach2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _models = __webpack_require__(72); var _models2 = _interopRequireDefault(_models); var _account = __webpack_require__(258); var _account2 = _interopRequireDefault(_account); var _pinger = __webpack_require__(259); var _pinger2 = _interopRequireDefault(_pinger); var _file = __webpack_require__(230); var _file2 = _interopRequireDefault(_file); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Main Syncano object. * @constructor * @type {Syncano} * @param {Object} options All configuration options * @param {Object} [options.baseUrl = 'https://api.syncano.io'] Base URL for all api calls. * @param {Object} [options.accountKey = null] Your Syncano account key. * @param {Object} [options.userKey = null] Instance user api key. * @param {Object} [options.socialToken = null] Instance social authentication token. * @returns {Syncano} * @example {@lang javascript} * var connection = Syncano({accountKey: '123'}); * var connection = Syncano({userKey: '123'}); * var connection = Syncano({socialToken: '123'}); */ var Syncano = (0, _stampit2.default)() // We need function here, do not use arrow syntax! .init(function () { var _this = this; this.Account = _account2.default.setConfig(this)(); this.Monitor = _pinger2.default.setConfig(this)(); (0, _forEach3.default)(_models2.default, function (model, name) { _this[name] = model.setConfig(_this); }); }).refs({ baseUrl: 'https://api.syncano.io', accountKey: null, userKey: null, apiKey: null, socialToken: null }).methods({ /** * Sets *baseUrl*. * @memberOf Syncano * @instance * @param {String} baseUrl Base URL for all api calls * @returns {Syncano} * @throws {Error} Base URL is required. * @example {@lang javascript} * var connection = Syncano({accountKey: '123'}); * connection.setBaseUrl('https://dummy.com/'); */ setBaseUrl: function setBaseUrl(baseUrl) { if ((0, _isEmpty3.default)(baseUrl)) throw new Error('Base URL is required.'); this.baseUrl = baseUrl; return this; }, /** * Gets *baseUrl*. * @memberOf Syncano * @instance * @returns {String} * @example {@lang javascript} * var connection = Syncano({accountKey: '123'}); * var baseUrl = connection.getBaseUrl(); */ getBaseUrl: function getBaseUrl() { return this.baseUrl; }, /** * Sets *accountKey*. * @memberOf Syncano * @instance * @param {String} accountKey Your {@link https://syncano.io|Syncano} account key * @returns {Syncano} * @example {@lang javascript} * var connection = Syncano({accountKey: '123'}); * connection.setAccountKey('abcd'); */ setAccountKey: function setAccountKey(accountKey) { this.accountKey = accountKey; return this; }, /** * Gets *accountKey*. * @memberOf Syncano * @instance * @returns {String} * @example {@lang javascript} * var connection = Syncano({accountKey: '123'}); * var accountKey = connection.getAccountKey(); */ getAccountKey: function getAccountKey() { return this.accountKey; }, /** * Sets *userKey*. * @memberOf Syncano * @instance * @param {String} userKey Instance user api key * @returns {Syncano} * @example {@lang javascript} * var connection = Syncano({userKey: '123'}); * connection.setUserKey('abcd'); */ setUserKey: function setUserKey(userKey) { this.userKey = userKey; return this; }, /** * Gets *userKey*. * @memberOf Syncano * @instance * @returns {String} * @example {@lang javascript} * var connection = Syncano({userKey: '123'}); * var userKey = connection.getUserKey(); */ getUserKey: function getUserKey() { return this.userKey; }, /** * Sets *apiKey*. * @memberOf Syncano * @instance * @param {String} apiKey Instance user api key * @returns {Syncano} * @example {@lang javascript} * var connection = Syncano({apiKey: '123'}); * connection.setApiKey('abcd'); */ setApiKey: function setApiKey(apiKey) { this.apiKey = apiKey; return this; }, /** * Gets *apiKey*. * @memberOf Syncano * @instance * @returns {String} * @example {@lang javascript} * var connection = Syncano({apiKey: '123'}); * var apiKey = connection.getApiKey(); */ getApiKey: function getApiKey() { return this.apiKey; }, /** * Sets *socialToken*. * @memberOf Syncano * @instance * @param {String} socialToken Instance social authentication token * @returns {Syncano} * @example {@lang javascript} * var connection = Syncano({socialToken: '123'}); * connection.setSocialToken('abcd'); */ setSocialToken: function setSocialToken(socialToken) { this.socialToken = socialToken; return this; }, /** * Gets *socialToken*. * @memberOf Syncano * @instance * @returns {String} * @example {@lang javascript} * var connection = Syncano({socialToken: '123'}); * var socialToken = connection.getSocialToken(); */ getSocialToken: function getSocialToken() { return this.socialToken; }, file: function file(content) { return new _file2.default(content); } }).static({ file: function file(content) { return new _file2.default(content); } }); exports.default = Syncano; module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var isArguments = __webpack_require__(2), isArray = __webpack_require__(11), isArrayLike = __webpack_require__(4), isFunction = __webpack_require__(7), isString = __webpack_require__(12); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if `value` is an empty collection or object. A value is considered * empty if it's an `arguments` object, array, string, or jQuery-like collection * with a length of `0` or has no own enumerable properties. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (isArrayLike(value) && (isArray(value) || isString(value) || isFunction(value.splice) || isArguments(value))) { return !value.length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } module.exports = isEmpty; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var isArrayLikeObject = __webpack_require__(3); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { // Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } module.exports = isArguments; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(4), isObjectLike = __webpack_require__(10); /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } module.exports = isArrayLikeObject; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var getLength = __webpack_require__(5), isFunction = __webpack_require__(7), isLength = __webpack_require__(9); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(getLength(value)) && !isFunction(value); } module.exports = isArrayLike; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(6); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; /***/ }, /* 6 */ /***/ function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(8); /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8 which returns 'object' for typed array and weak map constructors, // and PhantomJS 1.9 which returns 'function' for `NodeList` instances. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } module.exports = isFunction; /***/ }, /* 8 */ /***/ function(module, exports) { /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 9 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is loosely based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }, /* 10 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 11 */ /***/ function(module, exports) { /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @type {Function} * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(11), isObjectLike = __webpack_require__(10); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); } module.exports = isString; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(14), baseCastFunction = __webpack_require__(15), baseEach = __webpack_require__(17), isArray = __webpack_require__(11); /** * Iterates over elements of `collection` invoking `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" property * are iterated like arrays. To avoid this behavior use `_.forIn` or `_.forOwn` * for object iteration. * * @static * @memberOf _ * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @example * * _([1, 2]).forEach(function(value) { * console.log(value); * }); * // => logs `1` then `2` * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => logs 'a' then 'b' (iteration order is not guaranteed) */ function forEach(collection, iteratee) { return (typeof iteratee == 'function' && isArray(collection)) ? arrayEach(collection, iteratee) : baseEach(collection, baseCastFunction(iteratee)); } module.exports = forEach; /***/ }, /* 14 */ /***/ function(module, exports) { /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(16); /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Array} Returns the array-like object. */ function baseCastFunction(value) { return typeof value == 'function' ? value : identity; } module.exports = baseCastFunction; /***/ }, /* 16 */ /***/ function(module, exports) { /** * This method returns the first argument given to it. * * @static * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(18), createBaseEach = __webpack_require__(28); /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); module.exports = baseEach; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(19), keys = __webpack_require__(21); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } module.exports = baseForOwn; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(20); /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; /***/ }, /* 20 */ /***/ function(module, exports) { /** * Creates a base function for methods like `_.forIn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(22), baseKeys = __webpack_require__(23), indexKeys = __webpack_require__(24), isArrayLike = __webpack_require__(4), isIndex = __webpack_require__(26), isPrototype = __webpack_require__(27); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { var isProto = isPrototype(object); if (!(isProto || isArrayLike(object))) { return baseKeys(object); } var indexes = indexKeys(object), skipIndexes = !!indexes, result = indexes || [], length = result.length; for (var key in object) { if (baseHas(object, key) && !(skipIndexes && (key == 'length' || isIndex(key, length))) && !(isProto && key == 'constructor')) { result.push(key); } } return result; } module.exports = keys; /***/ }, /* 22 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var getPrototypeOf = Object.getPrototypeOf; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} object The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { // Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`, // that are composed entirely of index properties, return `false` for // `hasOwnProperty` checks of them. return hasOwnProperty.call(object, key) || (typeof object == 'object' && key in object && getPrototypeOf(object) === null); } module.exports = baseHas; /***/ }, /* 23 */ /***/ function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = Object.keys; /** * The base implementation of `_.keys` which doesn't skip the constructor * property of prototypes or treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { return nativeKeys(Object(object)); } module.exports = baseKeys; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(25), isArguments = __webpack_require__(2), isArray = __webpack_require__(11), isLength = __webpack_require__(9), isString = __webpack_require__(12); /** * Creates an array of index keys for `object` values of arrays, * `arguments` objects, and strings, otherwise `null` is returned. * * @private * @param {Object} object The object to query. * @returns {Array|null} Returns index keys, else `null`. */ function indexKeys(object) { var length = object ? object.length : undefined; if (isLength(length) && (isArray(object) || isString(object) || isArguments(object))) { return baseTimes(length, String); } return null; } module.exports = indexKeys; /***/ }, /* 25 */ /***/ function(module, exports) { /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } module.exports = baseTimes; /***/ }, /* 26 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } module.exports = isIndex; /***/ }, /* 27 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } module.exports = isPrototype; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(4); /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } module.exports = createBaseEach; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /** * Stampit ** * Create objects from reusable, composable behaviors. ** * Copyright (c) 2013 Eric Elliott * http://opensource.org/licenses/MIT **/ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashCollectionForEach = __webpack_require__(30); var _lodashCollectionForEach2 = _interopRequireDefault(_lodashCollectionForEach); var _lodashLangIsFunction = __webpack_require__(41); var _lodashLangIsFunction2 = _interopRequireDefault(_lodashLangIsFunction); var _lodashLangIsObject = __webpack_require__(37); var _lodashLangIsObject2 = _interopRequireDefault(_lodashLangIsObject); var _supermixer = __webpack_require__(56); var create = Object.create; function isThenable(value) { return value && (0, _lodashLangIsFunction2['default'])(value.then); } function extractFunctions() { var result = []; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if ((0, _lodashLangIsFunction2['default'])(args[0])) { (0, _lodashCollectionForEach2['default'])(args, function (fn) { // assuming all the arguments are functions if ((0, _lodashLangIsFunction2['default'])(fn)) { result.push(fn); } }); } else if ((0, _lodashLangIsObject2['default'])(args[0])) { (0, _lodashCollectionForEach2['default'])(args, function (obj) { (0, _lodashCollectionForEach2['default'])(obj, function (fn) { if ((0, _lodashLangIsFunction2['default'])(fn)) { result.push(fn); } }); }); } return result; } function addMethods(fixed) { for (var _len2 = arguments.length, methods = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { methods[_key2 - 1] = arguments[_key2]; } return _supermixer.mixinFunctions.apply(undefined, [fixed.methods].concat(methods)); } function addRefs(fixed) { for (var _len3 = arguments.length, refs = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { refs[_key3 - 1] = arguments[_key3]; } fixed.refs = fixed.state = _supermixer.mixin.apply(undefined, [fixed.refs].concat(refs)); return fixed.refs; } function addInit(fixed) { for (var _len4 = arguments.length, inits = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { inits[_key4 - 1] = arguments[_key4]; } var extractedInits = extractFunctions.apply(undefined, inits); fixed.init = fixed.enclose = fixed.init.concat(extractedInits); return fixed.init; } function addProps(fixed) { for (var _len5 = arguments.length, propses = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { propses[_key5 - 1] = arguments[_key5]; } return _supermixer.merge.apply(undefined, [fixed.props].concat(propses)); } function addStatic(fixed) { for (var _len6 = arguments.length, statics = Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { statics[_key6 - 1] = arguments[_key6]; } return _supermixer.mixin.apply(undefined, [fixed['static']].concat(statics)); } function cloneAndExtend(fixed, extensionFunction) { var stamp = stampit(fixed); for (var _len7 = arguments.length, args = Array(_len7 > 2 ? _len7 - 2 : 0), _key7 = 2; _key7 < _len7; _key7++) { args[_key7 - 2] = arguments[_key7]; } extensionFunction.apply(undefined, [stamp.fixed].concat(args)); return stamp; } function _compose() { var result = stampit(); for (var _len8 = arguments.length, factories = Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { factories[_key8] = arguments[_key8]; } (0, _lodashCollectionForEach2['default'])(factories, function (source) { if (source && source.fixed) { addMethods(result.fixed, source.fixed.methods); // We might end up having two different stampit modules loaded and used in conjunction. // These || operators ensure that old stamps could be combined with the current version stamps. // 'state' is the old name for 'refs' addRefs(result.fixed, source.fixed.refs || source.fixed.state); // 'enclose' is the old name for 'init' addInit(result.fixed, source.fixed.init || source.fixed.enclose); addProps(result.fixed, source.fixed.props); addStatic(result.fixed, source.fixed['static']); } }); return (0, _supermixer.mixin)(result, result.fixed['static']); } /** * Return a factory function that will produce new objects using the * components that are passed in or composed. * * @param {Object} [options] Options to build stamp from: `{ methods, refs, init, props }` * @param {Object} [options.methods] A map of method names and bodies for delegation. * @param {Object} [options.refs] A map of property names and values to be mixed into each new object. * @param {Object} [options.init] A closure (function) used to create private data and privileged methods. * @param {Object} [options.props] An object to be deeply cloned into each newly stamped object. * @param {Object} [options.static] An object to be mixed into each `this` and derived stamps (not objects!). * @return {Function(refs)} factory A factory to produce objects. * @return {Function(refs)} factory.create Just like calling the factory function. * @return {Object} factory.fixed An object map containing the stamp components. * @return {Function(methods)} factory.methods Add methods to the stamp. Chainable. * @return {Function(refs)} factory.refs Add references to the stamp. Chainable. * @return {Function(Function(context))} factory.init Add a closure which called on object instantiation. Chainable. * @return {Function(props)} factory.props Add deeply cloned properties to the produced objects. Chainable. * @return {Function(stamps)} factory.compose Combine several stamps into single. Chainable. * @return {Function(statics)} factory.static Add properties to the stamp (not objects!). Chainable. */ var stampit = function stampit(options) { var fixed = { methods: {}, refs: {}, init: [], props: {}, 'static': {} }; fixed.state = fixed.refs; // Backward compatibility. 'state' is the old name for 'refs'. fixed.enclose = fixed.init; // Backward compatibility. 'enclose' is the old name for 'init'. if (options) { addMethods(fixed, options.methods); addRefs(fixed, options.refs); addInit(fixed, options.init); addProps(fixed, options.props); addStatic(fixed, options['static']); } var factory = function Factory(refs) { for (var _len9 = arguments.length, args = Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) { args[_key9 - 1] = arguments[_key9]; } var instance = (0, _supermixer.mixin)(create(fixed.methods), fixed.refs, refs); (0, _supermixer.mergeUnique)(instance, fixed.props); // props are safely merged into refs var nextPromise = null; if (fixed.init.length > 0) { (0, _lodashCollectionForEach2['default'])(fixed.init, function (fn) { if (!(0, _lodashLangIsFunction2['default'])(fn)) { return; // not a function, do nothing. } // Check if we are in the async mode. if (!nextPromise) { // Call the init(). var callResult = fn.call(instance, { args: args, instance: instance, stamp: factory }); if (!callResult) { return; // The init() returned nothing. Proceed to the next init(). } // Returned value is meaningful. // It will replace the stampit-created object. if (!isThenable(callResult)) { instance = callResult; // stamp is synchronous so far. return; } // This is the sync->async conversion point. // Since now our factory will return a promise, not an object. nextPromise = callResult; } else { // As long as one of the init() functions returned a promise, // now our factory will 100% return promise too. // Linking the init() functions into the promise chain. nextPromise = nextPromise.then(function (newInstance) { // The previous promise might want to return a value, // which we should take as a new object instance. instance = newInstance || instance; // Calling the following init(). // NOTE, than `fn` is wrapped to a closure within the forEach loop. var callResult = fn.call(instance, { args: args, instance: instance, stamp: factory }); // Check if call result is truthy. if (!callResult) { // The init() returned nothing. Thus using the previous object instance. return instance; } if (!isThenable(callResult)) { // This init() was synchronous and returned a meaningful value. instance = callResult; // Resolve the instance for the next `then()`. return instance; } // The init() returned another promise. It is becoming our nextPromise. return callResult; }); } }); } // At the end we should resolve the last promise and // return the resolved value (as a promise too). return nextPromise ? nextPromise.then(function (newInstance) { return newInstance || instance; }) : instance; }; var refsMethod = cloneAndExtend.bind(null, fixed, addRefs); var initMethod = cloneAndExtend.bind(null, fixed, addInit); return (0, _supermixer.mixin)(factory, { /** * Creates a new object instance form the stamp. */ create: factory, /** * The stamp components. */ fixed: fixed, /** * Take n objects and add them to the methods list of a new stamp. Creates new stamp. * @return {Function} A new stamp (factory object). */ methods: cloneAndExtend.bind(null, fixed, addMethods), /** * Take n objects and add them to the references list of a new stamp. Creates new stamp. * @return {Function} A new stamp (factory object). */ refs: refsMethod, /** * @deprecated since v2.0. Use refs() instead. * Alias to refs(). * @return {Function} A new stamp (factory object). */ state: refsMethod, /** * Take n functions, an array of functions, or n objects and add * the functions to the initializers list of a new stamp. Creates new stamp. * @return {Function} A new stamp (factory object). */ init: initMethod, /** * @deprecated since v2.0. User init() instead. * Alias to init(). * @return {Function} A new stamp (factory object). */ enclose: initMethod, /** * Take n objects and deep merge them to the properties. Creates new stamp. * @return {Function} A new stamp (factory object). */ props: cloneAndExtend.bind(null, fixed, addProps), /** * Take n objects and add all props to the factory object. Creates new stamp. * @return {Function} A new stamp (factory object). */ 'static': function _static() { for (var _len10 = arguments.length, statics = Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { statics[_key10] = arguments[_key10]; } var newStamp = cloneAndExtend.apply(undefined, [factory.fixed, addStatic].concat(statics)); return (0, _supermixer.mixin)(newStamp, newStamp.fixed['static']); }, /** * Take one or more factories produced from stampit() and * combine them with `this` to produce and return a new factory. * Combining overrides properties with last-in priority. * @param {[Function]|...Function} factories Stampit factories. * @return {Function} A new stampit factory composed from arguments. */ compose: function compose() { for (var _len11 = arguments.length, factories = Array(_len11), _key11 = 0; _key11 < _len11; _key11++) { factories[_key11] = arguments[_key11]; } return _compose.apply(undefined, [factory].concat(factories)); } }, fixed['static']); }; // Static methods function isStamp(obj) { return (0, _lodashLangIsFunction2['default'])(obj) && (0, _lodashLangIsFunction2['default'])(obj.methods) && ( // isStamp can be called for old stampit factory object. // We should check old names (state and enclose) too. (0, _lodashLangIsFunction2['default'])(obj.refs) || (0, _lodashLangIsFunction2['default'])(obj.state)) && ((0, _lodashLangIsFunction2['default'])(obj.init) || (0, _lodashLangIsFunction2['default'])(obj.enclose)) && (0, _lodashLangIsFunction2['default'])(obj.props) && (0, _lodashLangIsFunction2['default'])(obj['static']) && (0, _lodashLangIsObject2['default'])(obj.fixed); } function convertConstructor(Constructor) { var stamp = stampit(); stamp.fixed.refs = stamp.fixed.state = (0, _supermixer.mergeChainNonFunctions)(stamp.fixed.refs, Constructor.prototype); (0, _supermixer.mixin)(stamp, (0, _supermixer.mixin)(stamp.fixed['static'], Constructor)); (0, _supermixer.mixinChainFunctions)(stamp.fixed.methods, Constructor.prototype); addInit(stamp.fixed, function (_ref) { var instance = _ref.instance; var args = _ref.args; return Constructor.apply(instance, args); }); return stamp; } function shortcutMethod(extensionFunction) { var stamp = stampit(); for (var _len12 = arguments.length, args = Array(_len12 > 1 ? _len12 - 1 : 0), _key12 = 1; _key12 < _len12; _key12++) { args[_key12 - 1] = arguments[_key12]; } extensionFunction.apply(undefined, [stamp.fixed].concat(args)); return stamp; } function mixinWithConsoleWarning() { console.log('stampit.mixin(), .mixIn(), .extend(), and .assign() are deprecated.', 'Use Object.assign or _.assign instead'); return _supermixer.mixin.apply(this, arguments); } exports['default'] = (0, _supermixer.mixin)(stampit, { /** * Take n objects and add them to the methods list of a new stamp. Creates new stamp. * @return {Function} A new stamp (factory object). */ methods: shortcutMethod.bind(null, addMethods), /** * Take n objects and add them to the references list of a new stamp. Creates new stamp. * @return {Function} A new stamp (factory object). */ refs: shortcutMethod.bind(null, addRefs), /** * Take n functions, an array of functions, or n objects and add * the functions to the initializers list of a new stamp. Creates new stamp. * @return {Function} A new stamp (factory object). */ init: shortcutMethod.bind(null, addInit), /** * Take n objects and deep merge them to the properties. Creates new stamp. * @return {Function} A new stamp (factory object). */ props: shortcutMethod.bind(null, addProps), /** * Take n objects and add all props to the factory object. Creates new stamp. * @return {Function} A new stamp (factory object). */ 'static': function _static() { for (var _len13 = arguments.length, statics = Array(_len13), _key13 = 0; _key13 < _len13; _key13++) { statics[_key13] = arguments[_key13]; } var newStamp = shortcutMethod.apply(undefined, [addStatic].concat(statics)); return (0, _supermixer.mixin)(newStamp, newStamp.fixed['static']); }, /** * Take two or more factories produced from stampit() and * combine them to produce a new factory. * Combining overrides properties with last-in priority. * @param {[Function]|...Function} factories Stamps produced by stampit(). * @return {Function} A new stampit factory composed from arguments. */ compose: _compose, /** * @deprecated Since v2.2. Use Object.assign or _.assign instead. * Alias to Object.assign. */ mixin: mixinWithConsoleWarning, extend: mixinWithConsoleWarning, mixIn: mixinWithConsoleWarning, assign: mixinWithConsoleWarning, /** * Check if an object is a stamp. * @param {Object} obj An object to check. * @returns {Boolean} */ isStamp: isStamp, /** * Take an old-fashioned JS constructor and return a stampit stamp * that you can freely compose with other stamps. * @param {Function} Constructor * @return {Function} A composable stampit factory (aka stamp). */ convertConstructor: convertConstructor }); module.exports = exports['default']; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(31), baseEach = __webpack_require__(32), createForEach = __webpack_require__(53); /** * Iterates over elements of `collection` invoking `iteratee` for each element. * The `iteratee` is bound to `thisArg` and invoked with three arguments: * (value, index|key, collection). Iteratee functions may exit iteration early * by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" property * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` * may be used for object iteration. * * @static * @memberOf _ * @alias each * @category Collection * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2]).forEach(function(n) { * console.log(n); * }).value(); * // => logs each value from left to right and returns the array * * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) { * console.log(n, key); * }); * // => logs each value-key pair and returns the object (iteration order is not guaranteed) */ var forEach = createForEach(arrayEach, baseEach); module.exports = forEach; /***/ }, /* 31 */ /***/ function(module, exports) { /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(33), createBaseEach = __webpack_require__(52); /** * The base implementation of `_.forEach` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object|string} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); module.exports = baseEach; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(34), keys = __webpack_require__(38); /** * The base implementation of `_.forOwn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } module.exports = baseForOwn; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(35); /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var toObject = __webpack_require__(36); /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(37); /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { return isObject(value) ? value : Object(value); } module.exports = toObject; /***/ }, /* 37 */ /***/ function(module, exports) { /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(39), isArrayLike = __webpack_require__(43), isObject = __webpack_require__(37), shimKeys = __webpack_require__(47); /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? undefined : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; module.exports = keys; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var isNative = __webpack_require__(40); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } module.exports = getNative; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(41), isObjectLike = __webpack_require__(42); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } module.exports = isNative; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(37); /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 which returns 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } module.exports = isFunction; /***/ }, /* 42 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var getLength = __webpack_require__(44), isLength = __webpack_require__(46); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } module.exports = isArrayLike; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(45); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; /***/ }, /* 45 */ /***/ function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }, /* 46 */ /***/ function(module, exports) { /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { var isArguments = __webpack_require__(48), isArray = __webpack_require__(49), isIndex = __webpack_require__(50), isLength = __webpack_require__(46), keysIn = __webpack_require__(51); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } module.exports = shimKeys; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(43), isObjectLike = __webpack_require__(42); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); } module.exports = isArguments; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(39), isLength = __webpack_require__(46), isObjectLike = __webpack_require__(42); /** `Object#toString` result references. */ var arrayTag = '[object Array]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; module.exports = isArray; /***/ }, /* 50 */ /***/ function(module, exports) { /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } module.exports = isIndex; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { var isArguments = __webpack_require__(48), isArray = __webpack_require__(49), isIndex = __webpack_require__(50), isLength = __webpack_require__(46), isObject = __webpack_require__(37); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object)) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = keysIn; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var getLength = __webpack_require__(44), isLength = __webpack_require__(46), toObject = __webpack_require__(36); /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } module.exports = createBaseEach; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { var bindCallback = __webpack_require__(54), isArray = __webpack_require__(49); /** * Creates a function for `_.forEach` or `_.forEachRight`. * * @private * @param {Function} arrayFunc The function to iterate over an array. * @param {Function} eachFunc The function to iterate over a collection. * @returns {Function} Returns the new each function. */ function createForEach(arrayFunc, eachFunc) { return function(collection, iteratee, thisArg) { return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) ? arrayFunc(collection, iteratee) : eachFunc(collection, bindCallback(iteratee, thisArg, 3)); }; } module.exports = createForEach; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(55); /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } module.exports = bindCallback; /***/ }, /* 55 */ /***/ function(module, exports) { /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _mixer = __webpack_require__(57); var _mixer2 = _interopRequireDefault(_mixer); var _lodashLangIsFunction = __webpack_require__(41); var _lodashLangIsFunction2 = _interopRequireDefault(_lodashLangIsFunction); var isNotFunction = function isNotFunction(val) { return !(0, _lodashLangIsFunction2['default'])(val); }; /** * Regular mixin function. */ var mixin = (0, _mixer2['default'])(); /** * Mixin functions only. */ var mixinFunctions = (0, _mixer2['default'])({ filter: _lodashLangIsFunction2['default'] }); /** * Mixin functions including prototype chain. */ var mixinChainFunctions = (0, _mixer2['default'])({ filter: _lodashLangIsFunction2['default'], chain: true }); /** * Regular object merge function. Ignores functions. */ var merge = (0, _mixer2['default'])({ deep: true }); /** * Regular object merge function. Ignores functions. */ var mergeUnique = (0, _mixer2['default'])({ deep: true, noOverwrite: true }); /** * Merge objects including prototype chain properties. */ var mergeChainNonFunctions = (0, _mixer2['default'])({ filter: isNotFunction, deep: true, chain: true }); exports['default'] = _mixer2['default']; exports.mixin = mixin; exports.mixinFunctions = mixinFunctions; exports.mixinChainFunctions = mixinChainFunctions; exports.merge = merge; exports.mergeUnique = mergeUnique; exports.mergeChainNonFunctions = mergeChainNonFunctions; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = mixer; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashObjectForOwn = __webpack_require__(58); var _lodashObjectForOwn2 = _interopRequireDefault(_lodashObjectForOwn); var _lodashObjectForIn = __webpack_require__(60); var _lodashObjectForIn2 = _interopRequireDefault(_lodashObjectForIn); var _lodashLangCloneDeep = __webpack_require__(62); var _lodashLangCloneDeep2 = _interopRequireDefault(_lodashLangCloneDeep); var _lodashLangIsObject = __webpack_require__(37); var _lodashLangIsObject2 = _interopRequireDefault(_lodashLangIsObject); var _lodashLangIsUndefined = __webpack_require__(71); var _lodashLangIsUndefined2 = _interopRequireDefault(_lodashLangIsUndefined); /** * Factory for creating mixin functions of all kinds. * * @param {Object} opts * @param {Function} opts.filter Function which filters value and key. * @param {Function} opts.transform Function which transforms each value. * @param {Boolean} opts.chain Loop through prototype properties too. * @param {Boolean} opts.deep Deep looping through the nested properties. * @param {Boolean} opts.noOverwrite Do not overwrite any existing data (aka first one wins). * @return {Function} A new mix function. */ function mixer() { var opts = arguments[0] === undefined ? {} : arguments[0]; // We will be recursively calling the exact same function when walking deeper. if (opts.deep && !opts._innerMixer) { opts._innerMixer = true; // avoiding infinite recursion. opts._innerMixer = mixer(opts); // create same mixer for recursion purpose. } /** * Combine properties from the passed objects into target. This method mutates target, * if you want to create a new Object pass an empty object as first param. * * @param {Object} target Target Object * @param {...Object} objects Objects to be combined (0...n objects). * @return {Object} The mixed object. */ return function mix(target) { for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { sources[_key - 1] = arguments[_key]; } // Check if it's us who called the function. See recursion calls are below. if ((0, _lodashLangIsUndefined2['default'])(target) || !opts.noOverwrite && !(0, _lodashLangIsObject2['default'])(target)) { if (sources.length > 1) { // Weird, but someone (not us!) called this mixer with an incorrect first argument. return opts._innerMixer.apply(opts, [{}].concat(sources)); } return (0, _lodashLangCloneDeep2['default'])(sources[0]); } if (opts.noOverwrite) { if (!(0, _lodashLangIsObject2['default'])(target) || !(0, _lodashLangIsObject2['default'])(sources[0])) { return target; } } function iteratee(sourceValue, key) { var targetValue = target[key]; if (opts.filter && !opts.filter(sourceValue, targetValue, key)) { return; } var result = opts.deep ? opts._innerMixer(targetValue, sourceValue) : sourceValue; target[key] = opts.transform ? opts.transform(result, targetValue, key) : result; } var loop = opts.chain ? _lodashObjectForIn2['default'] : _lodashObjectForOwn2['default']; sources.forEach(function (obj) { loop(obj, iteratee); }); return target; }; } module.exports = exports['default']; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(33), createForOwn = __webpack_require__(59); /** * Iterates over own enumerable properties of an object invoking `iteratee` * for each property. The `iteratee` is bound to `thisArg` and invoked with * three arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => logs 'a' and 'b' (iteration order is not guaranteed) */ var forOwn = createForOwn(baseForOwn); module.exports = forOwn; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var bindCallback = __webpack_require__(54); /** * Creates a function for `_.forOwn` or `_.forOwnRight`. * * @private * @param {Function} objectFunc The function to iterate over an object. * @returns {Function} Returns the new each function. */ function createForOwn(objectFunc) { return function(object, iteratee, thisArg) { if (typeof iteratee != 'function' || thisArg !== undefined) { iteratee = bindCallback(iteratee, thisArg, 3); } return objectFunc(object, iteratee); }; } module.exports = createForOwn; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(34), createForIn = __webpack_require__(61); /** * Iterates over own and inherited enumerable properties of an object invoking * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [thisArg] The `this` binding of `iteratee`. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed) */ var forIn = createForIn(baseFor); module.exports = forIn; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { var bindCallback = __webpack_require__(54), keysIn = __webpack_require__(51); /** * Creates a function for `_.forIn` or `_.forInRight`. * * @private * @param {Function} objectFunc The function to iterate over an object. * @returns {Function} Returns the new each function. */ function createForIn(objectFunc) { return function(object, iteratee, thisArg) { if (typeof iteratee != 'function' || thisArg !== undefined) { iteratee = bindCallback(iteratee, thisArg, 3); } return objectFunc(object, iteratee, keysIn); }; } module.exports = createForIn; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { var baseClone = __webpack_require__(63), bindCallback = __webpack_require__(54); /** * Creates a deep clone of `value`. If `customizer` is provided it's invoked * to produce the cloned values. If `customizer` returns `undefined` cloning * is handled by the method instead. The `customizer` is bound to `thisArg` * and invoked with up to three argument; (value [, index|key, object]). * * **Note:** This method is loosely based on the * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). * The enumerable properties of `arguments` objects and objects created by * constructors other than `Object` are cloned to plain `Object` objects. An * empty object is returned for uncloneable values such as functions, DOM nodes, * Maps, Sets, and WeakMaps. * * @static * @memberOf _ * @category Lang * @param {*} value The value to deep clone. * @param {Function} [customizer] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {*} Returns the deep cloned value. * @example * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * var deep = _.cloneDeep(users); * deep[0] === users[0]; * // => false * * // using a customizer callback * var el = _.cloneDeep(document.body, function(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * }); * * el === document.body * // => false * el.nodeName * // => BODY * el.childNodes.length; * // => 20 */ function cloneDeep(value, customizer, thisArg) { return typeof customizer == 'function' ? baseClone(value, true, bindCallback(customizer, thisArg, 3)) : baseClone(value, true); } module.exports = cloneDeep; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { var arrayCopy = __webpack_require__(64), arrayEach = __webpack_require__(31), baseAssign = __webpack_require__(65), baseForOwn = __webpack_require__(33), initCloneArray = __webpack_require__(67), initCloneByTag = __webpack_require__(68), initCloneObject = __webpack_require__(70), isArray = __webpack_require__(49), isObject = __webpack_require__(37); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[stringTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[mapTag] = cloneableTags[setTag] = cloneableTags[weakMapTag] = false; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * The base implementation of `_.clone` without support for argument juggling * and `this` binding `customizer` functions. * * @private * @param {*} value The value to clone. * @param {boolean} [isDeep] Specify a deep clone. * @param {Function} [customizer] The function to customize cloning values. * @param {string} [key] The key of `value`. * @param {Object} [object] The object `value` belongs to. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates clones with source counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { var result; if (customizer) { result = object ? customizer(value, key, object) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return arrayCopy(value, result); } } else { var tag = objToString.call(value), isFunc = tag == funcTag; if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = initCloneObject(isFunc ? {} : value); if (!isDeep) { return baseAssign(result, value); } } else { return cloneableTags[tag] ? initCloneByTag(value, tag, isDeep) : (object ? value : {}); } } // Check for circular references and return its corresponding clone. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == value) { return stackB[length]; } } // Add the source value to the stack of traversed objects and associate it with its clone. stackA.push(value); stackB.push(result); // Recursively populate clone (susceptible to call stack limits). (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) { result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB); }); return result; } module.exports = baseClone; /***/ }, /* 64 */ /***/ function(module, exports) { /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = arrayCopy; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { var baseCopy = __webpack_require__(66), keys = __webpack_require__(38); /** * The base implementation of `_.assign` without support for argument juggling, * multiple sources, and `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return source == null ? object : baseCopy(source, keys(source), object); } module.exports = baseAssign; /***/ }, /* 66 */ /***/ function(module, exports) { /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ function baseCopy(source, props, object) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } module.exports = baseCopy; /***/ }, /* 67 */ /***/ function(module, exports) { /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add array properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } module.exports = initCloneArray; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { var bufferClone = __webpack_require__(69); /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', numberTag = '[object Number]', regexpTag = '[object RegExp]', stringTag = '[object String]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return bufferClone(object); case boolTag: case dateTag: return new Ctor(+object); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: var buffer = object.buffer; return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length); case numberTag: case stringTag: return new Ctor(object); case regexpTag: var result = new Ctor(object.source, reFlags.exec(object)); result.lastIndex = object.lastIndex; } return result; } module.exports = initCloneByTag; /***/ }, /* 69 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** Native method references. */ var ArrayBuffer = global.ArrayBuffer, Uint8Array = global.Uint8Array; /** * Creates a clone of the given array buffer. * * @private * @param {ArrayBuffer} buffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function bufferClone(buffer) { var result = new ArrayBuffer(buffer.byteLength), view = new Uint8Array(result); view.set(new Uint8Array(buffer)); return result; } module.exports = bufferClone; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 70 */ /***/ function(module, exports) { /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { var Ctor = object.constructor; if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) { Ctor = Object; } return new Ctor; } module.exports = initCloneObject; /***/ }, /* 71 */ /***/ function(module, exports) { /** * Checks if `value` is `undefined`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } module.exports = isUndefined; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _instance = __webpack_require__(73); var _instance2 = _interopRequireDefault(_instance); var _class = __webpack_require__(231); var _class2 = _interopRequireDefault(_class); var _channel = __webpack_require__(232); var _channel2 = _interopRequireDefault(_channel); var _dataobject = __webpack_require__(233); var _dataobject2 = _interopRequireDefault(_dataobject); var _user = __webpack_require__(236); var _user2 = _interopRequireDefault(_user); var _group = __webpack_require__(237); var _group2 = _interopRequireDefault(_group); var _admin = __webpack_require__(238); var _admin2 = _interopRequireDefault(_admin); var _apikey = __webpack_require__(239); var _apikey2 = _interopRequireDefault(_apikey); var _instanceinvitation = __webpack_require__(240); var _instanceinvitation2 = _interopRequireDefault(_instanceinvitation); var _invitation = __webpack_require__(241); var _invitation2 = _interopRequireDefault(_invitation); var _script = __webpack_require__(242); var _script2 = _interopRequireDefault(_script); var _schedule = __webpack_require__(243); var _schedule2 = _interopRequireDefault(_schedule); var _trigger = __webpack_require__(244); var _trigger2 = _interopRequireDefault(_trigger); var _scriptendpoint = __webpack_require__(245); var _scriptendpoint2 = _interopRequireDefault(_scriptendpoint); var _dataendpoint = __webpack_require__(246); var _dataendpoint2 = _interopRequireDefault(_dataendpoint); var _scripttrace = __webpack_require__(247); var _scripttrace2 = _interopRequireDefault(_scripttrace); var _scheduletrace = __webpack_require__(248); var _scheduletrace2 = _interopRequireDefault(_scheduletrace); var _triggertrace = __webpack_require__(249); var _triggertrace2 = _interopRequireDefault(_triggertrace); var _scriptendpointtrace = __webpack_require__(250); var _scriptendpointtrace2 = _interopRequireDefault(_scriptendpointtrace); var _gcmdevice = __webpack_require__(251); var _gcmdevice2 = _interopRequireDefault(_gcmdevice); var _gcmconfig = __webpack_require__(252); var _gcmconfig2 = _interopRequireDefault(_gcmconfig); var _apnsdevice = __webpack_require__(253); var _apnsdevice2 = _interopRequireDefault(_apnsdevice); var _apnsconfig = __webpack_require__(254); var _apnsconfig2 = _interopRequireDefault(_apnsconfig); var _gcmmessage = __webpack_require__(255); var _gcmmessage2 = _interopRequireDefault(_gcmmessage); var _apnsmessage = __webpack_require__(256); var _apnsmessage2 = _interopRequireDefault(_apnsmessage); var _template = __webpack_require__(257); var _template2 = _interopRequireDefault(_template); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { Instance: _instance2.default, Class: _class2.default, Channel: _channel2.default, DataObject: _dataobject2.default, User: _user2.default, Group: _group2.default, Admin: _admin2.default, ApiKey: _apikey2.default, InstanceInvitation: _instanceinvitation2.default, Invitation: _invitation2.default, Script: _script2.default, Schedule: _schedule2.default, Trigger: _trigger2.default, ScriptEndpoint: _scriptendpoint2.default, DataEndpoint: _dataendpoint2.default, ScriptTrace: _scripttrace2.default, ScheduleTrace: _scheduletrace2.default, TriggerTrace: _triggertrace2.default, ScriptEndpointTrace: _scriptendpointtrace2.default, GCMDevice: _gcmdevice2.default, APNSDevice: _apnsdevice2.default, APNSConfig: _apnsconfig2.default, GCMMessage: _gcmmessage2.default, GCMConfig: _gcmconfig2.default, APNSMessage: _apnsmessage2.default, Template: _template2.default }; module.exports = exports['default']; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); var _querySet2 = _interopRequireDefault(_querySet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var InstanceQuerySet = (0, _stampit2.default)().compose(_querySet2.default).methods({ rename: function rename() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var object = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.payload = object; this.method = 'POST'; this.endpoint = 'rename'; return this; } }); var InstanceMeta = (0, _base.Meta)({ name: 'instance', pluralName: 'instances', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{name}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/' }, 'rename': { 'methods': ['post'], 'path': '/v1.1/instances/{name}/rename/' } }, relatedModels: ['Admin', 'Class', 'Script', 'Schedule', 'InstanceInvitation', 'ApiKey', 'Trigger', 'ScriptEndpoint', 'User', 'Group', 'GCMDevice', 'Channel', 'APNSDevice', 'Template'] }); var InstanceConstraints = { name: { presence: true, string: true, length: { minimum: 5 } }, description: { string: true }, metadata: { object: true } }; /** * OO wrapper around instances {@link http://docs.syncano.io/v0.1/docs/instances-list endpoint}. * @constructor * @type {Instance} * @property {String} name * @property {Object} owner * @property {Number} owner.id * @property {String} owner.email * @property {String} owner.first_name * @property {String} owner.last_name * @property {Boolean} owner.is_active * @property {Boolean} owner.has_password * @property {String} role * @property {Object} [metadata = {}] * @property {String} [description = null] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var Instance = (0, _stampit2.default)().compose(_base.Model).setMeta(InstanceMeta).methods({ rename: function rename() { var payload = arguments.length <= 0 || arguments[0] === undefined ? { new_name: this.name } : arguments[0]; var options = { payload: payload }; var meta = this.getMeta(); var path = meta.resolveEndpointPath('rename', this); return this.makeRequest('POST', path, options); } }).setQuerySet(InstanceQuerySet).setConstraints(InstanceConstraints); exports.default = Instance; module.exports = exports['default']; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(75), copyObject = __webpack_require__(77), createAssigner = __webpack_require__(79), isArrayLike = __webpack_require__(4), isPrototype = __webpack_require__(27), keys = __webpack_require__(21); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */ var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf'); /** * Assigns own enumerable properties of source objects to the destination * object. Source objects are applied from left to right. Subsequent sources * overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * function Foo() { * this.c = 3; * } * * function Bar() { * this.e = 5; * } * * Foo.prototype.d = 4; * Bar.prototype.f = 6; * * _.assign({ 'a': 1 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3, 'e': 5 } */ var assign = createAssigner(function(object, source) { if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); module.exports = assign; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(76); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { object[key] = value; } } module.exports = assignValue; /***/ }, /* 76 */ /***/ function(module, exports) { /** * Performs a [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'user': 'fred' }; * var other = { 'user': 'fred' }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { var copyObjectWith = __webpack_require__(78); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ function copyObject(source, props, object) { return copyObjectWith(source, props, object); } module.exports = copyObject; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(75); /** * This function is like `copyObject` except that it accepts a function to * customize copied values. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObjectWith(source, props, object, customizer) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : source[key]; assignValue(object, key, newValue); } return object; } module.exports = copyObjectWith; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { var isIterateeCall = __webpack_require__(80), rest = __webpack_require__(81); /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return rest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = typeof customizer == 'function' ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } module.exports = createAssigner; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(76), isArrayLike = __webpack_require__(4), isIndex = __webpack_require__(26), isObject = __webpack_require__(8); /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object)) { return eq(object[index], value); } return false; } module.exports = isIterateeCall; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(82), toInteger = __webpack_require__(83); /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : toInteger(start), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } switch (start) { case 0: return func.call(this, array); case 1: return func.call(this, args[0], array); case 2: return func.call(this, args[0], args[1], array); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = array; return apply(func, this, otherArgs); }; } module.exports = rest; /***/ }, /* 82 */ /***/ function(module, exports) { /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {...*} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { var length = args.length; switch (length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { var toNumber = __webpack_require__(84); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to an integer. * * **Note:** This function is loosely based on [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger). * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3'); * // => 3 */ function toInteger(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } var remainder = value % 1; return value === value ? (remainder ? value - remainder : value) : 0; } module.exports = toInteger; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(7), isObject = __webpack_require__(8); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3); * // => 3 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3'); * // => 3 */ function toNumber(value) { if (isObject(value)) { var other = isFunction(value.valueOf) ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Model = exports.Meta = undefined; var _get2 = __webpack_require__(86); var _get3 = _interopRequireDefault(_get2); var _includes2 = __webpack_require__(97); var _includes3 = _interopRequireDefault(_includes2); var _camelCase2 = __webpack_require__(103); var _camelCase3 = _interopRequireDefault(_camelCase2); var _lastIndexOf2 = __webpack_require__(113); var _lastIndexOf3 = _interopRequireDefault(_lastIndexOf2); var _last2 = __webpack_require__(114); var _last3 = _interopRequireDefault(_last2); var _functions2 = __webpack_require__(115); var _functions3 = _interopRequireDefault(_functions2); var _omit2 = __webpack_require__(118); var _omit3 = _interopRequireDefault(_omit2); var _has2 = __webpack_require__(155); var _has3 = _interopRequireDefault(_has2); var _map2 = __webpack_require__(159); var _map3 = _interopRequireDefault(_map2); var _intersection2 = __webpack_require__(192); var _intersection3 = _interopRequireDefault(_intersection2); var _keys2 = __webpack_require__(21); var _keys3 = _interopRequireDefault(_keys2); var _difference2 = __webpack_require__(195); var _difference3 = _interopRequireDefault(_difference2); var _isEmpty2 = __webpack_require__(1); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _pick2 = __webpack_require__(196); var _pick3 = _interopRequireDefault(_pick2); var _mapValues2 = __webpack_require__(197); var _mapValues3 = _interopRequireDefault(_mapValues2); var _reduce2 = __webpack_require__(198); var _reduce3 = _interopRequireDefault(_reduce2); var _union2 = __webpack_require__(200); var _union3 = _interopRequireDefault(_union2); var _forEach2 = __webpack_require__(13); var _forEach3 = _interopRequireDefault(_forEach2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _bluebird = __webpack_require__(204); var _bluebird2 = _interopRequireDefault(_bluebird); var _validate2 = __webpack_require__(207); var _validate3 = _interopRequireDefault(_validate2); var _querySet = __webpack_require__(209); var _querySet2 = _interopRequireDefault(_querySet); var _request = __webpack_require__(213); var _request2 = _interopRequireDefault(_request); var _errors = __webpack_require__(229); var _utils = __webpack_require__(223); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } _validate3.default.Promise = _bluebird2.default; _validate3.default.validators.object = function (value) { if (value) { if (!_validate3.default.isObject(value)) { return "is not an object"; } } return null; }; _validate3.default.validators.array = function (value) { if (value) { if (!_validate3.default.isArray(value)) { return "is not an array"; } } return null; }; _validate3.default.validators.boolean = function (value) { if (value) { if (typeof value !== 'boolean') { return "is not a boolean"; } } return null; }; _validate3.default.validators.string = function (value) { if (value) { if (!_validate3.default.isString(value)) { return "is not a string"; } } return null; }; /** * Object which holds whole configuration for {@link Model}. * @constructor * @type {Meta} * @property {String} [name = null] * @property {String} [pluralName = null] * @property {Array} [properties = []] * @property {Array} [endpoints = {}] * @property {Array} [relatedModels = undefined] * @example {@lang javascript} * var MyMeta = Meta({name: 'test'}); * var MyModel = SomeModel.setMeta(MyMeta); */ var Meta = exports.Meta = (0, _stampit2.default)().props({ name: null, pluralName: null, properties: [], endpoints: {} }).init(function (_ref) { var _this = this; var instance = _ref.instance; (0, _forEach3.default)(instance.endpoints, function (value) { value.properties = _this.getPathProperties(value.path); instance.properties = (0, _union3.default)(instance.properties, value.properties); }); }).methods({ /** * Gets required properties from object. Used mostly during serialization. * @memberOf Meta * @instance * @param {Object} object * @returns {Object} */ getObjectProperties: function getObjectProperties(object) { return (0, _reduce3.default)(this.properties, function (result, property) { result[property] = object[property]; return result; }, {}); }, /** * Makes a copy of target and adds required properties from source. * @memberOf Meta * @instance * @param {Object} source * @param {Object} target * @returns {Object} */ assignProperties: function assignProperties(source, target) { var dateFields = (0, _mapValues3.default)((0, _pick3.default)(target, ['created_at', 'updated_at', 'executed_at']), function (o) { return new Date(o); }); return (0, _assign3.default)({}, this.getObjectProperties(source), target, dateFields); }, getPathProperties: function getPathProperties(path) { var re = /{([^}]*)}/gi; var match = null; var result = []; while ((match = re.exec(path)) !== null) { result.push(match[1]); } return result; }, /** * Resolves endpoint path e.g: `/v1.1/instances/{name}/` will be converted to `/v1.1/instances/someName/`. * @memberOf Meta * @instance * @param {String} endpointName * @param {Object} properties * @returns {String} */ resolveEndpointPath: function resolveEndpointPath(endpointName, properties) { if ((0, _isEmpty3.default)(this.endpoints[endpointName])) { throw new Error('Invalid endpoit name: "' + endpointName + '".'); } var endpoint = this.endpoints[endpointName]; var diff = (0, _difference3.default)(endpoint.properties, (0, _keys3.default)(properties)); var path = endpoint.path; if (diff.length) { throw new Error('Missing path properties "' + diff.join() + '" for "' + endpointName + '" endpoint.'); } (0, _forEach3.default)(endpoint.properties, function (property) { path = path.replace('{' + property + '}', properties[property]); }); return path; }, /** * Looks for the first allowed method from `methodNames` for selected endpoint. * @memberOf Meta * @instance * @param {String} endpointName * @param {...String} methodNames * @returns {String} */ findAllowedMethod: function findAllowedMethod(endpointName) { var endpoint = this.endpoints[endpointName]; for (var _len = arguments.length, methodNames = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { methodNames[_key - 1] = arguments[_key]; } var methods = (0, _intersection3.default)((0, _map3.default)(methodNames, function (m) { return m.toLowerCase(); }), endpoint.methods); if ((0, _isEmpty3.default)(methods)) { throw Error('Unsupported request methods: ' + methodNames.join() + '.'); } return methods[0]; } }); /** * Base {@link https://github.com/stampit-org/stampit|stamp} for all models which wraps all raw JavaScript objects. * **Not** meant to be used directly more like mixin in other {@link https://github.com/stampit-org/stampit|stamps}. * @constructor * @type {Model} * @property {Syncano} _config private attribute which holds {@link Syncano} object * @property {Meta} _meta private attribute which holds {@link Meta} object * @property {Object} _constraints private attribute which holds validation constraints * @property {Request} _request private attribute which holds {@link Request} configuration * @property {Request} _querySet private attribute which holds {@link QuerySet} stamp * @example {@lang javascript} * var MyModel = stampit() .compose(Model) .setMeta(MyMeta) .setConstraints(MyConstraints); */ var Model = exports.Model = (0, _stampit2.default)({ refs: { _querySet: _querySet2.default }, static: { /** * Sets {@link QuerySet} and returns new {@link https://github.com/stampit-org/stampit|stampit} definition. * @memberOf Model * @static * @param {QuerySet} querySet {@link QuerySet} definition * @returns {Model} * @example {@lang javascript} * var MyStamp = stampit().compose(Model).setQuerySet({}); */ setQuerySet: function setQuerySet(querySet) { return this.refs({ _querySet: querySet }); }, /** * Gets {@link QuerySet} from {@link https://github.com/stampit-org/stampit|stampit} definition. * @memberOf Model * @static * @returns {QuerySet} * @example {@lang javascript} * var querySet = stampit().compose(Model).getQuerySet(); */ getQuerySet: function getQuerySet() { return this.fixed.refs._querySet; }, /** * Returns {@link QuerySet} instance which allows to do ORM like operations on {@link https://syncano.io/|Syncano} API. * @memberOf Model * @static * @param {Object} [properties = {}] some default properties for all ORM operations * @returns {QuerySet} * @example {@lang javascript} * MyModel.please().list(); */ please: function please() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var querySet = this.getQuerySet(); return querySet({ model: this, properties: properties, _config: this.getConfig() }); }, /** * Used only for serialization for raw object to {@link https://github.com/stampit-org/stampit|stamp}. * @memberOf Model * @static * @param {Object} rawJSON * @param {Object} [properties = {}] some default properties which will be assigned to model instance * @returns {Model} */ fromJSON: function fromJSON(rawJSON) { var properties = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var meta = this.getMeta(); var attrs = meta.assignProperties(properties, rawJSON); return this(attrs); } }, methods: { /** * Checks if model instance if already saved. * @memberOf Model * @instance * @returns {Boolean} */ isNew: function isNew() { return !(0, _has3.default)(this, 'links'); }, /** * Validates current model instance in context of defined constraints. * @memberOf Model * @instance * @returns {Object|undefined} */ validate: function validate() { var constraints = this.getConstraints(); var attributes = this.toJSON(); if ((0, _isEmpty3.default)(constraints)) { return; } return (0, _validate3.default)(attributes, constraints); }, /** * Serializes raw JavaScript object into {@link Model} instance. * @memberOf Model * @instance * @returns {Model} */ serialize: function serialize(object) { var meta = this.getMeta(); return this.getStamp()(meta.assignProperties(this, object)); }, /** * Creates or updates the current instance. * @memberOf Model * @instance * @returns {Promise} */ save: function save() { var _this2 = this; var meta = this.getMeta(); var errors = this.validate(); var path = null; var endpoint = 'list'; var method = 'POST'; var payload = this.toJSON(); if (!(0, _isEmpty3.default)(errors)) { return _bluebird2.default.reject(new _errors.ValidationError(errors)); } try { if (!this.isNew()) { endpoint = 'detail'; method = meta.findAllowedMethod(endpoint, 'PUT', 'PATCH', 'POST'); } path = meta.resolveEndpointPath(endpoint, this); } catch (err) { return _bluebird2.default.reject(err); } return this.makeRequest(method, path, { payload: payload }).then(function (body) { return _this2.serialize(body); }); }, /** * Removes the current instance. * @memberOf Model * @instance * @returns {Promise} */ delete: function _delete() { var meta = this.getMeta(); var path = meta.resolveEndpointPath('detail', this); return this.makeRequest('DELETE', path); }, toJSON: function toJSON() { var attrs = [ // Private stuff '_config', '_meta', '_request', '_constraints', '_querySet', // Read only stuff 'links', 'created_at', 'updated_at']; return (0, _omit3.default)(this, attrs.concat((0, _functions3.default)(this))); } } }).init(function (_ref2) { var instance = _ref2.instance; var stamp = _ref2.stamp; if (!stamp.fixed.methods.getStamp) { stamp.fixed.methods.getStamp = function () { return stamp; }; } if ((0, _has3.default)(instance, '_meta.relatedModels')) { (function () { var relatedModels = instance._meta.relatedModels; var properties = instance._meta.properties.slice(); var last = (0, _last3.default)(properties); var lastIndex = (0, _lastIndexOf3.default)(properties, last); properties[lastIndex] = (0, _camelCase3.default)(instance._meta.name + ' ' + last); var map = {}; map[last] = properties[lastIndex]; map = (0, _reduce3.default)(properties, function (result, property) { result[property] = property; return result; }, map); (0, _forEach3.default)(instance.getConfig(), function (model, name) { if ((0, _includes3.default)(relatedModels, name)) { instance[model.getMeta().pluralName] = function () { var _properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var parentProperties = (0, _reduce3.default)(map, function (result, target, source) { var value = (0, _get3.default)(instance, source, null); if (value !== null) { result[target] = value; } return result; }, {}); return (0, _stampit2.default)().compose(model).please((0, _assign3.default)(parentProperties, _properties)); }; } }); })(); } }).compose(_utils.ConfigMixin, _utils.MetaMixin, _utils.ConstraintsMixin, _request2.default); exports.default = Model; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(87); /** * Gets the value at `path` of `object`. If the resolved value is * `undefined` the `defaultValue` is used in its place. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } module.exports = get; /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { var baseCastPath = __webpack_require__(88), isKey = __webpack_require__(96); /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = isKey(path, object) ? [path + ''] : baseCastPath(path); var index = 0, length = path.length; while (object != null && index < length) { object = object[path[index++]]; } return (index && index == length) ? object : undefined; } module.exports = baseGet; /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(11), stringToPath = __webpack_require__(89); /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @returns {Array} Returns the cast property path array. */ function baseCastPath(value) { return isArray(value) ? value : stringToPath(value); } module.exports = baseCastPath; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(90); /** Used to match property names within property paths. */ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ function stringToPath(string) { var result = []; toString(string).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; } module.exports = stringToPath; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(91), isSymbol = __webpack_require__(95); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (value == null) { return ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toString; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(92); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module, global) {var checkGlobal = __webpack_require__(94); /** Used to determine if values are of the language type `Object`. */ var objectTypes = { 'function': true, 'object': true }; /** Detect free variable `exports`. */ var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : undefined; /** Detect free variable `module`. */ var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : undefined; /** Detect free variable `global` from Node.js. */ var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global); /** Detect free variable `self`. */ var freeSelf = checkGlobal(objectTypes[typeof self] && self); /** Detect free variable `window`. */ var freeWindow = checkGlobal(objectTypes[typeof window] && window); /** Detect `this` as the global object. */ var thisGlobal = checkGlobal(objectTypes[typeof this] && this); /** * Used as a reference to the global object. * * The `this` value is used if it's the global object to avoid Greasemonkey's * restricted `window` object, otherwise the `window` object is used. */ var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')(); module.exports = root; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(93)(module), (function() { return this; }()))) /***/ }, /* 93 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 94 */ /***/ function(module, exports) { /** * Checks if `value` is a global object. * * @private * @param {*} value The value to check. * @returns {null|Object} Returns `value` if it's a global object, else `null`. */ function checkGlobal(value) { return (value && value.Object === Object) ? value : null; } module.exports = checkGlobal; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { var isObjectLike = __webpack_require__(10); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } module.exports = isSymbol; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(11); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (typeof value == 'number') { return true; } return !isArray(value) && (reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object))); } module.exports = isKey; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(98), isArrayLike = __webpack_require__(4), isString = __webpack_require__(12), toInteger = __webpack_require__(83), values = __webpack_require__(100); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string it's checked * for a substring of `value`, otherwise [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for functions like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'user': 'fred', 'age': 40 }, 'fred'); * // => true * * _.includes('pebbles', 'eb'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } module.exports = includes; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { var indexOfNaN = __webpack_require__(99); /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { if (value !== value) { return indexOfNaN(array, fromIndex); } var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } module.exports = baseIndexOf; /***/ }, /* 99 */ /***/ function(module, exports) { /** * Gets the index at which the first occurrence of `NaN` is found in `array`. * * @private * @param {Array} array The array to search. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched `NaN`, else `-1`. */ function indexOfNaN(array, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 0 : -1); while ((fromRight ? index-- : ++index < length)) { var other = array[index]; if (other !== other) { return index; } } return -1; } module.exports = indexOfNaN; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { var baseValues = __webpack_require__(101), keys = __webpack_require__(21); /** * Creates an array of the own enumerable property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object ? baseValues(object, keys(object)) : []; } module.exports = values; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(102); /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } module.exports = baseValues; /***/ }, /* 102 */ /***/ function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { var capitalize = __webpack_require__(104), createCompounder = __webpack_require__(108); /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar'); * // => 'fooBar' * * _.camelCase('__foo_bar__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); module.exports = camelCase; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(90), upperFirst = __webpack_require__(105); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } module.exports = capitalize; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { var createCaseFirst = __webpack_require__(106); /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); module.exports = upperFirst; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { var stringToArray = __webpack_require__(107), toString = __webpack_require__(90); /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', rsComboSymbolsRange = '\\u20d0-\\u20f0', rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasComplexSymbol = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = reHasComplexSymbol.test(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0), trailing = strSymbols ? strSymbols.slice(1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } module.exports = createCaseFirst; /***/ }, /* 107 */ /***/ function(module, exports) { /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', rsComboSymbolsRange = '\\u20d0-\\u20f0', rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange + ']', rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reComplexSymbol = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return string.match(reComplexSymbol); } module.exports = stringToArray; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { var arrayReduce = __webpack_require__(109), deburr = __webpack_require__(110), words = __webpack_require__(112); /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string)), callback, ''); }; } module.exports = createCompounder; /***/ }, /* 109 */ /***/ function(module, exports) { /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } module.exports = arrayReduce; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { var deburrLetter = __webpack_require__(111), toString = __webpack_require__(90); /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; /** Used to compose unicode character classes. */ var rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', rsComboSymbolsRange = '\\u20d0-\\u20f0'; /** Used to compose unicode capture groups. */ var rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']'; /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); } module.exports = deburr; /***/ }, /* 111 */ /***/ function(module, exports) { /** Used to map latin-1 supplementary letters to basic latin letters. */ var deburredLetters = { '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss' }; /** * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ function deburrLetter(letter) { return deburredLetters[letter]; } module.exports = deburrLetter; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { var toString = __webpack_require__(90); /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', rsComboSymbolsRange = '\\u20d0-\\u20f0', rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsQuoteRange = '\\u2018\\u2019\\u201c\\u201d', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsQuoteRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq; /** Used to match non-compound words composed of alphanumeric characters. */ var reBasicWord = /[a-zA-Z0-9]+/g; /** Used to match complex or compound words. */ var reComplexWord = RegExp([ rsUpper + '?' + rsLower + '+(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsUpperMisc + '+(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', rsUpper + '?' + rsLowerMisc + '+', rsUpper + '+', rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasComplexWord = /[a-z][A-Z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for functions like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { pattern = reHasComplexWord.test(string) ? reComplexWord : reBasicWord; } return string.match(pattern) || []; } module.exports = words; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { var indexOfNaN = __webpack_require__(99), toInteger = __webpack_require__(83); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max, nativeMin = Math.min; /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @category Array * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = (index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1)) + 1; } if (value !== value) { return indexOfNaN(array, index, true); } while (index--) { if (array[index] === value) { return index; } } return -1; } module.exports = lastIndexOf; /***/ }, /* 114 */ /***/ function(module, exports) { /** * Gets the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } module.exports = last; /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { var baseFunctions = __webpack_require__(116), keys = __webpack_require__(21); /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the new array of property names. * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } module.exports = functions; /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(117), isFunction = __webpack_require__(7); /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the new array of filtered property names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } module.exports = baseFunctions; /***/ }, /* 117 */ /***/ function(module, exports) { /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } module.exports = arrayFilter; /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(102), baseDifference = __webpack_require__(119), baseFlatten = __webpack_require__(148), basePick = __webpack_require__(150), keysIn = __webpack_require__(151), rest = __webpack_require__(81); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable properties of `object` that are not omitted. * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [props] The property names to omit, specified * individually or in arrays. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = rest(function(object, props) { if (object == null) { return {}; } props = arrayMap(baseFlatten(props, 1), String); return basePick(object, baseDifference(keysIn(object), props)); }); module.exports = omit; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(120), arrayIncludes = __webpack_require__(144), arrayIncludesWith = __webpack_require__(145), arrayMap = __webpack_require__(102), baseUnary = __webpack_require__(146), cacheHas = __webpack_require__(147); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of methods like `_.difference` without support for * excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } module.exports = baseDifference; /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(121), cachePush = __webpack_require__(143); /** * * Creates a set cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values ? values.length : 0; this.__data__ = new MapCache; while (++index < length) { this.push(values[index]); } } // Add functions to the `SetCache`. SetCache.prototype.push = cachePush; module.exports = SetCache; /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { var mapClear = __webpack_require__(122), mapDelete = __webpack_require__(129), mapGet = __webpack_require__(135), mapHas = __webpack_require__(138), mapSet = __webpack_require__(140); /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [values] The values to cache. */ function MapCache(values) { var index = -1, length = values ? values.length : 0; this.clear(); while (++index < length) { var entry = values[index]; this.set(entry[0], entry[1]); } } // Add functions to the `MapCache`. MapCache.prototype.clear = mapClear; MapCache.prototype['delete'] = mapDelete; MapCache.prototype.get = mapGet; MapCache.prototype.has = mapHas; MapCache.prototype.set = mapSet; module.exports = MapCache; /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { var Hash = __webpack_require__(123), Map = __webpack_require__(128); /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapClear() { this.__data__ = { 'hash': new Hash, 'map': Map ? new Map : [], 'string': new Hash }; } module.exports = mapClear; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(124); /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Creates an hash object. * * @private * @constructor * @returns {Object} Returns the new hash object. */ function Hash() {} // Avoid inheriting from `Object.prototype` when possible. Hash.prototype = nativeCreate ? nativeCreate(null) : objectProto; module.exports = Hash; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(125); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { var isNative = __webpack_require__(126); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object[key]; return isNative(value) ? value : undefined; } module.exports = getNative; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(7), isHostObject = __webpack_require__(127), isObjectLike = __webpack_require__(10); /** Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(funcToString.call(value)); } return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value); } module.exports = isNative; /***/ }, /* 127 */ /***/ function(module, exports) { /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } module.exports = isHostObject; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(125), root = __webpack_require__(92); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { var Map = __webpack_require__(128), assocDelete = __webpack_require__(130), hashDelete = __webpack_require__(132), isKeyable = __webpack_require__(134); /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapDelete(key) { var data = this.__data__; if (isKeyable(key)) { return hashDelete(typeof key == 'string' ? data.string : data.hash, key); } return Map ? data.map['delete'](key) : assocDelete(data.map, key); } module.exports = mapDelete; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(131); /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the associative array. * * @private * @param {Array} array The array to query. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function assocDelete(array, key) { var index = assocIndexOf(array, key); if (index < 0) { return false; } var lastIndex = array.length - 1; if (index == lastIndex) { array.pop(); } else { splice.call(array, index, 1); } return true; } module.exports = assocDelete; /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(76); /** * Gets the index at which the first occurrence of `key` is found in `array` * of key-value pairs. * * @private * @param {Array} array The array to search. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } module.exports = assocIndexOf; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { var hashHas = __webpack_require__(133); /** * Removes `key` and its value from the hash. * * @private * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(hash, key) { return hashHas(hash, key) && delete hash[key]; } module.exports = hashDelete; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(124); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @param {Object} hash The hash to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(hash, key) { return nativeCreate ? hash[key] !== undefined : hasOwnProperty.call(hash, key); } module.exports = hashHas; /***/ }, /* 134 */ /***/ function(module, exports) { /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return type == 'number' || type == 'boolean' || (type == 'string' && value != '__proto__') || value == null; } module.exports = isKeyable; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { var Map = __webpack_require__(128), assocGet = __webpack_require__(136), hashGet = __webpack_require__(137), isKeyable = __webpack_require__(134); /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapGet(key) { var data = this.__data__; if (isKeyable(key)) { return hashGet(typeof key == 'string' ? data.string : data.hash, key); } return Map ? data.map.get(key) : assocGet(data.map, key); } module.exports = mapGet; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(131); /** * Gets the associative array value for `key`. * * @private * @param {Array} array The array to query. * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function assocGet(array, key) { var index = assocIndexOf(array, key); return index < 0 ? undefined : array[index][1]; } module.exports = assocGet; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(124); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @param {Object} hash The hash to query. * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(hash, key) { if (nativeCreate) { var result = hash[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(hash, key) ? hash[key] : undefined; } module.exports = hashGet; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { var Map = __webpack_require__(128), assocHas = __webpack_require__(139), hashHas = __webpack_require__(133), isKeyable = __webpack_require__(134); /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapHas(key) { var data = this.__data__; if (isKeyable(key)) { return hashHas(typeof key == 'string' ? data.string : data.hash, key); } return Map ? data.map.has(key) : assocHas(data.map, key); } module.exports = mapHas; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(131); /** * Checks if an associative array value for `key` exists. * * @private * @param {Array} array The array to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function assocHas(array, key) { return assocIndexOf(array, key) > -1; } module.exports = assocHas; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { var Map = __webpack_require__(128), assocSet = __webpack_require__(141), hashSet = __webpack_require__(142), isKeyable = __webpack_require__(134); /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache object. */ function mapSet(key, value) { var data = this.__data__; if (isKeyable(key)) { hashSet(typeof key == 'string' ? data.string : data.hash, key, value); } else if (Map) { data.map.set(key, value); } else { assocSet(data.map, key, value); } return this; } module.exports = mapSet; /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(131); /** * Sets the associative array `key` to `value`. * * @private * @param {Array} array The array to modify. * @param {string} key The key of the value to set. * @param {*} value The value to set. */ function assocSet(array, key, value) { var index = assocIndexOf(array, key); if (index < 0) { array.push([key, value]); } else { array[index][1] = value; } } module.exports = assocSet; /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(124); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @param {Object} hash The hash to modify. * @param {string} key The key of the value to set. * @param {*} value The value to set. */ function hashSet(hash, key, value) { hash[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; } module.exports = hashSet; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(134); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Adds `value` to the set cache. * * @private * @name push * @memberOf SetCache * @param {*} value The value to cache. */ function cachePush(value) { var map = this.__data__; if (isKeyable(value)) { var data = map.__data__, hash = typeof value == 'string' ? data.string : data.hash; hash[value] = HASH_UNDEFINED; } else { map.set(value, HASH_UNDEFINED); } } module.exports = cachePush; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(98); /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} array The array to search. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { return !!array.length && baseIndexOf(array, value, 0) > -1; } module.exports = arrayIncludes; /***/ }, /* 145 */ /***/ function(module, exports) { /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} array The array to search. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } module.exports = arrayIncludesWith; /***/ }, /* 146 */ /***/ function(module, exports) { /** * The base implementation of `_.unary` without support for storing wrapper metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new function. */ function baseUnary(func) { return function(value) { return func(value); }; } module.exports = baseUnary; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(134); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Checks if `value` is in `cache`. * * @private * @param {Object} cache The set cache to search. * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function cacheHas(cache, value) { var map = cache.__data__; if (isKeyable(value)) { var data = map.__data__, hash = typeof value == 'string' ? data.string : data.hash; return hash[value] === HASH_UNDEFINED; } return map.has(value); } module.exports = cacheHas; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(149), isArguments = __webpack_require__(2), isArray = __webpack_require__(11), isArrayLikeObject = __webpack_require__(3); /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [isStrict] Restrict flattening to arrays-like objects. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, isStrict, result) { result || (result = []); var index = -1, length = array.length; while (++index < length) { var value = array[index]; if (depth > 0 && isArrayLikeObject(value) && (isStrict || isArray(value) || isArguments(value))) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } module.exports = baseFlatten; /***/ }, /* 149 */ /***/ function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { var arrayReduce = __webpack_require__(109); /** * The base implementation of `_.pick` without support for individual * property names. * * @private * @param {Object} object The source object. * @param {string[]} props The property names to pick. * @returns {Object} Returns the new object. */ function basePick(object, props) { object = Object(object); return arrayReduce(props, function(result, key) { if (key in object) { result[key] = object[key]; } return result; }, {}); } module.exports = basePick; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { var baseKeysIn = __webpack_require__(152), indexKeys = __webpack_require__(24), isIndex = __webpack_require__(26), isPrototype = __webpack_require__(27); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { var index = -1, isProto = isPrototype(object), props = baseKeysIn(object), propsLength = props.length, indexes = indexKeys(object), skipIndexes = !!indexes, result = indexes || [], length = result.length; while (++index < propsLength) { var key = props[index]; if (!(skipIndexes && (key == 'length' || isIndex(key, length))) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = keysIn; /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { var Reflect = __webpack_require__(153), iteratorToArray = __webpack_require__(154); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Built-in value references. */ var enumerate = Reflect ? Reflect.enumerate : undefined, propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * The base implementation of `_.keysIn` which doesn't skip the constructor * property of prototypes or treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { object = object == null ? object : Object(object); var result = []; for (var key in object) { result.push(key); } return result; } // Fallback for IE < 9 with es6-shim. if (enumerate && !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf')) { baseKeysIn = function(object) { return iteratorToArray(enumerate(object)); }; } module.exports = baseKeysIn; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(92); /** Built-in value references. */ var Reflect = root.Reflect; module.exports = Reflect; /***/ }, /* 154 */ /***/ function(module, exports) { /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } module.exports = iteratorToArray; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(22), hasPath = __webpack_require__(156); /** * Checks if `path` is a direct property of `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': { 'c': 3 } } }; * var other = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b.c'); * // => true * * _.has(object, ['a', 'b', 'c']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return hasPath(object, path, baseHas); } module.exports = has; /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { var baseCastPath = __webpack_require__(88), isArguments = __webpack_require__(2), isArray = __webpack_require__(11), isIndex = __webpack_require__(26), isKey = __webpack_require__(96), isLength = __webpack_require__(9), isString = __webpack_require__(12), last = __webpack_require__(114), parent = __webpack_require__(157); /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { if (object == null) { return false; } var result = hasFunc(object, path); if (!result && !isKey(path)) { path = baseCastPath(path); object = parent(object, path); if (object != null) { path = last(path); result = hasFunc(object, path); } } var length = object ? object.length : undefined; return result || ( !!length && isLength(length) && isIndex(path, length) && (isArray(object) || isString(object) || isArguments(object)) ); } module.exports = hasPath; /***/ }, /* 157 */ /***/ function(module, exports, __webpack_require__) { var baseSlice = __webpack_require__(158), get = __webpack_require__(86); /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length == 1 ? object : get(object, baseSlice(path, 0, -1)); } module.exports = parent; /***/ }, /* 158 */ /***/ function(module, exports) { /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } module.exports = baseSlice; /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(102), baseIteratee = __webpack_require__(160), baseMap = __webpack_require__(191), isArray = __webpack_require__(11); /** * Creates an array of values by running each element in `collection` through * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, `fill`, * `invert`, `parseInt`, `random`, `range`, `rangeRight`, `slice`, `some`, * `sortBy`, `take`, `takeRight`, `template`, `trim`, `trimEnd`, `trimStart`, * and `words` * * @static * @memberOf _ * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, baseIteratee(iteratee, 3)); } module.exports = map; /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(161), baseMatchesProperty = __webpack_require__(186), identity = __webpack_require__(16), isArray = __webpack_require__(11), property = __webpack_require__(189); /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { var type = typeof value; if (type == 'function') { return value; } if (value == null) { return identity; } if (type == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } module.exports = baseIteratee; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(162), getMatchData = __webpack_require__(182); /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { var key = matchData[0][0], value = matchData[0][1]; return function(object) { if (object == null) { return false; } return object[key] === value && (value !== undefined || (key in Object(object))); }; } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } module.exports = baseMatches; /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(163), baseIsEqual = __webpack_require__(169); /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack, result = customizer ? customizer(objValue, srcValue, key, object, source, stack) : undefined; if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch; /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { var stackClear = __webpack_require__(164), stackDelete = __webpack_require__(165), stackGet = __webpack_require__(166), stackHas = __webpack_require__(167), stackSet = __webpack_require__(168); /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [values] The values to cache. */ function Stack(values) { var index = -1, length = values ? values.length : 0; this.clear(); while (++index < length) { var entry = values[index]; this.set(entry[0], entry[1]); } } // Add functions to the `Stack` cache. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; module.exports = Stack; /***/ }, /* 164 */ /***/ function(module, exports) { /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = { 'array': [], 'map': null }; } module.exports = stackClear; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { var assocDelete = __webpack_require__(130); /** * 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; /***/ }, /* 166 */ /***/ function(module, exports, __webpack_require__) { var assocGet = __webpack_require__(136); /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { var data = this.__data__, array = data.array; return array ? assocGet(array, key) : data.map.get(key); } module.exports = stackGet; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { var assocHas = __webpack_require__(139); /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { var data = this.__data__, array = data.array; return array ? assocHas(array, key) : data.map.has(key); } module.exports = stackHas; /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(121), assocSet = __webpack_require__(141); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache object. */ function stackSet(key, value) { var data = this.__data__, array = data.array; if (array) { if (array.length < (LARGE_ARRAY_SIZE - 1)) { assocSet(array, key, value); } else { data.array = null; data.map = new MapCache(array); } } var map = data.map; if (map) { map.set(key, value); } return this; } module.exports = stackSet; /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(170), isObject = __webpack_require__(8), isObjectLike = __webpack_require__(10); /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @param {boolean} [bitmask] The bitmask of comparison flags. * The bitmask may be composed of the following flags: * 1 - Unordered comparison * 2 - Partial comparison * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, bitmask, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); } module.exports = baseIsEqual; /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(163), equalArrays = __webpack_require__(171), equalByTag = __webpack_require__(173), equalObjects = __webpack_require__(177), getTag = __webpack_require__(178), isArray = __webpack_require__(11), isHostObject = __webpack_require__(127), isTypedArray = __webpack_require__(181); /** Used to compose bitmasks for comparison styles. */ var PARTIAL_COMPARE_FLAG = 2; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparisons. * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` for more details. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = getTag(object); objTag = objTag == argsTag ? objectTag : objTag; } if (!othIsArr) { othTag = getTag(other); othTag = othTag == argsTag ? objectTag : othTag; } var objIsObj = objTag == objectTag && !isHostObject(object), othIsObj = othTag == objectTag && !isHostObject(other), isSameTag = objTag == othTag; if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); } if (!(bitmask & PARTIAL_COMPARE_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { stack || (stack = new Stack); return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, bitmask, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, equalFunc, customizer, bitmask, stack); } module.exports = baseIsEqualDeep; /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { var arraySome = __webpack_require__(172); /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` for more details. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { var index = -1, isPartial = bitmask & PARTIAL_COMPARE_FLAG, isUnordered = bitmask & UNORDERED_COMPARE_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked) { return stacked == other; } var result = true; stack.set(array, other); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (isUnordered) { if (!arraySome(other, function(othValue) { return arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack); })) { result = false; break; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { result = false; break; } } stack['delete'](array); return result; } module.exports = equalArrays; /***/ }, /* 172 */ /***/ function(module, exports) { /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, else `false`. */ function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } module.exports = arraySome; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(91), Uint8Array = __webpack_require__(174), equalArrays = __webpack_require__(171), mapToArray = __webpack_require__(175), setToArray = __webpack_require__(176); /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]'; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { switch (tag) { case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: // Coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. return +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: // Treat `NaN` vs. `NaN` as equal. return (object != +object) ? other != +other : object == +other; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings primitives and string // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & PARTIAL_COMPARE_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } // Recursively compare objects (susceptible to call stack limits). return equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask | UNORDERED_COMPARE_FLAG, stack.set(object, other)); case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } module.exports = equalByTag; /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(92); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }, /* 175 */ /***/ function(module, exports) { /** * Converts `map` to an array. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the converted array. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } module.exports = mapToArray; /***/ }, /* 176 */ /***/ function(module, exports) { /** * Converts `set` to an array. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the converted array. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } module.exports = setToArray; /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(22), keys = __webpack_require__(21); /** Used to compose bitmasks for comparison styles. */ var PARTIAL_COMPARE_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : baseHas(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } var result = true; stack.set(object, other); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); return result; } module.exports = equalObjects; /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { var Map = __webpack_require__(128), Set = __webpack_require__(179), WeakMap = __webpack_require__(180); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = Function.prototype.toString; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to detect maps, sets, and weakmaps. */ var mapCtorString = Map ? funcToString.call(Map) : '', setCtorString = Set ? funcToString.call(Set) : '', weakMapCtorString = WeakMap ? funcToString.call(WeakMap) : ''; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function getTag(value) { return objectToString.call(value); } // Fallback for IE 11 providing `toStringTag` values for maps, sets, and weakmaps. if ((Map && getTag(new Map) != mapTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : null, ctorString = typeof Ctor == 'function' ? funcToString.call(Ctor) : ''; if (ctorString) { switch (ctorString) { case mapCtorString: return mapTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } module.exports = getTag; /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(125), root = __webpack_require__(92); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(125), root = __webpack_require__(92); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { var isLength = __webpack_require__(9), isObjectLike = __webpack_require__(10); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; } module.exports = isTypedArray; /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(183), toPairs = __webpack_require__(184); /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = toPairs(object), length = result.length; while (length--) { result[length][2] = isStrictComparable(result[length][1]); } return result; } module.exports = getMatchData; /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(8); /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable; /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { var baseToPairs = __webpack_require__(185), keys = __webpack_require__(21); /** * Creates an array of own enumerable key-value pairs for `object` which * can be consumed by `_.fromPairs`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the new array of key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ function toPairs(object) { return baseToPairs(object, keys(object)); } module.exports = toPairs; /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(102); /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the new array of key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } module.exports = baseToPairs; /***/ }, /* 186 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(169), get = __webpack_require__(86), hasIn = __webpack_require__(187); /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new function. */ function baseMatchesProperty(path, srcValue) { return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); }; } module.exports = baseMatchesProperty; /***/ }, /* 187 */ /***/ function(module, exports, __webpack_require__) { var baseHasIn = __webpack_require__(188), hasPath = __webpack_require__(156); /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': _.create({ 'c': 3 }) }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b.c'); * // => true * * _.hasIn(object, ['a', 'b', 'c']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return hasPath(object, path, baseHasIn); } module.exports = hasIn; /***/ }, /* 188 */ /***/ function(module, exports) { /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} object The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return key in Object(object); } module.exports = baseHasIn; /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(6), basePropertyDeep = __webpack_require__(190), isKey = __webpack_require__(96); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': 2 } } }, * { 'a': { 'b': { 'c': 1 } } } * ]; * * _.map(objects, _.property('a.b.c')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } module.exports = property; /***/ }, /* 190 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(87); /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } module.exports = basePropertyDeep; /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(17), isArrayLike = __webpack_require__(4); /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } module.exports = baseMap; /***/ }, /* 192 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(102), baseCastArrayLikeObject = __webpack_require__(193), baseIntersection = __webpack_require__(194), rest = __webpack_require__(81); /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. The order of result values is determined by the * order they occur in the first array. * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [4, 2], [1, 2]); * // => [2] */ var intersection = rest(function(arrays) { var mapped = arrayMap(arrays, baseCastArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); module.exports = intersection; /***/ }, /* 193 */ /***/ function(module, exports, __webpack_require__) { var isArrayLikeObject = __webpack_require__(3); /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array} Returns the array-like object. */ function baseCastArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } module.exports = baseCastArrayLikeObject; /***/ }, /* 194 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(120), arrayIncludes = __webpack_require__(144), arrayIncludesWith = __webpack_require__(145), arrayMap = __webpack_require__(102), baseUnary = __webpack_require__(146), cacheHas = __webpack_require__(147); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseIntersection; /***/ }, /* 195 */ /***/ function(module, exports, __webpack_require__) { var baseDifference = __webpack_require__(119), baseFlatten = __webpack_require__(148), isArrayLikeObject = __webpack_require__(3), rest = __webpack_require__(81); /** * Creates an array of unique `array` values not included in the other * given arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. The order of result values is determined by the * order they occur in the first array. * * @static * @memberOf _ * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @example * * _.difference([3, 2, 1], [4, 2]); * // => [3, 1] */ var difference = rest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, true)) : []; }); module.exports = difference; /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(148), basePick = __webpack_require__(150), rest = __webpack_require__(81); /** * Creates an object composed of the picked `object` properties. * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [props] The property names to pick, specified * individually or in arrays. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = rest(function(object, props) { return object == null ? {} : basePick(object, baseFlatten(props, 1)); }); module.exports = pick; /***/ }, /* 197 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(18), baseIteratee = __webpack_require__(160); /** * Creates an object with the same keys as `object` and values generated by * running each own enumerable property of `object` through `iteratee`. The * iteratee is invoked with three arguments: (value, key, object). * * @static * @memberOf _ * @category Object * @param {Object} object The object to iterate over. * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = baseIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { result[key] = iteratee(value, key, object); }); return result; } module.exports = mapValues; /***/ }, /* 198 */ /***/ function(module, exports, __webpack_require__) { var arrayReduce = __webpack_require__(109), baseEach = __webpack_require__(17), baseIteratee = __webpack_require__(160), baseReduce = __webpack_require__(199), isArray = __webpack_require__(11); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` through `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach); } module.exports = reduce; /***/ }, /* 199 */ /***/ function(module, exports) { /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } module.exports = baseReduce; /***/ }, /* 200 */ /***/ function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(148), baseUniq = __webpack_require__(201), rest = __webpack_require__(81); /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2, 1], [4, 2], [1, 2]); * // => [2, 1, 4] */ var union = rest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, true)); }); module.exports = union; /***/ }, /* 201 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(120), arrayIncludes = __webpack_require__(144), arrayIncludesWith = __webpack_require__(145), cacheHas = __webpack_require__(147), createSet = __webpack_require__(202), setToArray = __webpack_require__(176); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseUniq; /***/ }, /* 202 */ /***/ function(module, exports, __webpack_require__) { var Set = __webpack_require__(179), noop = __webpack_require__(203); /** * Creates a set of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && new Set([1, 2]).size === 2) ? noop : function(values) { return new Set(values); }; module.exports = createSet; /***/ }, /* 203 */ /***/ function(module, exports) { /** * A no-operation function that returns `undefined` regardless of the * arguments it receives. * * @static * @memberOf _ * @category Util * @example * * var object = { 'user': 'fred' }; * * _.noop(object) === undefined; * // => true */ function noop() { // No operation performed. } module.exports = noop; /***/ }, /* 204 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, global, setImmediate) {/* @preserve * The MIT License (MIT) * * Copyright (c) 2013-2015 Petka Antonov * * 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. * */ /** * bluebird build version 3.3.4 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each */ !function(e){if(true)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var SomePromiseArray = Promise._SomePromiseArray; function any(promises) { var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(1); ret.setUnwrap(); ret.init(); return promise; } Promise.any = function (promises) { return any(promises); }; Promise.prototype.any = function () { return any(this); }; }; },{}],2:[function(_dereq_,module,exports){ "use strict"; var firstLineError; try {throw new Error(); } catch (e) {firstLineError = e;} var schedule = _dereq_("./schedule"); var Queue = _dereq_("./queue"); var util = _dereq_("./util"); function Async() { this._isTickUsed = false; this._lateQueue = new Queue(16); this._normalQueue = new Queue(16); this._haveDrainedQueues = false; this._trampolineEnabled = true; var self = this; this.drainQueues = function () { self._drainQueues(); }; this._schedule = schedule; } Async.prototype.enableTrampoline = function() { this._trampolineEnabled = true; }; Async.prototype.disableTrampolineIfNecessary = function() { if (util.hasDevTools) { this._trampolineEnabled = false; } }; Async.prototype.haveItemsQueued = function () { return this._isTickUsed || this._haveDrainedQueues; }; Async.prototype.fatalError = function(e, isNode) { if (isNode) { process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + "\n"); process.exit(2); } else { this.throwLater(e); } }; Async.prototype.throwLater = function(fn, arg) { if (arguments.length === 1) { arg = fn; fn = function () { throw arg; }; } if (typeof setTimeout !== "undefined") { setTimeout(function() { fn(arg); }, 0); } else try { this._schedule(function() { fn(arg); }); } catch (e) { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } }; function AsyncInvokeLater(fn, receiver, arg) { this._lateQueue.push(fn, receiver, arg); this._queueTick(); } function AsyncInvoke(fn, receiver, arg) { this._normalQueue.push(fn, receiver, arg); this._queueTick(); } function AsyncSettlePromises(promise) { this._normalQueue._pushOne(promise); this._queueTick(); } if (!util.hasDevTools) { Async.prototype.invokeLater = AsyncInvokeLater; Async.prototype.invoke = AsyncInvoke; Async.prototype.settlePromises = AsyncSettlePromises; } else { Async.prototype.invokeLater = function (fn, receiver, arg) { if (this._trampolineEnabled) { AsyncInvokeLater.call(this, fn, receiver, arg); } else { this._schedule(function() { setTimeout(function() { fn.call(receiver, arg); }, 100); }); } }; Async.prototype.invoke = function (fn, receiver, arg) { if (this._trampolineEnabled) { AsyncInvoke.call(this, fn, receiver, arg); } else { this._schedule(function() { fn.call(receiver, arg); }); } }; Async.prototype.settlePromises = function(promise) { if (this._trampolineEnabled) { AsyncSettlePromises.call(this, promise); } else { this._schedule(function() { promise._settlePromises(); }); } }; } Async.prototype.invokeFirst = function (fn, receiver, arg) { this._normalQueue.unshift(fn, receiver, arg); this._queueTick(); }; Async.prototype._drainQueue = function(queue) { while (queue.length() > 0) { var fn = queue.shift(); if (typeof fn !== "function") { fn._settlePromises(); continue; } var receiver = queue.shift(); var arg = queue.shift(); fn.call(receiver, arg); } }; Async.prototype._drainQueues = function () { this._drainQueue(this._normalQueue); this._reset(); this._haveDrainedQueues = true; this._drainQueue(this._lateQueue); }; Async.prototype._queueTick = function () { if (!this._isTickUsed) { this._isTickUsed = true; this._schedule(this.drainQueues); } }; Async.prototype._reset = function () { this._isTickUsed = false; }; module.exports = Async; module.exports.firstLineError = firstLineError; },{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { var calledBind = false; var rejectThis = function(_, e) { this._reject(e); }; var targetRejected = function(e, context) { context.promiseRejectionQueued = true; context.bindingPromise._then(rejectThis, rejectThis, null, this, e); }; var bindingResolved = function(thisArg, context) { if (((this._bitField & 50397184) === 0)) { this._resolveCallback(context.target); } }; var bindingRejected = function(e, context) { if (!context.promiseRejectionQueued) this._reject(e); }; Promise.prototype.bind = function (thisArg) { if (!calledBind) { calledBind = true; Promise.prototype._propagateFrom = debug.propagateFromFunction(); Promise.prototype._boundValue = debug.boundValueFunction(); } var maybePromise = tryConvertToPromise(thisArg); var ret = new Promise(INTERNAL); ret._propagateFrom(this, 1); var target = this._target(); ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { var context = { promiseRejectionQueued: false, promise: ret, target: target, bindingPromise: maybePromise }; target._then(INTERNAL, targetRejected, undefined, ret, context); maybePromise._then( bindingResolved, bindingRejected, undefined, ret, context); ret._setOnCancel(maybePromise); } else { ret._resolveCallback(target); } return ret; }; Promise.prototype._setBoundTo = function (obj) { if (obj !== undefined) { this._bitField = this._bitField | 2097152; this._boundTo = obj; } else { this._bitField = this._bitField & (~2097152); } }; Promise.prototype._isBound = function () { return (this._bitField & 2097152) === 2097152; }; Promise.bind = function (thisArg, value) { return Promise.resolve(value).bind(thisArg); }; }; },{}],4:[function(_dereq_,module,exports){ "use strict"; var old; if (typeof Promise !== "undefined") old = Promise; function noConflict() { try { if (Promise === bluebird) Promise = old; } catch (e) {} return bluebird; } var bluebird = _dereq_("./promise")(); bluebird.noConflict = noConflict; module.exports = bluebird; },{"./promise":22}],5:[function(_dereq_,module,exports){ "use strict"; var cr = Object.create; if (cr) { var callerCache = cr(null); var getterCache = cr(null); callerCache[" size"] = getterCache[" size"] = 0; } module.exports = function(Promise) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var isIdentifier = util.isIdentifier; var getMethodCaller; var getGetter; if (false) { var makeMethodCaller = function (methodName) { return new Function("ensureMethod", " \n\ return function(obj) { \n\ 'use strict' \n\ var len = this.length; \n\ ensureMethod(obj, 'methodName'); \n\ switch(len) { \n\ case 1: return obj.methodName(this[0]); \n\ case 2: return obj.methodName(this[0], this[1]); \n\ case 3: return obj.methodName(this[0], this[1], this[2]); \n\ case 0: return obj.methodName(); \n\ default: \n\ return obj.methodName.apply(obj, this); \n\ } \n\ }; \n\ ".replace(/methodName/g, methodName))(ensureMethod); }; var makeGetter = function (propertyName) { return new Function("obj", " \n\ 'use strict'; \n\ return obj.propertyName; \n\ ".replace("propertyName", propertyName)); }; var getCompiled = function(name, compiler, cache) { var ret = cache[name]; if (typeof ret !== "function") { if (!isIdentifier(name)) { return null; } ret = compiler(name); cache[name] = ret; cache[" size"]++; if (cache[" size"] > 512) { var keys = Object.keys(cache); for (var i = 0; i < 256; ++i) delete cache[keys[i]]; cache[" size"] = keys.length - 256; } } return ret; }; getMethodCaller = function(name) { return getCompiled(name, makeMethodCaller, callerCache); }; getGetter = function(name) { return getCompiled(name, makeGetter, getterCache); }; } function ensureMethod(obj, methodName) { var fn; if (obj != null) fn = obj[methodName]; if (typeof fn !== "function") { var message = "Object " + util.classString(obj) + " has no method '" + util.toString(methodName) + "'"; throw new Promise.TypeError(message); } return fn; } function caller(obj) { var methodName = this.pop(); var fn = ensureMethod(obj, methodName); return fn.apply(obj, this); } Promise.prototype.call = function (methodName) { var args = [].slice.call(arguments, 1);; if (false) { if (canEvaluate) { var maybeCaller = getMethodCaller(methodName); if (maybeCaller !== null) { return this._then( maybeCaller, undefined, undefined, args, undefined); } } } args.push(methodName); return this._then(caller, undefined, undefined, args, undefined); }; function namedGetter(obj) { return obj[this]; } function indexedGetter(obj) { var index = +this; if (index < 0) index = Math.max(0, index + obj.length); return obj[index]; } Promise.prototype.get = function (propertyName) { var isIndex = (typeof propertyName === "number"); var getter; if (!isIndex) { if (canEvaluate) { var maybeGetter = getGetter(propertyName); getter = maybeGetter !== null ? maybeGetter : namedGetter; } else { getter = namedGetter; } } else { getter = indexedGetter; } return this._then(getter, undefined, undefined, propertyName, undefined); }; }; },{"./util":36}],6:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; Promise.prototype["break"] = Promise.prototype.cancel = function() { if (!debug.cancellation()) return this._warn("cancellation is disabled"); var promise = this; var child = promise; while (promise.isCancellable()) { if (!promise._cancelBy(child)) { if (child._isFollowing()) { child._followee().cancel(); } else { child._cancelBranched(); } break; } var parent = promise._cancellationParent; if (parent == null || !parent.isCancellable()) { if (promise._isFollowing()) { promise._followee().cancel(); } else { promise._cancelBranched(); } break; } else { if (promise._isFollowing()) promise._followee().cancel(); child = promise; promise = parent; } } }; Promise.prototype._branchHasCancelled = function() { this._branchesRemainingToCancel--; }; Promise.prototype._enoughBranchesHaveCancelled = function() { return this._branchesRemainingToCancel === undefined || this._branchesRemainingToCancel <= 0; }; Promise.prototype._cancelBy = function(canceller) { if (canceller === this) { this._branchesRemainingToCancel = 0; this._invokeOnCancel(); return true; } else { this._branchHasCancelled(); if (this._enoughBranchesHaveCancelled()) { this._invokeOnCancel(); return true; } } return false; }; Promise.prototype._cancelBranched = function() { if (this._enoughBranchesHaveCancelled()) { this._cancel(); } }; Promise.prototype._cancel = function() { if (!this.isCancellable()) return; this._setCancelled(); async.invoke(this._cancelPromises, this, undefined); }; Promise.prototype._cancelPromises = function() { if (this._length() > 0) this._settlePromises(); }; Promise.prototype._unsetOnCancel = function() { this._onCancelField = undefined; }; Promise.prototype.isCancellable = function() { return this.isPending() && !this.isCancelled(); }; Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { if (util.isArray(onCancelCallback)) { for (var i = 0; i < onCancelCallback.length; ++i) { this._doInvokeOnCancel(onCancelCallback[i], internalOnly); } } else if (onCancelCallback !== undefined) { if (typeof onCancelCallback === "function") { if (!internalOnly) { var e = tryCatch(onCancelCallback).call(this._boundValue()); if (e === errorObj) { this._attachExtraTrace(e.e); async.throwLater(e.e); } } } else { onCancelCallback._resultCancelled(this); } } }; Promise.prototype._invokeOnCancel = function() { var onCancelCallback = this._onCancel(); this._unsetOnCancel(); async.invoke(this._doInvokeOnCancel, this, onCancelCallback); }; Promise.prototype._invokeInternalOnCancel = function() { if (this.isCancellable()) { this._doInvokeOnCancel(this._onCancel(), true); this._unsetOnCancel(); } }; Promise.prototype._resultCancelled = function() { this.cancel(); }; }; },{"./util":36}],7:[function(_dereq_,module,exports){ "use strict"; module.exports = function(NEXT_FILTER) { var util = _dereq_("./util"); var getKeys = _dereq_("./es5").keys; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function catchFilter(instances, cb, promise) { return function(e) { var boundTo = promise._boundValue(); predicateLoop: for (var i = 0; i < instances.length; ++i) { var item = instances[i]; if (item === Error || (item != null && item.prototype instanceof Error)) { if (e instanceof item) { return tryCatch(cb).call(boundTo, e); } } else if (typeof item === "function") { var matchesPredicate = tryCatch(item).call(boundTo, e); if (matchesPredicate === errorObj) { return matchesPredicate; } else if (matchesPredicate) { return tryCatch(cb).call(boundTo, e); } } else if (util.isObject(e)) { var keys = getKeys(item); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; if (item[key] != e[key]) { continue predicateLoop; } } return tryCatch(cb).call(boundTo, e); } } return NEXT_FILTER; }; } return catchFilter; }; },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var longStackTraces = false; var contextStack = []; Promise.prototype._promiseCreated = function() {}; Promise.prototype._pushContext = function() {}; Promise.prototype._popContext = function() {return null;}; Promise._peekContext = Promise.prototype._peekContext = function() {}; function Context() { this._trace = new Context.CapturedTrace(peekContext()); } Context.prototype._pushContext = function () { if (this._trace !== undefined) { this._trace._promiseCreated = null; contextStack.push(this._trace); } }; Context.prototype._popContext = function () { if (this._trace !== undefined) { var trace = contextStack.pop(); var ret = trace._promiseCreated; trace._promiseCreated = null; return ret; } return null; }; function createContext() { if (longStackTraces) return new Context(); } function peekContext() { var lastIndex = contextStack.length - 1; if (lastIndex >= 0) { return contextStack[lastIndex]; } return undefined; } Context.CapturedTrace = null; Context.create = createContext; Context.deactivateLongStackTraces = function() {}; Context.activateLongStackTraces = function() { var Promise_pushContext = Promise.prototype._pushContext; var Promise_popContext = Promise.prototype._popContext; var Promise_PeekContext = Promise._peekContext; var Promise_peekContext = Promise.prototype._peekContext; var Promise_promiseCreated = Promise.prototype._promiseCreated; Context.deactivateLongStackTraces = function() { Promise.prototype._pushContext = Promise_pushContext; Promise.prototype._popContext = Promise_popContext; Promise._peekContext = Promise_PeekContext; Promise.prototype._peekContext = Promise_peekContext; Promise.prototype._promiseCreated = Promise_promiseCreated; longStackTraces = false; }; longStackTraces = true; Promise.prototype._pushContext = Context.prototype._pushContext; Promise.prototype._popContext = Context.prototype._popContext; Promise._peekContext = Promise.prototype._peekContext = peekContext; Promise.prototype._promiseCreated = function() { var ctx = this._peekContext(); if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; }; }; return Context; }; },{}],9:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, Context) { var getDomain = Promise._getDomain; var async = Promise._async; var Warning = _dereq_("./errors").Warning; var util = _dereq_("./util"); var canAttachTrace = util.canAttachTrace; var unhandledRejectionHandled; var possiblyUnhandledRejection; var bluebirdFramePattern = /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; var stackFramePattern = null; var formatStack = null; var indentStackFrames = false; var printWarning; var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && (true || util.env("BLUEBIRD_DEBUG") || util.env("NODE_ENV") === "development")); var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && (debugging || util.env("BLUEBIRD_WARNINGS"))); var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); Promise.prototype.suppressUnhandledRejections = function() { var target = this._target(); target._bitField = ((target._bitField & (~1048576)) | 524288); }; Promise.prototype._ensurePossibleRejectionHandled = function () { if ((this._bitField & 524288) !== 0) return; this._setRejectionIsUnhandled(); async.invokeLater(this._notifyUnhandledRejection, this, undefined); }; Promise.prototype._notifyUnhandledRejectionIsHandled = function () { fireRejectionEvent("rejectionHandled", unhandledRejectionHandled, undefined, this); }; Promise.prototype._setReturnedNonUndefined = function() { this._bitField = this._bitField | 268435456; }; Promise.prototype._returnedNonUndefined = function() { return (this._bitField & 268435456) !== 0; }; Promise.prototype._notifyUnhandledRejection = function () { if (this._isRejectionUnhandled()) { var reason = this._settledValue(); this._setUnhandledRejectionIsNotified(); fireRejectionEvent("unhandledRejection", possiblyUnhandledRejection, reason, this); } }; Promise.prototype._setUnhandledRejectionIsNotified = function () { this._bitField = this._bitField | 262144; }; Promise.prototype._unsetUnhandledRejectionIsNotified = function () { this._bitField = this._bitField & (~262144); }; Promise.prototype._isUnhandledRejectionNotified = function () { return (this._bitField & 262144) > 0; }; Promise.prototype._setRejectionIsUnhandled = function () { this._bitField = this._bitField | 1048576; }; Promise.prototype._unsetRejectionIsUnhandled = function () { this._bitField = this._bitField & (~1048576); if (this._isUnhandledRejectionNotified()) { this._unsetUnhandledRejectionIsNotified(); this._notifyUnhandledRejectionIsHandled(); } }; Promise.prototype._isRejectionUnhandled = function () { return (this._bitField & 1048576) > 0; }; Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { return warn(message, shouldUseOwnTrace, promise || this); }; Promise.onPossiblyUnhandledRejection = function (fn) { var domain = getDomain(); possiblyUnhandledRejection = typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) : undefined; }; Promise.onUnhandledRejectionHandled = function (fn) { var domain = getDomain(); unhandledRejectionHandled = typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) : undefined; }; var disableLongStackTraces = function() {}; Promise.longStackTraces = function () { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } if (!config.longStackTraces && longStackTracesIsSupported()) { var Promise_captureStackTrace = Promise.prototype._captureStackTrace; var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; config.longStackTraces = true; disableLongStackTraces = function() { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } Promise.prototype._captureStackTrace = Promise_captureStackTrace; Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; Context.deactivateLongStackTraces(); async.enableTrampoline(); config.longStackTraces = false; }; Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; Context.activateLongStackTraces(); async.disableTrampolineIfNecessary(); } }; Promise.hasLongStackTraces = function () { return config.longStackTraces && longStackTracesIsSupported(); }; var fireDomEvent = (function() { try { var event = document.createEvent("CustomEvent"); event.initCustomEvent("testingtheevent", false, true, {}); util.global.dispatchEvent(event); return function(name, event) { var domEvent = document.createEvent("CustomEvent"); domEvent.initCustomEvent(name.toLowerCase(), false, true, event); return !util.global.dispatchEvent(domEvent); }; } catch (e) {} return function() { return false; }; })(); var fireGlobalEvent = (function() { if (util.isNode) { return function() { return process.emit.apply(process, arguments); }; } else { if (!util.global) { return function() { return false; }; } return function(name) { var methodName = "on" + name.toLowerCase(); var method = util.global[methodName]; if (!method) return false; method.apply(util.global, [].slice.call(arguments, 1)); return true; }; } })(); function generatePromiseLifecycleEventObject(name, promise) { return {promise: promise}; } var eventToObjectGenerator = { promiseCreated: generatePromiseLifecycleEventObject, promiseFulfilled: generatePromiseLifecycleEventObject, promiseRejected: generatePromiseLifecycleEventObject, promiseResolved: generatePromiseLifecycleEventObject, promiseCancelled: generatePromiseLifecycleEventObject, promiseChained: function(name, promise, child) { return {promise: promise, child: child}; }, warning: function(name, warning) { return {warning: warning}; }, unhandledRejection: function (name, reason, promise) { return {reason: reason, promise: promise}; }, rejectionHandled: generatePromiseLifecycleEventObject }; var activeFireEvent = function (name) { var globalEventFired = false; try { globalEventFired = fireGlobalEvent.apply(null, arguments); } catch (e) { async.throwLater(e); globalEventFired = true; } var domEventFired = false; try { domEventFired = fireDomEvent(name, eventToObjectGenerator[name].apply(null, arguments)); } catch (e) { async.throwLater(e); domEventFired = true; } return domEventFired || globalEventFired; }; Promise.config = function(opts) { opts = Object(opts); if ("longStackTraces" in opts) { if (opts.longStackTraces) { Promise.longStackTraces(); } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { disableLongStackTraces(); } } if ("warnings" in opts) { var warningsOption = opts.warnings; config.warnings = !!warningsOption; wForgottenReturn = config.warnings; if (util.isObject(warningsOption)) { if ("wForgottenReturn" in warningsOption) { wForgottenReturn = !!warningsOption.wForgottenReturn; } } } if ("cancellation" in opts && opts.cancellation && !config.cancellation) { if (async.haveItemsQueued()) { throw new Error( "cannot enable cancellation after promises are in use"); } Promise.prototype._clearCancellationData = cancellationClearCancellationData; Promise.prototype._propagateFrom = cancellationPropagateFrom; Promise.prototype._onCancel = cancellationOnCancel; Promise.prototype._setOnCancel = cancellationSetOnCancel; Promise.prototype._attachCancellationCallback = cancellationAttachCancellationCallback; Promise.prototype._execute = cancellationExecute; propagateFromFunction = cancellationPropagateFrom; config.cancellation = true; } if ("monitoring" in opts) { if (opts.monitoring && !config.monitoring) { config.monitoring = true; Promise.prototype._fireEvent = activeFireEvent; } else if (!opts.monitoring && config.monitoring) { config.monitoring = false; Promise.prototype._fireEvent = defaultFireEvent; } } }; function defaultFireEvent() { return false; } Promise.prototype._fireEvent = defaultFireEvent; Promise.prototype._execute = function(executor, resolve, reject) { try { executor(resolve, reject); } catch (e) { return e; } }; Promise.prototype._onCancel = function () {}; Promise.prototype._setOnCancel = function (handler) { ; }; Promise.prototype._attachCancellationCallback = function(onCancel) { ; }; Promise.prototype._captureStackTrace = function () {}; Promise.prototype._attachExtraTrace = function () {}; Promise.prototype._clearCancellationData = function() {}; Promise.prototype._propagateFrom = function (parent, flags) { ; ; }; function cancellationExecute(executor, resolve, reject) { var promise = this; try { executor(resolve, reject, function(onCancel) { if (typeof onCancel !== "function") { throw new TypeError("onCancel must be a function, got: " + util.toString(onCancel)); } promise._attachCancellationCallback(onCancel); }); } catch (e) { return e; } } function cancellationAttachCancellationCallback(onCancel) { if (!this.isCancellable()) return this; var previousOnCancel = this._onCancel(); if (previousOnCancel !== undefined) { if (util.isArray(previousOnCancel)) { previousOnCancel.push(onCancel); } else { this._setOnCancel([previousOnCancel, onCancel]); } } else { this._setOnCancel(onCancel); } } function cancellationOnCancel() { return this._onCancelField; } function cancellationSetOnCancel(onCancel) { this._onCancelField = onCancel; } function cancellationClearCancellationData() { this._cancellationParent = undefined; this._onCancelField = undefined; } function cancellationPropagateFrom(parent, flags) { if ((flags & 1) !== 0) { this._cancellationParent = parent; var branchesRemainingToCancel = parent._branchesRemainingToCancel; if (branchesRemainingToCancel === undefined) { branchesRemainingToCancel = 0; } parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; } if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } function bindingPropagateFrom(parent, flags) { if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } var propagateFromFunction = bindingPropagateFrom; function boundValueFunction() { var ret = this._boundTo; if (ret !== undefined) { if (ret instanceof Promise) { if (ret.isFulfilled()) { return ret.value(); } else { return undefined; } } } return ret; } function longStackTracesCaptureStackTrace() { this._trace = new CapturedTrace(this._peekContext()); } function longStackTracesAttachExtraTrace(error, ignoreSelf) { if (canAttachTrace(error)) { var trace = this._trace; if (trace !== undefined) { if (ignoreSelf) trace = trace._parent; } if (trace !== undefined) { trace.attachExtraTrace(error); } else if (!error.__stackCleaned__) { var parsed = parseStackAndMessage(error); util.notEnumerableProp(error, "stack", parsed.message + "\n" + parsed.stack.join("\n")); util.notEnumerableProp(error, "__stackCleaned__", true); } } } function checkForgottenReturns(returnValue, promiseCreated, name, promise, parent) { if (returnValue === undefined && promiseCreated !== null && wForgottenReturn) { if (parent !== undefined && parent._returnedNonUndefined()) return; var bitField = promise._bitField; if ((bitField & 65535) === 0) return; if (name) name = name + " "; var msg = "a promise was created in a " + name + "handler but was not returned from it"; promise._warn(msg, true, promiseCreated); } } function deprecated(name, replacement) { var message = name + " is deprecated and will be removed in a future version."; if (replacement) message += " Use " + replacement + " instead."; return warn(message); } function warn(message, shouldUseOwnTrace, promise) { if (!config.warnings) return; var warning = new Warning(message); var ctx; if (shouldUseOwnTrace) { promise._attachExtraTrace(warning); } else if (config.longStackTraces && (ctx = Promise._peekContext())) { ctx.attachExtraTrace(warning); } else { var parsed = parseStackAndMessage(warning); warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); } if (!activeFireEvent("warning", warning)) { formatAndLogError(warning, "", true); } } function reconstructStack(message, stacks) { for (var i = 0; i < stacks.length - 1; ++i) { stacks[i].push("From previous event:"); stacks[i] = stacks[i].join("\n"); } if (i < stacks.length) { stacks[i] = stacks[i].join("\n"); } return message + "\n" + stacks.join("\n"); } function removeDuplicateOrEmptyJumps(stacks) { for (var i = 0; i < stacks.length; ++i) { if (stacks[i].length === 0 || ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { stacks.splice(i, 1); i--; } } } function removeCommonRoots(stacks) { var current = stacks[0]; for (var i = 1; i < stacks.length; ++i) { var prev = stacks[i]; var currentLastIndex = current.length - 1; var currentLastLine = current[currentLastIndex]; var commonRootMeetPoint = -1; for (var j = prev.length - 1; j >= 0; --j) { if (prev[j] === currentLastLine) { commonRootMeetPoint = j; break; } } for (var j = commonRootMeetPoint; j >= 0; --j) { var line = prev[j]; if (current[currentLastIndex] === line) { current.pop(); currentLastIndex--; } else { break; } } current = prev; } } function cleanStack(stack) { var ret = []; for (var i = 0; i < stack.length; ++i) { var line = stack[i]; var isTraceLine = " (No stack trace)" === line || stackFramePattern.test(line); var isInternalFrame = isTraceLine && shouldIgnore(line); if (isTraceLine && !isInternalFrame) { if (indentStackFrames && line.charAt(0) !== " ") { line = " " + line; } ret.push(line); } } return ret; } function stackFramesAsArray(error) { var stack = error.stack.replace(/\s+$/g, "").split("\n"); for (var i = 0; i < stack.length; ++i) { var line = stack[i]; if (" (No stack trace)" === line || stackFramePattern.test(line)) { break; } } if (i > 0) { stack = stack.slice(i); } return stack; } function parseStackAndMessage(error) { var stack = error.stack; var message = error.toString(); stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error) : [" (No stack trace)"]; return { message: message, stack: cleanStack(stack) }; } function formatAndLogError(error, title, isSoft) { if (typeof console !== "undefined") { var message; if (util.isObject(error)) { var stack = error.stack; message = title + formatStack(stack, error); } else { message = title + String(error); } if (typeof printWarning === "function") { printWarning(message, isSoft); } else if (typeof console.log === "function" || typeof console.log === "object") { console.log(message); } } } function fireRejectionEvent(name, localHandler, reason, promise) { var localEventFired = false; try { if (typeof localHandler === "function") { localEventFired = true; if (name === "rejectionHandled") { localHandler(promise); } else { localHandler(reason, promise); } } } catch (e) { async.throwLater(e); } if (name === "unhandledRejection") { if (!activeFireEvent(name, reason, promise) && !localEventFired) { formatAndLogError(reason, "Unhandled rejection "); } } else { activeFireEvent(name, promise); } } function formatNonError(obj) { var str; if (typeof obj === "function") { str = "[function " + (obj.name || "anonymous") + "]"; } else { str = obj && typeof obj.toString === "function" ? obj.toString() : util.toString(obj); var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; if (ruselessToString.test(str)) { try { var newStr = JSON.stringify(obj); str = newStr; } catch(e) { } } if (str.length === 0) { str = "(empty array)"; } } return ("(<" + snip(str) + ">, no stack trace)"); } function snip(str) { var maxChars = 41; if (str.length < maxChars) { return str; } return str.substr(0, maxChars - 3) + "..."; } function longStackTracesIsSupported() { return typeof captureStackTrace === "function"; } var shouldIgnore = function() { return false; }; var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; function parseLineInfo(line) { var matches = line.match(parseLineInfoRegex); if (matches) { return { fileName: matches[1], line: parseInt(matches[2], 10) }; } } function setBounds(firstLineError, lastLineError) { if (!longStackTracesIsSupported()) return; var firstStackLines = firstLineError.stack.split("\n"); var lastStackLines = lastLineError.stack.split("\n"); var firstIndex = -1; var lastIndex = -1; var firstFileName; var lastFileName; for (var i = 0; i < firstStackLines.length; ++i) { var result = parseLineInfo(firstStackLines[i]); if (result) { firstFileName = result.fileName; firstIndex = result.line; break; } } for (var i = 0; i < lastStackLines.length; ++i) { var result = parseLineInfo(lastStackLines[i]); if (result) { lastFileName = result.fileName; lastIndex = result.line; break; } } if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || firstFileName !== lastFileName || firstIndex >= lastIndex) { return; } shouldIgnore = function(line) { if (bluebirdFramePattern.test(line)) return true; var info = parseLineInfo(line); if (info) { if (info.fileName === firstFileName && (firstIndex <= info.line && info.line <= lastIndex)) { return true; } } return false; }; } function CapturedTrace(parent) { this._parent = parent; this._promisesCreated = 0; var length = this._length = 1 + (parent === undefined ? 0 : parent._length); captureStackTrace(this, CapturedTrace); if (length > 32) this.uncycle(); } util.inherits(CapturedTrace, Error); Context.CapturedTrace = CapturedTrace; CapturedTrace.prototype.uncycle = function() { var length = this._length; if (length < 2) return; var nodes = []; var stackToIndex = {}; for (var i = 0, node = this; node !== undefined; ++i) { nodes.push(node); node = node._parent; } length = this._length = i; for (var i = length - 1; i >= 0; --i) { var stack = nodes[i].stack; if (stackToIndex[stack] === undefined) { stackToIndex[stack] = i; } } for (var i = 0; i < length; ++i) { var currentStack = nodes[i].stack; var index = stackToIndex[currentStack]; if (index !== undefined && index !== i) { if (index > 0) { nodes[index - 1]._parent = undefined; nodes[index - 1]._length = 1; } nodes[i]._parent = undefined; nodes[i]._length = 1; var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; if (index < length - 1) { cycleEdgeNode._parent = nodes[index + 1]; cycleEdgeNode._parent.uncycle(); cycleEdgeNode._length = cycleEdgeNode._parent._length + 1; } else { cycleEdgeNode._parent = undefined; cycleEdgeNode._length = 1; } var currentChildLength = cycleEdgeNode._length + 1; for (var j = i - 2; j >= 0; --j) { nodes[j]._length = currentChildLength; currentChildLength++; } return; } } }; CapturedTrace.prototype.attachExtraTrace = function(error) { if (error.__stackCleaned__) return; this.uncycle(); var parsed = parseStackAndMessage(error); var message = parsed.message; var stacks = [parsed.stack]; var trace = this; while (trace !== undefined) { stacks.push(cleanStack(trace.stack.split("\n"))); trace = trace._parent; } removeCommonRoots(stacks); removeDuplicateOrEmptyJumps(stacks); util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); util.notEnumerableProp(error, "__stackCleaned__", true); }; var captureStackTrace = (function stackDetection() { var v8stackFramePattern = /^\s*at\s*/; var v8stackFormatter = function(stack, error) { if (typeof stack === "string") return stack; if (error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") { Error.stackTraceLimit += 6; stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; var captureStackTrace = Error.captureStackTrace; shouldIgnore = function(line) { return bluebirdFramePattern.test(line); }; return function(receiver, ignoreUntil) { Error.stackTraceLimit += 6; captureStackTrace(receiver, ignoreUntil); Error.stackTraceLimit -= 6; }; } var err = new Error(); if (typeof err.stack === "string" && err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { stackFramePattern = /@/; formatStack = v8stackFormatter; indentStackFrames = true; return function captureStackTrace(o) { o.stack = new Error().stack; }; } var hasStackAfterThrow; try { throw new Error(); } catch(e) { hasStackAfterThrow = ("stack" in e); } if (!("stack" in err) && hasStackAfterThrow && typeof Error.stackTraceLimit === "number") { stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; return function captureStackTrace(o) { Error.stackTraceLimit += 6; try { throw new Error(); } catch(e) { o.stack = e.stack; } Error.stackTraceLimit -= 6; }; } formatStack = function(stack, error) { if (typeof stack === "string") return stack; if ((typeof error === "object" || typeof error === "function") && error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; return null; })([]); if (typeof console !== "undefined" && typeof console.warn !== "undefined") { printWarning = function (message) { console.warn(message); }; if (util.isNode && process.stderr.isTTY) { printWarning = function(message, isSoft) { var color = isSoft ? "\u001b[33m" : "\u001b[31m"; console.warn(color + message + "\u001b[0m\n"); }; } else if (!util.isNode && typeof (new Error().stack) === "string") { printWarning = function(message, isSoft) { console.warn("%c" + message, isSoft ? "color: darkorange" : "color: red"); }; } } var config = { warnings: warnings, longStackTraces: false, cancellation: false, monitoring: false }; if (longStackTraces) Promise.longStackTraces(); return { longStackTraces: function() { return config.longStackTraces; }, warnings: function() { return config.warnings; }, cancellation: function() { return config.cancellation; }, monitoring: function() { return config.monitoring; }, propagateFromFunction: function() { return propagateFromFunction; }, boundValueFunction: function() { return boundValueFunction; }, checkForgottenReturns: checkForgottenReturns, setBounds: setBounds, warn: warn, deprecated: deprecated, CapturedTrace: CapturedTrace, fireDomEvent: fireDomEvent, fireGlobalEvent: fireGlobalEvent }; }; },{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function returner() { return this.value; } function thrower() { throw this.reason; } Promise.prototype["return"] = Promise.prototype.thenReturn = function (value) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( returner, undefined, undefined, {value: value}, undefined); }; Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) { return this._then( thrower, undefined, undefined, {reason: reason}, undefined); }; Promise.prototype.catchThrow = function (reason) { if (arguments.length <= 1) { return this._then( undefined, thrower, undefined, {reason: reason}, undefined); } else { var _reason = arguments[1]; var handler = function() {throw _reason;}; return this.caught(reason, handler); } }; Promise.prototype.catchReturn = function (value) { if (arguments.length <= 1) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( undefined, returner, undefined, {value: value}, undefined); } else { var _value = arguments[1]; if (_value instanceof Promise) _value.suppressUnhandledRejections(); var handler = function() {return _value;}; return this.caught(value, handler); } }; }; },{}],11:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseReduce = Promise.reduce; var PromiseAll = Promise.all; function promiseAllThis() { return PromiseAll(this); } function PromiseMapSeries(promises, fn) { return PromiseReduce(promises, fn, INTERNAL, INTERNAL); } Promise.prototype.each = function (fn) { return this.mapSeries(fn) ._then(promiseAllThis, undefined, undefined, this, undefined); }; Promise.prototype.mapSeries = function (fn) { return PromiseReduce(this, fn, INTERNAL, INTERNAL); }; Promise.each = function (promises, fn) { return PromiseMapSeries(promises, fn) ._then(promiseAllThis, undefined, undefined, promises, undefined); }; Promise.mapSeries = PromiseMapSeries; }; },{}],12:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var Objectfreeze = es5.freeze; var util = _dereq_("./util"); var inherits = util.inherits; var notEnumerableProp = util.notEnumerableProp; function subError(nameProperty, defaultMessage) { function SubError(message) { if (!(this instanceof SubError)) return new SubError(message); notEnumerableProp(this, "message", typeof message === "string" ? message : defaultMessage); notEnumerableProp(this, "name", nameProperty); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { Error.call(this); } } inherits(SubError, Error); return SubError; } var _TypeError, _RangeError; var Warning = subError("Warning", "warning"); var CancellationError = subError("CancellationError", "cancellation error"); var TimeoutError = subError("TimeoutError", "timeout error"); var AggregateError = subError("AggregateError", "aggregate error"); try { _TypeError = TypeError; _RangeError = RangeError; } catch(e) { _TypeError = subError("TypeError", "type error"); _RangeError = subError("RangeError", "range error"); } var methods = ("join pop push shift unshift slice filter forEach some " + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); for (var i = 0; i < methods.length; ++i) { if (typeof Array.prototype[methods[i]] === "function") { AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; } } es5.defineProperty(AggregateError.prototype, "length", { value: 0, configurable: false, writable: true, enumerable: true }); AggregateError.prototype["isOperational"] = true; var level = 0; AggregateError.prototype.toString = function() { var indent = Array(level * 4 + 1).join(" "); var ret = "\n" + indent + "AggregateError of:" + "\n"; level++; indent = Array(level * 4 + 1).join(" "); for (var i = 0; i < this.length; ++i) { var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; var lines = str.split("\n"); for (var j = 0; j < lines.length; ++j) { lines[j] = indent + lines[j]; } str = lines.join("\n"); ret += str + "\n"; } level--; return ret; }; function OperationalError(message) { if (!(this instanceof OperationalError)) return new OperationalError(message); notEnumerableProp(this, "name", "OperationalError"); notEnumerableProp(this, "message", message); this.cause = message; this["isOperational"] = true; if (message instanceof Error) { notEnumerableProp(this, "message", message.message); notEnumerableProp(this, "stack", message.stack); } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } inherits(OperationalError, Error); var errorTypes = Error["__BluebirdErrorTypes__"]; if (!errorTypes) { errorTypes = Objectfreeze({ CancellationError: CancellationError, TimeoutError: TimeoutError, OperationalError: OperationalError, RejectionError: OperationalError, AggregateError: AggregateError }); es5.defineProperty(Error, "__BluebirdErrorTypes__", { value: errorTypes, writable: false, enumerable: false, configurable: false }); } module.exports = { Error: Error, TypeError: _TypeError, RangeError: _RangeError, CancellationError: errorTypes.CancellationError, OperationalError: errorTypes.OperationalError, TimeoutError: errorTypes.TimeoutError, AggregateError: errorTypes.AggregateError, Warning: Warning }; },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ var isES5 = (function(){ "use strict"; return this === undefined; })(); if (isES5) { module.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, getDescriptor: Object.getOwnPropertyDescriptor, keys: Object.keys, names: Object.getOwnPropertyNames, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, isES5: isES5, propertyIsWritable: function(obj, prop) { var descriptor = Object.getOwnPropertyDescriptor(obj, prop); return !!(!descriptor || descriptor.writable || descriptor.set); } }; } else { var has = {}.hasOwnProperty; var str = {}.toString; var proto = {}.constructor.prototype; var ObjectKeys = function (o) { var ret = []; for (var key in o) { if (has.call(o, key)) { ret.push(key); } } return ret; }; var ObjectGetDescriptor = function(o, key) { return {value: o[key]}; }; var ObjectDefineProperty = function (o, key, desc) { o[key] = desc.value; return o; }; var ObjectFreeze = function (obj) { return obj; }; var ObjectGetPrototypeOf = function (obj) { try { return Object(obj).constructor.prototype; } catch (e) { return proto; } }; var ArrayIsArray = function (obj) { try { return str.call(obj) === "[object Array]"; } catch(e) { return false; } }; module.exports = { isArray: ArrayIsArray, keys: ObjectKeys, names: ObjectKeys, defineProperty: ObjectDefineProperty, getDescriptor: ObjectGetDescriptor, freeze: ObjectFreeze, getPrototypeOf: ObjectGetPrototypeOf, isES5: isES5, propertyIsWritable: function() { return true; } }; } },{}],14:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseMap = Promise.map; Promise.prototype.filter = function (fn, options) { return PromiseMap(this, fn, options, INTERNAL); }; Promise.filter = function (promises, fn, options) { return PromiseMap(promises, fn, options, INTERNAL); }; }; },{}],15:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, tryConvertToPromise) { var util = _dereq_("./util"); var CancellationError = Promise.CancellationError; var errorObj = util.errorObj; function PassThroughHandlerContext(promise, type, handler) { this.promise = promise; this.type = type; this.handler = handler; this.called = false; this.cancelPromise = null; } PassThroughHandlerContext.prototype.isFinallyHandler = function() { return this.type === 0; }; function FinallyHandlerCancelReaction(finallyHandler) { this.finallyHandler = finallyHandler; } FinallyHandlerCancelReaction.prototype._resultCancelled = function() { checkCancel(this.finallyHandler); }; function checkCancel(ctx, reason) { if (ctx.cancelPromise != null) { if (arguments.length > 1) { ctx.cancelPromise._reject(reason); } else { ctx.cancelPromise._cancel(); } ctx.cancelPromise = null; return true; } return false; } function succeed() { return finallyHandler.call(this, this.promise._target()._settledValue()); } function fail(reason) { if (checkCancel(this, reason)) return; errorObj.e = reason; return errorObj; } function finallyHandler(reasonOrValue) { var promise = this.promise; var handler = this.handler; if (!this.called) { this.called = true; var ret = this.isFinallyHandler() ? handler.call(promise._boundValue()) : handler.call(promise._boundValue(), reasonOrValue); if (ret !== undefined) { promise._setReturnedNonUndefined(); var maybePromise = tryConvertToPromise(ret, promise); if (maybePromise instanceof Promise) { if (this.cancelPromise != null) { if (maybePromise.isCancelled()) { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); errorObj.e = reason; return errorObj; } else if (maybePromise.isPending()) { maybePromise._attachCancellationCallback( new FinallyHandlerCancelReaction(this)); } } return maybePromise._then( succeed, fail, undefined, this, undefined); } } } if (promise.isRejected()) { checkCancel(this); errorObj.e = reasonOrValue; return errorObj; } else { checkCancel(this); return reasonOrValue; } } Promise.prototype._passThrough = function(handler, type, success, fail) { if (typeof handler !== "function") return this.then(); return this._then(success, fail, undefined, new PassThroughHandlerContext(this, type, handler), undefined); }; Promise.prototype.lastly = Promise.prototype["finally"] = function (handler) { return this._passThrough(handler, 0, finallyHandler, finallyHandler); }; Promise.prototype.tap = function (handler) { return this._passThrough(handler, 1, finallyHandler); }; return PassThroughHandlerContext; }; },{"./util":36}],16:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug) { var errors = _dereq_("./errors"); var TypeError = errors.TypeError; var util = _dereq_("./util"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; var yieldHandlers = []; function promiseFromYieldHandler(value, yieldHandlers, traceParent) { for (var i = 0; i < yieldHandlers.length; ++i) { traceParent._pushContext(); var result = tryCatch(yieldHandlers[i])(value); traceParent._popContext(); if (result === errorObj) { traceParent._pushContext(); var ret = Promise.reject(errorObj.e); traceParent._popContext(); return ret; } var maybePromise = tryConvertToPromise(result, traceParent); if (maybePromise instanceof Promise) return maybePromise; } return null; } function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { var promise = this._promise = new Promise(INTERNAL); promise._captureStackTrace(); promise._setOnCancel(this); this._stack = stack; this._generatorFunction = generatorFunction; this._receiver = receiver; this._generator = undefined; this._yieldHandlers = typeof yieldHandler === "function" ? [yieldHandler].concat(yieldHandlers) : yieldHandlers; this._yieldedPromise = null; } util.inherits(PromiseSpawn, Proxyable); PromiseSpawn.prototype._isResolved = function() { return this._promise === null; }; PromiseSpawn.prototype._cleanup = function() { this._promise = this._generator = null; }; PromiseSpawn.prototype._promiseCancelled = function() { if (this._isResolved()) return; var implementsReturn = typeof this._generator["return"] !== "undefined"; var result; if (!implementsReturn) { var reason = new Promise.CancellationError( "generator .return() sentinel"); Promise.coroutine.returnSentinel = reason; this._promise._attachExtraTrace(reason); this._promise._pushContext(); result = tryCatch(this._generator["throw"]).call(this._generator, reason); this._promise._popContext(); if (result === errorObj && result.e === reason) { result = null; } } else { this._promise._pushContext(); result = tryCatch(this._generator["return"]).call(this._generator, undefined); this._promise._popContext(); } var promise = this._promise; this._cleanup(); if (result === errorObj) { promise._rejectCallback(result.e, false); } else { promise.cancel(); } }; PromiseSpawn.prototype._promiseFulfilled = function(value) { this._yieldedPromise = null; this._promise._pushContext(); var result = tryCatch(this._generator.next).call(this._generator, value); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._promiseRejected = function(reason) { this._yieldedPromise = null; this._promise._attachExtraTrace(reason); this._promise._pushContext(); var result = tryCatch(this._generator["throw"]) .call(this._generator, reason); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._resultCancelled = function() { if (this._yieldedPromise instanceof Promise) { var promise = this._yieldedPromise; this._yieldedPromise = null; this._promiseCancelled(); promise.cancel(); } }; PromiseSpawn.prototype.promise = function () { return this._promise; }; PromiseSpawn.prototype._run = function () { this._generator = this._generatorFunction.call(this._receiver); this._receiver = this._generatorFunction = undefined; this._promiseFulfilled(undefined); }; PromiseSpawn.prototype._continue = function (result) { var promise = this._promise; if (result === errorObj) { this._cleanup(); return promise._rejectCallback(result.e, false); } var value = result.value; if (result.done === true) { this._cleanup(); return promise._resolveCallback(value); } else { var maybePromise = tryConvertToPromise(value, this._promise); if (!(maybePromise instanceof Promise)) { maybePromise = promiseFromYieldHandler(maybePromise, this._yieldHandlers, this._promise); if (maybePromise === null) { this._promiseRejected( new TypeError( "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + "From coroutine:\u000a" + this._stack.split("\n").slice(1, -7).join("\n") ) ); return; } } maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { this._yieldedPromise = maybePromise; maybePromise._proxy(this, null); } else if (((bitField & 33554432) !== 0)) { this._promiseFulfilled(maybePromise._value()); } else if (((bitField & 16777216) !== 0)) { this._promiseRejected(maybePromise._reason()); } else { this._promiseCancelled(); } } }; Promise.coroutine = function (generatorFunction, options) { if (typeof generatorFunction !== "function") { throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var yieldHandler = Object(options).yieldHandler; var PromiseSpawn$ = PromiseSpawn; var stack = new Error().stack; return function () { var generator = generatorFunction.apply(this, arguments); var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, stack); var ret = spawn.promise(); spawn._generator = generator; spawn._promiseFulfilled(undefined); return ret; }; }; Promise.coroutine.addYieldHandler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } yieldHandlers.push(fn); }; Promise.spawn = function (generatorFunction) { debug.deprecated("Promise.spawn()", "Promise.coroutine()"); if (typeof generatorFunction !== "function") { return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var spawn = new PromiseSpawn(generatorFunction, this); var ret = spawn.promise(); spawn._run(Promise.spawn); return ret; }; }; },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var tryCatch = util.tryCatch; var errorObj = util.errorObj; var reject; if (false) { if (canEvaluate) { var thenCallback = function(i) { return new Function("value", "holder", " \n\ 'use strict'; \n\ holder.pIndex = value; \n\ holder.checkFulfillment(this); \n\ ".replace(/Index/g, i)); }; var promiseSetter = function(i) { return new Function("promise", "holder", " \n\ 'use strict'; \n\ holder.pIndex = promise; \n\ ".replace(/Index/g, i)); }; var generateHolderClass = function(total) { var props = new Array(total); for (var i = 0; i < props.length; ++i) { props[i] = "this.p" + (i+1); } var assignment = props.join(" = ") + " = null;"; var cancellationCode= "var promise;\n" + props.map(function(prop) { return " \n\ promise = " + prop + "; \n\ if (promise instanceof Promise) { \n\ promise.cancel(); \n\ } \n\ "; }).join("\n"); var passedArguments = props.join(", "); var name = "Holder$" + total; var code = "return function(tryCatch, errorObj, Promise) { \n\ 'use strict'; \n\ function [TheName](fn) { \n\ [TheProperties] \n\ this.fn = fn; \n\ this.now = 0; \n\ } \n\ [TheName].prototype.checkFulfillment = function(promise) { \n\ var now = ++this.now; \n\ if (now === [TheTotal]) { \n\ promise._pushContext(); \n\ var callback = this.fn; \n\ var ret = tryCatch(callback)([ThePassedArguments]); \n\ promise._popContext(); \n\ if (ret === errorObj) { \n\ promise._rejectCallback(ret.e, false); \n\ } else { \n\ promise._resolveCallback(ret); \n\ } \n\ } \n\ }; \n\ \n\ [TheName].prototype._resultCancelled = function() { \n\ [CancellationCode] \n\ }; \n\ \n\ return [TheName]; \n\ }(tryCatch, errorObj, Promise); \n\ "; code = code.replace(/\[TheName\]/g, name) .replace(/\[TheTotal\]/g, total) .replace(/\[ThePassedArguments\]/g, passedArguments) .replace(/\[TheProperties\]/g, assignment) .replace(/\[CancellationCode\]/g, cancellationCode); return new Function("tryCatch", "errorObj", "Promise", code) (tryCatch, errorObj, Promise); }; var holderClasses = []; var thenCallbacks = []; var promiseSetters = []; for (var i = 0; i < 8; ++i) { holderClasses.push(generateHolderClass(i + 1)); thenCallbacks.push(thenCallback(i + 1)); promiseSetters.push(promiseSetter(i + 1)); } reject = function (reason) { this._reject(reason); }; }} Promise.join = function () { var last = arguments.length - 1; var fn; if (last > 0 && typeof arguments[last] === "function") { fn = arguments[last]; if (false) { if (last <= 8 && canEvaluate) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var HolderClass = holderClasses[last - 1]; var holder = new HolderClass(fn); var callbacks = thenCallbacks; for (var i = 0; i < last; ++i) { var maybePromise = tryConvertToPromise(arguments[i], ret); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { maybePromise._then(callbacks[i], reject, undefined, ret, holder); promiseSetters[i](maybePromise, holder); } else if (((bitField & 33554432) !== 0)) { callbacks[i].call(ret, maybePromise._value(), holder); } else if (((bitField & 16777216) !== 0)) { ret._reject(maybePromise._reason()); } else { ret._cancel(); } } else { callbacks[i].call(ret, maybePromise, holder); } } if (!ret._isFateSealed()) { ret._setAsyncGuaranteed(); ret._setOnCancel(holder); } return ret; } } } var args = [].slice.call(arguments);; if (fn) args.pop(); var ret = new PromiseArray(args).promise(); return fn !== undefined ? ret.spread(fn) : ret; }; }; },{"./util":36}],18:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var EMPTY_ARRAY = []; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); var domain = getDomain(); this._callback = domain === null ? fn : domain.bind(fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; this._limit = limit; this._inFlight = 0; this._queue = limit >= 1 ? [] : EMPTY_ARRAY; this._init$(undefined, -2); } util.inherits(MappingPromiseArray, PromiseArray); MappingPromiseArray.prototype._init = function () {}; MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { var values = this._values; var length = this.length(); var preservedValues = this._preservedValues; var limit = this._limit; if (index < 0) { index = (index * -1) - 1; values[index] = value; if (limit >= 1) { this._inFlight--; this._drainQueue(); if (this._isResolved()) return true; } } else { if (limit >= 1 && this._inFlight >= limit) { values[index] = value; this._queue.push(index); return false; } if (preservedValues !== null) preservedValues[index] = value; var promise = this._promise; var callback = this._callback; var receiver = promise._boundValue(); promise._pushContext(); var ret = tryCatch(callback).call(receiver, value, index, length); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, preservedValues !== null ? "Promise.filter" : "Promise.map", promise ); if (ret === errorObj) { this._reject(ret.e); return true; } var maybePromise = tryConvertToPromise(ret, this._promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { if (limit >= 1) this._inFlight++; values[index] = maybePromise; maybePromise._proxy(this, (index + 1) * -1); return false; } else if (((bitField & 33554432) !== 0)) { ret = maybePromise._value(); } else if (((bitField & 16777216) !== 0)) { this._reject(maybePromise._reason()); return true; } else { this._cancel(); return true; } } values[index] = ret; } var totalResolved = ++this._totalResolved; if (totalResolved >= length) { if (preservedValues !== null) { this._filter(values, preservedValues); } else { this._resolve(values); } return true; } return false; }; MappingPromiseArray.prototype._drainQueue = function () { var queue = this._queue; var limit = this._limit; var values = this._values; while (queue.length > 0 && this._inFlight < limit) { if (this._isResolved()) return; var index = queue.pop(); this._promiseFulfilled(values[index], index); } }; MappingPromiseArray.prototype._filter = function (booleans, values) { var len = values.length; var ret = new Array(len); var j = 0; for (var i = 0; i < len; ++i) { if (booleans[i]) ret[j++] = values[i]; } ret.length = j; this._resolve(ret); }; MappingPromiseArray.prototype.preservedValues = function () { return this._preservedValues; }; function map(promises, fn, options, _filter) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var limit = typeof options === "object" && options !== null ? options.concurrency : 0; limit = typeof limit === "number" && isFinite(limit) && limit >= 1 ? limit : 0; return new MappingPromiseArray(promises, fn, limit, _filter).promise(); } Promise.prototype.map = function (fn, options) { return map(this, fn, options, null); }; Promise.map = function (promises, fn, options, _filter) { return map(promises, fn, options, _filter); }; }; },{"./util":36}],19:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; Promise.method = function (fn) { if (typeof fn !== "function") { throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); } return function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.method", ret); ret._resolveFromSyncValue(value); return ret; }; }; Promise.attempt = Promise["try"] = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value; if (arguments.length > 1) { debug.deprecated("calling Promise.try with more than 1 argument"); var arg = arguments[1]; var ctx = arguments[2]; value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) : tryCatch(fn).call(ctx, arg); } else { value = tryCatch(fn)(); } var promiseCreated = ret._popContext(); debug.checkForgottenReturns( value, promiseCreated, "Promise.try", ret); ret._resolveFromSyncValue(value); return ret; }; Promise.prototype._resolveFromSyncValue = function (value) { if (value === util.errorObj) { this._rejectCallback(value.e, false); } else { this._resolveCallback(value, true); } }; }; },{"./util":36}],20:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var maybeWrapAsError = util.maybeWrapAsError; var errors = _dereq_("./errors"); var OperationalError = errors.OperationalError; var es5 = _dereq_("./es5"); function isUntypedError(obj) { return obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype; } var rErrorKey = /^(?:name|message|stack|cause)$/; function wrapAsOperationalError(obj) { var ret; if (isUntypedError(obj)) { ret = new OperationalError(obj); ret.name = obj.name; ret.message = obj.message; ret.stack = obj.stack; var keys = es5.keys(obj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!rErrorKey.test(key)) { ret[key] = obj[key]; } } return ret; } util.markAsOriginatingFromRejection(obj); return obj; } function nodebackForPromise(promise, multiArgs) { return function(err, value) { if (promise === null) return; if (err) { var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); promise._attachExtraTrace(wrapped); promise._reject(wrapped); } else if (!multiArgs) { promise._fulfill(value); } else { var args = [].slice.call(arguments, 1);; promise._fulfill(args); } promise = null; }; } module.exports = nodebackForPromise; },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var util = _dereq_("./util"); var async = Promise._async; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function spreadAdapter(val, nodeback) { var promise = this; if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); var ret = tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); if (ret === errorObj) { async.throwLater(ret.e); } } function successAdapter(val, nodeback) { var promise = this; var receiver = promise._boundValue(); var ret = val === undefined ? tryCatch(nodeback).call(receiver, null) : tryCatch(nodeback).call(receiver, null, val); if (ret === errorObj) { async.throwLater(ret.e); } } function errorAdapter(reason, nodeback) { var promise = this; if (!reason) { var newReason = new Error(reason + ""); newReason.cause = reason; reason = newReason; } var ret = tryCatch(nodeback).call(promise._boundValue(), reason); if (ret === errorObj) { async.throwLater(ret.e); } } Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, options) { if (typeof nodeback == "function") { var adapter = successAdapter; if (options !== undefined && Object(options).spread) { adapter = spreadAdapter; } this._then( adapter, errorAdapter, undefined, this, nodeback ); } return this; }; }; },{"./util":36}],22:[function(_dereq_,module,exports){ "use strict"; module.exports = function() { var makeSelfResolutionError = function () { return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var reflectHandler = function() { return new Promise.PromiseInspection(this._target()); }; var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; function Proxyable() {} var UNDEFINED_BINDING = {}; var util = _dereq_("./util"); var getDomain; if (util.isNode) { getDomain = function() { var ret = process.domain; if (ret === undefined) ret = null; return ret; }; } else { getDomain = function() { return null; }; } util.notEnumerableProp(Promise, "_getDomain", getDomain); var es5 = _dereq_("./es5"); var Async = _dereq_("./async"); var async = new Async(); es5.defineProperty(Promise, "_async", {value: async}); var errors = _dereq_("./errors"); var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; var CancellationError = Promise.CancellationError = errors.CancellationError; Promise.TimeoutError = errors.TimeoutError; Promise.OperationalError = errors.OperationalError; Promise.RejectionError = errors.OperationalError; Promise.AggregateError = errors.AggregateError; var INTERNAL = function(){}; var APPLY = {}; var NEXT_FILTER = {}; var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); var PromiseArray = _dereq_("./promise_array")(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable); var Context = _dereq_("./context")(Promise); /*jshint unused:false*/ var createContext = Context.create; var debug = _dereq_("./debuggability")(Promise, Context); var CapturedTrace = debug.CapturedTrace; var PassThroughHandlerContext = _dereq_("./finally")(Promise, tryConvertToPromise); var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); var nodebackForPromise = _dereq_("./nodeback"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; function check(self, executor) { if (typeof executor !== "function") { throw new TypeError("expecting a function but got " + util.classString(executor)); } if (self.constructor !== Promise) { throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } } function Promise(executor) { this._bitField = 0; this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; if (executor !== INTERNAL) { check(this, executor); this._resolveFromExecutor(executor); } this._promiseCreated(); this._fireEvent("promiseCreated", this); } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { var len = arguments.length; if (len > 1) { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (util.isObject(item)) { catchInstances[j++] = item; } else { return apiRejection("expecting an object but got " + util.classString(item)); } } catchInstances.length = j; fn = arguments[i]; return this.then(undefined, catchFilter(catchInstances, fn, this)); } return this.then(undefined, fn); }; Promise.prototype.reflect = function () { return this._then(reflectHandler, reflectHandler, undefined, this, undefined); }; Promise.prototype.then = function (didFulfill, didReject) { if (debug.warnings() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill); if (arguments.length > 1) { msg += ", " + util.classString(didReject); } this._warn(msg); } return this._then(didFulfill, didReject, undefined, undefined, undefined); }; Promise.prototype.done = function (didFulfill, didReject) { var promise = this._then(didFulfill, didReject, undefined, undefined, undefined); promise._setIsFinal(); }; Promise.prototype.spread = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } return this.all()._then(fn, undefined, undefined, APPLY, undefined); }; Promise.prototype.toJSON = function () { var ret = { isFulfilled: false, isRejected: false, fulfillmentValue: undefined, rejectionReason: undefined }; if (this.isFulfilled()) { ret.fulfillmentValue = this.value(); ret.isFulfilled = true; } else if (this.isRejected()) { ret.rejectionReason = this.reason(); ret.isRejected = true; } return ret; }; Promise.prototype.all = function () { if (arguments.length > 0) { this._warn(".all() was passed arguments but it does not take any"); } return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util.originatesFromRejection, fn); }; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = Promise.fromCallback = function(fn) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false; var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); if (result === errorObj) { ret._rejectCallback(result.e, true); } if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._setFulfilled(); ret._rejectionHandler0 = obj; } return ret; }; Promise.resolve = Promise.fulfilled = Promise.cast; Promise.reject = Promise.rejected = function (reason) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._rejectCallback(reason, true); return ret; }; Promise.setScheduler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } var prev = async._schedule; async._schedule = fn; return prev; }; Promise.prototype._then = function ( didFulfill, didReject, _, receiver, internalData ) { var haveInternalData = internalData !== undefined; var promise = haveInternalData ? internalData : new Promise(INTERNAL); var target = this._target(); var bitField = target._bitField; if (!haveInternalData) { promise._propagateFrom(this, 3); promise._captureStackTrace(); if (receiver === undefined && ((this._bitField & 2097152) !== 0)) { if (!((bitField & 50397184) === 0)) { receiver = this._boundValue(); } else { receiver = target === this ? undefined : this._boundTo; } } this._fireEvent("promiseChained", this, promise); } var domain = getDomain(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { value = target._rejectionHandler0; handler = didFulfill; } else if (((bitField & 16777216) !== 0)) { value = target._fulfillmentHandler0; handler = didReject; target._unsetRejectionIsUnhandled(); } else { settler = target._settlePromiseLateCancellationObserver; value = new CancellationError("late cancellation observer"); target._attachExtraTrace(value); handler = didReject; } async.invoke(settler, target, { handler: domain === null ? handler : (typeof handler === "function" && domain.bind(handler)), promise: promise, receiver: receiver, value: value }); } else { target._addCallbacks(didFulfill, didReject, promise, receiver, domain); } return promise; }; Promise.prototype._length = function () { return this._bitField & 65535; }; Promise.prototype._isFateSealed = function () { return (this._bitField & 117506048) !== 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & 67108864) === 67108864; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & -65536) | (len & 65535); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 33554432; this._fireEvent("promiseFulfilled", this); }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | 16777216; this._fireEvent("promiseRejected", this); }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 67108864; this._fireEvent("promiseResolved", this); }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 4194304; }; Promise.prototype._isFinal = function () { return (this._bitField & 4194304) > 0; }; Promise.prototype._unsetCancelled = function() { this._bitField = this._bitField & (~65536); }; Promise.prototype._setCancelled = function() { this._bitField = this._bitField | 65536; this._fireEvent("promiseCancelled", this); }; Promise.prototype._setAsyncGuaranteed = function() { this._bitField = this._bitField | 134217728; }; Promise.prototype._receiverAt = function (index) { var ret = index === 0 ? this._receiver0 : this[ index * 4 - 4 + 3]; if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { return this[ index * 4 - 4 + 2]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { return this[ index * 4 - 4 + 0]; }; Promise.prototype._rejectionHandlerAt = function (index) { return this[ index * 4 - 4 + 1]; }; Promise.prototype._boundValue = function() {}; Promise.prototype._migrateCallback0 = function (follower) { var bitField = follower._bitField; var fulfill = follower._fulfillmentHandler0; var reject = follower._rejectionHandler0; var promise = follower._promise0; var receiver = follower._receiverAt(0); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._migrateCallbackAt = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, promise, receiver, domain ) { var index = this._length(); if (index >= 65535 - 4) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { this._fulfillmentHandler0 = domain === null ? fulfill : domain.bind(fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : domain.bind(reject); } } else { var base = index * 4 - 4; this[base + 2] = promise; this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = domain === null ? fulfill : domain.bind(fulfill); } if (typeof reject === "function") { this[base + 1] = domain === null ? reject : domain.bind(reject); } } this._setLength(index + 1); return index; }; Promise.prototype._proxy = function (proxyable, arg) { this._addCallbacks(undefined, undefined, arg, proxyable, null); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (((this._bitField & 117506048) !== 0)) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); if (shouldBind) this._propagateFrom(maybePromise, 2); var promise = maybePromise._target(); if (promise === this) { this._reject(makeSelfResolutionError()); return; } var bitField = promise._bitField; if (((bitField & 50397184) === 0)) { var len = this._length(); if (len > 0) promise._migrateCallback0(this); for (var i = 1; i < len; ++i) { promise._migrateCallbackAt(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { this._reject(promise._reason()); } else { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); this._reject(reason); } }; Promise.prototype._rejectCallback = function(reason, synchronous, ignoreNonErrorWarnings) { var trace = util.ensureErrorObject(reason); var hasStack = trace === reason; if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { var message = "a promise was rejected with a non-error: " + util.classString(reason); this._warn(message, true); } this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason); }; Promise.prototype._resolveFromExecutor = function (executor) { var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = this._execute(executor, function(value) { promise._resolveCallback(value); }, function (reason) { promise._rejectCallback(reason, synchronous); }); synchronous = false; this._popContext(); if (r !== undefined) { promise._rejectCallback(r, true); } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { var bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; promise._pushContext(); var x; if (receiver === APPLY) { if (!value || typeof value.length !== "number") { x = errorObj; x.e = new TypeError("cannot .spread() a non-array: " + util.classString(value)); } else { x = tryCatch(handler).apply(this._boundValue(), value); } } else { x = tryCatch(handler).call(receiver, value); } var promiseCreated = promise._popContext(); bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; if (x === NEXT_FILTER) { promise._reject(value); } else if (x === errorObj) { promise._rejectCallback(x.e, false); } else { debug.checkForgottenReturns(x, promiseCreated, "", promise, this); promise._resolveCallback(x); } }; Promise.prototype._target = function() { var ret = this; while (ret._isFollowing()) ret = ret._followee(); return ret; }; Promise.prototype._followee = function() { return this._rejectionHandler0; }; Promise.prototype._setFollowee = function(promise) { this._rejectionHandler0 = promise; }; Promise.prototype._settlePromise = function(promise, handler, receiver, value) { var isPromise = promise instanceof Promise; var bitField = this._bitField; var asyncGuaranteed = ((bitField & 134217728) !== 0); if (((bitField & 65536) !== 0)) { if (isPromise) promise._invokeInternalOnCancel(); if (receiver instanceof PassThroughHandlerContext && receiver.isFinallyHandler()) { receiver.cancelPromise = promise; if (tryCatch(handler).call(receiver, value) === errorObj) { promise._reject(errorObj.e); } } else if (handler === reflectHandler) { promise._fulfill(reflectHandler.call(receiver)); } else if (receiver instanceof Proxyable) { receiver._promiseCancelled(promise); } else if (isPromise || promise instanceof PromiseArray) { promise._cancel(); } else { receiver.cancel(); } } else if (typeof handler === "function") { if (!isPromise) { handler.call(receiver, value, promise); } else { if (asyncGuaranteed) promise._setAsyncGuaranteed(); this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof Proxyable) { if (!receiver._isResolved()) { if (((bitField & 33554432) !== 0)) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (asyncGuaranteed) promise._setAsyncGuaranteed(); if (((bitField & 33554432) !== 0)) { promise._fulfill(value); } else { promise._reject(value); } } }; Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { var handler = ctx.handler; var promise = ctx.promise; var receiver = ctx.receiver; var value = ctx.value; if (typeof handler === "function") { if (!(promise instanceof Promise)) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (promise instanceof Promise) { promise._reject(value); } }; Promise.prototype._settlePromiseCtx = function(ctx) { this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); }; Promise.prototype._settlePromise0 = function(handler, value, bitField) { var promise = this._promise0; var receiver = this._receiverAt(0); this._promise0 = undefined; this._receiver0 = undefined; this._settlePromise(promise, handler, receiver, value); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { var base = index * 4 - 4; this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined; }; Promise.prototype._fulfill = function (value) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._reject(err); } this._setFulfilled(); this._rejectionHandler0 = value; if ((bitField & 65535) > 0) { if (((bitField & 134217728) !== 0)) { this._settlePromises(); } else { async.settlePromises(this); } } }; Promise.prototype._reject = function (reason) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; this._setRejected(); this._fulfillmentHandler0 = reason; if (this._isFinal()) { return async.fatalError(reason, util.isNode); } if ((bitField & 65535) > 0) { async.settlePromises(this); } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._fulfillPromises = function (len, value) { for (var i = 1; i < len; i++) { var handler = this._fulfillmentHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, value); } }; Promise.prototype._rejectPromises = function (len, reason) { for (var i = 1; i < len; i++) { var handler = this._rejectionHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, reason); } }; Promise.prototype._settlePromises = function () { var bitField = this._bitField; var len = (bitField & 65535); if (len > 0) { if (((bitField & 16842752) !== 0)) { var reason = this._fulfillmentHandler0; this._settlePromise0(this._rejectionHandler0, reason, bitField); this._rejectPromises(len, reason); } else { var value = this._rejectionHandler0; this._settlePromise0(this._fulfillmentHandler0, value, bitField); this._fulfillPromises(len, value); } this._setLength(0); } this._clearCancellationData(); }; Promise.prototype._settledValue = function() { var bitField = this._bitField; if (((bitField & 33554432) !== 0)) { return this._rejectionHandler0; } else if (((bitField & 16777216) !== 0)) { return this._fulfillmentHandler0; } }; function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} Promise.defer = Promise.pending = function() { debug.deprecated("Promise.defer", "new Promise"); var promise = new Promise(INTERNAL); return { promise: promise, resolve: deferResolve, reject: deferReject }; }; util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); _dereq_("./direct_resolve")(Promise); _dereq_("./synchronous_inspection")(Promise); _dereq_("./join")( Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug); Promise.Promise = Promise; _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); _dereq_('./timers.js')(Promise, INTERNAL, debug); _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); _dereq_('./nodeify.js')(Promise); _dereq_('./call_get.js')(Promise); _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./settle.js')(Promise, PromiseArray, debug); _dereq_('./some.js')(Promise, PromiseArray, apiRejection); _dereq_('./promisify.js')(Promise, INTERNAL); _dereq_('./any.js')(Promise); _dereq_('./each.js')(Promise, INTERNAL); _dereq_('./filter.js')(Promise, INTERNAL); util.toFastProperties(Promise); util.toFastProperties(Promise.prototype); function fillTypes(value) { var p = new Promise(INTERNAL); p._fulfillmentHandler0 = value; p._rejectionHandler0 = value; p._promise0 = value; p._receiver0 = value; } // Complete slack tracking, opt out of field-type tracking and // stabilize map fillTypes({a: 1}); fillTypes({b: 2}); fillTypes({c: 3}); fillTypes(1); fillTypes(function(){}); fillTypes(undefined); fillTypes(false); fillTypes(new Promise(INTERNAL)); debug.setBounds(Async.firstLineError, util.lastLineError); return Promise; }; },{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable) { var util = _dereq_("./util"); var isArray = util.isArray; function toResolutionValue(val) { switch(val) { case -2: return []; case -3: return {}; } } function PromiseArray(values) { var promise = this._promise = new Promise(INTERNAL); if (values instanceof Promise) { promise._propagateFrom(values, 3); } promise._setOnCancel(this); this._values = values; this._length = 0; this._totalResolved = 0; this._init(undefined, -2); } util.inherits(PromiseArray, Proxyable); PromiseArray.prototype.length = function () { return this._length; }; PromiseArray.prototype.promise = function () { return this._promise; }; PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { var values = tryConvertToPromise(this._values, this._promise); if (values instanceof Promise) { values = values._target(); var bitField = values._bitField; ; this._values = values; if (((bitField & 50397184) === 0)) { this._promise._setAsyncGuaranteed(); return values._then( init, this._reject, undefined, this, resolveValueIfEmpty ); } else if (((bitField & 33554432) !== 0)) { values = values._value(); } else if (((bitField & 16777216) !== 0)) { return this._reject(values._reason()); } else { return this._cancel(); } } values = util.asArray(values); if (values === null) { var err = apiRejection( "expecting an array or an iterable object but got " + util.classString(values)).reason(); this._promise._rejectCallback(err, false); return; } if (values.length === 0) { if (resolveValueIfEmpty === -5) { this._resolveEmptyArray(); } else { this._resolve(toResolutionValue(resolveValueIfEmpty)); } return; } this._iterate(values); }; PromiseArray.prototype._iterate = function(values) { var len = this.getActualLength(values.length); this._length = len; this._values = this.shouldCopyValues() ? new Array(len) : this._values; var result = this._promise; var isResolved = false; var bitField = null; for (var i = 0; i < len; ++i) { var maybePromise = tryConvertToPromise(values[i], result); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); bitField = maybePromise._bitField; } else { bitField = null; } if (isResolved) { if (bitField !== null) { maybePromise.suppressUnhandledRejections(); } } else if (bitField !== null) { if (((bitField & 50397184) === 0)) { maybePromise._proxy(this, i); this._values[i] = maybePromise; } else if (((bitField & 33554432) !== 0)) { isResolved = this._promiseFulfilled(maybePromise._value(), i); } else if (((bitField & 16777216) !== 0)) { isResolved = this._promiseRejected(maybePromise._reason(), i); } else { isResolved = this._promiseCancelled(i); } } else { isResolved = this._promiseFulfilled(maybePromise, i); } } if (!isResolved) result._setAsyncGuaranteed(); }; PromiseArray.prototype._isResolved = function () { return this._values === null; }; PromiseArray.prototype._resolve = function (value) { this._values = null; this._promise._fulfill(value); }; PromiseArray.prototype._cancel = function() { if (this._isResolved() || !this._promise.isCancellable()) return; this._values = null; this._promise._cancel(); }; PromiseArray.prototype._reject = function (reason) { this._values = null; this._promise._rejectCallback(reason, false); }; PromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; PromiseArray.prototype._promiseCancelled = function() { this._cancel(); return true; }; PromiseArray.prototype._promiseRejected = function (reason) { this._totalResolved++; this._reject(reason); return true; }; PromiseArray.prototype._resultCancelled = function() { if (this._isResolved()) return; var values = this._values; this._cancel(); if (values instanceof Promise) { values.cancel(); } else { for (var i = 0; i < values.length; ++i) { if (values[i] instanceof Promise) { values[i].cancel(); } } } }; PromiseArray.prototype.shouldCopyValues = function () { return true; }; PromiseArray.prototype.getActualLength = function (len) { return len; }; return PromiseArray; }; },{"./util":36}],24:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var THIS = {}; var util = _dereq_("./util"); var nodebackForPromise = _dereq_("./nodeback"); var withAppended = util.withAppended; var maybeWrapAsError = util.maybeWrapAsError; var canEvaluate = util.canEvaluate; var TypeError = _dereq_("./errors").TypeError; var defaultSuffix = "Async"; var defaultPromisified = {__isPromisified__: true}; var noCopyProps = [ "arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__" ]; var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); var defaultFilter = function(name) { return util.isIdentifier(name) && name.charAt(0) !== "_" && name !== "constructor"; }; function propsFilter(key) { return !noCopyPropsPattern.test(key); } function isPromisified(fn) { try { return fn.__isPromisified__ === true; } catch (e) { return false; } } function hasPromisified(obj, key, suffix) { var val = util.getDataPropertyOrDefault(obj, key + suffix, defaultPromisified); return val ? isPromisified(val) : false; } function checkValid(ret, suffix, suffixRegexp) { for (var i = 0; i < ret.length; i += 2) { var key = ret[i]; if (suffixRegexp.test(key)) { var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); for (var j = 0; j < ret.length; j += 2) { if (ret[j] === keyWithoutAsyncSuffix) { throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" .replace("%s", suffix)); } } } } } function promisifiableMethods(obj, suffix, suffixRegexp, filter) { var keys = util.inheritedDataKeys(obj); var ret = []; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var value = obj[key]; var passesDefaultFilter = filter === defaultFilter ? true : defaultFilter(key, value, obj); if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj, key, suffix) && filter(key, value, obj, passesDefaultFilter)) { ret.push(key, value); } } checkValid(ret, suffix, suffixRegexp); return ret; } var escapeIdentRegex = function(str) { return str.replace(/([$])/, "\\$"); }; var makeNodePromisifiedEval; if (false) { var switchCaseArgumentOrder = function(likelyArgumentCount) { var ret = [likelyArgumentCount]; var min = Math.max(0, likelyArgumentCount - 1 - 3); for(var i = likelyArgumentCount - 1; i >= min; --i) { ret.push(i); } for(var i = likelyArgumentCount + 1; i <= 3; ++i) { ret.push(i); } return ret; }; var argumentSequence = function(argumentCount) { return util.filledRange(argumentCount, "_arg", ""); }; var parameterDeclaration = function(parameterCount) { return util.filledRange( Math.max(parameterCount, 3), "_arg", ""); }; var parameterCount = function(fn) { if (typeof fn.length === "number") { return Math.max(Math.min(fn.length, 1023 + 1), 0); } return 0; }; makeNodePromisifiedEval = function(callback, receiver, originalName, fn, _, multiArgs) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); var shouldProxyThis = typeof callback === "string" || receiver === THIS; function generateCallForArgumentCount(count) { var args = argumentSequence(count).join(", "); var comma = count > 0 ? ", " : ""; var ret; if (shouldProxyThis) { ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; } else { ret = receiver === undefined ? "ret = callback({{args}}, nodeback); break;\n" : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; } return ret.replace("{{args}}", args).replace(", ", comma); } function generateArgumentSwitchCase() { var ret = ""; for (var i = 0; i < argumentOrder.length; ++i) { ret += "case " + argumentOrder[i] +":" + generateCallForArgumentCount(argumentOrder[i]); } ret += " \n\ default: \n\ var args = new Array(len + 1); \n\ var i = 0; \n\ for (var i = 0; i < len; ++i) { \n\ args[i] = arguments[i]; \n\ } \n\ args[i] = nodeback; \n\ [CodeForCall] \n\ break; \n\ ".replace("[CodeForCall]", (shouldProxyThis ? "ret = callback.apply(this, args);\n" : "ret = callback.apply(receiver, args);\n")); return ret; } var getFunctionCode = typeof callback === "string" ? ("this != null ? this['"+callback+"'] : fn") : "fn"; var body = "'use strict'; \n\ var ret = function (Parameters) { \n\ 'use strict'; \n\ var len = arguments.length; \n\ var promise = new Promise(INTERNAL); \n\ promise._captureStackTrace(); \n\ var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ var ret; \n\ var callback = tryCatch([GetFunctionCode]); \n\ switch(len) { \n\ [CodeForSwitchCase] \n\ } \n\ if (ret === errorObj) { \n\ promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ } \n\ if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ return promise; \n\ }; \n\ notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) .replace("[GetFunctionCode]", getFunctionCode); body = body.replace("Parameters", parameterDeclaration(newParameterCount)); return new Function("Promise", "fn", "receiver", "withAppended", "maybeWrapAsError", "nodebackForPromise", "tryCatch", "errorObj", "notEnumerableProp", "INTERNAL", body)( Promise, fn, receiver, withAppended, maybeWrapAsError, nodebackForPromise, util.tryCatch, util.errorObj, util.notEnumerableProp, INTERNAL); }; } function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { var defaultThis = (function() {return this;})(); var method = callback; if (typeof method === "string") { callback = fn; } function promisified() { var _receiver = receiver; if (receiver === THIS) _receiver = this; var promise = new Promise(INTERNAL); promise._captureStackTrace(); var cb = typeof method === "string" && this !== defaultThis ? this[method] : callback; var fn = nodebackForPromise(promise, multiArgs); try { cb.apply(_receiver, withAppended(arguments, fn)); } catch(e) { promise._rejectCallback(maybeWrapAsError(e), true, true); } if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); return promise; } util.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter); for (var i = 0, len = methods.length; i < len; i+= 2) { var key = methods[i]; var fn = methods[i+1]; var promisifiedKey = key + suffix; if (promisifier === makeNodePromisified) { obj[promisifiedKey] = makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); } else { var promisified = promisifier(fn, function() { return makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); }); util.notEnumerableProp(promisified, "__isPromisified__", true); obj[promisifiedKey] = promisified; } } util.toFastProperties(obj); return obj; } function promisify(callback, receiver, multiArgs) { return makeNodePromisified(callback, receiver, undefined, callback, null, multiArgs); } Promise.promisify = function (fn, options) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } if (isPromisified(fn)) { return fn; } options = Object(options); var receiver = options.context === undefined ? THIS : options.context; var multiArgs = !!options.multiArgs; var ret = promisify(fn, receiver, multiArgs); util.copyDescriptors(fn, ret, propsFilter); return ret; }; Promise.promisifyAll = function (target, options) { if (typeof target !== "function" && typeof target !== "object") { throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } options = Object(options); var multiArgs = !!options.multiArgs; var suffix = options.suffix; if (typeof suffix !== "string") suffix = defaultSuffix; var filter = options.filter; if (typeof filter !== "function") filter = defaultFilter; var promisifier = options.promisifier; if (typeof promisifier !== "function") promisifier = makeNodePromisified; if (!util.isIdentifier(suffix)) { throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var keys = util.inheritedDataKeys(target); for (var i = 0; i < keys.length; ++i) { var value = target[keys[i]]; if (keys[i] !== "constructor" && util.isClass(value)) { promisifyAll(value.prototype, suffix, filter, promisifier, multiArgs); promisifyAll(value, suffix, filter, promisifier, multiArgs); } } return promisifyAll(target, suffix, filter, promisifier, multiArgs); }; }; },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, PromiseArray, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var isObject = util.isObject; var es5 = _dereq_("./es5"); var Es6Map; if (typeof Map === "function") Es6Map = Map; var mapToEntries = (function() { var index = 0; var size = 0; function extractEntry(value, key) { this[index] = value; this[index + size] = key; index++; } return function mapToEntries(map) { size = map.size; index = 0; var ret = new Array(map.size * 2); map.forEach(extractEntry, ret); return ret; }; })(); var entriesToMap = function(entries) { var ret = new Es6Map(); var length = entries.length / 2 | 0; for (var i = 0; i < length; ++i) { var key = entries[length + i]; var value = entries[i]; ret.set(key, value); } return ret; }; function PropertiesPromiseArray(obj) { var isMap = false; var entries; if (Es6Map !== undefined && obj instanceof Es6Map) { entries = mapToEntries(obj); isMap = true; } else { var keys = es5.keys(obj); var len = keys.length; entries = new Array(len * 2); for (var i = 0; i < len; ++i) { var key = keys[i]; entries[i] = obj[key]; entries[i + len] = key; } } this.constructor$(entries); this._isMap = isMap; this._init$(undefined, -3); } util.inherits(PropertiesPromiseArray, PromiseArray); PropertiesPromiseArray.prototype._init = function () {}; PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { var val; if (this._isMap) { val = entriesToMap(this._values); } else { val = {}; var keyOffset = this.length(); for (var i = 0, len = this.length(); i < len; ++i) { val[this._values[i + keyOffset]] = this._values[i]; } } this._resolve(val); return true; } return false; }; PropertiesPromiseArray.prototype.shouldCopyValues = function () { return false; }; PropertiesPromiseArray.prototype.getActualLength = function (len) { return len >> 1; }; function props(promises) { var ret; var castValue = tryConvertToPromise(promises); if (!isObject(castValue)) { return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } else if (castValue instanceof Promise) { ret = castValue._then( Promise.props, undefined, undefined, undefined, undefined); } else { ret = new PropertiesPromiseArray(castValue).promise(); } if (castValue instanceof Promise) { ret._propagateFrom(castValue, 2); } return ret; } Promise.prototype.props = function () { return props(this); }; Promise.props = function (promises) { return props(promises); }; }; },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ "use strict"; function arrayMove(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; src[j + srcIndex] = void 0; } } function Queue(capacity) { this._capacity = capacity; this._length = 0; this._front = 0; } Queue.prototype._willBeOverCapacity = function (size) { return this._capacity < size; }; Queue.prototype._pushOne = function (arg) { var length = this.length(); this._checkCapacity(length + 1); var i = (this._front + length) & (this._capacity - 1); this[i] = arg; this._length = length + 1; }; Queue.prototype._unshiftOne = function(value) { var capacity = this._capacity; this._checkCapacity(this.length() + 1); var front = this._front; var i = (((( front - 1 ) & ( capacity - 1) ) ^ capacity ) - capacity ); this[i] = value; this._front = i; this._length = this.length() + 1; }; Queue.prototype.unshift = function(fn, receiver, arg) { this._unshiftOne(arg); this._unshiftOne(receiver); this._unshiftOne(fn); }; Queue.prototype.push = function (fn, receiver, arg) { var length = this.length() + 3; if (this._willBeOverCapacity(length)) { this._pushOne(fn); this._pushOne(receiver); this._pushOne(arg); return; } var j = this._front + length - 3; this._checkCapacity(length); var wrapMask = this._capacity - 1; this[(j + 0) & wrapMask] = fn; this[(j + 1) & wrapMask] = receiver; this[(j + 2) & wrapMask] = arg; this._length = length; }; Queue.prototype.shift = function () { var front = this._front, ret = this[front]; this[front] = undefined; this._front = (front + 1) & (this._capacity - 1); this._length--; return ret; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._resizeTo(this._capacity << 1); } }; Queue.prototype._resizeTo = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var front = this._front; var length = this._length; var moveItemsCount = (front + length) & (oldCapacity - 1); arrayMove(this, 0, this, oldCapacity, moveItemsCount); }; module.exports = Queue; },{}],27:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, INTERNAL, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var raceLater = function (promise) { return promise.then(function(array) { return race(array, promise); }); }; function race(promises, parent) { var maybePromise = tryConvertToPromise(promises); if (maybePromise instanceof Promise) { return raceLater(maybePromise); } else { promises = util.asArray(promises); if (promises === null) return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); } var ret = new Promise(INTERNAL); if (parent !== undefined) { ret._propagateFrom(parent, 3); } var fulfill = ret._fulfill; var reject = ret._reject; for (var i = 0, len = promises.length; i < len; ++i) { var val = promises[i]; if (val === undefined && !(i in promises)) { continue; } Promise.cast(val)._then(fulfill, reject, undefined, ret, null); } return ret; } Promise.race = function (promises) { return race(promises, undefined); }; Promise.prototype.race = function () { return race(this, undefined); }; }; },{"./util":36}],28:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; function ReductionPromiseArray(promises, fn, initialValue, _each) { this.constructor$(promises); var domain = getDomain(); this._fn = domain === null ? fn : domain.bind(fn); if (initialValue !== undefined) { initialValue = Promise.resolve(initialValue); initialValue._attachCancellationCallback(this); } this._initialValue = initialValue; this._currentCancellable = null; this._eachValues = _each === INTERNAL ? [] : undefined; this._promise._captureStackTrace(); this._init$(undefined, -5); } util.inherits(ReductionPromiseArray, PromiseArray); ReductionPromiseArray.prototype._gotAccum = function(accum) { if (this._eachValues !== undefined && accum !== INTERNAL) { this._eachValues.push(accum); } }; ReductionPromiseArray.prototype._eachComplete = function(value) { this._eachValues.push(value); return this._eachValues; }; ReductionPromiseArray.prototype._init = function() {}; ReductionPromiseArray.prototype._resolveEmptyArray = function() { this._resolve(this._eachValues !== undefined ? this._eachValues : this._initialValue); }; ReductionPromiseArray.prototype.shouldCopyValues = function () { return false; }; ReductionPromiseArray.prototype._resolve = function(value) { this._promise._resolveCallback(value); this._values = null; }; ReductionPromiseArray.prototype._resultCancelled = function(sender) { if (sender === this._initialValue) return this._cancel(); if (this._isResolved()) return; this._resultCancelled$(); if (this._currentCancellable instanceof Promise) { this._currentCancellable.cancel(); } if (this._initialValue instanceof Promise) { this._initialValue.cancel(); } }; ReductionPromiseArray.prototype._iterate = function (values) { this._values = values; var value; var i; var length = values.length; if (this._initialValue !== undefined) { value = this._initialValue; i = 0; } else { value = Promise.resolve(values[0]); i = 1; } this._currentCancellable = value; if (!value.isRejected()) { for (; i < length; ++i) { var ctx = { accum: null, value: values[i], index: i, length: length, array: this }; value = value._then(gotAccum, undefined, undefined, ctx, undefined); } } if (this._eachValues !== undefined) { value = value ._then(this._eachComplete, undefined, undefined, this, undefined); } value._then(completed, completed, undefined, value, this); }; Promise.prototype.reduce = function (fn, initialValue) { return reduce(this, fn, initialValue, null); }; Promise.reduce = function (promises, fn, initialValue, _each) { return reduce(promises, fn, initialValue, _each); }; function completed(valueOrReason, array) { if (this.isFulfilled()) { array._resolve(valueOrReason); } else { array._reject(valueOrReason); } } function reduce(promises, fn, initialValue, _each) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var array = new ReductionPromiseArray(promises, fn, initialValue, _each); return array.promise(); } function gotAccum(accum) { this.accum = accum; this.array._gotAccum(accum); var value = tryConvertToPromise(this.value, this.array._promise); if (value instanceof Promise) { this.array._currentCancellable = value; return value._then(gotValue, undefined, undefined, this, undefined); } else { return gotValue.call(this, value); } } function gotValue(value) { var array = this.array; var promise = array._promise; var fn = tryCatch(array._fn); promise._pushContext(); var ret; if (array._eachValues !== undefined) { ret = fn.call(promise._boundValue(), value, this.index, this.length); } else { ret = fn.call(promise._boundValue(), this.accum, value, this.index, this.length); } if (ret instanceof Promise) { array._currentCancellable = ret; } var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", promise ); return ret; } }; },{"./util":36}],29:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var schedule; var noAsyncScheduler = function() { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; if (util.isNode && typeof MutationObserver === "undefined") { var GlobalSetImmediate = global.setImmediate; var ProcessNextTick = process.nextTick; schedule = util.isRecentNode ? function(fn) { GlobalSetImmediate.call(global, fn); } : function(fn) { ProcessNextTick.call(process, fn); }; } else if ((typeof MutationObserver !== "undefined") && !(typeof window !== "undefined" && window.navigator && window.navigator.standalone)) { schedule = (function() { var div = document.createElement("div"); var opts = {attributes: true}; var toggleScheduled = false; var div2 = document.createElement("div"); var o2 = new MutationObserver(function() { div.classList.toggle("foo"); toggleScheduled = false; }); o2.observe(div2, opts); var scheduleToggle = function() { if (toggleScheduled) return; toggleScheduled = true; div2.classList.toggle("foo"); }; return function schedule(fn) { var o = new MutationObserver(function() { o.disconnect(); fn(); }); o.observe(div, opts); scheduleToggle(); }; })(); } else if (typeof setImmediate !== "undefined") { schedule = function (fn) { setImmediate(fn); }; } else if (typeof setTimeout !== "undefined") { schedule = function (fn) { setTimeout(fn, 0); }; } else { schedule = noAsyncScheduler; } module.exports = schedule; },{"./util":36}],30:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, debug) { var PromiseInspection = Promise.PromiseInspection; var util = _dereq_("./util"); function SettledPromiseArray(values) { this.constructor$(values); } util.inherits(SettledPromiseArray, PromiseArray); SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { this._values[index] = inspection; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { var ret = new PromiseInspection(); ret._bitField = 33554432; ret._settledValueField = value; return this._promiseResolved(index, ret); }; SettledPromiseArray.prototype._promiseRejected = function (reason, index) { var ret = new PromiseInspection(); ret._bitField = 16777216; ret._settledValueField = reason; return this._promiseResolved(index, ret); }; Promise.settle = function (promises) { debug.deprecated(".settle()", ".reflect()"); return new SettledPromiseArray(promises).promise(); }; Promise.prototype.settle = function () { return Promise.settle(this); }; }; },{"./util":36}],31:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection) { var util = _dereq_("./util"); var RangeError = _dereq_("./errors").RangeError; var AggregateError = _dereq_("./errors").AggregateError; var isArray = util.isArray; var CANCELLATION = {}; function SomePromiseArray(values) { this.constructor$(values); this._howMany = 0; this._unwrap = false; this._initialized = false; } util.inherits(SomePromiseArray, PromiseArray); SomePromiseArray.prototype._init = function () { if (!this._initialized) { return; } if (this._howMany === 0) { this._resolve([]); return; } this._init$(undefined, -5); var isArrayResolved = isArray(this._values); if (!this._isResolved() && isArrayResolved && this._howMany > this._canPossiblyFulfill()) { this._reject(this._getRangeError(this.length())); } }; SomePromiseArray.prototype.init = function () { this._initialized = true; this._init(); }; SomePromiseArray.prototype.setUnwrap = function () { this._unwrap = true; }; SomePromiseArray.prototype.howMany = function () { return this._howMany; }; SomePromiseArray.prototype.setHowMany = function (count) { this._howMany = count; }; SomePromiseArray.prototype._promiseFulfilled = function (value) { this._addFulfilled(value); if (this._fulfilled() === this.howMany()) { this._values.length = this.howMany(); if (this.howMany() === 1 && this._unwrap) { this._resolve(this._values[0]); } else { this._resolve(this._values); } return true; } return false; }; SomePromiseArray.prototype._promiseRejected = function (reason) { this._addRejected(reason); return this._checkOutcome(); }; SomePromiseArray.prototype._promiseCancelled = function () { if (this._values instanceof Promise || this._values == null) { return this._cancel(); } this._addRejected(CANCELLATION); return this._checkOutcome(); }; SomePromiseArray.prototype._checkOutcome = function() { if (this.howMany() > this._canPossiblyFulfill()) { var e = new AggregateError(); for (var i = this.length(); i < this._values.length; ++i) { if (this._values[i] !== CANCELLATION) { e.push(this._values[i]); } } if (e.length > 0) { this._reject(e); } else { this._cancel(); } return true; } return false; }; SomePromiseArray.prototype._fulfilled = function () { return this._totalResolved; }; SomePromiseArray.prototype._rejected = function () { return this._values.length - this.length(); }; SomePromiseArray.prototype._addRejected = function (reason) { this._values.push(reason); }; SomePromiseArray.prototype._addFulfilled = function (value) { this._values[this._totalResolved++] = value; }; SomePromiseArray.prototype._canPossiblyFulfill = function () { return this.length() - this._rejected(); }; SomePromiseArray.prototype._getRangeError = function (count) { var message = "Input array must contain at least " + this._howMany + " items but contains only " + count + " items"; return new RangeError(message); }; SomePromiseArray.prototype._resolveEmptyArray = function () { this._reject(this._getRangeError(0)); }; function some(promises, howMany) { if ((howMany | 0) !== howMany || howMany < 0) { return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(howMany); ret.init(); return promise; } Promise.some = function (promises, howMany) { return some(promises, howMany); }; Promise.prototype.some = function (howMany) { return some(this, howMany); }; Promise._SomePromiseArray = SomePromiseArray; }; },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function PromiseInspection(promise) { if (promise !== undefined) { promise = promise._target(); this._bitField = promise._bitField; this._settledValueField = promise._isFateSealed() ? promise._settledValue() : undefined; } else { this._bitField = 0; this._settledValueField = undefined; } } PromiseInspection.prototype._settledValue = function() { return this._settledValueField; }; var value = PromiseInspection.prototype.value = function () { if (!this.isFulfilled()) { throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var reason = PromiseInspection.prototype.error = PromiseInspection.prototype.reason = function () { if (!this.isRejected()) { throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { return (this._bitField & 33554432) !== 0; }; var isRejected = PromiseInspection.prototype.isRejected = function () { return (this._bitField & 16777216) !== 0; }; var isPending = PromiseInspection.prototype.isPending = function () { return (this._bitField & 50397184) === 0; }; var isResolved = PromiseInspection.prototype.isResolved = function () { return (this._bitField & 50331648) !== 0; }; PromiseInspection.prototype.isCancelled = Promise.prototype._isCancelled = function() { return (this._bitField & 65536) === 65536; }; Promise.prototype.isCancelled = function() { return this._target()._isCancelled(); }; Promise.prototype.isPending = function() { return isPending.call(this._target()); }; Promise.prototype.isRejected = function() { return isRejected.call(this._target()); }; Promise.prototype.isFulfilled = function() { return isFulfilled.call(this._target()); }; Promise.prototype.isResolved = function() { return isResolved.call(this._target()); }; Promise.prototype.value = function() { return value.call(this._target()); }; Promise.prototype.reason = function() { var target = this._target(); target._unsetRejectionIsUnhandled(); return reason.call(target); }; Promise.prototype._value = function() { return this._settledValue(); }; Promise.prototype._reason = function() { this._unsetRejectionIsUnhandled(); return this._settledValue(); }; Promise.PromiseInspection = PromiseInspection; }; },{}],33:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var util = _dereq_("./util"); var errorObj = util.errorObj; var isObject = util.isObject; function tryConvertToPromise(obj, context) { if (isObject(obj)) { if (obj instanceof Promise) return obj; var then = getThen(obj); if (then === errorObj) { if (context) context._pushContext(); var ret = Promise.reject(then.e); if (context) context._popContext(); return ret; } else if (typeof then === "function") { if (isAnyBluebirdPromise(obj)) { var ret = new Promise(INTERNAL); obj._then( ret._fulfill, ret._reject, undefined, ret, null ); return ret; } return doThenable(obj, then, context); } } return obj; } function doGetThen(obj) { return obj.then; } function getThen(obj) { try { return doGetThen(obj); } catch (e) { errorObj.e = e; return errorObj; } } var hasProp = {}.hasOwnProperty; function isAnyBluebirdPromise(obj) { return hasProp.call(obj, "_promise0"); } function doThenable(x, then, context) { var promise = new Promise(INTERNAL); var ret = promise; if (context) context._pushContext(); promise._captureStackTrace(); if (context) context._popContext(); var synchronous = true; var result = util.tryCatch(then).call(x, resolve, reject); synchronous = false; if (promise && result === errorObj) { promise._rejectCallback(result.e, true, true); promise = null; } function resolve(value) { if (!promise) return; promise._resolveCallback(value); promise = null; } function reject(reason) { if (!promise) return; promise._rejectCallback(reason, synchronous, true); promise = null; } return ret; } return tryConvertToPromise; }; },{"./util":36}],34:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, debug) { var util = _dereq_("./util"); var TimeoutError = Promise.TimeoutError; function HandleWrapper(handle) { this.handle = handle; } HandleWrapper.prototype._resultCancelled = function() { clearTimeout(this.handle); }; var afterValue = function(value) { return delay(+this).thenReturn(value); }; var delay = Promise.delay = function (ms, value) { var ret; var handle; if (value !== undefined) { ret = Promise.resolve(value) ._then(afterValue, null, null, ms, undefined); if (debug.cancellation() && value instanceof Promise) { ret._setOnCancel(value); } } else { ret = new Promise(INTERNAL); handle = setTimeout(function() { ret._fulfill(); }, +ms); if (debug.cancellation()) { ret._setOnCancel(new HandleWrapper(handle)); } } ret._setAsyncGuaranteed(); return ret; }; Promise.prototype.delay = function (ms) { return delay(ms, this); }; var afterTimeout = function (promise, message, parent) { var err; if (typeof message !== "string") { if (message instanceof Error) { err = message; } else { err = new TimeoutError("operation timed out"); } } else { err = new TimeoutError(message); } util.markAsOriginatingFromRejection(err); promise._attachExtraTrace(err); promise._reject(err); if (parent != null) { parent.cancel(); } }; function successClear(value) { clearTimeout(this.handle); return value; } function failureClear(reason) { clearTimeout(this.handle); throw reason; } Promise.prototype.timeout = function (ms, message) { ms = +ms; var ret, parent; var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { if (ret.isPending()) { afterTimeout(ret, message, parent); } }, ms)); if (debug.cancellation()) { parent = this.then(); ret = parent._then(successClear, failureClear, undefined, handleWrapper, undefined); ret._setOnCancel(handleWrapper); } else { ret = this._then(successClear, failureClear, undefined, handleWrapper, undefined); } return ret; }; }; },{"./util":36}],35:[function(_dereq_,module,exports){ "use strict"; module.exports = function (Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug) { var util = _dereq_("./util"); var TypeError = _dereq_("./errors").TypeError; var inherits = _dereq_("./util").inherits; var errorObj = util.errorObj; var tryCatch = util.tryCatch; function thrower(e) { setTimeout(function(){throw e;}, 0); } function castPreservingDisposable(thenable) { var maybePromise = tryConvertToPromise(thenable); if (maybePromise !== thenable && typeof thenable._isDisposable === "function" && typeof thenable._getDisposer === "function" && thenable._isDisposable()) { maybePromise._setDisposable(thenable._getDisposer()); } return maybePromise; } function dispose(resources, inspection) { var i = 0; var len = resources.length; var ret = new Promise(INTERNAL); function iterator() { if (i >= len) return ret._fulfill(); var maybePromise = castPreservingDisposable(resources[i++]); if (maybePromise instanceof Promise && maybePromise._isDisposable()) { try { maybePromise = tryConvertToPromise( maybePromise._getDisposer().tryDispose(inspection), resources.promise); } catch (e) { return thrower(e); } if (maybePromise instanceof Promise) { return maybePromise._then(iterator, thrower, null, null, null); } } iterator(); } iterator(); return ret; } function Disposer(data, promise, context) { this._data = data; this._promise = promise; this._context = context; } Disposer.prototype.data = function () { return this._data; }; Disposer.prototype.promise = function () { return this._promise; }; Disposer.prototype.resource = function () { if (this.promise().isFulfilled()) { return this.promise().value(); } return null; }; Disposer.prototype.tryDispose = function(inspection) { var resource = this.resource(); var context = this._context; if (context !== undefined) context._pushContext(); var ret = resource !== null ? this.doDispose(resource, inspection) : null; if (context !== undefined) context._popContext(); this._promise._unsetDisposable(); this._data = null; return ret; }; Disposer.isDisposer = function (d) { return (d != null && typeof d.resource === "function" && typeof d.tryDispose === "function"); }; function FunctionDisposer(fn, promise, context) { this.constructor$(fn, promise, context); } inherits(FunctionDisposer, Disposer); FunctionDisposer.prototype.doDispose = function (resource, inspection) { var fn = this.data(); return fn.call(resource, resource, inspection); }; function maybeUnwrapDisposer(value) { if (Disposer.isDisposer(value)) { this.resources[this.index]._setDisposable(value); return value.promise(); } return value; } function ResourceList(length) { this.length = length; this.promise = null; this[length-1] = null; } ResourceList.prototype._resultCancelled = function() { var len = this.length; for (var i = 0; i < len; ++i) { var item = this[i]; if (item instanceof Promise) { item.cancel(); } } }; Promise.using = function () { var len = arguments.length; if (len < 2) return apiRejection( "you must pass at least 2 arguments to Promise.using"); var fn = arguments[len - 1]; if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var input; var spreadArgs = true; if (len === 2 && Array.isArray(arguments[0])) { input = arguments[0]; len = input.length; spreadArgs = false; } else { input = arguments; len--; } var resources = new ResourceList(len); for (var i = 0; i < len; ++i) { var resource = input[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); resource._setDisposable(disposer); } else { var maybePromise = tryConvertToPromise(resource); if (maybePromise instanceof Promise) { resource = maybePromise._then(maybeUnwrapDisposer, null, null, { resources: resources, index: i }, undefined); } } resources[i] = resource; } var reflectedResources = new Array(resources.length); for (var i = 0; i < reflectedResources.length; ++i) { reflectedResources[i] = Promise.resolve(resources[i]).reflect(); } var resultPromise = Promise.all(reflectedResources) .then(function(inspections) { for (var i = 0; i < inspections.length; ++i) { var inspection = inspections[i]; if (inspection.isRejected()) { errorObj.e = inspection.error(); return errorObj; } else if (!inspection.isFulfilled()) { resultPromise.cancel(); return; } inspections[i] = inspection.value(); } promise._pushContext(); fn = tryCatch(fn); var ret = spreadArgs ? fn.apply(undefined, inspections) : fn(inspections); var promiseCreated = promise._popContext(); debug.checkForgottenReturns( ret, promiseCreated, "Promise.using", promise); return ret; }); var promise = resultPromise.lastly(function() { var inspection = new Promise.PromiseInspection(resultPromise); return dispose(resources, inspection); }); resources.promise = promise; promise._setOnCancel(resources); return promise; }; Promise.prototype._setDisposable = function (disposer) { this._bitField = this._bitField | 131072; this._disposer = disposer; }; Promise.prototype._isDisposable = function () { return (this._bitField & 131072) > 0; }; Promise.prototype._getDisposer = function () { return this._disposer; }; Promise.prototype._unsetDisposable = function () { this._bitField = this._bitField & (~131072); this._disposer = undefined; }; Promise.prototype.disposer = function (fn) { if (typeof fn === "function") { return new FunctionDisposer(fn, this, createContext()); } throw new TypeError(); }; }; },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var canEvaluate = typeof navigator == "undefined"; var errorObj = {e: {}}; var tryCatchTarget; var globalObject = typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : this !== undefined ? this : null; function tryCatcher() { try { var target = tryCatchTarget; tryCatchTarget = null; return target.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { tryCatchTarget = fn; return tryCatcher; } var inherits = function(Child, Parent) { var hasProp = {}.hasOwnProperty; function T() { this.constructor = Child; this.constructor$ = Parent; for (var propertyName in Parent.prototype) { if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length-1) !== "$" ) { this[propertyName + "$"] = Parent.prototype[propertyName]; } } } T.prototype = Parent.prototype; Child.prototype = new T(); return Child.prototype; }; function isPrimitive(val) { return val == null || val === true || val === false || typeof val === "string" || typeof val === "number"; } function isObject(value) { return typeof value === "function" || typeof value === "object" && value !== null; } function maybeWrapAsError(maybeError) { if (!isPrimitive(maybeError)) return maybeError; return new Error(safeToString(maybeError)); } function withAppended(target, appendee) { var len = target.length; var ret = new Array(len + 1); var i; for (i = 0; i < len; ++i) { ret[i] = target[i]; } ret[i] = appendee; return ret; } function getDataPropertyOrDefault(obj, key, defaultValue) { if (es5.isES5) { var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null) { return desc.get == null && desc.set == null ? desc.value : defaultValue; } } else { return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; } } function notEnumerableProp(obj, name, value) { if (isPrimitive(obj)) return obj; var descriptor = { value: value, configurable: true, enumerable: false, writable: true }; es5.defineProperty(obj, name, descriptor); return obj; } function thrower(r) { throw r; } var inheritedDataKeys = (function() { var excludedPrototypes = [ Array.prototype, Object.prototype, Function.prototype ]; var isExcludedProto = function(val) { for (var i = 0; i < excludedPrototypes.length; ++i) { if (excludedPrototypes[i] === val) { return true; } } return false; }; if (es5.isES5) { var getKeys = Object.getOwnPropertyNames; return function(obj) { var ret = []; var visitedKeys = Object.create(null); while (obj != null && !isExcludedProto(obj)) { var keys; try { keys = getKeys(obj); } catch (e) { return ret; } for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (visitedKeys[key]) continue; visitedKeys[key] = true; var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null && desc.get == null && desc.set == null) { ret.push(key); } } obj = es5.getPrototypeOf(obj); } return ret; }; } else { var hasProp = {}.hasOwnProperty; return function(obj) { if (isExcludedProto(obj)) return []; var ret = []; /*jshint forin:false */ enumeration: for (var key in obj) { if (hasProp.call(obj, key)) { ret.push(key); } else { for (var i = 0; i < excludedPrototypes.length; ++i) { if (hasProp.call(excludedPrototypes[i], key)) { continue enumeration; } } ret.push(key); } } return ret; }; } })(); var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; function isClass(fn) { try { if (typeof fn === "function") { var keys = es5.names(fn.prototype); var hasMethods = es5.isES5 && keys.length > 1; var hasMethodsOtherThanConstructor = keys.length > 0 && !(keys.length === 1 && keys[0] === "constructor"); var hasThisAssignmentAndStaticMethods = thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; if (hasMethods || hasMethodsOtherThanConstructor || hasThisAssignmentAndStaticMethods) { return true; } } return false; } catch (e) { return false; } } function toFastProperties(obj) { /*jshint -W027,-W055,-W031*/ function FakeConstructor() {} FakeConstructor.prototype = obj; var l = 8; while (l--) new FakeConstructor(); return obj; eval(obj); } var rident = /^[a-z$_][a-z$_0-9]*$/i; function isIdentifier(str) { return rident.test(str); } function filledRange(count, prefix, suffix) { var ret = new Array(count); for(var i = 0; i < count; ++i) { ret[i] = prefix + i + suffix; } return ret; } function safeToString(obj) { try { return obj + ""; } catch (e) { return "[no string representation]"; } } function isError(obj) { return obj !== null && typeof obj === "object" && typeof obj.message === "string" && typeof obj.name === "string"; } function markAsOriginatingFromRejection(e) { try { notEnumerableProp(e, "isOperational", true); } catch(ignore) {} } function originatesFromRejection(e) { if (e == null) return false; return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || e["isOperational"] === true); } function canAttachTrace(obj) { return isError(obj) && es5.propertyIsWritable(obj, "stack"); } var ensureErrorObject = (function() { if (!("stack" in new Error())) { return function(value) { if (canAttachTrace(value)) return value; try {throw new Error(safeToString(value));} catch(err) {return err;} }; } else { return function(value) { if (canAttachTrace(value)) return value; return new Error(safeToString(value)); }; } })(); function classString(obj) { return {}.toString.call(obj); } function copyDescriptors(from, to, filter) { var keys = es5.names(from); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (filter(key)) { try { es5.defineProperty(to, key, es5.getDescriptor(from, key)); } catch (ignore) {} } } } var asArray = function(v) { if (es5.isArray(v)) { return v; } return null; }; if (typeof Symbol !== "undefined" && Symbol.iterator) { var ArrayFrom = typeof Array.from === "function" ? function(v) { return Array.from(v); } : function(v) { var ret = []; var it = v[Symbol.iterator](); var itResult; while (!((itResult = it.next()).done)) { ret.push(itResult.value); } return ret; }; asArray = function(v) { if (es5.isArray(v)) { return v; } else if (v != null && typeof v[Symbol.iterator] === "function") { return ArrayFrom(v); } return null; }; } var isNode = typeof process !== "undefined" && classString(process).toLowerCase() === "[object process]"; function env(key, def) { return isNode ? process.env[key] : def; } var ret = { isClass: isClass, isIdentifier: isIdentifier, inheritedDataKeys: inheritedDataKeys, getDataPropertyOrDefault: getDataPropertyOrDefault, thrower: thrower, isArray: es5.isArray, asArray: asArray, notEnumerableProp: notEnumerableProp, isPrimitive: isPrimitive, isObject: isObject, isError: isError, canEvaluate: canEvaluate, errorObj: errorObj, tryCatch: tryCatch, inherits: inherits, withAppended: withAppended, maybeWrapAsError: maybeWrapAsError, toFastProperties: toFastProperties, filledRange: filledRange, toString: safeToString, canAttachTrace: canAttachTrace, ensureErrorObject: ensureErrorObject, originatesFromRejection: originatesFromRejection, markAsOriginatingFromRejection: markAsOriginatingFromRejection, classString: classString, copyDescriptors: copyDescriptors, hasDevTools: typeof chrome !== "undefined" && chrome && typeof chrome.loadTimes === "function", isNode: isNode, env: env, global: globalObject }; ret.isRecentNode = ret.isNode && (function() { var version = process.versions.node.split(".").map(Number); return (version[0] === 0 && version[1] > 10) || (version[0] > 0); })(); if (ret.isNode) ret.toFastProperties(process); try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; },{"./es5":13}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(205), (function() { return this; }()), __webpack_require__(206).setImmediate)) /***/ }, /* 205 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 206 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(setImmediate, clearImmediate) {var nextTick = __webpack_require__(205).nextTick; var apply = Function.prototype.apply; var slice = Array.prototype.slice; var immediateIds = {}; var nextImmediateId = 0; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }; exports.setInterval = function() { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function(timeout) { timeout.close(); }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function() {}; Timeout.prototype.close = function() { this._clearFn.call(window, this._id); }; // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } }; // That's not how node.js implements it but the exposed api is the same. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { var id = nextImmediateId++; var args = arguments.length < 2 ? false : slice.call(arguments, 1); immediateIds[id] = true; nextTick(function onNextTick() { if (immediateIds[id]) { // fn.call() is faster so we optimize for the common use-case // @see http://jsperf.com/call-apply-segu if (args) { fn.apply(null, args); } else { fn.call(null); } // Prevent ids from leaking exports.clearImmediate(id); } }); return id; }; exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { delete immediateIds[id]; }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(206).setImmediate, __webpack_require__(206).clearImmediate)) /***/ }, /* 207 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {/*! * validate.js 0.9.0 * * (c) 2013-2015 Nicklas Ansman, 2013 Wrapp * Validate.js may be freely distributed under the MIT license. * For all details and documentation: * http://validatejs.org/ */ (function(exports, module, define) { "use strict"; // The main function that calls the validators specified by the constraints. // The options are the following: // - format (string) - An option that controls how the returned value is formatted // * flat - Returns a flat array of just the error messages // * grouped - Returns the messages grouped by attribute (default) // * detailed - Returns an array of the raw validation data // - fullMessages (boolean) - If `true` (default) the attribute name is prepended to the error. // // Please note that the options are also passed to each validator. var validate = function(attributes, constraints, options) { options = v.extend({}, v.options, options); var results = v.runValidations(attributes, constraints, options) , attr , validator; for (attr in results) { for (validator in results[attr]) { if (v.isPromise(results[attr][validator])) { throw new Error("Use validate.async if you want support for promises"); } } } return validate.processValidationResults(results, options); }; var v = validate; // Copies over attributes from one or more sources to a single destination. // Very much similar to underscore's extend. // The first argument is the target object and the remaining arguments will be // used as sources. v.extend = function(obj) { [].slice.call(arguments, 1).forEach(function(source) { for (var attr in source) { obj[attr] = source[attr]; } }); return obj; }; v.extend(validate, { // This is the version of the library as a semver. // The toString function will allow it to be coerced into a string version: { major: 0, minor: 9, patch: 0, metadata: null, toString: function() { var version = v.format("%{major}.%{minor}.%{patch}", v.version); if (!v.isEmpty(v.version.metadata)) { version += "+" + v.version.metadata; } return version; } }, // Below is the dependencies that are used in validate.js // The constructor of the Promise implementation. // If you are using Q.js, RSVP or any other A+ compatible implementation // override this attribute to be the constructor of that promise. // Since jQuery promises aren't A+ compatible they won't work. Promise: typeof Promise !== "undefined" ? Promise : /* istanbul ignore next */ null, EMPTY_STRING_REGEXP: /^\s*$/, // Runs the validators specified by the constraints object. // Will return an array of the format: // [{attribute: "<attribute name>", error: "<validation result>"}, ...] runValidations: function(attributes, constraints, options) { var results = [] , attr , validatorName , value , validators , validator , validatorOptions , error; if (v.isDomElement(attributes) || v.isJqueryElement(attributes)) { attributes = v.collectFormValues(attributes); } // Loops through each constraints, finds the correct validator and run it. for (attr in constraints) { value = v.getDeepObjectValue(attributes, attr); // This allows the constraints for an attribute to be a function. // The function will be called with the value, attribute name, the complete dict of // attributes as well as the options and constraints passed in. // This is useful when you want to have different // validations depending on the attribute value. validators = v.result(constraints[attr], value, attributes, attr, options, constraints); for (validatorName in validators) { validator = v.validators[validatorName]; if (!validator) { error = v.format("Unknown validator %{name}", {name: validatorName}); throw new Error(error); } validatorOptions = validators[validatorName]; // This allows the options to be a function. The function will be // called with the value, attribute name, the complete dict of // attributes as well as the options and constraints passed in. // This is useful when you want to have different // validations depending on the attribute value. validatorOptions = v.result(validatorOptions, value, attributes, attr, options, constraints); if (!validatorOptions) { continue; } results.push({ attribute: attr, value: value, validator: validatorName, globalOptions: options, attributes: attributes, options: validatorOptions, error: validator.call(validator, value, validatorOptions, attr, attributes, options) }); } } return results; }, // Takes the output from runValidations and converts it to the correct // output format. processValidationResults: function(errors, options) { var attr; errors = v.pruneEmptyErrors(errors, options); errors = v.expandMultipleErrors(errors, options); errors = v.convertErrorMessages(errors, options); switch (options.format || "grouped") { case "detailed": // Do nothing more to the errors break; case "flat": errors = v.flattenErrorsToArray(errors); break; case "grouped": errors = v.groupErrorsByAttribute(errors); for (attr in errors) { errors[attr] = v.flattenErrorsToArray(errors[attr]); } break; default: throw new Error(v.format("Unknown format %{format}", options)); } return v.isEmpty(errors) ? undefined : errors; }, // Runs the validations with support for promises. // This function will return a promise that is settled when all the // validation promises have been completed. // It can be called even if no validations returned a promise. async: function(attributes, constraints, options) { options = v.extend({}, v.async.options, options); var WrapErrors = options.wrapErrors || function(errors) { return errors; }; // Removes unknown attributes if (options.cleanAttributes !== false) { attributes = v.cleanAttributes(attributes, constraints); } var results = v.runValidations(attributes, constraints, options); return new v.Promise(function(resolve, reject) { v.waitForResults(results).then(function() { var errors = v.processValidationResults(results, options); if (errors) { reject(new WrapErrors(errors, options, attributes, constraints)); } else { resolve(attributes); } }, function(err) { reject(err); }); }); }, single: function(value, constraints, options) { options = v.extend({}, v.single.options, options, { format: "flat", fullMessages: false }); return v({single: value}, {single: constraints}, options); }, // Returns a promise that is resolved when all promises in the results array // are settled. The promise returned from this function is always resolved, // never rejected. // This function modifies the input argument, it replaces the promises // with the value returned from the promise. waitForResults: function(results) { // Create a sequence of all the results starting with a resolved promise. return results.reduce(function(memo, result) { // If this result isn't a promise skip it in the sequence. if (!v.isPromise(result.error)) { return memo; } return memo.then(function() { return result.error.then( function(error) { result.error = error || null; }, function(error) { if (error instanceof Error) { throw error; } v.error("Rejecting promises with the result is deprecated. Please use the resolve callback instead."); result.error = error; } ); }); }, new v.Promise(function(r) { r(); })); // A resolved promise }, // If the given argument is a call: function the and: function return the value // otherwise just return the value. Additional arguments will be passed as // arguments to the function. // Example: // ``` // result('foo') // 'foo' // result(Math.max, 1, 2) // 2 // ``` result: function(value) { var args = [].slice.call(arguments, 1); if (typeof value === 'function') { value = value.apply(null, args); } return value; }, // Checks if the value is a number. This function does not consider NaN a // number like many other `isNumber` functions do. isNumber: function(value) { return typeof value === 'number' && !isNaN(value); }, // Returns false if the object is not a function isFunction: function(value) { return typeof value === 'function'; }, // A simple check to verify that the value is an integer. Uses `isNumber` // and a simple modulo check. isInteger: function(value) { return v.isNumber(value) && value % 1 === 0; }, // Uses the `Object` function to check if the given argument is an object. isObject: function(obj) { return obj === Object(obj); }, // Simply checks if the object is an instance of a date isDate: function(obj) { return obj instanceof Date; }, // Returns false if the object is `null` of `undefined` isDefined: function(obj) { return obj !== null && obj !== undefined; }, // Checks if the given argument is a promise. Anything with a `then` // function is considered a promise. isPromise: function(p) { return !!p && v.isFunction(p.then); }, isJqueryElement: function(o) { return o && v.isString(o.jquery); }, isDomElement: function(o) { if (!o) { return false; } if (!v.isFunction(o.querySelectorAll) || !v.isFunction(o.querySelector)) { return false; } if (v.isObject(document) && o === document) { return true; } // http://stackoverflow.com/a/384380/699304 /* istanbul ignore else */ if (typeof HTMLElement === "object") { return o instanceof HTMLElement; } else { return o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"; } }, isEmpty: function(value) { var attr; // Null and undefined are empty if (!v.isDefined(value)) { return true; } // functions are non empty if (v.isFunction(value)) { return false; } // Whitespace only strings are empty if (v.isString(value)) { return v.EMPTY_STRING_REGEXP.test(value); } // For arrays we use the length property if (v.isArray(value)) { return value.length === 0; } // Dates have no attributes but aren't empty if (v.isDate(value)) { return false; } // If we find at least one property we consider it non empty if (v.isObject(value)) { for (attr in value) { return false; } return true; } return false; }, // Formats the specified strings with the given values like so: // ``` // format("Foo: %{foo}", {foo: "bar"}) // "Foo bar" // ``` // If you want to write %{...} without having it replaced simply // prefix it with % like this `Foo: %%{foo}` and it will be returned // as `"Foo: %{foo}"` format: v.extend(function(str, vals) { if (!v.isString(str)) { return str; } return str.replace(v.format.FORMAT_REGEXP, function(m0, m1, m2) { if (m1 === '%') { return "%{" + m2 + "}"; } else { return String(vals[m2]); } }); }, { // Finds %{key} style patterns in the given string FORMAT_REGEXP: /(%?)%\{([^\}]+)\}/g }), // "Prettifies" the given string. // Prettifying means replacing [.\_-] with spaces as well as splitting // camel case words. prettify: function(str) { if (v.isNumber(str)) { // If there are more than 2 decimals round it to two if ((str * 100) % 1 === 0) { return "" + str; } else { return parseFloat(Math.round(str * 100) / 100).toFixed(2); } } if (v.isArray(str)) { return str.map(function(s) { return v.prettify(s); }).join(", "); } if (v.isObject(str)) { return str.toString(); } // Ensure the string is actually a string str = "" + str; return str // Splits keys separated by periods .replace(/([^\s])\.([^\s])/g, '$1 $2') // Removes backslashes .replace(/\\+/g, '') // Replaces - and - with space .replace(/[_-]/g, ' ') // Splits camel cased words .replace(/([a-z])([A-Z])/g, function(m0, m1, m2) { return "" + m1 + " " + m2.toLowerCase(); }) .toLowerCase(); }, stringifyValue: function(value) { return v.prettify(value); }, isString: function(value) { return typeof value === 'string'; }, isArray: function(value) { return {}.toString.call(value) === '[object Array]'; }, contains: function(obj, value) { if (!v.isDefined(obj)) { return false; } if (v.isArray(obj)) { return obj.indexOf(value) !== -1; } return value in obj; }, forEachKeyInKeypath: function(object, keypath, callback) { if (!v.isString(keypath)) { return undefined; } var key = "" , i , escape = false; for (i = 0; i < keypath.length; ++i) { switch (keypath[i]) { case '.': if (escape) { escape = false; key += '.'; } else { object = callback(object, key, false); key = ""; } break; case '\\': if (escape) { escape = false; key += '\\'; } else { escape = true; } break; default: escape = false; key += keypath[i]; break; } } return callback(object, key, true); }, getDeepObjectValue: function(obj, keypath) { if (!v.isObject(obj)) { return undefined; } return v.forEachKeyInKeypath(obj, keypath, function(obj, key) { if (v.isObject(obj)) { return obj[key]; } }); }, // This returns an object with all the values of the form. // It uses the input name as key and the value as value // So for example this: // <input type="text" name="email" value="foo@bar.com" /> // would return: // {email: "foo@bar.com"} collectFormValues: function(form, options) { var values = {} , i , input , inputs , value; if (v.isJqueryElement(form)) { form = form[0]; } if (!form) { return values; } options = options || {}; inputs = form.querySelectorAll("input[name], textarea[name]"); for (i = 0; i < inputs.length; ++i) { input = inputs.item(i); if (v.isDefined(input.getAttribute("data-ignored"))) { continue; } value = v.sanitizeFormValue(input.value, options); if (input.type === "number") { value = value ? +value : null; } else if (input.type === "checkbox") { if (input.attributes.value) { if (!input.checked) { value = values[input.name] || null; } } else { value = input.checked; } } else if (input.type === "radio") { if (!input.checked) { value = values[input.name] || null; } } values[input.name] = value; } inputs = form.querySelectorAll("select[name]"); for (i = 0; i < inputs.length; ++i) { input = inputs.item(i); value = v.sanitizeFormValue(input.options[input.selectedIndex].value, options); values[input.name] = value; } return values; }, sanitizeFormValue: function(value, options) { if (options.trim && v.isString(value)) { value = value.trim(); } if (options.nullify !== false && value === "") { return null; } return value; }, capitalize: function(str) { if (!v.isString(str)) { return str; } return str[0].toUpperCase() + str.slice(1); }, // Remove all errors who's error attribute is empty (null or undefined) pruneEmptyErrors: function(errors) { return errors.filter(function(error) { return !v.isEmpty(error.error); }); }, // In // [{error: ["err1", "err2"], ...}] // Out // [{error: "err1", ...}, {error: "err2", ...}] // // All attributes in an error with multiple messages are duplicated // when expanding the errors. expandMultipleErrors: function(errors) { var ret = []; errors.forEach(function(error) { // Removes errors without a message if (v.isArray(error.error)) { error.error.forEach(function(msg) { ret.push(v.extend({}, error, {error: msg})); }); } else { ret.push(error); } }); return ret; }, // Converts the error mesages by prepending the attribute name unless the // message is prefixed by ^ convertErrorMessages: function(errors, options) { options = options || {}; var ret = []; errors.forEach(function(errorInfo) { var error = v.result(errorInfo.error, errorInfo.value, errorInfo.attribute, errorInfo.options, errorInfo.attributes, errorInfo.globalOptions); if (!v.isString(error)) { ret.push(errorInfo); return; } if (error[0] === '^') { error = error.slice(1); } else if (options.fullMessages !== false) { error = v.capitalize(v.prettify(errorInfo.attribute)) + " " + error; } error = error.replace(/\\\^/g, "^"); error = v.format(error, {value: v.stringifyValue(errorInfo.value)}); ret.push(v.extend({}, errorInfo, {error: error})); }); return ret; }, // In: // [{attribute: "<attributeName>", ...}] // Out: // {"<attributeName>": [{attribute: "<attributeName>", ...}]} groupErrorsByAttribute: function(errors) { var ret = {}; errors.forEach(function(error) { var list = ret[error.attribute]; if (list) { list.push(error); } else { ret[error.attribute] = [error]; } }); return ret; }, // In: // [{error: "<message 1>", ...}, {error: "<message 2>", ...}] // Out: // ["<message 1>", "<message 2>"] flattenErrorsToArray: function(errors) { return errors.map(function(error) { return error.error; }); }, cleanAttributes: function(attributes, whitelist) { function whitelistCreator(obj, key, last) { if (v.isObject(obj[key])) { return obj[key]; } return (obj[key] = last ? true : {}); } function buildObjectWhitelist(whitelist) { var ow = {} , lastObject , attr; for (attr in whitelist) { if (!whitelist[attr]) { continue; } v.forEachKeyInKeypath(ow, attr, whitelistCreator); } return ow; } function cleanRecursive(attributes, whitelist) { if (!v.isObject(attributes)) { return attributes; } var ret = v.extend({}, attributes) , w , attribute; for (attribute in attributes) { w = whitelist[attribute]; if (v.isObject(w)) { ret[attribute] = cleanRecursive(ret[attribute], w); } else if (!w) { delete ret[attribute]; } } return ret; } if (!v.isObject(whitelist) || !v.isObject(attributes)) { return {}; } whitelist = buildObjectWhitelist(whitelist); return cleanRecursive(attributes, whitelist); }, exposeModule: function(validate, root, exports, module, define) { if (exports) { if (module && module.exports) { exports = module.exports = validate; } exports.validate = validate; } else { root.validate = validate; if (validate.isFunction(define) && define.amd) { define([], function () { return validate; }); } } }, warn: function(msg) { if (typeof console !== "undefined" && console.warn) { console.warn("[validate.js] " + msg); } }, error: function(msg) { if (typeof console !== "undefined" && console.error) { console.error("[validate.js] " + msg); } } }); validate.validators = { // Presence validates that the value isn't empty presence: function(value, options) { options = v.extend({}, this.options, options); if (v.isEmpty(value)) { return options.message || this.message || "can't be blank"; } }, length: function(value, options, attribute) { // Empty values are allowed if (v.isEmpty(value)) { return; } options = v.extend({}, this.options, options); var is = options.is , maximum = options.maximum , minimum = options.minimum , tokenizer = options.tokenizer || function(val) { return val; } , err , errors = []; value = tokenizer(value); var length = value.length; if(!v.isNumber(length)) { v.error(v.format("Attribute %{attr} has a non numeric value for `length`", {attr: attribute})); return options.message || this.notValid || "has an incorrect length"; } // Is checks if (v.isNumber(is) && length !== is) { err = options.wrongLength || this.wrongLength || "is the wrong length (should be %{count} characters)"; errors.push(v.format(err, {count: is})); } if (v.isNumber(minimum) && length < minimum) { err = options.tooShort || this.tooShort || "is too short (minimum is %{count} characters)"; errors.push(v.format(err, {count: minimum})); } if (v.isNumber(maximum) && length > maximum) { err = options.tooLong || this.tooLong || "is too long (maximum is %{count} characters)"; errors.push(v.format(err, {count: maximum})); } if (errors.length > 0) { return options.message || errors; } }, numericality: function(value, options) { // Empty values are fine if (v.isEmpty(value)) { return; } options = v.extend({}, this.options, options); var errors = [] , name , count , checks = { greaterThan: function(v, c) { return v > c; }, greaterThanOrEqualTo: function(v, c) { return v >= c; }, equalTo: function(v, c) { return v === c; }, lessThan: function(v, c) { return v < c; }, lessThanOrEqualTo: function(v, c) { return v <= c; } }; // Coerce the value to a number unless we're being strict. if (options.noStrings !== true && v.isString(value)) { value = +value; } // If it's not a number we shouldn't continue since it will compare it. if (!v.isNumber(value)) { return options.message || options.notValid || this.notValid || "is not a number"; } // Same logic as above, sort of. Don't bother with comparisons if this // doesn't pass. if (options.onlyInteger && !v.isInteger(value)) { return options.message || options.notInteger || this.notInteger || "must be an integer"; } for (name in checks) { count = options[name]; if (v.isNumber(count) && !checks[name](value, count)) { // This picks the default message if specified // For example the greaterThan check uses the message from // this.notGreaterThan so we capitalize the name and prepend "not" var key = "not" + v.capitalize(name); var msg = options[key] || this[key] || "must be %{type} %{count}"; errors.push(v.format(msg, { count: count, type: v.prettify(name) })); } } if (options.odd && value % 2 !== 1) { errors.push(options.notOdd || this.notOdd || "must be odd"); } if (options.even && value % 2 !== 0) { errors.push(options.notEven || this.notEven || "must be even"); } if (errors.length) { return options.message || errors; } }, datetime: v.extend(function(value, options) { if (!v.isFunction(this.parse) || !v.isFunction(this.format)) { throw new Error("Both the parse and format functions needs to be set to use the datetime/date validator"); } // Empty values are fine if (v.isEmpty(value)) { return; } options = v.extend({}, this.options, options); var err , errors = [] , earliest = options.earliest ? this.parse(options.earliest, options) : NaN , latest = options.latest ? this.parse(options.latest, options) : NaN; value = this.parse(value, options); // 86400000 is the number of seconds in a day, this is used to remove // the time from the date if (isNaN(value) || options.dateOnly && value % 86400000 !== 0) { return options.message || this.notValid || "must be a valid date"; } if (!isNaN(earliest) && value < earliest) { err = this.tooEarly || "must be no earlier than %{date}"; err = v.format(err, {date: this.format(earliest, options)}); errors.push(err); } if (!isNaN(latest) && value > latest) { err = this.tooLate || "must be no later than %{date}"; err = v.format(err, {date: this.format(latest, options)}); errors.push(err); } if (errors.length) { return options.message || errors; } }, { parse: null, format: null }), date: function(value, options) { options = v.extend({}, options, {dateOnly: true}); return v.validators.datetime.call(v.validators.datetime, value, options); }, format: function(value, options) { if (v.isString(options) || (options instanceof RegExp)) { options = {pattern: options}; } options = v.extend({}, this.options, options); var message = options.message || this.message || "is invalid" , pattern = options.pattern , match; // Empty values are allowed if (v.isEmpty(value)) { return; } if (!v.isString(value)) { return message; } if (v.isString(pattern)) { pattern = new RegExp(options.pattern, options.flags); } match = pattern.exec(value); if (!match || match[0].length != value.length) { return message; } }, inclusion: function(value, options) { // Empty values are fine if (v.isEmpty(value)) { return; } if (v.isArray(options)) { options = {within: options}; } options = v.extend({}, this.options, options); if (v.contains(options.within, value)) { return; } var message = options.message || this.message || "^%{value} is not included in the list"; return v.format(message, {value: value}); }, exclusion: function(value, options) { // Empty values are fine if (v.isEmpty(value)) { return; } if (v.isArray(options)) { options = {within: options}; } options = v.extend({}, this.options, options); if (!v.contains(options.within, value)) { return; } var message = options.message || this.message || "^%{value} is restricted"; return v.format(message, {value: value}); }, email: v.extend(function(value, options) { options = v.extend({}, this.options, options); var message = options.message || this.message || "is not a valid email"; // Empty values are fine if (v.isEmpty(value)) { return; } if (!v.isString(value)) { return message; } if (!this.PATTERN.exec(value)) { return message; } }, { PATTERN: /^[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/i }), equality: function(value, options, attribute, attributes) { if (v.isEmpty(value)) { return; } if (v.isString(options)) { options = {attribute: options}; } options = v.extend({}, this.options, options); var message = options.message || this.message || "is not equal to %{attribute}"; if (v.isEmpty(options.attribute) || !v.isString(options.attribute)) { throw new Error("The attribute must be a non empty string"); } var otherValue = v.getDeepObjectValue(attributes, options.attribute) , comparator = options.comparator || function(v1, v2) { return v1 === v2; }; if (!comparator(value, otherValue, options, attribute, attributes)) { return v.format(message, {attribute: v.prettify(options.attribute)}); } }, // A URL validator that is used to validate URLs with the ability to // restrict schemes and some domains. url: function(value, options) { if (v.isEmpty(value)) { return; } options = v.extend({}, this.options, options); var message = options.message || this.message || "is not a valid url" , schemes = options.schemes || this.schemes || ['http', 'https'] , allowLocal = options.allowLocal || this.allowLocal || false; if (!v.isString(value)) { return message; } // https://gist.github.com/dperini/729294 var regex = "^" + // schemes "(?:(?:" + schemes.join("|") + "):\\/\\/)" + // credentials "(?:\\S+(?::\\S*)?@)?"; regex += "(?:"; var hostname = "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" + "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" + "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))"; // This ia a special case for the localhost hostname if (allowLocal) { hostname = "(?:localhost|" + hostname + ")"; } else { // private & local addresses regex += "(?!10(?:\\.\\d{1,3}){3})" + "(?!127(?:\\.\\d{1,3}){3})" + "(?!169\\.254(?:\\.\\d{1,3}){2})" + "(?!192\\.168(?:\\.\\d{1,3}){2})" + "(?!172" + "\\.(?:1[6-9]|2\\d|3[0-1])" + "(?:\\.\\d{1,3})" + "{2})"; } // reserved addresses regex += "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + "|" + hostname + // port number "(?::\\d{2,5})?" + // path "(?:\\/[^\\s]*)?" + "$"; var PATTERN = new RegExp(regex, 'i'); if (!PATTERN.exec(value)) { return message; } } }; validate.exposeModule(validate, this, exports, module, __webpack_require__(208)); }).call(this, true ? /* istanbul ignore next */ exports : null, true ? /* istanbul ignore next */ module : null, __webpack_require__(208)); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(93)(module))) /***/ }, /* 208 */ /***/ function(module, exports) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }, /* 209 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseQuerySet = exports.BulkCreate = exports.Raw = exports.Ordering = exports.PageSize = exports.First = exports.UpdateOrCreate = exports.Update = exports.Delete = exports.List = exports.GetOrCreate = exports.Get = exports.Create = undefined; var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _includes2 = __webpack_require__(97); var _includes3 = _interopRequireDefault(_includes2); var _defaults2 = __webpack_require__(210); var _defaults3 = _interopRequireDefault(_defaults2); var _map2 = __webpack_require__(159); var _map3 = _interopRequireDefault(_map2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _bluebird = __webpack_require__(204); var _bluebird2 = _interopRequireDefault(_bluebird); var _request = __webpack_require__(213); var _request2 = _interopRequireDefault(_request); var _errors = __webpack_require__(229); var _errors2 = _interopRequireDefault(_errors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Wrapper around plain JavaScript Array which provides two additional methods for pagination. * @constructor * @type {ResultSet} * @param {QuerySet} querySet * @param {String} response * @param {Array} objects * @returns {ResultSet} * @property {Function} next * @property {Function} prev * @example {@lang javascript} * Instance.please().list() * // get next page * .then((instances) => instances.next()) * * // get prev page * .then((instances) => instances.prev()) * * .then((instances) => console.log('instances', instances)); */ var ResultSet = function ResultSet(querySet, response, objects) { var results = []; results.push.apply(results, objects); /** * Helper method which will fetch next page or throws `PaginationError`. * @memberOf ResultSet * @instance * @throws {PaginationError} * @returns {Promise} */ results.next = function () { if (!response.next) { return _bluebird2.default.reject(new _errors2.default('There is no next page')); } return querySet.request(response.next, { query: {} }); }; /** * Helper method which will fetch previous page or throws `PaginationError`. * @memberOf ResultSet * @instance * @throws {PaginationError} * @returns {Promise} */ results.prev = function () { if (!response.prev) { return _bluebird2.default.reject(new _errors2.default('There is no previous page')); } return querySet.request(response.prev, { query: {} }); }; return results; }; var QuerySetRequest = (0, _stampit2.default)().compose(_request2.default).refs({ model: null }).props({ endpoint: 'list', method: 'GET', headers: {}, properties: {}, query: {}, payload: {}, attachments: {}, _serialize: true }).methods({ /** * Converts raw objects to {@link https://github.com/stampit-org/stampit|stampit} instances * @memberOf QuerySet * @instance * @private * @param {Object} response raw JavaScript objects * @returns {Object} */ serialize: function serialize(response) { if (this._serialize === false) { return response; } if (this.endpoint === 'list') { return this.asResultSet(response); } return this.model.fromJSON(response, this.properties); }, /** * Converts API response into {ResultSet} * @memberOf QuerySet * @instance * @private * @param {Object} response raw JavaScript objects * @param {String} lookupField additional field to search for data * @returns {ResultSet} */ asResultSet: function asResultSet(response, lookupField) { var _this = this; var objects = (0, _map3.default)(response.objects, function (object) { var obj = lookupField ? object[lookupField] : object; return _this.model.fromJSON(obj, _this.properties); }); return ResultSet(this, response, objects); }, /** * Executes current state of QuerySet * @memberOf QuerySet * @instance * @param {String} [requestPath = null] * @param {Object} [requestOptions = {}] * @returns {Promise} * @example {@lang javascript} * Instance.please().list().request().then(function(instance) {}); */ request: function request() { var _this2 = this; var requestPath = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0]; var requestOptions = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var meta = this.model.getMeta(); var endpoint = meta.endpoints[this.endpoint] || {}; var allowedMethods = endpoint.methods || []; var path = requestPath || meta.resolveEndpointPath(this.endpoint, this.properties); var method = this.method.toLowerCase(); var options = (0, _defaults3.default)(requestOptions, { headers: this.headers, query: this.query, payload: this.payload, attachments: this.attachments, responseAttr: this.responseAttr }); if (!(0, _includes3.default)(allowedMethods, method)) { return _bluebird2.default.reject(new Error('Invalid request method: "' + this.method + '".')); } return this.makeRequest(method, path, options).then(function (body) { return _this2.serialize(body); }); }, /** * Wrapper around {@link Queryset.request} method * @memberOf QuerySet * @instance * @param {function} callback * @returns {Promise} */ then: function then(callback) { return this.request().then(callback); } }); var Create = exports.Create = (0, _stampit2.default)().methods({ /** * A convenience method for creating an object and saving it all in one step. * @memberOf QuerySet * @instance * @param {Object} object * @returns {Promise} * @example {@lang javascript} * // Thus: * * Instance * .please() * .create({name: 'test-one', description: 'description'}) * .then(function(instance) {}); * * // and: * * var instance = Instance({name: 'test-one', description: 'description'}); * instance.save().then(function(instance) {}); * * // are equivalent. */ create: function create(object) { var attrs = (0, _assign3.default)({}, this.properties, object); var instance = this.model(attrs); return instance.save(); } }); var Get = exports.Get = (0, _stampit2.default)().methods({ /** * Returns the object matching the given lookup properties. * @memberOf QuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @returns {QuerySet} * @example {@lang javascript} * Instance.please().get({name: 'test-one'}).then(function(instance) {}); */ get: function get() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'GET'; this.endpoint = 'detail'; return this; } }); var GetOrCreate = exports.GetOrCreate = (0, _stampit2.default)().methods({ /** * A convenience method for looking up an object with the given lookup properties, creating one if necessary. * Successful callback will receive **object, created** arguments. * @memberOf QuerySet * @instance * @param {Object} properties attributes which will be used for object retrieving * @param {Object} defaults attributes which will be used for object creation * @returns {Promise} * @example {@lang javascript} * Instance * .please() * .getOrCreate({name: 'test-one'}, {description: 'test'}) * .then(function(instance, created) {}); * * // above is equivalent to: * * Instance * .please() * .get({name: 'test-one'}) * .then(function(instance) { * // Get * }) * .catch(function() { * // Create * return Instance.please().create({name: 'test-one', description: 'test'}); * }); */ getOrCreate: function getOrCreate() { var _this3 = this; var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var defaults = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; return new _bluebird2.default(function (resolve, reject) { _this3.get(properties).then(function (object) { return resolve(object, false); }).catch(function () { var attrs = (0, _assign3.default)({}, _this3.properties, properties, defaults); return _this3.create(attrs).then(function (object) { return resolve(object, true); }).catch(reject); }); }); } }); var List = exports.List = (0, _stampit2.default)().methods({ /** * Returns list of objects that match the given lookup properties. * @memberOf QuerySet * @instance * @param {Object} [properties = {}] lookup properties used for path resolving * @param {Object} [query = {}] * @returns {QuerySet} * @example {@lang javascript} * Instance.please().list().then(function(instances) {}); * Class.please().list({instanceName: 'test-one'}).then(function(classes) {}); */ list: function list() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var query = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.query = (0, _assign3.default)({}, this.query, query); this.method = 'GET'; this.endpoint = 'list'; return this; } }); var Delete = exports.Delete = (0, _stampit2.default)().methods({ /** * Removes single object based on provided properties. * @memberOf QuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @returns {QuerySet} * @example {@lang javascript} * Instance.please().delete({name: 'test-instance'}).then(function() {}); * Class.please().delete({name: 'test', instanceName: 'test-one'}).then(function() {}); */ delete: function _delete() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'DELETE'; this.endpoint = 'detail'; return this; } }); var Update = exports.Update = (0, _stampit2.default)().methods({ /** * Updates single object based on provided arguments * @memberOf QuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @param {Object} object attributes to update * @returns {QuerySet} * @example {@lang javascript} * Instance .please() .update({name: 'test-instance'}, {description: 'new one'}) .then(function(instance) {}); * Class .please() .update({name: 'test', instanceName: 'test-one'}, {description: 'new one'}) .then(function(cls) {}); */ update: function update() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var object = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.payload = object; this.method = 'PATCH'; this.endpoint = 'detail'; return this; } }); var TemplateResponse = (0, _stampit2.default)().methods({ /** * Renders the api response as a template. * @memberOf QuerySet * @instance * @param {template_name} name of template to be rendered * @returns {QuerySet} * @example {@lang javascript} * DataObject .please() .list({instanceName: 'my-instance', className: 'my-class'}) .templateResponse('objects_html_table') .then(function(objects) {}); */ templateResponse: function templateResponse(template_name) { this._serialize = false; this.responseAttr = 'text'; this.query['template_response'] = template_name; return this; } }); var UpdateOrCreate = exports.UpdateOrCreate = (0, _stampit2.default)().methods({ /** * A convenience method for updating an object with the given properties, creating a new one if necessary. * Successful callback will receive **object, updated** arguments. * @memberOf QuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @param {Object} [object = {}] object with (field, value) pairs used in case of update * @param {Object} [defaults = {}] object with (field, value) pairs used in case of create * @returns {Promise} * @example {@lang javascript} * Instance * .please() * .updateOrCreate({name: 'test-one'}, {description: 'new-test'}, {description: 'create-test'}) * .then(function(instance, updated) {}); * * // above is equivalent to: * * Instance * .please() * .update({name: 'test-one'}, {description: 'new-test'}) * .then(function(instance) { * // Update * }) * .catch(function() { * // Create * return Instance.please().create({name: 'test-one', description: 'create-test'}); * }); */ updateOrCreate: function updateOrCreate() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var _this4 = this; var object = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var defaults = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; return new _bluebird2.default(function (resolve, reject) { _this4.update(properties, object).then(function (_object) { return resolve(_object, true); }).catch(function () { var attrs = (0, _assign3.default)({}, _this4.properties, properties, defaults); return _this4.create(attrs).then(function (_object) { return resolve(_object, false); }).catch(reject); }); }); } }); var ExcludedFields = (0, _stampit2.default)().methods({ /** * Removes specified fields from object response. * @memberOf QuerySet * @instance * @param {Object} fields * @returns {QuerySet} * @example {@lang javascript} * DataObject.please().list({ instanceName: 'test-instace', className: 'test-class' }).excludedFields(['title', 'author']).then(function(dataobjects) {}); */ excludedFields: function excludedFields() { var fields = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; this.query['excluded_fields'] = fields.join(); return this; } }); var Fields = (0, _stampit2.default)().methods({ /** * Selects specified fields from object. * @memberOf QuerySet * @instance * @param {Object} fields * @returns {QuerySet} * @example {@lang javascript} * DataObject.please().list({ instanceName: 'test-instace', className: 'test-class' }).fields(['title', 'author']).then(function(dataobjects) {}); */ fields: function fields() { var _fields = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; this.query['fields'] = _fields.join(); return this; } }); var First = exports.First = (0, _stampit2.default)().methods({ /** * Returns the first object matched by the lookup properties or undefined, if there is no matching object. * @memberOf QuerySet * @instance * @param {Object} [properties = {}] * @param {Object} [query = {}] * @returns {Promise} * @example {@lang javascript} * Instance.please().first().then(function(instance) {}); * Class.please().first({instanceName: 'test-one'}).then(function(cls) {}); */ first: function first() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var query = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; return this.pageSize(1).list(properties, query).then(function (objects) { if (objects.length) { return objects[0]; } }); } }); var PageSize = exports.PageSize = (0, _stampit2.default)().methods({ /** * Sets page size. * @memberOf QuerySet * @instance * @param {Number} value * @returns {QuerySet} * @example {@lang javascript} * Instance.please().pageSize(2).then(function(instances) {}); * Class.please({instanceName: 'test-one'}).pageSize(2).then(function(classes) {}); */ pageSize: function pageSize(value) { this.query['page_size'] = value; return this; } }); var Ordering = exports.Ordering = (0, _stampit2.default)().methods({ /** * Sets order of returned objects. * @memberOf QuerySet * @instance * @param {String} [value = 'asc'] allowed choices are "asc" and "desc" * @returns {QuerySet} * @example {@lang javascript} * Instance.please().ordering('desc').then(function(instances) {}); * Class.please({instanceName: 'test-one'}).ordering('desc').then(function(classes) {}); */ ordering: function ordering() { var value = arguments.length <= 0 || arguments[0] === undefined ? 'asc' : arguments[0]; var allowed = ['asc', 'desc']; var ordering = value.toLowerCase(); if (!(0, _includes3.default)(allowed, ordering)) { throw Error('Invalid order value: "' + value + '", allowed choices are ' + allowed.join() + '.'); } this.query['ordering'] = ordering; return this; } }); var Raw = exports.Raw = (0, _stampit2.default)().methods({ /** * Disables serialization. Callback will will recive raw JavaScript objects. * @memberOf QuerySet * @instance * @returns {QuerySet} * @example {@lang javascript} * Instance.please().raw().then(function(response) {}); * Class.please({instanceName: 'test-one'}).raw().then(function(response) {}); */ raw: function raw() { this._serialize = false; return this; } }); var BulkCreate = exports.BulkCreate = (0, _stampit2.default)().methods({ /** * Creates many objects based on provied Array of objects. * @memberOf QuerySet * @instance * @param {Array} objects * @returns {Promise} * @example {@lang javascript} * const objects = [Instance({name: 'test1'}), Instance({name: 'tes21'})]; * Instance.please().bulkCreate(objects).then(function(instances) { * console.log('instances', instances); * }); */ bulkCreate: function bulkCreate(objects) { return _bluebird2.default.mapSeries(objects, function (o) { return o.save(); }); } }); /** * Base class responsible for all ORM (``please``) actions. * @constructor * @type {QuerySet} * @property {Object} model * @property {String} [endpoint = 'list'] * @property {String} [method = 'GET'] * @property {Object} [headers = {}] * @property {Object} [properties = {}] * @property {Object} [query = {}] * @property {Object} [payload = {}] * @property {Object} [attachments = {}] * @property {Boolean} [_serialize = true] */ var QuerySet = _stampit2.default.compose(QuerySetRequest, Create, BulkCreate, Get, GetOrCreate, List, Delete, Update, UpdateOrCreate, First, PageSize, Ordering, Fields, ExcludedFields, Raw, TemplateResponse); var BaseQuerySet = exports.BaseQuerySet = _stampit2.default.compose(QuerySetRequest, Raw, Fields, ExcludedFields, Ordering, First, PageSize, TemplateResponse); exports.default = QuerySet; /***/ }, /* 210 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(82), assignInDefaults = __webpack_require__(211), assignInWith = __webpack_require__(212), rest = __webpack_require__(81); /** * Assigns own and inherited enumerable properties of source objects to the * destination object for all destination properties that resolve to `undefined`. * Source objects are applied from left to right. Once a property is set, * additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); * // => { 'user': 'barney', 'age': 36 } */ var defaults = rest(function(args) { args.push(undefined, assignInDefaults); return apply(assignInWith, undefined, args); }); module.exports = defaults; /***/ }, /* 211 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(76); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used by `_.defaults` to customize its `_.assignIn` use. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function assignInDefaults(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } module.exports = assignInDefaults; /***/ }, /* 212 */ /***/ function(module, exports, __webpack_require__) { var copyObjectWith = __webpack_require__(78), createAssigner = __webpack_require__(79), keysIn = __webpack_require__(151); /** * This method is like `_.assignIn` except that it accepts `customizer` which * is invoked to produce the assigned values. If `customizer` returns `undefined` * assignment is handled by the method instead. The `customizer` is invoked * with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObjectWith(source, keysIn(source), object, customizer); }); module.exports = assignInWith; /***/ }, /* 213 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _reduce2 = __webpack_require__(198); var _reduce3 = _interopRequireDefault(_reduce2); var _isUndefined2 = __webpack_require__(214); var _isUndefined3 = _interopRequireDefault(_isUndefined2); var _includes2 = __webpack_require__(97); var _includes3 = _interopRequireDefault(_includes2); var _isEmpty2 = __webpack_require__(1); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _defaults2 = __webpack_require__(210); var _defaults3 = _interopRequireDefault(_defaults2); var _startsWith2 = __webpack_require__(215); var _startsWith3 = _interopRequireDefault(_startsWith2); var _isString2 = __webpack_require__(12); var _isString3 = _interopRequireDefault(_isString2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _bluebird = __webpack_require__(204); var _bluebird2 = _interopRequireDefault(_bluebird); var _superagent = __webpack_require__(217); var _superagent2 = _interopRequireDefault(_superagent); var _utils = __webpack_require__(223); var _errors = __webpack_require__(229); var _file = __webpack_require__(230); var _file2 = _interopRequireDefault(_file); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var IS_NODE = typeof module !== 'undefined' && module.exports && typeof __webpack_require__ === 'undefined'; /** * Base request object **not** meant to be used directly more like mixin in other {@link https://github.com/stampit-org/stampit|stamps}. * @constructor * @type {Request} * @property {Object} _request * @property {Function} [_request.handler = superagent] * @property {Array} [_request.allowedMethods = ['GET', 'POST', 'DELETE', 'HEAD', 'PUT', 'PATCH']] * @example {@lang javascript} * var MyStamp = stampit().compose(Request); */ var Request = (0, _stampit2.default)().compose(_utils.ConfigMixin, _utils.Logger).refs({ _request: { handler: _superagent2.default, allowedMethods: ['GET', 'POST', 'DELETE', 'HEAD', 'PUT', 'PATCH'] } }).methods({ /** * Sets request handler, used for mocking. * @memberOf Request * @instance * @param {Function} handler * @returns {Request} */ setRequestHandler: function setRequestHandler(handler) { this._request.handler = handler; return this; }, /** * Gets request handler. * @memberOf Request * @instance * @returns {Function} */ getRequestHandler: function getRequestHandler() { return this._request.handler; }, /** * Builds full URL based on path. * @memberOf Request * @instance * @param {String} path path part of URL e.g: /v1.1/instances/ * @returns {String} */ buildUrl: function buildUrl(path) { var config = this.getConfig(); if (!(0, _isString3.default)(path)) { throw new Error('"path" needs to be a string.'); } if ((0, _startsWith3.default)(path, config.getBaseUrl())) { return path; } return '' + config.getBaseUrl() + path; }, /** * Wrapper around {@link http://visionmedia.github.io/superagent/|superagent} which validates and calls requests. * @memberOf Request * @instance * @param {String} methodName e.g GET, POST * @param {String} path e.g /v1.1/instances/ * @param {Object} requestOptions All options required to build request * @param {String} [requestOptions.type = 'json'] request type e.g form, json, png * @param {String} [requestOptions.accept = 'json'] request accept e.g form, json, png * @param {Number} [requestOptions.timeout = 15000] request timeout * @param {Object} [requestOptions.headers = {}] request headers * @param {Object} [requestOptions.query = {}] request query * @param {Object} [requestOptions.payload = {}] request payload * @returns {Promise} */ makeRequest: function makeRequest(methodName, path, requestOptions) { var _this = this; var config = this.getConfig(); var method = (methodName || '').toUpperCase(); var options = (0, _defaults3.default)({}, requestOptions, { type: 'json', accept: 'json', timeout: 15000, headers: {}, query: {}, payload: {}, responseAttr: 'body' }); if ((0, _isEmpty3.default)(methodName) || !(0, _includes3.default)(this._request.allowedMethods, method)) { return _bluebird2.default.reject(new Error('Invalid request method: "' + methodName + '".')); } if ((0, _isEmpty3.default)(path)) { return _bluebird2.default.reject(new Error('"path" is required.')); } if (!(0, _isUndefined3.default)(config)) { if (!(0, _isEmpty3.default)(config.getAccountKey())) { options.headers['X-API-KEY'] = config.getAccountKey(); } // Yes, we will replace account key if (!(0, _isEmpty3.default)(config.getApiKey())) { options.headers['X-API-KEY'] = config.getApiKey(); } if (!(0, _isEmpty3.default)(config.getUserKey())) { options.headers['X-USER-KEY'] = config.getUserKey(); } if (!(0, _isEmpty3.default)(config.getSocialToken())) { options.headers['Authorization'] = 'Token ' + config.getSocialToken(); } } // Grab files var files = (0, _reduce3.default)(options.payload, function (result, value, key) { if (value instanceof _file2.default) { result[key] = value; } return result; }, {}); var handler = this.getRequestHandler(); var request = handler(method, this.buildUrl(path)).accept(options.accept).timeout(options.timeout).set(options.headers).query(options.query); if ((0, _isEmpty3.default)(files)) { request = request.type(options.type).send(options.payload); } else if (IS_NODE === false && typeof FormData !== 'undefined' && typeof File !== 'undefined') { options.type = null; options.payload = (0, _reduce3.default)(options.payload, function (formData, value, key) { formData.append(key, files[key] ? value.content : value); return formData; }, new FormData()); request = request.type(options.type).send(options.payload); } else if (IS_NODE === true) { request = (0, _reduce3.default)(options.payload, function (result, value, key) { return files[key] ? result.attach(key, value.content) : result.field(key, value); }, request.type('form')); } return _bluebird2.default.promisify(request.end, { context: request })().then(function (response) { if (!response.ok) { throw new _errors.RequestError({ response: response, status: response.status, message: 'Bad request' }); } return response[options.responseAttr]; }).catch(function (err) { if (err.status && err.response) { _this.log('\n' + method + ' ' + path + '\n' + JSON.stringify(options, null, 2) + '\n'); _this.log('Response ' + err.status + ':', err.errors); if (err.name !== 'RequestError') { throw new _errors.RequestError(err, err.response); } } throw err; }); } }).static({ /** * Sets request handler and returns new {@link https://github.com/stampit-org/stampit|stampit} object, used for mocking. * @memberOf Request * @static * @returns {stampit} */ setRequestHandler: function setRequestHandler(handler) { var _request = this.fixed.refs._request || {}; _request.handler = handler; return this.refs({ _request: _request }); }, /** * Sets request handler from {@link https://github.com/stampit-org/stampit|stampit} definition. * @memberOf Request * @static * @returns {Function} */ getRequestHandler: function getRequestHandler() { return this.fixed.refs._request.handler; } }); exports.default = Request; module.exports = exports['default']; /***/ }, /* 214 */ /***/ function(module, exports) { /** * Checks if `value` is `undefined`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } module.exports = isUndefined; /***/ }, /* 215 */ /***/ function(module, exports, __webpack_require__) { var baseClamp = __webpack_require__(216), toInteger = __webpack_require__(83), toString = __webpack_require__(90); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to search. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = baseClamp(toInteger(position), 0, string.length); return string.lastIndexOf(target, position) == position; } module.exports = startsWith; /***/ }, /* 216 */ /***/ function(module, exports) { /** * The base implementation of `_.clamp` which doesn't coerce arguments to numbers. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } module.exports = baseClamp; /***/ }, /* 217 */ /***/ function(module, exports, __webpack_require__) { /** * Module dependencies. */ var Emitter = __webpack_require__(218); var reduce = __webpack_require__(219); var requestBase = __webpack_require__(220); var isObject = __webpack_require__(221); /** * Root reference for iframes. */ var root; if (typeof window !== 'undefined') { // Browser window root = window; } else if (typeof self !== 'undefined') { // Web Worker root = self; } else { // Other environments root = this; } /** * Noop. */ function noop(){}; /** * Check if `obj` is a host object, * we don't want to serialize these :) * * TODO: future proof, move to compoent land * * @param {Object} obj * @return {Boolean} * @api private */ function isHost(obj) { var str = {}.toString.call(obj); switch (str) { case '[object File]': case '[object Blob]': case '[object FormData]': return true; default: return false; } } /** * Expose `request`. */ var request = module.exports = __webpack_require__(222).bind(null, Request); /** * Determine XHR. */ request.getXHR = function () { if (root.XMLHttpRequest && (!root.location || 'file:' != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest; } else { try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} } return false; }; /** * Removes leading and trailing whitespace, added to support IE. * * @param {String} s * @return {String} * @api private */ var trim = ''.trim ? function(s) { return s.trim(); } : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; /** * Serialize the given `obj`. * * @param {Object} obj * @return {String} * @api private */ function serialize(obj) { if (!isObject(obj)) return obj; var pairs = []; for (var key in obj) { if (null != obj[key]) { pushEncodedKeyValuePair(pairs, key, obj[key]); } } return pairs.join('&'); } /** * Helps 'serialize' with serializing arrays. * Mutates the pairs array. * * @param {Array} pairs * @param {String} key * @param {Mixed} val */ function pushEncodedKeyValuePair(pairs, key, val) { if (Array.isArray(val)) { return val.forEach(function(v) { pushEncodedKeyValuePair(pairs, key, v); }); } pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); } /** * Expose serialization method. */ request.serializeObject = serialize; /** * Parse the given x-www-form-urlencoded `str`. * * @param {String} str * @return {Object} * @api private */ function parseString(str) { var obj = {}; var pairs = str.split('&'); var parts; var pair; for (var i = 0, len = pairs.length; i < len; ++i) { pair = pairs[i]; parts = pair.split('='); obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); } return obj; } /** * Expose parser. */ request.parseString = parseString; /** * Default MIME type map. * * superagent.types.xml = 'application/xml'; * */ request.types = { html: 'text/html', json: 'application/json', xml: 'application/xml', urlencoded: 'application/x-www-form-urlencoded', 'form': 'application/x-www-form-urlencoded', 'form-data': 'application/x-www-form-urlencoded' }; /** * Default serialization map. * * superagent.serialize['application/xml'] = function(obj){ * return 'generated xml here'; * }; * */ request.serialize = { 'application/x-www-form-urlencoded': serialize, 'application/json': JSON.stringify }; /** * Default parsers. * * superagent.parse['application/xml'] = function(str){ * return { object parsed from str }; * }; * */ request.parse = { 'application/x-www-form-urlencoded': parseString, 'application/json': JSON.parse }; /** * Parse the given header `str` into * an object containing the mapped fields. * * @param {String} str * @return {Object} * @api private */ function parseHeader(str) { var lines = str.split(/\r?\n/); var fields = {}; var index; var line; var field; var val; lines.pop(); // trailing CRLF for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i]; index = line.indexOf(':'); field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val; } return fields; } /** * Check if `mime` is json or has +json structured syntax suffix. * * @param {String} mime * @return {Boolean} * @api private */ function isJSON(mime) { return /[\/+]json\b/.test(mime); } /** * Return the mime type for the given `str`. * * @param {String} str * @return {String} * @api private */ function type(str){ return str.split(/ *; */).shift(); }; /** * Return header field parameters. * * @param {String} str * @return {Object} * @api private */ function params(str){ return reduce(str.split(/ *; */), function(obj, str){ var parts = str.split(/ *= */) , key = parts.shift() , val = parts.shift(); if (key && val) obj[key] = val; return obj; }, {}); }; /** * Initialize a new `Response` with the given `xhr`. * * - set flags (.ok, .error, etc) * - parse header * * Examples: * * Aliasing `superagent` as `request` is nice: * * request = superagent; * * We can use the promise-like API, or pass callbacks: * * request.get('/').end(function(res){}); * request.get('/', function(res){}); * * Sending data can be chained: * * request * .post('/user') * .send({ name: 'tj' }) * .end(function(res){}); * * Or passed to `.send()`: * * request * .post('/user') * .send({ name: 'tj' }, function(res){}); * * Or passed to `.post()`: * * request * .post('/user', { name: 'tj' }) * .end(function(res){}); * * Or further reduced to a single call for simple cases: * * request * .post('/user', { name: 'tj' }, function(res){}); * * @param {XMLHTTPRequest} xhr * @param {Object} options * @api private */ function Response(req, options) { options = options || {}; this.req = req; this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') ? this.xhr.responseText : null; this.statusText = this.req.xhr.statusText; this.setStatusProperties(this.xhr.status); this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but // getResponseHeader still works. so we get content-type even if getting // other headers fails. this.header['content-type'] = this.xhr.getResponseHeader('content-type'); this.setHeaderProperties(this.header); this.body = this.req.method != 'HEAD' ? this.parseBody(this.text ? this.text : this.xhr.response) : null; } /** * Get case-insensitive `field` value. * * @param {String} field * @return {String} * @api public */ Response.prototype.get = function(field){ return this.header[field.toLowerCase()]; }; /** * Set header related properties: * * - `.type` the content type without params * * A response of "Content-Type: text/plain; charset=utf-8" * will provide you with a `.type` of "text/plain". * * @param {Object} header * @api private */ Response.prototype.setHeaderProperties = function(header){ // content-type var ct = this.header['content-type'] || ''; this.type = type(ct); // params var obj = params(ct); for (var key in obj) this[key] = obj[key]; }; /** * Parse the given body `str`. * * Used for auto-parsing of bodies. Parsers * are defined on the `superagent.parse` object. * * @param {String} str * @return {Mixed} * @api private */ Response.prototype.parseBody = function(str){ var parse = request.parse[this.type]; if (!parse && isJSON(this.type)) { parse = request.parse['application/json']; } return parse && str && (str.length || str instanceof Object) ? parse(str) : null; }; /** * Set flags such as `.ok` based on `status`. * * For example a 2xx response will give you a `.ok` of __true__ * whereas 5xx will be __false__ and `.error` will be __true__. The * `.clientError` and `.serverError` are also available to be more * specific, and `.statusType` is the class of error ranging from 1..5 * sometimes useful for mapping respond colors etc. * * "sugar" properties are also defined for common cases. Currently providing: * * - .noContent * - .badRequest * - .unauthorized * - .notAcceptable * - .notFound * * @param {Number} status * @api private */ Response.prototype.setStatusProperties = function(status){ // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request if (status === 1223) { status = 204; } var type = status / 100 | 0; // status / class this.status = this.statusCode = status; this.statusType = type; // basics this.info = 1 == type; this.ok = 2 == type; this.clientError = 4 == type; this.serverError = 5 == type; this.error = (4 == type || 5 == type) ? this.toError() : false; // sugar this.accepted = 202 == status; this.noContent = 204 == status; this.badRequest = 400 == status; this.unauthorized = 401 == status; this.notAcceptable = 406 == status; this.notFound = 404 == status; this.forbidden = 403 == status; }; /** * Return an `Error` representative of this response. * * @return {Error} * @api public */ Response.prototype.toError = function(){ var req = this.req; var method = req.method; var url = req.url; var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; var err = new Error(msg); err.status = this.status; err.method = method; err.url = url; return err; }; /** * Expose `Response`. */ request.Response = Response; /** * Initialize a new `Request` with the given `method` and `url`. * * @param {String} method * @param {String} url * @api public */ function Request(method, url) { var self = this; this._query = this._query || []; this.method = method; this.url = url; this.header = {}; // preserves header name case this._header = {}; // coerces header names to lowercase this.on('end', function(){ var err = null; var res = null; try { res = new Response(self); } catch(e) { err = new Error('Parser is unable to parse the response'); err.parse = true; err.original = e; // issue #675: return the raw response if the response parsing fails err.rawResponse = self.xhr && self.xhr.responseText ? self.xhr.responseText : null; // issue #876: return the http status code if the response parsing fails err.statusCode = self.xhr && self.xhr.status ? self.xhr.status : null; return self.callback(err); } self.emit('response', res); if (err) { return self.callback(err, res); } if (res.status >= 200 && res.status < 300) { return self.callback(err, res); } var new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); new_err.original = err; new_err.response = res; new_err.status = res.status; self.callback(new_err, res); }); } /** * Mixin `Emitter` and `requestBase`. */ Emitter(Request.prototype); for (var key in requestBase) { Request.prototype[key] = requestBase[key]; } /** * Abort the request, and clear potential timeout. * * @return {Request} * @api public */ Request.prototype.abort = function(){ if (this.aborted) return; this.aborted = true; this.xhr.abort(); this.clearTimeout(); this.emit('abort'); return this; }; /** * Set Content-Type to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.xml = 'application/xml'; * * request.post('/') * .type('xml') * .send(xmlstring) * .end(callback); * * request.post('/') * .type('application/xml') * .send(xmlstring) * .end(callback); * * @param {String} type * @return {Request} for chaining * @api public */ Request.prototype.type = function(type){ this.set('Content-Type', request.types[type] || type); return this; }; /** * Set responseType to `val`. Presently valid responseTypes are 'blob' and * 'arraybuffer'. * * Examples: * * req.get('/') * .responseType('blob') * .end(callback); * * @param {String} val * @return {Request} for chaining * @api public */ Request.prototype.responseType = function(val){ this._responseType = val; return this; }; /** * Set Accept to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.json = 'application/json'; * * request.get('/agent') * .accept('json') * .end(callback); * * request.get('/agent') * .accept('application/json') * .end(callback); * * @param {String} accept * @return {Request} for chaining * @api public */ Request.prototype.accept = function(type){ this.set('Accept', request.types[type] || type); return this; }; /** * Set Authorization field value with `user` and `pass`. * * @param {String} user * @param {String} pass * @param {Object} options with 'type' property 'auto' or 'basic' (default 'basic') * @return {Request} for chaining * @api public */ Request.prototype.auth = function(user, pass, options){ if (!options) { options = { type: 'basic' } } switch (options.type) { case 'basic': var str = btoa(user + ':' + pass); this.set('Authorization', 'Basic ' + str); break; case 'auto': this.username = user; this.password = pass; break; } return this; }; /** * Add query-string `val`. * * Examples: * * request.get('/shoes') * .query('size=10') * .query({ color: 'blue' }) * * @param {Object|String} val * @return {Request} for chaining * @api public */ Request.prototype.query = function(val){ if ('string' != typeof val) val = serialize(val); if (val) this._query.push(val); return this; }; /** * Queue the given `file` as an attachment to the specified `field`, * with optional `filename`. * * ``` js * request.post('/upload') * .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"})) * .end(callback); * ``` * * @param {String} field * @param {Blob|File} file * @param {String} filename * @return {Request} for chaining * @api public */ Request.prototype.attach = function(field, file, filename){ this._getFormData().append(field, file, filename || file.name); return this; }; Request.prototype._getFormData = function(){ if (!this._formData) { this._formData = new root.FormData(); } return this._formData; }; /** * Send `data` as the request body, defaulting the `.type()` to "json" when * an object is given. * * Examples: * * // manual json * request.post('/user') * .type('json') * .send('{"name":"tj"}') * .end(callback) * * // auto json * request.post('/user') * .send({ name: 'tj' }) * .end(callback) * * // manual x-www-form-urlencoded * request.post('/user') * .type('form') * .send('name=tj') * .end(callback) * * // auto x-www-form-urlencoded * request.post('/user') * .type('form') * .send({ name: 'tj' }) * .end(callback) * * // defaults to x-www-form-urlencoded * request.post('/user') * .send('name=tobi') * .send('species=ferret') * .end(callback) * * @param {String|Object} data * @return {Request} for chaining * @api public */ Request.prototype.send = function(data){ var obj = isObject(data); var type = this._header['content-type']; // merge if (obj && isObject(this._data)) { for (var key in data) { this._data[key] = data[key]; } } else if ('string' == typeof data) { if (!type) this.type('form'); type = this._header['content-type']; if ('application/x-www-form-urlencoded' == type) { this._data = this._data ? this._data + '&' + data : data; } else { this._data = (this._data || '') + data; } } else { this._data = data; } if (!obj || isHost(data)) return this; if (!type) this.type('json'); return this; }; /** * @deprecated */ Response.prototype.parse = function serialize(fn){ if (root.console) { console.warn("Client-side parse() method has been renamed to serialize(). This method is not compatible with superagent v2.0"); } this.serialize(fn); return this; }; Response.prototype.serialize = function serialize(fn){ this._parser = fn; return this; }; /** * Invoke the callback with `err` and `res` * and handle arity check. * * @param {Error} err * @param {Response} res * @api private */ Request.prototype.callback = function(err, res){ var fn = this._callback; this.clearTimeout(); fn(err, res); }; /** * Invoke callback with x-domain error. * * @api private */ Request.prototype.crossDomainError = function(){ var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); err.crossDomain = true; err.status = this.status; err.method = this.method; err.url = this.url; this.callback(err); }; /** * Invoke callback with timeout error. * * @api private */ Request.prototype.timeoutError = function(){ var timeout = this._timeout; var err = new Error('timeout of ' + timeout + 'ms exceeded'); err.timeout = timeout; this.callback(err); }; /** * Enable transmission of cookies with x-domain requests. * * Note that for this to work the origin must not be * using "Access-Control-Allow-Origin" with a wildcard, * and also must set "Access-Control-Allow-Credentials" * to "true". * * @api public */ Request.prototype.withCredentials = function(){ this._withCredentials = true; return this; }; /** * Initiate request, invoking callback `fn(res)` * with an instanceof `Response`. * * @param {Function} fn * @return {Request} for chaining * @api public */ Request.prototype.end = function(fn){ var self = this; var xhr = this.xhr = request.getXHR(); var query = this._query.join('&'); var timeout = this._timeout; var data = this._formData || this._data; // store callback this._callback = fn || noop; // state change xhr.onreadystatechange = function(){ if (4 != xhr.readyState) return; // In IE9, reads to any property (e.g. status) off of an aborted XHR will // result in the error "Could not complete the operation due to error c00c023f" var status; try { status = xhr.status } catch(e) { status = 0; } if (0 == status) { if (self.timedout) return self.timeoutError(); if (self.aborted) return; return self.crossDomainError(); } self.emit('end'); }; // progress var handleProgress = function(e){ if (e.total > 0) { e.percent = e.loaded / e.total * 100; } e.direction = 'download'; self.emit('progress', e); }; if (this.hasListeners('progress')) { xhr.onprogress = handleProgress; } try { if (xhr.upload && this.hasListeners('progress')) { xhr.upload.onprogress = handleProgress; } } catch(e) { // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. // Reported here: // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context } // timeout if (timeout && !this._timer) { this._timer = setTimeout(function(){ self.timedout = true; self.abort(); }, timeout); } // querystring if (query) { query = request.serializeObject(query); this.url += ~this.url.indexOf('?') ? '&' + query : '?' + query; } // initiate request if (this.username && this.password) { xhr.open(this.method, this.url, true, this.username, this.password); } else { xhr.open(this.method, this.url, true); } // CORS if (this._withCredentials) xhr.withCredentials = true; // body if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) { // serialize stuff var contentType = this._header['content-type']; var serialize = this._parser || request.serialize[contentType ? contentType.split(';')[0] : '']; if (!serialize && isJSON(contentType)) serialize = request.serialize['application/json']; if (serialize) data = serialize(data); } // set header fields for (var field in this.header) { if (null == this.header[field]) continue; xhr.setRequestHeader(field, this.header[field]); } if (this._responseType) { xhr.responseType = this._responseType; } // send stuff this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) // We need null here if data is undefined xhr.send(typeof data !== 'undefined' ? data : null); return this; }; /** * Expose `Request`. */ request.Request = Request; /** * GET `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.get = function(url, data, fn){ var req = request('GET', url); if ('function' == typeof data) fn = data, data = null; if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * HEAD `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.head = function(url, data, fn){ var req = request('HEAD', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * DELETE `url` with optional callback `fn(res)`. * * @param {String} url * @param {Function} fn * @return {Request} * @api public */ function del(url, fn){ var req = request('DELETE', url); if (fn) req.end(fn); return req; }; request['del'] = del; request['delete'] = del; /** * PATCH `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.patch = function(url, data, fn){ var req = request('PATCH', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * POST `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.post = function(url, data, fn){ var req = request('POST', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * PUT `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.put = function(url, data, fn){ var req = request('PUT', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /***/ }, /* 218 */ /***/ function(module, exports) { /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks['$' + event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; /***/ }, /* 219 */ /***/ function(module, exports) { /** * Reduce `arr` with `fn`. * * @param {Array} arr * @param {Function} fn * @param {Mixed} initial * * TODO: combatible error handling? */ module.exports = function(arr, fn, initial){ var idx = 0; var len = arr.length; var curr = arguments.length == 3 ? initial : arr[idx++]; while (idx < len) { curr = fn.call(null, curr, arr[idx], ++idx, arr); } return curr; }; /***/ }, /* 220 */ /***/ function(module, exports, __webpack_require__) { /** * Module of mixed-in functions shared between node and client code */ var isObject = __webpack_require__(221); /** * Clear previous timeout. * * @return {Request} for chaining * @api public */ exports.clearTimeout = function _clearTimeout(){ this._timeout = 0; clearTimeout(this._timer); return this; }; /** * Force given parser * * Sets the body parser no matter type. * * @param {Function} * @api public */ exports.parse = function parse(fn){ this._parser = fn; return this; }; /** * Set timeout to `ms`. * * @param {Number} ms * @return {Request} for chaining * @api public */ exports.timeout = function timeout(ms){ this._timeout = ms; return this; }; /** * Faux promise support * * @param {Function} fulfill * @param {Function} reject * @return {Request} */ exports.then = function then(fulfill, reject) { return this.end(function(err, res) { err ? reject(err) : fulfill(res); }); } /** * Allow for extension */ exports.use = function use(fn) { fn(this); return this; } /** * Get request header `field`. * Case-insensitive. * * @param {String} field * @return {String} * @api public */ exports.get = function(field){ return this._header[field.toLowerCase()]; }; /** * Get case-insensitive header `field` value. * This is a deprecated internal API. Use `.get(field)` instead. * * (getHeader is no longer used internally by the superagent code base) * * @param {String} field * @return {String} * @api private * @deprecated */ exports.getHeader = exports.get; /** * Set header `field` to `val`, or multiple fields with one object. * Case-insensitive. * * Examples: * * req.get('/') * .set('Accept', 'application/json') * .set('X-API-Key', 'foobar') * .end(callback); * * req.get('/') * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) * .end(callback); * * @param {String|Object} field * @param {String} val * @return {Request} for chaining * @api public */ exports.set = function(field, val){ if (isObject(field)) { for (var key in field) { this.set(key, field[key]); } return this; } this._header[field.toLowerCase()] = val; this.header[field] = val; return this; }; /** * Remove header `field`. * Case-insensitive. * * Example: * * req.get('/') * .unset('User-Agent') * .end(callback); * * @param {String} field */ exports.unset = function(field){ delete this._header[field.toLowerCase()]; delete this.header[field]; return this; }; /** * Write the field `name` and `val` for "multipart/form-data" * request bodies. * * ``` js * request.post('/upload') * .field('foo', 'bar') * .end(callback); * ``` * * @param {String} name * @param {String|Blob|File|Buffer|fs.ReadStream} val * @return {Request} for chaining * @api public */ exports.field = function(name, val) { this._getFormData().append(name, val); return this; }; /***/ }, /* 221 */ /***/ function(module, exports) { /** * Check if `obj` is an object. * * @param {Object} obj * @return {Boolean} * @api private */ function isObject(obj) { return null != obj && 'object' == typeof obj; } module.exports = isObject; /***/ }, /* 222 */ /***/ function(module, exports) { // The node and browser modules expose versions of this with the // appropriate constructor function bound as first argument /** * Issue a request: * * Examples: * * request('GET', '/users').end(callback) * request('/users').end(callback) * request('/users', callback) * * @param {String} method * @param {String|Function} url or callback * @return {Request} * @api public */ function request(RequestConstructor, method, url) { // callback if ('function' == typeof url) { return new RequestConstructor('GET', method).end(url); } // url first if (2 == arguments.length) { return new RequestConstructor('GET', method); } return new RequestConstructor(method, url); } module.exports = request; /***/ }, /* 223 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Logger = exports.ConstraintsMixin = exports.MetaMixin = exports.ConfigMixin = exports.EventEmittable = undefined; var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _eventemitter = __webpack_require__(224); var _eventemitter2 = _interopRequireDefault(_eventemitter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Simple wrapper around `EventEmitter` * @constructor * @type {EventEmittable} * @example {@lang javascript} * var EmittableModel = stampit().compose(EventEmittable); */ var EventEmittable = exports.EventEmittable = _stampit2.default.convertConstructor(_eventemitter2.default); /** * Used as a manager for {@link Syncano} base object. **Not** meant to be used directly. * @constructor * @type {ConfigMixin} * @property {Syncano} _config private attribute which holds {@link Syncano} object * @example {@lang javascript} * var MyStamp = stampit().compose(ConfigMixin); */ var ConfigMixin = exports.ConfigMixin = (0, _stampit2.default)({ methods: { /** * Sets config. * @memberOf ConfigMixin * @instance * @param {Syncano} config instance of {@link Syncano} object * @returns {ConfigMixin} * @example {@lang javascript} * var MyStamp = stampit().compose(ConfigMixin); * var newObject = MyStamp().setConfig({}); */ setConfig: function setConfig(config) { this._config = config; return this; }, /** * Gets config. * @memberOf ConfigMixin * @instance * @returns {Syncano} * @example {@lang javascript} * var MyStamp = stampit().compose(ConfigMixin); * var config = MyStamp().getConfig(); */ getConfig: function getConfig() { return this._config; } }, static: { /** * Sets config and returns new {@link https://github.com/stampit-org/stampit|stampit} definition. * @memberOf ConfigMixin * @static * @param {Syncano} config instance of {@link Syncano} object * @returns {stampit} * @example {@lang javascript} * var MyStamp = stampit().compose(ConfigMixin).setConfig({}); */ setConfig: function setConfig(config) { return this.refs({ _config: config }); }, /** * Gets config from {@link https://github.com/stampit-org/stampit|stampit} definition. * @memberOf ConfigMixin * @static * @returns {Syncano} * @example {@lang javascript} * var config = stampit().compose(ConfigMixin).getConfig(); */ getConfig: function getConfig() { return this.fixed.refs._config; } } }); /** * Used as a manager for {@link Meta} object. **Not** meant to be used directly. * @constructor * @type {MetaMixin} * @property {Object} _meta private attribute which holds {@link Meta} object * @example {@lang javascript} * var MyStamp = stampit().compose(MetaMixin); */ var MetaMixin = exports.MetaMixin = (0, _stampit2.default)({ methods: { /** * Sets meta. * @memberOf MetaMixin * @instance * @param {Meta} meta instance of {@link Meta} object * @returns {MetaMixin} * @example {@lang javascript} * var MyStamp = stampit().compose(MetaMixin); * var newObject = MyStamp().setMeta({}); */ setMeta: function setMeta(meta) { this._meta = meta; return this; }, /** * Gets meta. * @memberOf MetaMixin * @instance * @returns {Meta} * @example {@lang javascript} * var MyStamp = stampit().compose(MetaMixin); * var meta = MyStamp().getMeta(); */ getMeta: function getMeta() { return this._meta; } }, static: { /** * Sets meta and returns new {@link https://github.com/stampit-org/stampit|stampit} definition. * @memberOf MetaMixin * @static * @param {Meta} meta instance of {@link Meta} object * @returns {stampit} * @example {@lang javascript} * var MyStamp = stampit().compose(MetaMixin).setMeta({}); */ setMeta: function setMeta(meta) { return this.refs({ _meta: meta }); }, /** * Gets meta from {@link https://github.com/stampit-org/stampit|stampit} definition. * @memberOf MetaMixin * @static * @returns {Meta} * @example {@lang javascript} * var meta = stampit().compose(MetaMixin).getMeta(); */ getMeta: function getMeta() { return this.fixed.refs._meta; } } }); /** * Used as a manager for {@link http://validatejs.org/#constraints|Constraints} object (validation). **Not** meant to be used directly. * @constructor * @type {ConstraintsMixin} * @property {Object} _constraints private attribute which holds constraints object * @example {@lang javascript} * var MyStamp = stampit().compose(ConstraintsMixin); */ var ConstraintsMixin = exports.ConstraintsMixin = (0, _stampit2.default)({ methods: { /** * Sets constraints used for validation. * @memberOf ConstraintsMixin * @instance * @param {Object} constraints plain JavaScript object * @returns {ConstraintsMixin} * @example {@lang javascript} * var MyStamp = stampit().compose(ConstraintsMixin); * var newObject = MyStamp().setConstraints({}); */ setConstraints: function setConstraints(constraints) { this._constraints = constraints; return this; }, /** * Gets constraints from object instance. * @memberOf ConstraintsMixin * @instance * @returns {Object} * @example {@lang javascript} * var MyStamp = stampit().compose(ConstraintsMixinn); * var constraints = MyStamp().getConstraints(); */ getConstraints: function getConstraints() { return this._constraints; } }, static: { /** * Sets constraints in {@link https://github.com/stampit-org/stampit|stampit} definition used for validation. * @memberOf ConstraintsMixin * @static * @param {Object} constraints plain JavaScript object * @returns {stampit} * @example {@lang javascript} * var MyStamp = stampit().compose(ConstraintsMixin).setConstraints({}); */ setConstraints: function setConstraints(constraints) { return this.refs({ _constraints: constraints }); }, /** * Gets constraints from {@link https://github.com/stampit-org/stampit|stampit} definition. * @memberOf ConstraintsMixin * @static * @returns {Object} * @example {@lang javascript} * var constraints = stampit().compose(ConstraintsMixin).getConstraints(); */ getConstraints: function getConstraints() { return this.fixed.refs._constraints; } } }); /** * Adds logging functionality. * @constructor * @type {Logger} * @example {@lang javascript} * var MyStamp = stampit().compose(Logger); */ var Logger = exports.Logger = (0, _stampit2.default)({ methods: { /** * Wrapper around *console.log*. * @memberOf Logger * @instance */ log: function log() { var env = undefined || 'test'; if (env === 'development') { var _console; /* eslint-disable no-console */ (_console = console).log.apply(_console, arguments); /* eslint-enable no-console */ } } } }); /***/ }, /* 224 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _forEach2 = __webpack_require__(13); var _forEach3 = _interopRequireDefault(_forEach2); var _pull2 = __webpack_require__(225); var _pull3 = _interopRequireDefault(_pull2); var _isArray2 = __webpack_require__(11); var _isArray3 = _interopRequireDefault(_isArray2); exports.default = EventEmitter; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * A simple implementation of an EventEmitter. Created for compatibility with environments that don't have access to native node modules (like React Native). Not meant to be used on it's own. */ function EventEmitter() { this.events = {}; } EventEmitter.prototype.on = function (event, listener) { if (!(0, _isArray3.default)(this.events[event])) { this.events[event] = []; } this.events[event].push(listener); }; EventEmitter.prototype.removeListener = function (event, listener) { if ((0, _isArray3.default)(this.events[event])) { (0, _pull3.default)(this.events[event], listener); } }; EventEmitter.prototype.emit = function (event) { var _this = this, _arguments = arguments; if ((0, _isArray3.default)(this.events[event])) { (function () { var listeners = _this.events[event].slice(); var args = [].slice.call(_arguments, 1); (0, _forEach3.default)(listeners, function (listener) { return listener.apply(_this, args); }); })(); } }; module.exports = exports['default']; /***/ }, /* 225 */ /***/ function(module, exports, __webpack_require__) { var pullAll = __webpack_require__(226), rest = __webpack_require__(81); /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3, 1, 2, 3]; * * _.pull(array, 2, 3); * console.log(array); * // => [1, 1] */ var pull = rest(pullAll); module.exports = pull; /***/ }, /* 226 */ /***/ function(module, exports, __webpack_require__) { var basePullAll = __webpack_require__(227); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3, 1, 2, 3]; * * _.pullAll(array, [2, 3]); * console.log(array); * // => [1, 1] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } module.exports = pullAll; /***/ }, /* 227 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(102), baseIndexOf = __webpack_require__(98), baseIndexOfWith = __webpack_require__(228), baseUnary = __webpack_require__(146); /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } module.exports = basePullAll; /***/ }, /* 228 */ /***/ function(module, exports) { /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } module.exports = baseIndexOfWith; /***/ }, /* 229 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(1); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _isArray2 = __webpack_require__(11); var _isArray3 = _interopRequireDefault(_isArray2); var _reduce2 = __webpack_require__(198); var _reduce3 = _interopRequireDefault(_reduce2); var _isObject2 = __webpack_require__(8); var _isObject3 = _interopRequireDefault(_isObject2); var _map2 = __webpack_require__(159); var _map3 = _interopRequireDefault(_map2); exports.SyncanoError = SyncanoError; exports.PaginationError = PaginationError; exports.ValidationError = ValidationError; exports.RequestError = RequestError; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function SyncanoError(message) { this.name = 'SyncanoError'; this.message = message || ''; this.stack = new Error().stack; } // something is wrong with babel6 in terms of error inheritance // so for now we will use almost plain js here SyncanoError.prototype = Object.create(Error.prototype); SyncanoError.prototype.constructor = SyncanoError; function PaginationError(message) { this.name = 'PaginationError'; this.message = message || ''; this.stack = new Error().stack; } PaginationError.prototype = Object.create(SyncanoError.prototype); PaginationError.prototype.constructor = SyncanoError; function ValidationError() { var errors = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.name = 'ValidationError'; this.stack = new Error().stack; this.errors = errors; this.message = (0, _map3.default)(errors, function (value, key) { return '"' + key + '" ' + value.join(', '); }).join('\n'); } ValidationError.prototype = Object.create(SyncanoError.prototype); ValidationError.prototype.constructor = ValidationError; function RequestError(error) { var _this = this; this.name = 'RequestError'; this.status = error.status; this.errors = error.response.body; this.originalError = error; this.response = error.response; this.message = ''; this.stack = new Error().stack; if ((0, _isObject3.default)(this.errors)) { this.message = (0, _reduce3.default)(['detail', 'error', '__all__', 'non_field_errors'], function (result, value) { var error = _this.errors[value]; if ((0, _isArray3.default)(error)) { error = error.join(', '); } result += error || ''; return result; }, this.message); if ((0, _isEmpty3.default)(this.message)) { this.message = (0, _map3.default)(this.errors, function (value, key) { if ((0, _isArray3.default)(value)) { value = value.join(', '); } return '"' + key + '" ' + value; }).join('\n'); } } if ((0, _isEmpty3.default)(this.message)) { this.message = error.message; } } RequestError.prototype = Object.create(SyncanoError.prototype); RequestError.prototype.constructor = RequestError; /***/ }, /* 230 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var SyncanoFile = function SyncanoFile(content) { _classCallCheck(this, SyncanoFile); this.content = content; }; exports.default = SyncanoFile; module.exports = exports['default']; /***/ }, /* 231 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ClassMeta = (0, _base.Meta)({ name: 'class', pluralName: 'classes', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/classes/{name}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/classes/' } }, relatedModels: ['DataObject'] }); var ClassConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, name: { presence: true, string: true }, description: { string: true }, schema: { object: true }, group: { numericality: { noStrings: true } }, group_permissions: { inclusion: ['none', 'read', 'create_objects'] }, other_permissions: { inclusion: ['none', 'read', 'create_objects'] }, metadata: { object: true } }; /** * OO wrapper around instance groups {@link http://docs.syncano.com/v4.0/docs/instancesinstanceclasses endpoint}. * @constructor * @type {Class} * @property {String} name * @property {String} instanceName * @property {Number} objects_count * @property {Array} schema * @property {String} status * @property {Object} metadata * @property {String} revision * @property {String} expected_revision * @property {String} group * @property {String} group_permissions * @property {String} other_permissions * @property {String} [description = null] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var Class = (0, _stampit2.default)().compose(_base.Model).setMeta(ClassMeta).setConstraints(ClassConstraints); exports.default = Class; module.exports = exports['default']; /***/ }, /* 232 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ChannelPoll = undefined; var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _request = __webpack_require__(213); var _request2 = _interopRequireDefault(_request); var _utils = __webpack_require__(223); var _querySet = __webpack_require__(209); var _querySet2 = _interopRequireDefault(_querySet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ChannelQuerySet = (0, _stampit2.default)().compose(_querySet2.default).methods({ /** * Puslishes to a channel. * @memberOf QuerySet * @instance * @param {Object} channel * @param {Object} message * @param {String} [room = null] * @returns {QuerySet} * @example {@lang javascript} * Channel.please().publish({ instanceName: 'test-instace', name: 'test-class' }, { content: 'my message'}); */ publish: function publish(properties, message) { var room = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.payload = { payload: JSON.stringify(message) }; if (room) { this.payload.room = room; } this.method = 'POST'; this.endpoint = 'publish'; return this; }, /** * Allows polling of a channel. * @memberOf QuerySet * @instance * @param {Object} options * @param {Boolean} [start = true] * @returns {ChannelPoll} * @example {@lang javascript} * var poll = Channel.please().poll({ instanceName: 'test-instace', name: 'test-class' }); * * poll.on('start', function() { * console.log('poll::start'); * }); * * poll.on('stop', function() { * console.log('poll::stop'); * }); * * poll.on('message', function(message) { * console.log('poll::message', message); * }); * * poll.on('custom', function(message) { * console.log('poll::custom', message); * }); * * poll.on('create', function(data) { * console.log('poll::create', data); * }); * * poll.on('delete', function(data) { * console.log('poll::delete', data); * }); * * poll.on('update', function(data) { * console.log('poll::update', data); * }); * * poll.on('error', function(error) { * console.log('poll::error', error); * }); * * poll.start(); * */ poll: function poll() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var start = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2]; this.properties = (0, _assign3.default)({}, this.properties, properties); var config = this.getConfig(); var meta = this.model.getMeta(); var path = meta.resolveEndpointPath('poll', this.properties); options.path = path; var channelPoll = ChannelPoll.setConfig(config)(options); if (start === true) { channelPoll.start(); } return channelPoll; }, history: function history() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var query = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'GET'; this.endpoint = 'history'; this.query = query; this._serialize = false; return this; } }); var ChannelMeta = (0, _base.Meta)({ name: 'channel', pluralName: 'channels', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/channels/{name}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/channels/' }, 'poll': { 'methods': ['get'], 'path': '/v1.1/instances/{instanceName}/channels/{name}/poll/' }, 'publish': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/channels/{name}/publish/' }, 'history': { 'methods': ['get'], 'path': '/v1.1/instances/{instanceName}/channels/{name}/history/' } } }); var channelConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, name: { presence: true, string: true, length: { minimum: 5 } }, description: { string: true }, type: { inclusion: ['default', 'seperate_rooms'] }, group: { numericality: { noStrings: true } }, group_permissions: { inclusion: ['none', 'subscribe', 'publish'] }, other_permissions: { inclusion: ['none', 'subscribe', 'publish'] }, custom_publish: { boolean: true } }; /** * Wrapper around {@link http://docs.syncano.io/v0.1/docs/channels-poll|channels poll} endpoint which implements `EventEmitter` interface. * Use it via `Channel` poll method. * @constructor * @type {ChannelPoll} * @property {Number} [timeout = 300000] 5 mins * @property {String} [path = null] request path * @property {Number} [lastId = null] used internally in for loop * @property {Number} [room = null] * @property {Boolean} [abort = false] used internally to conrole for loop * @example {@lang javascript} * var poll = ChannelPoll.setConfig(config)({ * path: '/v1.1/instances/some-instance/channels/some-channel/poll/' * }); * * poll.on('start', function() { * console.log('poll::start'); * }); * * poll.on('stop', function() { * console.log('poll::stop'); * }); * * poll.on('message', function(message) { * console.log('poll::message', message); * }); * * poll.on('custom', function(message) { * console.log('poll::custom', message); * }); * * poll.on('create', function(data) { * console.log('poll::create', data); * }); * * poll.on('delete', function(data) { * console.log('poll::delete', data); * }); * * poll.on('update', function(data) { * console.log('poll::update', data); * }); * * poll.on('error', function(error) { * console.log('poll::error', error); * }); * * poll.start(); * */ var ChannelPoll = exports.ChannelPoll = (0, _stampit2.default)().compose(_request2.default, _utils.EventEmittable).props({ timeout: 1000 * 60 * 5, path: null, lastId: null, room: null, abort: false }).methods({ request: function request() { var options = { timeout: this.timeout, query: { last_id: this.lastId, room: this.room } }; this.emit('request', options); return this.makeRequest('GET', this.path, options); }, start: function start() { var _this = this; this.emit('start'); // some kind of while loop which uses Promises var loop = function loop() { if (_this.abort === true) { _this.emit('stop'); return; } return _this.request().then(function (message) { _this.emit('message', message); _this.emit(message.action, message); _this.lastId = message.id; return message; }).finally(loop).catch(function (error) { if (error.timeout && error.timeout === _this.timeout) { return _this.emit('timeout', error); } _this.emit('error', error); _this.stop(); }); }; process.nextTick(loop); return this.stop; }, stop: function stop() { this.abort = true; return this; } }); /** * OO wrapper around channels {@link http://docs.syncano.io/v0.1/docs/channels-list endpoint}. * **Channel** has two special methods called ``publish`` and ``poll``. First one will send message to the channel and second one will create {@link http://en.wikipedia.org/wiki/Push_technology#Long_polling long polling} connection which will listen for messages. * @constructor * @type {Channel} * @property {String} name * @property {String} instanceName * @property {String} type * @property {Number} [group = null] * @property {String} [group_permissions = null] * @property {String} [other_permissions = null] * @property {Boolean} [custom_publish = null] * @example {@lang javascript} * Channel.please().get('instance-name', 'channel-name').then((channel) => { * return channel.publish({x: 1}); * }); * * Channel.please().get('instance-name', 'channel-name').then((channel) => { * const poll = channel.poll(); * * poll.on('start', function() { * console.log('poll::start'); * }); * * poll.on('stop', function() { * console.log('poll::stop'); * }); * * poll.on('message', function(message) { * console.log('poll::message', message); * }); * * poll.on('custom', function(message) { * console.log('poll::custom', message); * }); * * poll.on('create', function(data) { * console.log('poll::create', data); * }); * * poll.on('delete', function(data) { * console.log('poll::delete', data); * }); * * poll.on('update', function(data) { * console.log('poll::update', data); * }); * * poll.on('error', function(error) { * console.log('poll::error', error); * }); * * poll.start(); * }); */ var Channel = (0, _stampit2.default)().compose(_base.Model).setMeta(ChannelMeta).setQuerySet(ChannelQuerySet).methods({ poll: function poll() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var start = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1]; var config = this.getConfig(); var meta = this.getMeta(); var path = meta.resolveEndpointPath('poll', this); options.path = path; var channelPoll = ChannelPoll.setConfig(config)(options); if (start === true) { channelPoll.start(); } return channelPoll; }, publish: function publish(message) { var room = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; var options = { payload: { payload: JSON.stringify(message) } }; var meta = this.getMeta(); var path = meta.resolveEndpointPath('publish', this); if (room !== null) { options.payload.room = room; } return this.makeRequest('POST', path, options); }, history: function history() { var query = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var meta = this.getMeta(); var path = meta.resolveEndpointPath('history', this); return this.makeRequest('GET', path, { query: query }); } }).setConstraints(channelConstraints); exports.default = Channel; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(205))) /***/ }, /* 233 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _add2 = __webpack_require__(234); var _add3 = _interopRequireDefault(_add2); var _isNumber2 = __webpack_require__(235); var _isNumber3 = _interopRequireDefault(_isNumber2); var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _keys2 = __webpack_require__(21); var _keys3 = _interopRequireDefault(_keys2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); var _querySet2 = _interopRequireDefault(_querySet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var DataObjectQuerySet = (0, _stampit2.default)().compose(_querySet2.default).methods({ /** * Filters DataObjects. * @memberOf QuerySet * @instance * @param {Object} filters * @returns {QuerySet} * @example {@lang javascript} * DataObject.please().list({ instanceName: 'test-instace', className: 'test-class' }).filter({ field_name: { _contains: 'Lord Of The Rings' }}).then(function(dataobjects) {}); */ filter: function filter() { var filters = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.query['query'] = JSON.stringify(filters); return this; }, /** * Orders DataObject by field. * @memberOf QuerySet * @instance * @param {String} field * @returns {QuerySet} * @example {@lang javascript} * DataObject.please().list({ instanceName: 'test-instace', className: 'test-class' }).orderBy('author').then(function(dataobjects) {}); * DataObject.please().list({ instanceName: 'test-instace', className: 'test-class' }).orderBy('-author').then(function(dataobjects) {}); */ orderBy: function orderBy(field) { this.query['order_by'] = field; return this; }, /** * Updates single object based on provided arguments * @memberOf QuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @param {Object} field to increment. * @returns {QuerySet} * @example {@lang javascript} * DataObject.please().increment({instanceName: 'my-instance', className: 'my-class', id: 1}, {views: 1}) */ increment: function increment() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var object = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var payload = {}; payload[(0, _keys3.default)(object)[0]] = { _increment: object[(0, _keys3.default)(object)[0]] }; this.properties = (0, _assign3.default)({}, this.properties, properties); this.payload = JSON.stringify(payload); this.method = 'PATCH'; this.endpoint = 'detail'; return this; }, /** * Returns DataObject count. * @memberOf QuerySet * @instance * @returns {QuerySet} * @example {@lang javascript} * DataObject.please().list({ instanceName: 'test-instace', className: 'test-class' }).count().then(function(response) {}); */ count: function count() { this.query['include_count'] = true; this.raw(); return this; } }); var DataObjectMeta = (0, _base.Meta)({ name: 'dataobject', pluralName: 'dataobjects', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'post', 'get'], 'path': '/v1.1/instances/{instanceName}/classes/{className}/objects/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/classes/{className}/objects/' } } }); var DataobjectConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, className: { presence: true, string: true }, owner: { numericality: { noStrings: true } }, owner_permissions: { inclusion: ['none', 'read', 'write', 'full'] }, group: { numericality: { noStrings: true } }, group_permissions: { inclusion: ['none', 'read', 'write', 'full'] }, other_permissions: { inclusion: ['none', 'read', 'write', 'full'] }, channel: { string: true }, channel_room: { string: true } }; /** * OO wrapper around instance data objects {@link http://docs.syncano.com/v4.0/docs/view-data-objects endpoint}. * This model is special because each instance will be **dynamically populated** with fields defined in related {@link Class} schema attribute. * @constructor * @type {DataObject} * @property {Number} id * @property {String} instanceName * @property {String} className * @property {Number} revision * @property {Number} [owner = null] * @property {String} [owner_permissions = null] * @property {Number} [group = null] * @property {String} [group_permissions = null] * @property {String} [other_permissions = null] * @property {String} [channel = null] * @property {String} [channel_room = null] * @property {String} [description = null] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var DataObject = (0, _stampit2.default)().compose(_base.Model).setMeta(DataObjectMeta).methods({ increment: function increment(field, by) { if (!(0, _isNumber3.default)(this[field])) throw new Error('The ' + field + ' is not numeric.'); if (!(0, _isNumber3.default)(by)) throw new Error('The provided value is not numeric.'); this[field] += (0, _add3.default)(this[field], by); return this.save(); } }).setQuerySet(DataObjectQuerySet).setConstraints(DataobjectConstraints); exports.default = DataObject; module.exports = exports['default']; /***/ }, /* 234 */ /***/ function(module, exports) { /** * Adds two numbers. * * @static * @memberOf _ * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ function add(augend, addend) { var result; if (augend === undefined && addend === undefined) { return 0; } if (augend !== undefined) { result = augend; } if (addend !== undefined) { result = result === undefined ? addend : (result + addend); } return result; } module.exports = add; /***/ }, /* 235 */ /***/ function(module, exports, __webpack_require__) { var isObjectLike = __webpack_require__(10); /** `Object#toString` result references. */ var numberTag = '[object Number]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified * as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && objectToString.call(value) == numberTag); } module.exports = isNumber; /***/ }, /* 236 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(1); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var UserQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Get, _querySet.Create, _querySet.BulkCreate, _querySet.List).methods({ getDetails: function getDetails() { var _this = this; var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var user = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties, user); this.method = 'GET'; this.endpoint = 'groupUser'; return this.then(function (response) { return _this.model.fromJSON(response.user, _this.properties); }); }, groupUsers: function groupUsers() { var _this2 = this; var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'GET'; this.endpoint = 'groupUsers'; return this.then(function (response) { return _this2.model.please().asResultSet(response, 'user'); }); }, addUserToGroup: function addUserToGroup() { var _this3 = this; var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var user = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.payload = user; this.method = 'POST'; this.endpoint = 'groupUsers'; return this.then(function (response) { return _this3.model.fromJSON(response.user, _this3.properties); }); }, deleteUserFromGroup: function deleteUserFromGroup() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var user = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties, user); this.payload = user; this.method = 'DELETE'; this.endpoint = 'groupUser'; return this; }, get: function get() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var config = this.getConfig(); this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'GET'; this.endpoint = 'detail'; if ((0, _isEmpty3.default)(config.getAccountKey()) && !(0, _isEmpty3.default)(config.getUserKey()) && !(0, _isEmpty3.default)(config.getApiKey())) { this.endpoint = 'user'; } return this; }, update: function update() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var object = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var config = this.getConfig(); this.properties = (0, _assign3.default)({}, this.properties, properties); this.payload = object; this.method = 'PATCH'; this.endpoint = 'detail'; if ((0, _isEmpty3.default)(config.getAccountKey()) && !(0, _isEmpty3.default)(config.getUserKey()) && !(0, _isEmpty3.default)(config.getApiKey())) { this.endpoint = 'user'; } return this; }, /** * Restes user key. * @memberOf UserQuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @returns {Promise} * @example {@lang javascript} * User.please().resetKey({id: 1, instanceName: 'test-one'}).then(function(user) {}); */ resetKey: function resetKey() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'POST'; this.endpoint = 'reset_key'; return this; }, /** * A convenience method for authenticating instance user with email and password. * @memberOf UserQuerySet * @instance * @param {Object} properties * @param {String} properties.instanceName * @param {Object} credentials * @param {String} credentials.email * @param {String} credentials.password * @returns {Promise} */ login: function login() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var credentials = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'POST'; this.endpoint = 'login'; this.payload = credentials; return this; }, /** * A convenience method for authenticating instance user with email and password. * @memberOf UserQuerySet * @instance * @param {Object} properties * @param {String} properties.instanceName * @param {String} properties.backend * @param {Object} credentials * @param {String} credentials.access_token * @returns {Promise} */ socialLogin: function socialLogin() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var credentials = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'POST'; this.endpoint = 'socialLogin'; this.payload = credentials; return this; } }); var UserMeta = (0, _base.Meta)({ name: 'user', pluralName: 'users', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/users/{id}/' }, 'reset_key': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/users/{id}/reset_key/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/users/' }, 'groups': { 'methods': ['get', 'post'], 'path': '/v1.1/instances/{instanceName}/users/{id}/groups/' }, 'login': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/user/auth/' }, 'socialLogin': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/user/auth/{backend}/' }, 'user': { 'methods': ['get', 'post', 'patch'], 'path': '/v1.1/instances/{instanceName}/user/' }, 'groupUsers': { 'methods': ['get', 'post'], 'path': '/v1.1/instances/{instanceName}/groups/{id}/users/' }, 'groupUser': { 'methods': ['get', 'delete'], 'path': '/v1.1/instances/{instanceName}/groups/{id}/users/{user}/' } } }); var UserConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, username: { presence: true, string: true }, password: { presence: true, string: true }, profile: { object: true }, 'profile.owner_permissions': { inclusion: ['none', 'read', 'write', 'full'] }, 'profile.group': { numericality: { noStrings: true } }, 'profile.group_permissions': { inclusion: ['none', 'read', 'write', 'full'] }, 'profile.other_permissions': { inclusion: ['none', 'read', 'write', 'full'] }, 'profile.channel': { string: true }, 'profile.channel_room': { string: true } }; /** * OO wrapper around instance users {@link http://docs.syncano.com/v4.0/docs/user-management endpoint}. * @constructor * @type {User} * @property {Number} id * @property {String} instanceName * @property {String} username * @property {String} password * @property {String} user_key * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var User = (0, _stampit2.default)().compose(_base.Model).setMeta(UserMeta).setQuerySet(UserQuerySet).setConstraints(UserConstraints).methods({ /** * Restes user key. * @memberOf User * @instance * @returns {Promise} * @example {@lang javascript} * User.please().get({instanceName: 'test-one', id: 1}).then(function(user) { * user.resetKey().then(function(user) {}); * }); */ resetKey: function resetKey() { var _this4 = this; var meta = this.getMeta(); var path = meta.resolveEndpointPath('reset_key', this); return this.makeRequest('POST', path, {}).then(function (body) { return _this4.serialize(body); }); } }); exports.default = User; module.exports = exports['default']; /***/ }, /* 237 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); var _querySet2 = _interopRequireDefault(_querySet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var GroupQuerySet = (0, _stampit2.default)().compose(_querySet2.default).methods({ /** * Fetches Users belonging to a group. * @memberOf GroupQuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @returns {GroupQuerySet} * @example {@lang javascript} * Grop.please().users({ id: 1, instanceName: 'test-one'}).then(function(users) {}); */ users: function users() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var _getConfig = this.getConfig(); var User = _getConfig.User; this.properties = (0, _assign3.default)({}, this.properties, properties); return User.please().groupUsers(this.properties); }, /** * Adds user to group. * @memberOf GroupQuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @param {Object} user object with user to be added * @returns {GroupQuerySet} * @example {@lang javascript} * Grop.please().addUser({ id: 1, instanceName: 'test-one'}, { user: 1 }).then(function(response) {}); */ addUser: function addUser() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var user = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _getConfig2 = this.getConfig(); var User = _getConfig2.User; this.properties = (0, _assign3.default)({}, this.properties, properties); return User.please().addUserToGroup(this.properties, user); }, /** * Deletes user from group. * @memberOf GroupQuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @param {Object} user object with user to be added * @returns {GroupQuerySet} * @example {@lang javascript} * Grop.please().deleteUser({ id: 1, instanceName: 'test-one'}, { user: 1 }).then(function(response) {}); */ deleteUser: function deleteUser() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var user = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _getConfig3 = this.getConfig(); var User = _getConfig3.User; this.properties = (0, _assign3.default)({}, this.properties, properties); return User.please().deleteUserFromGroup(this.properties, user); }, /** * Fetches details of a user belonging to a group. * @memberOf Group * @instance * @param {Object} properties lookup properties used for path resolving * @param {Object} user object with user to be fetched * @example {@lang javascript} * Group.please().getUserDetails({ user: 1}).then(function(response) {}); */ getUserDetails: function getUserDetails() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var user = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _getConfig4 = this.getConfig(); var User = _getConfig4.User; this.properties = (0, _assign3.default)({}, this.properties, properties); return User.please().getDetails(this.properties, user); } }); var GroupMeta = (0, _base.Meta)({ name: 'group', pluralName: 'groups', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/groups/{id}/' }, 'list': { 'methods': ['get'], 'path': '/v1.1/instances/{instanceName}/groups/' } } }); var GroupConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, label: { presence: true, string: true }, description: { string: true } }; /** * OO wrapper around instance groups {@link http://docs.syncano.com/v4.0/docs/groups endpoint}. * @constructor * @type {Group} * @property {Number} id * @property {String} instanceName * @property {String} label * @property {String} [description = null] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var Group = (0, _stampit2.default)().compose(_base.Model).setMeta(GroupMeta).setConstraints(GroupConstraints).setQuerySet(GroupQuerySet).methods({ /** * Fetches Users belonging to a group. * @memberOf Group * @instance * @returns {Promise} * @example {@lang javascript} * Group.users().then(function(users) {}); */ users: function users() { var _getConfig5 = this.getConfig(); var User = _getConfig5.User; return User.please().groupUsers({ id: this.id, instanceName: this.instanceName }); }, /** * Add user to group. * @memberOf Group * @instance * @returns {Promise} * @example {@lang javascript} * Group.addUser({ user: 1}).then(function(response) {}); */ addUser: function addUser() { var user = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var _getConfig6 = this.getConfig(); var User = _getConfig6.User; return User.please().addUserToGroup({ id: this.id, instanceName: this.instanceName }, user); }, /** * Delete user from group. * @memberOf Group * @instance * @returns {Promise} * @example {@lang javascript} * Group.deleteUser({ user: 1}).then(function(response) {}); */ deleteUser: function deleteUser() { var user = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var _getConfig7 = this.getConfig(); var User = _getConfig7.User; return User.please().deleteUserFromGroup({ id: this.id, instanceName: this.instanceName }, user); }, /** * Fetches details of a user belonging to a group. * @memberOf Group * @instance * @returns {Promise} * @example {@lang javascript} * Group.getUserDetails({ user: 1}).then(function(response) {}); */ getUserDetails: function getUserDetails() { var user = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var _getConfig8 = this.getConfig(); var User = _getConfig8.User; return User.please().getDetails({ id: this.id, instanceName: this.instanceName }, user); } }); exports.default = Group; module.exports = exports['default']; /***/ }, /* 238 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var AdminQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Get, _querySet.List); var AdminMeta = (0, _base.Meta)({ name: 'admin', pluralName: 'admins', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/admins/{id}/' }, 'list': { 'methods': ['get'], 'path': '/v1.1/instances/{instanceName}/admins/' } } }); /** * OO wrapper around instance admins {@link http://docs.syncano.com/v4.0/docs/v1instancesinstanceadmins endpoint}. * @constructor * @type {Admin} * @property {Number} id * @property {String} instanceName * @property {String} first_name * @property {String} last_name * @property {String} email * @property {String} role One of full, write and read. * @property {Object} [links = {}] */ var Admin = (0, _stampit2.default)().compose(_base.Model).setQuerySet(AdminQuerySet).setMeta(AdminMeta); exports.default = Admin; module.exports = exports['default']; /***/ }, /* 239 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ApiKeyQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Get, _querySet.Create, _querySet.BulkCreate, _querySet.Delete, _querySet.Update, _querySet.List).methods({ reset: function reset() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'POST'; this.endpoint = 'reset'; return this; } }); var ApiKeyMeta = (0, _base.Meta)({ name: 'apiKey', pluralName: 'apiKeys', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/api_keys/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/api_keys/' }, 'reset': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/api_keys/{id}/reset_key/' } } }); var ApiKeyConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, description: { string: true }, ignore_acl: { boolean: true }, allow_user_create: { boolean: true }, allow_anonymous_read: { boolean: true } }; /** * OO wrapper around instance api keys {@link http://docs.syncano.io/docs/authentication endpoint}. * @constructor * @type {ApiKey} * @property {Number} id * @property {String} instanceName * @property {String} [api_key = null] * @property {Boolean} [allow_user_create = null] * @property {Boolean} [ignore_acl = null] * @property {String} [links = {}] */ var ApiKey = (0, _stampit2.default)().compose(_base.Model).setMeta(ApiKeyMeta).methods({ reset: function reset() { var meta = this.getMeta(); var path = meta.resolveEndpointPath('reset', this); return this.makeRequest('POST', path); } }).setQuerySet(ApiKeyQuerySet).setConstraints(ApiKeyConstraints); exports.default = ApiKey; module.exports = exports['default']; /***/ }, /* 240 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var InstanceInvitationQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Create, _querySet.BulkCreate, _querySet.Get, _querySet.GetOrCreate, _querySet.Delete, _querySet.List, _querySet.Delete).methods({ resend: function resend() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'POST'; this.endpoint = 'resend'; return this; } }); var InstanceInvitationMeta = (0, _base.Meta)({ name: 'instanceInvitation', pluralName: 'instanceInvitations', endpoints: { 'detail': { 'methods': ['delete', 'get'], 'path': '/v1.1/instances/{instanceName}/invitations/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/invitations/' }, 'resend': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/invitations/{id}/resend/' } } }); var InstanceInvitationConstraints = { email: { presence: true, email: true }, role: { presence: true, inclusion: ['full', 'write', 'read'] }, instanceName: { presence: true, length: { minimum: 5 } } }; /** * OO wrapper around instance invitations {@link # endpoint}. * @constructor * @type {InstanceInvitation} * @property {String} email * @property {String} role * @property {String} [key = null] * @property {String} [inviter = null] * @property {String} [status = null] * @property {Number} [id = null] * @property {String} [description = null] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var InstanceInvitation = (0, _stampit2.default)().compose(_base.Model).setMeta(InstanceInvitationMeta).methods({ resend: function resend() { var meta = this.getMeta(); var path = meta.resolveEndpointPath('resend', this); return this.makeRequest('POST', path); } }).setQuerySet(InstanceInvitationQuerySet).setConstraints(InstanceInvitationConstraints); exports.default = InstanceInvitation; module.exports = exports['default']; /***/ }, /* 241 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var InvitationQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Create, _querySet.BulkCreate, _querySet.Get, _querySet.GetOrCreate, _querySet.Delete, _querySet.List, _querySet.Delete).methods({ accept: function accept(invitationKey) { this.method = 'POST'; this.endpoint = 'accept'; this.payload = { invitationKey: invitationKey }; this._serialize = false; return this; } }); var InvitationMeta = (0, _base.Meta)({ name: 'invitation', pluralName: 'invitations', endpoints: { 'detail': { 'methods': ['delete', 'get'], 'path': '/v1.1/account/invitations/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/account/invitations/' }, 'accept': { 'methods': ['post'], 'path': '/v1.1/account/invitations/accept/' } } }); /** * OO wrapper around invitations {@link # endpoint}. * @constructor * @type {Invitation} * @property {String} email * @property {String} role * @property {String} [key = null] * @property {String} [inviter = null] * @property {String} [status = null] * @property {Number} [id = null] * @property {String} [description = null] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var Invitation = (0, _stampit2.default)().compose(_base.Model).setMeta(InvitationMeta).setQuerySet(InvitationQuerySet).methods({ accept: function accept(invitationKey) { var meta = this.getMeta(); var path = meta.resolveEndpointPath('accept', this); return this.makeRequest('POST', path, { invitationKey: invitationKey }); } }); exports.default = Invitation; module.exports = exports['default']; /***/ }, /* 242 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); var _querySet2 = _interopRequireDefault(_querySet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ScriptQuerySet = (0, _stampit2.default)().compose(_querySet2.default).methods({ /** * Runs Script matching the given lookup properties. * @memberOf ScriptQuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @returns {ScriptQuerySet} * @example {@lang javascript} * Script.please().run({id: 1, instanceName: 'test-one'}).then(function(trace) {}); */ run: function run() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var payload = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'POST'; this.endpoint = 'run'; this.payload = payload; this._serialize = false; return this; }, /** * Gets allowed runtimes. * @memberOf ScriptQuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @returns {ScriptQuerySet} * @example {@lang javascript} * Script.please().runtimes({instanceName: 'test-one'}).then(function(trace) {}); */ getRuntimes: function getRuntimes() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'GET'; this.endpoint = 'runtimes'; this.payload = payload; this._serialize = false; return this; } }); var ScriptMeta = (0, _base.Meta)({ name: 'script', pluralName: 'scripts', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/snippets/scripts/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/snippets/scripts/' }, 'runtimes': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/snippets/scripts/runtimes/' }, 'run': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/snippets/scripts/{id}/run/' } }, relatedModels: ['ScriptTrace'] }); var ScriptConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, runtime_name: { presence: true, inclusion: ['nodejs', 'python', 'ruby', 'golang', 'php', 'swift'] }, source: { string: true }, config: { object: true }, label: { presence: true, string: true }, description: { string: true } }; /** * OO wrapper around scripts {@link http://docs.syncano.com/v4.0/docs/codebox-list-codeboxes endpoint}. * **Script** has special method called ``run`` which will execute attached source code. * @constructor * @type {Script} * @property {Number} id * @property {String} instanceName * @property {String} label * @property {String} source * @property {String} runtime_name * @property {String} [description = null] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var Script = (0, _stampit2.default)().compose(_base.Model).setMeta(ScriptMeta).setConstraints(ScriptConstraints).setQuerySet(ScriptQuerySet).methods({ /** * Runs current Script. * @memberOf Script * @instance * @param {Object} [payload = {}] * @returns {Promise} * @example {@lang javascript} * Script.please().get({instanceName: 'test-one', id: 1}).then(function(script) { * script.run({some: 'variable'}).then(function(trace) {}); * }); */ run: function run() { var payload = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var meta = this.getMeta(); var path = meta.resolveEndpointPath('run', this); return this.makeRequest('POST', path, { payload: payload }); }, /** * Gets allowed runtimes. * @memberOf Script * @instance * @returns {Promise} * @example {@lang javascript} * Script.please().runtimes({instanceName: 'test-one', id: 1}).then(function(script) { * script.runtimes().then(function(runtimes) {}); * }); */ getRuntimes: function getRuntimes() { var meta = this.getMeta(); var path = meta.resolveEndpointPath('runtimes', this); return this.makeRequest('GET', path, { payload: payload }); } }); exports.default = Script; module.exports = exports['default']; /***/ }, /* 243 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ScheduleMeta = (0, _base.Meta)({ name: 'schedule', pluralName: 'schedules', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/schedules/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/schedules/' } }, relatedModels: ['ScheduleTrace'] }); var ScheduleConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, label: { presence: true, string: true }, description: { string: true }, interval_sec: { numericality: { noStrings: true } }, crontab: { format: { pattern: /([0-59]|\*)\s([0-23]|\*)\s([1-31]|\*)\s([1-12]|\*)\s([0-7]|\*)/ } }, timezone: { string: true }, script: { presence: true, numericality: { noStrings: true } } }; /** * OO wrapper around instance groups {@link http://docs.syncano.com/v4.0/docs/codebox-schedules-list endpoint}. * @constructor * @type {Schedule} * @property {Number} id * @property {String} instanceName * @property {String} label * @property {Number} interval_sec * @property {String} crontab * @property {Object} payload * @property {String} scheduled_next * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var Schedule = (0, _stampit2.default)().compose(_base.Model).setMeta(ScheduleMeta).setConstraints(ScheduleConstraints); exports.default = Schedule; module.exports = exports['default']; /***/ }, /* 244 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TriggerMeta = (0, _base.Meta)({ name: 'trigger', pluralName: 'triggers', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/triggers/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/triggers/' } }, relatedModels: ['TriggerTrace'] }); var TriggerConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, label: { presence: true, string: true }, description: { string: true }, signal: { presence: true, inclusion: ['post_update', 'post_create', 'post_delete'] }, script: { presence: true, numericality: { noStrings: true } }, class: { presence: true, string: true } }; /** * OO wrapper around instance triggers {@link # endpoint}. * @constructor * @type {Trigger} * @property {Number} id * @property {String} instanceName * @property {String} label * @property {String} signal * @property {Number} codebox * @property {String} class * @property {String} [description = null] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var Trigger = (0, _stampit2.default)().compose(_base.Model).setConstraints(TriggerConstraints).setMeta(TriggerMeta); exports.default = Trigger; module.exports = exports['default']; /***/ }, /* 245 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); var _querySet2 = _interopRequireDefault(_querySet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ScriptEndpointQuerySet = (0, _stampit2.default)().compose(_querySet2.default).methods({ /** * Runs ScriptEndpoint matching the given lookup properties. * @memberOf ScriptEndpointQuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @returns {Promise} * @example {@lang javascript} * ScriptEndpoint.please().run({name: 'test', instanceName: 'test-one'}).then(function(trace) {}); */ run: function run() { var _this = this; var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var payload = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _getConfig = this.getConfig(); var ScriptEndpointTrace = _getConfig.ScriptEndpointTrace; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'POST'; this.endpoint = 'run'; this.payload = payload; this._serialize = false; return this.then(function (trace) { return ScriptEndpointTrace.fromJSON(trace, { instanceName: _this.properties.instanceName, webhookName: _this.properties.name }); }); }, /** * Runs `public` ScriptEndpoint matching the given lookup properties. * @memberOf ScriptEndpointQuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @returns {Promise} * @example {@lang javascript} * ScriptEndpoint.please().runPublic({public_link: '44cfc5552eacc', instanceName: 'test-one'}).then(function(trace) {}); */ runPublic: function runPublic() { var _this2 = this; var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var payload = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _getConfig2 = this.getConfig(); var ScriptEndpointTrace = _getConfig2.ScriptEndpointTrace; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'POST'; this.endpoint = 'public'; this.payload = payload; this._serialize = false; return this.then(function (trace) { return ScriptEndpointTrace.fromJSON(trace, { instanceName: _this2.properties.instanceName, webhookName: _this2.properties.name }); }); }, /** * Resets ScriptEndpoint matching the given lookup properties. * @memberOf ScriptEndpointQuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @returns {ScriptEndpointQuerySet} * @example {@lang javascript} * ScriptEndpoint.please().reset({name: 'test', instanceName: 'test-one'}).then(function(trace) {}); */ reset: function reset() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'POST'; this.endpoint = 'reset'; return this; } }); var ScriptEndpointMeta = (0, _base.Meta)({ name: 'scriptendpoint', pluralName: 'scriptendpoints', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/endpoints/scripts/{name}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/endpoints/scripts/' }, 'run': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/endpoints/scripts/{name}/run/' }, 'reset': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/endpoints/scripts/{name}/reset_link/' }, 'public': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/endpoints/scripts/p/{public_link}/{name}/' } }, relatedModels: ['ScriptEndpointTrace'] }); var ScriptEndpointConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, name: { presence: true, string: true, length: { minimum: 5 } }, description: { string: true }, public: { boolean: true }, script: { presence: true, numericality: { noStrings: true } } }; /** * OO wrapper around instance webhooks {@link # endpoint}. * @constructor * @type {ScriptEndpoint} * @property {String} name * @property {String} instanceName * @property {String} public_link * @property {Boolean} public * @property {Number} codebox * @property {String} [description = null] * @property {String} [links = {}] */ var ScriptEndpoint = (0, _stampit2.default)().compose(_base.Model).setMeta(ScriptEndpointMeta).setQuerySet(ScriptEndpointQuerySet).setConstraints(ScriptEndpointConstraints).methods({ /** * Runs current ScriptEndpoint. * @memberOf ScriptEndpoint * @instance * @param {Object} [payload = {}] * @returns {Promise} * @example {@lang javascript} * ScriptEndpoint.please().get({instanceName: 'test-one', id: 1}).then(function(codebox) { codebox.run({some: 'variable'}).then(function(trace) {}); }); */ run: function run() { var _this3 = this; var payload = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var _getConfig3 = this.getConfig(); var ScriptEndpointTrace = _getConfig3.ScriptEndpointTrace; var meta = this.getMeta(); var path = meta.resolveEndpointPath('run', this); return this.makeRequest('POST', path, { payload: payload }).then(function (body) { return ScriptEndpointTrace.fromJSON(body, { instanceName: _this3.instanceName, webhookName: _this3.name }); }); }, /** * Runs current `public` ScriptEndpoint. * @memberOf ScriptEndpoint * @instance * @param {Object} [payload = {}] * @returns {Promise} * @example {@lang javascript} * ScriptEndpoint.please().get({instanceName: 'test-one', id: 1}).then(function(codebox) { codebox.runPublic({some: 'variable'}).then(function(trace) {}); }); */ runPublic: function runPublic() { var _this4 = this; var payload = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var _getConfig4 = this.getConfig(); var ScriptEndpointTrace = _getConfig4.ScriptEndpointTrace; var meta = this.getMeta(); var path = meta.resolveEndpointPath('public', this); return this.makeRequest('POST', path, { payload: payload }).then(function (body) { return ScriptEndpointTrace.fromJSON(body, { instanceName: _this4.instanceName, webhookName: _this4.name }); }); }, /** * Resets current ScriptEndpoint. * @memberOf ScriptEndpoint * @instance * @returns {Promise} * @example {@lang javascript} * ScriptEndpoint.please().get({instanceName: 'test-one', name: 'test'}).then(function(webhook) { webhook.reset().then(function() {}); }); */ reset: function reset() { var _this5 = this; var meta = this.getMeta(); var path = meta.resolveEndpointPath('reset', this); return this.makeRequest('POST', path).then(function (body) { return _this5.serialize(body); }); } }); exports.default = ScriptEndpoint; module.exports = exports['default']; /***/ }, /* 246 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); var _querySet2 = _interopRequireDefault(_querySet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var DataEndpointQerySet = (0, _stampit2.default)().compose(_querySet2.default).methods({ /** * Fetches Data Objects matching the Data View properties. * @memberOf DataEndpointQerySet * @instance * @param {Object} properties lookup properties used for path resolving * @returns {DataEndpointQerySet} * @example {@lang javascript} * DataEndpoint.please().fetchData({name: 'dataViewName', instanceName: 'test-one'}).then(function(dataObjects) {}); */ fetchData: function fetchData() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'GET'; this.endpoint = 'get'; this._serialize = false; return this; } }); var DataEndpointMeta = (0, _base.Meta)({ name: 'dataview', pluralName: 'dataviews', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/endpoints/data/{name}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/endpoints/data/' }, 'get': { 'methods': ['get'], 'path': '/v1.1/instances/{instanceName}/endpoints/data/{name}/get/' }, 'rename': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/endpoints/data/{name}/rename/' }, 'clear_cache': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/endpoints/data/{name}/clear_cache/' } } }); var DataEndpointConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, name: { presence: true, string: true, length: { maximum: 64 } }, description: { string: true }, class: { presence: true, string: true, length: { minimum: 5 } }, query: { object: true }, excluded_fields: { string: true }, order_by: { string: true }, page_size: { numericality: { noStrings: true } }, expand: { string: true } }; /** * OO wrapper around data views {@link # endpoint}. * @constructor * @type {DataEndpoint} * @property {String} name * @property {String} instanceName * @property {Object} query * @property {String} excluded_fields * @property {String} order_by * @property {Number} page_size * @property {String} expand * @property {String} class * @property {String} [description = null] * @property {String} [links = {}] */ var DataEndpoint = (0, _stampit2.default)().compose(_base.Model).setMeta(DataEndpointMeta).setQuerySet(DataEndpointQerySet).setConstraints(DataEndpointConstraints).methods({ /** * Fetches Data Objects matching the Data View properties. * @memberOf DataEndpoint * @instance * @param {Object} * @returns {Promise} * @example {@lang javascript} * DataEndpoint.please().fetchData({name: 'dataViewName', instanceName: 'test-one'}).then(function(dataObjects) {}); */ fetchData: function fetchData() { var meta = this.getMeta(); var path = meta.resolveEndpointPath('get', this); return this.makeRequest('GET', path); } }); exports.default = DataEndpoint; module.exports = exports['default']; /***/ }, /* 247 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ScriptTraceQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Get, _querySet.List); var ScriptTraceMeta = (0, _base.Meta)({ name: 'scripttrace', pluralName: 'scripttrace', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/scripts/{scriptId}/traces/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/scripts/{scriptId}/traces/' } } }); var ScriptConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, scriptId: { presence: true } }; /** * OO wrapper around script trace {@link # endpoint}. * This model is *read only*. * @constructor * @type {ScriptTrace} * @property {Number} id * @property {String} instanceName * @property {Number} scriptId * @property {String} status * @property {Date} executed_at * @property {Number} duration * @property {Object} [result = {}] * @property {String} result.stderr * @property {String} result.stdout * @property {String} [links = {}] */ var ScriptTrace = (0, _stampit2.default)().compose(_base.Model).setQuerySet(ScriptTraceQuerySet).setConstraints(ScriptConstraints).setMeta(ScriptTraceMeta); exports.default = ScriptTrace; module.exports = exports['default']; /***/ }, /* 248 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ScheduleTraceQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Get, _querySet.List); var ScheduleTraceMeta = (0, _base.Meta)({ name: 'scheduletrace', pluralName: 'scheduletraces', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/schedules/{scheduleId}/traces/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/schedules/{scheduleId}/traces/' } } }); var ScheduleTraceConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, scheduleId: { presence: true, numericality: { noStrings: true } } }; /** * OO wrapper around shedule traces {@link # endpoint}. * @constructor * @type {ScheduleTrace} * @property {Number} id * @property {Number} scheduleId * @property {String} instanceName * @property {String} status * @property {Date} executed_at * @property {Number} duration * @property {Object} [result = {}] * @property {String} result.stderr * @property {String} result.stdout * @property {String} [links = {}] */ var ScheduleTrace = (0, _stampit2.default)().compose(_base.Model).setQuerySet(ScheduleTraceQuerySet).setMeta(ScheduleTraceMeta).setConstraints(ScheduleTraceConstraints); exports.default = ScheduleTrace; module.exports = exports['default']; /***/ }, /* 249 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TriggerTraceQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Get, _querySet.List); var TriggerTraceMeta = (0, _base.Meta)({ name: 'triggertrace', pluralName: 'triggertraces', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/triggers/{triggerId}/traces/{id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/triggers/{triggerId}/traces/' } } }); var TriggerTraceConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, triggerId: { presence: true, numericality: { noStrings: true } } }; /** * OO wrapper around trigger trace {@link # endpoint}. * This model is *read only*. * @constructor * @type {TriggerTrace} * @property {Number} id * @property {String} instanceName * @property {Number} triggerId * @property {String} status * @property {Date} executed_at * @property {Number} duration * @property {Object} [result = {}] * @property {String} result.stderr * @property {String} result.stdout * @property {String} [links = {}] */ var TriggerTrace = (0, _stampit2.default)().compose(_base.Model).setQuerySet(TriggerTraceQuerySet).setConstraints(TriggerTraceConstraints).setMeta(TriggerTraceMeta); exports.default = TriggerTrace; module.exports = exports['default']; /***/ }, /* 250 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ScriptEndpointTraceQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Get, _querySet.List); var ScriptEndpointTraceMeta = (0, _base.Meta)({ name: 'triggertrace', pluralName: 'triggertraces', endpoints: { 'detail': { 'methods': ['get'], 'path': '/v1.1/instances/{instanceName}/endpoints/scripts/{scriptEndpointName}/traces/{id}/' }, 'list': { 'methods': ['get'], 'path': '/v1.1/instances/{instanceName}/endpoints/scripts/{scriptEndpointName}/traces/' } } }); var ScriptEndpointTraceConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, scriptEndpointName: { presence: true, string: true } }; /** * OO wrapper around webhook traces {@link # endpoint}. * This model is *read only*. * @constructor * @type {ScriptEndpointTrace} * @property {Number} id * @property {String} instanceName * @property {String} scriptEndpointName * @property {String} status * @property {Date} executed_at * @property {Number} duration * @property {Object} [result = {}] * @property {String} result.stderr * @property {String} result.stdout * @property {String} [links = {}] */ var ScriptEndpointTrace = (0, _stampit2.default)().compose(_base.Model).setMeta(ScriptEndpointTraceMeta).setQuerySet(ScriptEndpointTraceQuerySet).setConstraints(ScriptEndpointTraceConstraints); exports.default = ScriptEndpointTrace; module.exports = exports['default']; /***/ }, /* 251 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var GCMDeviceQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.List, _querySet.Create, _querySet.BulkCreate, _querySet.Delete, _querySet.Get, _querySet.Update, _querySet.UpdateOrCreate, _querySet.GetOrCreate); var GCMDeviceMeta = (0, _base.Meta)({ name: 'gcmdevice', pluralName: 'gcmdevices', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/push_notifications/gcm/devices/{registration_id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/push_notifications/gcm/devices/' } } }); var GCMDevicConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, user: { numericality: { noStrings: true } }, registration_id: { presence: true, string: true }, device_id: { string: true }, metadata: { object: true }, is_active: { boolean: true } }; /** * OO wrapper around instance GCM devices {@link # endpoint}. * @constructor * @type {GCMDevice} * @property {String} registration_id * @property {String} device_id * @property {String} instanceName * @property {String} [label = null] * @property {Number} [user = null] * @property {Boolean} [is_active = true] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var GCMDevice = (0, _stampit2.default)().compose(_base.Model).setMeta(GCMDeviceMeta).setQuerySet(GCMDeviceQuerySet).setConstraints(GCMDevicConstraints); exports.default = GCMDevice; module.exports = exports['default']; /***/ }, /* 252 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var GCMConfigQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Update, _querySet.Get); var GCMConfigMeta = (0, _base.Meta)({ name: 'gcmconfig', pluralName: 'gcmconfig', endpoints: { 'detail': { 'methods': ['post', 'get', 'patch', 'put'], 'path': '/v1.1/instances/{instanceName}/push_notifications/gcm/config/' } } }); var GCMConfigConstraints = { instanceName: { presence: true, length: { minimum: 5 } } }; /** * OO wrapper around instance GCM config {@link # endpoint}. * @constructor * @type {GCMConfig} * @property {String} instanceName * @property {String} production_api_key * @property {String} development_api_key * @property {Object} [links = {}] */ var GCMConfig = (0, _stampit2.default)().compose(_base.Model).setMeta(GCMConfigMeta).setQuerySet(GCMConfigQuerySet).setConstraints(GCMConfigConstraints); exports.default = GCMConfig; module.exports = exports['default']; /***/ }, /* 253 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var APNSDeviceQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.List, _querySet.Create, _querySet.BulkCreate, _querySet.Delete, _querySet.Get, _querySet.Update, _querySet.UpdateOrCreate, _querySet.GetOrCreate); var APNSDeviceMeta = (0, _base.Meta)({ name: 'apnsdevice', pluralName: 'apnsdevices', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/push_notifications/apns/devices/{registration_id}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/push_notifications/apns/devices/' } } }); var APNSDeviceConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, user: { numericality: { noStrings: true } }, registration_id: { presence: true, string: true }, device_id: { string: true }, metadata: { object: true }, is_active: { boolean: true } }; /** * OO wrapper around instance APNS devices {@link # endpoint}. * @constructor * @type {APNSDevice} * @property {String} registration_id * @property {String} device_id * @property {String} instanceName * @property {String} [label = null] * @property {Number} [user = null] * @property {Boolean} [is_active = true] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var APNSDevice = (0, _stampit2.default)().compose(_base.Model).setMeta(APNSDeviceMeta).setQuerySet(APNSDeviceQuerySet).setConstraints(APNSDeviceConstraints); exports.default = APNSDevice; module.exports = exports['default']; /***/ }, /* 254 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var APNSConfigQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Update, _querySet.Get); var APNSConfigMeta = (0, _base.Meta)({ name: 'gcmconfig', pluralName: 'gcmconfig', endpoints: { 'detail': { 'methods': ['post', 'get', 'patch', 'put'], 'path': '/v1.1/instances/{instanceName}/push_notifications/apns/config/' } } }); var APNSConfigConstraints = { instanceName: { presence: true, length: { minimum: 5 } } }; /** * OO wrapper around instance APNS config {@link # endpoint}. * @constructor * @type {APNSConfig} * @property {String} instanceName * @property {File} production_certificate * @property {String} [production_certificate_name = null] * @property {String} production_bundle_identifier * @property {String} [production_expiration_date = null] * @property {String} development_certificate_name * @property {File} development_certificate * @property {String} development_bundle_identifier * @property {String} [development_expiration_date = null] * @property {Object} [links = {}] */ var APNSConfig = (0, _stampit2.default)().compose(_base.Model).setMeta(APNSConfigMeta).setQuerySet(APNSConfigQuerySet).setConstraints(APNSConfigConstraints); exports.default = APNSConfig; module.exports = exports['default']; /***/ }, /* 255 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var GCMMessageQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Create, _querySet.BulkCreate, _querySet.Get, _querySet.List, _querySet.GetOrCreate); var GCMMessageMeta = (0, _base.Meta)({ name: 'gcmmessage', pluralName: 'gcmmessages', endpoints: { 'detail': { 'methods': ['delete', 'get'], 'path': '/v1.1/instances/{instanceName}/push_notifications/gcm/messages/{id}/' }, 'list': { 'methods': ['get'], 'path': '/v1.1/instances/{instanceName}/push_notifications/gcm/messages/' } } }); var GCMMessageConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, content: { presence: true, object: true }, 'content.registration_ids': { presence: true, array: true }, 'content.environment': { presence: true, inclusion: ['development', 'production'] } }; /** * OO wrapper around instance GCM messages {@link # endpoint}. * @constructor * @type {GCMMessage} * @property {Number} id * @property {String} [status = null] * @property {Object} [content = {}] * @property {Object} [result = {}] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var GCMMessage = (0, _stampit2.default)().compose(_base.Model).setMeta(GCMMessageMeta).setQuerySet(GCMMessageQuerySet).setConstraints(GCMMessageConstraints); exports.default = GCMMessage; module.exports = exports['default']; /***/ }, /* 256 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var APNSMessageQuerySet = (0, _stampit2.default)().compose(_querySet.BaseQuerySet, _querySet.Create, _querySet.BulkCreate, _querySet.Get, _querySet.List, _querySet.GetOrCreate); var APNSMessageMeta = (0, _base.Meta)({ name: 'apnsmessage', pluralName: 'apnsmessages', endpoints: { 'detail': { 'methods': ['delete', 'get'], 'path': '/v1.1/instances/{instanceName}/push_notifications/apns/messages/{id}/' }, 'list': { 'methods': ['get'], 'path': '/v1.1/instances/{instanceName}/push_notifications/apns/messages/' } } }); var APNSMessageConstraints = { instanceName: { presence: true, length: { minimum: 5 } }, content: { presence: true, object: true }, 'content.registration_ids': { presence: true, array: true }, 'content.environment': { presence: true, inclusion: ['development', 'production'] }, 'content.aps': { presence: true }, 'content.aps.alert': { presence: true } }; /** * OO wrapper around instance APNS messages {@link # endpoint}. * @constructor * @type {APNSMessage} * @property {Number} id * @property {String} [status = null] * @property {Object} [content = {}] * @property {Object} [result = {}] * @property {String} [links = {}] * @property {Date} [created_at = null] * @property {Date} [updated_at = null] */ var APNSMessage = (0, _stampit2.default)().compose(_base.Model).setQuerySet(APNSMessageQuerySet).setConstraints(APNSMessageConstraints).setMeta(APNSMessageMeta); exports.default = APNSMessage; module.exports = exports['default']; /***/ }, /* 257 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _assign2 = __webpack_require__(74); var _assign3 = _interopRequireDefault(_assign2); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _base = __webpack_require__(85); var _querySet = __webpack_require__(209); var _querySet2 = _interopRequireDefault(_querySet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TemplateQuerySet = (0, _stampit2.default)().compose(_querySet2.default).methods({ /** * Renames a template. * @memberOf TemplateQuerySet * @instance * @param {Object} properties lookup properties used for path resolving * @param {Object} payload object with request payload * @returns {Promise} * @example {@lang javascript} * Template.please().rename({name: 'my-template', instanceName: 'test-one'}, { new_name: 'new-name'}).then(function(template) {}); */ rename: function rename() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var payload = arguments.length <= 1 || arguments[1] === undefined ? { new_name: this.name } : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'POST'; this.endpoint = 'rename'; this.payload = payload; return this; }, render: function render() { var properties = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var context = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this.properties = (0, _assign3.default)({}, this.properties, properties); this.method = 'POST'; this.endpoint = 'render'; this.payload = { context: context }; this.responseAttr = 'text'; this.raw(); return this; } }); var TemplateMeta = (0, _base.Meta)({ name: 'template', pluralName: 'templates', endpoints: { 'detail': { 'methods': ['delete', 'patch', 'put', 'get'], 'path': '/v1.1/instances/{instanceName}/snippets/templates/{name}/' }, 'list': { 'methods': ['post', 'get'], 'path': '/v1.1/instances/{instanceName}/snippets/templates/' }, 'rename': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/snippets/templates/{name}/rename/' }, 'render': { 'methods': ['post'], 'path': '/v1.1/instances/{instanceName}/snippets/templates/{name}/render/' } } }); var TemplateConstraints = { name: { presence: true, string: true, length: { minimum: 5 } }, instanceName: { presence: true, length: { minimum: 5 } }, content: { presence: true, string: true }, content_type: { presence: true, string: true }, context: { object: true } }; /** * OO wrapper around templates {@link # endpoint}. * @constructor * @type {Template} * @property {String} name * @property {String} instanceName * @property {String} content * @property {String} content_type * @property {Object} context * @property {String} [links = {}] */ var Template = (0, _stampit2.default)().compose(_base.Model).setMeta(TemplateMeta).setQuerySet(TemplateQuerySet).methods({ rename: function rename() { var payload = arguments.length <= 0 || arguments[0] === undefined ? { new_name: this.name } : arguments[0]; var options = { payload: payload }; var meta = this.getMeta(); var path = meta.resolveEndpointPath('rename', this); return this.makeRequest('POST', path, options); }, render: function render() { var context = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var options = { payload: { context: context }, responseAttr: 'text' }; var meta = this.getMeta(); var path = meta.resolveEndpointPath('render', this); return this.makeRequest('POST', path, options); } }).setConstraints(TemplateConstraints); exports.default = Template; module.exports = exports['default']; /***/ }, /* 258 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _request = __webpack_require__(213); var _request2 = _interopRequireDefault(_request); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Wrapper around account endpoint. Meant to be used directly form {@link Syncano} instance. * @constructor * @type {Account} * @example {@lang javascript} * const {Account} = Syncano(); * Account.login({email: '', password: ''}).then((user) => { * * }); */ var Account = (0, _stampit2.default)().compose(_request2.default).props({ _account: { registerPath: '/v1.1/account/register/', loginPath: '/v1.1/account/auth/', updatePath: '/v1.1/account/' } }).methods({ /** * A convenience method for creating a new account. * @memberOf Account * @instance * @param {Object} payload * @param {String} payload.email * @param {String} payload.password * @returns {Promise} */ register: function register() { var payload = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var path = this._account.registerPath; return this.makeRequest('POST', path, { payload: payload }); }, /** * A convenience method for authenticating with email and password. * @memberOf Account * @instance * @param {Object} payload * @param {String} payload.email * @param {String} payload.password * @param {Boolean} [setAccountKey = true] * @returns {Promise} */ login: function login() { var payload = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var setAccountKey = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1]; var config = this.getConfig(); var path = this._account.loginPath; return this.makeRequest('POST', path, { payload: payload }).then(function (user) { if (setAccountKey === true) { config.setAccountKey(user.account_key); } return user; }); }, /** * A convenience method for updating your account details. * @memberOf Account * @instance * @param {Object} payload * @param {String} payload.first_name * @param {String} payload.last_name * @returns {Promise} */ update: function update() { var payload = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var path = this._account.updatePath; return this.makeRequest('PUT', path, { payload: payload }); } }); exports.default = Account; module.exports = exports['default']; /***/ }, /* 259 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _stampit = __webpack_require__(29); var _stampit2 = _interopRequireDefault(_stampit); var _utils = __webpack_require__(223); var _request = __webpack_require__(213); var _request2 = _interopRequireDefault(_request); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Utility for pinging the api. Allows checking for connection to the platofrm. Meant to be used directly form the {@link Syncano} instance. * * @constructor * @type {Pinger} * * @example {@lang javascript} * const connection = Syncano(); * connection.Monitor.startMonitoring(); * connection.Monitor.on('connected', () => { * // connected to the api * }); * connection.Monitor.on('disconnected', (error) => { * // disconnected from the api * }); */ var Pinger = (0, _stampit2.default)().compose(_request2.default, _utils.EventEmittable).props({ timeout: 5000, interval: null, connected: null }).methods({ request: function request() { var path = this.getConfig().getBaseUrl(); return this.makeRequest('GET', path); }, startMonitoring: function startMonitoring() { var _this = this; this.interval = setInterval(function () { return _this.ping(); }, this.timeout); }, ping: function ping() { var _this2 = this; this.request().then(function () { if (!_this2.connected) { _this2.connected = true; _this2.emit('connected'); } }).catch(function (error) { if (_this2.connected) { _this2.connected = false; _this2.emit('disconnected', error); } }); }, stopMonitoring: function stopMonitoring() { clearInterval(this.interval); } }); exports.default = Pinger; module.exports = exports['default']; /***/ } /******/ ]); //# sourceMappingURL=syncano.js.map
/** * @fileoverview The event generator for AST nodes. * @author Toru Nagashima */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const esquery = require("esquery"); const lodash = require("lodash"); //------------------------------------------------------------------------------ // Typedefs //------------------------------------------------------------------------------ /** * An object describing an AST selector * @typedef {Object} ASTSelector * @property {string} rawSelector The string that was parsed into this selector * @property {boolean} isExit `true` if this should be emitted when exiting the node rather than when entering * @property {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector * @property {string[]|null} listenerTypes A list of node types that could possibly cause the selector to match, * or `null` if all node types could cause a match * @property {number} attributeCount The total number of classes, pseudo-classes, and attribute queries in this selector * @property {number} identifierCount The total number of identifier queries in this selector */ //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Gets the possible types of a selector * @param {Object} parsedSelector An object (from esquery) describing the matching behavior of the selector * @returns {string[]|null} The node types that could possibly trigger this selector, or `null` if all node types could trigger it */ function getPossibleTypes(parsedSelector) { switch (parsedSelector.type) { case "identifier": return [parsedSelector.value]; case "matches": { const typesForComponents = parsedSelector.selectors.map(getPossibleTypes); if (typesForComponents.every(typesForComponent => typesForComponent)) { return lodash.union.apply(null, typesForComponents); } return null; } case "compound": { const typesForComponents = parsedSelector.selectors.map(getPossibleTypes).filter(typesForComponent => typesForComponent); // If all of the components could match any type, then the compound could also match any type. if (!typesForComponents.length) { return null; } /* * If at least one of the components could only match a particular type, the compound could only match * the intersection of those types. */ return lodash.intersection.apply(null, typesForComponents); } case "child": case "descendant": case "sibling": case "adjacent": return getPossibleTypes(parsedSelector.right); default: return null; } } /** * Counts the number of class, pseudo-class, and attribute queries in this selector * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior * @returns {number} The number of class, pseudo-class, and attribute queries in this selector */ function countClassAttributes(parsedSelector) { switch (parsedSelector.type) { case "child": case "descendant": case "sibling": case "adjacent": return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right); case "compound": case "not": case "matches": return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0); case "attribute": case "field": case "nth-child": case "nth-last-child": return 1; default: return 0; } } /** * Counts the number of identifier queries in this selector * @param {Object} parsedSelector An object (from esquery) describing the selector's matching behavior * @returns {number} The number of identifier queries */ function countIdentifiers(parsedSelector) { switch (parsedSelector.type) { case "child": case "descendant": case "sibling": case "adjacent": return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right); case "compound": case "not": case "matches": return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0); case "identifier": return 1; default: return 0; } } /** * Compares the specificity of two selector objects, with CSS-like rules. * @param {ASTSelector} selectorA An AST selector descriptor * @param {ASTSelector} selectorB Another AST selector descriptor * @returns {number} * a value less than 0 if selectorA is less specific than selectorB * a value greater than 0 if selectorA is more specific than selectorB * a value less than 0 if selectorA and selectorB have the same specificity, and selectorA <= selectorB alphabetically * a value greater than 0 if selectorA and selectorB have the same specificity, and selectorA > selectorB alphabetically */ function compareSpecificity(selectorA, selectorB) { return selectorA.attributeCount - selectorB.attributeCount || selectorA.identifierCount - selectorB.identifierCount || (selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1); } /** * Parses a raw selector string, and throws a useful error if parsing fails. * @param {string} rawSelector A raw AST selector * @returns {Object} An object (from esquery) describing the matching behavior of this selector * @throws {Error} An error if the selector is invalid */ function tryParseSelector(rawSelector) { try { return esquery.parse(rawSelector.replace(/:exit$/, "")); } catch (err) { if (typeof err.offset === "number") { throw new Error(`Syntax error in selector "${rawSelector}" at position ${err.offset}: ${err.message}`); } throw err; } } /** * Parses a raw selector string, and returns the parsed selector along with specificity and type information. * @param {string} rawSelector A raw AST selector * @returns {ASTSelector} A selector descriptor */ const parseSelector = lodash.memoize(rawSelector => { const parsedSelector = tryParseSelector(rawSelector); return { rawSelector, isExit: rawSelector.endsWith(":exit"), parsedSelector, listenerTypes: getPossibleTypes(parsedSelector), attributeCount: countClassAttributes(parsedSelector), identifierCount: countIdentifiers(parsedSelector) }; }); //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ /** * The event generator for AST nodes. * This implements below interface. * * ```ts * interface EventGenerator { * emitter: SafeEmitter; * enterNode(node: ASTNode): void; * leaveNode(node: ASTNode): void; * } * ``` */ class NodeEventGenerator { /** * @param {SafeEmitter} emitter * An SafeEmitter which is the destination of events. This emitter must already * have registered listeners for all of the events that it needs to listen for. * (See lib/util/safe-emitter.js for more details on `SafeEmitter`.) * @returns {NodeEventGenerator} new instance */ constructor(emitter) { this.emitter = emitter; this.currentAncestry = []; this.enterSelectorsByNodeType = new Map(); this.exitSelectorsByNodeType = new Map(); this.anyTypeEnterSelectors = []; this.anyTypeExitSelectors = []; emitter.eventNames().forEach(rawSelector => { const selector = parseSelector(rawSelector); if (selector.listenerTypes) { selector.listenerTypes.forEach(nodeType => { const typeMap = selector.isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType; if (!typeMap.has(nodeType)) { typeMap.set(nodeType, []); } typeMap.get(nodeType).push(selector); }); } else { (selector.isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors).push(selector); } }); this.anyTypeEnterSelectors.sort(compareSpecificity); this.anyTypeExitSelectors.sort(compareSpecificity); this.enterSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity)); this.exitSelectorsByNodeType.forEach(selectorList => selectorList.sort(compareSpecificity)); } /** * Checks a selector against a node, and emits it if it matches * @param {ASTNode} node The node to check * @param {ASTSelector} selector An AST selector descriptor * @returns {void} */ applySelector(node, selector) { if (esquery.matches(node, selector.parsedSelector, this.currentAncestry)) { this.emitter.emit(selector.rawSelector, node); } } /** * Applies all appropriate selectors to a node, in specificity order * @param {ASTNode} node The node to check * @param {boolean} isExit `false` if the node is currently being entered, `true` if it's currently being exited * @returns {void} */ applySelectors(node, isExit) { const selectorsByNodeType = (isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType).get(node.type) || []; const anyTypeSelectors = isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors; /* * selectorsByNodeType and anyTypeSelectors were already sorted by specificity in the constructor. * Iterate through each of them, applying selectors in the right order. */ let selectorsByTypeIndex = 0; let anyTypeSelectorsIndex = 0; while (selectorsByTypeIndex < selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length) { if ( selectorsByTypeIndex >= selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length && compareSpecificity(anyTypeSelectors[anyTypeSelectorsIndex], selectorsByNodeType[selectorsByTypeIndex]) < 0 ) { this.applySelector(node, anyTypeSelectors[anyTypeSelectorsIndex++]); } else { this.applySelector(node, selectorsByNodeType[selectorsByTypeIndex++]); } } } /** * Emits an event of entering AST node. * @param {ASTNode} node - A node which was entered. * @returns {void} */ enterNode(node) { if (node.parent) { this.currentAncestry.unshift(node.parent); } this.applySelectors(node, false); } /** * Emits an event of leaving AST node. * @param {ASTNode} node - A node which was left. * @returns {void} */ leaveNode(node) { this.applySelectors(node, true); this.currentAncestry.shift(); } } module.exports = NodeEventGenerator;
frappe.listview_settings['Communication'] = { add_fields: [ "sent_or_received","recipients", "subject", "communication_medium", "communication_type", "sender", "seen", "reference_doctype", "reference_name", "has_attachment" ], filters: [["status", "=", "Open"]], onload: function(list_view) { let method = "frappe.email.inbox.create_email_flag_queue" list_view.page.add_menu_item(__("Mark as Read"), function() { list_view.call_for_selected_items(method, { action: "Read" }); }); list_view.page.add_menu_item(__("Mark as Unread"), function() { list_view.call_for_selected_items(method, { action: "Unread" }); }); }, set_primary_action: function(list_view) { var me = this; if (list_view.new_doctype) { list_view.page.set_primary_action( __("New"), function() { new frappe.views.CommunicationComposer({ doc: {} }) }, "octicon octicon-plus" ); } else { list_view.page.clear_primary_action(); } } };
'use strict'; /** * @ngdoc filter * @name orderBy * @kind function * * @description * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically * for strings and numerically for numbers. Note: if you notice numbers are not being sorted * as expected, make sure they are actually being saved as numbers and not strings. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `===`, `>` operator. * - `string`: An Angular expression. The result of this expression is used to compare elements * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by * 3 first characters of a property called `name`). The result of a constant expression * is interpreted as a property name to be used in comparisons (for example `"special name"` * to sort object by the value of their `special name` property). An expression can be * optionally prefixed with `+` or `-` to control ascending or descending sort order * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array * element itself is used to compare where sorting. * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * If the predicate is missing or empty then it defaults to `'+'`. * * @param {boolean=} reverse Reverse the order of the array. * @returns {Array} Sorted copy of the source array. * * * @example * The example below demonstrates a simple ngRepeat, where the data is sorted * by age in descending order (predicate is set to `'-age'`). * `reverse` is not set, which means it defaults to `false`. <example module="orderByExample"> <file name="index.html"> <script> angular.module('orderByExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}]; }]); </script> <div ng-controller="ExampleController"> <table class="friend"> <tr> <th>Name</th> <th>Phone Number</th> <th>Age</th> </tr> <tr ng-repeat="friend in friends | orderBy:'-age'"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> </tr> </table> </div> </file> </example> * * The predicate and reverse parameters can be controlled dynamically through scope properties, * as shown in the next example. * @example <example module="orderByExample"> <file name="index.html"> <script> angular.module('orderByExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}]; $scope.predicate = 'age'; $scope.reverse = true; $scope.order = function(predicate) { $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false; $scope.predicate = predicate; }; }]); </script> <style type="text/css"> .sortorder:after { content: '\25b2'; } .sortorder.reverse:after { content: '\25bc'; } </style> <div ng-controller="ExampleController"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng-click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th> <a href="" ng-click="order('name')">Name</a> <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span> </th> <th> <a href="" ng-click="order('phone')">Phone Number</a> <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span> </th> <th> <a href="" ng-click="order('age')">Age</a> <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span> </th> </tr> <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> </tr> </table> </div> </file> </example> * * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the * desired parameters. * * Example: * * @example <example module="orderByExample"> <file name="index.html"> <div ng-controller="ExampleController"> <table class="friend"> <tr> <th><a href="" ng-click="reverse=false;order('name', false)">Name</a> (<a href="" ng-click="order('-name',false)">^</a>)</th> <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th> <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th> </tr> <tr ng-repeat="friend in friends"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> </tr> </table> </div> </file> <file name="script.js"> angular.module('orderByExample', []) .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) { var orderBy = $filter('orderBy'); $scope.friends = [ { name: 'John', phone: '555-1212', age: 10 }, { name: 'Mary', phone: '555-9876', age: 19 }, { name: 'Mike', phone: '555-4321', age: 21 }, { name: 'Adam', phone: '555-5678', age: 35 }, { name: 'Julie', phone: '555-8765', age: 29 } ]; $scope.order = function(predicate, reverse) { $scope.friends = orderBy($scope.friends, predicate, reverse); }; $scope.order('-age',false); }]); </file> </example> */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse) { return function(array, sortPredicate, reverseOrder) { if (!(isArrayLike(array))) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate]; if (sortPredicate.length === 0) { sortPredicate = ['+']; } sortPredicate = sortPredicate.map(function(predicate) { var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } if (predicate === '') { // Effectively no predicate was passed so we compare identity return reverseComparator(compare, descending); } get = $parse(predicate); if (get.constant) { var key = get(); return reverseComparator(function(a, b) { return compare(a[key], b[key]); }, descending); } } return reverseComparator(function(a, b) { return compare(get(a),get(b)); }, descending); }); return slice.call(array).sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2) { for (var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return descending ? function(a, b) {return comp(b,a);} : comp; } function isPrimitive(value) { switch (typeof value) { case 'number': /* falls through */ case 'boolean': /* falls through */ case 'string': return true; default: return false; } } function objectToString(value) { if (value === null) return 'null'; if (typeof value.valueOf === 'function') { value = value.valueOf(); if (isPrimitive(value)) return value; } if (typeof value.toString === 'function') { value = value.toString(); if (isPrimitive(value)) return value; } return ''; } function compare(v1, v2) { var t1 = typeof v1; var t2 = typeof v2; if (t1 === t2 && t1 === "object") { v1 = objectToString(v1); v2 = objectToString(v2); } if (t1 === t2) { if (t1 === "string") { v1 = v1.toLowerCase(); v2 = v2.toLowerCase(); } if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } }; }
module.exports={A:{A:{"2":"H E G C B A WB"},B:{"2":"D u g I J"},C:{"33":"0 1 2 3 4 5 6 F L H E G C B A D u g I J Y O e P Q R S T U V W X v Z a b c d N f M h i j k l m n o p q r s t y K","164":"UB x SB RB"},D:{"2":"0 1 2 3 4 5 6 F L H E G C B A D u g I J Y O e P Q R S T U V W X v Z a b c d N f M h i j k l m n o p q r s t y K GB AB CB VB DB EB"},E:{"2":"9 F L H E G C B A FB HB IB JB KB LB MB"},F:{"2":"7 8 C A D I J Y O e P Q R S T U V W X v Z a b c d N f M h i j k l m n o p q r s t NB OB PB QB TB w"},G:{"2":"9 G A BB z XB YB ZB aB bB cB dB eB"},H:{"2":"fB"},I:{"2":"x F K gB hB iB jB z kB lB"},J:{"2":"E B"},K:{"2":"7 8 B A D M w"},L:{"2":"AB"},M:{"33":"K"},N:{"2":"B A"},O:{"2":"mB"},P:{"2":"F L"},Q:{"2":"nB"},R:{"2":"oB"}},B:5,C:"CSS element() function"};
let $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { … } else { $I18N_0$ = $localize`Some Message`; }
(function(/*! Brunch !*/) { 'use strict'; if (!this.require) { var modules = {}; var cache = {}; var __hasProp = ({}).hasOwnProperty; var expand = function(root, name) { var results = [], parts, part; if (/^\.\.?(\/|$)/.test(name)) { parts = [root, name].join('/').split('/'); } else { parts = name.split('/'); } for (var i = 0, length = parts.length; i < length; i++) { part = parts[i]; if (part == '..') { results.pop(); } else if (part != '.' && part != '') { results.push(part); } } return results.join('/'); }; var getFullPath = function(path, fromCache) { var store = fromCache ? cache : modules; var dirIndex; if (__hasProp.call(store, path)) return path; dirIndex = expand(path, './index'); if (__hasProp.call(store, dirIndex)) return dirIndex; }; var cacheModule = function(name, path, contentFn) { var module = {id: path, exports: {}}; try { cache[path] = module.exports; contentFn(module.exports, function(name) { return require(name, dirname(path)); }, module); cache[path] = module.exports; } catch (err) { delete cache[path]; throw err; } return cache[path]; }; var require = function(name, root) { var path = expand(root, name); var fullPath; if (fullPath = getFullPath(path, true)) { return cache[fullPath]; } else if (fullPath = getFullPath(path, false)) { return cacheModule(name, fullPath, modules[fullPath]); } else { throw new Error("Cannot find module '" + name + "'"); } }; var dirname = function(path) { return path.split('/').slice(0, -1).join('/'); }; this.require = function(name) { return require(name, ''); }; this.require.brunch = true; this.require.define = function(bundle) { for (var key in bundle) { if (__hasProp.call(bundle, key)) { modules[key] = bundle[key]; } } }; } }).call(this);/* console */ /* jquery */ /* underscore */ /* backbone */ // lib/handlebars/base.js var Handlebars = {}; Handlebars.VERSION = "1.0.beta.6"; Handlebars.helpers = {}; Handlebars.partials = {}; Handlebars.registerHelper = function(name, fn, inverse) { if(inverse) { fn.not = inverse; } this.helpers[name] = fn; }; Handlebars.registerPartial = function(name, str) { this.partials[name] = str; }; Handlebars.registerHelper('helperMissing', function(arg) { if(arguments.length === 2) { return undefined; } else { throw new Error("Could not find property '" + arg + "'"); } }); var toString = Object.prototype.toString, functionType = "[object Function]"; Handlebars.registerHelper('blockHelperMissing', function(context, options) { var inverse = options.inverse || function() {}, fn = options.fn; var ret = ""; var type = toString.call(context); if(type === functionType) { context = context.call(this); } if(context === true) { return fn(this); } else if(context === false || context == null) { return inverse(this); } else if(type === "[object Array]") { if(context.length > 0) { for(var i=0, j=context.length; i<j; i++) { ret = ret + fn(context[i]); } } else { ret = inverse(this); } return ret; } else { return fn(context); } }); Handlebars.registerHelper('each', function(context, options) { var fn = options.fn, inverse = options.inverse; var ret = ""; if(context && context.length > 0) { for(var i=0, j=context.length; i<j; i++) { ret = ret + fn(context[i]); } } else { ret = inverse(this); } return ret; }); Handlebars.registerHelper('if', function(context, options) { var type = toString.call(context); if(type === functionType) { context = context.call(this); } if(!context || Handlebars.Utils.isEmpty(context)) { return options.inverse(this); } else { return options.fn(this); } }); Handlebars.registerHelper('unless', function(context, options) { var fn = options.fn, inverse = options.inverse; options.fn = inverse; options.inverse = fn; return Handlebars.helpers['if'].call(this, context, options); }); Handlebars.registerHelper('with', function(context, options) { return options.fn(context); }); Handlebars.registerHelper('log', function(context) { Handlebars.log(context); }); ; // lib/handlebars/utils.js Handlebars.Exception = function(message) { var tmp = Error.prototype.constructor.apply(this, arguments); for (var p in tmp) { if (tmp.hasOwnProperty(p)) { this[p] = tmp[p]; } } this.message = tmp.message; }; Handlebars.Exception.prototype = new Error; // Build out our basic SafeString type Handlebars.SafeString = function(string) { this.string = string; }; Handlebars.SafeString.prototype.toString = function() { return this.string.toString(); }; (function() { var escape = { "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }; var badChars = /&(?!\w+;)|[<>"'`]/g; var possible = /[&<>"'`]/; var escapeChar = function(chr) { return escape[chr] || "&amp;"; }; Handlebars.Utils = { escapeExpression: function(string) { // don't escape SafeStrings, since they're already safe if (string instanceof Handlebars.SafeString) { return string.toString(); } else if (string == null || string === false) { return ""; } if(!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); }, isEmpty: function(value) { if (typeof value === "undefined") { return true; } else if (value === null) { return true; } else if (value === false) { return true; } else if(Object.prototype.toString.call(value) === "[object Array]" && value.length === 0) { return true; } else { return false; } } }; })();; // lib/handlebars/runtime.js Handlebars.VM = { template: function(templateSpec) { // Just add water var container = { escapeExpression: Handlebars.Utils.escapeExpression, invokePartial: Handlebars.VM.invokePartial, programs: [], program: function(i, fn, data) { var programWrapper = this.programs[i]; if(data) { return Handlebars.VM.program(fn, data); } else if(programWrapper) { return programWrapper; } else { programWrapper = this.programs[i] = Handlebars.VM.program(fn); return programWrapper; } }, programWithDepth: Handlebars.VM.programWithDepth, noop: Handlebars.VM.noop }; return function(context, options) { options = options || {}; return templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data); }; }, programWithDepth: function(fn, data, $depth) { var args = Array.prototype.slice.call(arguments, 2); return function(context, options) { options = options || {}; return fn.apply(this, [context, options.data || data].concat(args)); }; }, program: function(fn, data) { return function(context, options) { options = options || {}; return fn(context, options.data || data); }; }, noop: function() { return ""; }, invokePartial: function(partial, name, context, helpers, partials, data) { options = { helpers: helpers, partials: partials, data: data }; if(partial === undefined) { throw new Handlebars.Exception("The partial " + name + " could not be found"); } else if(partial instanceof Function) { return partial(context, options); } else if (!Handlebars.compile) { throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode"); } else { partials[name] = Handlebars.compile(partial); return partials[name](context, options); } } }; Handlebars.template = Handlebars.VM.template; ;
// Copyright 2012 Selenium committers // Copyright 2012 Software Freedom Conservancy // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var base = require('./_base'); exports.Executor = base.require('webdriver.http.Executor'); exports.Request = base.require('webdriver.http.Request'); exports.Response = base.require('webdriver.http.Response'); exports.HttpClient = base.require('node.http.HttpClient');
"use strict"; (function (global, factory) { if (typeof define === "function" && define.amd) { define(["exports", "foo", "foo-bar", "./directory/foo-bar"], factory); } else if (typeof exports !== "undefined") { factory(exports, require("foo"), require("foo-bar"), require("./directory/foo-bar")); } else { var mod = { exports: {} }; factory(mod.exports, global.foo, global.fooBar, global.fooBar); global.actual = mod.exports; } })(this, function (exports, _foo) { Object.defineProperty(exports, "__esModule", { value: true }); exports.test2 = exports.test = undefined; var foo2 = babelHelpers.interopRequireWildcard(_foo); exports.test = test; var test2 = exports.test2 = 5; exports.default = test; _foo.bar; _foo.foo; });
// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. load('base.js'); load('richards.js'); load('deltablue.js'); load('crypto.js'); load('raytrace.js'); load('earley-boyer.js'); load('regexp.js'); load('splay.js'); var success = true; function PrintResult(name, result) { print(name + ': ' + result); } function PrintError(name, error) { PrintResult(name, error); success = false; } function PrintScore(score) { if (success) { print('----'); print('Score (version ' + BenchmarkSuite.version + '): ' + score); } } BenchmarkSuite.RunSuites({ NotifyResult: PrintResult, NotifyError: PrintError, NotifyScore: PrintScore });
/** * @fileoverview disallow unncessary concatenation of literals or template literals * @author Henry Zhu * @copyright 2015 Henry Zhu. All rights reserved. * See LICENSE file in root directory for full license. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var rule = require("../../../lib/rules/no-useless-concat"), RuleTester = require("../../../lib/testers/rule-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var ruleTester = new RuleTester(); ruleTester.run("no-useless-concat", rule, { valid: [ { code: "var a = 1 + 1;" }, { code: "var a = 1 * '2';" }, { code: "var a = 1 - 2;" }, { code: "var a = foo + bar;" }, { code: "var a = 'foo' + bar;" }, { code: "var foo = 'foo' +\n 'bar';" }, // https://github.com/eslint/eslint/issues/3575 { code: "var string = (number + 1) + 'px';" }, { code: "'a' + 1" }, { code: "1 + '1'" }, { code: "1 + `1`", parserOptions: { ecmaVersion: 6 } }, { code: "`1` + 1", parserOptions: { ecmaVersion: 6 } }, { code: "(1 + +2) + `b`", parserOptions: { ecmaVersion: 6 } } ], invalid: [ { code: "'a' + 'b'", errors: [ { message: "Unexpected string concatenation of literals."} ] }, { code: "foo + 'a' + 'b'", errors: [ { message: "Unexpected string concatenation of literals."} ] }, { code: "'a' + 'b' + 'c'", errors: [ { message: "Unexpected string concatenation of literals.", line: 1, column: 5 }, { message: "Unexpected string concatenation of literals.", line: 1, column: 11 } ] }, { code: "(foo + 'a') + ('b' + 'c')", errors: [ { column: 13, message: "Unexpected string concatenation of literals."}, { column: 20, message: "Unexpected string concatenation of literals."} ] }, { code: "`a` + 'b'", parserOptions: { ecmaVersion: 6 }, errors: [ { message: "Unexpected string concatenation of literals."} ] }, { code: "`a` + `b`", parserOptions: { ecmaVersion: 6 }, errors: [ { message: "Unexpected string concatenation of literals."} ] }, { code: "foo + `a` + `b`", parserOptions: { ecmaVersion: 6 }, errors: [ { message: "Unexpected string concatenation of literals."} ] } ] });