From a40d9896607968702e082d3e0de4842f3d2718df Mon Sep 17 00:00:00 2001 From: Robert Plummer Date: Fri, 10 Aug 2018 07:48:42 -0400 Subject: [PATCH] chore: Increment and ready for release --- browser.js | 488 +++++++++++++++++++++++++++++-------- browser.min.js | 40 +-- dist/neural-network.js | 6 +- dist/neural-network.js.map | 2 +- dist/recurrent/rnn.js | 2 +- dist/recurrent/rnn.js.map | 2 +- package.json | 2 +- 7 files changed, 410 insertions(+), 132 deletions(-) diff --git a/browser.js b/browser.js index 4b988597a..373542705 100644 --- a/browser.js +++ b/browser.js @@ -6,7 +6,7 @@ * license: MIT (http://opensource.org/licenses/MIT) * author: Heather Arthur * homepage: https://github.com/brainjs/brain.js#readme - * version: 1.2.4 + * version: 1.2.5 * * acorn: * license: MIT (http://opensource.org/licenses/MIT) @@ -41,7 +41,7 @@ * license: MIT (http://opensource.org/licenses/MIT) * author: The gpu.js Team * homepage: http://gpu.rocks/ - * version: 1.5.2 + * version: 1.6.0 * * ieee754: * license: BSD-3-Clause (http://opensource.org/licenses/BSD-3-Clause) @@ -1983,11 +1983,11 @@ var NeuralNetwork = function () { case 'sigmoid': return '1/(1+1/Math.exp(' + result.join('') + '))'; case 'relu': - return 'var sum = ' + result.join('') + ';(sum < 0 ? 0 : sum);'; + return '(' + result.join('') + ' < 0 ? 0 : ' + result.join('') + ')'; case 'leaky-relu': - return 'var sum = ' + result.join('') + ';(sum < 0 ? 0 : 0.01 * sum);'; + return '(' + result.join('') + ' < 0 ? 0 : 0.01 * ' + result.join('') + ')'; case 'tanh': - return 'Math.tanh(' + result.join('') + ');'; + return 'Math.tanh(' + result.join('') + ')'; default: throw new Error('unknown activation type ' + activation); } @@ -4295,7 +4295,7 @@ var RNN = function () { if (isNaN(error)) throw new Error('network error rate is unexpected NaN, check network configurations and try again'); if (log && i % logPeriod == 0) { - log('iterations:', i, 'training error:', error); + log('iterations: ' + i + ', training error: ' + error); } if (callback && i % callbackPeriod == 0) { callback({ error: error, iterations: i }); @@ -9081,8 +9081,8 @@ module.exports = function (_KernelBase) { return ' ' + name + 'Z = new Array(' + threadDim[2] + ');\n'; }).join('')) + '\n for (this.thread.z = 0; this.thread.z < ' + threadDim[2] + '; this.thread.z++) {\n ret[this.thread.z] = new Array(' + threadDim[1] + ');\n ' + (this.subKernelOutputVariableNames === null ? '' : this.subKernelOutputVariableNames.map(function (name) { return ' ' + name + 'Z[this.thread.z] = new Array(' + threadDim[1] + ');\n'; - }).join('')) + '\n for (this.thread.y = 0; this.thread.y < ' + threadDim[1] + '; this.thread.y++) {\n ret[this.thread.z][this.thread.y] = new Array(' + threadDim[0] + ');\n ' + (this.subKernelOutputVariableNames === null ? '' : this.subKernelOutputVariableNames.map(function (name) { - return ' ' + name + 'Z[this.thread.z][this.thread.y] = new Array(' + threadDim[0] + ');\n'; + }).join('')) + '\n for (this.thread.y = 0; this.thread.y < ' + threadDim[1] + '; this.thread.y++) {\n ret[this.thread.z][this.thread.y] = ' + (this.floatOutput ? 'new Float32Array(' + threadDim[0] + ')' : 'new Array(' + threadDim[0] + ')') + ';\n ' + (this.subKernelOutputVariableNames === null ? '' : this.subKernelOutputVariableNames.map(function (name) { + return ' ' + name + 'Z[this.thread.z][this.thread.y] = ' + (_this2.floatOutput ? 'new Float32Array(' + threadDim[0] + ')' : 'new Array(' + threadDim[0] + ')') + ';\n'; }).join('')) + '\n for (this.thread.x = 0; this.thread.x < ' + threadDim[0] + '; this.thread.x++) {\n var kernelResult;\n ' + kernel + '\n ret[this.thread.z][this.thread.y][this.thread.x] = kernelResult;\n' + (this.subKernelOutputVariableNames === null ? '' : this.subKernelOutputVariableNames.map(function (name) { return ' ' + name + 'Z[this.thread.z][this.thread.y][this.thread.x] = ' + name + ';\n'; }).join('')) + '\n }\n }\n }\n \n if (this.graphical) {\n this._imageData.data.set(this._colorData);\n this._canvasCtx.putImageData(this._imageData, 0, 0);\n return;\n }\n \n if (this.output.length === 1) {\n ret = ret[0][0];\n ' + (this.subKernelOutputVariableNames === null ? '' : this.subKernelOutputVariableNames.map(function (name) { @@ -9640,6 +9640,7 @@ module.exports = function () { this.output = null; this.declarations = {}; this.states = []; + this.fixIntegerDivisionAccuracy = null; var paramTypes = void 0; var returnType = void 0; @@ -9665,6 +9666,9 @@ module.exports = function () { if (options.hasOwnProperty('returnType')) { returnType = options.returnType; } + if (options.hasOwnProperty('fixIntegerDivisionAccuracy')) { + this.fixIntegerDivisionAccuracy = options.fixIntegerDivisionAccuracy; + } } // @@ -10307,6 +10311,7 @@ module.exports = function () { * @prop {Array} subKernels - Sub kernels bound to this kernel instance * @prop {Object} subKernelProperties - Sub kernels bound to this kernel instance as key/value pairs * @prop {Array} subKernelOutputVariableNames - Names of the variables outputted by the subkerls + * @prop {Boolean} fixIntegerDivisionAccuracy - fix issues with some graphics cards not returning whole numbers when dividing by factors of 3 * */ function KernelBase(fnString, settings) { @@ -10340,6 +10345,7 @@ module.exports = function () { this.functionBuilder = null; this.paramTypes = null; this.paramSizes = null; + this.fixIntegerDivisionAccuracy = null; for (var p in settings) { if (!settings.hasOwnProperty(p) || !this.hasOwnProperty(p)) continue; @@ -10484,6 +10490,24 @@ module.exports = function () { /** * @memberOf KernelBase# * @function + * @name setFixIntegerDivisionAccuracy + * + * @desc Fix division by factor of 3 FP accuracy bug + * + * @param {Boolean} fix - should fix + * + */ + + }, { + key: 'setFixIntegerDivisionAccuracy', + value: function setFixIntegerDivisionAccuracy(fix) { + this.fixIntegerDivisionAccuracy = fix; + return this; + } + + /** + * @memberOf KernelBase# + * @function * @name setConstants * @desc Set Constants */ @@ -10718,6 +10742,22 @@ module.exports = function () { value: function addNativeFunction(name, source) { this.functionBuilder.addNativeFunction(name, source); } + + /** + * + * Destroys all memory associated with this kernel + * + * @name destroy + * @function + * @memberOf KernelBase# + * + * * @param {Boolean} removeCanvasReferences remve any associated canvas references? + * + */ + + }, { + key: 'destroy', + value: function destroy() {} }]); return KernelBase; @@ -11252,6 +11292,12 @@ module.exports = function (_FunctionNodeBase) { this.astGeneric(ast.left, retArr); retArr.push('!='); this.astGeneric(ast.right, retArr); + } else if (this.fixIntegerDivisionAccuracy && ast.operator === '/') { + retArr.push('div_with_int_check('); + this.astGeneric(ast.left, retArr); + retArr.push(', '); + this.astGeneric(ast.right, retArr); + retArr.push(')'); } else { this.astGeneric(ast.left, retArr); retArr.push(ast.operator); @@ -11959,6 +12005,9 @@ module.exports = function (_FunctionNodeBase) { this.astGeneric(mNode.object, retArr); retArr.push('Dim[2]'); retArr.push('), '); + this.astGeneric(mNode.object, retArr); + retArr.push('BitRatio'); + retArr.push(', '); this.popState('not-in-get-call-parameters'); this.pushState('in-get-call-parameters'); this.astGeneric(mNode.property, retArr); @@ -12300,6 +12349,8 @@ module.exports = function (gpuKernel, name) { },{"../../core/utils":84,"../kernel-run-shortcut":61}],66:[function(require,module,exports){ 'use strict'; +var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; + 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"); } } @@ -12375,6 +12426,8 @@ module.exports = function (_KernelBase) { _this.argumentsLength = 0; _this.compiledFragShaderString = null; _this.compiledVertShaderString = null; + _this.fragShader = null; + _this.vertShader = null; _this.drawBuffersMap = null; _this.outputTexture = null; _this.maxTexSize = null; @@ -12419,6 +12472,13 @@ module.exports = function (_KernelBase) { this.floatOutput = isFloatReadPixel; } + var hasIntegerDivisionBug = utils.hasIntegerDivisionAccuracyBug(); + if (this.fixIntegerDivisionAccuracy == null) { + this.fixIntegerDivisionAccuracy = hasIntegerDivisionBug; + } else if (this.fixIntegerDivisionAccuracy && !hasIntegerDivisionBug) { + this.fixIntegerDivisionAccuracy = false; + } + utils.checkOutput(this.output); if (!this.output || this.output.length === 0) { @@ -12512,11 +12572,14 @@ module.exports = function (_KernelBase) { var vertShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertShader, compiledVertShaderString); gl.compileShader(vertShader); + if (this.vertShader) {} + this.vertShader = vertShader; var compiledFragShaderString = this._getFragShaderString(arguments); var fragShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragShader, compiledFragShaderString); gl.compileShader(fragShader); + this.fragShader = fragShader; if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) { console.log(compiledVertShaderString); @@ -12988,6 +13051,7 @@ module.exports = function (_KernelBase) { CONSTANTS: this._getConstantsString(), DECODE32_ENDIANNESS: this._getDecode32EndiannessString(), ENCODE32_ENDIANNESS: this._getEncode32EndiannessString(), + DIVIDE_WITH_INTEGER_CHECK: this._getDivideWithIntegerCheckString(), GET_WRAPAROUND: this._getGetWraparoundString(), GET_TEXTURE_CHANNEL: this._getGetTextureChannelString(), GET_TEXTURE_INDEX: this._getGetTextureIndexString(), @@ -13037,38 +13101,24 @@ module.exports = function (_KernelBase) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); var length = size[0] * size[1]; - if (this.floatTextures) { - length *= 4; - } - var valuesFlat = void 0; - - if (utils.isArray(value[0])) { - // not already flat - valuesFlat = new Float32Array(length); - utils.flattenTo(value, valuesFlat); - } else if (value.constructor != Float32Array) { - // TODO: would be great if we could not have to create Float32Array buffers - // if input is 8/16 bit values... - // valuesFlat = new Float32Array(value); - valuesFlat = new Float32Array(length); - valuesFlat.set(value); - } else { - valuesFlat = value; - } + var _formatArrayTransfer2 = this._formatArrayTransfer(value, length), + valuesFlat = _formatArrayTransfer2.valuesFlat, + bitRatio = _formatArrayTransfer2.bitRatio; var buffer = void 0; if (this.floatTextures) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size[0], size[1], 0, gl.RGBA, gl.FLOAT, valuesFlat); } else { buffer = new Uint8Array(valuesFlat.buffer); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size[0], size[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, buffer); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size[0] / bitRatio, size[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, buffer); } if (!this.hardcodeConstants) { this.setUniform3iv('user_' + name + 'Dim', dim); this.setUniform2iv('user_' + name + 'Size', size); } + this.setUniform1i('user_' + name + 'BitRatio', bitRatio); this.setUniform1i('user_' + name, this.argumentsLength); break; } @@ -13094,26 +13144,23 @@ module.exports = function (_KernelBase) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); var _length = _size[0] * _size[1]; - var inputArray = void 0; - if (this.floatTextures) { - _length *= 4; - inputArray = new Float32Array(_length); - inputArray.set(input.value); - } else { - inputArray = input.value; - } + + var _formatArrayTransfer3 = this._formatArrayTransfer(value.value, _length), + _valuesFlat = _formatArrayTransfer3.valuesFlat, + _bitRatio = _formatArrayTransfer3.bitRatio; if (this.floatTextures) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, _size[0], _size[1], 0, gl.RGBA, gl.FLOAT, inputArray); } else { - var _buffer = new Uint8Array(inputArray.buffer); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, _size[0], _size[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, _buffer); + var _buffer = new Uint8Array(_valuesFlat.buffer); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, _size[0] / _bitRatio, _size[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, _buffer); } if (!this.hardcodeConstants) { this.setUniform3iv('user_' + name + 'Dim', _dim); this.setUniform2iv('user_' + name + 'Size', _size); } + this.setUniform1i('user_' + name + 'BitRatio', _bitRatio); this.setUniform1i('user_' + name, this.argumentsLength); break; } @@ -13152,6 +13199,7 @@ module.exports = function (_KernelBase) { this.setUniform3iv('user_' + name + 'Dim', _dim3); this.setUniform2iv('user_' + name + 'Size', _size3); + this.setUniform1i('user_' + name + 'BitRatio', 1); // aways float32 this.setUniform1i('user_' + name, this.argumentsLength); break; } @@ -13164,6 +13212,55 @@ module.exports = function (_KernelBase) { /** * @memberOf WebGLKernel# * @function + * @name _formatArrayTransfer + * + * @desc Adds kernel parameters to the Argument Texture, + * binding it to the webGl instance, etc. + * + * @param {Array} value - The actual argument supplied to the kernel + * @param {String} length - the expected total length of the output array + * + * @returns {Object} bitRatio - bit storage ratio of source to target 'buffer', i.e. if 8bit array -> 32bit tex = 4 + * valuesFlat - flattened array to transfer + */ + + }, { + key: '_formatArrayTransfer', + value: function _formatArrayTransfer(value, length) { + var bitRatio = 1; // bit storage ratio of source to target 'buffer', i.e. if 8bit array -> 32bit tex = 4 + var valuesFlat = value; + if (utils.isArray(value[0]) || this.floatTextures) { + // not already flat + valuesFlat = new Float32Array(length); + utils.flattenTo(value, valuesFlat); + } else { + + switch (value.constructor) { + case Uint8Array: + case Int8Array: + bitRatio = 4; + break; + case Uint16Array: + case Int16Array: + bitRatio = 2; + case Float32Array: + case Int32Array: + break; + + default: + valuesFlat = new Float32Array(length); + utils.flattenTo(value, valuesFlat); + } + } + return { + bitRatio: bitRatio, + valuesFlat: valuesFlat + }; + } + + /** + * @memberOf WebGLKernel# + * @function * @name _getHeaderString * * @desc Get the header string for the program. @@ -13218,9 +13315,9 @@ module.exports = function (_KernelBase) { var threadDim = this.threadDim; var texSize = this.texSize; if (this.hardcodeConstants) { - result.push('highp ivec3 uOutputDim = ivec3(' + threadDim[0] + ',' + threadDim[1] + ', ' + threadDim[2] + ')', 'highp ivec2 uTexSize = ivec2(' + texSize[0] + ', ' + texSize[1] + ')'); + result.push('ivec3 uOutputDim = ivec3(' + threadDim[0] + ',' + threadDim[1] + ', ' + threadDim[2] + ')', 'ivec2 uTexSize = ivec2(' + texSize[0] + ', ' + texSize[1] + ')'); } else { - result.push('uniform highp ivec3 uOutputDim', 'uniform highp ivec2 uTexSize'); + result.push('uniform ivec3 uOutputDim', 'uniform ivec2 uTexSize'); } return this._linesToString(result); @@ -13242,9 +13339,9 @@ module.exports = function (_KernelBase) { value: function _getTextureCoordinate() { var names = this.subKernelOutputVariableNames; if (names === null || names.length < 1) { - return 'varying highp vec2 vTexCoord;\n'; + return 'varying vec2 vTexCoord;\n'; } else { - return 'out highp vec2 vTexCoord;\n'; + return 'out vec2 vTexCoord;\n'; } } @@ -13282,6 +13379,23 @@ module.exports = function (_KernelBase) { return this.endianness === 'LE' ? '' : ' rgba.rgba = rgba.abgr;\n'; } + /** + * @memberOf WebGLKernel# + * @function + * @name _getDivideWithIntegerCheckString + * + * @desc if fixIntegerDivisionAccuracy provide method to replace / + * + * @returns {String} result + * + */ + + }, { + key: '_getDivideWithIntegerCheckString', + value: function _getDivideWithIntegerCheckString() { + return this.fixIntegerDivisionAccuracy ? '\n\t\t\t float div_with_int_check(float x, float y) {\n\t\t\t if (floor(x) == x && floor(y) == y && integerMod(x, y) == 0.0) {\n\t\t\t return float(int(x)/int(y));\n\t\t\t }\n\t\t\t return x / y;\n\t\t\t}\n\t\t\t' : ''; + } + /** * @function * @memberOf WebGLKernel# @@ -13308,7 +13422,7 @@ module.exports = function (_KernelBase) { value: function _getGetTextureChannelString() { if (!this.floatTextures) return ''; - return this._linesToString([' int channel = int(integerMod(index, 4))', ' index = index / 4']); + return this._linesToString([' int channel = integerMod(index, 4)', ' index = index / 4']); } /** @@ -13339,7 +13453,9 @@ module.exports = function (_KernelBase) { }, { key: '_getGetResultString', value: function _getGetResultString() { - if (!this.floatTextures) return ' return decode32(texel);\n'; + if (!this.floatTextures) { + return ' return decode(texel, x, bitRatio);'; + } return this._linesToString([' if (channel == 0) return texel.r', ' if (channel == 1) return texel.g', ' if (channel == 2) return texel.b', ' if (channel == 3) return texel.a']); } @@ -13374,17 +13490,20 @@ module.exports = function (_KernelBase) { floatOutput: this.floatOutput }, paramDim); - result.push('uniform highp sampler2D user_' + paramName, 'highp ivec2 user_' + paramName + 'Size = vec2(' + paramSize[0] + ', ' + paramSize[1] + ')', 'highp ivec3 user_' + paramName + 'Dim = vec3(' + paramDim[0] + ', ' + paramDim[1] + ', ' + paramDim[2] + ')'); + result.push('uniform sampler2D user_' + paramName, 'ivec2 user_' + paramName + 'Size = vec2(' + paramSize[0] + ', ' + paramSize[1] + ')', 'ivec3 user_' + paramName + 'Dim = vec3(' + paramDim[0] + ', ' + paramDim[1] + ', ' + paramDim[2] + ')', 'uniform int user_' + paramName + 'BitRatio'); } else if (paramType === 'Integer') { - result.push('highp float user_' + paramName + ' = ' + param + '.0'); + result.push('float user_' + paramName + ' = ' + param + '.0'); } else if (paramType === 'Float') { - result.push('highp float user_' + paramName + ' = ' + param); + result.push('float user_' + paramName + ' = ' + param); } } else { if (paramType === 'Array' || paramType === 'Texture' || paramType === 'Input' || paramType === 'HTMLImage') { - result.push('uniform highp sampler2D user_' + paramName, 'uniform highp ivec2 user_' + paramName + 'Size', 'uniform highp ivec3 user_' + paramName + 'Dim'); + result.push('uniform sampler2D user_' + paramName, 'uniform ivec2 user_' + paramName + 'Size', 'uniform ivec3 user_' + paramName + 'Dim'); + if (paramType !== 'HTMLImage') { + result.push('uniform int user_' + paramName + 'BitRatio'); + } } else if (paramType === 'Integer' || paramType === 'Float') { - result.push('uniform highp float user_' + paramName); + result.push('uniform float user_' + paramName); } else { throw new Error('Param type ' + paramType + ' not supported in WebGL, only WebGL2'); } @@ -13441,12 +13560,12 @@ module.exports = function (_KernelBase) { var result = []; var names = this.subKernelOutputVariableNames; if (names !== null) { - result.push('highp float kernelResult = 0.0'); + result.push('float kernelResult = 0.0'); for (var i = 0; i < names.length; i++) { - result.push('highp float ' + names[i] + ' = 0.0'); + result.push('float ' + names[i] + ' = 0.0'); } } else { - result.push('highp float kernelResult = 0.0'); + result.push('float kernelResult = 0.0'); } return this._linesToString(result) + this.functionBuilder.getPrototypeString('kernel'); @@ -13583,7 +13702,8 @@ module.exports = function (_KernelBase) { debug: this.debug, loopMaxIterations: this.loopMaxIterations, paramNames: this.paramNames, - paramTypes: this.paramTypes + paramTypes: this.paramTypes, + fixIntegerDivisionAccuracy: this.fixIntegerDivisionAccuracy }); if (this.subKernels !== null) { @@ -13610,7 +13730,8 @@ module.exports = function (_KernelBase) { constants: this.constants, output: this.output, debug: this.debug, - loopMaxIterations: this.loopMaxIterations + loopMaxIterations: this.loopMaxIterations, + fixIntegerDivisionAccuracy: this.fixIntegerDivisionAccuracy }); this.subKernelOutputVariableNames.push(subKernel.name + 'Result'); } @@ -13680,6 +13801,53 @@ module.exports = function (_KernelBase) { value: function addFunction(fn) { this.functionBuilder.addFunction(null, fn); } + }, { + key: 'destroy', + value: function destroy(removeCanvasReferences) { + _get(WebGLKernel.prototype.__proto__ || Object.getPrototypeOf(WebGLKernel.prototype), 'destroy', this).call(this); + if (this.outputTexture) { + this._webGl.deleteTexture(this.outputTexture); + } + if (this.buffer) { + this._webGl.deleteBuffer(this.buffer); + } + if (this.framebuffer) { + this._webGl.deleteFramebuffer(this.framebuffer); + } + + if (this.vertShader) { + this._webGl.deleteShader(this.vertShader); + } + + if (this.fragShader) { + this._webGl.deleteShader(this.fragShader); + } + + if (this.program) { + this._webGl.deleteProgram(this.program); + } + + var keys = Object.keys(this.textureCache); + + for (var i = 0; i < keys.length; i++) { + var name = keys[i]; + this._webGl.deleteTexture(this.textureCache[name]); + } + + if (this.subKernelOutputTextures) { + for (var _i3 = 0; _i3 < this.subKernelOutputTextures.length; _i3++) { + this._webGl.deleteTexture(this.subKernelOutputTextures[_i3]); + } + } + if (removeCanvasReferences) { + var idx = canvases.indexOf(this._canvas); + if (idx >= 0) { + canvases[idx] = null; + maxTexSizes[idx] = null; + } + } + delete this._webGl; + } }]); return WebGLKernel; @@ -13745,11 +13913,11 @@ module.exports = function (_RunnerBase) { },{"../runner-base":62,"./function-builder":63,"./kernel":66}],68:[function(require,module,exports){ "use strict"; -module.exports = "__HEADER__;\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n\nconst float LOOP_MAX = __LOOP_MAX__;\n#define EPSILON 0.0000001;\n\n__CONSTANTS__;\n\nvarying highp vec2 vTexCoord;\n\nvec4 round(vec4 x) {\n return floor(x + 0.5);\n}\n\nhighp float round(highp float x) {\n return floor(x + 0.5);\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nhighp float integerMod(highp float x, highp float y) {\n highp float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nhighp int integerMod(highp int x, highp int y) {\n return x - (y * int(x/y));\n}\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nhighp float decode32(highp vec4 rgba) {\n __DECODE32_ENDIANNESS__;\n rgba *= 255.0;\n vec2 gte128;\n gte128.x = rgba.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = rgba.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * rgba.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = exp2(round(exponent));\n rgba.b = rgba.b - 128.0 * gte128.x;\n res = dot(rgba, SCALE_FACTOR) * exp2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nhighp vec4 encode32(highp float f) {\n highp float F = abs(f);\n highp float sign = f < 0.0 ? 1.0 : 0.0;\n highp float exponent = floor(log2(F));\n highp float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 rgba = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n rgba.rg = integerMod(rgba.rg, 256.0);\n rgba.b = integerMod(rgba.b, 128.0);\n rgba.a = exponent*0.5 + 63.5;\n rgba.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n rgba = floor(rgba);\n rgba *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return rgba;\n}\n// Dragons end here\n\nhighp int index;\nhighp ivec3 threadId;\n\nhighp ivec3 indexTo3D(highp int idx, highp ivec3 texDim) {\n highp int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n highp int y = int(idx / texDim.x);\n highp int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nhighp float get(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int z, highp int y, highp int x) {\n highp ivec3 xyz = ivec3(x, y, z);\n __GET_WRAPAROUND__;\n highp int index = xyz.x + texDim.x * (xyz.y + texDim.y * xyz.z);\n __GET_TEXTURE_CHANNEL__;\n highp int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n __GET_TEXTURE_INDEX__;\n highp vec4 texel = texture2D(tex, st / vec2(texSize));\n __GET_RESULT__;\n \n}\n\nhighp vec4 getImage2D(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int z, highp int y, highp int x) {\n highp ivec3 xyz = ivec3(x, y, z);\n __GET_WRAPAROUND__;\n highp int index = xyz.x + texDim.x * (xyz.y + texDim.y * xyz.z);\n __GET_TEXTURE_CHANNEL__;\n highp int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n __GET_TEXTURE_INDEX__;\n return texture2D(tex, st / vec2(texSize));\n}\n\nhighp float get(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int y, highp int x) {\n return get(tex, texSize, texDim, int(0), y, x);\n}\n\nhighp vec4 getImage2D(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int y, highp int x) {\n return getImage2D(tex, texSize, texDim, int(0), y, x);\n}\n\nhighp float get(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int x) {\n return get(tex, texSize, texDim, int(0), int(0), x);\n}\n\nhighp vec4 getImage2D(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int x) {\n return getImage2D(tex, texSize, texDim, int(0), int(0), x);\n}\n\n\nhighp vec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\n__MAIN_PARAMS__;\n__MAIN_CONSTANTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}"; +module.exports = "__HEADER__;\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n\nconst float LOOP_MAX = __LOOP_MAX__;\n\n__CONSTANTS__;\n\nvarying vec2 vTexCoord;\n\nvec4 round(vec4 x) {\n return floor(x + 0.5);\n}\n\nfloat round(float x) {\n return floor(x + 0.5);\n}\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x / y));\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 rgba) {\n __DECODE32_ENDIANNESS__;\n rgba *= 255.0;\n vec2 gte128;\n gte128.x = rgba.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = rgba.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * rgba.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = exp2(round(exponent));\n rgba.b = rgba.b - 128.0 * gte128.x;\n res = dot(rgba, SCALE_FACTOR) * exp2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nvec4 encode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 rgba = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n rgba.rg = integerMod(rgba.rg, 256.0);\n rgba.b = integerMod(rgba.b, 128.0);\n rgba.a = exponent*0.5 + 63.5;\n rgba.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n rgba = floor(rgba);\n rgba *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return rgba;\n}\n// Dragons end here\n\nfloat decode(vec4 rgba, int x, int bitRatio) {\n if (bitRatio == 1) {\n return decode32(rgba);\n }\n __DECODE32_ENDIANNESS__;\n int channel = integerMod(x, bitRatio);\n if (bitRatio == 4) {\n if (channel == 0) return rgba.r * 255.0;\n if (channel == 1) return rgba.g * 255.0;\n if (channel == 2) return rgba.b * 255.0;\n if (channel == 3) return rgba.a * 255.0;\n }\n else {\n if (channel == 0) return rgba.r * 255.0 + rgba.g * 65280.0;\n if (channel == 1) return rgba.b * 255.0 + rgba.a * 65280.0;\n }\n}\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get(sampler2D tex, ivec2 texSize, ivec3 texDim, int bitRatio, int z, int y, int x) {\n ivec3 xyz = ivec3(x, y, z);\n __GET_WRAPAROUND__;\n int index = xyz.x + texDim.x * (xyz.y + texDim.y * xyz.z);\n __GET_TEXTURE_CHANNEL__;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n __GET_TEXTURE_INDEX__;\n vec4 texel = texture2D(tex, st / vec2(texSize));\n __GET_RESULT__;\n \n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n ivec3 xyz = ivec3(x, y, z);\n __GET_WRAPAROUND__;\n int index = xyz.x + texDim.x * (xyz.y + texDim.y * xyz.z);\n __GET_TEXTURE_CHANNEL__;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n __GET_TEXTURE_INDEX__;\n return texture2D(tex, st / vec2(texSize));\n}\n\nfloat get(sampler2D tex, ivec2 texSize, ivec3 texDim, int bitRatio, int y, int x) {\n return get(tex, texSize, texDim, bitRatio, int(0), y, x);\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int y, int x) {\n return getImage2D(tex, texSize, texDim, int(0), y, x);\n}\n\nfloat get(sampler2D tex, ivec2 texSize, ivec3 texDim, int bitRatio, int x) {\n return get(tex, texSize, texDim, bitRatio, int(0), int(0), x);\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int x) {\n return getImage2D(tex, texSize, texDim, int(0), int(0), x);\n}\n\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\nvoid color(sampler2D image) {\n actualColor = texture2D(image, vTexCoord);\n}\n\n__MAIN_PARAMS__;\n__MAIN_CONSTANTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}"; },{}],69:[function(require,module,exports){ "use strict"; -module.exports = "precision highp float;\nprecision highp int;\nprecision highp sampler2D;\n\nattribute highp vec2 aPos;\nattribute highp vec2 aTexCoord;\n\nvarying highp vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"; +module.exports = "precision highp float;\nprecision highp int;\nprecision highp sampler2D;\n\nattribute vec2 aPos;\nattribute vec2 aTexCoord;\n\nvarying vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"; },{}],70:[function(require,module,exports){ 'use strict'; @@ -14096,6 +14264,13 @@ module.exports = function (_WebGLKernel) { this.floatOutput = isFloatReadPixel; } + var hasIntegerDivisionBug = utils.hasIntegerDivisionAccuracyBug(); + if (this.fixIntegerDivisionAccuracy == null) { + this.fixIntegerDivisionAccuracy = hasIntegerDivisionBug; + } else if (this.fixIntegerDivisionAccuracy && !hasIntegerDivisionBug) { + this.fixIntegerDivisionAccuracy = false; + } + utils.checkOutput(this.output); if (!this.output || this.output.length === 0) { @@ -14344,38 +14519,24 @@ module.exports = function (_WebGLKernel) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); var length = size[0] * size[1]; - if (this.floatTextures) { - length *= 4; - } - var valuesFlat = void 0; - - if (utils.isArray(value[0])) { - // not already flat - valuesFlat = new Float32Array(length); - utils.flattenTo(value, valuesFlat); - } else if (value.constructor != Float32Array) { - // TODO: would be great if we could not have to create Float32Array buffers - // if input is 8/16 bit values... - // valuesFlat = new Float32Array(value); - valuesFlat = new Float32Array(length); - valuesFlat.set(value); - } else { - valuesFlat = value; - } + var _formatArrayTransfer = this._formatArrayTransfer(value, length), + valuesFlat = _formatArrayTransfer.valuesFlat, + bitRatio = _formatArrayTransfer.bitRatio; var buffer = void 0; if (this.floatTextures) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, size[0], size[1], 0, gl.RGBA, gl.FLOAT, valuesFlat); } else { buffer = new Uint8Array(valuesFlat.buffer); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size[0], size[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, buffer); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size[0] / bitRatio, size[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, buffer); } if (!this.hardcodeConstants) { this.setUniform3iv('user_' + name + 'Dim', dim); this.setUniform2iv('user_' + name + 'Size', size); } + this.setUniform1i('user_' + name + 'BitRatio', bitRatio); this.setUniform1i('user_' + name, this.argumentsLength); break; } @@ -14401,26 +14562,23 @@ module.exports = function (_WebGLKernel) { gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); var _length = _size[0] * _size[1]; - var inputArray = void 0; - if (this.floatTextures) { - _length *= 4; - inputArray = new Float32Array(_length); - inputArray.set(input.value); - } else { - inputArray = input.value; - } + + var _formatArrayTransfer2 = this._formatArrayTransfer(value.value, _length), + _valuesFlat = _formatArrayTransfer2.valuesFlat, + _bitRatio = _formatArrayTransfer2.bitRatio; if (this.floatTextures) { gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, _size[0], _size[1], 0, gl.RGBA, gl.FLOAT, inputArray); } else { - var _buffer = new Uint8Array(inputArray.buffer); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, _size[0], _size[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, _buffer); + var _buffer = new Uint8Array(_valuesFlat.buffer); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, _size[0] / _bitRatio, _size[1], 0, gl.RGBA, gl.UNSIGNED_BYTE, _buffer); } if (!this.hardcodeConstants) { this.setUniform3iv('user_' + name + 'Dim', _dim); this.setUniform2iv('user_' + name + 'Size', _size); } + this.setUniform1i('user_' + name + 'BitRatio', _bitRatio); this.setUniform1i('user_' + name, this.argumentsLength); break; } @@ -14491,6 +14649,7 @@ module.exports = function (_WebGLKernel) { this.setUniform3iv('user_' + name + 'Dim', _dim4); this.setUniform2iv('user_' + name + 'Size', _size4); + this.setUniform1i('user_' + name + 'BitRatio', 1); // always float32 this.setUniform1i('user_' + name, this.argumentsLength); break; } @@ -14503,6 +14662,22 @@ module.exports = function (_WebGLKernel) { /** * @memberOf WebGL2Kernel# * @function + * @name _getGetResultString + * + */ + + }, { + key: '_getGetResultString', + value: function _getGetResultString() { + if (!this.floatTextures) { + return ' return decode(texel, x, bitRatio);'; + } + return ' return texel[channel];'; + } + + /** + * @memberOf WebGL2Kernel# + * @function * @name _getHeaderString * * @desc Get the header string for the program. @@ -14571,7 +14746,11 @@ module.exports = function (_WebGLKernel) { floatOutput: this.floatOutput }, paramDim); - result.push('uniform highp sampler2D user_' + paramName, 'highp ivec2 user_' + paramName + 'Size = ivec2(' + paramSize[0] + ', ' + paramSize[1] + ')', 'highp ivec3 user_' + paramName + 'Dim = ivec3(' + paramDim[0] + ', ' + paramDim[1] + ', ' + paramDim[2] + ')'); + result.push('uniform highp sampler2D user_' + paramName, 'highp ivec2 user_' + paramName + 'Size = ivec2(' + paramSize[0] + ', ' + paramSize[1] + ')', 'highp ivec3 user_' + paramName + 'Dim = ivec3(' + paramDim[0] + ', ' + paramDim[1] + ', ' + paramDim[2] + ')', 'uniform highp int user_' + paramName + 'BitRatio'); + + if (paramType === 'Array') { + result.push('uniform highp int user_' + paramName + 'BitRatio'); + } } else if (paramType === 'Integer') { result.push('highp float user_' + paramName + ' = ' + param + '.0'); } else if (paramType === 'Float') { @@ -14580,10 +14759,13 @@ module.exports = function (_WebGLKernel) { } else { if (paramType === 'Array' || paramType === 'Texture' || paramType === 'Input' || paramType === 'HTMLImage') { result.push('uniform highp sampler2D user_' + paramName, 'uniform highp ivec2 user_' + paramName + 'Size', 'uniform highp ivec3 user_' + paramName + 'Dim'); + if (paramType !== 'HTMLImage') { + result.push('uniform highp int user_' + paramName + 'BitRatio'); + } } else if (paramType === 'HTMLImageArray') { result.push('uniform highp sampler2DArray user_' + paramName, 'uniform highp ivec2 user_' + paramName + 'Size', 'uniform highp ivec3 user_' + paramName + 'Dim'); } else if (paramType === 'Integer' || paramType === 'Float') { - result.push('uniform highp float user_' + paramName); + result.push('uniform float user_' + paramName); } } } @@ -14607,14 +14789,14 @@ module.exports = function (_WebGLKernel) { var result = []; var names = this.subKernelOutputVariableNames; if (names !== null) { - result.push('highp float kernelResult = 0.0'); - result.push('layout(location = 0) out highp vec4 data0'); + result.push('float kernelResult = 0.0'); + result.push('layout(location = 0) out vec4 data0'); for (var i = 0; i < names.length; i++) { - result.push('highp float ' + names[i] + ' = 0.0', 'layout(location = ' + (i + 1) + ') out highp vec4 data' + (i + 1)); + result.push('float ' + names[i] + ' = 0.0', 'layout(location = ' + (i + 1) + ') out vec4 data' + (i + 1)); } } else { - result.push('out highp vec4 data0'); - result.push('highp float kernelResult = 0.0'); + result.push('out vec4 data0'); + result.push('float kernelResult = 0.0'); } return this._linesToString(result) + this.functionBuilder.getPrototypeString('kernel'); @@ -14709,7 +14891,8 @@ module.exports = function (_WebGLKernel) { debug: this.debug, loopMaxIterations: this.loopMaxIterations, paramNames: this.paramNames, - paramTypes: this.paramTypes + paramTypes: this.paramTypes, + fixIntegerDivisionAccuracy: this.fixIntegerDivisionAccuracy }); if (this.subKernels !== null) { @@ -14847,11 +15030,11 @@ module.exports = function (_RunnerBase) { },{"../runner-base":62,"./function-builder":71,"./kernel":73}],75:[function(require,module,exports){ "use strict"; -module.exports = "#version 300 es\n__HEADER__;\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n\nconst float LOOP_MAX = __LOOP_MAX__;\n#define EPSILON 0.0000001;\n\n__CONSTANTS__;\n\nin highp vec2 vTexCoord;\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nhighp float integerMod(highp float x, highp float y) {\n highp float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nhighp int integerMod(highp int x, highp int y) {\n return x - (y * int(x/y));\n}\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nhighp float decode32(highp vec4 rgba) {\n __DECODE32_ENDIANNESS__;\n rgba *= 255.0;\n vec2 gte128;\n gte128.x = rgba.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = rgba.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * rgba.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = exp2(round(exponent));\n rgba.b = rgba.b - 128.0 * gte128.x;\n res = dot(rgba, SCALE_FACTOR) * exp2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nhighp vec4 encode32(highp float f) {\n highp float F = abs(f);\n highp float sign = f < 0.0 ? 1.0 : 0.0;\n highp float exponent = floor(log2(F));\n highp float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 rgba = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n rgba.rg = integerMod(rgba.rg, 256.0);\n rgba.b = integerMod(rgba.b, 128.0);\n rgba.a = exponent*0.5 + 63.5;\n rgba.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n rgba = floor(rgba);\n rgba *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return rgba;\n}\n// Dragons end here\n\nhighp int index;\nhighp ivec3 threadId;\n\nhighp ivec3 indexTo3D(highp int idx, highp ivec3 texDim) {\n highp int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n highp int y = int(idx / texDim.x);\n highp int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nhighp float get(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int z, highp int y, highp int x) {\n highp ivec3 xyz = ivec3(x, y, z);\n __GET_WRAPAROUND__;\n highp int index = xyz.x + texDim.x * (xyz.y + texDim.y * xyz.z);\n __GET_TEXTURE_CHANNEL__;\n highp int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n __GET_TEXTURE_INDEX__;\n highp vec4 texel = texture(tex, st / vec2(texSize));\n __GET_RESULT__;\n \n}\n\nhighp vec4 getImage2D(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int z, highp int y, highp int x) {\n highp ivec3 xyz = ivec3(x, y, z);\n __GET_WRAPAROUND__;\n highp int index = xyz.x + texDim.x * (xyz.y + texDim.y * xyz.z);\n __GET_TEXTURE_CHANNEL__;\n highp int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n __GET_TEXTURE_INDEX__;\n return texture(tex, st / vec2(texSize));\n}\n\nhighp vec4 getImage3D(highp sampler2DArray tex, highp ivec2 texSize, highp ivec3 texDim, highp int z, highp int y, highp int x) {\n highp ivec3 xyz = ivec3(x, y, z);\n __GET_WRAPAROUND__;\n highp int index = xyz.x + texDim.x * (xyz.y + texDim.y * xyz.z);\n __GET_TEXTURE_CHANNEL__;\n highp int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n __GET_TEXTURE_INDEX__;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nhighp float get(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int y, highp int x) {\n return get(tex, texSize, texDim, int(0), y, x);\n}\n\nhighp float get(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int x) {\n return get(tex, texSize, texDim, int(0), int(0), x);\n}\n\nhighp vec4 getImage2D(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int y, highp int x) {\n return getImage2D(tex, texSize, texDim, int(0), y, x);\n}\n\nhighp vec4 getImage2D(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp int x) {\n return getImage2D(tex, texSize, texDim, int(0), int(0), x);\n}\n\nhighp vec4 getImage2D(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp float y, highp float x) {\n return getImage2D(tex, texSize, texDim, int(0), int(y), int(x));\n}\n\nhighp vec4 getImage2D(highp sampler2D tex, highp ivec2 texSize, highp ivec3 texDim, highp float x) {\n return getImage2D(tex, texSize, texDim, int(0), int(0), int(x));\n}\n\nhighp vec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\n__MAIN_PARAMS__;\n__MAIN_CONSTANTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}"; +module.exports = "#version 300 es\n__HEADER__;\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n\nconst float LOOP_MAX = __LOOP_MAX__;\n\n__CONSTANTS__;\n\nin vec2 vTexCoord;\n\nvec2 integerMod(vec2 x, float y) {\n vec2 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec3 integerMod(vec3 x, float y) {\n vec3 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nvec4 integerMod(vec4 x, vec4 y) {\n vec4 res = floor(mod(x, y));\n return res * step(1.0 - floor(y), -res);\n}\n\nfloat integerMod(float x, float y) {\n float res = floor(mod(x, y));\n return res * (res > floor(y) - 1.0 ? 0.0 : 1.0);\n}\n\nint integerMod(int x, int y) {\n return x - (y * int(x/y));\n}\n\n__DIVIDE_WITH_INTEGER_CHECK__;\n\n// Here be dragons!\n// DO NOT OPTIMIZE THIS CODE\n// YOU WILL BREAK SOMETHING ON SOMEBODY'S MACHINE\n// LEAVE IT AS IT IS, LEST YOU WASTE YOUR OWN TIME\nconst vec2 MAGIC_VEC = vec2(1.0, -256.0);\nconst vec4 SCALE_FACTOR = vec4(1.0, 256.0, 65536.0, 0.0);\nconst vec4 SCALE_FACTOR_INV = vec4(1.0, 0.00390625, 0.0000152587890625, 0.0); // 1, 1/256, 1/65536\nfloat decode32(vec4 rgba) {\n __DECODE32_ENDIANNESS__;\n rgba *= 255.0;\n vec2 gte128;\n gte128.x = rgba.b >= 128.0 ? 1.0 : 0.0;\n gte128.y = rgba.a >= 128.0 ? 1.0 : 0.0;\n float exponent = 2.0 * rgba.a - 127.0 + dot(gte128, MAGIC_VEC);\n float res = exp2(round(exponent));\n rgba.b = rgba.b - 128.0 * gte128.x;\n res = dot(rgba, SCALE_FACTOR) * exp2(round(exponent-23.0)) + res;\n res *= gte128.y * -2.0 + 1.0;\n return res;\n}\n\nvec4 encode32(float f) {\n float F = abs(f);\n float sign = f < 0.0 ? 1.0 : 0.0;\n float exponent = floor(log2(F));\n float mantissa = (exp2(-exponent) * F);\n // exponent += floor(log2(mantissa));\n vec4 rgba = vec4(F * exp2(23.0-exponent)) * SCALE_FACTOR_INV;\n rgba.rg = integerMod(rgba.rg, 256.0);\n rgba.b = integerMod(rgba.b, 128.0);\n rgba.a = exponent*0.5 + 63.5;\n rgba.ba += vec2(integerMod(exponent+127.0, 2.0), sign) * 128.0;\n rgba = floor(rgba);\n rgba *= 0.003921569; // 1/255\n __ENCODE32_ENDIANNESS__;\n return rgba;\n}\n// Dragons end here\n\nfloat decode(vec4 rgba, int x, int bitRatio) {\n if (bitRatio == 1) {\n return decode32(rgba);\n }\n __DECODE32_ENDIANNESS__;\n int channel = integerMod(x, bitRatio);\n if (bitRatio == 4) {\n return rgba[channel] * 255.0;\n }\n else {\n return rgba[channel*2] * 255.0 + rgba[channel*2 + 1] * 65280.0;\n }\n}\n\nint index;\nivec3 threadId;\n\nivec3 indexTo3D(int idx, ivec3 texDim) {\n int z = int(idx / (texDim.x * texDim.y));\n idx -= z * int(texDim.x * texDim.y);\n int y = int(idx / texDim.x);\n int x = int(integerMod(idx, texDim.x));\n return ivec3(x, y, z);\n}\n\nfloat get(sampler2D tex, ivec2 texSize, ivec3 texDim, int bitRatio, int z, int y, int x) {\n ivec3 xyz = ivec3(x, y, z);\n __GET_WRAPAROUND__;\n int index = xyz.x + texDim.x * (xyz.y + texDim.y * xyz.z);\n __GET_TEXTURE_CHANNEL__;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n __GET_TEXTURE_INDEX__;\n vec4 texel = texture(tex, st / vec2(texSize));\n __GET_RESULT__;\n \n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n ivec3 xyz = ivec3(x, y, z);\n __GET_WRAPAROUND__;\n int index = xyz.x + texDim.x * (xyz.y + texDim.y * xyz.z);\n __GET_TEXTURE_CHANNEL__;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n __GET_TEXTURE_INDEX__;\n return texture(tex, st / vec2(texSize));\n}\n\nvec4 getImage3D(sampler2DArray tex, ivec2 texSize, ivec3 texDim, int z, int y, int x) {\n ivec3 xyz = ivec3(x, y, z);\n __GET_WRAPAROUND__;\n int index = xyz.x + texDim.x * (xyz.y + texDim.y * xyz.z);\n __GET_TEXTURE_CHANNEL__;\n int w = texSize.x;\n vec2 st = vec2(float(integerMod(index, w)), float(index / w)) + 0.5;\n __GET_TEXTURE_INDEX__;\n return texture(tex, vec3(st / vec2(texSize), z));\n}\n\nfloat get(sampler2D tex, ivec2 texSize, ivec3 texDim, int bitRatio, int y, int x) {\n return get(tex, texSize, texDim, bitRatio, 0, y, x);\n}\n\nfloat get(sampler2D tex, ivec2 texSize, ivec3 texDim, int bitRatio, int x) {\n return get(tex, texSize, texDim, bitRatio, 0, 0, x);\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int y, int x) {\n return getImage2D(tex, texSize, texDim, 0, y, x);\n}\n\nvec4 getImage2D(sampler2D tex, ivec2 texSize, ivec3 texDim, int x) {\n return getImage2D(tex, texSize, texDim, 0, 0, x);\n}\n\nvec4 actualColor;\nvoid color(float r, float g, float b, float a) {\n actualColor = vec4(r,g,b,a);\n}\n\nvoid color(float r, float g, float b) {\n color(r,g,b,1.0);\n}\n\n__MAIN_PARAMS__;\n__MAIN_CONSTANTS__;\n__KERNEL__;\n\nvoid main(void) {\n index = int(vTexCoord.s * float(uTexSize.x)) + int(vTexCoord.t * float(uTexSize.y)) * uTexSize.x;\n __MAIN_RESULT__;\n}"; },{}],76:[function(require,module,exports){ "use strict"; -module.exports = "#version 300 es\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n\nin highp vec2 aPos;\nin highp vec2 aTexCoord;\n\nout highp vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"; +module.exports = "#version 300 es\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n\nin vec2 aPos;\nin vec2 aTexCoord;\n\nout vec2 vTexCoord;\nuniform vec2 ratio;\n\nvoid main(void) {\n gl_Position = vec4((aPos + vec2(1)) * ratio + vec2(-1), 0, 1);\n vTexCoord = aTexCoord;\n}"; },{}],77:[function(require,module,exports){ 'use strict'; @@ -15069,7 +15252,6 @@ var GPU = function (_GPUCore) { } else { detectedMode = mode || 'gpu'; } - _this.kernels = []; var runnerSettings = { @@ -15389,6 +15571,27 @@ var GPU = function (_GPUCore) { /** * + * Return TRUE, if system has integer division accuracy issue + * + * @name get hasIntegerDivisionAccuracyBug + * @function + * @memberOf GPU# + * + * Note: This function can also be called directly `GPU.hasIntegerDivisionAccuracyBug()` + * + * @returns {Boolean} TRUE if system has integer division accuracy issue + * + * + */ + + }, { + key: 'hasIntegerDivisionAccuracyBug', + value: function hasIntegerDivisionAccuracyBug() { + return utils.hasIntegerDivisionAccuracyBug(); + } + + /** + * * Return the canvas object bound to this gpu instance. * * @name getCanvas @@ -15422,6 +15625,44 @@ var GPU = function (_GPUCore) { value: function getWebGl() { return this._webGl; } + + /** + * + * Destroys all memory associated with gpu.js & the webGl if we created it + * + * @name destroy + * @function + * @memberOf GPU# + * + * + */ + + }, { + key: 'destroy', + value: function destroy() { + var _this2 = this; + + // perform on next runloop - for some reason we dont get lose context events + // if webGl is created and destroyed in the same run loop. + setTimeout(function () { + var kernels = _this2.kernels; + + var destroyWebGl = !_this2._webGl && kernels.length && kernels[0]._webGl; + for (var i = 0; i < _this2.kernels.length; i++) { + _this2.kernels[i].destroy(true); // remove canvas if exists + } + + if (destroyWebGl) { + destroyWebGl.OES_texture_float = null; + destroyWebGl.OES_texture_float_linear = null; + destroyWebGl.OES_element_index_uint = null; + var loseContextExt = destroyWebGl.getExtension('WEBGL_lose_context'); + if (loseContextExt) { + loseContextExt.loseContext(); + } + } + }, 0); + } }]); return GPU; @@ -15468,8 +15709,6 @@ var _createClass = function () { function defineProperties(target, props) { for function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var gpu = null; - module.exports = function () { /** @@ -15895,6 +16134,8 @@ var _isMixedIdentifiersSupported = function () { } }(); +var _hasIntegerDivisionAccuracyBug = null; + /** * @class * @extends UtilsCore @@ -16209,9 +16450,10 @@ var Utils = function (_UtilsCore) { } var GPU = require('../index'); - var x = new GPU({ + var gpu = new GPU({ mode: 'webgl-validator' - }).createKernel(function () { + }); + var x = gpu.createKernel(function () { return 1; }, { output: [2], @@ -16221,7 +16463,7 @@ var Utils = function (_UtilsCore) { })(); _isFloatReadPixelsSupported = x[0] === 1; - + gpu.destroy(); return _isFloatReadPixelsSupported; } @@ -16245,9 +16487,10 @@ var Utils = function (_UtilsCore) { } var GPU = require('../index'); - var x = new GPU({ + var gpu = new GPU({ mode: 'webgl2-validator' - }).createKernel(function () { + }); + var x = gpu.createKernel(function () { return 1; }, { output: [2], @@ -16257,9 +16500,45 @@ var Utils = function (_UtilsCore) { })(); _isFloatReadPixelsSupportedWebGL2 = x[0] === 1; - + gpu.destroy(); return _isFloatReadPixelsSupportedWebGL2; } + + /** + * @memberOf Utils + * @name hasIntegerDivisionAccuracyBug + * @function + * @static + * + * Checks if the system has inaccuracies when dividing integers + * + * @returns {Boolean} true if bug is exhibited on this system + * + */ + + }, { + key: 'hasIntegerDivisionAccuracyBug', + value: function hasIntegerDivisionAccuracyBug() { + if (_hasIntegerDivisionAccuracyBug !== null) { + return _hasIntegerDivisionAccuracyBug; + } + + var GPU = require('../index'); + var gpu = new GPU({ + mode: 'webgl-validator' + }); + var x = gpu.createKernel(function (v1, v2) { + return v1[this.thread.x] / v2[this.thread.x]; + }, { + output: [1] + })([6, 6030401], [3, 3991]); + + // have we not got whole numbers for 6/3 or 6030401/3991 + // add more here if others see this problem + _hasIntegerDivisionAccuracyBug = x[0] !== 2 || x[1] !== 1511; + gpu.destroy(); + return _hasIntegerDivisionAccuracyBug; + } }, { key: 'isMixedIdentifiersSupported', value: function isMixedIdentifiersSupported() { @@ -16276,8 +16555,7 @@ var Utils = function (_UtilsCore) { } if (opt.floatTextures && (!output || opt.floatOutput)) { - numTexels = Math.ceil(numTexels / 4); - w = Math.ceil(numTexels / 4); + w = numTexels = Math.ceil(numTexels / 4); } // if given dimensions == a 2d image if (h > 1 && w * h === numTexels) { diff --git a/browser.min.js b/browser.min.js index 2b9bcde4e..2e1eb33d8 100644 --- a/browser.min.js +++ b/browser.min.js @@ -6,7 +6,7 @@ * license: MIT (http://opensource.org/licenses/MIT) * author: Heather Arthur * homepage: https://github.com/brainjs/brain.js#readme - * version: 1.2.4 + * version: 1.2.5 * * acorn: * license: MIT (http://opensource.org/licenses/MIT) @@ -41,7 +41,7 @@ * license: MIT (http://opensource.org/licenses/MIT) * author: The gpu.js Team * homepage: http://gpu.rocks/ - * version: 1.5.2 + * version: 1.6.0 * * ieee754: * license: BSD-3-Clause (http://opensource.org/licenses/BSD-3-Clause) @@ -123,7 +123,7 @@ "use strict";function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t}}function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function weightedSumSigmoid(t,e,a){for(var s=e[this.thread.x],i=0;i0?t:0}function calcDeltasLeakyRelu(t,e){return e>0?t:.01*t}function calcDeltasTanh(t,e){return(1-e*e)*t}function calcError(t,e){for(var a=0,s=0;s0&&void 0!==arguments[0]?arguments[0]:{};_classCallCheck(this,e);var a=_possibleConstructorReturn(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return a.forwardPropagate=[],a.backwardPropagate=[],a.changesPropagate=[],a.biasesPropagate=[],a.biasCopies=[],a.copyBias=[],a.changesCopies=[],a.copyChanges=[],a.weightsCopies=[],a.copyWeights=[],a.errorCheckInterval=100,a.gpu=new _gpu2.default({mode:t.mode}),a}return _inherits(e,t),_createClass(e,[{key:"_initialize",value:function(){_get(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"_initialize",this).call(this),this.buildRunInput(),this.buildCalculateDeltas(),this.buildGetChanges(),this.buildChangeBiases(),this.buildGetMSE()}},{key:"setActivation",value:function(){}},{key:"_trainPattern",value:function(t,e,a){return this.runInput(t),this.calculateDeltas(e),this.getChanges(),this.changeBiases(),a?this.getMSE(this.errors[this.outputLayer])[0]:null}},{key:"buildRunInput",value:function(){var t=null;switch(this.activation){case"sigmoid":t=weightedSumSigmoid;break;case"relu":t=weightedSumRelu;break;case"leaky-relu":t=weightedSumLeakyRelu;break;case"tanh":t=weightedSumTanh;break;default:throw new Error("unknown activation "+this.activation)}for(var e=1;e<=this.outputLayer;e++)this.forwardPropagate[e]=this.gpu.createKernel(t,{output:[this.sizes[e]],outputToTexture:!0,hardcodeConstants:!0,constants:{size:this.sizes[e-1]}});this._texturizeInputData=this.gpu.createKernel(function(t){return t[this.thread.x]},{output:[this.sizes[1]],outputToTexture:!0,hardcodeConstants:!0,outputImmutable:!0})}},{key:"runInput",value:function(t){var e=void 0;this.outputs[0]=t;for(var a=1;a<=this.outputLayer;a++)this.outputs[a]=this.forwardPropagate[a](this.weights[a],this.biases[a],t),e=t=this.outputs[a];return e}},{key:"buildCalculateDeltas",value:function(){var t=null;switch(this.activation){case"sigmoid":t=calcDeltasSigmoid;break;case"relu":t=calcDeltasRelu;break;case"leaky-relu":t=calcDeltasLeakyRelu;break;case"tanh":t=calcDeltasTanh;break;default:throw new Error("unknown activation "+this.activation)}for(var e=this.outputLayer;e>0;e--)e===this.outputLayer?this.backwardPropagate[e]=this.gpu.createKernelMap({error:_gpu2.default.alias("calcErrorOutput",calcErrorOutput),deltas:_gpu2.default.alias("calcDeltas",t)},function(e,a){var s=e[this.thread.x];return t(calcErrorOutput(s,a),s)},{output:[this.sizes[e]],outputToTexture:!0,hardcodeConstants:!0}):this.backwardPropagate[e]=this.gpu.createKernelMap({error:_gpu2.default.alias("calcError",calcError),deltas:_gpu2.default.alias("calcDeltas",t)},function(e,a,s){var i=a[this.thread.x];return t(calcError(e,s),i)},{output:[this.sizes[e]],outputToTexture:!0,hardcodeConstants:!0,constants:{size:this.deltas[e+1].length}})}},{key:"calculateDeltas",value:function(t){for(var e=this.outputLayer;e>0;e--){var a=void 0;a=e===this.outputLayer?this.backwardPropagate[e](this.outputs[e],t):this.backwardPropagate[e](this.weights[e+1],this.outputs[e],this.deltas[e+1]),this.deltas[e]=a.deltas,this.errors[e]=a.error}}},{key:"buildGetChanges",value:function(){for(var t=1;t<=this.outputLayer;t++)this.changesPropagate[t]=this.gpu.createKernelMap({weights:_gpu2.default.alias("addWeights",addWeights),changes:_gpu2.default.alias("calcChanges",calcChanges)},function(t,e,a,s){return addWeights(calcChanges(s,e,t),a)},{output:[this.sizes[t-1],this.sizes[t]],outputToTexture:!0,hardcodeConstants:!0,constants:{size:this.outputs[t-1].length,learningRate:this.trainOpts.learningRate,momentum:this.trainOpts.momentum}}),this.copyChanges[t]=this.gpu.createKernel(function(t){return t[this.thread.y][this.thread.x]},{output:this.changesPropagate[t].output,outputToTexture:!0,hardCodeConstants:!0}),this.copyWeights[t]=this.gpu.createKernel(function(t){return t[this.thread.y][this.thread.x]},{output:this.changesPropagate[t].output,outputToTexture:!0,hardCodeConstants:!0})}},{key:"getChanges",value:function(){for(var t=1;t<=this.outputLayer;t++){var e=this.changesPropagate[t](this.outputs[t-1],this.deltas[t],this.weightsCopies[t]||this.weights[t],this.changesCopies[t]||this.changes[t]);this.changes[t]=e.changes,this.weights[t]=e.weights,this.changesCopies[t]=this.copyChanges[t](e.changes),this.weightsCopies[t]=this.copyWeights[t](e.weights)}}},{key:"buildChangeBiases",value:function(){for(var t=1;t<=this.outputLayer;t++)this.biasesPropagate[t]=this.gpu.createKernel(addBiases,{output:[this.sizes[t]],outputToTexture:!0,hardcodeConstants:!0,constants:{learningRate:this.trainOpts.learningRate}}),this.copyBias[t]=this.gpu.createKernel(function(t){return t[this.thread.x]},{output:this.biasesPropagate[t].output,outputToTexture:!0,hardCodeConstants:!0})}},{key:"changeBiases",value:function(){for(var t=1;t<=this.outputLayer;t++)this.biases[t]=this.biasesPropagate[t](this.biasCopies[t]||this.biases[t],this.deltas[t]),this.biasCopies[t]=this.copyBias[t](this.biases[t])}},{key:"buildGetMSE",value:function(){this.getMSE=this.gpu.createKernel(mse,{output:[1],hardcodeConstants:!0,constants:{size:this.sizes[this.outputLayer]}})}},{key:"run",value:function(t){if(!this.isRunnable)return null;this.inputLookup&&(t=_lookup2.default.toArray(this.inputLookup,t));var e=this._texturizeInputData(t),a=this.runInput(e),s=a.toArray(this.gpu);return this.outputLookup&&(s=_lookup2.default.toHash(this.outputLookup,s)),s}},{key:"_verifyIsInitialized",value:function(t){var e=this;this.sizes||(this.sizes=[],t[0].size||(t[0].size={input:t[0].input.length,output:t[0].output.length}),this.sizes.push(t[0].size.input),this.hiddenSizes?this.hiddenSizes.forEach(function(t){e.sizes.push(t)}):this.sizes.push(Math.max(3,Math.floor(t[0].size.input/2))),this.sizes.push(t[0].size.output),this._initialize())}},{key:"_prepTraining",value:function(t,e){var a=this;this._updateTrainingOptions(e),t=this._formatData(t);var s=Date.now()+this.trainOpts.timeout,i={error:1,iterations:0};this._verifyIsInitialized(t);var r=this.gpu.createKernel(function(t){return t[this.thread.x]},{output:[t[0].output.length],outputToTexture:!0,hardcodeConstants:!0,outputImmutable:!0});return{data:t.map(function(t){return{size:t.size,input:a._texturizeInputData(t.input),output:r(t.output)}}),status:i,endTime:s}}},{key:"toFunction",value:function(){throw new Error("not implemented on NeuralNetworkGPU")}}]),e}(_neuralNetwork2.default);exports.default=NeuralNetworkGPU; },{"./lookup":3,"./neural-network":5,"gpu.js":85}],5:[function(require,module,exports){ -"use strict";function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t}}function _toConsumableArray(t){if(Array.isArray(t)){for(var i=0,e=Array(t.length);i0&&void 0!==arguments[0]?arguments[0]:{};_classCallCheck(this,t),Object.assign(this,this.constructor.defaults,i),this.hiddenSizes=i.hiddenLayers,this.trainOpts={},this._updateTrainingOptions(Object.assign({},this.constructor.trainDefaults,i)),this.sizes=null,this.outputLayer=null,this.biases=null,this.weights=null,this.outputs=null,this.deltas=null,this.changes=null,this.errors=null,this.errorCheckInterval=1,this.constructor.prototype.hasOwnProperty("runInput")||(this.runInput=null),this.constructor.prototype.hasOwnProperty("calculateDeltas")||(this.calculateDeltas=null)}return _createClass(t,null,[{key:"_validateTrainingOptions",value:function(i){var e={iterations:function(t){return"number"==typeof t&&t>0},errorThresh:function(t){return"number"==typeof t&&t>0&&t<1},log:function(t){return"function"==typeof t||"boolean"==typeof t},logPeriod:function(t){return"number"==typeof t&&t>0},learningRate:function(t){return"number"==typeof t&&t>0&&t<1},momentum:function(t){return"number"==typeof t&&t>0&&t<1},callback:function(t){return"function"==typeof t||null===t},callbackPeriod:function(t){return"number"==typeof t&&t>0},timeout:function(t){return"number"==typeof t&&t>0}};Object.keys(t.trainDefaults).forEach(function(t){if(e.hasOwnProperty(t)&&!e[t](i[t]))throw new Error("["+t+", "+i[t]+"] is out of normal training range, your network will probably not train.")})}},{key:"trainDefaults",get:function(){return{iterations:2e4,errorThresh:.005,log:!1,logPeriod:10,learningRate:.3,momentum:.1,callback:null,callbackPeriod:10,timeout:1/0}}},{key:"defaults",get:function(){return{binaryThresh:.5,hiddenLayers:[3],activation:"sigmoid"}}}]),_createClass(t,[{key:"_initialize",value:function(){if(!this.sizes)throw new Error("Sizes must be set before initializing");this.outputLayer=this.sizes.length-1,this.biases=[],this.weights=[],this.outputs=[],this.deltas=[],this.changes=[],this.errors=[];for(var t=0;t<=this.outputLayer;t++){var i=this.sizes[t];if(this.deltas[t]=(0,_zeros2.default)(i),this.errors[t]=(0,_zeros2.default)(i),this.outputs[t]=(0,_zeros2.default)(i),t>0){this.biases[t]=(0,_randos2.default)(i),this.weights[t]=new Array(i),this.changes[t]=new Array(i);for(var e=0;e=this.trainOpts.iterations||i.error<=this.trainOpts.errorThresh||Date.now()>=e)&&(i.iterations++,this.trainOpts.log&&i.iterations%this.trainOpts.logPeriod==0?(i.error=this._calculateTrainingError(t),this.trainOpts.log("iterations: "+i.iterations+", training error: "+i.error)):i.iterations%this.errorCheckInterval==0?i.error=this._calculateTrainingError(t):this._trainPatterns(t),this.trainOpts.callback&&i.iterations%this.trainOpts.callbackPeriod==0&&this.trainOpts.callback(Object.assign(i)),!0)}},{key:"_prepTraining",value:function(t,i){this._updateTrainingOptions(i),t=this._formatData(t);var e=Date.now()+this.trainOpts.timeout,r={error:1,iterations:0};return this._verifyIsInitialized(t),{data:t,status:r,endTime:e}}},{key:"train",value:function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},e=void 0,r=void 0,s=this._prepTraining(t,i);for(t=s.data,e=s.status,r=s.endTime;this._trainingTick(t,e,r););return e}},{key:"trainAsync",value:function(t){var i=this,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=void 0,s=void 0,a=this._prepTraining(t,e);return t=a.data,r=a.status,s=a.endTime,new Promise(function(e,a){try{var n=new _thaw2.default(new Array(i.trainOpts.iterations),{delay:!0,each:function(){return i._trainingTick(t,r,s)||n.stop()},done:function(){return e(r)}});n.tick()}catch(t){a({trainError:t,status:r})}})}},{key:"_trainPattern",value:function(t,i,e){return this.runInput(t),this.calculateDeltas(i),this._adjustWeights(),e?(0,_mse2.default)(this.errors[this.outputLayer]):null}},{key:"_calculateDeltasSigmoid",value:function(t){for(var i=this.outputLayer;i>=0;i--)for(var e=0;e=0;i--)for(var e=0;e0?s:0}}},{key:"_calculateDeltasLeakyRelu",value:function(t){for(var i=this.outputLayer;i>=0;i--)for(var e=0;e0?s:.01*s}}},{key:"_calculateDeltasTanh",value:function(t){for(var i=this.outputLayer;i>=0;i--)for(var e=0;ei.binaryThresh?1:0,f=p[0]):(c=l.indexOf((0,_max2.default)(l)),f=p.indexOf((0,_max2.default)(p))),c!==f){var v=t[h];Object.assign(v,{actual:c,expected:f}),u.push(v)}e&&(0===c&&0===f?n++:1===c&&1===f?a++:0===c&&1===f?s++:1===c&&0===f&&r++);var y=l.map(function(t,i){return p[i]-t});o+=(0,_mse2.default)(y)}(h);var l=o/t.length,p={error:l,misclasses:u};return e&&Object.assign(p,{trueNeg:n,truePos:a,falseNeg:s,falsePos:r,total:t.length,precision:a/(a+r),recall:a/(a+s),accuracy:(n+a)/t.length}),p}},{key:"toJSON",value:function(){for(var t=[],i=0;i<=this.outputLayer;i++){t[i]={};var e=void 0;e=0===i&&this.inputLookup?Object.keys(this.inputLookup):i===this.outputLayer&&this.outputLookup?Object.keys(this.outputLookup):(0,_range2.default)(0,this.sizes[i]);for(var r=0;r0){t[i][s].bias=this.biases[i][r],t[i][s].weights={};for(var a in t[i-1]){var n=a;1===i&&this.inputLookup&&(n=this.inputLookup[a]),t[i][s].weights[a]=this.weights[i][r][n]}}}}return{sizes:this.sizes,layers:t,outputLookup:!!this.outputLookup,inputLookup:!!this.inputLookup,activation:this.activation,trainOpts:this._getTrainOptsJSON()}}},{key:"fromJSON",value:function(t){this.sizes=t.sizes,this._initialize();for(var i=0;i<=this.outputLayer;i++){var e=t.layers[i];if(0!==i||e[0]&&!t.inputLookup?i!==this.outputLayer||e[0]&&!t.outputLookup||(this.outputLookup=_lookup2.default.lookupFromHash(e)):this.inputLookup=_lookup2.default.lookupFromHash(e),i>0){var r=Object.keys(e);this.sizes[i]=r.length;for(var s in r){var a=r[s];this.biases[i][s]=e[a].bias,this.weights[i][s]=(0,_toArray2.default)(e[a].weights)}}}return t.hasOwnProperty("trainOpts")&&this._updateTrainingOptions(t.trainOpts),this.setActivation(this.activation||"sigmoid"),this}},{key:"toFunction",value:function(){function t(e,r,s){if(0===r)return"string"==typeof s?"input['"+s+"']":"input["+s+"]";var a=e[r],n=a[s],u=[n.bias];for(var o in n.weights)n.weights[o]<0?u.push(n.weights[o]+"*("+t(e,r-1,o)+")"):u.push("+"+n.weights[o]+"*("+t(e,r-1,o)+")");switch(i){case"sigmoid":return"1/(1+1/Math.exp("+u.join("")+"))";case"relu":return"var sum = "+u.join("")+";(sum < 0 ? 0 : sum);";case"leaky-relu":return"var sum = "+u.join("")+";(sum < 0 ? 0 : 0.01 * sum);";case"tanh":return"Math.tanh("+u.join("")+");";default:throw new Error("unknown activation type "+i)}}var i=this.activation,e=this.toJSON().layers,r=[],s=void 0;for(var a in e[e.length-1])r.push(t(e,e.length-1,a));return s=this.outputLookup?"{"+Object.keys(this.outputLookup).map(function(t,i){return"'"+t+"':"+r[i]})+"}":"["+r.join(",")+"]",new Function("input","return "+s)}},{key:"createTrainStream",value:function(t){return t=t||{},t.neuralNetwork=this,this.setActivation(),this.trainStream=new _trainStream2.default(t),this.trainStream}},{key:"isRunnable",get:function(){var t=this;if(!this.runInput)return console.error("Activation function has not been initialized, did you run train()?"),!1;var i=["sizes","outputLayer","biases","weights","outputs","deltas","changes","errors"].filter(function(i){return null===t[i]});return!(i.length>0)||(console.error("Some settings have not been initialized correctly, did you run train()? Found issues with: "+i.join(", ")),!1)}}]),t}();exports.default=NeuralNetwork; +"use strict";function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t}}function _toConsumableArray(t){if(Array.isArray(t)){for(var i=0,e=Array(t.length);i0&&void 0!==arguments[0]?arguments[0]:{};_classCallCheck(this,t),Object.assign(this,this.constructor.defaults,i),this.hiddenSizes=i.hiddenLayers,this.trainOpts={},this._updateTrainingOptions(Object.assign({},this.constructor.trainDefaults,i)),this.sizes=null,this.outputLayer=null,this.biases=null,this.weights=null,this.outputs=null,this.deltas=null,this.changes=null,this.errors=null,this.errorCheckInterval=1,this.constructor.prototype.hasOwnProperty("runInput")||(this.runInput=null),this.constructor.prototype.hasOwnProperty("calculateDeltas")||(this.calculateDeltas=null)}return _createClass(t,null,[{key:"_validateTrainingOptions",value:function(i){var e={iterations:function(t){return"number"==typeof t&&t>0},errorThresh:function(t){return"number"==typeof t&&t>0&&t<1},log:function(t){return"function"==typeof t||"boolean"==typeof t},logPeriod:function(t){return"number"==typeof t&&t>0},learningRate:function(t){return"number"==typeof t&&t>0&&t<1},momentum:function(t){return"number"==typeof t&&t>0&&t<1},callback:function(t){return"function"==typeof t||null===t},callbackPeriod:function(t){return"number"==typeof t&&t>0},timeout:function(t){return"number"==typeof t&&t>0}};Object.keys(t.trainDefaults).forEach(function(t){if(e.hasOwnProperty(t)&&!e[t](i[t]))throw new Error("["+t+", "+i[t]+"] is out of normal training range, your network will probably not train.")})}},{key:"trainDefaults",get:function(){return{iterations:2e4,errorThresh:.005,log:!1,logPeriod:10,learningRate:.3,momentum:.1,callback:null,callbackPeriod:10,timeout:1/0}}},{key:"defaults",get:function(){return{binaryThresh:.5,hiddenLayers:[3],activation:"sigmoid"}}}]),_createClass(t,[{key:"_initialize",value:function(){if(!this.sizes)throw new Error("Sizes must be set before initializing");this.outputLayer=this.sizes.length-1,this.biases=[],this.weights=[],this.outputs=[],this.deltas=[],this.changes=[],this.errors=[];for(var t=0;t<=this.outputLayer;t++){var i=this.sizes[t];if(this.deltas[t]=(0,_zeros2.default)(i),this.errors[t]=(0,_zeros2.default)(i),this.outputs[t]=(0,_zeros2.default)(i),t>0){this.biases[t]=(0,_randos2.default)(i),this.weights[t]=new Array(i),this.changes[t]=new Array(i);for(var e=0;e=this.trainOpts.iterations||i.error<=this.trainOpts.errorThresh||Date.now()>=e)&&(i.iterations++,this.trainOpts.log&&i.iterations%this.trainOpts.logPeriod==0?(i.error=this._calculateTrainingError(t),this.trainOpts.log("iterations: "+i.iterations+", training error: "+i.error)):i.iterations%this.errorCheckInterval==0?i.error=this._calculateTrainingError(t):this._trainPatterns(t),this.trainOpts.callback&&i.iterations%this.trainOpts.callbackPeriod==0&&this.trainOpts.callback(Object.assign(i)),!0)}},{key:"_prepTraining",value:function(t,i){this._updateTrainingOptions(i),t=this._formatData(t);var e=Date.now()+this.trainOpts.timeout,r={error:1,iterations:0};return this._verifyIsInitialized(t),{data:t,status:r,endTime:e}}},{key:"train",value:function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},e=void 0,r=void 0,s=this._prepTraining(t,i);for(t=s.data,e=s.status,r=s.endTime;this._trainingTick(t,e,r););return e}},{key:"trainAsync",value:function(t){var i=this,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=void 0,s=void 0,a=this._prepTraining(t,e);return t=a.data,r=a.status,s=a.endTime,new Promise(function(e,a){try{var n=new _thaw2.default(new Array(i.trainOpts.iterations),{delay:!0,each:function(){return i._trainingTick(t,r,s)||n.stop()},done:function(){return e(r)}});n.tick()}catch(t){a({trainError:t,status:r})}})}},{key:"_trainPattern",value:function(t,i,e){return this.runInput(t),this.calculateDeltas(i),this._adjustWeights(),e?(0,_mse2.default)(this.errors[this.outputLayer]):null}},{key:"_calculateDeltasSigmoid",value:function(t){for(var i=this.outputLayer;i>=0;i--)for(var e=0;e=0;i--)for(var e=0;e0?s:0}}},{key:"_calculateDeltasLeakyRelu",value:function(t){for(var i=this.outputLayer;i>=0;i--)for(var e=0;e0?s:.01*s}}},{key:"_calculateDeltasTanh",value:function(t){for(var i=this.outputLayer;i>=0;i--)for(var e=0;ei.binaryThresh?1:0,f=p[0]):(c=l.indexOf((0,_max2.default)(l)),f=p.indexOf((0,_max2.default)(p))),c!==f){var v=t[h];Object.assign(v,{actual:c,expected:f}),u.push(v)}e&&(0===c&&0===f?n++:1===c&&1===f?a++:0===c&&1===f?s++:1===c&&0===f&&r++);var y=l.map(function(t,i){return p[i]-t});o+=(0,_mse2.default)(y)}(h);var l=o/t.length,p={error:l,misclasses:u};return e&&Object.assign(p,{trueNeg:n,truePos:a,falseNeg:s,falsePos:r,total:t.length,precision:a/(a+r),recall:a/(a+s),accuracy:(n+a)/t.length}),p}},{key:"toJSON",value:function(){for(var t=[],i=0;i<=this.outputLayer;i++){t[i]={};var e=void 0;e=0===i&&this.inputLookup?Object.keys(this.inputLookup):i===this.outputLayer&&this.outputLookup?Object.keys(this.outputLookup):(0,_range2.default)(0,this.sizes[i]);for(var r=0;r0){t[i][s].bias=this.biases[i][r],t[i][s].weights={};for(var a in t[i-1]){var n=a;1===i&&this.inputLookup&&(n=this.inputLookup[a]),t[i][s].weights[a]=this.weights[i][r][n]}}}}return{sizes:this.sizes,layers:t,outputLookup:!!this.outputLookup,inputLookup:!!this.inputLookup,activation:this.activation,trainOpts:this._getTrainOptsJSON()}}},{key:"fromJSON",value:function(t){this.sizes=t.sizes,this._initialize();for(var i=0;i<=this.outputLayer;i++){var e=t.layers[i];if(0!==i||e[0]&&!t.inputLookup?i!==this.outputLayer||e[0]&&!t.outputLookup||(this.outputLookup=_lookup2.default.lookupFromHash(e)):this.inputLookup=_lookup2.default.lookupFromHash(e),i>0){var r=Object.keys(e);this.sizes[i]=r.length;for(var s in r){var a=r[s];this.biases[i][s]=e[a].bias,this.weights[i][s]=(0,_toArray2.default)(e[a].weights)}}}return t.hasOwnProperty("trainOpts")&&this._updateTrainingOptions(t.trainOpts),this.setActivation(this.activation||"sigmoid"),this}},{key:"toFunction",value:function(){function t(e,r,s){if(0===r)return"string"==typeof s?"input['"+s+"']":"input["+s+"]";var a=e[r],n=a[s],u=[n.bias];for(var o in n.weights)n.weights[o]<0?u.push(n.weights[o]+"*("+t(e,r-1,o)+")"):u.push("+"+n.weights[o]+"*("+t(e,r-1,o)+")");switch(i){case"sigmoid":return"1/(1+1/Math.exp("+u.join("")+"))";case"relu":return"("+u.join("")+" < 0 ? 0 : "+u.join("")+")";case"leaky-relu":return"("+u.join("")+" < 0 ? 0 : 0.01 * "+u.join("")+")";case"tanh":return"Math.tanh("+u.join("")+")";default:throw new Error("unknown activation type "+i)}}var i=this.activation,e=this.toJSON().layers,r=[],s=void 0;for(var a in e[e.length-1])r.push(t(e,e.length-1,a));return s=this.outputLookup?"{"+Object.keys(this.outputLookup).map(function(t,i){return"'"+t+"':"+r[i]})+"}":"["+r.join(",")+"]",new Function("input","return "+s)}},{key:"createTrainStream",value:function(t){return t=t||{},t.neuralNetwork=this,this.setActivation(),this.trainStream=new _trainStream2.default(t),this.trainStream}},{key:"isRunnable",get:function(){var t=this;if(!this.runInput)return console.error("Activation function has not been initialized, did you run train()?"),!1;var i=["sizes","outputLayer","biases","weights","outputs","deltas","changes","errors"].filter(function(i){return null===t[i]});return!(i.length>0)||(console.error("Some settings have not been initialized correctly, did you run train()? Found issues with: "+i.join(", ")),!1)}}]),t}();exports.default=NeuralNetwork; },{"./lookup":3,"./train-stream":36,"./utilities/max":38,"./utilities/mse":39,"./utilities/randos":43,"./utilities/range":44,"./utilities/to-array":45,"./utilities/zeros":46,"thaw.js":110}],6:[function(require,module,exports){ "use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function e(e,t){for(var r=0;r0?t.equationConnections[t.equationConnections.length-1]:this.initialLayerInputs,u=this.getEquation(i,i.input(t.input),o[0],n[0]);r.push(u);for(var a=1,s=e.length;a-1;t--)this.model.equations[t].runBackpropagate()}},{key:"run",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(!this.isRunnable)return null;for(var n=this.model;n.equations.length0&&void 0!==arguments[0]?arguments[0]:{};_classCallCheck(this,t);var n=this.constructor.defaults;Object.assign(this,n,r),this.stepCache={},this.runs=0,this.totalCost=null,this.ratioClipped=null,this.model=null,this.initialLayerInputs=this.hiddenSizes.map(function(t){return new _matrix2.default(e.hiddenSizes[0],1)}),this.inputLookup=null,this.outputLookup=null,this.initialize()}return _createClass(t,[{key:"initialize",value:function(){this.model={input:null,hiddenLayers:[],output:null,equations:[],allMatrices:[],equationConnections:[]},null!==this.dataFormatter&&(this.inputSize=this.inputRange=this.outputSize=this.dataFormatter.characters.length),this.json?this.fromJSON(this.json):this.mapModel()}},{key:"createHiddenLayers",value:function(){var t=this.hiddenSizes,e=this.model,r=e.hiddenLayers;r.push(this.getModel(t[0],this.inputSize));for(var n=t[0],a=1;a0?t.equationConnections[t.equationConnections.length-1]:this.initialLayerInputs,o=this.getEquation(n,n.inputMatrixToRow(t.input),i[0],r[0]);a.push(o);for(var u=1,s=e.length;u1&&void 0!==arguments[1]?arguments[1]:null,r=this.runInput(t);return this.runBackpropagate(t),this.step(e),r}},{key:"runInput",value:function(t){this.runs++;for(var e=this.model,r=t.length,n=0,a=0,i=void 0;e.equations.length<=t.length+1;)this.bindEquation();for(var o=-1,u=t.length;o0;)n[e].runBackpropagate(t[e-1]+1),e--;n[0].runBackpropagate(0)}},{key:"step",value:function(){for(var t=(arguments.length>0&&void 0!==arguments[0]&&arguments[0],this.learningRate),e=this.regc,r=this.clipval,n=this.model,a=0,i=0,o=n.allMatrices,u=0;ur&&(f=r,a++),f<-r&&(f=-r,a++),i++,l[d]=c+-t*f/Math.sqrt(p[d]+this.smoothEps)-e*c}}this.ratioClipped=a/i}},{key:"run",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;if(!this.isRunnable)return null;for(var a=this.formatDataIn(t),i=this.model,o=[],u=0;i.equations.length=e)break;o.push(m)}return this.formatDataOut(a,o.slice(a.length).map(function(t){return t-1}))}},{key:"train",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e=Object.assign({},this.constructor.trainDefaults,e);var r=e.iterations,n=e.errorThresh,a=!0===e.log?console.log:e.log,i=e.logPeriod,o=e.learningRate||this.learningRate,u=e.callback,s=e.callbackPeriod,l=1/0,h=void 0;for(this.hasOwnProperty("setupData")&&(t=this.setupData(t)),e.keepNetworkIntact||this.initialize(),h=0;hn;h++){for(var p=0,d=0;d-1)return"typeof prevStates["+o+"] === 'object' ? prevStates["+o+"].product : new Matrix("+t.rows+", "+t.columns+")";case i.right:if(o>-1)return"typeof prevStates["+o+"] === 'object' ? prevStates["+o+"].product : new Matrix("+t.rows+", "+t.columns+")";case i.product:return"new Matrix("+t.rows+", "+t.columns+")";default:throw Error("unknown state")}}if(t===i.product)return"states["+n+"].product";if(t===i.right)return"states["+n+"].right";if(t===i.left)return"states["+n+"].left"}}function e(t){for(var e=a.equationConnections[0],r=i[0].states,n=0,o=r.length;n= maxPredictionLength) {\n break;\n }\n\n output.push(nextIndex);\n }\n "+(null!==this.dataFormatter&&"function"==typeof this.formatDataOut?"return formatDataOut(input, output.slice(input.length).map(function(value) { return value - 1; }))":"return output.slice(input.length).map(function(value) { return value - 1; })")+";\n function Matrix(rows, columns) {\n this.rows = rows;\n this.columns = columns;\n this.weights = zeros(rows * columns);\n }\n "+(null!==this.dataFormatter&&"function"==typeof this.formatDataIn?"function formatDataIn(input, output) { "+n(this.formatDataIn.toString()).replace(/this[.]dataFormatter[\n\s]+[.]/g,"").replace(/this[.]dataFormatter[.]/g,"").replace(/this[.]dataFormatter/g,"true")+" }":"")+"\n "+(null!==this.dataFormatter&&"function"==typeof this.formatDataOut?"function formatDataOut(input, output) { "+n(this.formatDataOut.toString()).replace(/this[.]dataFormatter[\n\s]+[.]/g,"").replace(/this[.]dataFormatter[.]/g,"").replace(/this[.]dataFormatter/g,"true")+" }":"")+"\n "+_zeros2.default.toString()+"\n "+_softmax2.default.toString().replace("_2.default","Matrix")+"\n "+_random.randomF.toString()+"\n "+_sampleI2.default.toString()+"\n "+_maxI2.default.toString();return new Function("rawInput","maxPredictionLength","isSampleI","temperature",g)}},{key:"isRunnable",get:function(){return 0!==this.model.equations.length||(console.error("No equations bound, did you run train()?"),!1)}}]),t}();exports.default=RNN,RNN.defaults={inputSize:20,inputRange:20,hiddenSizes:[20,20],outputSize:20,learningRate:.01,decayRate:.999,smoothEps:1e-8,regc:1e-6,clipval:5,json:null,setupData:function(t){if(!("string"==typeof t[0]||Array.isArray(t[0])||t[0].hasOwnProperty("input")&&t[0].hasOwnProperty("output")))return t;var e=[],r=[];if("string"==typeof t[0]||Array.isArray(t[0])){if(null===this.dataFormatter){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;return null!==this.dataFormatter?this.dataFormatter.indexTable.hasOwnProperty("stop-input")?this.dataFormatter.toIndexesInputOutput(t,e):this.dataFormatter.toIndexes(t):t},formatDataOut:function(t,e){return null!==this.dataFormatter?this.dataFormatter.toCharacters(e).join(""):e},dataFormatter:null},RNN.trainDefaults={iterations:2e4,errorThresh:.005,log:!1,logPeriod:10,learningRate:.3,callback:null,callbackPeriod:10,keepNetworkIntact:!1}; +"use strict";function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t}}function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(exports,"__esModule",{value:!0});var _createClass=function(){function t(t,e){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{};_classCallCheck(this,t);var n=this.constructor.defaults;Object.assign(this,n,r),this.stepCache={},this.runs=0,this.totalCost=null,this.ratioClipped=null,this.model=null,this.initialLayerInputs=this.hiddenSizes.map(function(t){return new _matrix2.default(e.hiddenSizes[0],1)}),this.inputLookup=null,this.outputLookup=null,this.initialize()}return _createClass(t,[{key:"initialize",value:function(){this.model={input:null,hiddenLayers:[],output:null,equations:[],allMatrices:[],equationConnections:[]},null!==this.dataFormatter&&(this.inputSize=this.inputRange=this.outputSize=this.dataFormatter.characters.length),this.json?this.fromJSON(this.json):this.mapModel()}},{key:"createHiddenLayers",value:function(){var t=this.hiddenSizes,e=this.model,r=e.hiddenLayers;r.push(this.getModel(t[0],this.inputSize));for(var n=t[0],a=1;a0?t.equationConnections[t.equationConnections.length-1]:this.initialLayerInputs,o=this.getEquation(n,n.inputMatrixToRow(t.input),i[0],r[0]);a.push(o);for(var u=1,s=e.length;u1&&void 0!==arguments[1]?arguments[1]:null,r=this.runInput(t);return this.runBackpropagate(t),this.step(e),r}},{key:"runInput",value:function(t){this.runs++;for(var e=this.model,r=t.length,n=0,a=0,i=void 0;e.equations.length<=t.length+1;)this.bindEquation();for(var o=-1,u=t.length;o0;)n[e].runBackpropagate(t[e-1]+1),e--;n[0].runBackpropagate(0)}},{key:"step",value:function(){for(var t=(arguments.length>0&&void 0!==arguments[0]&&arguments[0],this.learningRate),e=this.regc,r=this.clipval,n=this.model,a=0,i=0,o=n.allMatrices,u=0;ur&&(f=r,a++),f<-r&&(f=-r,a++),i++,l[d]=c+-t*f/Math.sqrt(p[d]+this.smoothEps)-e*c}}this.ratioClipped=a/i}},{key:"run",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;if(!this.isRunnable)return null;for(var a=this.formatDataIn(t),i=this.model,o=[],u=0;i.equations.length=e)break;o.push(m)}return this.formatDataOut(a,o.slice(a.length).map(function(t){return t-1}))}},{key:"train",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e=Object.assign({},this.constructor.trainDefaults,e);var r=e.iterations,n=e.errorThresh,a=!0===e.log?console.log:e.log,i=e.logPeriod,o=e.learningRate||this.learningRate,u=e.callback,s=e.callbackPeriod,l=1/0,h=void 0;for(this.hasOwnProperty("setupData")&&(t=this.setupData(t)),e.keepNetworkIntact||this.initialize(),h=0;hn;h++){for(var p=0,d=0;d-1)return"typeof prevStates["+o+"] === 'object' ? prevStates["+o+"].product : new Matrix("+t.rows+", "+t.columns+")";case i.right:if(o>-1)return"typeof prevStates["+o+"] === 'object' ? prevStates["+o+"].product : new Matrix("+t.rows+", "+t.columns+")";case i.product:return"new Matrix("+t.rows+", "+t.columns+")";default:throw Error("unknown state")}}if(t===i.product)return"states["+n+"].product";if(t===i.right)return"states["+n+"].right";if(t===i.left)return"states["+n+"].left"}}function e(t){for(var e=a.equationConnections[0],r=i[0].states,n=0,o=r.length;n= maxPredictionLength) {\n break;\n }\n\n output.push(nextIndex);\n }\n "+(null!==this.dataFormatter&&"function"==typeof this.formatDataOut?"return formatDataOut(input, output.slice(input.length).map(function(value) { return value - 1; }))":"return output.slice(input.length).map(function(value) { return value - 1; })")+";\n function Matrix(rows, columns) {\n this.rows = rows;\n this.columns = columns;\n this.weights = zeros(rows * columns);\n }\n "+(null!==this.dataFormatter&&"function"==typeof this.formatDataIn?"function formatDataIn(input, output) { "+n(this.formatDataIn.toString()).replace(/this[.]dataFormatter[\n\s]+[.]/g,"").replace(/this[.]dataFormatter[.]/g,"").replace(/this[.]dataFormatter/g,"true")+" }":"")+"\n "+(null!==this.dataFormatter&&"function"==typeof this.formatDataOut?"function formatDataOut(input, output) { "+n(this.formatDataOut.toString()).replace(/this[.]dataFormatter[\n\s]+[.]/g,"").replace(/this[.]dataFormatter[.]/g,"").replace(/this[.]dataFormatter/g,"true")+" }":"")+"\n "+_zeros2.default.toString()+"\n "+_softmax2.default.toString().replace("_2.default","Matrix")+"\n "+_random.randomF.toString()+"\n "+_sampleI2.default.toString()+"\n "+_maxI2.default.toString();return new Function("rawInput","maxPredictionLength","isSampleI","temperature",g)}},{key:"isRunnable",get:function(){return 0!==this.model.equations.length||(console.error("No equations bound, did you run train()?"),!1)}}]),t}();exports.default=RNN,RNN.defaults={inputSize:20,inputRange:20,hiddenSizes:[20,20],outputSize:20,learningRate:.01,decayRate:.999,smoothEps:1e-8,regc:1e-6,clipval:5,json:null,setupData:function(t){if(!("string"==typeof t[0]||Array.isArray(t[0])||t[0].hasOwnProperty("input")&&t[0].hasOwnProperty("output")))return t;var e=[],r=[];if("string"==typeof t[0]||Array.isArray(t[0])){if(null===this.dataFormatter){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:null;return null!==this.dataFormatter?this.dataFormatter.indexTable.hasOwnProperty("stop-input")?this.dataFormatter.toIndexesInputOutput(t,e):this.dataFormatter.toIndexes(t):t},formatDataOut:function(t,e){return null!==this.dataFormatter?this.dataFormatter.toCharacters(e).join(""):e},dataFormatter:null},RNN.trainDefaults={iterations:2e4,errorThresh:.005,log:!1,logPeriod:10,learningRate:.3,callback:null,callbackPeriod:10,keepNetworkIntact:!1}; },{"../utilities/data-formatter":37,"../utilities/random":42,"../utilities/zeros":46,"./matrix":16,"./matrix/copy":14,"./matrix/equation":15,"./matrix/max-i":17,"./matrix/random-matrix":23,"./matrix/sample-i":28,"./matrix/softmax":31}],36:[function(require,module,exports){ "use strict";function _interopRequireDefault(t){return t&&t.__esModule?t:{default:t}}function _toConsumableArray(t){if(Array.isArray(t)){for(var e=0,r=Array(t.length);ethis.errorThresh){if("function"==typeof this.floodCallback)return this.floodCallback()}else if("function"==typeof this.doneTrainingCallback)return this.doneTrainingCallback({error:n,iterations:this.i})}}]),e}(_stream.Writable);exports.default=TrainStream; @@ -276,7 +276,7 @@ function EventEmitter(){this._events=this._events||{},this._maxListeners=this._m "use strict";function removeFnNoise(n){return/^function /.test(n)&&(n=n.substring(9)),n.replace(/[_]typeof/g,"typeof")}function removeNoise(n){return n.replace(/[_]typeof/g,"typeof")}var utils=require("../../core/utils"),kernelRunShortcut=require("../kernel-run-shortcut");module.exports=function(n,t){return"() => {\n "+kernelRunShortcut.toString()+";\n const utils = {\n allPropertiesOf: "+removeNoise(utils.allPropertiesOf.toString())+",\n clone: "+removeNoise(utils.clone.toString())+",\n checkOutput: "+removeNoise(utils.checkOutput.toString())+"\n };\n const Utils = utils;\n class "+(t||"Kernel")+" {\n constructor() { \n this.argumentsLength = 0;\n this._canvas = null;\n this._webGl = null;\n this.built = false;\n this.program = null;\n this.paramNames = "+JSON.stringify(n.paramNames)+";\n this.paramTypes = "+JSON.stringify(n.paramTypes)+";\n this.texSize = "+JSON.stringify(n.texSize)+";\n this.output = "+JSON.stringify(n.output)+";\n this._kernelString = `"+n._kernelString+"`;\n this.output = "+JSON.stringify(n.output)+";\n\t\t this.run = function() {\n this.run = null;\n this.build();\n return this.run.apply(this, arguments);\n }.bind(this);\n this.thread = {\n x: 0,\n y: 0,\n z: 0\n };\n }\n setCanvas(canvas) { this._canvas = canvas; return this; }\n setWebGl(webGl) { this._webGl = webGl; return this; }\n "+removeFnNoise(n.build.toString())+"\n "+removeFnNoise(n.setupParams.toString())+"\n run () { "+n.kernelString+" }\n getKernelString() { return this._kernelString; }\n "+removeFnNoise(n.validateOptions.toString())+"\n };\n return kernelRunShortcut(new Kernel());\n };"}; },{"../../core/utils":84,"../kernel-run-shortcut":61}],56:[function(require,module,exports){ -"use strict";function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var _createClass=function(){function t(t,e){for(var n=0;n1?l=l.filter(function(t){return/^function/.test(t)?t:(o=t,!1)}):o=l.shift(),this._kernelString="\n\t\tvar LOOP_MAX = "+this._getLoopMaxString()+";\n\t\tvar _this = this;\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" var "+t+" = null;\n"}).join(""))+"\n return function ("+this.paramNames.map(function(t){return"user_"+t}).join(", ")+") {\n "+this._processInputs()+"\n var ret = new Array("+n[2]+");\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+"Z = new Array("+n[2]+");\n"}).join(""))+"\n for (this.thread.z = 0; this.thread.z < "+n[2]+"; this.thread.z++) {\n ret[this.thread.z] = new Array("+n[1]+");\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+"Z[this.thread.z] = new Array("+n[1]+");\n"}).join(""))+"\n for (this.thread.y = 0; this.thread.y < "+n[1]+"; this.thread.y++) {\n ret[this.thread.z][this.thread.y] = new Array("+n[0]+");\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+"Z[this.thread.z][this.thread.y] = new Array("+n[0]+");\n"}).join(""))+"\n for (this.thread.x = 0; this.thread.x < "+n[0]+"; this.thread.x++) {\n var kernelResult;\n "+o+"\n ret[this.thread.z][this.thread.y][this.thread.x] = kernelResult;\n"+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+"Z[this.thread.z][this.thread.y][this.thread.x] = "+t+";\n"}).join(""))+"\n }\n }\n }\n \n if (this.graphical) {\n this._imageData.data.set(this._colorData);\n this._canvasCtx.putImageData(this._imageData, 0, 0);\n return;\n }\n \n if (this.output.length === 1) {\n ret = ret[0][0];\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+" = "+t+"Z[0][0];\n"}).join(""))+"\n \n } else if (this.output.length === 2) {\n ret = ret[0];\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+" = "+t+"Z[0];\n"}).join(""))+"\n } else {\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+" = "+t+"Z;\n"}).join(""))+"\n }\n \n "+(null===this.subKernelOutputVariableNames?"return ret;\n":null!==this.subKernels?"var result = [\n "+this.subKernelOutputVariableNames.map(function(t){return""+t}).join(",\n")+"\n ];\n result.result = ret;\n return result;\n":"return {\n result: ret,\n "+Object.keys(this.subKernelProperties).map(function(e,n){return e+": "+t.subKernelOutputVariableNames[n]}).join(",\n")+"\n };")+"\n "+(l.length>0?l.join("\n"):"")+"\n }.bind(this);"}},{key:"toString",value:function(){return kernelString(this)}},{key:"_getLoopMaxString",value:function(){return this.loopMaxIterations?" "+parseInt(this.loopMaxIterations)+";\n":" 1000;\n"}},{key:"_processInputs",value:function(){for(var t=[],e=0;e=0;s--){n[s]=new Array(t.width);for(var a=0;a1?l=l.filter(function(t){return/^function/.test(t)?t:(o=t,!1)}):o=l.shift(),this._kernelString="\n\t\tvar LOOP_MAX = "+this._getLoopMaxString()+";\n\t\tvar _this = this;\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" var "+t+" = null;\n"}).join(""))+"\n return function ("+this.paramNames.map(function(t){return"user_"+t}).join(", ")+") {\n "+this._processInputs()+"\n var ret = new Array("+n[2]+");\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+"Z = new Array("+n[2]+");\n"}).join(""))+"\n for (this.thread.z = 0; this.thread.z < "+n[2]+"; this.thread.z++) {\n ret[this.thread.z] = new Array("+n[1]+");\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+"Z[this.thread.z] = new Array("+n[1]+");\n"}).join(""))+"\n for (this.thread.y = 0; this.thread.y < "+n[1]+"; this.thread.y++) {\n ret[this.thread.z][this.thread.y] = "+(this.floatOutput?"new Float32Array("+n[0]+")":"new Array("+n[0]+")")+";\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(e){return" "+e+"Z[this.thread.z][this.thread.y] = "+(t.floatOutput?"new Float32Array("+n[0]+")":"new Array("+n[0]+")")+";\n"}).join(""))+"\n for (this.thread.x = 0; this.thread.x < "+n[0]+"; this.thread.x++) {\n var kernelResult;\n "+o+"\n ret[this.thread.z][this.thread.y][this.thread.x] = kernelResult;\n"+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+"Z[this.thread.z][this.thread.y][this.thread.x] = "+t+";\n"}).join(""))+"\n }\n }\n }\n \n if (this.graphical) {\n this._imageData.data.set(this._colorData);\n this._canvasCtx.putImageData(this._imageData, 0, 0);\n return;\n }\n \n if (this.output.length === 1) {\n ret = ret[0][0];\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+" = "+t+"Z[0][0];\n"}).join(""))+"\n \n } else if (this.output.length === 2) {\n ret = ret[0];\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+" = "+t+"Z[0];\n"}).join(""))+"\n } else {\n "+(null===this.subKernelOutputVariableNames?"":this.subKernelOutputVariableNames.map(function(t){return" "+t+" = "+t+"Z;\n"}).join(""))+"\n }\n \n "+(null===this.subKernelOutputVariableNames?"return ret;\n":null!==this.subKernels?"var result = [\n "+this.subKernelOutputVariableNames.map(function(t){return""+t}).join(",\n")+"\n ];\n result.result = ret;\n return result;\n":"return {\n result: ret,\n "+Object.keys(this.subKernelProperties).map(function(e,n){return e+": "+t.subKernelOutputVariableNames[n]}).join(",\n")+"\n };")+"\n "+(l.length>0?l.join("\n"):"")+"\n }.bind(this);"}},{key:"toString",value:function(){return kernelString(this)}},{key:"_getLoopMaxString",value:function(){return this.loopMaxIterations?" "+parseInt(this.loopMaxIterations)+";\n":" 1000;\n"}},{key:"_processInputs",value:function(){for(var t=[],e=0;e=0;s--){n[s]=new Array(t.width);for(var a=0;a=0||t.push(n)),t}},{key:"addKernel",value:function(n,t){var e=new this.Node("kernel",n,t);return e.setAddFunction(this.addFunction.bind(this)),e.isRootKernel=!0,this.addFunctionNode(e),e}},{key:"addSubKernel",value:function(n,t){var e=new this.Node(null,n,t);return e.setAddFunction(this.addFunction.bind(this)),e.isSubKernel=!0,this.addFunctionNode(e),e}},{key:"getPrototypeString",value:function(n){return this.getPrototypes(n).join("\n")}},{key:"getPrototypes",value:function(n){return this.rootKernel.generate(),n?this.getPrototypesFromFunctionNames(this.traceFunctionCalls(n,[]).reverse()):this.getPrototypesFromFunctionNames(Object.keys(this.nodeMap))}},{key:"getStringFromFunctionNames",value:function(n){for(var t=[],e=0;e ("+r.length+","+this.paramNames.length+")";this.paramTypes=r}else if("object"===(void 0===r?"undefined":_typeof(r))){var i=Object.keys(r);if(r.hasOwnProperty("returns")&&(this.returnType=r.returns,i.splice(i.indexOf("returns"),1)),i.length>0&&i.length!==this.paramNames.length)throw"Invalid argument type array length, against function length -> ("+i.length+","+this.paramNames.length+")";this.paramTypes=this.paramNames.map(function(t){return r.hasOwnProperty(t)?r[t]:"float"})}}else this.paramTypes=[];this.returnType||(this.returnType=s||"float")}return _createClass(BaseFunctionNode,[{key:"isIdentifierConstant",value:function(t){return!!this.constants&&this.constants.hasOwnProperty(t)}},{key:"isInput",value:function(t){return"Input"===this.paramTypes[this.paramNames.indexOf(t)]}},{key:"setAddFunction",value:function(t){return this.addFunction=t,this}},{key:"pushState",value:function(t){this.states.push(t)}},{key:"popState",value:function(t){if(this.state!==t)throw new Error("Cannot popState "+t+" when in "+this.state);this.states.pop()}},{key:"isState",value:function(t){return this.state===t}},{key:"getJsFunction",value:function getJsFunction(){if(this.jsFunction)return this.jsFunction;if(this.jsFunctionString)return this.jsFunction=eval(this.jsFunctionString),this.jsFunction;throw"Missing jsFunction, and jsFunctionString parameter"}},{key:"astMemberExpressionUnroll",value:function(t){if("Identifier"===t.type)return t.name;if("ThisExpression"===t.type)return"this";if("MemberExpression"===t.type&&t.object&&t.property)return t.object.hasOwnProperty("name")&&"_"===t.object.name[0]?this.astMemberExpressionUnroll(t.property):this.astMemberExpressionUnroll(t.object)+"."+this.astMemberExpressionUnroll(t.property);if(t.hasOwnProperty("expressions")){var e=t.expressions[0];if("Literal"===e.type&&0===e.value&&2===t.expressions.length)return this.astMemberExpressionUnroll(t.expressions[1])}throw this.astErrorOutput("Unknown CallExpression_unroll",t)}},{key:"getJsAST",value:function(t){if(this.jsFunctionAST)return this.jsFunctionAST;if(null===(t=t||acorn))throw"Missing JS to AST parser";var e=t.parse("var "+this.functionName+" = "+this.jsFunctionString+";",{locations:!0});if(null===e)throw"Failed to parse JS code";var n=e.body[0].declarations[0].init;return this.jsFunctionAST=n,n}},{key:"getFunctionString",value:function(){return this.generate(),this.functionString}},{key:"setFunctionString",value:function(t){this.functionString=t}},{key:"getParamType",value:function(t){var e=this.paramNames.indexOf(t);if(-1===e)return this.declarations.hasOwnProperty(t)?this.declarations[t]:null;if(this.parent){if(this.paramTypes[e])return this.paramTypes[e];for(var n=this.parent.calledFunctionsArguments[this.functionName],r=0;r ("+r.length+","+this.paramNames.length+")";this.paramTypes=r}else if("object"===(void 0===r?"undefined":_typeof(r))){var i=Object.keys(r);if(r.hasOwnProperty("returns")&&(this.returnType=r.returns,i.splice(i.indexOf("returns"),1)),i.length>0&&i.length!==this.paramNames.length)throw"Invalid argument type array length, against function length -> ("+i.length+","+this.paramNames.length+")";this.paramTypes=this.paramNames.map(function(t){return r.hasOwnProperty(t)?r[t]:"float"})}}else this.paramTypes=[];this.returnType||(this.returnType=s||"float")}return _createClass(BaseFunctionNode,[{key:"isIdentifierConstant",value:function(t){return!!this.constants&&this.constants.hasOwnProperty(t)}},{key:"isInput",value:function(t){return"Input"===this.paramTypes[this.paramNames.indexOf(t)]}},{key:"setAddFunction",value:function(t){return this.addFunction=t,this}},{key:"pushState",value:function(t){this.states.push(t)}},{key:"popState",value:function(t){if(this.state!==t)throw new Error("Cannot popState "+t+" when in "+this.state);this.states.pop()}},{key:"isState",value:function(t){return this.state===t}},{key:"getJsFunction",value:function getJsFunction(){if(this.jsFunction)return this.jsFunction;if(this.jsFunctionString)return this.jsFunction=eval(this.jsFunctionString),this.jsFunction;throw"Missing jsFunction, and jsFunctionString parameter"}},{key:"astMemberExpressionUnroll",value:function(t){if("Identifier"===t.type)return t.name;if("ThisExpression"===t.type)return"this";if("MemberExpression"===t.type&&t.object&&t.property)return t.object.hasOwnProperty("name")&&"_"===t.object.name[0]?this.astMemberExpressionUnroll(t.property):this.astMemberExpressionUnroll(t.object)+"."+this.astMemberExpressionUnroll(t.property);if(t.hasOwnProperty("expressions")){var e=t.expressions[0];if("Literal"===e.type&&0===e.value&&2===t.expressions.length)return this.astMemberExpressionUnroll(t.expressions[1])}throw this.astErrorOutput("Unknown CallExpression_unroll",t)}},{key:"getJsAST",value:function(t){if(this.jsFunctionAST)return this.jsFunctionAST;if(null===(t=t||acorn))throw"Missing JS to AST parser";var e=t.parse("var "+this.functionName+" = "+this.jsFunctionString+";",{locations:!0});if(null===e)throw"Failed to parse JS code";var n=e.body[0].declarations[0].init;return this.jsFunctionAST=n,n}},{key:"getFunctionString",value:function(){return this.generate(),this.functionString}},{key:"setFunctionString",value:function(t){this.functionString=t}},{key:"getParamType",value:function(t){var e=this.paramNames.indexOf(t);if(-1===e)return this.declarations.hasOwnProperty(t)?this.declarations[t]:null;if(this.parent){if(this.paramTypes[e])return this.paramTypes[e];for(var n=this.parent.calledFunctionsArguments[this.functionName],r=0;r0&&t.push(", ");var i=this.getParamType(r);switch(i){case"Texture":case"Input":case"Array":t.push("sampler2D");break;default:t.push("float")}t.push(" "),t.push("user_"),t.push(r)}t.push(") {\n");for(var n=0;n1){for(var n=null,a=0;a0&&t.push(",");var i=[];this.astGeneric(r,i),"getImage2D("===i[2]||"getImage3D("===i[2]?(0===s&&t.push("vec4 "),this.declarations[r.id.name]="vec4"):(0===s&&t.push("float "),this.declarations[r.id.name]="float"),t.push.apply(t,i)}return t.push(";"),t}},{key:"astVariableDeclarator",value:function(e,t){return this.astGeneric(e.id,t),null!==e.init&&(t.push("="),this.astGeneric(e.init,t)),t}},{key:"astIfStatement",value:function(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}},{key:"astBreakStatement",value:function(e,t){return t.push("break;\n"),t}},{key:"astContinueStatement",value:function(e,t){return t.push("continue;\n"),t}},{key:"astLogicalExpression",value:function(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}},{key:"astUpdateExpression",value:function(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}},{key:"astUnaryExpression",value:function(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}},{key:"astThisExpression",value:function(e,t){return t.push("this"),t}},{key:"astMemberExpression",value:function(e,t){if(debugLog("[in] astMemberExpression "+e.object.type),e.computed)if("Identifier"===e.object.type){var s=e.object.name,r=this.functionName||"kernel",i=!1;if(this.paramNames){var n=this.paramNames.indexOf(s);n>=0&&"float"===this.paramTypes[n]&&(i=!0)}if(debugLog("- astMemberExpression "+s+" "+r),i)this.astGeneric(e.object,t),t.push("[int("),this.astGeneric(e.property,t),t.push(")]");else{var a=this.isState("in-get-call-parameters"),u=this.isState("multi-member-expression");switch(u&&this.popState("multi-member-expression"),this.pushState("not-in-get-call-parameters"),this.getParamType(e.object.name)){case"vec4":this.astGeneric(e.object,t),t.push("["),t.push(e.property.raw),t.push("]"),u&&this.popState("not-in-get-call-parameters");break;case"HTMLImageArray":t.push("getImage3D("),this.astGeneric(e.object,t),t.push(", ivec2("),this.astGeneric(e.object,t),t.push("Size[0],"),this.astGeneric(e.object,t),t.push("Size[1]), ivec3("),this.astGeneric(e.object,t),t.push("Dim[0],"),this.astGeneric(e.object,t),t.push("Dim[1],"),this.astGeneric(e.object,t),t.push("Dim[2]"),t.push("), "),this.popState("not-in-get-call-parameters"),this.pushState("in-get-call-parameters"),this.astGeneric(e.property,t),u||this.popState("in-get-call-parameters"),t.push(")");break;case"HTMLImage":t.push("getImage2D("),this.astGeneric(e.object,t),t.push(", ivec2("),this.astGeneric(e.object,t),t.push("Size[0],"),this.astGeneric(e.object,t),t.push("Size[1]), ivec3("),this.astGeneric(e.object,t),t.push("Dim[0],"),this.astGeneric(e.object,t),t.push("Dim[1],"),this.astGeneric(e.object,t),t.push("Dim[2]"),t.push("), "),this.popState("not-in-get-call-parameters"),this.pushState("in-get-call-parameters"),this.astGeneric(e.property,t),u||this.popState("in-get-call-parameters"),t.push(")");break;default:a&&t.push("int("),t.push("get("),this.astGeneric(e.object,t),t.push(", ivec2("),this.astGeneric(e.object,t),t.push("Size[0],"),this.astGeneric(e.object,t),t.push("Size[1]), ivec3("),this.astGeneric(e.object,t),t.push("Dim[0],"),this.astGeneric(e.object,t),t.push("Dim[1],"),this.astGeneric(e.object,t),t.push("Dim[2]"),t.push("), "),this.popState("not-in-get-call-parameters"),this.pushState("in-get-call-parameters"),this.astGeneric(e.property,t),u||this.popState("in-get-call-parameters"),t.push(")"),a&&t.push(")")}}}else{debugLog("- astMemberExpression obj:",e.object);var h=(this.states.length,this.isState("in-get-call-parameters"));h||this.pushState("multi-member-expression"),this.astGeneric(e.object,t),this.isState("multi-member-expression")&&this.popState("multi-member-expression");var o=!h&&this.isState("in-get-call-parameters"),p=t.pop();t.push(","),debugLog("- astMemberExpression prop:",e.property);var c=this.isState("should-pop-in-get-call-parameters");c&&this.popState("should-pop-in-get-call-parameters"),this.astGeneric(e.property,t),t.push(p),o?this.pushState("should-pop-in-get-call-parameters"):c&&this.popState("in-get-call-parameters")}else{var l=this.astMemberExpressionUnroll(e),f=l.toLowerCase();debugLog("- astMemberExpression unrolled:",l),0===l.indexOf(constantsPrefix)&&(l="constants_"+l.slice(constantsPrefix.length));var m=!this.isState("in-get-call-parameters");switch(f){case"this.thread.x":m&&t.push("float("),t.push("threadId.x"),m&&t.push(")");break;case"this.thread.y":m&&t.push("float("),t.push("threadId.y"),m&&t.push(")");break;case"this.thread.z":m&&t.push("float("),t.push("threadId.z"),m&&t.push(")");break;case"this.output.x":t.push(this.output[0]+".0");break;case"this.output.y":t.push(this.output[1]+".0");break;case"this.output.z":t.push(this.output[2]+".0");break;default:t.push(l)}}return debugLog("[out] astMemberExpression "+e.object.type),t}},{key:"astSequenceExpression",value:function(e,t){for(var s=0;s0&&t.push(","),this.astGeneric(e.expressions,t);return t}},{key:"astCallExpression",value:function(e,t){if(e.callee){var s=this.astMemberExpressionUnroll(e.callee);0===s.indexOf(jsMathPrefix)&&(s=s.slice(jsMathPrefix.length)),0===s.indexOf(localPrefix)&&(s=s.slice(localPrefix.length)),"atan2"===s&&(s="atan"),this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.hasOwnProperty("funcName")||(this.calledFunctionsArguments[s]=[]);var r=[];this.calledFunctionsArguments[s].push(r),t.push(s),t.push("(");for(var i=0;i0&&t.push(", "),this.astGeneric(n,t),"Identifier"===n.type){var a=this.paramNames.indexOf(n.name);-1===a?r.push(null):r.push({name:n.name,type:this.paramTypes[a]})}else r.push(null)}return t.push(")"),t}throw this.astErrorOutput("Unknown CallExpression",e)}},{key:"astArrayExpression",value:function(e,t){var s=e.elements.length;t.push("float["+s+"](");for(var r=0;r0&&t.push(", ");var i=e.elements[r];this.astGeneric(i,t)}return t.push(")"),t}},{key:"getFunctionPrototypeString",value:function(){return this.webGlFunctionPrototypeString?this.webGlFunctionPrototypeString:this.webGlFunctionPrototypeString=this.generate()}},{key:"build",value:function(){return this.getFunctionPrototypeString().length>0}}],[{key:"astFunctionPrototype",value:function(e,t){if(this.isRootKernel||this.isSubKernel)return t;t.push(this.returnType),t.push(" "),t.push(this.functionName),t.push("(");for(var s=0;s0&&t.push(", "),t.push(this.paramTypes[s]),t.push(" "),t.push("user_"),t.push(this.paramNames[s]);return t.push(");\n"),t}}]),t}(FunctionNodeBase); +"use strict";function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function isIdentifierKernelParam(e,t,s){return-1!==s.paramNames.indexOf(e)}function ensureIndentifierType(e,t,s,i){var r=s.loc.start;if(!isIdentifierKernelParam(e)&&"float"!==t)throw new Error("Error unexpected identifier "+e+" on line "+r.line);if(i.paramTypes[i.paramNames.indexOf(e)]!==t)throw new Error("Error unexpected identifier "+e+" on line "+r.line)}function webGlRegexOptimize(e){return e.replace(DECODE32_ENCODE32,"((").replace(ENCODE32_DECODE32,"((")}var _createClass=function(){function e(e,t){for(var s=0;s0&&t.push(", ");var r=this.getParamType(i);switch(r){case"Texture":case"Input":case"Array":t.push("sampler2D");break;default:t.push("float")}t.push(" "),t.push("user_"),t.push(i)}t.push(") {\n");for(var n=0;n1){for(var n=null,a=0;a0&&t.push(",");var r=[];this.astGeneric(i,r),"getImage2D("===r[2]||"getImage3D("===r[2]?(0===s&&t.push("vec4 "),this.declarations[i.id.name]="vec4"):(0===s&&t.push("float "),this.declarations[i.id.name]="float"),t.push.apply(t,r)}return t.push(";"),t}},{key:"astVariableDeclarator",value:function(e,t){return this.astGeneric(e.id,t),null!==e.init&&(t.push("="),this.astGeneric(e.init,t)),t}},{key:"astIfStatement",value:function(e,t){return t.push("if ("),this.astGeneric(e.test,t),t.push(")"),"BlockStatement"===e.consequent.type?this.astGeneric(e.consequent,t):(t.push(" {\n"),this.astGeneric(e.consequent,t),t.push("\n}\n")),e.alternate&&(t.push("else "),"BlockStatement"===e.alternate.type?this.astGeneric(e.alternate,t):(t.push(" {\n"),this.astGeneric(e.alternate,t),t.push("\n}\n"))),t}},{key:"astBreakStatement",value:function(e,t){return t.push("break;\n"),t}},{key:"astContinueStatement",value:function(e,t){return t.push("continue;\n"),t}},{key:"astLogicalExpression",value:function(e,t){return t.push("("),this.astGeneric(e.left,t),t.push(e.operator),this.astGeneric(e.right,t),t.push(")"),t}},{key:"astUpdateExpression",value:function(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}},{key:"astUnaryExpression",value:function(e,t){return e.prefix?(t.push(e.operator),this.astGeneric(e.argument,t)):(this.astGeneric(e.argument,t),t.push(e.operator)),t}},{key:"astThisExpression",value:function(e,t){return t.push("this"),t}},{key:"astMemberExpression",value:function(e,t){if(debugLog("[in] astMemberExpression "+e.object.type),e.computed)if("Identifier"===e.object.type){var s=e.object.name,i=this.functionName||"kernel",r=!1;if(this.paramNames){var n=this.paramNames.indexOf(s);n>=0&&"float"===this.paramTypes[n]&&(r=!0)}if(debugLog("- astMemberExpression "+s+" "+i),r)this.astGeneric(e.object,t),t.push("[int("),this.astGeneric(e.property,t),t.push(")]");else{var a=this.isState("in-get-call-parameters"),u=this.isState("multi-member-expression");switch(u&&this.popState("multi-member-expression"),this.pushState("not-in-get-call-parameters"),this.getParamType(e.object.name)){case"vec4":this.astGeneric(e.object,t),t.push("["),t.push(e.property.raw),t.push("]"),u&&this.popState("not-in-get-call-parameters");break;case"HTMLImageArray":t.push("getImage3D("),this.astGeneric(e.object,t),t.push(", ivec2("),this.astGeneric(e.object,t),t.push("Size[0],"),this.astGeneric(e.object,t),t.push("Size[1]), ivec3("),this.astGeneric(e.object,t),t.push("Dim[0],"),this.astGeneric(e.object,t),t.push("Dim[1],"),this.astGeneric(e.object,t),t.push("Dim[2]"),t.push("), "),this.popState("not-in-get-call-parameters"),this.pushState("in-get-call-parameters"),this.astGeneric(e.property,t),u||this.popState("in-get-call-parameters"),t.push(")");break;case"HTMLImage":t.push("getImage2D("),this.astGeneric(e.object,t),t.push(", ivec2("),this.astGeneric(e.object,t),t.push("Size[0],"),this.astGeneric(e.object,t),t.push("Size[1]), ivec3("),this.astGeneric(e.object,t),t.push("Dim[0],"),this.astGeneric(e.object,t),t.push("Dim[1],"),this.astGeneric(e.object,t),t.push("Dim[2]"),t.push("), "),this.popState("not-in-get-call-parameters"),this.pushState("in-get-call-parameters"),this.astGeneric(e.property,t),u||this.popState("in-get-call-parameters"),t.push(")");break;default:a&&t.push("int("),t.push("get("),this.astGeneric(e.object,t),t.push(", ivec2("),this.astGeneric(e.object,t),t.push("Size[0],"),this.astGeneric(e.object,t),t.push("Size[1]), ivec3("),this.astGeneric(e.object,t),t.push("Dim[0],"),this.astGeneric(e.object,t),t.push("Dim[1],"),this.astGeneric(e.object,t),t.push("Dim[2]"),t.push("), "),this.astGeneric(e.object,t),t.push("BitRatio"),t.push(", "),this.popState("not-in-get-call-parameters"),this.pushState("in-get-call-parameters"),this.astGeneric(e.property,t),u||this.popState("in-get-call-parameters"),t.push(")"),a&&t.push(")")}}}else{debugLog("- astMemberExpression obj:",e.object);var h=(this.states.length,this.isState("in-get-call-parameters"));h||this.pushState("multi-member-expression"),this.astGeneric(e.object,t),this.isState("multi-member-expression")&&this.popState("multi-member-expression");var o=!h&&this.isState("in-get-call-parameters"),p=t.pop();t.push(","),debugLog("- astMemberExpression prop:",e.property);var c=this.isState("should-pop-in-get-call-parameters");c&&this.popState("should-pop-in-get-call-parameters"),this.astGeneric(e.property,t),t.push(p),o?this.pushState("should-pop-in-get-call-parameters"):c&&this.popState("in-get-call-parameters")}else{var l=this.astMemberExpressionUnroll(e),f=l.toLowerCase();debugLog("- astMemberExpression unrolled:",l),0===l.indexOf(constantsPrefix)&&(l="constants_"+l.slice(constantsPrefix.length));var m=!this.isState("in-get-call-parameters");switch(f){case"this.thread.x":m&&t.push("float("),t.push("threadId.x"),m&&t.push(")");break;case"this.thread.y":m&&t.push("float("),t.push("threadId.y"),m&&t.push(")");break;case"this.thread.z":m&&t.push("float("),t.push("threadId.z"),m&&t.push(")");break;case"this.output.x":t.push(this.output[0]+".0");break;case"this.output.y":t.push(this.output[1]+".0");break;case"this.output.z":t.push(this.output[2]+".0");break;default:t.push(l)}}return debugLog("[out] astMemberExpression "+e.object.type),t}},{key:"astSequenceExpression",value:function(e,t){for(var s=0;s0&&t.push(","),this.astGeneric(e.expressions,t);return t}},{key:"astCallExpression",value:function(e,t){if(e.callee){var s=this.astMemberExpressionUnroll(e.callee);0===s.indexOf(jsMathPrefix)&&(s=s.slice(jsMathPrefix.length)),0===s.indexOf(localPrefix)&&(s=s.slice(localPrefix.length)),"atan2"===s&&(s="atan"),this.calledFunctions.indexOf(s)<0&&this.calledFunctions.push(s),this.hasOwnProperty("funcName")||(this.calledFunctionsArguments[s]=[]);var i=[];this.calledFunctionsArguments[s].push(i),t.push(s),t.push("(");for(var r=0;r0&&t.push(", "),this.astGeneric(n,t),"Identifier"===n.type){var a=this.paramNames.indexOf(n.name);-1===a?i.push(null):i.push({name:n.name,type:this.paramTypes[a]})}else i.push(null)}return t.push(")"),t}throw this.astErrorOutput("Unknown CallExpression",e)}},{key:"astArrayExpression",value:function(e,t){var s=e.elements.length;t.push("float["+s+"](");for(var i=0;i0&&t.push(", ");var r=e.elements[i];this.astGeneric(r,t)}return t.push(")"),t}},{key:"getFunctionPrototypeString",value:function(){return this.webGlFunctionPrototypeString?this.webGlFunctionPrototypeString:this.webGlFunctionPrototypeString=this.generate()}},{key:"build",value:function(){return this.getFunctionPrototypeString().length>0}}],[{key:"astFunctionPrototype",value:function(e,t){if(this.isRootKernel||this.isSubKernel)return t;t.push(this.returnType),t.push(" "),t.push(this.functionName),t.push("(");for(var s=0;s0&&t.push(", "),t.push(this.paramTypes[s]),t.push(" "),t.push("user_"),t.push(this.paramNames[s]);return t.push(");\n"),t}}]),t}(FunctionNodeBase); },{"../../core/utils":84,"../function-node-base":59}],65:[function(require,module,exports){ "use strict";function removeFnNoise(t){return/^function /.test(t)&&(t=t.substring(9)),t.replace(/[_]typeof/g,"typeof")}function removeNoise(t){return t.replace(/[_]typeof/g,"typeof")}var utils=require("../../core/utils"),kernelRunShortcut=require("../kernel-run-shortcut");module.exports=function(t,e){return"() => {\n "+kernelRunShortcut.toString()+";\n const utils = {\n allPropertiesOf: "+removeNoise(utils.allPropertiesOf.toString())+",\n clone: "+removeNoise(utils.clone.toString())+",\n splitArray: "+removeNoise(utils.splitArray.toString())+",\n getArgumentType: "+removeNoise(utils.getArgumentType.toString())+",\n getDimensions: "+removeNoise(utils.getDimensions.toString())+",\n dimToTexSize: "+removeNoise(utils.dimToTexSize.toString())+",\n flattenTo: "+removeNoise(utils.flattenTo.toString())+",\n flatten2dArrayTo: "+removeNoise(utils.flatten2dArrayTo.toString())+",\n flatten3dArrayTo: "+removeNoise(utils.flatten3dArrayTo.toString())+",\n systemEndianness: '"+removeNoise(utils.systemEndianness())+"',\n initWebGl: "+removeNoise(utils.initWebGl.toString())+",\n isArray: "+removeNoise(utils.isArray.toString())+",\n checkOutput: "+removeNoise(utils.checkOutput.toString())+"\n };\n const Utils = utils;\n const canvases = [];\n const maxTexSizes = {};\n class "+(e||"Kernel")+" {\n constructor() {\n this.maxTexSize = null;\n this.argumentsLength = 0;\n this._canvas = null;\n this._webGl = null;\n this.built = false;\n this.program = null;\n this.paramNames = "+JSON.stringify(t.paramNames)+";\n this.paramTypes = "+JSON.stringify(t.paramTypes)+";\n this.texSize = "+JSON.stringify(t.texSize)+";\n this.output = "+JSON.stringify(t.output)+";\n this.compiledFragShaderString = `"+t.compiledFragShaderString+"`;\n\t\t this.compiledVertShaderString = `"+t.compiledVertShaderString+"`;\n\t\t this.programUniformLocationCache = {};\n\t\t this.textureCache = {};\n\t\t this.subKernelOutputTextures = null;\n\t\t this.subKernelOutputVariableNames = null;\n\t\t this.uniform1fCache = {};\n\t\t this.uniform1iCache = {};\n\t\t this.uniform2fCache = {};\n\t\t this.uniform2fvCache = {};\n\t\t this.uniform2ivCache = {};\n\t\t this.uniform3fvCache = {};\n\t\t this.uniform3ivCache = {};\n }\n "+removeFnNoise(t._getFragShaderString.toString())+"\n "+removeFnNoise(t._getVertShaderString.toString())+"\n validateOptions() {}\n setupParams() {}\n setCanvas(canvas) { this._canvas = canvas; return this; }\n setWebGl(webGl) { this._webGl = webGl; return this; }\n "+removeFnNoise(t.getUniformLocation.toString())+"\n "+removeFnNoise(t.setupParams.toString())+"\n "+removeFnNoise(t.build.toString())+"\n\t\t "+removeFnNoise(t.run.toString())+"\n\t\t "+removeFnNoise(t._addArgument.toString())+"\n\t\t "+removeFnNoise(t.getArgumentTexture.toString())+"\n\t\t "+removeFnNoise(t.getTextureCache.toString())+"\n\t\t "+removeFnNoise(t.getOutputTexture.toString())+"\n\t\t "+removeFnNoise(t.renderOutput.toString())+"\n\t\t "+removeFnNoise(t.updateMaxTexSize.toString())+"\n\t\t "+removeFnNoise(t._setupOutputTexture.toString())+"\n\t\t "+removeFnNoise(t.detachTextureCache.toString())+"\n\t\t "+removeFnNoise(t.setUniform1f.toString())+"\n\t\t "+removeFnNoise(t.setUniform1i.toString())+"\n\t\t "+removeFnNoise(t.setUniform2f.toString())+"\n\t\t "+removeFnNoise(t.setUniform2fv.toString())+"\n\t\t "+removeFnNoise(t.setUniform2iv.toString())+"\n\t\t "+removeFnNoise(t.setUniform3fv.toString())+" \n\t\t "+removeFnNoise(t.setUniform3iv.toString())+" \n };\n return kernelRunShortcut(new Kernel());\n };"}; },{"../../core/utils":84,"../kernel-run-shortcut":61}],66:[function(require,module,exports){ -"use strict";function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var _createClass=function(){function e(e,t){for(var r=0;r0&&this._setupSubOutputTextures(this.subKernelOutputVariableNames.length))}},{key:"run",value:function(){null===this.program&&this.build.apply(this,arguments);var e=this.paramNames,t=this.paramTypes,r=this.texSize,i=this._webGl;i.useProgram(this.program),i.scissor(0,0,r[0],r[1]),this.hardcodeConstants||(this.setUniform3iv("uOutputDim",this.threadDim),this.setUniform2iv("uTexSize",r)),this.setUniform2f("ratio",r[0]/this.maxTexSize[0],r[1]/this.maxTexSize[1]),this.argumentsLength=0;for(var n=0;n0?e.join(";\n")+";\n":"\n"}},{key:"_replaceArtifacts",value:function(e,t){return e.replace(/[ ]*__([A-Z]+[0-9]*([_]?[A-Z])*)__;\n/g,function(e,r){if(t.hasOwnProperty(r))return t[r];throw"unhandled artifact "+r})}},{key:"_addKernels",value:function(){var e=this,t=this.functionBuilder,r=this._webGl;if(t.addFunctions(this.functions,{constants:this.constants,output:this.output}),t.addNativeFunctions(this.nativeFunctions),t.addKernel(this.fnString,{prototypeOnly:!1,constants:this.constants,output:this.output,debug:this.debug,loopMaxIterations:this.loopMaxIterations,paramNames:this.paramNames,paramTypes:this.paramTypes}),null!==this.subKernels){if(!(this.drawBuffers=r.getExtension("WEBGL_draw_buffers")))throw new Error("could not instantiate draw buffers extension");this.subKernelOutputVariableNames=[],this.subKernels.forEach(function(t){return e._addSubKernel(t)})}else if(null!==this.subKernelProperties){var i=this.drawBuffers=r.getExtension("WEBGL_draw_buffers");if(!i)throw new Error("could not instantiate draw buffers extension");this.subKernelOutputVariableNames=[],Object.keys(this.subKernelProperties).forEach(function(t){return e._addSubKernel(e.subKernelProperties[t])})}}},{key:"_addSubKernel",value:function(e){this.functionBuilder.addSubKernel(e,{prototypeOnly:!1,constants:this.constants,output:this.output,debug:this.debug,loopMaxIterations:this.loopMaxIterations}),this.subKernelOutputVariableNames.push(e.name+"Result")}},{key:"_getFragShaderString",value:function(e){return null!==this.compiledFragShaderString?this.compiledFragShaderString:this.compiledFragShaderString=this._replaceArtifacts(this.constructor.fragShaderString,this._getFragShaderArtifactMap(e))}},{key:"_getVertShaderString",value:function(e){return null!==this.compiledVertShaderString?this.compiledVertShaderString:this.compiledVertShaderString=this.constructor.vertShaderString}},{key:"toString",value:function(){return kernelString(this)}},{key:"addFunction",value:function(e){this.functionBuilder.addFunction(null,e)}}]),t}(KernelBase); +"use strict";function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var _get=function e(t,r,i){null===t&&(t=Function.prototype);var n=Object.getOwnPropertyDescriptor(t,r);if(void 0===n){var a=Object.getPrototypeOf(t);return null===a?void 0:e(a,r,i)}if("value"in n)return n.value;var s=n.get;if(void 0!==s)return s.call(i)},_createClass=function(){function e(e,t){for(var r=0;r0&&this._setupSubOutputTextures(this.subKernelOutputVariableNames.length))}},{key:"run",value:function(){null===this.program&&this.build.apply(this,arguments);var e=this.paramNames,t=this.paramTypes,r=this.texSize,i=this._webGl;i.useProgram(this.program),i.scissor(0,0,r[0],r[1]),this.hardcodeConstants||(this.setUniform3iv("uOutputDim",this.threadDim),this.setUniform2iv("uTexSize",r)),this.setUniform2f("ratio",r[0]/this.maxTexSize[0],r[1]/this.maxTexSize[1]),this.argumentsLength=0;for(var n=0;n0?e.join(";\n")+";\n":"\n"}},{key:"_replaceArtifacts",value:function(e,t){return e.replace(/[ ]*__([A-Z]+[0-9]*([_]?[A-Z])*)__;\n/g,function(e,r){if(t.hasOwnProperty(r))return t[r];throw"unhandled artifact "+r})}},{key:"_addKernels",value:function(){var e=this,t=this.functionBuilder,r=this._webGl;if(t.addFunctions(this.functions,{constants:this.constants,output:this.output}),t.addNativeFunctions(this.nativeFunctions),t.addKernel(this.fnString,{prototypeOnly:!1,constants:this.constants,output:this.output,debug:this.debug,loopMaxIterations:this.loopMaxIterations,paramNames:this.paramNames,paramTypes:this.paramTypes,fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy}),null!==this.subKernels){if(!(this.drawBuffers=r.getExtension("WEBGL_draw_buffers")))throw new Error("could not instantiate draw buffers extension");this.subKernelOutputVariableNames=[],this.subKernels.forEach(function(t){return e._addSubKernel(t)})}else if(null!==this.subKernelProperties){var i=this.drawBuffers=r.getExtension("WEBGL_draw_buffers");if(!i)throw new Error("could not instantiate draw buffers extension");this.subKernelOutputVariableNames=[],Object.keys(this.subKernelProperties).forEach(function(t){return e._addSubKernel(e.subKernelProperties[t])})}}},{key:"_addSubKernel",value:function(e){this.functionBuilder.addSubKernel(e,{prototypeOnly:!1,constants:this.constants,output:this.output,debug:this.debug,loopMaxIterations:this.loopMaxIterations,fixIntegerDivisionAccuracy:this.fixIntegerDivisionAccuracy}),this.subKernelOutputVariableNames.push(e.name+"Result")}},{key:"_getFragShaderString",value:function(e){return null!==this.compiledFragShaderString?this.compiledFragShaderString:this.compiledFragShaderString=this._replaceArtifacts(this.constructor.fragShaderString,this._getFragShaderArtifactMap(e))}},{key:"_getVertShaderString",value:function(e){return null!==this.compiledVertShaderString?this.compiledVertShaderString:this.compiledVertShaderString=this.constructor.vertShaderString}},{key:"toString",value:function(){return kernelString(this)}},{key:"addFunction",value:function(e){this.functionBuilder.addFunction(null,e)}},{key:"destroy",value:function(e){_get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"destroy",this).call(this),this.outputTexture&&this._webGl.deleteTexture(this.outputTexture),this.buffer&&this._webGl.deleteBuffer(this.buffer),this.framebuffer&&this._webGl.deleteFramebuffer(this.framebuffer),this.vertShader&&this._webGl.deleteShader(this.vertShader),this.fragShader&&this._webGl.deleteShader(this.fragShader),this.program&&this._webGl.deleteProgram(this.program);for(var r=Object.keys(this.textureCache),i=0;i=0&&(canvases[s]=null,maxTexSizes[s]=null)}delete this._webGl}}]),t}(KernelBase); },{"../../core/texture":82,"../../core/utils":84,"../kernel-base":60,"./kernel-string":65,"./shader-frag":68,"./shader-vert":69}],67:[function(require,module,exports){ "use strict";function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(e,r){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!r||"object"!=typeof r&&"function"!=typeof r?e:r}function _inherits(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function, not "+typeof r);e.prototype=Object.create(r&&r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),r&&(Object.setPrototypeOf?Object.setPrototypeOf(e,r):e.__proto__=r)}var _createClass=function(){function e(e,r){for(var t=0;t0&&t.push(", ");var n=this.getParamType(s);switch(n){case"Texture":case"Input":case"Array":case"HTMLImage":t.push("sampler2D");break;default:t.push("float")}t.push(" "),t.push("user_"),t.push(s)}t.push(") {\n");for(var i=0;i1&&o*i===r)return[o,i];for(var l=Math.sqrt(r),a=Math.ceil(l),s=Math.floor(l);a*s>r;)a--,s=Math.ceil(r/a);return o=s,i=Math.ceil(r/o),[o,i]}},{key:"getDimensions",value:function(e,n){var r=void 0;if(t.isArray(e)){for(var o=[],i=e;t.isArray(i);)o.push(i.length),i=i[0];r=o.reverse()}else if(e instanceof Texture)r=e.output;else{if(!(e instanceof Input))throw"Unknown dimensions of "+e;r=e.size}if(n)for(r=t.clone(r);r.length<3;)r.push(1);return new Int32Array(r)}},{key:"pad",value:function(e,t){function n(e){return Array.apply(null,new Array(e)).map(Number.prototype.valueOf,0)}for(var r=e.length+2*t,o=e.map(function(e){return[].concat(n(t),e,n(t))}),i=0;i1&&o*i===n)return[o,i];for(var a=Math.sqrt(n),l=Math.ceil(a),s=Math.floor(a);l*s>n;)l--,s=Math.ceil(n/l);return o=s,i=Math.ceil(n/o),[o,i]}},{key:"getDimensions",value:function(e,r){var n=void 0;if(t.isArray(e)){for(var o=[],i=e;t.isArray(i);)o.push(i.length),i=i[0];n=o.reverse()}else if(e instanceof Texture)n=e.output;else{if(!(e instanceof Input))throw"Unknown dimensions of "+e;n=e.size}if(r)for(n=t.clone(n);n.length<3;)n.push(1);return new Int32Array(n)}},{key:"pad",value:function(e,t){function r(e){return Array.apply(null,new Array(e)).map(Number.prototype.valueOf,0)}for(var n=e.length+2*t,o=e.map(function(e){return[].concat(r(t),e,r(t))}),i=0;it)return!1;if((i+=e[s+1])>=t)return!0}}function i(t,i){return t<65?36===t:t<91||(t<97?95===t:t<123||(t<=65535?t>=170&&M.test(String.fromCharCode(t)):!1!==i&&e(t,U)))}function s(t,i){return t<48?36===t:t<58||!(t<65)&&(t<91||(t<97?95===t:t<123||(t<=65535?t>=170&&F.test(String.fromCharCode(t)):!1!==i&&(e(t,U)||e(t,G)))))}function r(t,e){return new q(t,{beforeExpr:!0,binop:e})}function a(t,e){return void 0===e&&(e={}),e.keyword=t,j[t]=new q(t,e)}function n(t){return 10===t||13===t||8232===t||8233===t}function o(t,e){return $.call(t,e)}function h(t,e){for(var i=1,s=0;;){K.lastIndex=s;var r=K.exec(t);if(!(r&&r.index=2015&&(e.ecmaVersion-=2009),null==e.allowReserved&&(e.allowReserved=e.ecmaVersion<5),tt(e.onToken)){var s=e.onToken;e.onToken=function(t){return s.push(t)}}return tt(e.onComment)&&(e.onComment=c(e,e.onComment)),e}function c(t,e){return function(i,s,r,a,n,o){var h={type:i?"Block":"Line",value:s,start:r,end:a};t.locations&&(h.loc=new it(this,n,o)),t.ranges&&(h.range=[r,a]),e.push(h)}}function u(t){return new RegExp("^(?:"+t.replace(/ /g,"|")+")$")}function l(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}function d(t,e,i,s){return t.type=e,t.end=i,this.options.locations&&(t.loc.end=s),this.options.ranges&&(t.range[1]=i),t}function f(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode(55296+(t>>10),56320+(1023&t)))}function m(t){return 36===t||t>=40&&t<=43||46===t||63===t||t>=91&&t<=94||t>=123&&t<=125}function x(t){return i(t,!0)||36===t||95===t}function g(t){return s(t,!0)||36===t||95===t||8204===t||8205===t}function v(t){return t>=65&&t<=90||t>=97&&t<=122}function y(t){return t>=0&&t<=1114111}function _(t){return 100===t||68===t||115===t||83===t||119===t||87===t}function b(t){return v(t)||95===t}function k(t){return b(t)||C(t)}function C(t){return t>=48&&t<=57}function S(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function E(t){return t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:t-48}function w(t){return t>=48&&t<=55}function A(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode(55296+(t>>10),56320+(1023&t)))}function I(t,e){return new at(e,t).parse()}function P(t,e,i){var s=new at(i,t,e);return s.nextToken(),s.parseExpression()}function L(t,e){return new at(e,t)}function N(e,i,s){t.parse_dammit=e,t.LooseParser=i,t.pluginsLoose=s}var T={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},V="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",R={5:V,6:V+" const class extends export import super"},D=/^in(stanceof)?$/,B="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄮㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿪ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞮꞰ-ꞷꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭥꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",O="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_",M=new RegExp("["+B+"]"),F=new RegExp("["+B+O+"]");B=O=null;var U=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,257,0,11,39,8,0,22,0,12,39,3,3,55,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,698,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,1,31,6124,20,754,9486,286,82,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,15,7472,3104,541],G=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,280,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,19719,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239],q=function(t,e){void 0===e&&(e={}),this.label=t,this.keyword=e.keyword,this.beforeExpr=!!e.beforeExpr,this.startsExpr=!!e.startsExpr,this.isLoop=!!e.isLoop,this.isAssign=!!e.isAssign,this.prefix=!!e.prefix,this.postfix=!!e.postfix,this.binop=e.binop||null,this.updateContext=null},H={beforeExpr:!0},W={startsExpr:!0},j={},z={num:new q("num",W),regexp:new q("regexp",W),string:new q("string",W),name:new q("name",W),eof:new q("eof"),bracketL:new q("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new q("]"),braceL:new q("{",{beforeExpr:!0,startsExpr:!0}),braceR:new q("}"),parenL:new q("(",{beforeExpr:!0,startsExpr:!0}),parenR:new q(")"),comma:new q(",",H),semi:new q(";",H),colon:new q(":",H),dot:new q("."),question:new q("?",H),arrow:new q("=>",H),template:new q("template"),invalidTemplate:new q("invalidTemplate"),ellipsis:new q("...",H),backQuote:new q("`",W),dollarBraceL:new q("${",{beforeExpr:!0,startsExpr:!0}),eq:new q("=",{beforeExpr:!0,isAssign:!0}),assign:new q("_=",{beforeExpr:!0,isAssign:!0}),incDec:new q("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new q("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:r("||",1),logicalAND:r("&&",2),bitwiseOR:r("|",3),bitwiseXOR:r("^",4),bitwiseAND:r("&",5),equality:r("==/!=/===/!==",6),relational:r("/<=/>=",7),bitShift:r("<>/>>>",8),plusMin:new q("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:r("%",10),star:r("*",10),slash:r("/",10),starstar:new q("**",{beforeExpr:!0}),_break:a("break"),_case:a("case",H),_catch:a("catch"),_continue:a("continue"),_debugger:a("debugger"),_default:a("default",H),_do:a("do",{isLoop:!0,beforeExpr:!0}),_else:a("else",H),_finally:a("finally"),_for:a("for",{isLoop:!0}),_function:a("function",W),_if:a("if"),_return:a("return",H),_switch:a("switch"),_throw:a("throw",H),_try:a("try"),_var:a("var"),_const:a("const"),_while:a("while",{isLoop:!0}),_with:a("with"),_new:a("new",{beforeExpr:!0,startsExpr:!0}),_this:a("this",W),_super:a("super",W),_class:a("class",W),_extends:a("extends",H),_export:a("export"),_import:a("import"),_null:a("null",W),_true:a("true",W),_false:a("false",W),_in:a("in",{beforeExpr:!0,binop:7}),_instanceof:a("instanceof",{beforeExpr:!0,binop:7}),_typeof:a("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:a("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:a("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},Q=/\r\n?|\n|\u2028|\u2029/,K=new RegExp(Q.source,"g"),X=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/,Y=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,Z=Object.prototype,$=Z.hasOwnProperty,J=Z.toString,tt=Array.isArray||function(t){return"[object Array]"===J.call(t)},et=function(t,e){this.line=t,this.column=e};et.prototype.offset=function(t){return new et(this.line,this.column+t)};var it=function(t,e,i){this.start=e,this.end=i,null!==t.sourceFile&&(this.source=t.sourceFile)},st={ecmaVersion:7,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowHashBang:!1,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1,plugins:{}},rt={},at=function(t,e,i){this.options=t=p(t),this.sourceFile=t.sourceFile,this.keywords=u(R[t.ecmaVersion>=6?6:5]);var s="";if(!t.allowReserved){for(var r=t.ecmaVersion;!(s=T[r]);r--);"module"==t.sourceType&&(s+=" await")}this.reservedWords=u(s);var a=(s?s+" ":"")+T.strict;this.reservedWordsStrict=u(a),this.reservedWordsStrictBind=u(a+" "+T.strictBind),this.input=String(e),this.containsEsc=!1,this.loadPlugins(t.plugins),i?(this.pos=i,this.lineStart=this.input.lastIndexOf("\n",i-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(Q).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=z.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===t.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.inFunction=this.inGenerator=this.inAsync=!1,this.yieldPos=this.awaitPos=0,this.labels=[],0===this.pos&&t.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterFunctionScope(),this.regexpState=null};at.prototype.isKeyword=function(t){return this.keywords.test(t)},at.prototype.isReservedWord=function(t){return this.reservedWords.test(t)},at.prototype.extend=function(t,e){this[t]=e(this[t])},at.prototype.loadPlugins=function(t){var e=this;for(var i in t){var s=rt[i];if(!s)throw new Error("Plugin '"+i+"' not found");s(e,t[i])}},at.prototype.parse=function(){var t=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(t)};var nt=at.prototype,ot=/^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)"|;)/;nt.strictDirective=function(t){for(var e=this;;){Y.lastIndex=t,t+=Y.exec(e.input)[0].length;var i=ot.exec(e.input.slice(t));if(!i)return!1;if("use strict"==(i[1]||i[2]))return!0;t+=i[0].length}},nt.eat=function(t){return this.type===t&&(this.next(),!0)},nt.isContextual=function(t){return this.type===z.name&&this.value===t&&!this.containsEsc},nt.eatContextual=function(t){return!!this.isContextual(t)&&(this.next(),!0)},nt.expectContextual=function(t){this.eatContextual(t)||this.unexpected()},nt.canInsertSemicolon=function(){return this.type===z.eof||this.type===z.braceR||Q.test(this.input.slice(this.lastTokEnd,this.start))},nt.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},nt.semicolon=function(){this.eat(z.semi)||this.insertSemicolon()||this.unexpected()},nt.afterTrailingComma=function(t,e){if(this.type==t)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),e||this.next(),!0},nt.expect=function(t){this.eat(t)||this.unexpected()},nt.unexpected=function(t){this.raise(null!=t?t:this.start,"Unexpected token")},nt.checkPatternErrors=function(t,e){if(t){t.trailingComma>-1&&this.raiseRecoverable(t.trailingComma,"Comma is not permitted after the rest element");var i=e?t.parenthesizedAssign:t.parenthesizedBind;i>-1&&this.raiseRecoverable(i,"Parenthesized pattern")}},nt.checkExpressionErrors=function(t,e){if(!t)return!1;var i=t.shorthandAssign,s=t.doubleProto;if(!e)return i>=0||s>=0;i>=0&&this.raise(i,"Shorthand property assignments are valid only in destructuring patterns"),s>=0&&this.raiseRecoverable(s,"Redefinition of __proto__ property")},nt.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos=6&&(t.sourceType=this.options.sourceType),this.finishNode(t,"Program")};var pt={kind:"loop"},ct={kind:"switch"};ht.isLet=function(){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;Y.lastIndex=this.pos;var t=Y.exec(this.input),e=this.pos+t[0].length,r=this.input.charCodeAt(e);if(91===r||123==r)return!0;if(i(r,!0)){for(var a=e+1;s(this.input.charCodeAt(a),!0);)++a;var n=this.input.slice(e,a);if(!D.test(n))return!0}return!1},ht.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;Y.lastIndex=this.pos;var t=Y.exec(this.input),e=this.pos+t[0].length;return!(Q.test(this.input.slice(this.pos,e))||"function"!==this.input.slice(e,e+8)||e+8!=this.input.length&&s(this.input.charAt(e+8)))},ht.parseStatement=function(t,e,i){var s,r=this.type,a=this.startNode();switch(this.isLet()&&(r=z._var,s="let"),r){case z._break:case z._continue:return this.parseBreakContinueStatement(a,r.keyword);case z._debugger:return this.parseDebuggerStatement(a);case z._do:return this.parseDoStatement(a);case z._for:return this.parseForStatement(a);case z._function:return!t&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(a,!1);case z._class:return t||this.unexpected(),this.parseClass(a,!0);case z._if:return this.parseIfStatement(a);case z._return:return this.parseReturnStatement(a);case z._switch:return this.parseSwitchStatement(a);case z._throw:return this.parseThrowStatement(a);case z._try:return this.parseTryStatement(a);case z._const:case z._var:return s=s||this.value,t||"var"==s||this.unexpected(),this.parseVarStatement(a,s);case z._while:return this.parseWhileStatement(a);case z._with:return this.parseWithStatement(a);case z.braceL:return this.parseBlock();case z.semi:return this.parseEmptyStatement(a);case z._export:case z._import:return this.options.allowImportExportEverywhere||(e||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),r===z._import?this.parseImport(a):this.parseExport(a,i);default:if(this.isAsyncFunction())return t||this.unexpected(),this.next(),this.parseFunctionStatement(a,!0);var n=this.value,o=this.parseExpression();return r===z.name&&"Identifier"===o.type&&this.eat(z.colon)?this.parseLabeledStatement(a,n,o):this.parseExpressionStatement(a,o)}},ht.parseBreakContinueStatement=function(t,e){var i=this,s="break"==e;this.next(),this.eat(z.semi)||this.insertSemicolon()?t.label=null:this.type!==z.name?this.unexpected():(t.label=this.parseIdent(),this.semicolon());for(var r=0;r=6?this.eat(z.semi):this.semicolon(),this.finishNode(t,"DoWhileStatement")},ht.parseForStatement=function(t){this.next();var e=this.options.ecmaVersion>=9&&this.inAsync&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(pt),this.enterLexicalScope(),this.expect(z.parenL),this.type===z.semi)return e>-1&&this.unexpected(e),this.parseFor(t,null);var i=this.isLet();if(this.type===z._var||this.type===z._const||i){var s=this.startNode(),r=i?"let":this.value;return this.next(),(this.parseVar(s,!0,r),this.finishNode(s,"VariableDeclaration"),!(this.type===z._in||this.options.ecmaVersion>=6&&this.isContextual("of"))||1!==s.declarations.length||"var"!==r&&s.declarations[0].init)?(e>-1&&this.unexpected(e),this.parseFor(t,s)):(this.options.ecmaVersion>=9&&(this.type===z._in?e>-1&&this.unexpected(e):t.await=e>-1),this.parseForIn(t,s))}var a=new l,n=this.parseExpression(!0,a);return this.type===z._in||this.options.ecmaVersion>=6&&this.isContextual("of")?(this.options.ecmaVersion>=9&&(this.type===z._in?e>-1&&this.unexpected(e):t.await=e>-1),this.toAssignable(n,!1,a),this.checkLVal(n),this.parseForIn(t,n)):(this.checkExpressionErrors(a,!0),e>-1&&this.unexpected(e),this.parseFor(t,n))},ht.parseFunctionStatement=function(t,e){return this.next(),this.parseFunction(t,!0,!1,e)},ht.parseIfStatement=function(t){return this.next(),t.test=this.parseParenExpression(),t.consequent=this.parseStatement(!this.strict&&this.type==z._function),t.alternate=this.eat(z._else)?this.parseStatement(!this.strict&&this.type==z._function):null,this.finishNode(t,"IfStatement")},ht.parseReturnStatement=function(t){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(z.semi)||this.insertSemicolon()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")},ht.parseSwitchStatement=function(t){var e=this;this.next(),t.discriminant=this.parseParenExpression(),t.cases=[],this.expect(z.braceL),this.labels.push(ct),this.enterLexicalScope();for(var i,s=!1;this.type!=z.braceR;)if(e.type===z._case||e.type===z._default){var r=e.type===z._case;i&&e.finishNode(i,"SwitchCase"),t.cases.push(i=e.startNode()),i.consequent=[],e.next(),r?i.test=e.parseExpression():(s&&e.raiseRecoverable(e.lastTokStart,"Multiple default clauses"),s=!0,i.test=null),e.expect(z.colon)}else i||e.unexpected(),i.consequent.push(e.parseStatement(!0));return this.exitLexicalScope(),i&&this.finishNode(i,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(t,"SwitchStatement")},ht.parseThrowStatement=function(t){return this.next(),Q.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")};var ut=[];ht.parseTryStatement=function(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.type===z._catch){var e=this.startNode();this.next(),this.expect(z.parenL),e.param=this.parseBindingAtom(),this.enterLexicalScope(),this.checkLVal(e.param,"let"),this.expect(z.parenR),e.body=this.parseBlock(!1),this.exitLexicalScope(),t.handler=this.finishNode(e,"CatchClause")}return t.finalizer=this.eat(z._finally)?this.parseBlock():null,t.handler||t.finalizer||this.raise(t.start,"Missing catch or finally clause"),this.finishNode(t,"TryStatement")},ht.parseVarStatement=function(t,e){return this.next(),this.parseVar(t,!1,e),this.semicolon(),this.finishNode(t,"VariableDeclaration")},ht.parseWhileStatement=function(t){return this.next(),t.test=this.parseParenExpression(),this.labels.push(pt),t.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(t,"WhileStatement")},ht.parseWithStatement=function(t){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),t.object=this.parseParenExpression(),t.body=this.parseStatement(!1),this.finishNode(t,"WithStatement")},ht.parseEmptyStatement=function(t){return this.next(),this.finishNode(t,"EmptyStatement")},ht.parseLabeledStatement=function(t,e,i){for(var s=this,r=0,a=s.labels;r=0;o--){var h=s.labels[o];if(h.statementStart!=t.start)break;h.statementStart=s.start,h.kind=n}return this.labels.push({name:e,kind:n,statementStart:this.start}),t.body=this.parseStatement(!0),("ClassDeclaration"==t.body.type||"VariableDeclaration"==t.body.type&&"var"!=t.body.kind||"FunctionDeclaration"==t.body.type&&(this.strict||t.body.generator))&&this.raiseRecoverable(t.body.start,"Invalid labeled declaration"),this.labels.pop(),t.label=i,this.finishNode(t,"LabeledStatement")},ht.parseExpressionStatement=function(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")},ht.parseBlock=function(t){var e=this;void 0===t&&(t=!0);var i=this.startNode();for(i.body=[],this.expect(z.braceL),t&&this.enterLexicalScope();!this.eat(z.braceR);){var s=e.parseStatement(!0);i.body.push(s)}return t&&this.exitLexicalScope(),this.finishNode(i,"BlockStatement")},ht.parseFor=function(t,e){return t.init=e,this.expect(z.semi),t.test=this.type===z.semi?null:this.parseExpression(),this.expect(z.semi),t.update=this.type===z.parenR?null:this.parseExpression(),this.expect(z.parenR),this.exitLexicalScope(),t.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(t,"ForStatement")},ht.parseForIn=function(t,e){var i=this.type===z._in?"ForInStatement":"ForOfStatement";return this.next(),"ForInStatement"==i&&("AssignmentPattern"===e.type||"VariableDeclaration"===e.type&&null!=e.declarations[0].init&&(this.strict||"Identifier"!==e.declarations[0].id.type))&&this.raise(e.start,"Invalid assignment in for-in loop head"),t.left=e,t.right="ForInStatement"==i?this.parseExpression():this.parseMaybeAssign(),this.expect(z.parenR),this.exitLexicalScope(),t.body=this.parseStatement(!1),this.labels.pop(),this.finishNode(t,i)},ht.parseVar=function(t,e,i){var s=this;for(t.declarations=[],t.kind=i;;){var r=s.startNode();if(s.parseVarId(r,i),s.eat(z.eq)?r.init=s.parseMaybeAssign(e):"const"!==i||s.type===z._in||s.options.ecmaVersion>=6&&s.isContextual("of")?"Identifier"==r.id.type||e&&(s.type===z._in||s.isContextual("of"))?r.init=null:s.raise(s.lastTokEnd,"Complex binding patterns require an initialization value"):s.unexpected(),t.declarations.push(s.finishNode(r,"VariableDeclarator")),!s.eat(z.comma))break}return t},ht.parseVarId=function(t,e){t.id=this.parseBindingAtom(e),this.checkLVal(t.id,e,!1)},ht.parseFunction=function(t,e,i,s){this.initFunction(t),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s)&&(t.generator=this.eat(z.star)),this.options.ecmaVersion>=8&&(t.async=!!s),e&&(t.id="nullableID"===e&&this.type!=z.name?null:this.parseIdent(),t.id&&this.checkLVal(t.id,"var"));var r=this.inGenerator,a=this.inAsync,n=this.yieldPos,o=this.awaitPos,h=this.inFunction;return this.inGenerator=t.generator,this.inAsync=t.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,this.enterFunctionScope(),e||(t.id=this.type==z.name?this.parseIdent():null),this.parseFunctionParams(t),this.parseFunctionBody(t,i),this.inGenerator=r,this.inAsync=a,this.yieldPos=n,this.awaitPos=o,this.inFunction=h,this.finishNode(t,e?"FunctionDeclaration":"FunctionExpression")},ht.parseFunctionParams=function(t){this.expect(z.parenL),t.params=this.parseBindingList(z.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},ht.parseClass=function(t,e){var i=this;this.next(),this.parseClassId(t,e),this.parseClassSuper(t);var s=this.startNode(),r=!1;for(s.body=[],this.expect(z.braceL);!this.eat(z.braceR);){var a=i.parseClassMember(s);a&&"MethodDefinition"===a.type&&"constructor"===a.kind&&(r&&i.raise(a.start,"Duplicate constructor in the same class"),r=!0)}return t.body=this.finishNode(s,"ClassBody"),this.finishNode(t,e?"ClassDeclaration":"ClassExpression")},ht.parseClassMember=function(t){var e=this;if(this.eat(z.semi))return null;var i=this.startNode(),s=function(t,s){void 0===s&&(s=!1);var r=e.start,a=e.startLoc;return!!e.eatContextual(t)&&(!(e.type===z.parenL||s&&e.canInsertSemicolon())||(i.key&&e.unexpected(),i.computed=!1,i.key=e.startNodeAt(r,a),i.key.name=t,e.finishNode(i.key,"Identifier"),!1))};i.kind="method",i.static=s("static");var r=this.eat(z.star),a=!1;r||(this.options.ecmaVersion>=8&&s("async",!0)?(a=!0,r=this.options.ecmaVersion>=9&&this.eat(z.star)):s("get")?i.kind="get":s("set")&&(i.kind="set")),i.key||this.parsePropertyName(i);var n=i.key;return i.computed||i.static||!("Identifier"===n.type&&"constructor"===n.name||"Literal"===n.type&&"constructor"===n.value)?i.static&&"Identifier"===n.type&&"prototype"===n.name&&this.raise(n.start,"Classes may not have a static property named prototype"):("method"!==i.kind&&this.raise(n.start,"Constructor can't have get/set modifier"),r&&this.raise(n.start,"Constructor can't be a generator"),a&&this.raise(n.start,"Constructor can't be an async method"),i.kind="constructor"),this.parseClassMethod(t,i,r,a),"get"===i.kind&&0!==i.value.params.length&&this.raiseRecoverable(i.value.start,"getter should have no params"),"set"===i.kind&&1!==i.value.params.length&&this.raiseRecoverable(i.value.start,"setter should have exactly one param"),"set"===i.kind&&"RestElement"===i.value.params[0].type&&this.raiseRecoverable(i.value.params[0].start,"Setter cannot use rest params"),i},ht.parseClassMethod=function(t,e,i,s){e.value=this.parseMethod(i,s),t.body.push(this.finishNode(e,"MethodDefinition"))},ht.parseClassId=function(t,e){t.id=this.type===z.name?this.parseIdent():!0===e?this.unexpected():null},ht.parseClassSuper=function(t){t.superClass=this.eat(z._extends)?this.parseExprSubscripts():null},ht.parseExport=function(t,e){var i=this;if(this.next(),this.eat(z.star))return this.expectContextual("from"),this.type!==z.string&&this.unexpected(),t.source=this.parseExprAtom(),this.semicolon(),this.finishNode(t,"ExportAllDeclaration");if(this.eat(z._default)){this.checkExport(e,"default",this.lastTokStart);var s;if(this.type===z._function||(s=this.isAsyncFunction())){var r=this.startNode();this.next(),s&&this.next(),t.declaration=this.parseFunction(r,"nullableID",!1,s)}else if(this.type===z._class){var a=this.startNode();t.declaration=this.parseClass(a,"nullableID")}else t.declaration=this.parseMaybeAssign(),this.semicolon();return this.finishNode(t,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement())t.declaration=this.parseStatement(!0),"VariableDeclaration"===t.declaration.type?this.checkVariableExport(e,t.declaration.declarations):this.checkExport(e,t.declaration.id.name,t.declaration.id.start),t.specifiers=[],t.source=null;else{if(t.declaration=null,t.specifiers=this.parseExportSpecifiers(e),this.eatContextual("from"))this.type!==z.string&&this.unexpected(),t.source=this.parseExprAtom();else{for(var n=0,o=t.specifiers;n=6&&t)switch(t.type){case"Identifier":this.inAsync&&"await"===t.name&&this.raise(t.start,"Can not use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":t.type="ObjectPattern",i&&this.checkPatternErrors(i,!0);for(var r=0,a=t.properties;r=9&&"SpreadElement"===t.type||this.options.ecmaVersion>=6&&(t.computed||t.method||t.shorthand))){var s,r=t.key;switch(r.type){case"Identifier":s=r.name;break;case"Literal":s=String(r.value);break;default:return}var a=t.kind;if(this.options.ecmaVersion>=6)return void("__proto__"===s&&"init"===a&&(e.proto&&(i&&i.doubleProto<0?i.doubleProto=r.start:this.raiseRecoverable(r.start,"Redefinition of __proto__ property")),e.proto=!0));s="$"+s;var n=e[s];if(n){var o;o="init"===a?this.strict&&n.init||n.get||n.set:n.init||n[a],o&&this.raiseRecoverable(r.start,"Redefinition of property")}else n=e[s]={init:!1,get:!1,set:!1};n[a]=!0}},dt.parseExpression=function(t,e){var i=this,s=this.start,r=this.startLoc,a=this.parseMaybeAssign(t,e);if(this.type===z.comma){var n=this.startNodeAt(s,r);for(n.expressions=[a];this.eat(z.comma);)n.expressions.push(i.parseMaybeAssign(t,e));return this.finishNode(n,"SequenceExpression")}return a},dt.parseMaybeAssign=function(t,e,i){if(this.inGenerator&&this.isContextual("yield"))return this.parseYield();var s=!1,r=-1,a=-1;e?(r=e.parenthesizedAssign,a=e.trailingComma,e.parenthesizedAssign=e.trailingComma=-1):(e=new l,s=!0);var n=this.start,o=this.startLoc;this.type!=z.parenL&&this.type!=z.name||(this.potentialArrowAt=this.start);var h=this.parseMaybeConditional(t,e);if(i&&(h=i.call(this,h,n,o)),this.type.isAssign){var p=this.startNodeAt(n,o);return p.operator=this.value,p.left=this.type===z.eq?this.toAssignable(h,!1,e):h,s||l.call(e),e.shorthandAssign=-1,this.checkLVal(h),this.next(),p.right=this.parseMaybeAssign(t),this.finishNode(p,"AssignmentExpression")}return s&&this.checkExpressionErrors(e,!0),r>-1&&(e.parenthesizedAssign=r),a>-1&&(e.trailingComma=a),h},dt.parseMaybeConditional=function(t,e){var i=this.start,s=this.startLoc,r=this.parseExprOps(t,e);if(this.checkExpressionErrors(e))return r;if(this.eat(z.question)){var a=this.startNodeAt(i,s);return a.test=r,a.consequent=this.parseMaybeAssign(),this.expect(z.colon),a.alternate=this.parseMaybeAssign(t),this.finishNode(a,"ConditionalExpression")}return r},dt.parseExprOps=function(t,e){var i=this.start,s=this.startLoc,r=this.parseMaybeUnary(e,!1);return this.checkExpressionErrors(e)?r:r.start==i&&"ArrowFunctionExpression"===r.type?r:this.parseExprOp(r,i,s,-1,t)},dt.parseExprOp=function(t,e,i,s,r){var a=this.type.binop;if(null!=a&&(!r||this.type!==z._in)&&a>s){var n=this.type===z.logicalOR||this.type===z.logicalAND,o=this.value;this.next();var h=this.start,p=this.startLoc,c=this.parseExprOp(this.parseMaybeUnary(null,!1),h,p,a,r),u=this.buildBinary(e,i,t,c,o,n);return this.parseExprOp(u,e,i,s,r)}return t},dt.buildBinary=function(t,e,i,s,r,a){var n=this.startNodeAt(t,e);return n.left=i,n.operator=r,n.right=s,this.finishNode(n,a?"LogicalExpression":"BinaryExpression")},dt.parseMaybeUnary=function(t,e){var i,s=this,r=this.start,a=this.startLoc;if(this.inAsync&&this.isContextual("await"))i=this.parseAwait(),e=!0;else if(this.type.prefix){var n=this.startNode(),o=this.type===z.incDec;n.operator=this.value,n.prefix=!0,this.next(),n.argument=this.parseMaybeUnary(null,!0),this.checkExpressionErrors(t,!0),o?this.checkLVal(n.argument):this.strict&&"delete"===n.operator&&"Identifier"===n.argument.type?this.raiseRecoverable(n.start,"Deleting local variable in strict mode"):e=!0,i=this.finishNode(n,o?"UpdateExpression":"UnaryExpression")}else{if(i=this.parseExprSubscripts(t),this.checkExpressionErrors(t))return i;for(;this.type.postfix&&!this.canInsertSemicolon();){var h=s.startNodeAt(r,a);h.operator=s.value,h.prefix=!1,h.argument=i,s.checkLVal(i),s.next(),i=s.finishNode(h,"UpdateExpression")}}return!e&&this.eat(z.starstar)?this.buildBinary(r,a,i,this.parseMaybeUnary(null,!1),"**",!1):i},dt.parseExprSubscripts=function(t){var e=this.start,i=this.startLoc,s=this.parseExprAtom(t),r="ArrowFunctionExpression"===s.type&&")"!==this.input.slice(this.lastTokStart,this.lastTokEnd);if(this.checkExpressionErrors(t)||r)return s;var a=this.parseSubscripts(s,e,i);return t&&"MemberExpression"===a.type&&(t.parenthesizedAssign>=a.start&&(t.parenthesizedAssign=-1),t.parenthesizedBind>=a.start&&(t.parenthesizedBind=-1)),a},dt.parseSubscripts=function(t,e,i,s){for(var r=this,a=this.options.ecmaVersion>=8&&"Identifier"===t.type&&"async"===t.name&&this.lastTokEnd==t.end&&!this.canInsertSemicolon()&&"async"===this.input.slice(t.start,t.end),n=void 0;;)if((n=r.eat(z.bracketL))||r.eat(z.dot)){var o=r.startNodeAt(e,i);o.object=t,o.property=n?r.parseExpression():r.parseIdent(!0),o.computed=!!n,n&&r.expect(z.bracketR),t=r.finishNode(o,"MemberExpression")}else if(!s&&r.eat(z.parenL)){var h=new l,p=r.yieldPos,c=r.awaitPos;r.yieldPos=0,r.awaitPos=0;var u=r.parseExprList(z.parenR,r.options.ecmaVersion>=8,!1,h);if(a&&!r.canInsertSemicolon()&&r.eat(z.arrow))return r.checkPatternErrors(h,!1),r.checkYieldAwaitInDefaultParams(),r.yieldPos=p,r.awaitPos=c,r.parseArrowExpression(r.startNodeAt(e,i),u,!0);r.checkExpressionErrors(h,!0),r.yieldPos=p||r.yieldPos,r.awaitPos=c||r.awaitPos;var d=r.startNodeAt(e,i);d.callee=t,d.arguments=u,t=r.finishNode(d,"CallExpression")}else{if(r.type!==z.backQuote)return t;var f=r.startNodeAt(e,i);f.tag=t,f.quasi=r.parseTemplate({isTagged:!0}),t=r.finishNode(f,"TaggedTemplateExpression")}},dt.parseExprAtom=function(t){var e,i=this.potentialArrowAt==this.start;switch(this.type){case z._super:return this.inFunction||this.raise(this.start,"'super' outside of function or class"),e=this.startNode(),this.next(),this.type!==z.dot&&this.type!==z.bracketL&&this.type!==z.parenL&&this.unexpected(),this.finishNode(e,"Super");case z._this:return e=this.startNode(),this.next(),this.finishNode(e,"ThisExpression");case z.name:var s=this.start,r=this.startLoc,a=this.containsEsc,n=this.parseIdent(this.type!==z.name);if(this.options.ecmaVersion>=8&&!a&&"async"===n.name&&!this.canInsertSemicolon()&&this.eat(z._function))return this.parseFunction(this.startNodeAt(s,r),!1,!1,!0);if(i&&!this.canInsertSemicolon()){if(this.eat(z.arrow))return this.parseArrowExpression(this.startNodeAt(s,r),[n],!1);if(this.options.ecmaVersion>=8&&"async"===n.name&&this.type===z.name&&!a)return n=this.parseIdent(),!this.canInsertSemicolon()&&this.eat(z.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(s,r),[n],!0)}return n;case z.regexp:var o=this.value;return e=this.parseLiteral(o.value),e.regex={pattern:o.pattern,flags:o.flags},e;case z.num:case z.string:return this.parseLiteral(this.value);case z._null:case z._true:case z._false:return e=this.startNode(),e.value=this.type===z._null?null:this.type===z._true,e.raw=this.type.keyword,this.next(),this.finishNode(e,"Literal");case z.parenL:var h=this.start,p=this.parseParenAndDistinguishExpression(i);return t&&(t.parenthesizedAssign<0&&!this.isSimpleAssignTarget(p)&&(t.parenthesizedAssign=h),t.parenthesizedBind<0&&(t.parenthesizedBind=h)),p;case z.bracketL:return e=this.startNode(),this.next(),e.elements=this.parseExprList(z.bracketR,!0,!0,t),this.finishNode(e,"ArrayExpression");case z.braceL:return this.parseObj(!1,t);case z._function:return e=this.startNode(),this.next(),this.parseFunction(e,!1);case z._class:return this.parseClass(this.startNode(),!1);case z._new:return this.parseNew();case z.backQuote:return this.parseTemplate();default:this.unexpected()}},dt.parseLiteral=function(t){var e=this.startNode();return e.value=t,e.raw=this.input.slice(this.start,this.end),this.next(),this.finishNode(e,"Literal")},dt.parseParenExpression=function(){this.expect(z.parenL);var t=this.parseExpression();return this.expect(z.parenR),t},dt.parseParenAndDistinguishExpression=function(t){var e,i=this,s=this.start,r=this.startLoc,a=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var n,o=this.start,h=this.startLoc,p=[],c=!0,u=!1,d=new l,f=this.yieldPos,m=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==z.parenR;){if(c?c=!1:i.expect(z.comma),a&&i.afterTrailingComma(z.parenR,!0)){u=!0;break}if(i.type===z.ellipsis){n=i.start,p.push(i.parseParenItem(i.parseRestBinding())),i.type===z.comma&&i.raise(i.start,"Comma is not permitted after the rest element");break}p.push(i.parseMaybeAssign(!1,d,i.parseParenItem))}var x=this.start,g=this.startLoc;if(this.expect(z.parenR),t&&!this.canInsertSemicolon()&&this.eat(z.arrow))return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=f,this.awaitPos=m,this.parseParenArrowList(s,r,p);p.length&&!u||this.unexpected(this.lastTokStart),n&&this.unexpected(n),this.checkExpressionErrors(d,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=m||this.awaitPos,p.length>1?(e=this.startNodeAt(o,h),e.expressions=p,this.finishNodeAt(e,"SequenceExpression",x,g)):e=p[0]}else e=this.parseParenExpression();if(this.options.preserveParens){var v=this.startNodeAt(s,r);return v.expression=e,this.finishNode(v,"ParenthesizedExpression")}return e},dt.parseParenItem=function(t){return t},dt.parseParenArrowList=function(t,e,i){return this.parseArrowExpression(this.startNodeAt(t,e),i)};var ft=[];dt.parseNew=function(){var t=this.startNode(),e=this.parseIdent(!0);if(this.options.ecmaVersion>=6&&this.eat(z.dot)){t.meta=e;var i=this.containsEsc;return t.property=this.parseIdent(!0),("target"!==t.property.name||i)&&this.raiseRecoverable(t.property.start,"The only valid meta property for new is new.target"),this.inFunction||this.raiseRecoverable(t.start,"new.target can only be used in functions"),this.finishNode(t,"MetaProperty")}var s=this.start,r=this.startLoc;return t.callee=this.parseSubscripts(this.parseExprAtom(),s,r,!0),this.eat(z.parenL)?t.arguments=this.parseExprList(z.parenR,this.options.ecmaVersion>=8,!1):t.arguments=ft,this.finishNode(t,"NewExpression")},dt.parseTemplateElement=function(t){var e=t.isTagged,i=this.startNode();return this.type===z.invalidTemplate?(e||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),i.value={raw:this.value,cooked:null}):i.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),i.tail=this.type===z.backQuote,this.finishNode(i,"TemplateElement")},dt.parseTemplate=function(t){var e=this;void 0===t&&(t={});var i=t.isTagged;void 0===i&&(i=!1);var s=this.startNode();this.next(),s.expressions=[];var r=this.parseTemplateElement({isTagged:i});for(s.quasis=[r];!r.tail;)e.expect(z.dollarBraceL),s.expressions.push(e.parseExpression()),e.expect(z.braceR),s.quasis.push(r=e.parseTemplateElement({isTagged:i}));return this.next(),this.finishNode(s,"TemplateLiteral")},dt.isAsyncProp=function(t){return!t.computed&&"Identifier"===t.key.type&&"async"===t.key.name&&(this.type===z.name||this.type===z.num||this.type===z.string||this.type===z.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===z.star)&&!Q.test(this.input.slice(this.lastTokEnd,this.start))},dt.parseObj=function(t,e){var i=this,s=this.startNode(),r=!0,a={};for(s.properties=[],this.next();!this.eat(z.braceR);){if(r)r=!1;else if(i.expect(z.comma),i.afterTrailingComma(z.braceR))break;var n=i.parseProperty(t,e);t||i.checkPropClash(n,a,e),s.properties.push(n)}return this.finishNode(s,t?"ObjectPattern":"ObjectExpression")},dt.parseProperty=function(t,e){var i,s,r,a,n=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(z.ellipsis))return t?(n.argument=this.parseIdent(!1),this.type===z.comma&&this.raise(this.start,"Comma is not permitted after the rest element"),this.finishNode(n,"RestElement")):(this.type===z.parenL&&e&&(e.parenthesizedAssign<0&&(e.parenthesizedAssign=this.start),e.parenthesizedBind<0&&(e.parenthesizedBind=this.start)),n.argument=this.parseMaybeAssign(!1,e),this.type===z.comma&&e&&e.trailingComma<0&&(e.trailingComma=this.start),this.finishNode(n,"SpreadElement"));this.options.ecmaVersion>=6&&(n.method=!1,n.shorthand=!1,(t||e)&&(r=this.start,a=this.startLoc),t||(i=this.eat(z.star)));var o=this.containsEsc;return this.parsePropertyName(n),!t&&!o&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(n)?(s=!0,i=this.options.ecmaVersion>=9&&this.eat(z.star),this.parsePropertyName(n,e)):s=!1,this.parsePropertyValue(n,t,i,s,r,a,e,o),this.finishNode(n,"Property")},dt.parsePropertyValue=function(t,e,i,s,r,a,n,o){if((i||s)&&this.type===z.colon&&this.unexpected(),this.eat(z.colon))t.value=e?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,n),t.kind="init";else if(this.options.ecmaVersion>=6&&this.type===z.parenL)e&&this.unexpected(),t.kind="init",t.method=!0,t.value=this.parseMethod(i,s);else if(e||o||!(this.options.ecmaVersion>=5)||t.computed||"Identifier"!==t.key.type||"get"!==t.key.name&&"set"!==t.key.name||this.type==z.comma||this.type==z.braceR)this.options.ecmaVersion>=6&&!t.computed&&"Identifier"===t.key.type?(this.checkUnreserved(t.key),t.kind="init",e?t.value=this.parseMaybeDefault(r,a,t.key):this.type===z.eq&&n?(n.shorthandAssign<0&&(n.shorthandAssign=this.start),t.value=this.parseMaybeDefault(r,a,t.key)):t.value=t.key,t.shorthand=!0):this.unexpected();else{(i||s)&&this.unexpected(),t.kind=t.key.name,this.parsePropertyName(t),t.value=this.parseMethod(!1);var h="get"===t.kind?0:1;if(t.value.params.length!==h){var p=t.value.start;"get"===t.kind?this.raiseRecoverable(p,"getter should have no params"):this.raiseRecoverable(p,"setter should have exactly one param")}else"set"===t.kind&&"RestElement"===t.value.params[0].type&&this.raiseRecoverable(t.value.params[0].start,"Setter cannot use rest params")}},dt.parsePropertyName=function(t){if(this.options.ecmaVersion>=6){if(this.eat(z.bracketL))return t.computed=!0,t.key=this.parseMaybeAssign(),this.expect(z.bracketR),t.key;t.computed=!1}return t.key=this.type===z.num||this.type===z.string?this.parseExprAtom():this.parseIdent(!0)},dt.initFunction=function(t){t.id=null,this.options.ecmaVersion>=6&&(t.generator=!1,t.expression=!1),this.options.ecmaVersion>=8&&(t.async=!1)},dt.parseMethod=function(t,e){var i=this.startNode(),s=this.inGenerator,r=this.inAsync,a=this.yieldPos,n=this.awaitPos,o=this.inFunction;return this.initFunction(i),this.options.ecmaVersion>=6&&(i.generator=t),this.options.ecmaVersion>=8&&(i.async=!!e),this.inGenerator=i.generator,this.inAsync=i.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,this.enterFunctionScope(),this.expect(z.parenL),i.params=this.parseBindingList(z.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(i,!1),this.inGenerator=s,this.inAsync=r,this.yieldPos=a,this.awaitPos=n,this.inFunction=o,this.finishNode(i,"FunctionExpression")},dt.parseArrowExpression=function(t,e,i){var s=this.inGenerator,r=this.inAsync,a=this.yieldPos,n=this.awaitPos,o=this.inFunction;return this.enterFunctionScope(),this.initFunction(t),this.options.ecmaVersion>=8&&(t.async=!!i),this.inGenerator=!1,this.inAsync=t.async,this.yieldPos=0,this.awaitPos=0,this.inFunction=!0,t.params=this.toAssignableList(e,!0),this.parseFunctionBody(t,!0),this.inGenerator=s,this.inAsync=r,this.yieldPos=a,this.awaitPos=n,this.inFunction=o,this.finishNode(t,"ArrowFunctionExpression")},dt.parseFunctionBody=function(t,e){var i=e&&this.type!==z.braceL,s=this.strict,r=!1;if(i)t.body=this.parseMaybeAssign(),t.expression=!0,this.checkParams(t,!1);else{var a=this.options.ecmaVersion>=7&&!this.isSimpleParamList(t.params);s&&!a||(r=this.strictDirective(this.end))&&a&&this.raiseRecoverable(t.start,"Illegal 'use strict' directive in function with non-simple parameter list");var n=this.labels;this.labels=[],r&&(this.strict=!0),this.checkParams(t,!s&&!r&&!e&&this.isSimpleParamList(t.params)),t.body=this.parseBlock(!1),t.expression=!1,this.adaptDirectivePrologue(t.body.body),this.labels=n}this.exitFunctionScope(),this.strict&&t.id&&this.checkLVal(t.id,"none"),this.strict=s},dt.isSimpleParamList=function(t){for(var e=0,i=t;e0;)e[i]=arguments[i+1];for(var s=0,r=e;s=1;e--){var i=t.context[e];if("function"===i.token)return i.generator}return!1},kt.updateContext=function(t){var e,i=this.type;i.keyword&&t==z.dot?this.exprAllowed=!1:(e=i.updateContext)?e.call(this,t):this.exprAllowed=i.beforeExpr},z.parenR.updateContext=z.braceR.updateContext=function(){if(1==this.context.length)return void(this.exprAllowed=!0);var t=this.context.pop();t===bt.b_stat&&"function"===this.curContext().token&&(t=this.context.pop()),this.exprAllowed=!t.isExpr},z.braceL.updateContext=function(t){this.context.push(this.braceIsBlock(t)?bt.b_stat:bt.b_expr),this.exprAllowed=!0},z.dollarBraceL.updateContext=function(){this.context.push(bt.b_tmpl),this.exprAllowed=!0},z.parenL.updateContext=function(t){var e=t===z._if||t===z._for||t===z._with||t===z._while;this.context.push(e?bt.p_stat:bt.p_expr),this.exprAllowed=!0},z.incDec.updateContext=function(){},z._function.updateContext=z._class.updateContext=function(t){t.beforeExpr&&t!==z.semi&&t!==z._else&&(t!==z.colon&&t!==z.braceL||this.curContext()!==bt.b_stat)?this.context.push(bt.f_expr):this.context.push(bt.f_stat),this.exprAllowed=!1},z.backQuote.updateContext=function(){this.curContext()===bt.q_tmpl?this.context.pop():this.context.push(bt.q_tmpl),this.exprAllowed=!1},z.star.updateContext=function(t){if(t==z._function){var e=this.context.length-1;this.context[e]===bt.f_expr?this.context[e]=bt.f_expr_gen:this.context[e]=bt.f_gen}this.exprAllowed=!0},z.name.updateContext=function(t){var e=!1;this.options.ecmaVersion>=6&&("of"==this.value&&!this.exprAllowed||"yield"==this.value&&this.inGeneratorContext())&&(e=!0),this.exprAllowed=e};var Ct={$LONE:["ASCII","ASCII_Hex_Digit","AHex","Alphabetic","Alpha","Any","Assigned","Bidi_Control","Bidi_C","Bidi_Mirrored","Bidi_M","Case_Ignorable","CI","Cased","Changes_When_Casefolded","CWCF","Changes_When_Casemapped","CWCM","Changes_When_Lowercased","CWL","Changes_When_NFKC_Casefolded","CWKCF","Changes_When_Titlecased","CWT","Changes_When_Uppercased","CWU","Dash","Default_Ignorable_Code_Point","DI","Deprecated","Dep","Diacritic","Dia","Emoji","Emoji_Component","Emoji_Modifier","Emoji_Modifier_Base","Emoji_Presentation","Extender","Ext","Grapheme_Base","Gr_Base","Grapheme_Extend","Gr_Ext","Hex_Digit","Hex","IDS_Binary_Operator","IDSB","IDS_Trinary_Operator","IDST","ID_Continue","IDC","ID_Start","IDS","Ideographic","Ideo","Join_Control","Join_C","Logical_Order_Exception","LOE","Lowercase","Lower","Math","Noncharacter_Code_Point","NChar","Pattern_Syntax","Pat_Syn","Pattern_White_Space","Pat_WS","Quotation_Mark","QMark","Radical","Regional_Indicator","RI","Sentence_Terminal","STerm","Soft_Dotted","SD","Terminal_Punctuation","Term","Unified_Ideograph","UIdeo","Uppercase","Upper","Variation_Selector","VS","White_Space","space","XID_Continue","XIDC","XID_Start","XIDS"],General_Category:["Cased_Letter","LC","Close_Punctuation","Pe","Connector_Punctuation","Pc","Control","Cc","cntrl","Currency_Symbol","Sc","Dash_Punctuation","Pd","Decimal_Number","Nd","digit","Enclosing_Mark","Me","Final_Punctuation","Pf","Format","Cf","Initial_Punctuation","Pi","Letter","L","Letter_Number","Nl","Line_Separator","Zl","Lowercase_Letter","Ll","Mark","M","Combining_Mark","Math_Symbol","Sm","Modifier_Letter","Lm","Modifier_Symbol","Sk","Nonspacing_Mark","Mn","Number","N","Open_Punctuation","Ps","Other","C","Other_Letter","Lo","Other_Number","No","Other_Punctuation","Po","Other_Symbol","So","Paragraph_Separator","Zp","Private_Use","Co","Punctuation","P","punct","Separator","Z","Space_Separator","Zs","Spacing_Mark","Mc","Surrogate","Cs","Symbol","S","Titlecase_Letter","Lt","Unassigned","Cn","Uppercase_Letter","Lu"],Script:["Adlam","Adlm","Ahom","Anatolian_Hieroglyphs","Hluw","Arabic","Arab","Armenian","Armn","Avestan","Avst","Balinese","Bali","Bamum","Bamu","Bassa_Vah","Bass","Batak","Batk","Bengali","Beng","Bhaiksuki","Bhks","Bopomofo","Bopo","Brahmi","Brah","Braille","Brai","Buginese","Bugi","Buhid","Buhd","Canadian_Aboriginal","Cans","Carian","Cari","Caucasian_Albanian","Aghb","Chakma","Cakm","Cham","Cherokee","Cher","Common","Zyyy","Coptic","Copt","Qaac","Cuneiform","Xsux","Cypriot","Cprt","Cyrillic","Cyrl","Deseret","Dsrt","Devanagari","Deva","Duployan","Dupl","Egyptian_Hieroglyphs","Egyp","Elbasan","Elba","Ethiopic","Ethi","Georgian","Geor","Glagolitic","Glag","Gothic","Goth","Grantha","Gran","Greek","Grek","Gujarati","Gujr","Gurmukhi","Guru","Han","Hani","Hangul","Hang","Hanunoo","Hano","Hatran","Hatr","Hebrew","Hebr","Hiragana","Hira","Imperial_Aramaic","Armi","Inherited","Zinh","Qaai","Inscriptional_Pahlavi","Phli","Inscriptional_Parthian","Prti","Javanese","Java","Kaithi","Kthi","Kannada","Knda","Katakana","Kana","Kayah_Li","Kali","Kharoshthi","Khar","Khmer","Khmr","Khojki","Khoj","Khudawadi","Sind","Lao","Laoo","Latin","Latn","Lepcha","Lepc","Limbu","Limb","Linear_A","Lina","Linear_B","Linb","Lisu","Lycian","Lyci","Lydian","Lydi","Mahajani","Mahj","Malayalam","Mlym","Mandaic","Mand","Manichaean","Mani","Marchen","Marc","Masaram_Gondi","Gonm","Meetei_Mayek","Mtei","Mende_Kikakui","Mend","Meroitic_Cursive","Merc","Meroitic_Hieroglyphs","Mero","Miao","Plrd","Modi","Mongolian","Mong","Mro","Mroo","Multani","Mult","Myanmar","Mymr","Nabataean","Nbat","New_Tai_Lue","Talu","Newa","Nko","Nkoo","Nushu","Nshu","Ogham","Ogam","Ol_Chiki","Olck","Old_Hungarian","Hung","Old_Italic","Ital","Old_North_Arabian","Narb","Old_Permic","Perm","Old_Persian","Xpeo","Old_South_Arabian","Sarb","Old_Turkic","Orkh","Oriya","Orya","Osage","Osge","Osmanya","Osma","Pahawh_Hmong","Hmng","Palmyrene","Palm","Pau_Cin_Hau","Pauc","Phags_Pa","Phag","Phoenician","Phnx","Psalter_Pahlavi","Phlp","Rejang","Rjng","Runic","Runr","Samaritan","Samr","Saurashtra","Saur","Sharada","Shrd","Shavian","Shaw","Siddham","Sidd","SignWriting","Sgnw","Sinhala","Sinh","Sora_Sompeng","Sora","Soyombo","Soyo","Sundanese","Sund","Syloti_Nagri","Sylo","Syriac","Syrc","Tagalog","Tglg","Tagbanwa","Tagb","Tai_Le","Tale","Tai_Tham","Lana","Tai_Viet","Tavt","Takri","Takr","Tamil","Taml","Tangut","Tang","Telugu","Telu","Thaana","Thaa","Thai","Tibetan","Tibt","Tifinagh","Tfng","Tirhuta","Tirh","Ugaritic","Ugar","Vai","Vaii","Warang_Citi","Wara","Yi","Yiii","Zanabazar_Square","Zanb"]};Array.prototype.push.apply(Ct.$LONE,Ct.General_Category),Ct.gc=Ct.General_Category,Ct.sc=Ct.Script_Extensions=Ct.scx=Ct.Script;var St=at.prototype,Et=function(t){this.parser=t,this.validFlags="gim"+(t.options.ecmaVersion>=6?"uy":"")+(t.options.ecmaVersion>=9?"s":""),this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=[],this.backReferenceNames=[]};Et.prototype.reset=function(t,e,i){var s=-1!==i.indexOf("u");this.start=0|t,this.source=e+"",this.flags=i,this.switchU=s&&this.parser.options.ecmaVersion>=6,this.switchN=s&&this.parser.options.ecmaVersion>=9},Et.prototype.raise=function(t){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+t)},Et.prototype.at=function(t){var e=this.source,i=e.length;if(t>=i)return-1;var s=e.charCodeAt(t);return!this.switchU||s<=55295||s>=57344||t+1>=i?s:(s<<10)+e.charCodeAt(t+1)-56613888},Et.prototype.nextIndex=function(t){var e=this.source,i=e.length;if(t>=i)return i;var s=e.charCodeAt(t);return!this.switchU||s<=55295||s>=57344||t+1>=i?t+1:t+2},Et.prototype.current=function(){return this.at(this.pos)},Et.prototype.lookahead=function(){return this.at(this.nextIndex(this.pos))},Et.prototype.advance=function(){this.pos=this.nextIndex(this.pos)},Et.prototype.eat=function(t){return this.current()===t&&(this.advance(),!0)},St.validateRegExpFlags=function(t){for(var e=this,i=t.validFlags,s=t.flags,r=0;r>1,i=-7,N=t?h- function isBuffer(f){return!!f.constructor&&"function"==typeof f.constructor.isBuffer&&f.constructor.isBuffer(f)}function isSlowBuffer(f){return"function"==typeof f.readFloatLE&&"function"==typeof f.slice&&isBuffer(f.slice(0,0))}module.exports=function(f){return null!=f&&(isBuffer(f)||isSlowBuffer(f)||!!f._isBuffer)}; },{}],90:[function(require,module,exports){ var toString={}.toString;module.exports=Array.isArray||function(r){return"[object Array]"==toString.call(r)}; - },{}],91:[function(require,module,exports){ (function (process){ "use strict";function nextTick(e,n,c,r){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var s,t,o=arguments.length;switch(o){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(function(){e.call(null,n)});case 3:return process.nextTick(function(){e.call(null,n,c)});case 4:return process.nextTick(function(){e.call(null,n,c,r)});default:for(s=new Array(o-1),t=0;t1)for(var r=1;r0?("string"==typeof t||i.objectMode||Object.getPrototypeOf(t)===Buffer.prototype||(t=_uint8ArrayToBuffer(t)),r?i.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):addChunk(e,i,t,!0):i.ended?e.emit("error",new Error("stream.push() after EOF")):(i.reading=!1,i.decoder&&!n?(t=i.decoder.write(t),i.objectMode||0!==t.length?addChunk(e,i,t,!1):maybeReadMore(e,i)):addChunk(e,i,t,!1))):r||(i.reading=!1)}return needMoreData(i)}function addChunk(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&emitReadable(e)),maybeReadMore(e,t)}function chunkInvalid(e,t){var n;return _isUint8Array(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function needMoreData(e){return!e.ended&&(e.needReadable||e.length=MAX_HWM?e=MAX_HWM:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function howMuchToRead(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=computeNewHighWaterMark(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function onEofChunk(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,emitReadable(e)}}function emitReadable(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(debug("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?pna.nextTick(emitReadable_,e):emitReadable_(e))}function emitReadable_(e){debug("emit readable"),e.emit("readable"),flow(e)}function maybeReadMore(e,t){t.readingMore||(t.readingMore=!0,pna.nextTick(maybeReadMore_,e,t))}function maybeReadMore_(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=fromListPartial(e,t.buffer,t.decoder),n}function fromListPartial(e,t,n){var r;return ei.length?i.length:e;if(d===i.length?a+=i:a+=i.slice(0,e),0===(e-=d)){d===i.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=i.slice(d));break}++r}return t.length-=r,a}function copyFromBuffer(e,t){var n=Buffer.allocUnsafe(e),r=t.head,a=1;for(r.data.copy(n),e-=r.data.length;r=r.next;){var i=r.data,d=e>i.length?i.length:e;if(i.copy(n,n.length-e,0,d),0===(e-=d)){d===i.length?(++a,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=i.slice(d));break}++a}return t.length-=a,n}function endReadable(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,pna.nextTick(endReadableNT,t,e))}function endReadableNT(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function forEach(e,t){for(var n=0,r=e.length;n=t.highWaterMark||t.ended))return debug("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?endReadable(this):emitReadable(this),null;if(0===(e=howMuchToRead(e,t))&&t.ended)return 0===t.length&&endReadable(this),null;var r=t.needReadable;debug("need readable",r),(0===t.length||t.length-e0?fromList(e,t):null,null===a?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&endReadable(this)),null!==a&&this.emit("data",a),a},Readable.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(e,t){function n(e,t){debug("onunpipe"),e===s&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,a())}function r(){debug("onend"),e.end()}function a(){debug("cleanup"),e.removeListener("close",o),e.removeListener("finish",u),e.removeListener("drain",b),e.removeListener("error",d),e.removeListener("unpipe",n),s.removeListener("end",r),s.removeListener("end",l),s.removeListener("data",i),c=!0,!h.awaitDrain||e._writableState&&!e._writableState.needDrain||b()}function i(t){debug("ondata"),g=!1,!1!==e.write(t)||g||((1===h.pipesCount&&h.pipes===e||h.pipesCount>1&&-1!==indexOf(h.pipes,e))&&!c&&(debug("false write response, pause",s._readableState.awaitDrain),s._readableState.awaitDrain++,g=!0),s.pause())}function d(t){debug("onerror",t),l(),e.removeListener("error",d),0===EElistenerCount(e,"error")&&e.emit("error",t)}function o(){e.removeListener("finish",u),l()}function u(){debug("onfinish"),e.removeListener("close",o),l()}function l(){debug("unpipe"),s.unpipe(e)}var s=this,h=this._readableState;switch(h.pipesCount){case 0:h.pipes=e;break;case 1:h.pipes=[h.pipes,e];break;default:h.pipes.push(e)}h.pipesCount+=1,debug("pipe count=%d opts=%j",h.pipesCount,t);var f=(!t||!1!==t.end)&&e!==process.stdout&&e!==process.stderr,p=f?r:l;h.endEmitted?pna.nextTick(p):s.once("end",p),e.on("unpipe",n);var b=pipeOnDrain(s);e.on("drain",b);var c=!1,g=!1;return s.on("data",i),prependListener(e,"error",d),e.once("close",o),e.once("finish",u),e.emit("pipe",s),h.flowing||(debug("pipe resume"),s.resume()),e},Readable.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n),this);if(!e){var r=t.pipes,a=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1?setImmediate:pna.nextTick,Duplex;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")},Stream=require("./internal/streams/stream"),Buffer=require("safe-buffer").Buffer,OurUint8Array=global.Uint8Array||function(){},destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(e){return!!realHasInstance.call(this,e)||this===Writable&&(e&&e._writableState instanceof WritableState)}})):realHasInstance=function(e){return e instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(e,t,r){var i=this._writableState,n=!1,o=!i.objectMode&&_isUint8Array(e);return o&&!Buffer.isBuffer(e)&&(e=_uint8ArrayToBuffer(e)),"function"==typeof t&&(r=t,t=null),o?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=nop),i.ended?writeAfterEnd(this,r):(o||validChunk(this,i,e,r))&&(i.pendingcb++,n=writeOrBuffer(this,i,o,e,t,r)),n},Writable.prototype.cork=function(){this._writableState.corked++},Writable.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||clearBuffer(this,e))},Writable.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Writable.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(e,t,r){var i=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!==e&&void 0!==e&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||endWritable(this,i,r)},Object.defineProperty(Writable.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),Writable.prototype.destroy=destroyImpl.destroy,Writable.prototype._undestroy=destroyImpl.undestroy,Writable.prototype._destroy=function(e,t){this.end(),t(e)}; + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) },{"./_stream_duplex":94,"./internal/streams/destroy":100,"./internal/streams/stream":101,"_process":92,"core-util-is":51,"inherits":88,"process-nextick-args":91,"safe-buffer":107,"timers":112,"util-deprecate":113}],99:[function(require,module,exports){ "use strict";function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function copyBuffer(t,e,i){t.copy(e,i)}var Buffer=require("safe-buffer").Buffer,util=require("util");module.exports=function(){function t(){_classCallCheck(this,t),this.head=null,this.tail=null,this.length=0}return t.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},t.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},t.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},t.prototype.clear=function(){this.head=this.tail=null,this.length=0},t.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,i=""+e.data;e=e.next;)i+=t+e.data;return i},t.prototype.concat=function(t){if(0===this.length)return Buffer.alloc(0);if(1===this.length)return this.head.data;for(var e=Buffer.allocUnsafe(t>>>0),i=this.head,n=0;i;)copyBuffer(i.data,e,n),n+=i.data.length,i=i.next;return e},t}(),util&&util.inspect&&util.inspect.custom&&(module.exports.prototype[util.inspect.custom]=function(){var t=util.inspect({length:this.length});return this.constructor.name+" "+t}); @@ -439,7 +440,6 @@ function Stream(){EE.call(this)}module.exports=Stream;var EE=require("events").E },{"./":110}],110:[function(require,module,exports){ "use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.Block=void 0;var _thaw=require("./thaw"),_thaw2=_interopRequireDefault(_thaw),_block=require("./block"),_block2=_interopRequireDefault(_block);exports.default=_thaw2.default,exports.Block=_block2.default,"undefined"!=typeof window&&(window.Thaw=_thaw2.default,window.Thaw.Block=_block2.default); - },{"./block":109,"./thaw":111}],111:[function(require,module,exports){ "use strict";function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function thaw(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Thaw(t,e)}Object.defineProperty(exports,"__esModule",{value:!0});var _extends=Object.assign||function(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:{};_classCallCheck(this,t);var s=_extends({},this.constructor.defaultSettings,n),a=s.each,r=s.done;this.items=e,this.i=0,this.options=n;var h=this.tick=function(){if(!(i.i<0||(i.timeout=setTimeout(h,0),thawing))){var t=e[i.i];if(i.i>=e.length)return null!==r&&(thawing=!0,r(t,i.i),thawing=!1),i.i=-1,void clearTimeout(i.timeout);null!==a?(thawing=!0,a(t,i.i),thawing=!1):void 0!==t&&t(),i.i++}};thaws.push(this),n.delay||h()}return _createClass(t,null,[{key:"stopAll",value:function(){for(var t=0;t