Comparing version 1.0.0-alpha.9 to 1.0.0-alpha.10
CHANGELOG | ||
v1.0.0-alpha.10 | ||
- bundle size tests | ||
- no longer use external assert | ||
v1.0.0-alpha.9 | ||
@@ -4,0 +8,0 @@ - not stop server when failed |
@@ -1,409 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.LOG_ENTRY = undefined; | ||
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; }; }(); /* eslint-disable no-console */ | ||
/* global setTimeout, console */ | ||
exports.logResultsAsMarkdownTable = logResultsAsMarkdownTable; | ||
exports.logResultsAsTree = logResultsAsTree; | ||
exports.logResultsAsTreeWithElapsed = logResultsAsTreeWithElapsed; | ||
var _formatters = require('../lib/utils/formatters'); | ||
var _globals = require('../lib/utils/globals'); | ||
var _autobind = require('../lib/utils/autobind'); | ||
var _localStorage = require('../lib/utils/local-storage'); | ||
var _localStorage2 = _interopRequireDefault(_localStorage); | ||
var _assert = require('assert'); | ||
var _assert2 = _interopRequireDefault(_assert); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
var noop = function noop() {}; | ||
var TIME_THRESHOLD_MS = 80; // Minimum number of milliseconds to iterate each bench test | ||
var TIME_COOLDOWN_MS = 5; // milliseconds of "cooldown" between tests | ||
var MIN_ITERATIONS = 1; // Increase if OK to let slow benchmarks take long time | ||
var LOG_ENTRY = exports.LOG_ENTRY = { | ||
GROUP: 'group', | ||
TEST: 'test', | ||
COMPLETE: 'complete' | ||
}; | ||
var CALIBRATION_TESTS = [{ | ||
id: 'warmup', | ||
initFunc: noop, | ||
testFunc: function testFunc() { | ||
return 100; | ||
}, | ||
opts: {} | ||
}]; | ||
var Bench = function () { | ||
function Bench() { | ||
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, | ||
id = _ref.id, | ||
log = _ref.log, | ||
_ref$time = _ref.time, | ||
time = _ref$time === undefined ? TIME_THRESHOLD_MS : _ref$time, | ||
_ref$delay = _ref.delay, | ||
delay = _ref$delay === undefined ? TIME_COOLDOWN_MS : _ref$delay, | ||
_ref$minIterations = _ref.minIterations, | ||
minIterations = _ref$minIterations === undefined ? MIN_ITERATIONS : _ref$minIterations; | ||
_classCallCheck(this, Bench); | ||
if (!log) { | ||
var markdown = _globals.global.probe && _globals.global.probe.markdown; | ||
log = markdown ? logResultsAsMarkdownTable : logResultsAsTree; | ||
} | ||
this.id = id; | ||
this.opts = { log: log, time: time, delay: delay, minIterations: minIterations }; | ||
this.tests = {}; | ||
this.results = {}; | ||
this.table = {}; | ||
(0, _autobind.autobind)(this); | ||
Object.seal(this); | ||
} | ||
_createClass(Bench, [{ | ||
key: 'calibrate', | ||
value: function calibrate(id, func1, func2, opts) { | ||
return this; | ||
} | ||
}, { | ||
key: 'run', | ||
value: function run() { | ||
var _this = this; | ||
var timer = new Date(); | ||
var tests = this.tests, | ||
onBenchmarkComplete = this.onBenchmarkComplete; | ||
var promise = runAsyncTests({ tests: tests, onBenchmarkComplete: onBenchmarkComplete }); | ||
promise.then(function () { | ||
var elapsed = (new Date() - timer) / 1000; | ||
logEntry(_this, { entry: LOG_ENTRY.COMPLETE, time: elapsed, message: 'Complete' }); | ||
_this.onSuiteComplete(); | ||
}); | ||
return promise; | ||
} | ||
}, { | ||
key: 'group', | ||
value: function group(id) { | ||
(0, _assert2.default)(!this.tests[id], 'tests need unique id strings'); | ||
this.tests[id] = { id: id, group: true, opts: this.opts }; | ||
return this; | ||
} | ||
// Signatures: | ||
// add(priority, id, initFunc, testFunc) | ||
// add(priority, id, testFunc) | ||
// add(id, initFunc, testFunc) | ||
// add(id, testFunc) | ||
}, { | ||
key: 'add', | ||
value: function add(priority, id, func1, func2) { | ||
if (typeof priority === 'string') { | ||
func2 = func1; | ||
func1 = id; | ||
id = priority; | ||
priority = 0; | ||
} | ||
(0, _assert2.default)(id); | ||
(0, _assert2.default)(typeof func1 === 'function'); | ||
var initFunc = null; | ||
var testFunc = func1; | ||
if (typeof func2 === 'function') { | ||
initFunc = func1; | ||
testFunc = func2; | ||
} | ||
(0, _assert2.default)(!this.tests[id], 'tests need unique id strings'); | ||
this.tests[id] = { id: id, priority: priority, initFunc: initFunc, testFunc: testFunc, opts: this.opts }; | ||
return this; | ||
} | ||
}, { | ||
key: 'onBenchmarkComplete', | ||
value: function onBenchmarkComplete(_ref2) { | ||
var id = _ref2.id, | ||
time = _ref2.time, | ||
iterations = _ref2.iterations, | ||
itersPerSecond = _ref2.itersPerSecond; | ||
// calculate iterations per second, save as numeric value | ||
var current = Math.round(iterations / time); | ||
// Format as human readable strings | ||
this.table[id] = { | ||
percent: '', | ||
iterations: itersPerSecond + '/s', | ||
current: current, | ||
max: '' | ||
}; | ||
} | ||
}, { | ||
key: 'onSuiteComplete', | ||
value: function onSuiteComplete() { | ||
var localStorage = new _localStorage2.default({ id: this.id }); | ||
var saved = localStorage.getConfiguration(); | ||
var current = this.updateTable(this.table, saved); | ||
localStorage.updateConfiguration(current); | ||
console.table(current); | ||
} | ||
}, { | ||
key: 'updateTable', | ||
value: function updateTable(current, saved) { | ||
for (var id in this.table) { | ||
if (saved[id] && saved[id].max !== undefined) { | ||
current[id].max = Math.max(current[id].current, saved[id].max); | ||
var delta = current[id].current / saved[id].max; | ||
current[id].percent = Math.round(delta * 100 - 100) + '%'; | ||
} else { | ||
current[id].max = current[id].current; | ||
} | ||
} | ||
return current; | ||
} | ||
}]); | ||
return Bench; | ||
}(); | ||
// Helper methods | ||
exports.default = Bench; | ||
function runCalibrationTests(_ref3) { | ||
var tests = _ref3.tests; | ||
var promise = Promise.resolve(true); | ||
// Run default warm up and calibration tests | ||
var _iteratorNormalCompletion = true; | ||
var _didIteratorError = false; | ||
var _iteratorError = undefined; | ||
try { | ||
var _loop = function _loop() { | ||
var test = _step.value; | ||
promise = promise.then(function () { | ||
return runAsyncTest({ test: test, silent: true }); | ||
}); | ||
}; | ||
for (var _iterator = CALIBRATION_TESTS[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { | ||
_loop(); | ||
} | ||
} catch (err) { | ||
_didIteratorError = true; | ||
_iteratorError = err; | ||
} finally { | ||
try { | ||
if (!_iteratorNormalCompletion && _iterator.return) { | ||
_iterator.return(); | ||
} | ||
} finally { | ||
if (_didIteratorError) { | ||
throw _iteratorError; | ||
} | ||
} | ||
} | ||
return promise; | ||
} | ||
// Run a list of bench test case async | ||
function runAsyncTests(_ref4) { | ||
var tests = _ref4.tests, | ||
_ref4$onBenchmarkComp = _ref4.onBenchmarkComplete, | ||
onBenchmarkComplete = _ref4$onBenchmarkComp === undefined ? noop : _ref4$onBenchmarkComp; | ||
// Run default warm up and calibration tests | ||
var promise = runCalibrationTests({ tests: tests, onBenchmarkComplete: onBenchmarkComplete }); | ||
// Run the suite tests | ||
var _loop2 = function _loop2(id) { | ||
var test = tests[id]; | ||
promise = promise.then(function () { | ||
return runAsyncTest({ test: test, onBenchmarkComplete: onBenchmarkComplete }); | ||
}); | ||
}; | ||
for (var id in tests) { | ||
_loop2(id); | ||
} | ||
return promise; | ||
} | ||
function runAsyncTest(_ref5) { | ||
var test = _ref5.test, | ||
onBenchmarkComplete = _ref5.onBenchmarkComplete, | ||
_ref5$silent = _ref5.silent, | ||
silent = _ref5$silent === undefined ? false : _ref5$silent; | ||
return new Promise(function (resolve) { | ||
setTimeout(function () { | ||
try { | ||
if (test.group) { | ||
logEntry(test, { entry: LOG_ENTRY.GROUP, id: test.id, message: test.id }); | ||
} else { | ||
var _runBenchTest = runBenchTest(test), | ||
time = _runBenchTest.time, | ||
iterations = _runBenchTest.iterations; | ||
var iterationsPerSecond = iterations / time; | ||
var itersPerSecond = (0, _formatters.formatSI)(iterationsPerSecond); | ||
if (!silent) { | ||
logEntry(test, { | ||
entry: LOG_ENTRY.TEST, id: test.id, priority: test.priority, itersPerSecond: itersPerSecond, time: time, | ||
message: test.id + ' ' + itersPerSecond + '/s' | ||
}); | ||
} | ||
if (onBenchmarkComplete) { | ||
onBenchmarkComplete({ | ||
id: test.id, | ||
time: time, | ||
iterations: iterations, | ||
iterationsPerSecond: iterationsPerSecond, | ||
itersPerSecond: itersPerSecond | ||
}); | ||
} | ||
} | ||
} finally { | ||
resolve(true); | ||
} | ||
}, test.opts.delay); // small delay between each test. System cools and DOM console updates... | ||
}); | ||
} | ||
// Run a test func for an increasing amount of iterations until time threshold exceeded | ||
function runBenchTest(test) { | ||
var iterations = test.opts.minIterations / 10; | ||
var elapsedMillis = 0; | ||
// Run increasing amount of interations until we reach time threshold, default at least 100ms | ||
while (elapsedMillis < test.opts.time) { | ||
var multiplier = 10; | ||
if (elapsedMillis > 10) { | ||
multiplier = test.opts.time / elapsedMillis * 1.25; | ||
} | ||
iterations *= multiplier; | ||
var timer = new Date(); | ||
runBenchTestIterations(test, iterations); | ||
elapsedMillis = new Date() - timer; | ||
} | ||
var time = elapsedMillis / 1000; | ||
return { time: time, iterations: iterations }; | ||
} | ||
// Run a test func for a specific amount of iterations | ||
function runBenchTestIterations(test, iterations) { | ||
var testArgs = test.initFunc && test.initFunc(); | ||
var context = test.context, | ||
testFunc = test.testFunc; | ||
if (context && testArgs) { | ||
for (var i = 0; i < iterations; i++) { | ||
testFunc.call(context, testArgs); | ||
} | ||
} else { | ||
for (var _i = 0; _i < iterations; _i++) { | ||
testFunc.call(context); | ||
} | ||
} | ||
} | ||
function logEntry(test, opts) { | ||
var priority = (_globals.global.probe && _globals.global.probe.priority) | 10; | ||
if ((opts.priority | 0) <= priority) { | ||
test.opts.log(opts); | ||
} | ||
} | ||
function logResultsAsMarkdownTable(_ref6) { | ||
var entry = _ref6.entry, | ||
id = _ref6.id, | ||
itersPerSecond = _ref6.itersPerSecond, | ||
time = _ref6.time; | ||
var COL1 = 50; | ||
var COL2 = 12; | ||
switch (entry) { | ||
case LOG_ENTRY.GROUP: | ||
console.log(''); | ||
console.log('| ' + (0, _formatters.rightPad)(id, COL1) + ' | iterations/s |'); | ||
console.log('| ' + (0, _formatters.rightPad)('---', COL1) + ' | --- |'); | ||
break; | ||
case LOG_ENTRY.TEST: | ||
console.log('| ' + (0, _formatters.rightPad)(id, COL1) + ' | ' + (0, _formatters.rightPad)(itersPerSecond, COL2) + ' |'); | ||
break; | ||
case LOG_ENTRY.COMPLETE: | ||
console.log(''); | ||
console.log('Completed benchmark in ' + time + 's'); | ||
break; | ||
default: | ||
} | ||
} | ||
function logResultsAsTree(_ref7) { | ||
var entry = _ref7.entry, | ||
id = _ref7.id, | ||
itersPerSecond = _ref7.itersPerSecond, | ||
time = _ref7.time; | ||
switch (entry) { | ||
case LOG_ENTRY.GROUP: | ||
console.log(''); | ||
console.log('' + id); | ||
break; | ||
case LOG_ENTRY.TEST: | ||
console.log('\u251C\u2500 ' + id + ': ' + itersPerSecond + ' iterations/s'); | ||
break; | ||
case LOG_ENTRY.COMPLETE: | ||
console.log(''); | ||
console.log('Completed benchmark in ' + time + 's'); | ||
break; | ||
default: | ||
} | ||
} | ||
function logResultsAsTreeWithElapsed(_ref8) { | ||
var entry = _ref8.entry, | ||
id = _ref8.id, | ||
itersPerSecond = _ref8.itersPerSecond, | ||
time = _ref8.time; | ||
switch (entry) { | ||
case LOG_ENTRY.TEST: | ||
console.log('\u251C\u2500 ' + id + ': ' + itersPerSecond + ' iterations/s (' + time.toFixed(2) + 's elapsed)'); | ||
break; | ||
default: | ||
logResultsAsTree({ entry: entry, id: id, itersPerSecond: itersPerSecond, time: time }); | ||
} | ||
} | ||
'use strict';var _createClass=function(){function defineProperties(target,props){for(var descriptor,i=0;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();Object.defineProperty(exports,'__esModule',{value:!0}),exports.LOG_ENTRY=void 0;exports.logResultsAsMarkdownTable=logResultsAsMarkdownTable,exports.logResultsAsTree=logResultsAsTree,exports.logResultsAsTreeWithElapsed=logResultsAsTreeWithElapsed;var _formatters=require('../lib/utils/formatters'),_globals=require('../lib/utils/globals'),_autobind=require('../lib/utils/autobind'),_localStorage=require('../lib/utils/local-storage'),_localStorage2=_interopRequireDefault(_localStorage),_assert=require('assert'),_assert2=_interopRequireDefault(_assert);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}var noop=function(){},TIME_THRESHOLD_MS=80,TIME_COOLDOWN_MS=5,MIN_ITERATIONS=1,LOG_ENTRY=exports.LOG_ENTRY={GROUP:'group',TEST:'test',COMPLETE:'complete'},CALIBRATION_TESTS=[{id:'warmup',initFunc:noop,testFunc:function testFunc(){return 100},opts:{}}],Bench=function(){function Bench(){var _ref=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},id=_ref.id,log=_ref.log,_ref$time=_ref.time,time=void 0===_ref$time?TIME_THRESHOLD_MS:_ref$time,_ref$delay=_ref.delay,delay=void 0===_ref$delay?TIME_COOLDOWN_MS:_ref$delay,_ref$minIterations=_ref.minIterations,minIterations=void 0===_ref$minIterations?MIN_ITERATIONS:_ref$minIterations;if(_classCallCheck(this,Bench),!log){var markdown=_globals.global.probe&&_globals.global.probe.markdown;log=markdown?logResultsAsMarkdownTable:logResultsAsTree}this.id=id,this.opts={log:log,time:time,delay:delay,minIterations:minIterations},this.tests={},this.results={},this.table={},(0,_autobind.autobind)(this),Object.seal(this)}var _Mathround=Math.round;return _createClass(Bench,[{key:'calibrate',value:function calibrate(){return this}},{key:'run',value:function run(){var _this=this,timer=new Date,tests=this.tests,onBenchmarkComplete=this.onBenchmarkComplete,promise=runAsyncTests({tests:tests,onBenchmarkComplete:onBenchmarkComplete});return promise.then(function(){var elapsed=(new Date-timer)/1e3;logEntry(_this,{entry:LOG_ENTRY.COMPLETE,time:elapsed,message:'Complete'}),_this.onSuiteComplete()}),promise}},{key:'group',value:function group(id){return(0,_assert2.default)(!this.tests[id],'tests need unique id strings'),this.tests[id]={id:id,group:!0,opts:this.opts},this}},{key:'add',value:function add(priority,id,func1,func2){'string'==typeof priority&&(func2=func1,func1=id,id=priority,priority=0),(0,_assert2.default)(id),(0,_assert2.default)('function'==typeof func1);var initFunc=null,testFunc=func1;return'function'==typeof func2&&(initFunc=func1,testFunc=func2),(0,_assert2.default)(!this.tests[id],'tests need unique id strings'),this.tests[id]={id:id,priority:priority,initFunc:initFunc,testFunc:testFunc,opts:this.opts},this}},{key:'onBenchmarkComplete',value:function onBenchmarkComplete(_ref2){var id=_ref2.id,time=_ref2.time,iterations=_ref2.iterations,itersPerSecond=_ref2.itersPerSecond,current=_Mathround(iterations/time);this.table[id]={percent:'',iterations:itersPerSecond+'/s',current:current,max:''}}},{key:'onSuiteComplete',value:function onSuiteComplete(){var localStorage=new _localStorage2.default({id:this.id}),saved=localStorage.getConfiguration(),current=this.updateTable(this.table,saved);localStorage.updateConfiguration(current),console.table(current)}},{key:'updateTable',value:function updateTable(current,saved){for(var id in this.table)if(saved[id]&&void 0!==saved[id].max){current[id].max=Math.max(current[id].current,saved[id].max);var delta=current[id].current/saved[id].max;current[id].percent=_Mathround(100*delta-100)+'%'}else current[id].max=current[id].current;return current}}]),Bench}();exports.default=Bench;function runCalibrationTests(_ref3){var tests=_ref3.tests,promise=Promise.resolve(!0),_iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0;try{for(var _step,_loop=function(){var test=_step.value;promise=promise.then(function(){return runAsyncTest({test:test,silent:!0})})},_iterator=CALIBRATION_TESTS[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0)_loop()}catch(err){_didIteratorError=!0,_iteratorError=err}finally{try{!_iteratorNormalCompletion&&_iterator.return&&_iterator.return()}finally{if(_didIteratorError)throw _iteratorError}}return promise}function runAsyncTests(_ref4){var tests=_ref4.tests,_ref4$onBenchmarkComp=_ref4.onBenchmarkComplete,onBenchmarkComplete=_ref4$onBenchmarkComp===void 0?noop:_ref4$onBenchmarkComp,promise=runCalibrationTests({tests:tests,onBenchmarkComplete:onBenchmarkComplete}),_loop2=function(id){var test=tests[id];promise=promise.then(function(){return runAsyncTest({test:test,onBenchmarkComplete:onBenchmarkComplete})})};for(var id in tests)_loop2(id);return promise}function runAsyncTest(_ref5){var test=_ref5.test,onBenchmarkComplete=_ref5.onBenchmarkComplete,_ref5$silent=_ref5.silent;return new Promise(function(resolve){setTimeout(function(){try{if(test.group)logEntry(test,{entry:LOG_ENTRY.GROUP,id:test.id,message:test.id});else{var _runBenchTest=runBenchTest(test),time=_runBenchTest.time,iterations=_runBenchTest.iterations,iterationsPerSecond=iterations/time,itersPerSecond=(0,_formatters.formatSI)(iterationsPerSecond);_ref5$silent!==void 0&&_ref5$silent||logEntry(test,{entry:LOG_ENTRY.TEST,id:test.id,priority:test.priority,itersPerSecond:itersPerSecond,time:time,message:test.id+' '+itersPerSecond+'/s'}),onBenchmarkComplete&&onBenchmarkComplete({id:test.id,time:time,iterations:iterations,iterationsPerSecond:iterationsPerSecond,itersPerSecond:itersPerSecond})}}finally{resolve(!0)}},test.opts.delay)})}function runBenchTest(test){for(var iterations=test.opts.minIterations/10,elapsedMillis=0;elapsedMillis<test.opts.time;){var multiplier=10;10<elapsedMillis&&(multiplier=1.25*(test.opts.time/elapsedMillis)),iterations*=multiplier;var timer=new Date;runBenchTestIterations(test,iterations),elapsedMillis=new Date-timer}var time=elapsedMillis/1e3;return{time:time,iterations:iterations}}function runBenchTestIterations(test,iterations){var testArgs=test.initFunc&&test.initFunc(),context=test.context,testFunc=test.testFunc;if(context&&testArgs)for(var i=0;i<iterations;i++)testFunc.call(context,testArgs);else for(var _i=0;_i<iterations;_i++)testFunc.call(context)}function logEntry(test,opts){var priority=10|(_globals.global.probe&&_globals.global.probe.priority);(0|opts.priority)<=priority&&test.opts.log(opts)}function logResultsAsMarkdownTable(_ref6){var entry=_ref6.entry,id=_ref6.id,itersPerSecond=_ref6.itersPerSecond,time=_ref6.time,COL1=50;switch(entry){case LOG_ENTRY.GROUP:console.log(''),console.log('| '+(0,_formatters.rightPad)(id,COL1)+' | iterations/s |'),console.log('| '+(0,_formatters.rightPad)('---',COL1)+' | --- |');break;case LOG_ENTRY.TEST:console.log('| '+(0,_formatters.rightPad)(id,COL1)+' | '+(0,_formatters.rightPad)(itersPerSecond,12)+' |');break;case LOG_ENTRY.COMPLETE:console.log(''),console.log('Completed benchmark in '+time+'s');break;default:}}function logResultsAsTree(_ref7){var entry=_ref7.entry,id=_ref7.id,itersPerSecond=_ref7.itersPerSecond,time=_ref7.time;switch(entry){case LOG_ENTRY.GROUP:console.log(''),console.log(''+id);break;case LOG_ENTRY.TEST:console.log('\u251C\u2500 '+id+': '+itersPerSecond+' iterations/s');break;case LOG_ENTRY.COMPLETE:console.log(''),console.log('Completed benchmark in '+time+'s');break;default:}}function logResultsAsTreeWithElapsed(_ref8){var entry=_ref8.entry,id=_ref8.id,itersPerSecond=_ref8.itersPerSecond,time=_ref8.time;entry===LOG_ENTRY.TEST?console.log('\u251C\u2500 '+id+': '+itersPerSecond+' iterations/s ('+time.toFixed(2)+'s elapsed)'):logResultsAsTree({entry:entry,id:id,itersPerSecond:itersPerSecond,time:time})} | ||
//# sourceMappingURL=bench.js.map |
@@ -1,41 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
var _bench = require('./bench'); | ||
Object.defineProperty(exports, 'Bench', { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_bench).default; | ||
} | ||
}); | ||
Object.defineProperty(exports, 'LOG_ENTRY', { | ||
enumerable: true, | ||
get: function get() { | ||
return _bench.LOG_ENTRY; | ||
} | ||
}); | ||
Object.defineProperty(exports, 'logResultsAsMarkdownTable', { | ||
enumerable: true, | ||
get: function get() { | ||
return _bench.logResultsAsMarkdownTable; | ||
} | ||
}); | ||
Object.defineProperty(exports, 'logResultsAsTree', { | ||
enumerable: true, | ||
get: function get() { | ||
return _bench.logResultsAsTree; | ||
} | ||
}); | ||
Object.defineProperty(exports, 'logResultsAsTreeWithElapsed', { | ||
enumerable: true, | ||
get: function get() { | ||
return _bench.logResultsAsTreeWithElapsed; | ||
} | ||
}); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var _bench=require('./bench');Object.defineProperty(exports,'Bench',{enumerable:!0,get:function get(){return _interopRequireDefault(_bench).default}}),Object.defineProperty(exports,'LOG_ENTRY',{enumerable:!0,get:function get(){return _bench.LOG_ENTRY}}),Object.defineProperty(exports,'logResultsAsMarkdownTable',{enumerable:!0,get:function get(){return _bench.logResultsAsMarkdownTable}}),Object.defineProperty(exports,'logResultsAsTree',{enumerable:!0,get:function get(){return _bench.logResultsAsTree}}),Object.defineProperty(exports,'logResultsAsTreeWithElapsed',{enumerable:!0,get:function get(){return _bench.logResultsAsTreeWithElapsed}});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} | ||
//# sourceMappingURL=index.js.map |
@@ -1,61 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.experimental = exports.Stats = exports.COLOR = exports.Log = exports.VERSION = undefined; | ||
var _globals = require('./lib/utils/globals'); | ||
Object.defineProperty(exports, 'VERSION', { | ||
enumerable: true, | ||
get: function get() { | ||
return _globals.VERSION; | ||
} | ||
}); | ||
var _log = require('./lib/log'); | ||
Object.defineProperty(exports, 'Log', { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_log).default; | ||
} | ||
}); | ||
var _color = require('./lib/utils/color'); | ||
Object.defineProperty(exports, 'COLOR', { | ||
enumerable: true, | ||
get: function get() { | ||
return _color.COLOR; | ||
} | ||
}); | ||
var _stats = require('./lib/stats'); | ||
Object.defineProperty(exports, 'Stats', { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_stats).default; | ||
} | ||
}); | ||
require('./init'); | ||
var _logToDom = require('./lib/utils/log-to-dom'); | ||
var _log2 = _interopRequireDefault(_log); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
// DOM logging | ||
var experimental = exports.experimental = { | ||
enableDOMLogging: _logToDom.enableDOMLogging | ||
}; | ||
// Default export is a log | ||
exports.default = new _log2.default({ id: 'probe.gl' }); | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.experimental=exports.Stats=exports.COLOR=exports.Log=exports.VERSION=void 0;var _globals=require('./lib/utils/globals');Object.defineProperty(exports,'VERSION',{enumerable:!0,get:function get(){return _globals.VERSION}});var _log=require('./lib/log');Object.defineProperty(exports,'Log',{enumerable:!0,get:function get(){return _interopRequireDefault(_log).default}});var _color=require('./lib/utils/color');Object.defineProperty(exports,'COLOR',{enumerable:!0,get:function get(){return _color.COLOR}});var _stats=require('./lib/stats');Object.defineProperty(exports,'Stats',{enumerable:!0,get:function get(){return _interopRequireDefault(_stats).default}}),require('./init');var _logToDom=require('./lib/utils/log-to-dom'),_log2=_interopRequireDefault(_log);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var experimental=exports.experimental={enableDOMLogging:_logToDom.enableDOMLogging};exports.default=new _log2.default({id:'probe.gl'}); | ||
//# sourceMappingURL=index.js.map |
@@ -1,6 +0,2 @@ | ||
'use strict'; | ||
var _globals = require('./lib/utils/globals'); | ||
_globals.global.probe = {}; | ||
'use strict';var _globals=require('./lib/utils/globals');_globals.global.probe={}; | ||
//# sourceMappingURL=init.js.map |
@@ -1,611 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
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 _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; }; }(); // Copyright (c) 2017 Uber Technologies, Inc. | ||
// | ||
// 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. | ||
/* eslint-disable no-console, no-try-catch */ | ||
/* global console */ | ||
var _globals = require('./utils/globals'); | ||
var _localStorage = require('./utils/local-storage'); | ||
var _localStorage2 = _interopRequireDefault(_localStorage); | ||
var _timestamp = require('./utils/timestamp'); | ||
var _formatters = require('./utils/formatters'); | ||
var _color = require('./utils/color'); | ||
var _autobind = require('./utils/autobind'); | ||
var _assert = require('assert'); | ||
var _assert2 = _interopRequireDefault(_assert); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
/* eslint-disable no-console */ | ||
/* global console, window, Image */ | ||
// Instrumentation in other packages may override console methods, so preserve them here | ||
var originalConsole = { | ||
debug: _globals.isBrowser ? console.debug || console.log : console.log, | ||
log: console.log, | ||
info: console.info, | ||
warn: console.warn, | ||
error: console.error | ||
}; | ||
var DEFAULT_SETTINGS = { | ||
enabled: false, | ||
priority: 0 | ||
}; | ||
function noop() {} | ||
var cache = {}; | ||
/* | ||
function throttle(tag, timeout) { | ||
const prevTime = cache[tag]; | ||
const time = Date.now(); | ||
if (!prevTime || (time - prevTime > timeout)) { | ||
cache[tag] = time; | ||
return true; | ||
} | ||
return false; | ||
} | ||
// Assertions don't generate standard exceptions and don't print nicely | ||
function checkForAssertionErrors(args) { | ||
const isAssertion = | ||
args && | ||
args.length > 0 && | ||
typeof args[0] === 'object' && | ||
args[0] !== null && | ||
args[0].name === 'AssertionError'; | ||
if (isAssertion) { | ||
args = Array.prototype.slice.call(args); | ||
args.unshift(`assert(${args[0].message})`); | ||
} | ||
return args; | ||
} | ||
*/ | ||
function getTableHeader(table) { | ||
for (var key in table) { | ||
for (var title in table[key]) { | ||
return title || 'untitled'; | ||
} | ||
} | ||
return 'empty'; | ||
} | ||
// A console wrapper | ||
var Log = function () { | ||
function Log() { | ||
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, | ||
id = _ref.id; | ||
_classCallCheck(this, Log); | ||
this.id = id; | ||
this.VERSION = _globals.VERSION; | ||
this._startTs = (0, _timestamp.getTimestamp)(); | ||
this._deltaTs = (0, _timestamp.getTimestamp)(); | ||
// TODO - fix support from throttling groups | ||
this.LOG_THROTTLE_TIMEOUT = 0; // Time before throttled messages are logged again | ||
this._storage = new _localStorage2.default('__probe-' + this.id + '__', DEFAULT_SETTINGS); | ||
this.userData = {}; | ||
this.timeStamp(this.id + ' started'); | ||
(0, _autobind.autobind)(this); | ||
Object.seal(this); | ||
} | ||
_createClass(Log, [{ | ||
key: 'isEnabled', | ||
value: function isEnabled() { | ||
return this._storage.config.enabled; | ||
} | ||
}, { | ||
key: 'getPriority', | ||
value: function getPriority() { | ||
return this._storage.config.priority; | ||
} | ||
}, { | ||
key: 'getLevel', | ||
value: function getLevel() { | ||
return this._storage.config.priority; | ||
} | ||
// @return {Number} milliseconds, with fractions | ||
}, { | ||
key: 'getTotal', | ||
value: function getTotal() { | ||
return Number(((0, _timestamp.getTimestamp)() - this._startTs).toPrecision(10)); | ||
} | ||
// @return {Number} milliseconds, with fractions | ||
}, { | ||
key: 'getDelta', | ||
value: function getDelta() { | ||
return Number(((0, _timestamp.getTimestamp)() - this._deltaTs).toPrecision(10)); | ||
} | ||
// Configure | ||
}, { | ||
key: 'enable', | ||
value: function enable() { | ||
var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; | ||
this._storage.updateConfiguration({ enabled: enabled }); | ||
return this; | ||
} | ||
}, { | ||
key: 'setLevel', | ||
value: function setLevel(level) { | ||
this._storage.updateConfiguration({ priority: level }); | ||
return this; | ||
} | ||
// Unconditional logging | ||
// Warn, but only once, no console flooding | ||
}, { | ||
key: 'warn', | ||
value: function warn(message) { | ||
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { | ||
args[_key - 1] = arguments[_key]; | ||
} | ||
return this._getLogFunction({ | ||
message: message, | ||
args: args, | ||
method: originalConsole.warn, | ||
once: true | ||
}); | ||
} | ||
// Print an error | ||
}, { | ||
key: 'error', | ||
value: function error(message) { | ||
for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | ||
args[_key2 - 1] = arguments[_key2]; | ||
} | ||
return this._getLogFunction({ message: message, args: args, method: originalConsole.error }); | ||
} | ||
}, { | ||
key: 'deprecated', | ||
value: function deprecated(oldUsage, newUsage) { | ||
return this.warn('`' + oldUsage + '` is deprecated and will be removed in a later version. Use `' + newUsage + '` instead'); | ||
} | ||
}, { | ||
key: 'removed', | ||
value: function removed(oldUsage, newUsage) { | ||
return this.error('`' + oldUsage + '` has been removed. Use `' + newUsage + '` instead'); | ||
} | ||
// Conditional logging | ||
// Log to a group | ||
}, { | ||
key: 'probe', | ||
value: function probe(priority, message) { | ||
for (var _len3 = arguments.length, args = Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { | ||
args[_key3 - 2] = arguments[_key3]; | ||
} | ||
return this._getLogFunction({ | ||
priority: priority, | ||
message: message, | ||
args: args, | ||
method: originalConsole.log, | ||
time: true | ||
}); | ||
} | ||
// Log a debug message | ||
}, { | ||
key: 'log', | ||
value: function log(priority, message) { | ||
for (var _len4 = arguments.length, args = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) { | ||
args[_key4 - 2] = arguments[_key4]; | ||
} | ||
return this._getLogFunction({ | ||
priority: priority, | ||
message: message, | ||
args: args, | ||
method: originalConsole.debug | ||
}); | ||
} | ||
// Log a normal message | ||
}, { | ||
key: 'info', | ||
value: function info(priority, message) { | ||
for (var _len5 = arguments.length, args = Array(_len5 > 2 ? _len5 - 2 : 0), _key5 = 2; _key5 < _len5; _key5++) { | ||
args[_key5 - 2] = arguments[_key5]; | ||
} | ||
return this._getLogFunction({ | ||
priority: priority, message: message, args: args, | ||
method: console.info | ||
}); | ||
} | ||
// Log a normal message, but only once, no console flooding | ||
}, { | ||
key: 'once', | ||
value: function once(priority, message) { | ||
for (var _len6 = arguments.length, args = Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) { | ||
args[_key6 - 2] = arguments[_key6]; | ||
} | ||
return this._getLogFunction({ | ||
priority: priority, | ||
message: message, | ||
args: args, | ||
method: originalConsole.debug || originalConsole.info, | ||
once: true | ||
}); | ||
} | ||
// Logs an object as a table | ||
}, { | ||
key: 'table', | ||
value: function table(priority, _table, columns) { | ||
if (_table) { | ||
var tag = getTableHeader(_table); | ||
return this._getLogFunction({ | ||
priority: priority, | ||
message: _table, | ||
args: columns && [columns], | ||
tag: tag, | ||
method: console.table || noop | ||
}); | ||
} | ||
return noop; | ||
} | ||
// logs an image under Chrome | ||
}, { | ||
key: 'image', | ||
value: function image(_ref2) { | ||
var priority = _ref2.priority, | ||
_image = _ref2.image, | ||
_ref2$message = _ref2.message, | ||
message = _ref2$message === undefined ? '' : _ref2$message, | ||
_ref2$scale = _ref2.scale, | ||
scale = _ref2$scale === undefined ? 1 : _ref2$scale; | ||
if (priority > this.getPriority()) { | ||
return noop; | ||
} | ||
if (typeof window === 'undefined') { | ||
// Let's not try this under node | ||
return noop; | ||
} | ||
if (typeof _image === 'string') { | ||
var img = new Image(); | ||
img.onload = function () { | ||
return console.log(_formatters.formatImage.bind(null, img, message, scale)); | ||
}; | ||
img.src = _image; | ||
} | ||
var element = _image.nodeName || ''; | ||
if (element.toLowerCase() === 'img') { | ||
console.log((0, _formatters.formatImage)(_image, message, scale)); | ||
} | ||
if (element.toLowerCase() === 'canvas') { | ||
var _img = new Image(); | ||
_img.onload = function () { | ||
return console.log(_formatters.formatImage.bind(null, _img, message, scale)); | ||
}; | ||
_img.src = _image.toDataURL(); | ||
} | ||
return noop; | ||
} | ||
}, { | ||
key: 'time', | ||
value: function time(priority, message) { | ||
return this._getLogFunction({ | ||
priority: priority, | ||
message: message, | ||
method: console.time ? console.time : console.info | ||
}); | ||
} | ||
}, { | ||
key: 'timeEnd', | ||
value: function timeEnd(priority, message) { | ||
return this._getLogFunction({ | ||
priority: priority, | ||
message: message, | ||
method: console.timeEnd ? console.timeEnd : console.info | ||
}); | ||
} | ||
}, { | ||
key: 'timeStamp', | ||
value: function timeStamp(priority, message) { | ||
return this._getLogFunction({ | ||
priority: priority, | ||
message: message, | ||
method: console.timeStamp || noop | ||
}); | ||
} | ||
}, { | ||
key: 'group', | ||
value: function group(priority, message) { | ||
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { collapsed: false }; | ||
opts = this._parseArguments({ priority: priority, message: message, opts: opts }); | ||
var _opts = opts, | ||
collapsed = _opts.collapsed; | ||
return this._getLogFunction({ | ||
priority: priority, | ||
message: message, | ||
opts: opts, | ||
method: (collapsed ? console.groupCollapsed : console.group) || console.info | ||
}); | ||
} | ||
}, { | ||
key: 'groupCollapsed', | ||
value: function groupCollapsed(priority, message) { | ||
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
return this.group(priority, message, Object.assign({}, opts, { collapsed: true })); | ||
} | ||
}, { | ||
key: 'groupEnd', | ||
value: function groupEnd(priority) { | ||
return this._getLogFunction({ | ||
priority: priority, | ||
message: '', | ||
method: console.groupEnd || noop | ||
}); | ||
} | ||
// EXPERIMENTAL | ||
}, { | ||
key: 'withGroup', | ||
value: function withGroup(priority, message, func) { | ||
var opts = this._parseArguments({ | ||
priority: priority, | ||
message: message | ||
}); | ||
this.group(opts); | ||
try { | ||
func(); | ||
} finally { | ||
this.groupEnd(opts.message); | ||
} | ||
} | ||
}, { | ||
key: 'trace', | ||
value: function trace() { | ||
if (console.trace) { | ||
console.trace(); | ||
} | ||
} | ||
// PRIVATE METHODS | ||
}, { | ||
key: '_shouldLog', | ||
value: function _shouldLog(priority) { | ||
(0, _assert2.default)(Number.isFinite(priority), 'log priority must be a number'); | ||
return priority === 0 || this.isEnabled() && this.getPriority() >= priority; | ||
} | ||
}, { | ||
key: '_getElapsedTime', | ||
value: function _getElapsedTime() { | ||
var total = this.getTotal(); | ||
var delta = this.getDelta(); | ||
// reset delta timer | ||
this._deltaTs = (0, _timestamp.getTimestamp)(); | ||
return { total: total, delta: delta }; | ||
} | ||
}, { | ||
key: '_getLogFunction', | ||
value: function _getLogFunction(opts) { | ||
var _opts2 = opts, | ||
method = _opts2.method; | ||
opts = this._parseArguments(opts); | ||
(0, _assert2.default)(method); | ||
if (this._shouldLog(opts.priority)) { | ||
var _opts3 = opts, | ||
message = _opts3.message; | ||
var tag = opts.tag || opts.message; | ||
if (opts.once) { | ||
if (!cache[tag]) { | ||
cache[tag] = (0, _timestamp.getTimestamp)(); | ||
} else { | ||
return noop; | ||
} | ||
} | ||
// TODO - Make throttling work with groups | ||
// if (opts.nothrottle || !throttle(tag, this.LOG_THROTTLE_TIMEOUT)) { | ||
// return noop; | ||
// } | ||
message = this._decorateMessage(message, opts); | ||
// Bind console function so that it can be called after being returned | ||
return method.bind.apply(method, [console, message].concat(_toConsumableArray(opts.args))); | ||
} | ||
return noop; | ||
} | ||
// "Normalizes" the various argument patterns into an object with known types | ||
// - log(priority, message, args) => {priority, message, args} | ||
// - log(message, args) => {priority: 0, message, args} | ||
// - log({priority, ...}, message, args) => {priority, message, args} | ||
// - log({priority, message, args}) => {priority, message, args} | ||
}, { | ||
key: '_parseArguments', | ||
value: function _parseArguments(options) { | ||
var priority = options.priority, | ||
message = options.message, | ||
_options$args = options.args, | ||
args = _options$args === undefined ? [] : _options$args, | ||
_options$opts = options.opts, | ||
opts = _options$opts === undefined ? {} : _options$opts; | ||
var normOpts = this._normalizeArguments({ priority: priority, message: message, args: args }); | ||
var _getElapsedTime2 = this._getElapsedTime(), | ||
delta = _getElapsedTime2.delta, | ||
total = _getElapsedTime2.total; | ||
// original opts + normalized opts + opts arg + fixed up message + timings | ||
return Object.assign(options, normOpts, opts, { | ||
delta: delta, | ||
total: total | ||
}); | ||
} | ||
// helper for _parseArguments | ||
}, { | ||
key: '_normalizeArguments', | ||
value: function _normalizeArguments(_ref3) { | ||
var priority = _ref3.priority, | ||
message = _ref3.message, | ||
_ref3$args = _ref3.args, | ||
args = _ref3$args === undefined ? [] : _ref3$args; | ||
var newOpts = null; | ||
switch (typeof priority === 'undefined' ? 'undefined' : _typeof(priority)) { | ||
case 'number': | ||
(0, _assert2.default)(priority >= 0); | ||
newOpts = { priority: priority, message: message, args: args }; | ||
break; | ||
case 'string': | ||
case 'function': | ||
if (message !== undefined) { | ||
args.unshift(message); | ||
} | ||
newOpts = { priority: 0, message: priority, args: args }; | ||
break; | ||
case 'object': | ||
var opts = priority; | ||
newOpts = Object.assign({ priority: 0, message: message, args: args }, opts); | ||
break; | ||
default: | ||
newOpts = { priority: 0, message: message, args: args }; | ||
break; | ||
} | ||
(0, _assert2.default)(Number.isFinite(newOpts.priority)); // 'log priority must be a number' | ||
// Resolve functions into strings by calling them | ||
if (typeof newOpts.message === 'function') { | ||
newOpts.message = this._shouldLog(newOpts.priority) ? newOpts.message() : ''; | ||
} | ||
// 'log message must be a string' or object | ||
(0, _assert2.default)(typeof newOpts.message === 'string' || _typeof(newOpts.message) === 'object'); | ||
return newOpts; | ||
} | ||
}, { | ||
key: '_decorateMessage', | ||
value: function _decorateMessage(message, opts) { | ||
if (typeof message === 'string') { | ||
var time = ''; | ||
if (opts.time) { | ||
var _getElapsedTime3 = this._getElapsedTime(), | ||
total = _getElapsedTime3.total; | ||
time = (0, _formatters.leftPad)((0, _formatters.formatTime)(total)); | ||
} | ||
message = opts.time ? this.id + ': ' + time + ' ' + message : this.id + ': ' + time + ' ' + message; | ||
message = (0, _color.addColor)(message, opts.color, opts.background); | ||
} | ||
return message; | ||
} | ||
}, { | ||
key: 'priority', | ||
set: function set(newPriority) { | ||
this._storage.updateConfiguration({ priority: newPriority }); | ||
return this; | ||
}, | ||
get: function get() { | ||
return this._storage.config.priority; | ||
} | ||
}]); | ||
return Log; | ||
}(); | ||
exports.default = Log; | ||
Log.VERSION = _globals.VERSION; | ||
'use strict';var _typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj},_createClass=function(){function defineProperties(target,props){for(var descriptor,i=0;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_globals=require('./utils/globals'),_localStorage=require('./utils/local-storage'),_localStorage2=_interopRequireDefault(_localStorage),_timestamp=require('./utils/timestamp'),_formatters=require('./utils/formatters'),_color=require('./utils/color'),_autobind=require('./utils/autobind'),_assert=require('../lib/utils/assert'),_assert2=_interopRequireDefault(_assert);Object.defineProperty(exports,'__esModule',{value:!0});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _toConsumableArray(arr){if(Array.isArray(arr)){for(var i=0,arr2=Array(arr.length);i<arr.length;i++)arr2[i]=arr[i];return arr2}return Array.from(arr)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}var originalConsole={debug:_globals.isBrowser?console.debug||console.log:console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},DEFAULT_SETTINGS={enabled:!1,priority:0};function noop(){}var cache={};function getTableHeader(table){for(var key in table)for(var title in table[key])return title||'untitled';return'empty'}var Log=function(){function Log(){var _ref=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},id=_ref.id;_classCallCheck(this,Log),this.id=id,this.VERSION=_globals.VERSION,this._startTs=(0,_timestamp.getTimestamp)(),this._deltaTs=(0,_timestamp.getTimestamp)(),this.LOG_THROTTLE_TIMEOUT=0,this._storage=new _localStorage2.default('__probe-'+this.id+'__',DEFAULT_SETTINGS),this.userData={},this.timeStamp(this.id+' started'),(0,_autobind.autobind)(this),Object.seal(this)}var _NumberisFinite=Number.isFinite;return _createClass(Log,[{key:'isEnabled',value:function isEnabled(){return this._storage.config.enabled}},{key:'getPriority',value:function getPriority(){return this._storage.config.priority}},{key:'getLevel',value:function getLevel(){return this._storage.config.priority}},{key:'getTotal',value:function getTotal(){return+((0,_timestamp.getTimestamp)()-this._startTs).toPrecision(10)}},{key:'getDelta',value:function getDelta(){return+((0,_timestamp.getTimestamp)()-this._deltaTs).toPrecision(10)}},{key:'enable',value:function enable(){var enabled=!(0<arguments.length&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:enabled}),this}},{key:'setLevel',value:function setLevel(level){return this._storage.updateConfiguration({priority:level}),this}},{key:'warn',value:function warn(message){for(var _len=arguments.length,args=Array(1<_len?_len-1:0),_key=1;_key<_len;_key++)args[_key-1]=arguments[_key];return this._getLogFunction({message:message,args:args,method:originalConsole.warn,once:!0})}},{key:'error',value:function error(message){for(var _len2=arguments.length,args=Array(1<_len2?_len2-1:0),_key2=1;_key2<_len2;_key2++)args[_key2-1]=arguments[_key2];return this._getLogFunction({message:message,args:args,method:originalConsole.error})}},{key:'deprecated',value:function deprecated(oldUsage,newUsage){return this.warn('`'+oldUsage+'` is deprecated and will be removed in a later version. Use `'+newUsage+'` instead')}},{key:'removed',value:function removed(oldUsage,newUsage){return this.error('`'+oldUsage+'` has been removed. Use `'+newUsage+'` instead')}},{key:'probe',value:function probe(priority,message){for(var _len3=arguments.length,args=Array(2<_len3?_len3-2:0),_key3=2;_key3<_len3;_key3++)args[_key3-2]=arguments[_key3];return this._getLogFunction({priority:priority,message:message,args:args,method:originalConsole.log,time:!0})}},{key:'log',value:function log(priority,message){for(var _len4=arguments.length,args=Array(2<_len4?_len4-2:0),_key4=2;_key4<_len4;_key4++)args[_key4-2]=arguments[_key4];return this._getLogFunction({priority:priority,message:message,args:args,method:originalConsole.debug})}},{key:'info',value:function info(priority,message){for(var _len5=arguments.length,args=Array(2<_len5?_len5-2:0),_key5=2;_key5<_len5;_key5++)args[_key5-2]=arguments[_key5];return this._getLogFunction({priority:priority,message:message,args:args,method:console.info})}},{key:'once',value:function once(priority,message){for(var _len6=arguments.length,args=Array(2<_len6?_len6-2:0),_key6=2;_key6<_len6;_key6++)args[_key6-2]=arguments[_key6];return this._getLogFunction({priority:priority,message:message,args:args,method:originalConsole.debug||originalConsole.info,once:!0})}},{key:'table',value:function table(priority,_table,columns){if(_table){var tag=getTableHeader(_table);return this._getLogFunction({priority:priority,message:_table,args:columns&&[columns],tag:tag,method:console.table||noop})}return noop}},{key:'image',value:function image(_ref2){var priority=_ref2.priority,_image=_ref2.image,_ref2$message=_ref2.message,message=void 0===_ref2$message?'':_ref2$message,_ref2$scale=_ref2.scale,scale=void 0===_ref2$scale?1:_ref2$scale;if(priority>this.getPriority())return noop;if('undefined'==typeof window)return noop;if('string'==typeof _image){var img=new Image;img.onload=function(){return console.log(_formatters.formatImage.bind(null,img,message,scale))},img.src=_image}var element=_image.nodeName||'';if('img'===element.toLowerCase()&&console.log((0,_formatters.formatImage)(_image,message,scale)),'canvas'===element.toLowerCase()){var _img=new Image;_img.onload=function(){return console.log(_formatters.formatImage.bind(null,_img,message,scale))},_img.src=_image.toDataURL()}return noop}},{key:'time',value:function time(priority,message){return this._getLogFunction({priority:priority,message:message,method:console.time?console.time:console.info})}},{key:'timeEnd',value:function timeEnd(priority,message){return this._getLogFunction({priority:priority,message:message,method:console.timeEnd?console.timeEnd:console.info})}},{key:'timeStamp',value:function timeStamp(priority,message){return this._getLogFunction({priority:priority,message:message,method:console.timeStamp||noop})}},{key:'group',value:function group(priority,message){var opts=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{collapsed:!1};opts=this._parseArguments({priority:priority,message:message,opts:opts});var _opts=opts,collapsed=_opts.collapsed;return this._getLogFunction({priority:priority,message:message,opts:opts,method:(collapsed?console.groupCollapsed:console.group)||console.info})}},{key:'groupCollapsed',value:function groupCollapsed(priority,message){var opts=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};return this.group(priority,message,Object.assign({},opts,{collapsed:!0}))}},{key:'groupEnd',value:function groupEnd(priority){return this._getLogFunction({priority:priority,message:'',method:console.groupEnd||noop})}},{key:'withGroup',value:function withGroup(priority,message,func){var opts=this._parseArguments({priority:priority,message:message});this.group(opts);try{func()}finally{this.groupEnd(opts.message)}}},{key:'trace',value:function trace(){console.trace&&console.trace()}},{key:'_shouldLog',value:function _shouldLog(priority){return(0,_assert2.default)(_NumberisFinite(priority),'log priority must be a number'),0===priority||this.isEnabled()&&this.getPriority()>=priority}},{key:'_getElapsedTime',value:function _getElapsedTime(){var total=this.getTotal(),delta=this.getDelta();return this._deltaTs=(0,_timestamp.getTimestamp)(),{total:total,delta:delta}}},{key:'_getLogFunction',value:function _getLogFunction(opts){var _opts2=opts,method=_opts2.method;if(opts=this._parseArguments(opts),(0,_assert2.default)(method),this._shouldLog(opts.priority)){var _opts3=opts,message=_opts3.message,tag=opts.tag||opts.message;if(opts.once)if(!cache[tag])cache[tag]=(0,_timestamp.getTimestamp)();else return noop;return message=this._decorateMessage(message,opts),method.bind.apply(method,[console,message].concat(_toConsumableArray(opts.args)))}return noop}},{key:'_parseArguments',value:function _parseArguments(options){var priority=options.priority,message=options.message,_options$args=options.args,args=void 0===_options$args?[]:_options$args,_options$opts=options.opts,opts=void 0===_options$opts?{}:_options$opts,normOpts=this._normalizeArguments({priority:priority,message:message,args:args}),_getElapsedTime2=this._getElapsedTime(),delta=_getElapsedTime2.delta,total=_getElapsedTime2.total;return Object.assign(options,normOpts,opts,{delta:delta,total:total})}},{key:'_normalizeArguments',value:function _normalizeArguments(_ref3){var priority=_ref3.priority,message=_ref3.message,_ref3$args=_ref3.args,args=void 0===_ref3$args?[]:_ref3$args,newOpts=null;switch('undefined'==typeof priority?'undefined':_typeof(priority)){case'number':(0,_assert2.default)(0<=priority),newOpts={priority:priority,message:message,args:args};break;case'string':case'function':void 0!==message&&args.unshift(message),newOpts={priority:0,message:priority,args:args};break;case'object':newOpts=Object.assign({priority:0,message:message,args:args},priority);break;default:newOpts={priority:0,message:message,args:args};}return(0,_assert2.default)(_NumberisFinite(newOpts.priority)),'function'==typeof newOpts.message&&(newOpts.message=this._shouldLog(newOpts.priority)?newOpts.message():''),(0,_assert2.default)('string'==typeof newOpts.message||'object'===_typeof(newOpts.message)),newOpts}},{key:'_decorateMessage',value:function _decorateMessage(message,opts){if('string'==typeof message){var time='';if(opts.time){var _getElapsedTime3=this._getElapsedTime(),total=_getElapsedTime3.total;time=(0,_formatters.leftPad)((0,_formatters.formatTime)(total))}message=opts.time?this.id+': '+time+' '+message:this.id+': '+time+' '+message,message=(0,_color.addColor)(message,opts.color,opts.background)}return message}},{key:'priority',set:function set(newPriority){return this._storage.updateConfiguration({priority:newPriority}),this},get:function get(){return this._storage.config.priority}}]),Log}();exports.default=Log,Log.VERSION=_globals.VERSION; | ||
//# sourceMappingURL=log.js.map |
@@ -1,219 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
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 _timestamp = require('./utils/timestamp'); | ||
var _formatters = require('./utils/formatters'); | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
// const MAX_FPS = 70; | ||
var Stats = function () { | ||
function Stats(_ref) { | ||
var id = _ref.id; | ||
_classCallCheck(this, Stats); | ||
this.id = id; | ||
this.time = (0, _timestamp.getTimestamp)(); | ||
this.counters = {}; | ||
Object.seal(this); | ||
} | ||
// Initialize a new counter | ||
_createClass(Stats, [{ | ||
key: 'addCounter', | ||
value: function addCounter(name) { | ||
this._getCounter(name); | ||
return this; | ||
} | ||
// Call to bump a counter (+1) | ||
}, { | ||
key: 'bump', | ||
value: function bump(name) { | ||
var counter = this._getCounter(name); | ||
counter.call++; | ||
counter.count++; | ||
return this; | ||
} | ||
// Call to bump a counter | ||
}, { | ||
key: 'increment', | ||
value: function increment(name, count) { | ||
var counter = this._getCounter(name); | ||
counter.call++; | ||
counter.count += count; | ||
return this; | ||
} | ||
}, { | ||
key: 'addTimer', | ||
value: function addTimer(name) { | ||
var timer = this._getCounter(name); | ||
timer.time = 0; | ||
return this; | ||
} | ||
}, { | ||
key: 'addTime', | ||
value: function addTime(name, time) { | ||
var timer = this._getCounter(name); | ||
timer.time += time; | ||
timer.count++; | ||
return this; | ||
} | ||
}, { | ||
key: 'timeStart', | ||
value: function timeStart(name, subname) { | ||
var timer = this._getCounter(name); | ||
timer._startTime = (0, _timestamp.getTimestamp)(); | ||
} | ||
}, { | ||
key: 'timeEnd', | ||
value: function timeEnd(name, subname) { | ||
var timer = this._getCounter(name); | ||
this.addTime(name, (0, _timestamp.getTimestamp)() - timer._startTime); | ||
} | ||
// Reset all timers | ||
}, { | ||
key: 'reset', | ||
value: function reset() { | ||
this.time = (0, _timestamp.getTimestamp)(); | ||
for (var key in this.counters) { | ||
var counter = this.counters[key]; | ||
counter.count = 0; | ||
counter.time = 0; | ||
} | ||
return this; | ||
} | ||
// ACCESSORS | ||
}, { | ||
key: 'hasTimeElapsed', | ||
value: function hasTimeElapsed() { | ||
var deltaTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1000; | ||
return (0, _timestamp.getTimestamp)() - this.time > 1000; | ||
} | ||
}, { | ||
key: 'getStats', | ||
value: function getStats() { | ||
var deltaTime = ((0, _timestamp.getTimestamp)() - this.time) / 1000; | ||
var stats = {}; | ||
for (var key in this.counters) { | ||
var counter = this.counters[key]; | ||
stats[counter.title] = { | ||
total: counter.count, | ||
fps: Math.round(counter.count / deltaTime) | ||
}; | ||
if (counter.time) { | ||
stats[counter.title].totalTime = (0, _formatters.formatTime)(counter.time); | ||
stats[counter.title].avgTime = (0, _formatters.formatTime)(counter.time / counter.count); | ||
} | ||
} | ||
return stats; | ||
} | ||
// Return stats in a "table format" suitable for console.table() or Log.table() | ||
}, { | ||
key: 'getStatsTable', | ||
value: function getStatsTable() { | ||
var stats = this.getStats(); | ||
for (var key in stats) { | ||
if (stats[key].total === 0) { | ||
delete stats[key]; | ||
} | ||
} | ||
return stats; | ||
} | ||
// Returns the names of all registered stats, enables iteration | ||
}, { | ||
key: 'getStatNames', | ||
value: function getStatNames() { | ||
return Object.keys(this.counters); | ||
} | ||
}, { | ||
key: 'get', | ||
value: function get(name) { | ||
var counter = this._getCounter(name); | ||
return counter.count; | ||
} | ||
}, { | ||
key: 'getCount', | ||
value: function getCount(name) { | ||
var counter = this._getCounter(name); | ||
return counter.count; | ||
} | ||
}, { | ||
key: 'getFPS', | ||
value: function getFPS(name) { | ||
var counter = this._getCounter(name); | ||
var deltaTime = ((0, _timestamp.getTimestamp)() - this.time) / 1000; | ||
return Math.round(counter.count / deltaTime); | ||
} | ||
// DEPRECATED METHODS | ||
}, { | ||
key: 'getTimeString', | ||
value: function getTimeString() { | ||
return this.id + ':' + (0, _formatters.formatTime)(this.time) + '(' + this.count + ')'; | ||
} | ||
}, { | ||
key: 'oneSecondPassed', | ||
value: function oneSecondPassed() { | ||
var deltaTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1000; | ||
return this.hasTimeElapsed(deltaTime); | ||
} | ||
// PRIVATE METHODS | ||
}, { | ||
key: '_getCounter', | ||
value: function _getCounter(name) { | ||
var counter = this.counters[name]; | ||
if (!counter) { | ||
counter = { | ||
title: name, | ||
unit: '', | ||
timer: false, | ||
count: 0, | ||
time: 0, | ||
totalTime: 0, | ||
averageTime: 0 | ||
}; | ||
this.counters[name] = counter; | ||
} | ||
return counter; | ||
} | ||
}, { | ||
key: '_incrementTimer', | ||
value: function _incrementTimer(counter, time, count) { | ||
counter.count += count; | ||
counter.totalTime += time; | ||
counter.averageTime = counter.totalTime / count; | ||
} | ||
}]); | ||
return Stats; | ||
}(); | ||
exports.default = Stats; | ||
'use strict';var _createClass=function(){function defineProperties(target,props){for(var descriptor,i=0;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_timestamp=require('./utils/timestamp'),_formatters=require('./utils/formatters');Object.defineProperty(exports,'__esModule',{value:!0});function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}var Stats=function(){function Stats(_ref){var id=_ref.id;_classCallCheck(this,Stats),this.id=id,this.time=(0,_timestamp.getTimestamp)(),this.counters={},Object.seal(this)}var _Mathround=Math.round;return _createClass(Stats,[{key:'addCounter',value:function addCounter(name){return this._getCounter(name),this}},{key:'bump',value:function bump(name){var counter=this._getCounter(name);return counter.call++,counter.count++,this}},{key:'increment',value:function increment(name,count){var counter=this._getCounter(name);return counter.call++,counter.count+=count,this}},{key:'addTimer',value:function addTimer(name){var timer=this._getCounter(name);return timer.time=0,this}},{key:'addTime',value:function addTime(name,time){var timer=this._getCounter(name);return timer.time+=time,timer.count++,this}},{key:'timeStart',value:function timeStart(name){var timer=this._getCounter(name);timer._startTime=(0,_timestamp.getTimestamp)()}},{key:'timeEnd',value:function timeEnd(name){var timer=this._getCounter(name);this.addTime(name,(0,_timestamp.getTimestamp)()-timer._startTime)}},{key:'reset',value:function reset(){for(var key in this.time=(0,_timestamp.getTimestamp)(),this.counters){var counter=this.counters[key];counter.count=0,counter.time=0}return this}},{key:'hasTimeElapsed',value:function hasTimeElapsed(){0<arguments.length&&void 0!==arguments[0]?arguments[0]:1e3;return 1e3<(0,_timestamp.getTimestamp)()-this.time}},{key:'getStats',value:function getStats(){var deltaTime=((0,_timestamp.getTimestamp)()-this.time)/1e3,stats={};for(var key in this.counters){var counter=this.counters[key];stats[counter.title]={total:counter.count,fps:_Mathround(counter.count/deltaTime)},counter.time&&(stats[counter.title].totalTime=(0,_formatters.formatTime)(counter.time),stats[counter.title].avgTime=(0,_formatters.formatTime)(counter.time/counter.count))}return stats}},{key:'getStatsTable',value:function getStatsTable(){var stats=this.getStats();for(var key in stats)0===stats[key].total&&delete stats[key];return stats}},{key:'getStatNames',value:function getStatNames(){return Object.keys(this.counters)}},{key:'get',value:function get(name){var counter=this._getCounter(name);return counter.count}},{key:'getCount',value:function getCount(name){var counter=this._getCounter(name);return counter.count}},{key:'getFPS',value:function getFPS(name){var counter=this._getCounter(name),deltaTime=((0,_timestamp.getTimestamp)()-this.time)/1e3;return _Mathround(counter.count/deltaTime)}},{key:'getTimeString',value:function getTimeString(){return this.id+':'+(0,_formatters.formatTime)(this.time)+'('+this.count+')'}},{key:'oneSecondPassed',value:function oneSecondPassed(){var deltaTime=0<arguments.length&&void 0!==arguments[0]?arguments[0]:1e3;return this.hasTimeElapsed(deltaTime)}},{key:'_getCounter',value:function _getCounter(name){var counter=this.counters[name];return counter||(counter={title:name,unit:'',timer:!1,count:0,time:0,totalTime:0,averageTime:0},this.counters[name]=counter),counter}},{key:'_incrementTimer',value:function _incrementTimer(counter,time,count){counter.count+=count,counter.totalTime+=time,counter.averageTime=counter.totalTime/count}}]),Stats}();exports.default=Stats; | ||
//# sourceMappingURL=stats.js.map |
@@ -1,71 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.autobind = autobind; | ||
// Copyright (c) 2015 - 2017 Uber Technologies, Inc. | ||
// | ||
// 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. | ||
/** | ||
* Binds the "this" argument of all functions on a class instance to the instance | ||
* @param {Object} obj - class instance (typically a react component) | ||
*/ | ||
function autobind(obj) { | ||
var predefined = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['constructor']; | ||
var proto = Object.getPrototypeOf(obj); | ||
var propNames = Object.getOwnPropertyNames(proto); | ||
var _iteratorNormalCompletion = true; | ||
var _didIteratorError = false; | ||
var _iteratorError = undefined; | ||
try { | ||
var _loop = function _loop() { | ||
var key = _step.value; | ||
if (typeof obj[key] === 'function') { | ||
if (!predefined.find(function (name) { | ||
return key === name; | ||
})) { | ||
obj[key] = obj[key].bind(obj); | ||
} | ||
} | ||
}; | ||
for (var _iterator = propNames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { | ||
_loop(); | ||
} | ||
} catch (err) { | ||
_didIteratorError = true; | ||
_iteratorError = err; | ||
} finally { | ||
try { | ||
if (!_iteratorNormalCompletion && _iterator.return) { | ||
_iterator.return(); | ||
} | ||
} finally { | ||
if (_didIteratorError) { | ||
throw _iteratorError; | ||
} | ||
} | ||
} | ||
} | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.autobind=autobind;function autobind(obj){var predefined=1<arguments.length&&arguments[1]!==void 0?arguments[1]:['constructor'],proto=Object.getPrototypeOf(obj),propNames=Object.getOwnPropertyNames(proto),_iteratorNormalCompletion=!0,_didIteratorError=!1,_iteratorError=void 0;try{for(var _step,_loop=function(){var key=_step.value;'function'!=typeof obj[key]||predefined.find(function(name){return key===name})||(obj[key]=obj[key].bind(obj))},_iterator=propNames[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=!0)_loop()}catch(err){_didIteratorError=!0,_iteratorError=err}finally{try{!_iteratorNormalCompletion&&_iterator.return&&_iterator.return()}finally{if(_didIteratorError)throw _iteratorError}}} | ||
//# sourceMappingURL=autobind.js.map |
@@ -1,49 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.COLOR = undefined; | ||
exports.addColor = addColor; | ||
var _globals = require('./globals'); | ||
var COLOR = exports.COLOR = { | ||
BLACK: 30, | ||
RED: 31, | ||
GREEN: 32, | ||
YELLOW: 33, | ||
BLUE: 34, | ||
MAGENTA: 35, | ||
CYAN: 36, | ||
WHITE: 37, | ||
BRIGHT_BLACK: 90, | ||
BRIGHT_RED: 91, | ||
BRIGHT_GREEN: 92, | ||
BRIGHT_YELLOW: 93, | ||
BRIGHT_BLUE: 94, | ||
BRIGHT_MAGENTA: 95, | ||
BRIGHT_CYAN: 96, | ||
BRIGHT_WHITE: 97 | ||
}; | ||
function getColor(color) { | ||
return typeof color === 'string' ? COLOR[color.toUpperCase()] || COLOR.WHITE : color; | ||
} | ||
function addColor(string, color, background) { | ||
if (!_globals.isBrowser && typeof string === 'string') { | ||
if (color) { | ||
color = getColor(color); | ||
string = '\x1B[' + color + 'm' + string + '\x1B[39m'; | ||
} | ||
if (background) { | ||
// background colors values are +10 | ||
color = getColor(background); | ||
string = '\x1B[' + (background + 10) + 'm' + string + '\x1B[49m'; | ||
} | ||
} | ||
return string; | ||
} | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.COLOR=void 0,exports.addColor=addColor;var _globals=require('./globals'),COLOR=exports.COLOR={BLACK:30,RED:31,GREEN:32,YELLOW:33,BLUE:34,MAGENTA:35,CYAN:36,WHITE:37,BRIGHT_BLACK:90,BRIGHT_RED:91,BRIGHT_GREEN:92,BRIGHT_YELLOW:93,BRIGHT_BLUE:94,BRIGHT_MAGENTA:95,BRIGHT_CYAN:96,BRIGHT_WHITE:97};function getColor(color){return'string'==typeof color?COLOR[color.toUpperCase()]||COLOR.WHITE:color}function addColor(string,color,background){return _globals.isBrowser||'string'!=typeof string||(color&&(color=getColor(color),string='\x1B['+color+'m'+string+'\x1B[39m'),background&&(color=getColor(background),string='\x1B['+(background+10)+'m'+string+'\x1B[49m')),string} | ||
//# sourceMappingURL=color.js.map |
@@ -1,134 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.formatTime = formatTime; | ||
exports.leftPad = leftPad; | ||
exports.rightPad = rightPad; | ||
exports.getSISuffix = getSISuffix; | ||
exports.formatSI = formatSI; | ||
exports.formatValue = formatValue; | ||
exports.formatImage = formatImage; | ||
// TODO: Currently unused, keeping in case we want it later for log formatting | ||
function formatTime(ms) { | ||
var formatted = void 0; | ||
if (ms < 10) { | ||
formatted = ms.toFixed(2) + 'ms'; | ||
} else if (ms < 100) { | ||
formatted = ms.toFixed(1) + 'ms'; | ||
} else if (ms < 1000) { | ||
formatted = ms.toFixed(0) + 'ms'; | ||
} else { | ||
formatted = (ms / 1000).toFixed(2) + 's'; | ||
} | ||
return formatted; | ||
} | ||
function leftPad(string) { | ||
var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8; | ||
var padLength = Math.max(length - string.length, 0); | ||
return '' + ' '.repeat(padLength) + string; | ||
} | ||
function rightPad(string) { | ||
var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 8; | ||
var padLength = Math.max(length - string.length, 0); | ||
return '' + string + ' '.repeat(padLength); | ||
} | ||
// Breaks a number into a normalized base and an exponent | ||
// E.g. 5640 => {5.64, 1000} | ||
function splitIntoBaseAndExponent(number) { | ||
var base = number; | ||
var exponent = 0; | ||
if (number !== 0) { | ||
while (base >= 10 || base <= -10) { | ||
base /= 10; | ||
exponent++; | ||
} | ||
while (base < 1 && base > -1) { | ||
base *= 10; | ||
exponent--; | ||
} | ||
} | ||
return { base: base, exponent: exponent }; | ||
} | ||
function getSISuffix(multipleOf3) { | ||
var SI_SUFFIXES = { 0: '', 1: 'K', 2: 'M', 3: 'G', '-1': 'm', '-2': 'µ', '-3': 'n' }; | ||
var key = String(multipleOf3); | ||
return key in SI_SUFFIXES ? SI_SUFFIXES[key] : 'e' + multipleOf3 * 3; | ||
} | ||
function formatSI(number) { | ||
var precision = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3; | ||
var _splitIntoBaseAndExpo = splitIntoBaseAndExponent(number), | ||
base = _splitIntoBaseAndExpo.base, | ||
exponent = _splitIntoBaseAndExpo.exponent; | ||
var multipleOf3 = Math.floor(exponent / 3); | ||
var remaining = exponent - multipleOf3 * 3; | ||
var digits = base * Math.pow(10, remaining); | ||
return '' + digits.toPrecision(precision) + getSISuffix(multipleOf3); | ||
} | ||
function formatValue(v) { | ||
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var EPSILON = 1e-16; | ||
var _opts$isInteger = opts.isInteger, | ||
isInteger = _opts$isInteger === undefined ? false : _opts$isInteger; | ||
if (Array.isArray(v) || ArrayBuffer.isView(v)) { | ||
return formatArrayValue(v, opts); | ||
} | ||
if (!Number.isFinite(v)) { | ||
return String(v); | ||
} | ||
if (Math.abs(v) < EPSILON) { | ||
return isInteger ? '0' : '0.'; | ||
} | ||
if (isInteger) { | ||
return v.toFixed(0); | ||
} | ||
if (Math.abs(v) > 100 && Math.abs(v) < 10000) { | ||
return v.toFixed(0); | ||
} | ||
var string = v.toPrecision(2); | ||
var decimal = string.indexOf('.0'); | ||
return decimal === string.length - 2 ? string.slice(0, -1) : string; | ||
} | ||
// Helper to formatValue | ||
function formatArrayValue(v, opts) { | ||
var _opts$maxElts = opts.maxElts, | ||
maxElts = _opts$maxElts === undefined ? 16 : _opts$maxElts, | ||
_opts$size = opts.size, | ||
size = _opts$size === undefined ? 1 : _opts$size; | ||
var string = '['; | ||
for (var i = 0; i < v.length && i < maxElts; ++i) { | ||
if (i > 0) { | ||
string += ',' + (i % size === 0 ? ' ' : ''); | ||
} | ||
string += formatValue(v[i], opts); | ||
} | ||
var terminator = v.length > maxElts ? '...' : ']'; | ||
return '' + string + terminator; | ||
} | ||
// Inspired by https://github.com/hughsk/console-image (MIT license) | ||
function formatImage(image, message, scale) { | ||
var width = image.width * scale; | ||
var height = image.height * scale; | ||
var imageUrl = image.src.replace(/\(/g, '%28').replace(/\)/g, '%29'); | ||
var style = ['font-size:1px;', 'padding:' + Math.floor(height / 2) + 'px ' + Math.floor(width / 2) + 'px;', 'line-height:' + height + 'px;', 'background:url(' + imageUrl + ');', 'background-size:' + width + 'px ' + height + 'px;', 'color:transparent;'].join(''); | ||
return [message + ' %c+', style]; | ||
} | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.formatTime=formatTime,exports.leftPad=leftPad,exports.rightPad=rightPad,exports.getSISuffix=getSISuffix,exports.formatSI=formatSI,exports.formatValue=formatValue,exports.formatImage=formatImage;function formatTime(ms){var formatted;return formatted=10>ms?ms.toFixed(2)+'ms':100>ms?ms.toFixed(1)+'ms':1e3>ms?ms.toFixed(0)+'ms':(ms/1e3).toFixed(2)+'s',formatted}function leftPad(string){var length=1<arguments.length&&arguments[1]!==void 0?arguments[1]:8,padLength=Math.max(length-string.length,0);return''+' '.repeat(padLength)+string}function rightPad(string){var length=1<arguments.length&&arguments[1]!==void 0?arguments[1]:8,padLength=Math.max(length-string.length,0);return''+string+' '.repeat(padLength)}function splitIntoBaseAndExponent(number){var base=number,exponent=0;if(0!==number){for(;10<=base||-10>=base;)base/=10,exponent++;for(;1>base&&-1<base;)base*=10,exponent--}return{base:base,exponent:exponent}}function getSISuffix(multipleOf3){var SI_SUFFIXES={0:'',1:'K',2:'M',3:'G',"-1":'m',"-2":'\xB5',"-3":'n'},key=multipleOf3+'';return key in SI_SUFFIXES?SI_SUFFIXES[key]:'e'+3*multipleOf3}function formatSI(number){var precision=1<arguments.length&&arguments[1]!==void 0?arguments[1]:3,_splitIntoBaseAndExpo=splitIntoBaseAndExponent(number),base=_splitIntoBaseAndExpo.base,exponent=_splitIntoBaseAndExpo.exponent,multipleOf3=Math.floor(exponent/3),digits=base*Math.pow(10,exponent-3*multipleOf3);return''+digits.toPrecision(precision)+getSISuffix(multipleOf3)}function formatValue(v){var _Mathabs=Math.abs,opts=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},_opts$isInteger=opts.isInteger,isInteger=void 0!==_opts$isInteger&&_opts$isInteger;if(Array.isArray(v)||ArrayBuffer.isView(v))return formatArrayValue(v,opts);if(!Number.isFinite(v))return v+'';if(_Mathabs(v)<1e-16)return isInteger?'0':'0.';if(isInteger)return v.toFixed(0);if(100<_Mathabs(v)&&1e4>_Mathabs(v))return v.toFixed(0);var string=v.toPrecision(2),decimal=string.indexOf('.0');return decimal===string.length-2?string.slice(0,-1):string}function formatArrayValue(v,opts){for(var _opts$maxElts=opts.maxElts,maxElts=_opts$maxElts===void 0?16:_opts$maxElts,_opts$size=opts.size,size=_opts$size===void 0?1:_opts$size,string='[',i=0;i<v.length&&i<maxElts;++i)0<i&&(string+=','+(0==i%size?' ':'')),string+=formatValue(v[i],opts);var terminator=v.length>maxElts?'...':']';return''+string+terminator}function formatImage(image,message,scale){var _Mathfloor=Math.floor,width=image.width*scale,height=image.height*scale,imageUrl=image.src.replace(/\(/g,'%28').replace(/\)/g,'%29'),style=['font-size:1px;','padding:'+_Mathfloor(height/2)+'px '+_Mathfloor(width/2)+'px;','line-height:'+height+'px;','background:url('+imageUrl+');','background-size:'+width+'px '+height+'px;','color:transparent;'].join('');return[message+' %c+',style]} | ||
//# sourceMappingURL=formatters.js.map |
@@ -1,33 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
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; }; | ||
/* global process, global, window, document, console */ | ||
// Check if in browser by duck-typing Node context | ||
var isBrowser = (typeof process === 'undefined' ? 'undefined' : _typeof(process)) !== 'object' || String(process) !== '[object process]' || process.browser; | ||
// Provide fallbacks for browser globals | ||
var window_ = typeof window !== 'undefined' ? window : global; | ||
var document_ = typeof document !== 'undefined' ? document : {}; | ||
// Provide fallbacks for Node globals | ||
var global_ = typeof global !== 'undefined' ? global : window; | ||
var process_ = (typeof process === 'undefined' ? 'undefined' : _typeof(process)) === 'object' ? process : {}; | ||
// Extract injected version from package.json (injected by babel plugin) | ||
/* global __VERSION__ */ | ||
var VERSION = typeof '1.0.0-alpha.9' !== 'undefined' ? '1.0.0-alpha.9' : 'untranspiled source'; | ||
exports.window = window_; | ||
exports.document = document_; | ||
exports.global = global_; | ||
exports.process = process_; | ||
exports.console = console; | ||
exports.isBrowser = isBrowser; | ||
exports.VERSION = VERSION; | ||
'use strict';var _typeof='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&'function'==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?'symbol':typeof obj},isBrowser='object'!==('undefined'==typeof process?'undefined':_typeof(process))||'[object process]'!==process+''||process.browser,window_='undefined'==typeof window?global:window,document_='undefined'==typeof document?{}:document,global_='undefined'==typeof global?window:global,process_='object'===('undefined'==typeof process?'undefined':_typeof(process))?process:{},VERSION='1.0.0-alpha.10';Object.defineProperty(exports,'__esModule',{value:!0});exports.window=window_,exports.document=document_,exports.global=global_,exports.process=process_,exports.console=console,exports.isBrowser=isBrowser,exports.VERSION=VERSION; | ||
//# sourceMappingURL=globals.js.map |
@@ -1,100 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
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; }; }(); | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
// Copyright (c) 2017 Uber Technologies, Inc. | ||
// | ||
// 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. | ||
/* global window */ | ||
function getStorage(type) { | ||
try { | ||
var storage = window[type]; | ||
var x = '__storage_test__'; | ||
storage.setItem(x, x); | ||
storage.removeItem(x); | ||
return storage; | ||
} catch (e) { | ||
return null; | ||
} | ||
} | ||
// Store keys in local storage via simple interface | ||
var LocalStorage = function () { | ||
function LocalStorage(id, defaultSettings) { | ||
var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'sessionStorage'; | ||
_classCallCheck(this, LocalStorage); | ||
this.storage = getStorage(type); | ||
this.id = id; | ||
this.config = {}; | ||
Object.assign(this.config, defaultSettings); | ||
this._loadConfiguration(); | ||
} | ||
_createClass(LocalStorage, [{ | ||
key: 'getConfiguration', | ||
value: function getConfiguration() { | ||
return this.config; | ||
} | ||
}, { | ||
key: 'setConfiguration', | ||
value: function setConfiguration(configuration) { | ||
this.config = {}; | ||
return this.updateConfiguration(configuration); | ||
} | ||
}, { | ||
key: 'updateConfiguration', | ||
value: function updateConfiguration(configuration) { | ||
Object.assign(this.config, configuration); | ||
if (this.storage) { | ||
var serialized = JSON.stringify(this.config); | ||
this.storage.setItem(this.id, serialized); | ||
} | ||
return this; | ||
} | ||
// Get config from persistent store, if available | ||
}, { | ||
key: '_loadConfiguration', | ||
value: function _loadConfiguration() { | ||
var configuration = {}; | ||
if (this.storage) { | ||
var serializedConfiguration = this.storage.getItem(this.id); | ||
configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {}; | ||
} | ||
Object.assign(this.config, configuration); | ||
return this; | ||
} | ||
}]); | ||
return LocalStorage; | ||
}(); | ||
exports.default = LocalStorage; | ||
'use strict';var _createClass=function(){function defineProperties(target,props){for(var descriptor,i=0;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();Object.defineProperty(exports,'__esModule',{value:!0});function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}function getStorage(type){try{var storage=window[type],x='__storage_test__';return storage.setItem(x,x),storage.removeItem(x),storage}catch(e){return null}}var LocalStorage=function(){function LocalStorage(id,defaultSettings){var type=2<arguments.length&&void 0!==arguments[2]?arguments[2]:'sessionStorage';_classCallCheck(this,LocalStorage),this.storage=getStorage(type),this.id=id,this.config={},Object.assign(this.config,defaultSettings),this._loadConfiguration()}return _createClass(LocalStorage,[{key:'getConfiguration',value:function getConfiguration(){return this.config}},{key:'setConfiguration',value:function setConfiguration(configuration){return this.config={},this.updateConfiguration(configuration)}},{key:'updateConfiguration',value:function updateConfiguration(configuration){if(Object.assign(this.config,configuration),this.storage){var serialized=JSON.stringify(this.config);this.storage.setItem(this.id,serialized)}return this}},{key:'_loadConfiguration',value:function _loadConfiguration(){var configuration={};if(this.storage){var serializedConfiguration=this.storage.getItem(this.id);configuration=serializedConfiguration?JSON.parse(serializedConfiguration):{}}return Object.assign(this.config,configuration),this}}]),LocalStorage}();exports.default=LocalStorage; | ||
//# sourceMappingURL=local-storage.js.map |
@@ -1,51 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.enableDOMLogging = enableDOMLogging; | ||
exports.logLineToDOM = logLineToDOM; | ||
var _globals = require('./globals'); | ||
var old = null; | ||
// Can log a (not too long) number of messages to a div in the DOM | ||
/* eslint-disable no-console */ | ||
function enableDOMLogging() { | ||
var enable = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; | ||
// First time, add a log div | ||
if (enable && !old) { | ||
old = _globals.console.log.bind(_globals.console); | ||
_globals.console.log = function () { | ||
logLineToDOM.apply(undefined, arguments); | ||
old.apply(undefined, arguments); | ||
}; | ||
} | ||
if (!enable && old) { | ||
_globals.console.log = old; | ||
old = null; | ||
} | ||
} | ||
var logDiv = null; | ||
function logLineToDOM(message) { | ||
if (!logDiv) { | ||
var markdown = _globals.global.probe.markdown; | ||
logDiv = _globals.document.createElement(markdown ? 'pre' : 'div'); | ||
} | ||
// Ensure the element comes first | ||
var childNodes = _globals.document.body.childNodes; | ||
_globals.document.body.insertBefore(logDiv, childNodes && childNodes[0]); | ||
// Add the line to the log element | ||
if (typeof message === 'string') { | ||
logDiv.innerHTML += message + '<br />'; | ||
} | ||
} | ||
exports.default = enableDOMLogging; | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.enableDOMLogging=enableDOMLogging,exports.logLineToDOM=logLineToDOM;var _globals=require('./globals'),old=null;function enableDOMLogging(){var enable=!(0<arguments.length&&arguments[0]!==void 0)||arguments[0];enable&&!old&&(old=_globals.console.log.bind(_globals.console),_globals.console.log=function(){logLineToDOM.apply(void 0,arguments),old.apply(void 0,arguments)}),!enable&&old&&(_globals.console.log=old,old=null)}var logDiv=null;function logLineToDOM(message){if(!logDiv){var markdown=_globals.global.probe.markdown;logDiv=_globals.document.createElement(markdown?'pre':'div')}var childNodes=_globals.document.body.childNodes;_globals.document.body.insertBefore(logDiv,childNodes&&childNodes[0]),'string'==typeof message&&(logDiv.innerHTML+=message+'<br />')}exports.default=enableDOMLogging; | ||
//# sourceMappingURL=log-to-dom.js.map |
@@ -1,45 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.startTimestamp = undefined; | ||
exports.getTimestamp = getTimestamp; | ||
var _globals = require('./globals'); | ||
// High resolution timer | ||
function getTimestamp() { | ||
if (!_globals.isBrowser) { | ||
var secondsAndNanoseconds = _globals.process.hrtime(); | ||
return secondsAndNanoseconds[0] + secondsAndNanoseconds[1] / 1e6; | ||
} | ||
if (_globals.window.performance) { | ||
return _globals.window.performance.now(); | ||
} | ||
return Date.now(); | ||
} // Copyright (c) 2017 Uber Technologies, Inc. | ||
// | ||
// 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. | ||
/** | ||
* Common environment setup | ||
*/ | ||
var startTimestamp = exports.startTimestamp = getTimestamp(); | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.startTimestamp=void 0,exports.getTimestamp=getTimestamp;var _globals=require('./globals');function getTimestamp(){if(!_globals.isBrowser){var secondsAndNanoseconds=_globals.process.hrtime();return secondsAndNanoseconds[0]+secondsAndNanoseconds[1]/1e6}return _globals.window.performance?_globals.window.performance.now():Date.now()}var startTimestamp=exports.startTimestamp=getTimestamp(); | ||
//# sourceMappingURL=timestamp.js.map |
@@ -1,149 +0,2 @@ | ||
'use strict'; | ||
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; }; }(); | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
// Built on https://github.com/Erkaman/regl-stats-widget (MIT license) | ||
// widget styling constants. | ||
var TEXT_SIZE = 10; | ||
var TEXT_START = [7, 37]; | ||
var TEXT_SPACING = 6; | ||
var HEADER_SIZE = 20; | ||
var BOTTOM_SPACING = 20; | ||
var HEADER_POS = [3, 3]; | ||
var BG = '#000'; | ||
var FG = '#ccc'; | ||
var WIDTH = 160; | ||
var HEIGHT = function HEIGHT(items) { | ||
return items.length * TEXT_SIZE + (items.length - 1) * TEXT_SPACING + TEXT_START[1] + BOTTOM_SPACING; | ||
}; | ||
var StatsWidget = function () { | ||
function StatsWidget(items) { | ||
_classCallCheck(this, StatsWidget); | ||
// the widget keeps track of the previous values of gpuTime, | ||
// in order to compute the frame time. | ||
var prevGpuTimes = []; | ||
for (var _i = 0; _i < items.length; _i++) { | ||
prevGpuTimes[_i] = 0; | ||
} | ||
// we update the widget every second, we need to keep track of the time: | ||
var totalTime = 1.1; | ||
// we show the average frametime to the user. | ||
var N = 50; | ||
var totalFrameTime = []; | ||
var frameTimeCount = 0; | ||
var avgFrameTime = []; | ||
for (i = 0; i < items.length; ++i) { | ||
totalFrameTime[i] = 0.0; | ||
avgFrameTime[i] = 0.0; | ||
} | ||
} | ||
_createClass(StatsWidget, [{ | ||
key: 'update', | ||
value: function update(deltaTime) { | ||
totalTime += deltaTime; | ||
if (totalTime > 1.0) { | ||
totalTime = 0; | ||
// make sure that we clear the old text before drawing new text. | ||
_clearTextArea(); | ||
// const frameTime; | ||
// for (let i = 0; i < drawCalls.length; i++) { | ||
// const drawCall = drawCalls[i]; | ||
// this._drawTextItem(context, i, drawCalls[i], avgFrameTime[i]); | ||
} | ||
frameTimeCount++; | ||
// make sure to update the previous gpuTime, and to compute the average. | ||
for (i = 0; i < drawCalls.length; i++) { | ||
drawCall = drawCalls[i]; | ||
frameTime = drawCall[0].stats.gpuTime - prevGpuTimes[i]; | ||
totalFrameTime[i] += frameTime; | ||
if (frameTimeCount === N) { | ||
avgFrameTime[i] = totalFrameTime[i] / N; | ||
totalFrameTime[i] = 0.0; | ||
} | ||
prevGpuTimes[i] = drawCall[0].stats.gpuTime; | ||
} | ||
// reset avg calculation. | ||
if (frameTimeCount === N) { | ||
frameTimeCount = 0; | ||
} | ||
} | ||
}, { | ||
key: '_createDOM', | ||
value: function _createDOM() { | ||
var pr = Math.round(window.devicePixelRatio || 1); | ||
// the widget is contained in a <div> | ||
var container = document.createElement('div'); | ||
container.style.cssText = 'position:fixed;top:20px;left:20px;opacity:0.8;z-index:10000;'; | ||
// we draw the widget on a canvas. | ||
var canvas = document.createElement('canvas'); | ||
var context = canvas.getContext('2d'); | ||
// set canvas size | ||
canvas.width = WIDTH * pr; | ||
canvas.height = HEIGHT * pr; | ||
canvas.style.cssText = 'width: ' + WIDTH + 'px;height: ' + HEIGHT + 'px'; | ||
// draw background. | ||
context.fillStyle = BG; | ||
context.fillRect(0, 0, WIDTH * pr, HEIGHT * pr); | ||
container.appendChild(canvas); | ||
document.body.appendChild(container); | ||
this.context = context; | ||
} | ||
}, { | ||
key: '_drawHeader', | ||
value: function _drawHeader(context) { | ||
var pr = Math.round(window.devicePixelRatio || 1); | ||
context.font = 'bold ' + HEADER_SIZE * pr + 'px Helvetica,Arial,sans-serif'; | ||
context.textBaseline = 'top'; | ||
context.fillStyle = FG; | ||
context.fillText('Stats', HEADER_POS[0] * pr, HEADER_POS[1] * pr); | ||
} | ||
}, { | ||
key: '_clearTextArea', | ||
value: function _clearTextArea(context) { | ||
var pr = Math.round(window.devicePixelRatio || 1); | ||
context.fillStyle = BG; | ||
context.fillRect(TEXT_START[0] * pr, TEXT_START[1] * pr, (WIDTH - TEXT_START[0]) * pr, (HEIGHT - TEXT_START[1]) * pr); | ||
context.font = 'bold ' + TEXT_SIZE * pr + 'px Helvetica,Arial,sans-serif'; | ||
context.fillStyle = FG; | ||
} | ||
}, { | ||
key: '_drawTextItem', | ||
value: function _drawTextItem(context, i, title, value) { | ||
var pr = Math.round(window.devicePixelRatio || 1); | ||
// context, i, drawCalls[i], avgFrameTime[i]); | ||
var textCursor = [TEXT_START[0], TEXT_START[1]]; | ||
var str = drawCall[1] + ' : ' + Math.round(100.0 * avgFrameTime[i]) / 100.0 + 'ms'; | ||
context.fillText(str, textCursor[0] * pr, textCursor[1] * pr); | ||
// next line | ||
textCursor[1] += TEXT_SIZE + TEXT_SPACING; | ||
} | ||
}]); | ||
return StatsWidget; | ||
}(); | ||
'use strict';var _createClass=function(){function defineProperties(target,props){for(var descriptor,i=0;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}var TEXT_SIZE=10,TEXT_START=[7,37],TEXT_SPACING=6,HEADER_SIZE=20,BOTTOM_SPACING=20,HEADER_POS=[3,3],BG='#000',FG='#ccc',WIDTH=160,HEIGHT=function(items){return items.length*TEXT_SIZE+(items.length-1)*TEXT_SPACING+TEXT_START[1]+BOTTOM_SPACING},StatsWidget=function(){function StatsWidget(items){_classCallCheck(this,StatsWidget);for(var prevGpuTimes=[],_i=0;_i<items.length;_i++)prevGpuTimes[_i]=0;var totalFrameTime=[],avgFrameTime=[];for(i=0;i<items.length;++i)totalFrameTime[i]=0,avgFrameTime[i]=0}var _Mathround=Math.round;return _createClass(StatsWidget,[{key:'update',value:function update(deltaTime){for(totalTime+=deltaTime,1<totalTime&&(totalTime=0,_clearTextArea()),frameTimeCount++,i=0;i<drawCalls.length;i++)drawCall=drawCalls[i],frameTime=drawCall[0].stats.gpuTime-prevGpuTimes[i],totalFrameTime[i]+=frameTime,frameTimeCount===N&&(avgFrameTime[i]=totalFrameTime[i]/N,totalFrameTime[i]=0),prevGpuTimes[i]=drawCall[0].stats.gpuTime;frameTimeCount===N&&(frameTimeCount=0)}},{key:'_createDOM',value:function _createDOM(){var pr=_Mathround(window.devicePixelRatio||1),container=document.createElement('div');container.style.cssText='position:fixed;top:20px;left:20px;opacity:0.8;z-index:10000;';var canvas=document.createElement('canvas'),context=canvas.getContext('2d');canvas.width=WIDTH*pr,canvas.height=HEIGHT*pr,canvas.style.cssText='width: '+WIDTH+'px;height: '+HEIGHT+'px',context.fillStyle=BG,context.fillRect(0,0,WIDTH*pr,HEIGHT*pr),container.appendChild(canvas),document.body.appendChild(container),this.context=context}},{key:'_drawHeader',value:function _drawHeader(context){var pr=_Mathround(window.devicePixelRatio||1);context.font='bold '+HEADER_SIZE*pr+'px Helvetica,Arial,sans-serif',context.textBaseline='top',context.fillStyle=FG,context.fillText('Stats',HEADER_POS[0]*pr,HEADER_POS[1]*pr)}},{key:'_clearTextArea',value:function _clearTextArea(context){var pr=_Mathround(window.devicePixelRatio||1);context.fillStyle=BG,context.fillRect(TEXT_START[0]*pr,TEXT_START[1]*pr,(WIDTH-TEXT_START[0])*pr,(HEIGHT-TEXT_START[1])*pr),context.font='bold '+TEXT_SIZE*pr+'px Helvetica,Arial,sans-serif',context.fillStyle=FG}},{key:'_drawTextItem',value:function _drawTextItem(context,i){var pr=_Mathround(window.devicePixelRatio||1),textCursor=[TEXT_START[0],TEXT_START[1]],str=drawCall[1]+' : '+_Mathround(100*avgFrameTime[i])/100+'ms';context.fillText(str,textCursor[0]*pr,textCursor[1]*pr),textCursor[1]+=TEXT_SIZE+TEXT_SPACING}}]),StatsWidget}(); | ||
//# sourceMappingURL=stats-widget.js.map |
@@ -1,182 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
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; }; }(); // Copyright (c) 2015 - 2017 Uber Technologies, Inc. | ||
// | ||
// 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. | ||
// TODO - use a Log | ||
var _color = require('../../lib/utils/color'); | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
var ERR_AUTOMATION = 'Browser automation error. Check stack trace.\n Also note that Chrome 64 or higher is required.'; | ||
var DEFAULT_CONFIG = { | ||
process: './node_modules/.bin/webpack-dev-server', | ||
parameters: ['--config', 'webpack.config.js'], | ||
options: { maxBuffer: 5000 * 1024 } | ||
}; | ||
var DEFAULT_PUPPETEER_OPTIONS = { | ||
headless: false, | ||
executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' | ||
}; | ||
var BrowserDriver = function () { | ||
function BrowserDriver() { | ||
_classCallCheck(this, BrowserDriver); | ||
this.execFile = module.require('child_process').execFile; | ||
this.puppeteer = module.require('puppeteer'); | ||
this.console = module.require('console'); | ||
this.process = module.require('process'); | ||
this.child = null; | ||
this.browser = null; | ||
this.page = null; | ||
this.shellStatus = 0; | ||
} | ||
_createClass(BrowserDriver, [{ | ||
key: 'setShellStatus', | ||
value: function setShellStatus(success) { | ||
// return value that is visible to the shell, 0 is success | ||
this.shellStatus = success ? 0 : 1; | ||
} | ||
}, { | ||
key: 'startBrowser', | ||
value: function startBrowser() { | ||
var _this = this; | ||
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_PUPPETEER_OPTIONS; | ||
if (this.browser) { | ||
return Promise.resolve(this.browser); | ||
} | ||
return this.puppeteer.launch(options).then(function (browser) { | ||
_this.browser = browser; | ||
}).catch(function (error) { | ||
console.error((0, _color.addColor)(ERR_AUTOMATION, _color.COLOR.BRIGHT_RED)); // eslint-disable-line | ||
throw error; | ||
}); | ||
} | ||
}, { | ||
key: 'newPage', | ||
value: function newPage() { | ||
var _this2 = this; | ||
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, | ||
_ref$url = _ref.url, | ||
url = _ref$url === undefined ? 'http://localhost:8080' : _ref$url, | ||
_ref$width = _ref.width, | ||
width = _ref$width === undefined ? 1550 : _ref$width, | ||
_ref$height = _ref.height, | ||
height = _ref$height === undefined ? 850 : _ref$height; | ||
return this.startBrowser().then(function (_) { | ||
return _this2.browser.newPage(); | ||
}).then(function (page) { | ||
_this2.page = page; | ||
}).then(function (_) { | ||
return _this2.page.waitFor(1000); | ||
}).then(function (_) { | ||
return _this2.page.goto(url); | ||
}).then(function (_) { | ||
return _this2.page.setViewport({ width: 1550, height: 850 }); | ||
}).catch(function (error) { | ||
console.error((0, _color.addColor)(ERR_AUTOMATION, _color.COLOR.BRIGHT_RED)); // eslint-disable-line | ||
throw error; | ||
}); | ||
} | ||
}, { | ||
key: 'exposeFunction', | ||
value: function exposeFunction() { | ||
var _this3 = this; | ||
var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'testDriverDone'; | ||
return new Promise(function (resolve) { | ||
_this3.page.exposeFunction(name, resolve); | ||
}); | ||
} | ||
}, { | ||
key: 'stopBrowser', | ||
value: function stopBrowser() { | ||
var _this4 = this; | ||
return Promise.resolve().then(function (_) { | ||
return _this4.page.waitFor(1000); | ||
}).then(function (_) { | ||
return _this4.browser.close(); | ||
}).catch(function (error) { | ||
console.error((0, _color.addColor)(ERR_AUTOMATION, _color.COLOR.BRIGHT_RED)); // eslint-disable-line | ||
throw error; | ||
}); | ||
} | ||
}, { | ||
key: 'startServer', | ||
value: function startServer() { | ||
var _this5 = this; | ||
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
this.child = this.execFile(config.process || DEFAULT_CONFIG.process, config.parameters || DEFAULT_CONFIG.parameters, config.options || DEFAULT_CONFIG.options, function (err, stdout) { | ||
if (err) { | ||
_this5.console.error(err); | ||
return; | ||
} | ||
_this5.console.log(stdout); | ||
}); | ||
} | ||
}, { | ||
key: 'stopServer', | ||
value: function stopServer() { | ||
if (this.child) { | ||
this.child.kill(); | ||
this.child = null; | ||
} | ||
} | ||
}, { | ||
key: 'exitProcess', | ||
value: function exitProcess() { | ||
// generate a return value that is visible to the shell, 0 is success | ||
this.process.exit(this.shellStatus); | ||
} | ||
}, { | ||
key: 'exit', | ||
value: function exit() { | ||
var _this6 = this; | ||
return Promise.all([this.stopBrowser(), this.stopServer()]).then(function (_) { | ||
return _this6.exitProcess(); | ||
}); | ||
} | ||
}]); | ||
return BrowserDriver; | ||
}(); | ||
exports.default = BrowserDriver; | ||
'use strict';var _createClass=function(){function defineProperties(target,props){for(var descriptor,i=0;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_color=require('../../lib/utils/color');Object.defineProperty(exports,'__esModule',{value:!0});function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}var ERR_AUTOMATION='Browser automation error. Check stack trace.\n Also note that Chrome 64 or higher is required.',DEFAULT_CONFIG={process:'./node_modules/.bin/webpack-dev-server',parameters:['--config','webpack.config.js'],options:{maxBuffer:5120000}},DEFAULT_PUPPETEER_OPTIONS={headless:!1,executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'},BrowserDriver=function(){function BrowserDriver(){_classCallCheck(this,BrowserDriver),this.execFile=module.require('child_process').execFile,this.puppeteer=module.require('puppeteer'),this.console=module.require('console'),this.process=module.require('process'),this.child=null,this.browser=null,this.page=null,this.shellStatus=0}return _createClass(BrowserDriver,[{key:'setShellStatus',value:function setShellStatus(success){this.shellStatus=success?0:1}},{key:'startBrowser',value:function startBrowser(){var _this=this,options=0<arguments.length&&void 0!==arguments[0]?arguments[0]:DEFAULT_PUPPETEER_OPTIONS;return this.browser?Promise.resolve(this.browser):this.puppeteer.launch(options).then(function(browser){_this.browser=browser}).catch(function(error){throw console.error((0,_color.addColor)(ERR_AUTOMATION,_color.COLOR.BRIGHT_RED)),error})}},{key:'newPage',value:function newPage(){var _this2=this,_ref=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},_ref$url=_ref.url,url=void 0===_ref$url?'http://localhost:8080':_ref$url,_ref$width=_ref.width,width=void 0===_ref$width?1550:_ref$width,_ref$height=_ref.height,height=void 0===_ref$height?850:_ref$height;return this.startBrowser().then(function(){return _this2.browser.newPage()}).then(function(page){_this2.page=page}).then(function(){return _this2.page.waitFor(1e3)}).then(function(){return _this2.page.goto(url)}).then(function(){return _this2.page.setViewport({width:1550,height:850})}).catch(function(error){throw console.error((0,_color.addColor)(ERR_AUTOMATION,_color.COLOR.BRIGHT_RED)),error})}},{key:'exposeFunction',value:function exposeFunction(){var _this3=this,name=0<arguments.length&&void 0!==arguments[0]?arguments[0]:'testDriverDone';return new Promise(function(resolve){_this3.page.exposeFunction(name,resolve)})}},{key:'stopBrowser',value:function stopBrowser(){var _this4=this;return Promise.resolve().then(function(){return _this4.page.waitFor(1e3)}).then(function(){return _this4.browser.close()}).catch(function(error){throw console.error((0,_color.addColor)(ERR_AUTOMATION,_color.COLOR.BRIGHT_RED)),error})}},{key:'startServer',value:function startServer(){var _this5=this,config=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};this.child=this.execFile(config.process||DEFAULT_CONFIG.process,config.parameters||DEFAULT_CONFIG.parameters,config.options||DEFAULT_CONFIG.options,function(err,stdout){return err?void _this5.console.error(err):void _this5.console.log(stdout)})}},{key:'stopServer',value:function stopServer(){this.child&&(this.child.kill(),this.child=null)}},{key:'exitProcess',value:function exitProcess(){this.process.exit(this.shellStatus)}},{key:'exit',value:function exit(){var _this6=this;return Promise.all([this.stopBrowser(),this.stopServer()]).then(function(){return _this6.exitProcess()})}}]),BrowserDriver}();exports.default=BrowserDriver; | ||
//# sourceMappingURL=browser-driver.js.map |
@@ -1,140 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
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 _browserDriver = require('./browser-driver'); | ||
var _browserDriver2 = _interopRequireDefault(_browserDriver); | ||
var _color = require('../../lib/utils/color'); | ||
var _log = require('../../lib/log'); | ||
var _log2 = _interopRequireDefault(_log); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
function _possibleConstructorReturn(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; } | ||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // Copyright (c) 2015 - 2017 Uber Technologies, Inc. | ||
// | ||
// 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. | ||
/* global process */ | ||
var log = new _log2.default('render-test'); | ||
// DEFAULT config, intended to be overridden in the node script that calls us | ||
// read the webpack env from 3 arg (node script arg) | ||
var webpackEnv = 'render'; | ||
if (process.argv.length >= 3) { | ||
webpackEnv = process.argv[2]; | ||
} | ||
var DEFAULT_CONFIG = { | ||
title: 'BrowserTestDriver: tests', | ||
exposeFunction: 'taskComplete', | ||
parameters: ['--env.' + webpackEnv] | ||
}; | ||
var BrowserTestDriver = function (_BrowserDriver) { | ||
_inherits(BrowserTestDriver, _BrowserDriver); | ||
function BrowserTestDriver() { | ||
_classCallCheck(this, BrowserTestDriver); | ||
return _possibleConstructorReturn(this, (BrowserTestDriver.__proto__ || Object.getPrototypeOf(BrowserTestDriver)).apply(this, arguments)); | ||
} | ||
_createClass(BrowserTestDriver, [{ | ||
key: 'run', | ||
value: function run() { | ||
var _this2 = this; | ||
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
config = Object.assign(DEFAULT_CONFIG, config); | ||
var _config = config, | ||
title = _config.title, | ||
exposeFunction = _config.exposeFunction; | ||
this.title = title; | ||
log.log({ | ||
message: title + ' starting. Starting Chrome instance, waiting for ' + exposeFunction + '...', | ||
color: _color.COLOR.YELLOW | ||
})(); | ||
this.time = Date.now(); | ||
return Promise.resolve().then(function (_) { | ||
return _this2.startServer(config); | ||
}).then(function (_) { | ||
return _this2.startBrowser(); | ||
}).then(function (_) { | ||
return _this2.newPage(); | ||
}).then(function (_) { | ||
return _this2.exposeFunction(exposeFunction); | ||
}).then(function (resultString) { | ||
var result = JSON.parse(resultString); | ||
var ok = result.success === Boolean(result.success) && (!result.failedTest || typeof result.failedTest === 'string'); | ||
if (!ok) { | ||
throw new Error('Illegal response "' + resultString + '" returned from Chrome test script'); | ||
} | ||
if (!result.success) { | ||
throw new Error(result.failedTest || 'Unknown failure'); | ||
} | ||
_this2._success(); | ||
}).catch(function (error) { | ||
_this2._failure(error); | ||
}); | ||
} | ||
}, { | ||
key: '_success', | ||
value: function _success() { | ||
var elapsed = ((Date.now() - this.time) / 1000).toFixed(1); | ||
log.log({ | ||
message: this.title + ' successfully completed in ' + elapsed + 's!', | ||
color: _color.COLOR.BRIGHT_GREEN | ||
})(); | ||
this.setShellStatus(true); | ||
this.exit(); | ||
} | ||
}, { | ||
key: '_failure', | ||
value: function _failure(error) { | ||
log.log({ | ||
message: this.title + ' failed: ' + error.message + '. Keeping browser open to allow debugging.', | ||
color: _color.COLOR.BRIGHT_RED | ||
})(); | ||
// Don't call exit(). Leave browser running so user can inspect image that failed to render | ||
this.setShellStatus(false); | ||
} | ||
}]); | ||
return BrowserTestDriver; | ||
}(_browserDriver2.default); | ||
exports.default = BrowserTestDriver; | ||
'use strict';var _createClass=function(){function defineProperties(target,props){for(var descriptor,i=0;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,'value'in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_browserDriver=require('./browser-driver'),_browserDriver2=_interopRequireDefault(_browserDriver),_color=require('../../lib/utils/color'),_log=require('../../lib/log'),_log2=_interopRequireDefault(_log);Object.defineProperty(exports,'__esModule',{value:!0});function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError('Cannot call a class as a function')}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return call&&('object'==typeof call||'function'==typeof call)?call:self}function _inherits(subClass,superClass){if('function'!=typeof superClass&&null!==superClass)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:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var log=new _log2.default('render-test'),webpackEnv='render';3<=process.argv.length&&(webpackEnv=process.argv[2]);var DEFAULT_CONFIG={title:'BrowserTestDriver: tests',exposeFunction:'taskComplete',parameters:['--env.'+webpackEnv]},BrowserTestDriver=function(_BrowserDriver){function BrowserTestDriver(){return _classCallCheck(this,BrowserTestDriver),_possibleConstructorReturn(this,(BrowserTestDriver.__proto__||Object.getPrototypeOf(BrowserTestDriver)).apply(this,arguments))}return _inherits(BrowserTestDriver,_BrowserDriver),_createClass(BrowserTestDriver,[{key:'run',value:function run(){var _this2=this,config=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};config=Object.assign(DEFAULT_CONFIG,config);var _config=config,title=_config.title,exposeFunction=_config.exposeFunction;return this.title=title,log.log({message:title+' starting. Starting Chrome instance, waiting for '+exposeFunction+'...',color:_color.COLOR.YELLOW})(),this.time=Date.now(),Promise.resolve().then(function(){return _this2.startServer(config)}).then(function(){return _this2.startBrowser()}).then(function(){return _this2.newPage()}).then(function(){return _this2.exposeFunction(exposeFunction)}).then(function(resultString){var result=JSON.parse(resultString),ok=result.success===!!result.success&&(!result.failedTest||'string'==typeof result.failedTest);if(!ok)throw new Error('Illegal response "'+resultString+'" returned from Chrome test script');if(!result.success)throw new Error(result.failedTest||'Unknown failure');_this2._success()}).catch(function(error){_this2._failure(error)})}},{key:'_success',value:function _success(){var elapsed=((Date.now()-this.time)/1e3).toFixed(1);log.log({message:this.title+' successfully completed in '+elapsed+'s!',color:_color.COLOR.BRIGHT_GREEN})(),this.setShellStatus(!0),this.exit()}},{key:'_failure',value:function _failure(error){log.log({message:this.title+' failed: '+error.message+'. Keeping browser open to allow debugging.',color:_color.COLOR.BRIGHT_RED})(),this.setShellStatus(!1)}}]),BrowserTestDriver}(_browserDriver2.default);exports.default=BrowserTestDriver; | ||
//# sourceMappingURL=browser-test-driver.js.map |
@@ -1,20 +0,2 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.callExposedFunction = callExposedFunction; | ||
/* global window */ | ||
function callExposedFunction(exposedFunction, result) { | ||
// Node test driver (puppeteer) may not have had time to expose the function | ||
// if the test suite is short. If not available, wait a second and try again | ||
if (window[exposedFunction]) { | ||
var resultString = JSON.stringify(result); | ||
console.error("Calling exposed function " + exposedFunction + "(" + resultString + ")"); // eslint-disable-line | ||
window[exposedFunction](resultString); | ||
} else { | ||
console.warn("window." + exposedFunction + "() not yet exposed, waiting 1 second"); // eslint-disable-line | ||
window.setTimeout(callExposedFunction.bind(null, exposedFunction, result), 1000); | ||
} | ||
} | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.callExposedFunction=callExposedFunction;function callExposedFunction(exposedFunction,result){if(window[exposedFunction]){var resultString=JSON.stringify(result);console.error("Calling exposed function "+exposedFunction+"("+resultString+")"),window[exposedFunction](resultString)}else console.warn("window."+exposedFunction+"() not yet exposed, waiting 1 second"),window.setTimeout(callExposedFunction.bind(null,exposedFunction,result),1e3)} | ||
//# sourceMappingURL=call-exposed-function.js.map |
@@ -1,75 +0,2 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.diffImagePixels = diffImagePixels; | ||
/* | ||
* Calculate perceived color difference using YIQ NTSC transmission color space | ||
* Based on 2010 paper by Yuriy Kotsarenko and Fernando Ramos | ||
* http://www.progmat.uaem.mx:8080/artVol2Num2/Articulo3Vol2Num2.pdf | ||
*/ | ||
var DEFAULT_THRESHOLD = 255 * 0.05; | ||
var getY = function getY(r, g, b) { | ||
return r * 0.29889531 + g * 0.58662247 + b * 0.11448223; | ||
}; | ||
var getI = function getI(r, g, b) { | ||
return r * 0.59597799 - g * 0.2741761 - b * 0.32180189; | ||
}; | ||
var getQ = function getQ(r, g, b) { | ||
return r * 0.21147017 - g * 0.52261711 + b * 0.31114694; | ||
}; | ||
var getESq = function getESq(dY, dI, dQ) { | ||
return 0.5053 * dY * dY + 0.299 * dI * dI + 0.1957 * dQ * dQ; | ||
}; | ||
// Get blended r/g/b value after applying alpha | ||
var applyAlpha = function applyAlpha(c, a) { | ||
return 255 + (c - 255) * a / 255; | ||
}; | ||
/** | ||
* Get dE square at given index from two pixel arrays | ||
* @param {Uint8ClampedArray} img1 - pixel data of first image | ||
* @param {Uint8ClampedArray} img2 - pixel data of second image | ||
* @param {Number} i - pixel index | ||
*/ | ||
function colorDelta(img1, img2, index) { | ||
return Math.sqrt(colorDeltaSq(img1, img2, index)); | ||
} | ||
function colorDeltaSq(img1, img2, index) { | ||
var i = index * 4; | ||
var a1 = img1[i + 3]; | ||
var a2 = img2[i + 3]; | ||
var r1 = applyAlpha(img1[i + 0], a1); | ||
var g1 = applyAlpha(img1[i + 1], a1); | ||
var b1 = applyAlpha(img1[i + 2], a1); | ||
var r2 = applyAlpha(img2[i + 0], a2); | ||
var g2 = applyAlpha(img2[i + 1], a2); | ||
var b2 = applyAlpha(img2[i + 2], a2); | ||
return getESq(getY(r1, g1, b1) - getY(r2, g2, b2), getI(r1, g1, b1) - getI(r2, g2, b2), getQ(r1, g1, b1) - getQ(r2, g2, b2)); | ||
} | ||
// TODO - expects imagedata structs | ||
// may need a helper func to accept different arguments types | ||
function diffImagePixels(data1, data2) { | ||
var colorDeltaThreshold = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_THRESHOLD; | ||
var pixelCount = data1.data.length / 4; | ||
var maxDeltaSq = colorDeltaThreshold * colorDeltaThreshold; | ||
var badPixels = 0; | ||
for (var i = 0; i < pixelCount; i++) { | ||
var delta = colorDeltaSq(data1.data, data2.data, i); | ||
if (delta > maxDeltaSq) { | ||
badPixels++; | ||
} | ||
} | ||
var percentage = 1 - badPixels / pixelCount; | ||
return percentage; | ||
} | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.diffImagePixels=diffImagePixels;var DEFAULT_THRESHOLD=.05*255,getY=function(r,g,b){return .29889531*r+.58662247*g+.11448223*b},getI=function(r,g,b){return .59597799*r-.2741761*g-.32180189*b},getQ=function(r,g,b){return .21147017*r-.52261711*g+.31114694*b},getESq=function(dY,dI,dQ){return .5053*dY*dY+.299*dI*dI+.1957*dQ*dQ},applyAlpha=function(c,a){return 255+(c-255)*a/255};function colorDelta(img1,img2,index){return Math.sqrt(colorDeltaSq(img1,img2,index))}function colorDeltaSq(img1,img2,index){var i=4*index,a1=img1[i+3],a2=img2[i+3],r1=applyAlpha(img1[i+0],a1),g1=applyAlpha(img1[i+1],a1),b1=applyAlpha(img1[i+2],a1),r2=applyAlpha(img2[i+0],a2),g2=applyAlpha(img2[i+1],a2),b2=applyAlpha(img2[i+2],a2);return getESq(getY(r1,g1,b1)-getY(r2,g2,b2),getI(r1,g1,b1)-getI(r2,g2,b2),getQ(r1,g1,b1)-getQ(r2,g2,b2))}function diffImagePixels(data1,data2){for(var delta,colorDeltaThreshold=2<arguments.length&&arguments[2]!==void 0?arguments[2]:DEFAULT_THRESHOLD,pixelCount=data1.data.length/4,badPixels=0,i=0;i<pixelCount;i++)delta=colorDeltaSq(data1.data,data2.data,i),delta>colorDeltaThreshold*colorDeltaThreshold&&badPixels++;var percentage=1-badPixels/pixelCount;return percentage} | ||
//# sourceMappingURL=diff-images.js.map |
@@ -1,47 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.createImage = createImage; | ||
exports.getImageFromContext = getImageFromContext; | ||
exports.getImagePixelData = getImagePixelData; | ||
// EXPERIMENTAL IMAGE TOOLS | ||
// TODO - only works in browser | ||
/* global document */ | ||
function createImage(width, height) { | ||
var image = document.createElement('img'); | ||
image.width = width; | ||
image.height = height; | ||
image.style.position = 'absolute'; | ||
image.style.top = 0; | ||
image.style.left = 0; | ||
return image; | ||
} | ||
function getImageFromContext(gl) { | ||
var image = createImage(gl.drawingBufferWidth, gl.drawingBufferHeight); | ||
return new Promise(function (resolve) { | ||
image.onload = function () { | ||
resolve(image); | ||
}; | ||
image.src = gl.canvas.toDataURL(); | ||
}); | ||
} | ||
function getImagePixelData(image) { | ||
var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; | ||
var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; | ||
width = width || image.width; | ||
height = height || image.height; | ||
var canvas = document.createElement('canvas'); | ||
canvas.width = width; | ||
canvas.height = height; | ||
var ctx = canvas.getContext('2d'); | ||
ctx.drawImage(image, 0, 0, width, height); | ||
return ctx.getImageData(0, 0, width, height); | ||
} | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.createImage=createImage,exports.getImageFromContext=getImageFromContext,exports.getImagePixelData=getImagePixelData;function createImage(width,height){var image=document.createElement('img');return image.width=width,image.height=height,image.style.position='absolute',image.style.top=0,image.style.left=0,image}function getImageFromContext(gl){var image=createImage(gl.drawingBufferWidth,gl.drawingBufferHeight);return new Promise(function(resolve){image.onload=function(){resolve(image)},image.src=gl.canvas.toDataURL()})}function getImagePixelData(image){var width=1<arguments.length&&void 0!==arguments[1]?arguments[1]:null,height=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;width=width||image.width,height=height||image.height;var canvas=document.createElement('canvas');canvas.width=width,canvas.height=height;var ctx=canvas.getContext('2d');return ctx.drawImage(image,0,0,width,height),ctx.getImageData(0,0,width,height)} | ||
//# sourceMappingURL=image-tools.js.map |
@@ -1,29 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.loadImage = loadImage; | ||
/* global Image */ | ||
function loadImage(url) { | ||
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, | ||
_ref$crossOrigin = _ref.crossOrigin, | ||
crossOrigin = _ref$crossOrigin === undefined ? 'anonymous' : _ref$crossOrigin; | ||
return new Promise(function (resolve, reject) { | ||
try { | ||
var image = new Image(); | ||
image.onload = function () { | ||
return resolve(image); | ||
}; | ||
image.onerror = function () { | ||
return reject(new Error('Could not load image ' + url + '.')); | ||
}; | ||
image.crossOrigin = crossOrigin; | ||
image.src = url; | ||
} catch (error) { | ||
reject(error); | ||
} | ||
}); | ||
} | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.loadImage=loadImage;function loadImage(url){var _ref=1<arguments.length&&arguments[1]!==void 0?arguments[1]:{},_ref$crossOrigin=_ref.crossOrigin,crossOrigin=_ref$crossOrigin===void 0?'anonymous':_ref$crossOrigin;return new Promise(function(resolve,reject){try{var image=new Image;image.onload=function(){return resolve(image)},image.onerror=function(){return reject(new Error('Could not load image '+url+'.'))},image.crossOrigin=crossOrigin,image.src=url}catch(error){reject(error)}})} | ||
//# sourceMappingURL=load-image.js.map |
@@ -1,64 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.experimental = exports.callExposedFunction = exports.BrowserTestDriver = exports.BrowserDriver = exports.makeSpy = undefined; | ||
var _makeSpy = require('./make-spy'); | ||
Object.defineProperty(exports, 'makeSpy', { | ||
enumerable: true, | ||
get: function get() { | ||
return _makeSpy.makeSpy; | ||
} | ||
}); | ||
var _browserDriver = require('./browser-automation/browser-driver'); | ||
Object.defineProperty(exports, 'BrowserDriver', { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_browserDriver).default; | ||
} | ||
}); | ||
var _browserTestDriver = require('./browser-automation/browser-test-driver'); | ||
Object.defineProperty(exports, 'BrowserTestDriver', { | ||
enumerable: true, | ||
get: function get() { | ||
return _interopRequireDefault(_browserTestDriver).default; | ||
} | ||
}); | ||
var _callExposedFunction = require('./browser-automation/call-exposed-function'); | ||
Object.defineProperty(exports, 'callExposedFunction', { | ||
enumerable: true, | ||
get: function get() { | ||
return _callExposedFunction.callExposedFunction; | ||
} | ||
}); | ||
var _loadImage = require('./image-utils/load-image'); | ||
var _imageTools = require('./image-utils/image-tools'); | ||
var _diffImages = require('./image-utils/diff-images'); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
// EXPERIMENTAL TEST UTILS | ||
// Image tools | ||
var experimental = exports.experimental = { | ||
loadImage: _loadImage.loadImage, | ||
createImage: _imageTools.createImage, | ||
getImageFromContext: _imageTools.getImageFromContext, | ||
getImagePixelData: _imageTools.getImagePixelData, | ||
diffImagePixels: _diffImages.diffImagePixels | ||
}; | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.experimental=exports.callExposedFunction=exports.BrowserTestDriver=exports.BrowserDriver=exports.makeSpy=void 0;var _makeSpy=require('./make-spy');Object.defineProperty(exports,'makeSpy',{enumerable:!0,get:function get(){return _makeSpy.makeSpy}});var _browserDriver=require('./browser-automation/browser-driver');Object.defineProperty(exports,'BrowserDriver',{enumerable:!0,get:function get(){return _interopRequireDefault(_browserDriver).default}});var _browserTestDriver=require('./browser-automation/browser-test-driver');Object.defineProperty(exports,'BrowserTestDriver',{enumerable:!0,get:function get(){return _interopRequireDefault(_browserTestDriver).default}});var _callExposedFunction=require('./browser-automation/call-exposed-function');Object.defineProperty(exports,'callExposedFunction',{enumerable:!0,get:function get(){return _callExposedFunction.callExposedFunction}});var _loadImage=require('./image-utils/load-image'),_imageTools=require('./image-utils/image-tools'),_diffImages=require('./image-utils/diff-images');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var experimental=exports.experimental={loadImage:_loadImage.loadImage,createImage:_imageTools.createImage,getImageFromContext:_imageTools.getImageFromContext,getImagePixelData:_imageTools.getImagePixelData,diffImagePixels:_diffImages.diffImagePixels}; | ||
//# sourceMappingURL=index.js.map |
@@ -1,74 +0,2 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
exports.makeSpy = makeSpy; | ||
// Inspired by https://github.com/popomore/spy | ||
// Attach a spy to the function. The spy has the following methods and fields | ||
// * restore() - remove spy completely | ||
// * reset() - reset call count | ||
// * callCount - number of calls | ||
// * called - whether spy was called | ||
function makeSpy(obj, func) { | ||
var methodName = void 0; | ||
if (!obj && !func) { | ||
func = function mock() {}; | ||
obj = {}; | ||
methodName = 'spy'; | ||
} else if (typeof obj === 'function' && !func) { | ||
func = obj; | ||
obj = {}; | ||
methodName = func.name + '-spy'; | ||
} else { | ||
methodName = func; | ||
func = obj[methodName]; | ||
} | ||
return wrapFunction(obj, func, methodName); | ||
} | ||
function wrapFunction(obj, func, methodName) { | ||
// will not wrap more than once | ||
if (func.func !== undefined) { | ||
return func; | ||
} | ||
// create a local function | ||
function spy() { | ||
spy.callCount++; | ||
spy.called = true; | ||
/* eslint-disable no-invalid-this */ | ||
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
return func.apply(this, args); | ||
} | ||
// Add functions and members | ||
Object.assign(spy, { | ||
reset: function reset() { | ||
spy.callCount = 0; | ||
spy.called = false; | ||
}, | ||
restore: function restore() { | ||
obj[methodName] = func; | ||
}, | ||
obj: obj, | ||
methodName: methodName, | ||
func: func, | ||
method: func | ||
}); | ||
spy.reset(); | ||
// Overwrite the spy on the object | ||
obj[methodName] = spy; | ||
return spy; | ||
} | ||
'use strict';Object.defineProperty(exports,'__esModule',{value:!0}),exports.makeSpy=makeSpy;function makeSpy(obj,func){var methodName;return obj||func?'function'!=typeof obj||func?(methodName=func,func=obj[methodName]):(func=obj,obj={},methodName=func.name+'-spy'):(func=function(){},obj={},methodName='spy'),wrapFunction(obj,func,methodName)}function wrapFunction(obj,func,methodName){function spy(){spy.callCount++,spy.called=!0;for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return func.apply(this,args)}return void 0===func.func?(Object.assign(spy,{reset:function reset(){spy.callCount=0,spy.called=!1},restore:function restore(){obj[methodName]=func},obj:obj,methodName:methodName,func:func,method:func}),spy.reset(),obj[methodName]=spy,spy):func} | ||
//# sourceMappingURL=make-spy.js.map |
@@ -5,3 +5,3 @@ { | ||
"license": "MIT", | ||
"version": "1.0.0-alpha.9", | ||
"version": "1.0.0-alpha.10", | ||
"keywords": [ | ||
@@ -40,2 +40,3 @@ "javascript", | ||
"test-cover": "NODE_ENV=test tape -r babel-register test/node.js && nyc report", | ||
"test-size": "npm run build && webpack --config test/webpack.config.js --env.import-nothing", | ||
"bench": "node test/start.js bench", | ||
@@ -57,5 +58,5 @@ "test-browser": "webpack-dev-server --env.test --progress --hot --open", | ||
"babel-polyfill": "^6.20.0", | ||
"babel-preset-babili": "^0.1.4", | ||
"babel-preset-env": "^1.6.1", | ||
"babel-preset-es2015": "^6.4.3", | ||
"babel-preset-minify": "^0.3.0", | ||
"coveralls": "^2.13.0", | ||
@@ -74,4 +75,5 @@ "eslint": "^3.0.0", | ||
"tape-catch": "^1.0.4", | ||
"uglify-js": "^2.6.1", | ||
"uglifyjs-webpack-plugin": "^1.2.4", | ||
"webpack": "^2.4.0", | ||
"webpack-bundle-analyzer": "^2.11.1", | ||
"webpack-dev-server": "^2.4.0" | ||
@@ -78,0 +80,0 @@ }, |
@@ -30,3 +30,3 @@ // Copyright (c) 2017 Uber Technologies, Inc. | ||
import {isBrowser} from './utils/globals'; | ||
import assert from 'assert'; | ||
import assert from '../lib/utils/assert'; | ||
@@ -33,0 +33,0 @@ /* eslint-disable no-console */ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 2 instances in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
76
0
212289
28
1830
13